@sola-air-ui/relay 1.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/package.json +29 -0
- package/src/cli.js +24 -0
- package/src/index.js +532 -0
package/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sola-air-ui/relay",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Sola Relay — local data proxy that keeps credentials on-device and streams live data to Sola components",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"sola-relay": "./src/cli.js"
|
|
8
|
+
},
|
|
9
|
+
"main": "./src/index.js",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": "./src/index.js"
|
|
12
|
+
},
|
|
13
|
+
"keywords": ["sola", "relay", "data", "postgres", "local-first", "proxy"],
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"homepage": "https://sola-air.dev",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "https://github.com/rbm3267/sola"
|
|
19
|
+
},
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"pg": "^8.11.0",
|
|
22
|
+
"mysql2": "^3.6.0",
|
|
23
|
+
"ws": "^8.14.0"
|
|
24
|
+
},
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public",
|
|
27
|
+
"registry": "https://registry.npmjs.org/"
|
|
28
|
+
}
|
|
29
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
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();
|
package/src/index.js
ADDED
|
@@ -0,0 +1,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
|
+
// ─── 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
|
+
}
|