@sola-air-ui/relay 1.0.2 → 1.0.4

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 (4) hide show
  1. package/README.md +25 -8
  2. package/package.json +5 -2
  3. package/src/cli.js +27 -23
  4. package/src/index.js +596 -532
package/src/index.js CHANGED
@@ -1,532 +1,596 @@
1
- // ─── Sola Relay Server ───
2
- // Zero-knowledge data proxy. Credentials stay local. Data never leaves.
3
-
4
- import { createServer } from 'http';
5
- import { readFileSync, appendFileSync, existsSync } from 'fs';
6
- import { join } from 'path';
7
-
8
- // ─── Connectors ───
9
- const connectors = new Map();
10
-
11
- class PostgresConnector {
12
- constructor(config) {
13
- this.config = config;
14
- this.pool = null;
15
- }
16
-
17
- async connect() {
18
- const { default: pg } = await import('pg');
19
- this.pool = new pg.Pool(this.config);
20
- // Verify connection
21
- const client = await this.pool.connect();
22
- client.release();
23
- }
24
-
25
- async query(sql, params = []) {
26
- const result = await this.pool.query(sql, params);
27
- return { rows: result.rows, rowCount: result.rowCount };
28
- }
29
-
30
- async schema() {
31
- const result = await this.pool.query(`
32
- SELECT table_name, column_name, data_type
33
- FROM information_schema.columns
34
- WHERE table_schema = 'public'
35
- ORDER BY table_name, ordinal_position
36
- `);
37
- const tables = {};
38
- for (const row of result.rows) {
39
- if (!tables[row.table_name]) tables[row.table_name] = [];
40
- tables[row.table_name].push({ name: row.column_name, type: row.data_type });
41
- }
42
- return tables;
43
- }
44
-
45
- async disconnect() {
46
- if (this.pool) await this.pool.end();
47
- }
48
- }
49
-
50
- class GoogleSheetsConnector {
51
- constructor(config) {
52
- this.sheetId = config.sheetId || config.host || config.source;
53
- this.apiKey = config.apiKey || null;
54
- }
55
-
56
- async connect() {
57
- // Validate sheetId exists
58
- if (!this.sheetId) throw new Error("Google Sheet ID is required for sheet:// relay");
59
- }
60
-
61
- async query(options = {}) {
62
- const url = `https://docs.google.com/spreadsheets/d/${this.sheetId}/gviz/tq?tqx=out:csv`;
63
- const res = await fetch(url);
64
- if (!res.ok) throw new Error(`Failed to fetch Google Sheet (${res.status} ${res.statusText})`);
65
-
66
- const csvText = await res.text();
67
- const lines = csvText.split(/\r?\n/).filter(line => line.trim().length > 0);
68
- if (lines.length === 0) return { rows: [], rowCount: 0 };
69
-
70
- const parseCsvLine = (line) => {
71
- const result = [];
72
- let current = '';
73
- let inQuotes = false;
74
- for (let i = 0; i < line.length; i++) {
75
- const char = line[i];
76
- if (char === '"' && (i === 0 || line[i - 1] !== '\\')) {
77
- inQuotes = !inQuotes;
78
- } else if (char === ',' && !inQuotes) {
79
- result.push(current.trim().replace(/^"|"$/g, ''));
80
- current = '';
81
- } else {
82
- current += char;
83
- }
84
- }
85
- result.push(current.trim().replace(/^"|"$/g, ''));
86
- return result;
87
- };
88
-
89
- const headers = parseCsvLine(lines[0]);
90
- const rows = [];
91
-
92
- for (let i = 1; i < lines.length; i++) {
93
- const values = parseCsvLine(lines[i]);
94
- const row = {};
95
- headers.forEach((header, idx) => {
96
- const val = values[idx] || '';
97
- const numVal = Number(val.replace(/[\$,]/g, ''));
98
- row[header] = !isNaN(numVal) && val !== '' ? numVal : val;
99
- });
100
- rows.push(row);
101
- }
102
-
103
- return { rows, rowCount: rows.length, headers };
104
- }
105
-
106
- async schema() {
107
- const { headers } = await this.query();
108
- return { "sheet_data": headers.map(h => ({ name: h, type: 'inferred' })) };
109
- }
110
-
111
- async disconnect() {}
112
- }
113
-
114
- class ServiceNowConnector {
115
- constructor(config) {
116
- this.instance = config.instance || config.host || process.env.SN_INSTANCE || '';
117
- this.username = config.username || config.user || process.env.SN_USERNAME || '';
118
- this.password = config.password || process.env.SN_PASSWORD || '';
119
- this.token = config.token || config.bearerToken || process.env.SN_BEARER_TOKEN || '';
120
- this.defaultTable = config.table || 'incident';
121
- }
122
-
123
- async connect() {
124
- if (!this.instance) {
125
- throw new Error("ServiceNow instance URL or domain is required (e.g. 'dev12345.service-now.com')");
126
- }
127
- }
128
-
129
- async query(options = {}) {
130
- const table = options.table || options.source || this.defaultTable;
131
- const query = options.query || options.sysparm_query || 'priority=1^state!=7^ORDERBYDESCsys_created_on';
132
- const limit = options.limit || options.sysparm_limit || 20;
133
- const fields = options.fields || 'number,short_description,priority,state,assigned_to,assignment_group,sys_created_on';
134
-
135
- const baseUrl = this.instance.startsWith('http') ? this.instance : `https://${this.instance}.service-now.com`;
136
- const endpoint = `${baseUrl}/api/now/table/${table}?sysparm_query=${encodeURIComponent(query)}&sysparm_limit=${limit}&sysparm_display_value=true&sysparm_fields=${encodeURIComponent(fields)}`;
137
-
138
- const headers = {
139
- 'Accept': 'application/json',
140
- 'Content-Type': 'application/json'
141
- };
142
-
143
- if (this.token) {
144
- headers['Authorization'] = `Bearer ${this.token}`;
145
- } else if (this.username && this.password) {
146
- const auth = Buffer.from(`${this.username}:${this.password}`).toString('base64');
147
- headers['Authorization'] = `Basic ${auth}`;
148
- }
149
-
150
- const res = await fetch(endpoint, { headers });
151
- if (!res.ok) {
152
- const errText = await res.text();
153
- throw new Error(`ServiceNow API error (${res.status} ${res.statusText}): ${errText}`);
154
- }
155
-
156
- const data = await res.json();
157
- const records = data.result || [];
158
- return { rows: records, rowCount: records.length, table };
159
- }
160
-
161
- async mutate(action, payload = {}) {
162
- const table = payload.table || this.defaultTable;
163
- const sysId = payload.sys_id || payload.id;
164
- if (!sysId) throw new Error("sys_id is required to mutate ServiceNow record");
165
-
166
- const baseUrl = this.instance.startsWith('http') ? this.instance : `https://${this.instance}.service-now.com`;
167
- const endpoint = `${baseUrl}/api/now/table/${table}/${sysId}`;
168
-
169
- const headers = {
170
- 'Accept': 'application/json',
171
- 'Content-Type': 'application/json'
172
- };
173
-
174
- if (this.token) {
175
- headers['Authorization'] = `Bearer ${this.token}`;
176
- } else if (this.username && this.password) {
177
- const auth = Buffer.from(`${this.username}:${this.password}`).toString('base64');
178
- headers['Authorization'] = `Basic ${auth}`;
179
- }
180
-
181
- const body = payload.data || payload.fields || {};
182
- const res = await fetch(endpoint, {
183
- method: 'PATCH',
184
- headers,
185
- body: JSON.stringify(body)
186
- });
187
-
188
- if (!res.ok) {
189
- const errText = await res.text();
190
- throw new Error(`ServiceNow mutation error (${res.status} ${res.statusText}): ${errText}`);
191
- }
192
-
193
- const data = await res.json();
194
- return { success: true, result: data.result };
195
- }
196
-
197
- async schema() {
198
- return {
199
- "incident": [
200
- { name: "number", type: "string" },
201
- { name: "short_description", type: "string" },
202
- { name: "priority", type: "string" },
203
- { name: "state", type: "string" },
204
- { name: "assigned_to", type: "string" },
205
- { name: "urgency", type: "string" },
206
- { name: "impact", type: "string" }
207
- ],
208
- "change_request": [
209
- { name: "number", type: "string" },
210
- { name: "short_description", type: "string" },
211
- { name: "risk", type: "string" },
212
- { name: "state", type: "string" },
213
- { name: "start_date", type: "string" }
214
- ]
215
- };
216
- }
217
-
218
- async disconnect() {}
219
- }
220
-
221
- class MySQLConnector {
222
- constructor(config) {
223
- this.config = config;
224
- this.pool = null;
225
- }
226
-
227
- async connect() {
228
- const mysql = await import('mysql2/promise');
229
- this.pool = mysql.createPool(this.config);
230
- // Verify
231
- const conn = await this.pool.getConnection();
232
- conn.release();
233
- }
234
-
235
- async query(sql, params = []) {
236
- const [rows] = await this.pool.execute(sql, params);
237
- return { rows, rowCount: rows.length };
238
- }
239
-
240
- async schema() {
241
- const [rows] = await this.pool.execute(`
242
- SELECT TABLE_NAME as table_name, COLUMN_NAME as column_name, DATA_TYPE as data_type
243
- FROM INFORMATION_SCHEMA.COLUMNS
244
- WHERE TABLE_SCHEMA = DATABASE()
245
- ORDER BY TABLE_NAME, ORDINAL_POSITION
246
- `);
247
- const tables = {};
248
- for (const row of rows) {
249
- if (!tables[row.table_name]) tables[row.table_name] = [];
250
- tables[row.table_name].push({ name: row.column_name, type: row.data_type });
251
- }
252
- return tables;
253
- }
254
-
255
- async disconnect() {
256
- if (this.pool) await this.pool.end();
257
- }
258
- }
259
-
260
- // ─── Audit Logger ───
261
- function auditLog(entry) {
262
- const line = JSON.stringify({
263
- timestamp: new Date().toISOString(),
264
- ...entry
265
- }) + '\n';
266
-
267
- try {
268
- appendFileSync('sola-relay-audit.log', line);
269
- } catch (e) {
270
- // Fallback to console
271
- console.log('[AUDIT]', line.trim());
272
- }
273
- }
274
-
275
- // ─── Connection Store ───
276
- const connections = new Map();
277
-
278
- function addConnection(name, type, config) {
279
- let connector;
280
- switch (type) {
281
- case 'postgres':
282
- connector = new PostgresConnector(config);
283
- break;
284
- case 'mysql':
285
- connector = new MySQLConnector(config);
286
- break;
287
- case 'sheet':
288
- case 'googlesheets':
289
- connector = new GoogleSheetsConnector(config);
290
- break;
291
- case 'servicenow':
292
- case 'now':
293
- connector = new ServiceNowConnector(config);
294
- break;
295
- default:
296
- throw new Error(`Unsupported connector type: ${type}`);
297
- }
298
- connections.set(name, { type, connector, config, status: 'disconnected' });
299
- }
300
-
301
- async function connectAll() {
302
- for (const [name, conn] of connections) {
303
- try {
304
- await conn.connector.connect();
305
- conn.status = 'connected';
306
- console.log(` ✓ Connected: ${name} (${conn.type})`);
307
- } catch (e) {
308
- conn.status = 'error';
309
- console.error(` ✗ Failed: ${name} — ${e.message}`);
310
- }
311
- }
312
- }
313
-
314
- // ─── Load connections from config ───
315
- function loadConfig() {
316
- const configPath = join(process.cwd(), 'sola-relay.json');
317
- if (existsSync(configPath)) {
318
- const config = JSON.parse(readFileSync(configPath, 'utf-8'));
319
- if (config.connections) {
320
- for (const [name, conn] of Object.entries(config.connections)) {
321
- addConnection(name, conn.type, conn);
322
- }
323
- }
324
- return config;
325
- }
326
- return {};
327
- }
328
-
329
- // ─── HTTP Server ───
330
- export class RelayServer {
331
- constructor(options = {}) {
332
- this.port = options.port || 4040;
333
- }
334
-
335
- start() {
336
- // Load config
337
- loadConfig();
338
-
339
- const server = createServer(async (req, res) => {
340
- // CORS — restrict to trusted origins (sola-air.dev, localhost variants, chrome-extension)
341
- const origin = req.headers['origin'];
342
- const staticAllowed = [
343
- 'https://www.sola-air.dev',
344
- 'https://sola-air.dev',
345
- 'http://localhost:5173',
346
- 'http://localhost:4173',
347
- 'http://127.0.0.1:5173'
348
- ];
349
- const isDynLocalhost = origin && /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin);
350
- const isExtension = origin && /^chrome-extension:\/\/[a-z]{32}$/.test(origin);
351
- const allowedOrigin = (isDynLocalhost || isExtension || staticAllowed.includes(origin)) ? origin : null;
352
-
353
- if (allowedOrigin) {
354
- res.setHeader('Access-Control-Allow-Origin', allowedOrigin);
355
- res.setHeader('Vary', 'Origin');
356
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
357
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
358
- }
359
-
360
- if (req.method === 'OPTIONS') {
361
- res.writeHead(204);
362
- res.end();
363
- return;
364
- }
365
-
366
- const url = new URL(req.url, `http://localhost:${this.port}`);
367
-
368
- // ── Status endpoint ──
369
- if (url.pathname === '/api/status' && req.method === 'GET') {
370
- const status = {};
371
- for (const [name, conn] of connections) {
372
- status[name] = { type: conn.type, status: conn.status };
373
- }
374
- res.writeHead(200, { 'Content-Type': 'application/json' });
375
- res.end(JSON.stringify({ relay: 'sola-relay', version: '1.0.0', connections: status }));
376
- return;
377
- }
378
-
379
- // ── Schema endpoint ──
380
- if (url.pathname === '/api/schema' && req.method === 'GET') {
381
- const source = url.searchParams.get('source');
382
- if (!source || !/^[a-zA-Z0-9_]+$/.test(source)) {
383
- res.writeHead(400, { 'Content-Type': 'application/json' });
384
- res.end(JSON.stringify({ error: 'Invalid source identifier' }));
385
- return;
386
- }
387
- const conn = connections.get(source);
388
- if (!conn) {
389
- res.writeHead(404, { 'Content-Type': 'application/json' });
390
- res.end(JSON.stringify({ error: `Source '${source}' not found` }));
391
- return;
392
- }
393
- try {
394
- const schema = await conn.connector.schema();
395
- res.writeHead(200, { 'Content-Type': 'application/json' });
396
- res.end(JSON.stringify({ source, schema }));
397
- } catch (e) {
398
- res.writeHead(500, { 'Content-Type': 'application/json' });
399
- res.end(JSON.stringify({ error: 'Schema fetch failed' }));
400
- }
401
- return;
402
- }
403
-
404
- // ── Query endpoint ──
405
- if (url.pathname === '/api/query' && req.method === 'POST') {
406
- let body = '';
407
- let bodySize = 0;
408
- const MAX_BODY_BYTES = 1024 * 1024; // 1 MB limit
409
-
410
- for await (const chunk of req) {
411
- bodySize += chunk.length;
412
- if (bodySize > MAX_BODY_BYTES) {
413
- res.writeHead(413, { 'Content-Type': 'application/json' });
414
- res.end(JSON.stringify({ error: 'Payload too large. Maximum size is 1MB.' }));
415
- return;
416
- }
417
- body += chunk;
418
- }
419
-
420
- try {
421
- const parsed = JSON.parse(body);
422
- const { source, query, limit } = parsed;
423
-
424
- if (!source || !/^[a-zA-Z0-9_]+$/.test(source)) {
425
- res.writeHead(400, { 'Content-Type': 'application/json' });
426
- res.end(JSON.stringify({ error: 'Invalid source identifier' }));
427
- return;
428
- }
429
-
430
- const conn = connections.get(source);
431
-
432
- if (!conn) {
433
- res.writeHead(404, { 'Content-Type': 'application/json' });
434
- res.end(JSON.stringify({ error: `Source '${source}' not found` }));
435
- return;
436
- }
437
-
438
- if (conn.status !== 'connected') {
439
- res.writeHead(503, { 'Content-Type': 'application/json' });
440
- res.end(JSON.stringify({ error: `Source '${source}' is not connected` }));
441
- return;
442
- }
443
-
444
- const safeLimit = Math.min(Math.max(1, parseInt(limit, 10) || 100), 1000);
445
-
446
- let result;
447
- if (typeof query === 'object' && query !== null && typeof query.text === 'string') {
448
- // Parameterized query — safe by construction
449
- const params = Array.isArray(query.params) ? query.params : [];
450
- result = await conn.connector.query(query.text, params);
451
- } else if (typeof query === 'string') {
452
- // String query — only SELECT permitted
453
- if (!/^\s*SELECT\b/i.test(query)) {
454
- res.writeHead(400, { 'Content-Type': 'application/json' });
455
- res.end(JSON.stringify({ error: 'Only SELECT queries are permitted' }));
456
- return;
457
- }
458
- result = await conn.connector.query(query);
459
- } else {
460
- result = await conn.connector.query(`SELECT * FROM ${source} LIMIT ${safeLimit}`);
461
- }
462
-
463
- // Local audit log
464
- auditLog({
465
- action: 'QUERY',
466
- source,
467
- query: typeof query === 'object' ? 'PARAMETERIZED_QUERY' : 'DEFAULT_SELECT',
468
- rowCount: result?.rowCount || 0,
469
- userAgent: req.headers['user-agent']
470
- });
471
-
472
- res.writeHead(200, { 'Content-Type': 'application/json' });
473
- res.end(JSON.stringify(result));
474
-
475
- } catch (e) {
476
- auditLog({ action: 'QUERY_ERROR', error: e.message });
477
- res.writeHead(500, { 'Content-Type': 'application/json' });
478
- res.end(JSON.stringify({ error: 'Query failed' }));
479
- }
480
- return;
481
- }
482
-
483
- // ── Dashboard (root) ──
484
- if (url.pathname === '/' && req.method === 'GET') {
485
- res.writeHead(200, { 'Content-Type': 'text/html' });
486
- res.end(`<!DOCTYPE html>
487
- <html>
488
- <head>
489
- <title>Sola Relay</title>
490
- <style>
491
- * { margin: 0; box-sizing: border-box; }
492
- body { font-family: system-ui, sans-serif; background: #f8fafc; color: #1e293b; padding: 40px; }
493
- h1 { font-size: 2rem; font-weight: 800; margin-bottom: 8px; }
494
- .sub { color: #94a3b8; margin-bottom: 32px; }
495
- .card { background: white; border: 1px solid #e2e8f0; border-radius: 16px; padding: 20px; margin-bottom: 16px; }
496
- .status { display: inline-block; padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: 700; text-transform: uppercase; }
497
- .connected { background: #ecfdf5; color: #059669; }
498
- .disconnected { background: #fef2f2; color: #dc2626; }
499
- code { background: #f1f5f9; padding: 2px 8px; border-radius: 6px; font-size: 13px; }
500
- </style>
501
- </head>
502
- <body>
503
- <h1>☀️ Sola Relay</h1>
504
- <p class="sub">Your data stays here. Always.</p>
505
- <div class="card">
506
- <p><strong>Status:</strong> Running on port ${this.port}</p>
507
- <p><strong>Connections:</strong> ${connections.size}</p>
508
- <p><strong>Config:</strong> <code>sola-relay.json</code></p>
509
- </div>
510
- <div class="card">
511
- <p><strong>API Endpoints:</strong></p>
512
- <p>POST <code>/api/query</code> — Execute a query</p>
513
- <p>GET <code>/api/schema?source=name</code> — Get table schema (metadata only)</p>
514
- <p>GET <code>/api/status</code> — Connection status</p>
515
- </div>
516
- </body>
517
- </html>`);
518
- return;
519
- }
520
-
521
- res.writeHead(404);
522
- res.end('Not found');
523
- });
524
-
525
- // Connect to all configured data sources
526
- connectAll().then(() => {
527
- server.listen(this.port, '127.0.0.1', () => {
528
- console.log(` Relay listening on http://127.0.0.1:${this.port}\n`);
529
- });
530
- });
531
- }
532
- }
1
+ // ─── Sola Relay Server ───
2
+ // Zero-knowledge data proxy. Credentials stay local. Data never leaves.
3
+
4
+ import { createServer } from 'http';
5
+ import { readFileSync, appendFileSync, existsSync } from 'fs';
6
+ import { join } from 'path';
7
+
8
+ const { version: RELAY_VERSION } = JSON.parse(
9
+ readFileSync(new URL('../package.json', import.meta.url), 'utf8')
10
+ );
11
+
12
+ // Only single-statement read-only SELECT queries are permitted on SQL connectors.
13
+ export function isReadOnlySql(sql) {
14
+ if (typeof sql !== 'string') return false;
15
+ const trimmed = sql.trim().replace(/;+\s*$/, '');
16
+ if (!trimmed) return false;
17
+ const withoutStrings = trimmed
18
+ .replace(/'(?:''|\\.|[^'])*'/g, "''")
19
+ .replace(/"(?:""|\\.|[^"])*"/g, '""');
20
+ const withoutComments = withoutStrings
21
+ .replace(/--[^\r\n]*/g, ' ')
22
+ .replace(/\/\*[\s\S]*?\*\//g, ' ')
23
+ .trim();
24
+ if (!/^SELECT\b/i.test(withoutComments)) return false;
25
+ if (withoutComments.includes(';')) return false;
26
+ // INTO covers SELECT ... INTO, which creates a table (PostgreSQL) or writes a file
27
+ // (MySQL INTO OUTFILE). This is defence in depth: give the relay a read-only role.
28
+ if (/\b(INSERT|UPDATE|DELETE|DROP|ALTER|TRUNCATE|CREATE|GRANT|REVOKE|COPY|CALL|EXEC|EXECUTE|INTO)\b/i.test(withoutComments)) {
29
+ return false;
30
+ }
31
+ return true;
32
+ }
33
+
34
+ // A source is `connection` or `connection:table` (as in $data('pg-primary:customers')).
35
+ // The connection is a name from sola-relay.json. The table goes into SQL, so it must
36
+ // be a plain identifier, optionally schema-qualified; anything else is rejected.
37
+ // Without a table, the connection name doubles as the table name, as before.
38
+ const SOURCE_PATTERN = /^([A-Za-z0-9_-]+)(?::([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?))?$/;
39
+
40
+ export function parseSource(source) {
41
+ const m = typeof source === 'string' ? SOURCE_PATTERN.exec(source) : null;
42
+ if (!m) return null;
43
+ return { connection: m[1], table: m[2] ?? null };
44
+ }
45
+
46
+ // ─── Connectors ───
47
+ const connectors = new Map();
48
+
49
+ class PostgresConnector {
50
+ constructor(config) {
51
+ this.config = config;
52
+ this.pool = null;
53
+ }
54
+
55
+ async connect() {
56
+ const { default: pg } = await import('pg');
57
+ this.pool = new pg.Pool(this.config);
58
+ // Verify connection
59
+ const client = await this.pool.connect();
60
+ client.release();
61
+ }
62
+
63
+ async query(sql, params = []) {
64
+ const result = await this.pool.query(sql, params);
65
+ return { rows: result.rows, rowCount: result.rowCount };
66
+ }
67
+
68
+ async schema() {
69
+ const result = await this.pool.query(`
70
+ SELECT table_name, column_name, data_type
71
+ FROM information_schema.columns
72
+ WHERE table_schema = 'public'
73
+ ORDER BY table_name, ordinal_position
74
+ `);
75
+ const tables = {};
76
+ for (const row of result.rows) {
77
+ if (!tables[row.table_name]) tables[row.table_name] = [];
78
+ tables[row.table_name].push({ name: row.column_name, type: row.data_type });
79
+ }
80
+ return tables;
81
+ }
82
+
83
+ async disconnect() {
84
+ if (this.pool) await this.pool.end();
85
+ }
86
+ }
87
+
88
+ class GoogleSheetsConnector {
89
+ constructor(config) {
90
+ this.sheetId = config.sheetId || config.host || config.source;
91
+ this.apiKey = config.apiKey || null;
92
+ }
93
+
94
+ async connect() {
95
+ // Validate sheetId exists
96
+ if (!this.sheetId) throw new Error("Google Sheet ID is required for sheet:// relay");
97
+ }
98
+
99
+ async query(options = {}) {
100
+ const url = `https://docs.google.com/spreadsheets/d/${this.sheetId}/gviz/tq?tqx=out:csv`;
101
+ const res = await fetch(url);
102
+ if (!res.ok) throw new Error(`Failed to fetch Google Sheet (${res.status} ${res.statusText})`);
103
+
104
+ const csvText = await res.text();
105
+ const lines = csvText.split(/\r?\n/).filter(line => line.trim().length > 0);
106
+ if (lines.length === 0) return { rows: [], rowCount: 0 };
107
+
108
+ const parseCsvLine = (line) => {
109
+ const result = [];
110
+ let current = '';
111
+ let inQuotes = false;
112
+ for (let i = 0; i < line.length; i++) {
113
+ const char = line[i];
114
+ if (char === '"' && (i === 0 || line[i - 1] !== '\\')) {
115
+ inQuotes = !inQuotes;
116
+ } else if (char === ',' && !inQuotes) {
117
+ result.push(current.trim().replace(/^"|"$/g, ''));
118
+ current = '';
119
+ } else {
120
+ current += char;
121
+ }
122
+ }
123
+ result.push(current.trim().replace(/^"|"$/g, ''));
124
+ return result;
125
+ };
126
+
127
+ const headers = parseCsvLine(lines[0]);
128
+ const rows = [];
129
+
130
+ for (let i = 1; i < lines.length; i++) {
131
+ const values = parseCsvLine(lines[i]);
132
+ const row = {};
133
+ headers.forEach((header, idx) => {
134
+ const val = values[idx] || '';
135
+ const numVal = Number(val.replace(/[\$,]/g, ''));
136
+ row[header] = !isNaN(numVal) && val !== '' ? numVal : val;
137
+ });
138
+ rows.push(row);
139
+ }
140
+
141
+ return { rows, rowCount: rows.length, headers };
142
+ }
143
+
144
+ async schema() {
145
+ const { headers } = await this.query();
146
+ return { "sheet_data": headers.map(h => ({ name: h, type: 'inferred' })) };
147
+ }
148
+
149
+ async disconnect() {}
150
+ }
151
+
152
+ class ServiceNowConnector {
153
+ constructor(config) {
154
+ this.instance = config.instance || config.host || process.env.SN_INSTANCE || '';
155
+ this.username = config.username || config.user || process.env.SN_USERNAME || '';
156
+ this.password = config.password || process.env.SN_PASSWORD || '';
157
+ this.token = config.token || config.bearerToken || process.env.SN_BEARER_TOKEN || '';
158
+ this.defaultTable = config.table || 'incident';
159
+ }
160
+
161
+ async connect() {
162
+ if (!this.instance) {
163
+ throw new Error("ServiceNow instance URL or domain is required (e.g. 'dev12345.service-now.com')");
164
+ }
165
+ }
166
+
167
+ async query(options = {}) {
168
+ const table = options.table || options.source || this.defaultTable;
169
+ const query = options.query || options.sysparm_query || 'priority=1^state!=7^ORDERBYDESCsys_created_on';
170
+ const limit = options.limit || options.sysparm_limit || 20;
171
+ const fields = options.fields || 'number,short_description,priority,state,assigned_to,assignment_group,sys_created_on';
172
+
173
+ const baseUrl = this.instance.startsWith('http') ? this.instance : `https://${this.instance}.service-now.com`;
174
+ const endpoint = `${baseUrl}/api/now/table/${table}?sysparm_query=${encodeURIComponent(query)}&sysparm_limit=${limit}&sysparm_display_value=true&sysparm_fields=${encodeURIComponent(fields)}`;
175
+
176
+ const headers = {
177
+ 'Accept': 'application/json',
178
+ 'Content-Type': 'application/json'
179
+ };
180
+
181
+ if (this.token) {
182
+ headers['Authorization'] = `Bearer ${this.token}`;
183
+ } else if (this.username && this.password) {
184
+ const auth = Buffer.from(`${this.username}:${this.password}`).toString('base64');
185
+ headers['Authorization'] = `Basic ${auth}`;
186
+ }
187
+
188
+ const res = await fetch(endpoint, { headers });
189
+ if (!res.ok) {
190
+ const errText = await res.text();
191
+ throw new Error(`ServiceNow API error (${res.status} ${res.statusText}): ${errText}`);
192
+ }
193
+
194
+ const data = await res.json();
195
+ const records = data.result || [];
196
+ return { rows: records, rowCount: records.length, table };
197
+ }
198
+
199
+ async mutate(action, payload = {}) {
200
+ const table = payload.table || this.defaultTable;
201
+ const sysId = payload.sys_id || payload.id;
202
+ if (!sysId) throw new Error("sys_id is required to mutate ServiceNow record");
203
+
204
+ const baseUrl = this.instance.startsWith('http') ? this.instance : `https://${this.instance}.service-now.com`;
205
+ const endpoint = `${baseUrl}/api/now/table/${table}/${sysId}`;
206
+
207
+ const headers = {
208
+ 'Accept': 'application/json',
209
+ 'Content-Type': 'application/json'
210
+ };
211
+
212
+ if (this.token) {
213
+ headers['Authorization'] = `Bearer ${this.token}`;
214
+ } else if (this.username && this.password) {
215
+ const auth = Buffer.from(`${this.username}:${this.password}`).toString('base64');
216
+ headers['Authorization'] = `Basic ${auth}`;
217
+ }
218
+
219
+ const body = payload.data || payload.fields || {};
220
+ const res = await fetch(endpoint, {
221
+ method: 'PATCH',
222
+ headers,
223
+ body: JSON.stringify(body)
224
+ });
225
+
226
+ if (!res.ok) {
227
+ const errText = await res.text();
228
+ throw new Error(`ServiceNow mutation error (${res.status} ${res.statusText}): ${errText}`);
229
+ }
230
+
231
+ const data = await res.json();
232
+ return { success: true, result: data.result };
233
+ }
234
+
235
+ async schema() {
236
+ return {
237
+ "incident": [
238
+ { name: "number", type: "string" },
239
+ { name: "short_description", type: "string" },
240
+ { name: "priority", type: "string" },
241
+ { name: "state", type: "string" },
242
+ { name: "assigned_to", type: "string" },
243
+ { name: "urgency", type: "string" },
244
+ { name: "impact", type: "string" }
245
+ ],
246
+ "change_request": [
247
+ { name: "number", type: "string" },
248
+ { name: "short_description", type: "string" },
249
+ { name: "risk", type: "string" },
250
+ { name: "state", type: "string" },
251
+ { name: "start_date", type: "string" }
252
+ ]
253
+ };
254
+ }
255
+
256
+ async disconnect() {}
257
+ }
258
+
259
+ class MySQLConnector {
260
+ constructor(config) {
261
+ this.config = config;
262
+ this.pool = null;
263
+ }
264
+
265
+ async connect() {
266
+ const mysql = await import('mysql2/promise');
267
+ this.pool = mysql.createPool(this.config);
268
+ // Verify
269
+ const conn = await this.pool.getConnection();
270
+ conn.release();
271
+ }
272
+
273
+ async query(sql, params = []) {
274
+ const [rows] = await this.pool.execute(sql, params);
275
+ return { rows, rowCount: rows.length };
276
+ }
277
+
278
+ async schema() {
279
+ const [rows] = await this.pool.execute(`
280
+ SELECT TABLE_NAME as table_name, COLUMN_NAME as column_name, DATA_TYPE as data_type
281
+ FROM INFORMATION_SCHEMA.COLUMNS
282
+ WHERE TABLE_SCHEMA = DATABASE()
283
+ ORDER BY TABLE_NAME, ORDINAL_POSITION
284
+ `);
285
+ const tables = {};
286
+ for (const row of rows) {
287
+ if (!tables[row.table_name]) tables[row.table_name] = [];
288
+ tables[row.table_name].push({ name: row.column_name, type: row.data_type });
289
+ }
290
+ return tables;
291
+ }
292
+
293
+ async disconnect() {
294
+ if (this.pool) await this.pool.end();
295
+ }
296
+ }
297
+
298
+ // ─── Audit Logger ───
299
+ function auditLog(entry) {
300
+ const line = JSON.stringify({
301
+ timestamp: new Date().toISOString(),
302
+ ...entry
303
+ }) + '\n';
304
+
305
+ try {
306
+ appendFileSync('sola-relay-audit.log', line);
307
+ } catch (e) {
308
+ // Fallback to console
309
+ console.log('[AUDIT]', line.trim());
310
+ }
311
+ }
312
+
313
+ // ─── Connection Store ───
314
+ export const connections = new Map();
315
+
316
+ export function addConnection(name, type, config) {
317
+ let connector;
318
+ switch (type) {
319
+ case 'postgres':
320
+ connector = new PostgresConnector(config);
321
+ break;
322
+ case 'mysql':
323
+ connector = new MySQLConnector(config);
324
+ break;
325
+ case 'sheet':
326
+ case 'googlesheets':
327
+ connector = new GoogleSheetsConnector(config);
328
+ break;
329
+ case 'servicenow':
330
+ case 'now':
331
+ connector = new ServiceNowConnector(config);
332
+ break;
333
+ default:
334
+ throw new Error(`Unsupported connector type: ${type}`);
335
+ }
336
+ connections.set(name, { type, connector, config, status: 'disconnected' });
337
+ }
338
+
339
+ async function connectAll() {
340
+ for (const [name, conn] of connections) {
341
+ try {
342
+ await conn.connector.connect();
343
+ conn.status = 'connected';
344
+ console.log(` ✓ Connected: ${name} (${conn.type})`);
345
+ } catch (e) {
346
+ conn.status = 'error';
347
+ console.error(` ✗ Failed: ${name} — ${e.message}`);
348
+ }
349
+ }
350
+ }
351
+
352
+ // ─── Load connections from config ───
353
+ function loadConfig() {
354
+ const configPath = join(process.cwd(), 'sola-relay.json');
355
+ if (existsSync(configPath)) {
356
+ const config = JSON.parse(readFileSync(configPath, 'utf-8'));
357
+ if (config.connections) {
358
+ for (const [name, conn] of Object.entries(config.connections)) {
359
+ addConnection(name, conn.type, conn);
360
+ }
361
+ }
362
+ return config;
363
+ }
364
+ return {};
365
+ }
366
+
367
+ // ─── HTTP Server ───
368
+ export class RelayServer {
369
+ constructor(options = {}) {
370
+ this.port = options.port || 4040;
371
+ }
372
+
373
+ start() {
374
+ // Load config
375
+ loadConfig();
376
+
377
+ const server = createServer(async (req, res) => {
378
+ // CORS — restrict to trusted origins (sola-air.dev, localhost variants, chrome-extension)
379
+ const origin = req.headers['origin'];
380
+ const staticAllowed = [
381
+ 'https://www.sola-air.dev',
382
+ 'https://sola-air.dev',
383
+ 'http://localhost:5173',
384
+ 'http://localhost:4173',
385
+ 'http://127.0.0.1:5173'
386
+ ];
387
+ const isDynLocalhost = origin && /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin);
388
+ const isExtension = origin && /^chrome-extension:\/\/[a-z]{32}$/.test(origin);
389
+ const allowedOrigin = (isDynLocalhost || isExtension || staticAllowed.includes(origin)) ? origin : null;
390
+
391
+ if (allowedOrigin) {
392
+ res.setHeader('Access-Control-Allow-Origin', allowedOrigin);
393
+ res.setHeader('Vary', 'Origin');
394
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
395
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
396
+ }
397
+
398
+ if (req.method === 'OPTIONS') {
399
+ res.writeHead(204);
400
+ res.end();
401
+ return;
402
+ }
403
+
404
+ const url = new URL(req.url, `http://localhost:${this.port}`);
405
+
406
+ // ── Status endpoint ──
407
+ if (url.pathname === '/api/status' && req.method === 'GET') {
408
+ const status = {};
409
+ for (const [name, conn] of connections) {
410
+ status[name] = { type: conn.type, status: conn.status };
411
+ }
412
+ res.writeHead(200, { 'Content-Type': 'application/json' });
413
+ res.end(JSON.stringify({ relay: 'sola-relay', version: RELAY_VERSION, connections: status }));
414
+ return;
415
+ }
416
+
417
+ // ── Schema endpoint ──
418
+ if (url.pathname === '/api/schema' && req.method === 'GET') {
419
+ const source = url.searchParams.get('source');
420
+ const parsedSource = parseSource(source);
421
+ if (!parsedSource) {
422
+ res.writeHead(400, { 'Content-Type': 'application/json' });
423
+ res.end(JSON.stringify({ error: 'Invalid source identifier' }));
424
+ return;
425
+ }
426
+ const conn = connections.get(parsedSource.connection);
427
+ if (!conn) {
428
+ res.writeHead(404, { 'Content-Type': 'application/json' });
429
+ res.end(JSON.stringify({ error: `Source '${parsedSource.connection}' not found` }));
430
+ return;
431
+ }
432
+ try {
433
+ const schema = await conn.connector.schema();
434
+ res.writeHead(200, { 'Content-Type': 'application/json' });
435
+ res.end(JSON.stringify({ source, schema }));
436
+ } catch (e) {
437
+ res.writeHead(500, { 'Content-Type': 'application/json' });
438
+ res.end(JSON.stringify({ error: 'Schema fetch failed' }));
439
+ }
440
+ return;
441
+ }
442
+
443
+ // ── Query endpoint ──
444
+ if (url.pathname === '/api/query' && req.method === 'POST') {
445
+ let body = '';
446
+ let bodySize = 0;
447
+ const MAX_BODY_BYTES = 1024 * 1024; // 1 MB limit
448
+
449
+ for await (const chunk of req) {
450
+ bodySize += chunk.length;
451
+ if (bodySize > MAX_BODY_BYTES) {
452
+ res.writeHead(413, { 'Content-Type': 'application/json' });
453
+ res.end(JSON.stringify({ error: 'Payload too large. Maximum size is 1MB.' }));
454
+ return;
455
+ }
456
+ body += chunk;
457
+ }
458
+
459
+ try {
460
+ const parsed = JSON.parse(body);
461
+ const { source, query, limit } = parsed;
462
+
463
+ const parsedSource = parseSource(source);
464
+ if (!parsedSource) {
465
+ res.writeHead(400, { 'Content-Type': 'application/json' });
466
+ res.end(JSON.stringify({ error: 'Invalid source identifier' }));
467
+ return;
468
+ }
469
+ const { connection } = parsedSource;
470
+ const table = parsedSource.table ?? connection;
471
+
472
+ const conn = connections.get(connection);
473
+
474
+ if (!conn) {
475
+ res.writeHead(404, { 'Content-Type': 'application/json' });
476
+ res.end(JSON.stringify({ error: `Source '${connection}' not found` }));
477
+ return;
478
+ }
479
+
480
+ if (conn.status !== 'connected') {
481
+ res.writeHead(503, { 'Content-Type': 'application/json' });
482
+ res.end(JSON.stringify({ error: `Source '${connection}' is not connected` }));
483
+ return;
484
+ }
485
+
486
+ const safeLimit = Math.min(Math.max(1, parseInt(limit, 10) || 100), 1000);
487
+
488
+ const isNonSql =
489
+ conn.type === 'sheet' ||
490
+ conn.type === 'googlesheets' ||
491
+ conn.type === 'servicenow' ||
492
+ conn.type === 'now';
493
+
494
+ let result;
495
+ if (isNonSql) {
496
+ const options = typeof query === 'object' && query !== null ? query : (query == null ? {} : { query });
497
+ result = await conn.connector.query({
498
+ ...(parsedSource.table && options.table == null ? { table: parsedSource.table } : {}),
499
+ ...options,
500
+ limit: safeLimit
501
+ });
502
+ } else if (typeof query === 'object' && query !== null && typeof query.text === 'string') {
503
+ if (!isReadOnlySql(query.text)) {
504
+ res.writeHead(400, { 'Content-Type': 'application/json' });
505
+ res.end(JSON.stringify({ error: 'Only SELECT queries are permitted' }));
506
+ return;
507
+ }
508
+ const params = Array.isArray(query.params) ? query.params : [];
509
+ result = await conn.connector.query(query.text, params);
510
+ } else if (typeof query === 'string') {
511
+ if (!isReadOnlySql(query)) {
512
+ res.writeHead(400, { 'Content-Type': 'application/json' });
513
+ res.end(JSON.stringify({ error: 'Only SELECT queries are permitted' }));
514
+ return;
515
+ }
516
+ result = await conn.connector.query(query);
517
+ } else if (query == null) {
518
+ result = await conn.connector.query(`SELECT * FROM ${table} LIMIT ${safeLimit}`);
519
+ } else {
520
+ res.writeHead(400, { 'Content-Type': 'application/json' });
521
+ res.end(JSON.stringify({ error: 'Only SELECT queries are permitted' }));
522
+ return;
523
+ }
524
+
525
+ // Local audit log
526
+ auditLog({
527
+ action: 'QUERY',
528
+ source,
529
+ query: typeof query === 'object' ? 'PARAMETERIZED_QUERY' : 'DEFAULT_SELECT',
530
+ rowCount: result?.rowCount || 0,
531
+ userAgent: req.headers['user-agent']
532
+ });
533
+
534
+ res.writeHead(200, { 'Content-Type': 'application/json' });
535
+ res.end(JSON.stringify(result));
536
+
537
+ } catch (e) {
538
+ auditLog({ action: 'QUERY_ERROR', error: e.message });
539
+ res.writeHead(500, { 'Content-Type': 'application/json' });
540
+ res.end(JSON.stringify({ error: 'Query failed' }));
541
+ }
542
+ return;
543
+ }
544
+
545
+ // ── Dashboard (root) ──
546
+ if (url.pathname === '/' && req.method === 'GET') {
547
+ res.writeHead(200, { 'Content-Type': 'text/html' });
548
+ res.end(`<!DOCTYPE html>
549
+ <html>
550
+ <head>
551
+ <title>Sola Relay</title>
552
+ <style>
553
+ * { margin: 0; box-sizing: border-box; }
554
+ body { font-family: system-ui, sans-serif; background: #f8fafc; color: #1e293b; padding: 40px; }
555
+ h1 { font-size: 2rem; font-weight: 800; margin-bottom: 8px; }
556
+ .sub { color: #94a3b8; margin-bottom: 32px; }
557
+ .card { background: white; border: 1px solid #e2e8f0; border-radius: 16px; padding: 20px; margin-bottom: 16px; }
558
+ .status { display: inline-block; padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: 700; text-transform: uppercase; }
559
+ .connected { background: #ecfdf5; color: #059669; }
560
+ .disconnected { background: #fef2f2; color: #dc2626; }
561
+ code { background: #f1f5f9; padding: 2px 8px; border-radius: 6px; font-size: 13px; }
562
+ </style>
563
+ </head>
564
+ <body>
565
+ <h1>☀️ Sola Relay</h1>
566
+ <p class="sub">Your data stays here. Always.</p>
567
+ <div class="card">
568
+ <p><strong>Status:</strong> Running on port ${this.port}</p>
569
+ <p><strong>Connections:</strong> ${connections.size}</p>
570
+ <p><strong>Config:</strong> <code>sola-relay.json</code></p>
571
+ </div>
572
+ <div class="card">
573
+ <p><strong>API Endpoints:</strong></p>
574
+ <p>POST <code>/api/query</code> — Execute a query</p>
575
+ <p>GET <code>/api/schema?source=name</code> — Get table schema (metadata only)</p>
576
+ <p>GET <code>/api/status</code> — Connection status</p>
577
+ </div>
578
+ </body>
579
+ </html>`);
580
+ return;
581
+ }
582
+
583
+ res.writeHead(404);
584
+ res.end('Not found');
585
+ });
586
+
587
+ this.server = server;
588
+ // Connect to all configured data sources
589
+ connectAll().then(() => {
590
+ server.listen(this.port, '127.0.0.1', () => {
591
+ console.log(` Relay listening on http://127.0.0.1:${this.port}\n`);
592
+ });
593
+ });
594
+ return server;
595
+ }
596
+ }