scorpiox-bot-plugin-hello
←plugin_hello.cc
526 lines · 18 KBHEADBlameDownload
1/*
2 * plugin_hello — SCORPIOX BOT open-source starter 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=... | ?format=json -> JSON node API
7 * 3. GET (default) -> responsive HTML starter bench
8 *
9 * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and
10 * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under
11 * scorpiox-server on the node.
12 *
13 * MIT License. Copyright (c) 2026 SCORPIOX INC.
14 */
15
16#if !defined(_WIN32)
17# define _POSIX_C_SOURCE 200809L
18# define _DEFAULT_SOURCE 1
19#endif
20
21#include <stdio.h>
22#include <stdlib.h>
23#include <string.h>
24#include <time.h>
25#include <ctype.h>
26
27#if defined(_WIN32)
28# define WIN32_LEAN_AND_MEAN
29# include <windows.h>
30# include <io.h>
31# include <fcntl.h>
32/* MinGW/MSVC CRT starts stdout in TEXT mode, which rewrites every \n we emit
33 * into \r\n. A CGI header block must end with exactly CRLF CRLF; text mode
34 * turns "\r\n\r\n" into "\r\r\n\r\r\n", scorpiox-server cannot find the
35 * header/body separator, and the entire reply (headers included) is served as
36 * a body. Force binary stdio before main() runs — same constructor the
37 * scorpiox-bot-api handlers use (sx_shell.h). */
38__attribute__((constructor))
39static void sx_plugin_binary_stdio(void) {
40 _setmode(_fileno(stdout), _O_BINARY);
41 _setmode(_fileno(stdin), _O_BINARY);
42}
43#else
44# include <unistd.h>
45# include <sys/utsname.h>
46#endif
47
48#include "bot_theme_plugin.h"
49
50#define PLUGIN_SLUG "hello"
51#define PLUGIN_ID "plugin_hello"
52#define PLUGIN_VER "1.1.4"
53
54/* ------------------------------------------------------------------ */
55/* Query string helpers */
56/* ------------------------------------------------------------------ */
57
58/* Percent-decode in place (handles '+' as space). */
59static void url_decode(char *s)
60{
61 char *o = s;
62 if (!s) return;
63 while (*s) {
64 if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
65 int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
66 int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
67 *o++ = (char)((hi << 4) | lo);
68 s += 3;
69 } else if (*s == '+') {
70 *o++ = ' ';
71 s++;
72 } else {
73 *o++ = *s++;
74 }
75 }
76 *o = '\0';
77}
78
79/* Read a single query parameter (decoded) into out. Returns 1 if found. */
80static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
81{
82 size_t klen;
83 const char *p;
84
85 if (!out || outsz == 0) return 0;
86 out[0] = '\0';
87 if (!qs || !key) return 0;
88 klen = strlen(key);
89
90 for (p = qs; *p; ) {
91 if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
92 const char *v = p + klen + 1;
93 size_t i = 0;
94 while (*v && *v != '&' && i + 1 < outsz)
95 out[i++] = *v++;
96 out[i] = '\0';
97 url_decode(out);
98 return 1;
99 }
100 p = strchr(p, '&');
101 if (!p) break;
102 p++;
103 }
104 return 0;
105}
106
107/* ------------------------------------------------------------------ */
108/* JSON output helpers */
109/* ------------------------------------------------------------------ */
110
111static void json_str(const char *s)
112{
113 putchar('"');
114 for (; s && *s; s++) {
115 unsigned char c = (unsigned char)*s;
116 switch (c) {
117 case '"': fputs("\\\"", stdout); break;
118 case '\\': fputs("\\\\", stdout); break;
119 case '\n': fputs("\\n", stdout); break;
120 case '\r': fputs("\\r", stdout); break;
121 case '\t': fputs("\\t", stdout); break;
122 default:
123 if (c < 0x20) printf("\\u%04x", (unsigned)c);
124 else putchar((int)c);
125 }
126 }
127 putchar('"');
128}
129
130/* ------------------------------------------------------------------ */
131/* Node facts */
132/* ------------------------------------------------------------------ */
133
134static int node_hostname(char *buf, size_t sz)
135{
136 buf[0] = '\0';
137#if defined(_WIN32)
138 {
139 DWORD n = (DWORD)sz;
140 if (!GetComputerNameA(buf, &n)) { strncpy(buf, "unknown", sz - 1); buf[sz - 1] = '\0'; }
141 }
142#else
143 if (gethostname(buf, sz) != 0) { strncpy(buf, "unknown", sz - 1); buf[sz - 1] = '\0'; }
144#endif
145 buf[sz - 1] = '\0';
146 return 0;
147}
148
149static const char *node_os(void)
150{
151#if defined(_WIN32)
152 return "windows";
153#elif defined(__APPLE__)
154 return "macos";
155#else
156 return "linux";
157#endif
158}
159
160static const char *node_arch(void)
161{
162#if defined(_WIN64) || defined(__x86_64__) || defined(__amd64__)
163 return "x86_64";
164#elif defined(_WIN32) || defined(__i386__)
165 return "x86";
166#elif defined(__aarch64__) || defined(__arm64__)
167 return "arm64";
168#elif defined(__arm__)
169 return "arm";
170#else
171 return "unknown";
172#endif
173}
174
175static const char *node_libc(void)
176{
177#if defined(_WIN32)
178 return "native";
179#elif defined(__APPLE__)
180 return "libc";
181#elif defined(__MUSL__)
182 return "musl";
183#else
184 return "glibc";
185#endif
186}
187
188static long node_pid(void)
189{
190#if defined(_WIN32)
191 return (long)GetCurrentProcessId();
192#else
193 return (long)getpid();
194#endif
195}
196
197/* ISO-8601 UTC timestamp. */
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 gmtime_s(&tmv, &t);
204#else
205 gmtime_r(&t, &tmv);
206#endif
207 if (strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv) == 0)
208 strncpy(buf, "1970-01-01T00:00:00Z", sz - 1), buf[sz - 1] = '\0';
209}
210
211/* ------------------------------------------------------------------ */
212/* Node auth */
213/* ------------------------------------------------------------------ */
214
215/*
216 * The node API (:8150) is reachable from the LAN, so a plugin must not answer
217 * an unauthenticated caller. Accepted forms match the rest of the node API:
218 * X-Bot-Password, Authorization: Bearer, or ?pwd=. When BOT_PASSWORD is unset
219 * the node is in explicitly open mode and this is a no-op, exactly like
220 * terminal_tmux.c and node_rdp.c.
221 */
222static void require_node_auth(void)
223{
224 const char *np = getenv("BOT_PASSWORD");
225 const char *xp;
226 const char *auth;
227 const char *qs;
228 char qpwd[256];
229
230 if (!np || !*np) return;
231
232 xp = getenv("HTTP_X_BOT_PASSWORD");
233 if (xp && strcmp(xp, np) == 0) return;
234
235 auth = getenv("HTTP_AUTHORIZATION");
236 if (auth) {
237 while (*auth == ' ') auth++;
238 if (strncmp(auth, "Bearer ", 7) == 0) {
239 auth += 7;
240 while (*auth == ' ') auth++;
241 if (strcmp(auth, np) == 0) return;
242 }
243 }
244
245 qs = getenv("QUERY_STRING");
246 if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0)
247 return;
248
249 fputs("Status: 401 Unauthorized\r\n"
250 "Content-Type: application/json; charset=utf-8\r\n"
251 "Cache-Control: no-store\r\n"
252 "X-Content-Type-Options: nosniff\r\n\r\n"
253 "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
254 exit(0);
255}
256
257/* ------------------------------------------------------------------ */
258/* Modes */
259/* ------------------------------------------------------------------ */
260static int mode_meta(void)
261{
262 puts("{\"name\":\"hello\",\"desc\":\"Starter demo\"}");
263 return 0;
264}
265
266static void json_header(void)
267{
268 /* Deliberately no Content-Length — the server owns framing. */
269 fputs("Content-Type: application/json; charset=utf-8\r\n"
270 "Cache-Control: no-store\r\n"
271 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
272}
273
274static void emit_hints(void)
275{
276 fputs(",\"hints\":{"
277 "\"next_step\":\"Edit src/plugin_hello.c, then run `make` (or `make musl win64`)\","
278 "\"install\":\"cp plugin_hello ~/.scorpiox/plugins/ \","
279 "\"docs\":\"See README.md for the 3-mode contract and the fork workflow\","
280 "\"verify\":\"plugin_hello --meta && QUERY_STRING='action=info' plugin_hello\""
281 "}", stdout);
282}
283
284static void emit_info_body(void)
285{
286 char host[256];
287 char ts[64];
288 const char *qs = getenv("QUERY_STRING");
289
290 node_hostname(host, sizeof(host));
291 utc_now(ts, sizeof(ts));
292
293 fputs("{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"slug\":\"" PLUGIN_SLUG "\","
294 "\"version\":\"" PLUGIN_VER "\",\"node\":{", stdout);
295 fputs("\"hostname\":", stdout); json_str(host);
296 fputs(",\"os\":", stdout); json_str(node_os());
297 fputs(",\"arch\":", stdout); json_str(node_arch());
298 fputs(",\"libc\":", stdout); json_str(node_libc());
299 printf(",\"pid\":%ld", node_pid());
300 fputs(",\"utc\":", stdout); json_str(ts);
301 fputs("},\"query_string\":", stdout); json_str(qs ? qs : "");
302 emit_hints();
303 fputs("}\n", stdout);
304}
305
306static int mode_json(const char *qs)
307{
308 char action[64];
309 char msg[512];
310 char format[32];
311
312 action[0] = '\0';
313 msg[0] = '\0';
314 format[0] = '\0';
315 get_query_val(qs, "action", action, sizeof(action));
316 get_query_val(qs, "msg", msg, sizeof(msg));
317 get_query_val(qs, "format", format, sizeof(format));
318
319 json_header();
320
321 if (!action[0] || strcmp(action, "info") == 0) {
322 emit_info_body();
323 return 0;
324 }
325
326 if (strcmp(action, "echo") == 0) {
327 fputs("{\"ok\":true,\"action\":\"echo\",\"msg\":", stdout);
328 json_str(msg);
329 printf(",\"len\":%lu}", (unsigned long)strlen(msg));
330 fputs("\n", stdout);
331 return 0;
332 }
333
334 fputs("{\"ok\":false,\"error\":\"unknown action\",\"action\":", stdout);
335 json_str(action);
336 fputs(",\"supported\":[\"info\",\"echo\"]}\n", stdout);
337 return 0;
338}
339
340/* ------------------------------------------------------------------ */
341/* HTML UI */
342/* ------------------------------------------------------------------ */
343
344static int mode_html(int embed)
345{
346 fputs("Content-Type: text/html; charset=utf-8\r\n"
347 "Cache-Control: no-store\r\n"
348 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
349
350 fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>"
351 "<meta name='viewport' content='width=device-width,initial-scale=1'>"
352 "<title>hello</title>", stdout);
353 /* Theme tokens + prepaint come from src/bot_theme_plugin.h (the bot's own
354 * palette), so ?theme= / the bot's postMessage land before first paint. */
355 fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS, stdout);
356 fputs(
357"body{padding:16px;font-size:14px;line-height:1.5}"
358".wrap{max-width:880px;margin:0 auto}"
359".top{display:flex;align-items:center;gap:10px;margin-bottom:16px;flex-wrap:wrap}"
360".title{font-size:20px;font-weight:700;margin:0}"
361".pill{font-size:11px;font-weight:600;padding:2px 8px;border-radius:999px;"
362 "background:var(--surface2);color:var(--muted);border:1px solid var(--line)}"
363".spacer{flex:1}"
364".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;"
365 "padding:16px;margin-bottom:14px}"
366".card h2{margin:0 0 10px;font-size:13px;letter-spacing:.06em;text-transform:uppercase;"
367 "color:var(--muted);font-weight:600}"
368".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px}"
369".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;padding:10px 12px}"
370".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}"
371".kpi .v{font-size:15px;font-weight:600;font-family:var(--mono);word-break:break-all;margin-top:2px}"
372"button{background:var(--accent);color:#fff;border:0;border-radius:999px;"
373 "padding:7px 16px;font-weight:600;font-size:13px;cursor:pointer}"
374"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}"
375"button:active{transform:scale(.98)}"
376"input{flex:1;min-width:0;background:var(--surface2);border:1px solid var(--line);"
377 "border-radius:10px;padding:8px 12px;color:var(--text);font-size:13px;font-family:var(--mono)}"
378"input:focus{outline:2px solid var(--accent);outline-offset:-1px}"
379".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}"
380"pre{background:var(--surface2);border:1px solid var(--line);border-radius:10px;"
381 "padding:12px;overflow:auto;font-family:var(--mono);font-size:12px;margin:10px 0 0;"
382 "max-height:260px;white-space:pre-wrap;word-break:break-word}"
383"code{font-family:var(--mono);background:var(--surface2);border-radius:5px;"
384 "padding:1px 5px;font-size:12px}"
385".ok{color:var(--accent2)}.err{color:var(--danger)}"
386"a{color:var(--accent);text-decoration:none;font-weight:600}"
387"ol{margin:8px 0 0;padding-left:20px}li{margin:4px 0}"
388"@media(max-width:520px){body{padding:10px}.card{padding:12px}}"
389"</style></head><body><div class='wrap'>", stdout);
390
391 if (!embed) {
392 fputs("<div class='top'><a href='/'>\xe2\x86\x90 Back to Bot</a></div>", stdout);
393 }
394
395 fputs("<div class='top'><h1 class='title'>hello</h1>"
396 "<span class='pill'>" PLUGIN_VER "</span>"
397 "<span class='pill' id='badge'>connecting</span>"
398 "<span class='spacer'></span>"
399 "<button class='ghost embed-hide' id='themeBtn' type='button'>Theme</button>"
400 "<button class='ghost' id='reloadBtn' type='button'>Refresh</button></div>", stdout);
401
402 /* ---- live node card ---- */
403 fputs("<div class='card'><h2>Live node info</h2><div class='grid'>"
404 "<div class='kpi'><div class='k'>hostname</div><div class='v' id='v-host'>&mdash;</div></div>"
405 "<div class='kpi'><div class='k'>os / arch</div><div class='v' id='v-os'>&mdash;</div></div>"
406 "<div class='kpi'><div class='k'>libc</div><div class='v' id='v-libc'>&mdash;</div></div>"
407 "<div class='kpi'><div class='k'>pid</div><div class='v' id='v-pid'>&mdash;</div></div>"
408 "<div class='kpi'><div class='k'>utc</div><div class='v' id='v-utc'>&mdash;</div></div>"
409 "</div><pre id='raw'>loading…</pre></div>", stdout);
410
411 /* ---- echo tester ---- */
412 fputs("<div class='card'><h2>Echo action tester</h2>"
413 "<div class='row'><input id='msg' type='text' value='hello from the browser' "
414 "placeholder='type anything'><button id='echoBtn' type='button'>Send echo</button></div>"
415 "<pre id='echoOut'>Run an echo to see the JSON response.</pre></div>", stdout);
416
417 /* ---- guide ---- */
418 fputs("<div class='card'><h2>Make it yours</h2>"
419 "<p style='margin:0;color:var(--muted)'>This is a clean-room reference plugin. "
420 "Fork it, edit one C file, rebuild in one command.</p>"
421 "<ol>"
422 "<li>Clone: <code>git clone https://plugingit.scorpiox.net/scorpiox-bot-plugin-hello.git</code></li>"
423 "<li>Edit <code>src/plugin_hello.c</code> &mdash; change the metadata, add an action, restyle the UI.</li>"
424 "<li>Build: <code>make</code> (or <code>make musl</code>, <code>make win64</code>)</li>"
425 "<li>Install: <code>cp plugin_hello ~/.scorpiox/plugins/</code></li>"
426 "<li>Verify: <code>plugin_hello --meta</code> &mdash; no server restart needed.</li>"
427 "</ol>"
428 "<pre>QUERY_STRING='action=info' ./plugin_hello\n"
429 "QUERY_STRING='action=echo&amp;msg=hi' ./plugin_hello</pre>"
430 "</div>", stdout);
431
432 /* ---- script ---- */
433 fputs(
434"<script>\n"
435"(function(){\n"
436" var q = new URLSearchParams(location.search);\n"
437" var HUB = q.get('plugin') || '';\n"
438" var node = q.get('node') || '';\n"
439" var sid = q.get('id') || '';\n"
440" var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n"
441" localStorage.getItem('bot_active_pwd') || '';\n"
442"\n"
443" function api(action, extra){\n"
444" var u = HUB ? '/plugins?plugin=' + HUB + '&action=' + encodeURIComponent(action)\n"
445" : '/" PLUGIN_ID "?action=' + encodeURIComponent(action);\n"
446" if (extra) u += extra;\n"
447" if (node) u += '&node=' + encodeURIComponent(node);\n"
448" if (sid) u += '&id=' + encodeURIComponent(sid);\n"
449" if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n"
450" return fetch(u, { headers: pwd ? { 'X-Bot-Password': pwd } : {} }).then(function(r){\n"
451" return r.json();\n"
452" });\n"
453" }\n"
454"\n"
455" function $(id){ return document.getElementById(id); }\n"
456" function set(id, v){ var e = $(id); if (e) e.textContent = (v === undefined || v === null || v === '') ? '\\u2014' : v; }\n"
457"\n"
458" function refresh(){\n"
459" api('info').then(function(d){\n"
460" var n = d.node || {};\n"
461" set('v-host', n.hostname);\n"
462" set('v-os', (n.os || '?') + ' / ' + (n.arch || '?'));\n"
463" set('v-libc', n.libc);\n"
464" set('v-pid', n.pid);\n"
465" set('v-utc', n.utc);\n"
466" var b = $('badge');\n"
467" if (b){ b.textContent = 'live'; b.style.color = 'var(--accent2)'; }\n"
468" $('raw').textContent = JSON.stringify(d, null, 2);\n"
469" }).catch(function(e){\n"
470" var b = $('badge');\n"
471" if (b){ b.textContent = 'offline'; b.style.color = 'var(--danger)'; }\n"
472" $('raw').textContent = 'error: ' + e;\n"
473" });\n"
474" }\n"
475"\n"
476" function sendEcho(){\n"
477" var m = $('msg').value;\n"
478" api('echo', '&msg=' + encodeURIComponent(m)).then(function(d){\n"
479" $('echoOut').textContent = JSON.stringify(d, null, 2);\n"
480" }).catch(function(e){\n"
481" $('echoOut').textContent = 'error: ' + e;\n"
482" });\n"
483" }\n"
484"\n"
485" $('reloadBtn').addEventListener('click', refresh);\n"
486" $('echoBtn').addEventListener('click', sendEcho);\n"
487" $('msg').addEventListener('keydown', function(e){ if (e.key === 'Enter') sendEcho(); });\n"
488" refresh();\n"
489"})();\n"
490SX_BOT_THEME_HANDOFF
491"</body></html>\n", stdout);
492
493 return 0;
494}
495
496/* ------------------------------------------------------------------ */
497/* Entry point */
498/* ------------------------------------------------------------------ */
499
500int main(int argc, char **argv)
501{
502 const char *qs;
503 char embedv[16];
504
505 if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META"))
506 return mode_meta();
507
508 if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) {
509 puts(PLUGIN_VER);
510 return 0;
511 }
512
513 require_node_auth();
514
515 qs = getenv("QUERY_STRING");
516 if (!qs) qs = "";
517
518 if (strstr(qs, "action=") || strstr(qs, "format=json"))
519 return mode_json(qs);
520
521 embedv[0] = '\0';
522 if (get_query_val(qs, "embed", embedv, sizeof(embedv)))
523 return mode_html(strcmp(embedv, "1") == 0 || strcmp(embedv, "true") == 0);
524
525 return mode_html(0);
526}