scorpiox-bot-plugin-sqlite
←plugin_sqlite.cc
1634 lines · 60 KBHEADBlameDownload
1/*
2 * plugin_sqlite - SCORPIOX BOT open-source read-only SQLite explorer plugin
3 *
4 * A single clean-room C99 binary that serves THREE modes:
5 * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery
6 * 2. ?action=dbs | ?action=schema&db=... | ?action=query&db=...&sql=...
7 * | ?action=info | ?format=json
8 * -> JSON node API (read-only database access)
9 * 3. GET (default) -> responsive HTML explorer UI
10 *
11 * READ-ONLY BY CONSTRUCTION
12 * - Every database is opened with SQLITE_OPEN_READONLY.
13 * - sqlite3_set_authorizer() permits only SQLITE_SELECT, SQLITE_READ,
14 * SQLITE_RECURSIVE, SQLITE_FUNCTION and a small whitelist of read-only
15 * PRAGMAs. INSERT / UPDATE / DELETE / CREATE / DROP / ALTER / ATTACH /
16 * DETACH / TRANSACTION / REINDEX / VACUUM are all refused by the engine
17 * before they can reach the file.
18 * - Only .db / .sqlite / .sqlite3 regular files under /workspace,
19 * /codebases, $HOME (or $SQLITE_ALLOWED_ROOT) are browsable. Paths are
20 * resolved and verified - '..' traversal, SQLite URI filenames and system
21 * paths such as /etc/passwd are rejected.
22 * - Result rows are capped at 500 and each statement is bounded by a
23 * sqlite3_progress_handler ceiling (~2 s).
24 *
25 * Vendors the public-domain SQLite amalgamation (vendor/sqlite3.{c,h}) and
26 * compiles it with -DSQLITE_OMIT_LOAD_EXTENSION -DSQLITE_THREADSAFE=0, so the
27 * Linux (glibc + musl static), macOS and Windows binaries need no sqlite3 CLI,
28 * no libsqlite3.so and no sqlite3.dll.
29 *
30 * Zero dependencies beyond libc. MIT License. Copyright (c) 2026 SCORPIOX INC.
31 */
32
33#if defined(__APPLE__)
34# define _DARWIN_C_SOURCE 1
35#elif !defined(_WIN32)
36# define _POSIX_C_SOURCE 200809L
37# define _DEFAULT_SOURCE 1
38#endif
39
40#include <stdio.h>
41#include <stdlib.h>
42#include <string.h>
43#include <time.h>
44#include <ctype.h>
45#include <errno.h>
46
47#if defined(_WIN32)
48# define WIN32_LEAN_AND_MEAN
49# include <windows.h>
50# include <direct.h>
51# include <io.h>
52# include <fcntl.h>
53/* MinGW/MSVC CRT starts stdout in TEXT mode, which rewrites every \n we emit
54 * into \r\n. A CGI header block must end with exactly CRLF CRLF; text mode
55 * turns "\r\n\r\n" into "\r\r\n\r\r\n", scorpiox-server cannot find the
56 * header/body separator, and the whole reply (headers included) is served as a
57 * body with Content-Type: text/html. Force binary stdio before main() runs —
58 * the same constructor scorpiox-bot-api handlers use (sx_shell.h). */
59__attribute__((constructor))
60static void sx_plugin_binary_stdio(void) {
61 _setmode(_fileno(stdout), _O_BINARY);
62 _setmode(_fileno(stdin), _O_BINARY);
63}
64# include <sys/stat.h>
65# define SX_STAT struct _stat64
66# define sx_stat(p,s) _stat64((p),(s))
67# define SX_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
68# define SX_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
69#else
70# include <unistd.h>
71# include <dirent.h>
72# include <sys/types.h>
73# include <sys/stat.h>
74# define SX_STAT struct stat
75# define sx_stat(p,s) stat((p),(s))
76# define SX_ISREG(m) S_ISREG(m)
77# define SX_ISDIR(m) S_ISDIR(m)
78#endif
79
80/* Relative include so the tree also builds without -I flags (the marketplace
81 * release CLI compiles every src and vendor C file in one command). */
82#include "../vendor/sqlite3.h"
83
84#include "bot_theme_plugin.h"
85
86#define PLUGIN_SLUG "sqlite"
87#define PLUGIN_ID "plugin_sqlite"
88#define PLUGIN_VER "1.0.3"
89
90#define MAX_NAME 256
91/* glibc's fortified realpath() demands a PATH_MAX-sized buffer. */
92#define MAX_PATHQ 4096
93#define MAX_DBS 200
94#define MAX_TABLES 200
95#define MAX_COLS 128
96#define MAX_SQL 16384
97#define MAX_ROWS 500
98#define MAX_SCAN_ENTRIES 60000
99#define MAX_SCAN_DEPTH 4
100#define STMT_BUDGET_MS 2000
101
102/*
103 * Per-root entry allowance for the discovery walk. $SQLITE_SCAN_BUDGET lowers
104 * it so tests can prove the truncation path on a tiny fixture; a value that is
105 * not a positive integer is ignored rather than trusted.
106 */
107static int scan_budget(void)
108{
109 static int cached = -1;
110 if (cached < 0) {
111 const char *e = getenv("SQLITE_SCAN_BUDGET");
112 long v = (e && *e) ? strtol(e, NULL, 10) : 0;
113 cached = (v > 0 && v <= MAX_SCAN_ENTRIES) ? (int)v : MAX_SCAN_ENTRIES;
114 }
115 return cached;
116}
117
118/* ------------------------------------------------------------------ */
119/* Small utilities */
120/* ------------------------------------------------------------------ */
121
122static void url_decode(char *s)
123{
124 char *o = s;
125 if (!s) return;
126 while (*s) {
127 if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
128 int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
129 int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
130 *o++ = (char)((hi << 4) | lo);
131 s += 3;
132 } else if (*s == '+') {
133 *o++ = ' ';
134 s++;
135 } else {
136 *o++ = *s++;
137 }
138 }
139 *o = '\0';
140}
141
142/* Read one parameter (decoded) out of a query or form string. */
143static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
144{
145 size_t klen;
146 const char *p;
147
148 if (!out || outsz == 0) return 0;
149 out[0] = '\0';
150 if (!qs || !key) return 0;
151 klen = strlen(key);
152
153 for (p = qs; *p; ) {
154 if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
155 const char *v = p + klen + 1;
156 size_t i = 0;
157 while (*v && *v != '&' && i + 1 < outsz)
158 out[i++] = *v++;
159 out[i] = '\0';
160 url_decode(out);
161 return 1;
162 }
163 p = strchr(p, '&');
164 if (!p) break;
165 p++;
166 }
167 return 0;
168}
169
170/* JSON string literal; drops control characters rather than escaping them. */
171static void json_str(const char *s)
172{
173 fputc('"', stdout);
174 if (s) {
175 for (; *s; s++) {
176 unsigned char c = (unsigned char)*s;
177 if (c == '"' || c == '\\') { fputc('\\', stdout); fputc((int)c, stdout); }
178 else if (c == '\n') fputs("\\n", stdout);
179 else if (c == '\r') fputs("\\r", stdout);
180 else if (c == '\t') fputs("\\t", stdout);
181 else if (c >= 0x20) fputc((int)c, stdout);
182 }
183 }
184 fputc('"', stdout);
185}
186
187static void copy_str(char *dst, size_t dstsz, const char *src)
188{
189 size_t n;
190 if (!dst || dstsz == 0) return;
191 if (!src) { dst[0] = '\0'; return; }
192 n = strlen(src);
193 if (n >= dstsz) n = dstsz - 1;
194 memcpy(dst, src, n);
195 dst[n] = '\0';
196}
197
198static void utc_now(char *buf, size_t sz)
199{
200 time_t t = time(NULL);
201 struct tm tmv;
202#if defined(_WIN32)
203 struct tm *p = gmtime(&t);
204 if (p) tmv = *p; else memset(&tmv, 0, sizeof tmv);
205#else
206 gmtime_r(&t, &tmv);
207#endif
208 strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv);
209}
210
211static long long now_ms(void)
212{
213#if defined(_WIN32)
214 return (long long)GetTickCount64();
215#else
216 struct timespec ts;
217 if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0;
218 return (long long)ts.tv_sec * 1000LL + ts.tv_nsec / 1000000LL;
219#endif
220}
221
222static long node_pid(void)
223{
224#if defined(_WIN32)
225 return (long)GetCurrentProcessId();
226#else
227 return (long)getpid();
228#endif
229}
230
231static const char *platform_name(void)
232{
233#if defined(_WIN32)
234 return "windows";
235#elif defined(__APPLE__)
236 return "macos";
237#else
238 return "linux";
239#endif
240}
241
242/* Case-insensitive prefix compare, portable across glibc / macOS / MinGW. */
243static int ci_prefix(const char *s, const char *pre)
244{
245 while (*pre) {
246 if (!*s) return 0;
247 if (tolower((unsigned char)*s) != tolower((unsigned char)*pre)) return 0;
248 s++; pre++;
249 }
250 return 1;
251}
252
253/* ------------------------------------------------------------------ */
254/* Node authentication */
255/* ------------------------------------------------------------------ */
256
257/*
258 * Everything except --meta discovery must prove it knows the node password.
259 * Accepted exactly like the rest of the node API: X-Bot-Password (what
260 * bot-web proxies with), Authorization: Bearer, and ?pwd= (what the plugin
261 * iframe appends). With BOT_PASSWORD unset the plugin is a deliberate no-op
262 * so it can be exercised from a shell during development.
263 */
264static void require_node_auth(void)
265{
266 const char *np = getenv("BOT_PASSWORD");
267 const char *xp;
268 const char *auth;
269 char qpwd[256];
270 const char *qs;
271
272 if (!np || !*np) return;
273
274 xp = getenv("HTTP_X_BOT_PASSWORD");
275 if (xp && strcmp(xp, np) == 0) return;
276
277 auth = getenv("HTTP_AUTHORIZATION");
278 if (auth) {
279 while (*auth == ' ') auth++;
280 if (ci_prefix(auth, "Bearer ")) {
281 auth += 7;
282 while (*auth == ' ') auth++;
283 if (strcmp(auth, np) == 0) return;
284 }
285 }
286
287 qs = getenv("QUERY_STRING");
288 if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0)
289 return;
290
291 fputs("Status: 401 Unauthorized\r\n"
292 "Content-Type: application/json; charset=utf-8\r\n"
293 "Cache-Control: no-store\r\n"
294 "X-Content-Type-Options: nosniff\r\n\r\n"
295 "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
296 exit(0);
297}
298
299/* ------------------------------------------------------------------ */
300/* Path discipline */
301/* ------------------------------------------------------------------ */
302
303typedef struct {
304 char path[MAX_PATHQ];
305 char label[32];
306 int exists;
307} sx_root_t;
308
309/*
310 * The allowlist. $SQLITE_ALLOWED_ROOT is honoured first so a node owner can
311 * point the plugin at a specific directory, and the three conventional roots
312 * follow. Nothing outside these is ever opened, no matter what the query says.
313 */
314static int collect_roots(sx_root_t *out, int max)
315{
316 int n = 0;
317 const char *extra = getenv("SQLITE_ALLOWED_ROOT");
318 const char *home = getenv("HOME");
319#if defined(_WIN32)
320 if (!home || !*home) home = getenv("USERPROFILE");
321#endif
322 SX_STAT st;
323
324 memset(out, 0, (size_t)max * sizeof(out[0]));
325
326 if (extra && *extra && n < max) {
327 copy_str(out[n].path, sizeof(out[n].path), extra);
328 copy_str(out[n].label, sizeof(out[n].label), "allowed");
329 out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode));
330 n++;
331 }
332#if !defined(_WIN32)
333 if (n < max) {
334 copy_str(out[n].path, sizeof(out[n].path), "/workspace");
335 copy_str(out[n].label, sizeof(out[n].label), "workspace");
336 out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode));
337 n++;
338 }
339 if (n < max) {
340 copy_str(out[n].path, sizeof(out[n].path), "/codebases");
341 copy_str(out[n].label, sizeof(out[n].label), "codebases");
342 out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode));
343 n++;
344 }
345#endif
346 if (home && *home && n < max) {
347 copy_str(out[n].path, sizeof(out[n].path), home);
348 copy_str(out[n].label, sizeof(out[n].label), "home");
349 out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode));
350 n++;
351 }
352 return n;
353}
354
355static int has_dotdot(const char *p)
356{
357 const char *s = p;
358 while (s && *s) {
359 if (s[0] == '.' && s[1] == '.' &&
360 (s == p || s[-1] == '/' || s[-1] == '\\') &&
361 (s[2] == '\0' || s[2] == '/' || s[2] == '\\'))
362 return 1;
363 s = strchr(s, '/');
364 if (!s) break;
365 s++;
366 }
367 return 0;
368}
369
370/* Suffix gate: .db / .sqlite / .sqlite3 / .db3 (case-insensitive). */
371static int has_db_suffix(const char *p)
372{
373 size_t n = strlen(p);
374 const char *s;
375 if (n < 4) return 0;
376 for (s = p + n; s > p && s[-1] != '/' && s[-1] != '\\'; s--) {
377 if (*s == '.') {
378 if (ci_prefix(s, ".db") || ci_prefix(s, ".db3") ||
379 ci_prefix(s, ".sqlite") || ci_prefix(s, ".sqlite3"))
380 return 1;
381 return 0;
382 }
383 }
384 return 0;
385}
386
387/*
388 * Resolve and validate a database path.
389 * 1 allowed, canonical path written to out
390 * 0 not allowed (outside the roots / traversal / not a db file)
391 * -1 allowed location but the file is absent
392 */
393static int resolve_db_path(const char *req, char *out, size_t outsz)
394{
395 sx_root_t roots[8];
396 int nroots, i;
397 char canon[MAX_PATHQ];
398 SX_STAT st;
399 size_t i2;
400
401 if (!req || !*req) return 0;
402 if (strlen(req) >= MAX_PATHQ) return 0;
403
404 /* SQLite URI filenames can smuggle a different file past a naive check. */
405 if (ci_prefix(req, "file:")) return 0;
406 if (strstr(req, "://")) return 0;
407 if (strstr(req, "?") || strstr(req, "#")) return 0;
408 if (has_dotdot(req)) return 0;
409 if (!has_db_suffix(req)) return 0;
410
411 /* An absolute request must resolve to itself; relative ones are joined to
412 * $HOME so a bare "app.db" still works from the UI. */
413 if (req[0] == '/' || (isalpha((unsigned char)req[0]) && req[1] == ':')) {
414 copy_str(canon, sizeof(canon), req);
415 } else {
416 const char *home = getenv("HOME");
417#if defined(_WIN32)
418 if (!home || !*home) home = getenv("USERPROFILE");
419#endif
420 if (!home || !*home) return 0;
421 snprintf(canon, sizeof(canon), "%s/%s", home, req);
422 }
423
424 /* Normalise to an absolute, symlink-free path when the platform can. A
425 * the leaf does not exist we resolve its parent instead and remember. */
426 {
427#if defined(_WIN32)
428 char tmp[MAX_PATHQ];
429 if (_fullpath(tmp, canon, sizeof(tmp)) != NULL)
430 copy_str(canon, sizeof(canon), tmp);
431 else
432 return 0;
433#else
434 char tmp[MAX_PATHQ];
435 if (realpath(canon, tmp) != NULL) {
436 copy_str(canon, sizeof(canon), tmp);
437 } else if (errno == ENOENT) {
438 char dir[MAX_PATHQ], parent[MAX_PATHQ], rp[MAX_PATHQ];
439 char *slash;
440 copy_str(dir, sizeof dir, canon);
441 slash = strrchr(dir, '/');
442 if (!slash) return 0;
443 *slash = '\0';
444 copy_str(parent, sizeof parent, slash + 1);
445 if (realpath(dir, rp) != NULL) {
446 /* Bounded manual join: snprintf's "%s/%s" over two
447 * PATH_MAX-sized buffers trips -Wformat-truncation. */
448 size_t rl = strlen(rp);
449 canon[0] = '\0';
450 if (rl + strlen(parent) + 2 < sizeof canon) {
451 memcpy(canon, rp, rl);
452 canon[rl] = '/';
453 copy_str(canon + rl + 1, sizeof(canon) - rl - 1, parent);
454 } else {
455 return 0;
456 }
457 }
458 } else {
459 return 0;
460 }
461#endif
462 }
463
464 nroots = collect_roots(roots, 8);
465 for (i = 0; i < nroots; i++) {
466 size_t rl;
467 if (!roots[i].exists) continue;
468 rl = strlen(roots[i].path);
469 while (rl > 1 && roots[i].path[rl - 1] == '/') rl--;
470 if (strncmp(canon, roots[i].path, rl) != 0) continue;
471 if (canon[rl] != '/' && canon[rl] != '\0') continue;
472
473 if (sx_stat(canon, &st) != 0) return -1;
474 if (!SX_ISREG(st.st_mode)) return 0;
475 copy_str(out, outsz, canon);
476 return 1;
477 }
478
479 /* Not under any root. Collapse any doubled separators first so the check
480 * above cannot be defeated by "//workspace//..//". */
481 for (i2 = 0; canon[i2]; i2++)
482 if (canon[i2] == '\\') canon[i2] = '/';
483 return 0;
484}
485
486/* ------------------------------------------------------------------ */
487/* SQLite: read-only open, authorizer, bounded execution */
488/* ------------------------------------------------------------------ */
489
490typedef struct {
491 long long deadline_ms;
492 int aborted;
493} sx_budget_t;
494
495static int progress_cb(void *p)
496{
497 sx_budget_t *b = (sx_budget_t *)p;
498 if (!b) return 0;
499 if (now_ms() > b->deadline_ms) { b->aborted = 1; return 1; }
500 return 0;
501}
502
503/* Read-only schema pragmas we are willing to run, and only these. */
504static int pragma_allowed(const char *name)
505{
506 static const char *ok[] = {
507 /* Pure readers only. Settable pragmas (journal_mode, encoding,
508 * auto_vacuum, user_version, application_id, schema_version) are
509 * deliberately absent: on a read-only handle they cannot write anyway,
510 * but refusing them keeps the contract honest and the error explicit. */
511 "table_info", "table_xinfo", "index_list", "index_info", "index_xinfo",
512 "foreign_key_list", "database_list", "collation_list",
513 "page_count", "page_size", "freelist_count", "compile_options",
514 "quick_check", "integrity_check", "table_list",
515 NULL
516 };
517 int i;
518 if (!name) return 0;
519 for (i = 0; ok[i]; i++)
520 if (ci_prefix(name, ok[i]) && (name[strlen(ok[i])] == '\0'))
521 return 1;
522 return 0;
523}
524
525/*
526 * SQLITE_DENY on everything not explicitly allowed. Note that this fires for
527 * the *compiled* statement, so a statement that tries to write is refused
528 * before execution even on a writable file - defence in depth on top of
529 * SQLITE_OPEN_READONLY.
530 */
531static int authorizer_cb(void *ud, int action, const char *a1, const char *a2,
532 const char *dbname, const char *trigger)
533{
534 (void)ud; (void)a2; (void)dbname; (void)trigger;
535
536 switch (action) {
537 case SQLITE_SELECT:
538 case SQLITE_READ:
539 case SQLITE_RECURSIVE:
540 return SQLITE_OK;
541 case SQLITE_FUNCTION:
542 /* Extension loading is off by default and we never enable it, but a
543 * binary built without -DSQLITE_OMIT_LOAD_EXTENSION could still reach
544 * the function entry point. Name it and refuse it. */
545 if (a2 && ci_prefix(a2, "load_extension") && !a2[14])
546 return SQLITE_DENY;
547 return SQLITE_OK;
548 case SQLITE_PRAGMA:
549 return pragma_allowed(a1) ? SQLITE_OK : SQLITE_DENY;
550 default:
551 return SQLITE_DENY;
552 }
553}
554
555static sqlite3 *open_ro(const char *path, int *errout)
556{
557 sqlite3 *db = NULL;
558 int rc;
559
560 if (errout) *errout = 0;
561
562 /* READONLY plus no URI handling: the path has already been canonicalised
563 * by resolve_db_path(), and URI filenames would re-introduce a second
564 * filename parser under our feet. */
565 rc = sqlite3_open_v2(path, &db,
566 SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, NULL);
567 if (rc != SQLITE_OK) {
568 if (db) sqlite3_close(db);
569 if (errout) *errout = rc;
570 return NULL;
571 }
572 sqlite3_extended_result_codes(db, 1);
573 sqlite3_limit(db, SQLITE_LIMIT_ATTACHED, 0);
574 sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 1000000);
575 sqlite3_limit(db, SQLITE_LIMIT_SQL_LENGTH, MAX_SQL);
576 sqlite3_busy_timeout(db, 500);
577 return db;
578}
579
580/* Confirm the file really is a SQLite database before we report anything. */
581static int is_database(sqlite3 *db)
582{
583 sqlite3_stmt *st = NULL;
584 int rc = sqlite3_prepare_v2(db, "SELECT count(*) FROM sqlite_master", -1, &st, NULL);
585 if (rc != SQLITE_OK) {
586 if (st) sqlite3_finalize(st);
587 return 0;
588 }
589 rc = sqlite3_step(st);
590 sqlite3_finalize(st);
591 return rc == SQLITE_ROW || rc == SQLITE_DONE;
592}
593
594/* ------------------------------------------------------------------ */
595/* JSON output helpers */
596/* ------------------------------------------------------------------ */
597
598static void json_header(void)
599{
600 /* Deliberately no Content-Length - the server owns framing. */
601 fputs("Content-Type: application/json; charset=utf-8\r\n"
602 "Cache-Control: no-store\r\n"
603 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
604}
605
606static void json_error(const char *code, const char *detail)
607{
608 json_header();
609 fputs("{\"ok\":false,\"error\":", stdout);
610 json_str(code);
611 if (detail && *detail) {
612 fputs(",\"detail\":", stdout);
613 json_str(detail);
614 }
615 fputs("}\n", stdout);
616}
617
618/* Emit one typed result value. BLOBs become a bounded hex preview. */
619static void emit_value(sqlite3_stmt *st, int col)
620{
621 switch (sqlite3_column_type(st, col)) {
622 case SQLITE_INTEGER:
623 printf("%lld", (long long)sqlite3_column_int64(st, col));
624 break;
625 case SQLITE_FLOAT: {
626 double d = sqlite3_column_double(st, col);
627 if (d != d || d > 1.7976931348623157e308 || d < -1.7976931348623157e308) {
628 /* NaN / Inf are not JSON numbers - describe them instead. */
629 char buf[32];
630 if (d != d) copy_str(buf, sizeof buf, "NaN");
631 else if (d > 0) copy_str(buf, sizeof buf, "Infinity");
632 else copy_str(buf, sizeof buf, "-Infinity");
633 json_str(buf);
634 } else {
635 printf("%.15g", d);
636 }
637 break;
638 }
639 case SQLITE_TEXT: {
640 const unsigned char *t = sqlite3_column_text(st, col);
641 json_str(t ? (const char *)t : "");
642 break;
643 }
644 case SQLITE_BLOB: {
645 const unsigned char *b = (const unsigned char *)sqlite3_column_blob(st, col);
646 int n = sqlite3_column_bytes(st, col), i, lim = n > 48 ? 48 : n;
647 printf("{\"blob_bytes\":%d,\"hex\":\"", n);
648 for (i = 0; i < lim; i++) printf("%02x", b[i]);
649 fputs(n > lim ? "...\"}" : "\"}", stdout);
650 break;
651 }
652 default:
653 fputs("null", stdout);
654 break;
655 }
656}
657
658static const char *value_type_name(sqlite3_stmt *st, int col)
659{
660 switch (sqlite3_column_type(st, col)) {
661 case SQLITE_INTEGER: return "int";
662 case SQLITE_FLOAT: return "float";
663 case SQLITE_TEXT: return "text";
664 case SQLITE_BLOB: return "blob";
665 default: return "null";
666 }
667}
668
669/* Quote an identifier for interpolation into SQL (never for user values). */
670static void quote_ident(const char *in, char *out, size_t outsz)
671{
672 size_t o = 0;
673 if (outsz < 3) { if (outsz) out[0] = '\0'; return; }
674 out[o++] = '"';
675 for (; in && *in && o + 3 < outsz; in++) {
676 if (*in == '"') out[o++] = '"';
677 out[o++] = *in;
678 }
679 out[o++] = '"';
680 out[o] = '\0';
681}
682
683/* ------------------------------------------------------------------ */
684/* Database discovery */
685/* ------------------------------------------------------------------ */
686
687typedef struct {
688 char path[MAX_PATHQ];
689 char root[32];
690 long long size;
691 long long mtime;
692} sx_db_t;
693
694static int db_suffix_ok(const char *name)
695{
696 size_t n = strlen(name);
697 const char *s = name + n;
698 while (s > name && *s != '.') s--;
699 if (*s != '.') return 0;
700 return ci_prefix(s, ".db") || ci_prefix(s, ".db3") ||
701 ci_prefix(s, ".sqlite") || ci_prefix(s, ".sqlite3");
702}
703
704static int skip_name(const char *n)
705{
706 if (!n || !*n) return 1;
707 if (n[0] == '.' && (n[1] == '\0' || (n[1] == '.' && n[2] == '\0'))) return 1;
708 /* Skip the obvious noise directories; they are never databases anyway. */
709 if (strcmp(n, ".git") == 0 || strcmp(n, "node_modules") == 0 ||
710 strcmp(n, "__pycache__") == 0 || strcmp(n, "venv") == 0 ||
711 strcmp(n, ".venv") == 0 || strcmp(n, "bin") == 0 ||
712 strcmp(n, "obj") == 0 || strcmp(n, "target") == 0)
713 return 1;
714 return 0;
715}
716
717static int walk_dbs(const char *dir, const char *rootlabel, int depth,
718 sx_db_t *out, int max, int *count, int *visited)
719{
720 if (depth > MAX_SCAN_DEPTH || *count >= max || *visited > scan_budget())
721 return 0;
722
723#if defined(_WIN32)
724 {
725 WIN32_FIND_DATAA fd;
726 HANDLE h;
727 char pat[MAX_PATHQ];
728 snprintf(pat, sizeof(pat), "%s\\*", dir);
729 h = FindFirstFileA(pat, &fd);
730 if (h == INVALID_HANDLE_VALUE) return 0;
731 do {
732 char full[MAX_PATHQ];
733 SX_STAT st;
734 if (skip_name(fd.cFileName)) continue;
735 (*visited)++;
736 if (*visited > scan_budget() || *count >= max) break;
737 snprintf(full, sizeof(full), "%s\\%s", dir, fd.cFileName);
738 if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
739 walk_dbs(full, rootlabel, depth + 1, out, max, count, visited);
740 } else if (db_suffix_ok(fd.cFileName) &&
741 sx_stat(full, &st) == 0 && SX_ISREG(st.st_mode)) {
742 copy_str(out[*count].path, sizeof(out[*count].path), full);
743 copy_str(out[*count].root, sizeof(out[*count].root), rootlabel);
744 out[*count].size = (long long)st.st_size;
745 out[*count].mtime = (long long)st.st_mtime;
746 (*count)++;
747 }
748 } while (FindNextFileA(h, &fd));
749 FindClose(h);
750 }
751#else
752 {
753 DIR *d = opendir(dir);
754 struct dirent *e;
755 if (!d) return 0;
756 while ((e = readdir(d)) != NULL) {
757 char full[MAX_PATHQ];
758 SX_STAT st;
759 if (skip_name(e->d_name)) continue;
760 (*visited)++;
761 if (*visited > scan_budget() || *count >= max) break;
762 snprintf(full, sizeof(full), "%s/%s", dir, e->d_name);
763 if (lstat(full, &st) != 0) continue;
764 if (S_ISDIR(st.st_mode)) {
765 /* Never follow a symlinked directory: that is how a walk
766 * escapes the allowlisted root. */
767 if (S_ISLNK(st.st_mode)) continue;
768 walk_dbs(full, rootlabel, depth + 1, out, max, count, visited);
769 } else if (S_ISREG(st.st_mode) && db_suffix_ok(e->d_name)) {
770 copy_str(out[*count].path, sizeof(out[*count].path), full);
771 copy_str(out[*count].root, sizeof(out[*count].root), rootlabel);
772 out[*count].size = (long long)st.st_size;
773 out[*count].mtime = (long long)st.st_mtime;
774 (*count)++;
775 }
776 }
777 closedir(d);
778 }
779#endif
780 return 0;
781}
782
783/* ------------------------------------------------------------------ */
784/* Actions */
785/* ------------------------------------------------------------------ */
786
787static void action_dbs(void)
788{
789 sx_root_t roots[8];
790 sx_db_t dbs[MAX_DBS];
791 int nroots, i, count = 0;
792 int total_visited = 0;
793 int root_visited[8];
794 int root_count[8];
795 int root_truncated[8];
796
797 nroots = collect_roots(roots, 8);
798 memset(dbs, 0, sizeof(dbs));
799 memset(root_visited, 0, sizeof(root_visited));
800 memset(root_count, 0, sizeof(root_count));
801 memset(root_truncated, 0, sizeof(root_truncated));
802
803 /* Each root gets its own entry budget. A single global counter lets one big
804 * tree (/codebases, a monorepo) exhaust the allowance before the walk ever
805 * reaches $HOME, so databases sitting in the user's home directory were
806 * undiscoverable - the UI reported "1 database" on a node that had three.
807 * The per-root counts also let the UI name the root that was truncated
808 * instead of silently showing a short list. */
809 for (i = 0; i < nroots && count < MAX_DBS; i++) {
810 int before = count;
811 int visited = 0;
812 if (!roots[i].exists) continue;
813 walk_dbs(roots[i].path, roots[i].label, 0, dbs, MAX_DBS, &count, &visited);
814 root_visited[i] = visited;
815 root_count[i] = count - before;
816 root_truncated[i] = (visited > scan_budget() || count >= MAX_DBS);
817 total_visited += visited;
818 }
819
820 json_header();
821 fputs("{\"ok\":true,\"action\":\"dbs\",\"plugin\":\"" PLUGIN_ID "\"", stdout);
822
823 fputs(",\"roots\":[", stdout);
824 for (i = 0; i < nroots; i++) {
825 if (i) fputc(',', stdout);
826 fputs("{\"label\":", stdout);
827 json_str(roots[i].label);
828 fputs(",\"path\":", stdout);
829 json_str(roots[i].path);
830 printf(",\"exists\":%s,\"dbs\":%d,\"scanned_entries\":%d,\"truncated\":%s}",
831 roots[i].exists ? "true" : "false",
832 root_count[i], root_visited[i],
833 root_truncated[i] ? "true" : "false");
834 }
835 fputs("]", stdout);
836
837 printf(",\"count\":%d,\"scanned_entries\":%d,\"max_depth\":%d,\"max_scan_entries\":%d,"
838 "\"dbs\":[",
839 count, total_visited, MAX_SCAN_DEPTH, scan_budget());
840 for (i = 0; i < count; i++) {
841 char utc[40];
842 time_t t = (time_t)dbs[i].mtime;
843 struct tm tmv;
844#if defined(_WIN32)
845 struct tm *p = gmtime(&t);
846 if (p) tmv = *p; else memset(&tmv, 0, sizeof tmv);
847#else
848 gmtime_r(&t, &tmv);
849#endif
850 strftime(utc, sizeof utc, "%Y-%m-%dT%H:%M:%SZ", &tmv);
851
852 if (i) fputc(',', stdout);
853 fputs("{\"path\":", stdout);
854 json_str(dbs[i].path);
855 fputs(",\"root\":", stdout);
856 json_str(dbs[i].root);
857 printf(",\"bytes\":%lld,\"mtime\":", dbs[i].size);
858 json_str(utc);
859 fputc('}', stdout);
860 }
861 fputs("],\"readonly\":true}\n", stdout);
862}
863
864/* Count rows in one table, bounded by the statement budget. */
865static int table_rows(sqlite3 *db, const char *table, long long *out)
866{
867 sqlite3_stmt *st = NULL;
868 char sql[MAX_NAME * 2 + 64];
869 char q[MAX_NAME * 2 + 4];
870 int rc;
871
872 quote_ident(table, q, sizeof q);
873 snprintf(sql, sizeof sql, "SELECT count(*) FROM %s", q);
874
875 rc = sqlite3_prepare_v2(db, sql, -1, &st, NULL);
876 if (rc != SQLITE_OK) { if (st) sqlite3_finalize(st); return rc; }
877 rc = sqlite3_step(st);
878 if (rc == SQLITE_ROW) { *out = (long long)sqlite3_column_int64(st, 0); rc = SQLITE_OK; }
879 else *out = -1;
880 sqlite3_finalize(st);
881 return rc;
882}
883
884static void action_schema(const char *dbreq)
885{
886 char path[MAX_PATHQ];
887 char errbuf[512];
888 sqlite3 *db;
889 sqlite3_stmt *st = NULL;
890 sx_budget_t budget;
891 int r, rc, tcount = 0;
892
893 memset(path, 0, sizeof path);
894 r = resolve_db_path(dbreq, path, sizeof path);
895 if (r == 0) { json_error("forbidden_path", "path outside the allowlisted roots or not a database file"); return; }
896 if (r < 0) { json_error("not_found", "database file does not exist"); return; }
897
898 db = open_ro(path, &rc);
899 if (!db) {
900 snprintf(errbuf, sizeof errbuf, "cannot open database (%s)", sqlite3_errstr(rc));
901 json_error("open_failed", errbuf);
902 return;
903 }
904 if (!is_database(db)) { sqlite3_close(db); json_error("not_a_database", "file is not a SQLite database"); return; }
905
906 sqlite3_set_authorizer(db, authorizer_cb, NULL);
907 budget.deadline_ms = now_ms() + STMT_BUDGET_MS;
908 budget.aborted = 0;
909 sqlite3_progress_handler(db, 20000, progress_cb, &budget);
910
911 json_header();
912 fputs("{\"ok\":true,\"action\":\"schema\",\"readonly\":true,\"db\":", stdout);
913 json_str(path);
914 fputs(",\"tables\":[", stdout);
915
916 rc = sqlite3_prepare_v2(db,
917 "SELECT name, type FROM sqlite_master "
918 "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' ORDER BY name",
919 -1, &st, NULL);
920 if (rc != SQLITE_OK) {
921 sqlite3_close(db);
922 /* Header already emitted, so finish the document with an error field. */
923 fputs("],\"error\":\"schema_query_failed\"}\n", stdout);
924 return;
925 }
926
927 while (sqlite3_step(st) == SQLITE_ROW && tcount < MAX_TABLES) {
928 const char *name = (const char *)sqlite3_column_text(st, 0);
929 const char *kind = (const char *)sqlite3_column_text(st, 1);
930 long long rows = -1;
931 sqlite3_stmt *cs = NULL;
932 char q[MAX_NAME * 2 + 4];
933 int ci = 0;
934 char sql[MAX_NAME * 2 + 96];
935
936 if (!name) continue;
937 if (tcount) fputc(',', stdout);
938 fputs("{\"name\":", stdout);
939 json_str(name);
940 fputs(",\"type\":", stdout);
941 json_str(kind ? kind : "table");
942
943 if (table_rows(db, name, &rows) == SQLITE_OK) printf(",\"rows\":%lld", rows);
944 else fputs(",\"rows\":null", stdout);
945
946 quote_ident(name, q, sizeof q);
947 fputs(",\"columns\":[", stdout);
948 snprintf(sql, sizeof sql, "PRAGMA table_info(%s)", q);
949 if (sqlite3_prepare_v2(db, sql, -1, &cs, NULL) == SQLITE_OK) {
950 while (sqlite3_step(cs) == SQLITE_ROW) {
951 const char *cn = (const char *)sqlite3_column_text(cs, 1);
952 const char *ct = (const char *)sqlite3_column_text(cs, 2);
953 int nn = sqlite3_column_int(cs, 3);
954 int pk = sqlite3_column_int(cs, 5);
955 if (ci++) fputc(',', stdout);
956 fputs("{\"name\":", stdout);
957 json_str(cn ? cn : "");
958 fputs(",\"type\":", stdout);
959 json_str(ct ? ct : "");
960 printf(",\"notnull\":%s,\"pk\":%d}", nn ? "true" : "false", pk);
961 }
962 }
963 sqlite3_finalize(cs);
964 fputs("]", stdout);
965
966 ci = 0;
967 fputs(",\"indexes\":[", stdout);
968 snprintf(sql, sizeof sql, "PRAGMA index_list(%s)", q);
969 if (sqlite3_prepare_v2(db, sql, -1, &cs, NULL) == SQLITE_OK) {
970 while (sqlite3_step(cs) == SQLITE_ROW) {
971 const char *in = (const char *)sqlite3_column_text(cs, 1);
972 int uniq = sqlite3_column_int(cs, 2);
973 if (ci++) fputc(',', stdout);
974 fputs("{\"name\":", stdout);
975 json_str(in ? in : "");
976 printf(",\"unique\":%s}", uniq ? "true" : "false");
977 }
978 }
979 sqlite3_finalize(cs);
980 fputs("]}", stdout);
981 tcount++;
982 }
983 sqlite3_finalize(st);
984
985 printf("],\"table_count\":%d,\"truncated\":%s,\"budget_ms\":%d}\n",
986 tcount, tcount >= MAX_TABLES ? "true" : "false", STMT_BUDGET_MS);
987 sqlite3_close(db);
988}
989
990/*
991 * First keyword of the statement. The authorizer is the real gate; this check
992 * only produces a friendlier error than "not authorized".
993 */
994static const char *first_keyword(const char *sql, char *out, size_t outsz)
995{
996 size_t i = 0;
997 while (*sql && isspace((unsigned char)*sql)) sql++;
998 while (*sql && (isalnum((unsigned char)*sql) || *sql == '_') && i + 1 < outsz)
999 out[i++] = (char)tolower((unsigned char)*sql++);
1000 out[i] = '\0';
1001 return out;
1002}
1003
1004static int statement_allowed_shape(const char *kw)
1005{
1006 return strcmp(kw, "select") == 0 || strcmp(kw, "with") == 0 ||
1007 strcmp(kw, "pragma") == 0 || strcmp(kw, "explain") == 0 ||
1008 strcmp(kw, "values") == 0;
1009}
1010
1011static void action_query(const char *dbreq, const char *sql)
1012{
1013 char path[MAX_PATHQ];
1014 char errbuf[512];
1015 char kw[32];
1016 sqlite3 *db;
1017 sqlite3_stmt *st = NULL;
1018 sx_budget_t budget;
1019 int r, rc, ncols, nrows = 0, truncated = 0, i;
1020 char types[MAX_COLS][8];
1021 const char *tail = NULL;
1022 long long t0, t1;
1023
1024 if (!sql || !*sql) { json_error("missing_sql", "pass ?sql=SELECT ... or POST sql=..."); return; }
1025 if (strlen(sql) >= MAX_SQL) { json_error("sql_too_long", "statement exceeds the SQL length limit"); return; }
1026
1027 r = resolve_db_path(dbreq, path, sizeof path);
1028 if (r == 0) { json_error("forbidden_path", "path outside the allowlisted roots or not a database file"); return; }
1029 if (r < 0) { json_error("not_found", "database file does not exist"); return; }
1030
1031 first_keyword(sql, kw, sizeof kw);
1032 if (!statement_allowed_shape(kw)) {
1033 json_error("read_only", "only SELECT / WITH / PRAGMA / EXPLAIN statements are accepted");
1034 return;
1035 }
1036
1037 db = open_ro(path, &rc);
1038 if (!db) {
1039 snprintf(errbuf, sizeof errbuf, "cannot open database (%s)", sqlite3_errstr(rc));
1040 json_error("open_failed", errbuf);
1041 return;
1042 }
1043 if (!is_database(db)) { sqlite3_close(db); json_error("not_a_database", "file is not a SQLite database"); return; }
1044
1045 sqlite3_set_authorizer(db, authorizer_cb, NULL);
1046 budget.deadline_ms = now_ms() + STMT_BUDGET_MS;
1047 budget.aborted = 0;
1048 sqlite3_progress_handler(db, 20000, progress_cb, &budget);
1049
1050 t0 = now_ms();
1051 rc = sqlite3_prepare_v2(db, sql, -1, &st, &tail);
1052 if (rc != SQLITE_OK) {
1053 snprintf(errbuf, sizeof errbuf, "%s", sqlite3_errmsg(db));
1054 sqlite3_close(db);
1055 json_error("sql_error", errbuf);
1056 return;
1057 }
1058 /* Reject stacked statements: prepare() stops after the first one and the
1059 * tail would otherwise be silently dropped. */
1060 while (tail && *tail && isspace((unsigned char)*tail)) tail++;
1061 if (tail && *tail) {
1062 sqlite3_finalize(st);
1063 sqlite3_close(db);
1064 json_error("multiple_statements", "submit one statement at a time");
1065 return;
1066 }
1067
1068 ncols = sqlite3_column_count(st);
1069
1070 json_header();
1071 fputs("{\"ok\":true,\"action\":\"query\",\"readonly\":true,\"db\":", stdout);
1072 json_str(path);
1073 printf(",\"columns\":[");
1074 for (i = 0; i < ncols; i++) {
1075 const char *cn = sqlite3_column_name(st, i);
1076 const char *dl = sqlite3_column_decltype(st, i);
1077 if (i) fputc(',', stdout);
1078 fputs("{\"name\":", stdout);
1079 json_str(cn ? cn : "");
1080 fputs(",\"decl\":", stdout);
1081 json_str(dl ? dl : "");
1082 fputc('}', stdout);
1083 }
1084 fputs("],\"rows\":[", stdout);
1085
1086 memset(types, 0, sizeof types);
1087 while ((rc = sqlite3_step(st)) == SQLITE_ROW) {
1088 if (nrows >= MAX_ROWS) { truncated = 1; break; }
1089 if (nrows) fputc(',', stdout);
1090 fputc('[', stdout);
1091 for (i = 0; i < ncols; i++) {
1092 if (i) fputc(',', stdout);
1093 emit_value(st, i);
1094 /* Column type is only meaningful while a row is positioned, so
1095 * remember the first row's types for the summary block. */
1096 if (nrows == 0 && i < MAX_COLS)
1097 copy_str(types[i], sizeof types[i], value_type_name(st, i));
1098 }
1099 fputc(']', stdout);
1100 nrows++;
1101 }
1102
1103 if (rc == SQLITE_INTERRUPT || budget.aborted) {
1104 /* Budget hit mid-scan: keep what we streamed and say so. */
1105 truncated = 1;
1106 } else if (rc != SQLITE_ROW && rc != SQLITE_DONE) {
1107 const char *m = sqlite3_errmsg(db);
1108 fputs("],\"error\":", stdout);
1109 json_str(m ? m : "statement failed");
1110 printf(",\"aborted\":%s}\n", budget.aborted ? "true" : "false");
1111 sqlite3_finalize(st);
1112 sqlite3_close(db);
1113 return;
1114 }
1115
1116 t1 = now_ms();
1117 printf("],\"row_count\":%d,\"truncated\":%s,\"limit\":%d,\"ms\":%lld,"
1118 "\"aborted\":%s,\"types\":[",
1119 nrows, truncated ? "true" : "false", MAX_ROWS, t1 - t0,
1120 budget.aborted ? "true" : "false");
1121 for (i = 0; i < ncols && nrows > 0 && i < MAX_COLS; i++) {
1122 if (i) fputc(',', stdout);
1123 json_str(types[i]);
1124 }
1125 fputs("]}\n", stdout);
1126
1127 sqlite3_finalize(st);
1128 sqlite3_close(db);
1129}
1130
1131static void action_info(void)
1132{
1133 char utc[40];
1134 utc_now(utc, sizeof utc);
1135
1136 json_header();
1137 fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\","
1138 "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout);
1139 json_str(platform_name());
1140 fputs(",\"sqlite\":", stdout);
1141 json_str(sqlite3_libversion());
1142 printf(",\"pid\":%ld,\"utc\":", node_pid());
1143 json_str(utc);
1144 fputs(",\"node_auth\":", stdout);
1145 {
1146 const char *np = getenv("BOT_PASSWORD");
1147 fputs((np && *np) ? "true" : "false", stdout);
1148 }
1149 fputs(",\"readonly\":true,\"zero_network\":true,\"threadsafe\":0,"
1150 "\"load_extension\":false,"
1151 "\"max_rows\":", stdout);
1152 printf("%d", MAX_ROWS);
1153 fputs(",\"budget_ms\":", stdout);
1154 printf("%d", STMT_BUDGET_MS);
1155 fputs(",\"allowed_roots\":[\"allowed\",\"workspace\",\"codebases\",\"home\"],"
1156 "\"actions\":[\"dbs\",\"schema\",\"query\",\"info\"]}\n", stdout);
1157}
1158
1159/* ------------------------------------------------------------------ */
1160/* HTML UI */
1161/* ------------------------------------------------------------------ */
1162
1163static int mode_html(int embed)
1164{
1165 fputs("Content-Type: text/html; charset=utf-8\r\n"
1166 "Cache-Control: no-store\r\n"
1167 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1168
1169 fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>"
1170 "<meta name='viewport' content='width=device-width,initial-scale=1'>"
1171 "<title>sqlite</title>", stdout);
1172
1173 fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS, stdout);
1174 fputs(
1175"*{box-sizing:border-box}"
1176"body{margin:0;padding:16px;background:var(--bg);color:var(--text);"
1177 "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;"
1178 "font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}"
1179".wrap{max-width:1240px;margin:0 auto;min-width:0}"
1180".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}"
1181".title{font-size:20px;font-weight:700;margin:0}"
1182".sub{color:var(--muted);font-size:12px;font-family:var(--mono);overflow-wrap:anywhere}"
1183".spacer{flex:1}"
1184".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;"
1185 "background:var(--surface2);color:var(--muted);border:1px solid var(--line);white-space:nowrap}"
1186".pill.ro{color:var(--ok);border-color:rgba(48,209,88,.4)}"
1187".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;"
1188 "padding:16px;margin-bottom:14px;min-width:0}"
1189".card h2{margin:0 0 12px;font-size:12px;letter-spacing:.06em;"
1190 "text-transform:uppercase;color:var(--muted);font-weight:600}"
1191"button{background:var(--accent);color:#fff;border:0;border-radius:999px;"
1192 "padding:6px 13px;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}"
1193"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}"
1194"button:active{transform:scale(.98)}"
1195"button:disabled{opacity:.5;cursor:default}"
1196"select,input,textarea{background:var(--surface2);color:var(--text);"
1197 "border:1px solid var(--line);border-radius:9px;padding:8px 10px;"
1198 "font-family:var(--mono);font-size:13px;width:100%}"
1199"textarea{min-height:104px;resize:vertical;line-height:1.5}"
1200"select{font-family:inherit}"
1201".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}"
1202".layout{display:grid;grid-template-columns:250px minmax(0,1fr);gap:14px;align-items:start}"
1203"@media(max-width:860px){.layout{grid-template-columns:minmax(0,1fr)}}"
1204".side{background:var(--surface);border:1px solid var(--line);border-radius:14px;"
1205 "padding:12px;min-width:0}"
1206".side h3{margin:0 0 8px;font-size:11px;letter-spacing:.06em;text-transform:uppercase;"
1207 "color:var(--muted);font-weight:600}"
1208".titem{display:block;width:100%;text-align:left;background:transparent;color:var(--text);"
1209 "border:0;border-radius:8px;padding:6px 8px;font-size:12px;font-family:var(--mono);"
1210 "cursor:pointer;overflow-wrap:anywhere}"
1211".titem:hover{background:var(--surface2)}"
1212".titem.on{background:var(--surface2);font-weight:700;color:var(--accent)}"
1213".titem .n{color:var(--muted);font-weight:400}"
1214".tblwrap{overflow:auto;max-height:60vh;border:1px solid var(--line);border-radius:10px}"
1215"table{width:100%;border-collapse:collapse;font-size:12.5px;font-family:var(--mono)}"
1216"th,td{text-align:left;padding:6px 9px;border-bottom:1px solid var(--line);"
1217 "white-space:nowrap;max-width:340px;overflow:hidden;text-overflow:ellipsis}"
1218"th{position:sticky;top:0;background:var(--surface2);cursor:pointer;"
1219 "font-weight:700;user-select:none;z-index:1}"
1220"th .dir{color:var(--accent);font-size:10px}"
1221"td.null{color:var(--muted);font-style:italic}"
1222"td.num{text-align:right}"
1223"tbody tr:hover{background:var(--surface2)}"
1224".empty{color:var(--muted);padding:14px 0;font-size:13px}"
1225".err{color:var(--danger);font-family:var(--mono);font-size:12.5px;overflow-wrap:anywhere}"
1226".cols{display:flex;gap:6px;flex-wrap:wrap;margin-top:8px}"
1227".chip{font-size:11px;font-family:var(--mono);color:var(--muted);"
1228 "background:var(--surface2);border:1px solid var(--line);border-radius:7px;padding:2px 7px}"
1229".hint{color:var(--muted);font-size:11.5px;margin-top:6px}"
1230"kbd{font-family:var(--mono);font-size:11px;background:var(--surface2);"
1231 "border:1px solid var(--line);border-radius:5px;padding:1px 5px}"
1232"</style></head>" SX_BOT_THEME_HANDOFF "<body>", stdout);
1233
1234 fputs("<div class='wrap'>", stdout);
1235
1236 if (!embed) {
1237 fputs("<div style='margin-bottom:12px'><a href='/' "
1238 "style='color:var(--accent);text-decoration:none;font-weight:600'>"
1239 "&larr; Back to Bot</a></div>", stdout);
1240 }
1241
1242 fputs("<div class='top'><h2 class='title'>sqlite</h2>"
1243 "<span class='pill ro'>read-only</span>"
1244 "<span class='pill' id='dbcount'>&mdash;</span>"
1245 "<span class='spacer'></span>"
1246 "<button class='ghost embed-hide' id='themebtn' type='button'>Theme</button>"
1247 "</div>", stdout);
1248
1249 fputs("<div class='card'><h2>Database</h2>"
1250 "<div class='row'><div style='flex:1 1 320px;min-width:0'>"
1251 "<select id='dbsel'><option value=''>Loading databases...</option></select></div>"
1252 "<button class='ghost' id='reloadbtn' type='button'>Rescan</button></div>"
1253 "<div class='hint' id='dbhint'>Only .db / .sqlite / .sqlite3 files under the "
1254 "allowlisted roots are listed.</div>"
1255 "<div class='hint' id='rootline'></div></div>", stdout);
1256
1257 fputs("<div class='layout'><div class='side'><h3>Tables</h3>"
1258 "<div id='tables'><div class='empty'>Select a database.</div></div></div>", stdout);
1259
1260 fputs("<div style='min-width:0'><div class='card'><h2>SQL</h2>"
1261 "<textarea id='sql' spellcheck='false'>SELECT name, type FROM sqlite_master LIMIT 50;</textarea>"
1262 "<div class='row' style='margin-top:8px'>"
1263 "<button id='runbtn' type='button'>Run</button>"
1264 "<button class='ghost' id='csvbtn' type='button'>Copy CSV</button>"
1265 "<button class='ghost' id='jsonbtn' type='button'>Copy JSON</button>"
1266 "<span class='spacer'></span>"
1267 "<span class='hint'><kbd>Ctrl</kbd>+<kbd>Enter</kbd> to run</span>"
1268 "</div><div class='hint' id='qmeta'></div></div>", stdout);
1269
1270 fputs("<div class='card'><h2>Results</h2>"
1271 "<div class='cols' id='cols'></div>"
1272 "<div class='tblwrap' id='reswrap' style='margin-top:10px'>"
1273 "<div class='empty'>No results yet.</div></div></div></div></div>", stdout);
1274
1275 fputs("<div class='card' id='infocard' style='display:none'><h2>Info</h2>"
1276 "<div class='cols' id='info'></div></div></div>", stdout);
1277
1278 /* ---------------- client ---------------- */
1279 fputs("<script>\n"
1280"var Q = new URLSearchParams(location.search);\n"
1281"var node = Q.get('node') || '';\n"
1282"var sid = Q.get('id') || '';\n"
1283"var HUB = Q.get('plugin') || '';\n"
1284"var pwd = Q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) || localStorage.getItem('bot_active_pwd') || '';\n"
1285"var currentDb = '';\n"
1286"var lastData = null;\n"
1287"\n"
1288"function $(id){ return document.getElementById(id); }\n"
1289"function txt(id, v){ var e = $(id); if (e) e.textContent = (v === undefined || v === null) ? '' : v; }\n"
1290"\n"
1291"/* Two routes, and getting this wrong is the classic plugin bug:\n"
1292" - served through the hub (bot.scorpiox.net/plugins?plugin=...&node=...)\n"
1293" -> call the hub proxy back with /plugins?plugin=<id>&action=...\n"
1294" - opened directly on the node -> the plugin IS the route: /plugin_sqlite?action=... */\n"
1295"function apiUrl(action, extra){\n"
1296" var u = (HUB ? '/plugins?plugin=' + encodeURIComponent(HUB)\n"
1297" : '/plugin_sqlite?') +\n"
1298" (HUB ? '&' : '') + 'action=' + encodeURIComponent(action);\n"
1299" if (extra) u += '&' + extra;\n"
1300" if (node) u += '&node=' + encodeURIComponent(node);\n"
1301" if (sid) u += '&id=' + encodeURIComponent(sid);\n"
1302" if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n"
1303" return u;\n"
1304"}\n"
1305"function api(action, extra){\n"
1306" return fetch(apiUrl(action, extra), {headers: pwd ? {'X-Bot-Password': pwd} : {}})\n"
1307" .then(function(r){ return r.json(); });\n"
1308"}\n"
1309"function apiPost(action, extra, body){\n"
1310" return fetch(apiUrl(action, extra), {\n"
1311" method: 'POST',\n"
1312" headers: pwd ? {'X-Bot-Password': pwd, 'Content-Type': 'application/x-www-form-urlencoded'} : {'Content-Type': 'application/x-www-form-urlencoded'},\n"
1313" body: body\n"
1314" }).then(function(r){ return r.json(); });\n"
1315"}\n"
1316"\n"
1317"function el(tag, c, t){\n"
1318" var e = document.createElement(tag);\n"
1319" if (c) e.className = c;\n"
1320" if (t !== undefined) e.textContent = t;\n"
1321" return e;\n"
1322"}\n"
1323"function bytes(n){\n"
1324" if (n === null || n === undefined) return '\\u2014';\n"
1325" var u = ['B','KB','MB','GB','TB'], i = 0, v = n;\n"
1326" while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }\n"
1327" return (i === 0 ? v.toFixed(0) : v.toFixed(v >= 100 ? 0 : 1)) + ' ' + u[i];\n"
1328"}\n"
1329"function err(msg){ var w = $('reswrap'); w.textContent = ''; w.appendChild(el('div','err', msg)); }\n"
1330"\n"
1331"/* ---- databases ---- */\n"
1332"function loadDbs(){\n"
1333" api('dbs').then(function(d){\n"
1334" var sel = $('dbsel');\n"
1335" sel.textContent = '';\n"
1336" if (!d.ok) { err(d.error || 'failed to list databases'); return; }\n"
1337" var list = d.dbs || [];\n"
1338" txt('dbcount', list.length + (list.length === 1 ? ' database' : ' databases'));\n"
1339" /* Name the roots, and say so out loud when one was cut short - a short\n"
1340" list because of the scan cap looks exactly like a node with no files. */\n"
1341" var roots = d.roots || [], walked = [], cut = [];\n"
1342" roots.forEach(function(r){\n"
1343" if (!r.exists) return;\n"
1344" walked.push(r.label);\n"
1345" if (r.truncated) cut.push(r.label);\n"
1346" });\n"
1347" txt('rootline', walked.length ? ('roots: ' + walked.join(', ') +\n"
1348" (cut.length ? ' \\u00b7 scan cap reached in ' + cut.join(', ') : '')) :\n"
1349" 'no allowlisted root exists on this node');\n"
1350" if (!list.length) {\n"
1351" var o = el('option', null, 'No .db / .sqlite files found');\n"
1352" o.value = ''; sel.appendChild(o);\n"
1353" $('tables').textContent = '';\n"
1354" $('tables').appendChild(el('div','empty','No database selected.'));\n"
1355" return;\n"
1356" }\n"
1357" var ph = el('option', null, 'Choose a database (' + list.length + ')');\n"
1358" ph.value = ''; sel.appendChild(ph);\n"
1359" list.forEach(function(x){\n"
1360" var o = el('option', null, x.path + ' \\u00b7 ' + bytes(x.bytes));\n"
1361" o.value = x.path;\n"
1362" sel.appendChild(o);\n"
1363" });\n"
1364" if (currentDb) sel.value = currentDb;\n"
1365" if (!sel.value && list.length === 1) { sel.value = list[0].path; selectDb(list[0].path); }\n"
1366" }).catch(function(e){ err('Error: ' + e); });\n"
1367"}\n"
1368"\n"
1369"function selectDb(path){\n"
1370" currentDb = path;\n"
1371" var box = $('tables');\n"
1372" box.textContent = '';\n"
1373" if (!path) { box.appendChild(el('div','empty','Select a database.')); return; }\n"
1374" box.appendChild(el('div','empty','Loading schema...'));\n"
1375" api('schema', 'db=' + encodeURIComponent(path)).then(function(d){\n"
1376" box.textContent = '';\n"
1377" if (!d.ok) { box.appendChild(el('div','err', d.error + (d.detail ? ': ' + d.detail : ''))); return; }\n"
1378" var list = d.tables || [];\n"
1379" txt('dbhint', path + ' \\u00b7 ' + list.length + ' table' + (list.length === 1 ? '' : 's') + ' \\u00b7 read-only');\n"
1380" if (!list.length) { box.appendChild(el('div','empty','No tables.')); return; }\n"
1381" list.forEach(function(t){\n"
1382" var b = el('button','titem');\n"
1383" b.type = 'button';\n"
1384" b.appendChild(document.createTextNode(t.name));\n"
1385" var n = el('span','n', ' ' + (t.rows === null || t.rows === undefined ? '?' : t.rows)\n"
1386" + (t.type === 'view' ? ' view' : ''));\n"
1387" b.appendChild(n);\n"
1388" b.title = (t.columns || []).map(function(c){ return c.name + ' ' + (c.type || ''); }).join('\\n');\n"
1389" b.onclick = function(){\n"
1390" Array.prototype.forEach.call(box.children, function(x){ x.classList.remove('on'); });\n"
1391" b.classList.add('on');\n"
1392" var q = 'SELECT * FROM \"' + String(t.name).replace(/\\\"/g, '\\\"\\\"') + '\" LIMIT 100;';\n"
1393" $('sql').value = q;\n"
1394" runQuery();\n"
1395" };\n"
1396" box.appendChild(b);\n"
1397" });\n"
1398" }).catch(function(e){ box.textContent = ''; box.appendChild(el('div','err','Error: ' + e)); });\n"
1399"}\n"
1400"\n"
1401"/* ---- query ---- */\n"
1402"function clearSorted(){ sortCol = -1; sortDir = 1; }\n"
1403"var sortCol = -1, sortDir = 1;\n"
1404"\n"
1405"function runQuery(){\n"
1406" var sql = $('sql').value;\n"
1407" if (!currentDb) { err('Select a database first.'); return; }\n"
1408" if (!sql.trim()) { err('Type a statement.'); return; }\n"
1409" $('runbtn').disabled = true;\n"
1410" txt('qmeta','Running...');\n"
1411" clearSorted();\n"
1412" apiPost('query', 'db=' + encodeURIComponent(currentDb),\n"
1413" 'sql=' + encodeURIComponent(sql)).then(function(d){\n"
1414" $('runbtn').disabled = false;\n"
1415" lastData = d;\n"
1416" if (!d.ok) { txt('qmeta',''); err((d.error || 'error') + (d.detail ? ': ' + d.detail : '')); $('cols').textContent=''; return; }\n"
1417" if (d.error) { txt('qmeta',''); err(d.error); $('cols').textContent=''; return; }\n"
1418" txt('qmeta', d.row_count + ' row' + (d.row_count === 1 ? '' : 's')\n"
1419" + (d.truncated ? ' (truncated)' : '') + ' \\u00b7 ' + d.ms + ' ms'\n"
1420" + (d.aborted ? ' \\u00b7 stopped at the time budget' : ''));\n"
1421" renderTable(d);\n"
1422" }).catch(function(e){\n"
1423" $('runbtn').disabled = false;\n"
1424" txt('qmeta',''); err('Request failed: ' + e);\n"
1425" });\n"
1426"}\n"
1427"\n"
1428"function renderTable(d){\n"
1429" var wrap = $('reswrap');\n"
1430" wrap.textContent = '';\n"
1431" $('cols').textContent = '';\n"
1432" var cols = d.columns || [], rows = d.rows || [];\n"
1433" cols.forEach(function(c){\n"
1434" $('cols').appendChild(el('span','chip', c.name + ' ' + (c.decl || '')));\n"
1435" });\n"
1436" if (!rows.length) { wrap.appendChild(el('div','empty','0 rows.')); return; }\n"
1437" drawGrid(wrap, cols, rows);\n"
1438"}\n"
1439"\n"
1440"function cellValue(v){\n"
1441" if (v === null || v === undefined) return {t: 'NULL', cls: 'null'};\n"
1442" if (typeof v === 'object') return {t: '[blob ' + v.blob_bytes + ']', cls: 'null'};\n"
1443" if (typeof v === 'number') return {t: String(v), cls: 'num'};\n"
1444" return {t: String(v), cls: ''};\n"
1445"}\n"
1446"\n"
1447"function drawGrid(wrap, cols, rows){\n"
1448" var tbl = el('table');\n"
1449" var thead = el('thead'), tr = el('tr');\n"
1450" cols.forEach(function(c, i){\n"
1451" var th = el('th');\n"
1452" th.appendChild(document.createTextNode(c.name));\n"
1453" if (sortCol === i) {\n"
1454" var dir = el('span','dir', sortDir > 0 ? ' \\u25b2' : ' \\u25bc');\n"
1455" th.appendChild(dir);\n"
1456" }\n"
1457" th.title = c.decl || '';\n"
1458" th.onclick = function(){\n"
1459" if (sortCol === i) sortDir = -sortDir; else { sortCol = i; sortDir = 1; }\n"
1460" var sorted = rows.slice().sort(function(a, b){\n"
1461" var x = a[i], y = b[i];\n"
1462" if (x === null || x === undefined) return 1;\n"
1463" if (y === null || y === undefined) return -1;\n"
1464" if (typeof x === 'number' && typeof y === 'number') return (x - y) * sortDir;\n"
1465" return String(x).localeCompare(String(y)) * sortDir;\n"
1466" });\n"
1467" wrap.textContent = '';\n"
1468" drawGrid(wrap, cols, sorted);\n"
1469" };\n"
1470" tr.appendChild(th);\n"
1471" });\n"
1472" thead.appendChild(tr);\n"
1473" tbl.appendChild(thead);\n"
1474" var tbody = el('tbody');\n"
1475" rows.forEach(function(r){\n"
1476" var row = el('tr');\n"
1477" cols.forEach(function(c, i){\n"
1478" var cv = cellValue(r[i]);\n"
1479" var td = el('td', cv.cls, cv.t);\n"
1480" td.title = cv.t;\n"
1481" row.appendChild(td);\n"
1482" });\n"
1483" tbody.appendChild(row);\n"
1484" });\n"
1485" tbl.appendChild(tbody);\n"
1486" wrap.appendChild(tbl);\n"
1487"}\n"
1488"\n"
1489"/* ---- export ---- */\n"
1490"function toCsv(d){\n"
1491" var cols = (d.columns || []).map(function(c){ return c.name; });\n"
1492" function q(v){\n"
1493" if (v === null || v === undefined) return '';\n"
1494" if (typeof v === 'object') return 'blob:' + v.blob_bytes;\n"
1495" var s = String(v);\n"
1496" return /[\",\\n\\r]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s;\n"
1497" }\n"
1498" var out = [cols.map(q).join(',')];\n"
1499" (d.rows || []).forEach(function(r){ out.push(r.map(q).join(',')); });\n"
1500" return out.join('\\n');\n"
1501"}\n"
1502"function copy(text, label){\n"
1503" var done = function(){ txt('qmeta', label + ' copied'); };\n"
1504" if (navigator.clipboard && navigator.clipboard.writeText) {\n"
1505" navigator.clipboard.writeText(text).then(done, function(){\n"
1506" var ta = el('textarea'); ta.value = text; document.body.appendChild(ta);\n"
1507" ta.select(); document.execCommand('copy'); document.body.removeChild(ta); done();\n"
1508" });\n"
1509" } else {\n"
1510" var ta = el('textarea'); ta.value = text; document.body.appendChild(ta);\n"
1511" ta.select(); document.execCommand('copy'); document.body.removeChild(ta); done();\n"
1512" }\n"
1513"}\n"
1514"\n"
1515"/* ---- theme ---- */\n"
1516"function applyTheme(t){\n"
1517" document.documentElement.setAttribute('data-theme', t);\n"
1518" try { localStorage.setItem('sqlite_theme', t); } catch (e) {}\n"
1519"}\n"
1520"var savedTheme = null;\n"
1521"try { savedTheme = localStorage.getItem('sqlite_theme'); } catch (e) {}\n"
1522"applyTheme(savedTheme || (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'));\n"
1523"$('themebtn').onclick = function(){\n"
1524" applyTheme(document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light');\n"
1525"};\n"
1526"\n"
1527"/* ---- wiring ---- */\n"
1528"$('dbsel').onchange = function(){ selectDb(this.value); };\n"
1529"$('reloadbtn').onclick = function(){ loadDbs(); if (currentDb) selectDb(currentDb); };\n"
1530"$('runbtn').onclick = runQuery;\n"
1531"$('sql').addEventListener('keydown', function(e){\n"
1532" if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); runQuery(); }\n"
1533"});\n"
1534"$('csvbtn').onclick = function(){ if (!lastData || !lastData.ok) { txt('qmeta','nothing to copy'); return; } copy(toCsv(lastData), 'CSV'); };\n"
1535"$('jsonbtn').onclick = function(){ if (!lastData || !lastData.ok) { txt('qmeta','nothing to copy'); return; } copy(JSON.stringify(lastData.rows, null, 0), 'JSON'); };\n"
1536"\n"
1537"loadDbs();\n"
1538"api('info').then(function(d){\n"
1539" if (!d.ok) return;\n"
1540" var box = $('info');\n"
1541" $('infocard').style.display = '';\n"
1542" [['plugin', d.plugin], ['version', d.version], ['sqlite', d.sqlite],\n"
1543" ['platform', d.platform], ['max rows', d.max_rows], ['budget ms', d.budget_ms]].forEach(function(kv){\n"
1544" box.appendChild(el('span','chip', kv[0] + ' ' + kv[1]));\n"
1545" });\n"
1546"}).catch(function(){});\n"
1547"</script></body></html>\n", stdout);
1548
1549 return 0;
1550}
1551
1552/* ------------------------------------------------------------------ */
1553/* Main */
1554/* ------------------------------------------------------------------ */
1555
1556int main(int argc, char **argv)
1557{
1558 const char *qs;
1559 char action[64], db[512], sqlbuf[MAX_SQL], format[16];
1560 int want_json = 0, embed = 0;
1561
1562 if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1563 puts("{\"name\":\"sqlite\",\"desc\":\"SQLite viewer\"}");
1564 return 0;
1565 }
1566 if (argc > 1 && strcmp(argv[1], "--version") == 0) {
1567 printf("%s %s (sqlite %s)\n", PLUGIN_ID, PLUGIN_VER, sqlite3_libversion());
1568 return 0;
1569 }
1570 if (argc > 1 && (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0)) {
1571 fputs("usage: " PLUGIN_ID " [--meta|--version|--help]\n"
1572 "\n"
1573 "Run as a CGI-style executable. Modes:\n"
1574 " --meta / SX_PLUGIN_META=1 discovery JSON\n"
1575 " ?action=dbs list databases under the allowed roots\n"
1576 " ?action=schema&db=<path> tables, columns, indexes, row counts\n"
1577 " ?action=query&db=<path>&sql=<SELECT> bounded read-only query (GET or POST sql=)\n"
1578 " ?action=info plugin build and limits\n"
1579 " GET (default) HTML explorer (honours ?embed=1)\n"
1580 "\n"
1581 "Read-only: the authorizer allows SELECT/READ/FUNCTION/read-only PRAGMA only and\n"
1582 "every database is opened with SQLITE_OPEN_READONLY. Rows are capped at 500.\n",
1583 stdout);
1584 return 0;
1585 }
1586
1587 require_node_auth();
1588
1589 qs = getenv("QUERY_STRING");
1590 if (!qs) qs = "";
1591
1592 action[0] = db[0] = sqlbuf[0] = format[0] = '\0';
1593 get_query_val(qs, "action", action, sizeof action);
1594 get_query_val(qs, "db", db, sizeof db);
1595 get_query_val(qs, "sql", sqlbuf, sizeof sqlbuf);
1596 get_query_val(qs, "format", format, sizeof format);
1597
1598 if (strstr(qs, "embed=1") || strstr(qs, "embed=true")) embed = 1;
1599 if (ci_prefix(format, "json")) want_json = 1;
1600
1601 /* POST bodies arrive through the server's body file; read a plain
1602 * urlencoded body and pull "sql" out of it. */
1603 if (!sqlbuf[0]) {
1604 const char *bodyfile = getenv("HTTP_BODY_FILE");
1605 if (bodyfile && *bodyfile) {
1606 FILE *f = fopen(bodyfile, "rb");
1607 if (f) {
1608 char body[MAX_SQL + 1024];
1609 size_t n = fread(body, 1, sizeof(body) - 1, f);
1610 body[n] = '\0';
1611 fclose(f);
1612 get_query_val(body, "sql", sqlbuf, sizeof sqlbuf);
1613 if (!sqlbuf[0]) {
1614 /* Some callers post the statement bare. */
1615 copy_str(sqlbuf, sizeof sqlbuf, body);
1616 }
1617 }
1618 }
1619 }
1620
1621 if (!action[0] && want_json) copy_str(action, sizeof action, "dbs");
1622
1623 if (action[0]) {
1624 if (strcmp(action, "dbs") == 0) { action_dbs(); return 0; }
1625 if (strcmp(action, "schema") == 0) { action_schema(db); return 0; }
1626 if (strcmp(action, "query") == 0) { action_query(db, sqlbuf); return 0; }
1627 if (strcmp(action, "info") == 0) { action_info(); return 0; }
1628 json_error("unknown_action", "supported actions: dbs, schema, query, info");
1629 return 0;
1630 }
1631
1632 mode_html(embed);
1633 return 0;
1634}