@sola-air-ui/relay 1.0.1 → 1.0.3

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