@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.
- package/README.md +25 -8
- package/package.json +5 -2
- package/src/cli.js +27 -23
- 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
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
this.
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
};
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
async
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
const
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
async
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
return;
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
const
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
source
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
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
|
+
}
|