scorpiox-bot-plugin-ntfy
←plugin_ntfy.cc
2004 lines · 80 KBHEADBlameDownload
1/*
2 * plugin_ntfy -- SCORPIOX BOT open-source ntfy push & pub/sub channel connector.
3 *
4 * A single clean-room C99 binary with FIVE modes:
5 *
6 * 1. --meta / SX_PLUGIN_META=1 JSON discovery metadata (unauthenticated,
7 * so /plugins can probe it).
8 * 2. --mcp stdio MCP JSON-RPC 2.0 server exposing the
9 * ntfy_send tool for agents (alerts, reports).
10 * 3. --daemon long-lived channel gateway: subscribes to
11 * <server>/<topic>/json, applies the
12 * default-deny pairing policy, forwards
13 * approved senders' messages to the SCORPIOX
14 * BOT node API (POST /inbox?id=<session>),
15 * and publishes the agent's replies back to
16 * the publish topic over TLS.
17 * 4. ?action=... or ?format=json the node JSON API (status/config/test/
18 * send/pending/approve/deny/start/stop/logs),
19 * everything behind require_node_auth().
20 * 5. GET (default) the Setup & Topic Pairing UI, bot-themed,
21 * embeddable, zero external resources.
22 *
23 * Security posture, in one paragraph: the connector is default-deny. ntfy has
24 * no sender-identity primitive -- anyone who knows a topic can publish to it,
25 * and the optional "user" field is publisher-controlled -- so every inbound
26 * identity (sha256 of user + tags + topic) is held in a pairing queue until
27 * the owner approves it in this UI or the sender types "PAIR <code>" (the
28 * code is delivered out-of-band through the challenge the connector posts on
29 * the reply topic). Nothing reaches /inbox before that. The one exception is
30 * NTFY_ALLOW_ALL=1, an explicitly opt-in dev mode, loudly reported in the UI
31 * and in the status JSON. Own publications are remembered by message id in a
32 * ledger and filtered from the subscription, and replies carry a visible
33 * prefix, so the bridge cannot loop on itself even when subscribe == publish.
34 * TLS fails closed against the bundled root store (src/ca_bundle_pem.h) with
35 * hostname verification; a private-CA relay needs an explicit ca_file or an
36 * explicit SPKI pin, and the only no-verify mode is NTFY_TLS_INSECURE=1 in
37 * the environment -- never a stored value, never an HTTP parameter. The node
38 * password and the ntfy bearer token are write-only: no response ever echoes
39 * them, only "has_bearer"/"has_bot_password" booleans.
40 *
41 * Ported from the protocol semantics of NousResearch/hermes-agent
42 * plugins/platforms/ntfy (server_url/topic/publish_topic/token/markdown/
43 * allowlist) reimplemented here from scratch in pure C99 with the ntfy
44 * publish/subscribe contract verified against the reference server
45 * (documented headers Title/Priority/Tags + X- variants, Authorization,
46 * NDJSON <topic>/json stream with keepalives and poll/since parameters).
47 *
48 * Zero external runtime dependencies. The only vendored code is yyjson and
49 * mbedTLS (see vendor/, LICENSE-yyjson, src/sx_ntfy_mbedtls_config.h).
50 *
51 * MIT License. Copyright (c) 2026 SCORPIOX INC.
52 */
53
54#if defined(_WIN32)
55# ifndef _WIN32_WINNT
56# define _WIN32_WINNT 0x0601
57# endif
58# define WIN32_LEAN_AND_MEAN
59#else
60# if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200809L
61# undef _POSIX_C_SOURCE
62# define _POSIX_C_SOURCE 200809L
63# endif
64# ifndef _DEFAULT_SOURCE
65# define _DEFAULT_SOURCE 1
66# endif
67# if defined(__APPLE__)
68# undef _DARWIN_C_SOURCE
69# define _DARWIN_C_SOURCE 1
70# endif
71#endif
72
73#include <stdio.h>
74#include <stdlib.h>
75#include <string.h>
76#include <ctype.h>
77#include <errno.h>
78#include <time.h>
79#include <signal.h>
80#include <sys/stat.h>
81
82#if defined(_WIN32)
83# include <winsock2.h>
84# include <windows.h>
85# include <io.h> /* _setmode / _fileno on MinGW */
86# include <fcntl.h> /* _O_BINARY (lives here, not in <io.h>) */
87# include <process.h>
88# define sx_sleep_ms(ms) Sleep(ms)
89#else
90# include <unistd.h>
91# include <fcntl.h>
92# define sx_sleep_ms(ms) usleep((ms) * 1000)
93#endif
94
95#include "sx_http.h"
96#include "sx_connectors.h"
97#include "bot_theme_plugin.h"
98#include "ui_html.h"
99#include "yyjson.h"
100
101#define PLUGIN_SLUG "ntfy"
102#define PLUGIN_ID "plugin_ntfy"
103#define PLUGIN_VER "1.0.3"
104#define SELF_SOURCE_ID "scorpiox-bot-plugin-ntfy"
105
106/* The tag every notification THIS plugin publishes carries. A second,
107 * human-visible layer of the anti-self-loop rule: a message with our tag on
108 * the subscribe topic is by construction our own echo. */
109#define SELF_TAG "scorpiox"
110
111/* Cap for one NDJSON record on the subscription. ntfy caps a message body at
112 * 4 KB by default; 256 KB per record absorbs attachments metadata and a
113 * hostile relay while keeping the daemon's footprint bounded. */
114#define SX_NTFY_STREAM_CAP (256 * 1024)
115
116/* ------------------------------------------------------------------ */
117/* Small helpers */
118/* ------------------------------------------------------------------ */
119
120static void trim_inplace(char *s)
121{
122 size_t n;
123 char *p = s;
124 while (*p && isspace((unsigned char)*p)) p++;
125 if (p != s) memmove(s, p, strlen(p) + 1);
126 n = strlen(s);
127 while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0';
128}
129
130/* Explicit truncating copy. The form fields and the inbound message body are
131 * longer than the config slots by design (a 1024-byte form field into a
132 * 256-byte server_url, a 9 KB notification into an 8 KB bridge body): the
133 * truncation IS the intended behaviour, so it is written as a memcpy the
134 * compiler cannot mis-read as an accident. */
135static void cp_trunc(char *dst, size_t capsz, const char *src)
136{
137 size_t n;
138 if (!capsz) return;
139 if (!src) { dst[0] = '\0'; return; }
140 n = strlen(src);
141 if (n > capsz - 1) n = capsz - 1;
142 memcpy(dst, src, n);
143 dst[n] = '\0';
144}
145
146static int ci_eq(const char *a, const char *b)
147{
148 return strcasecmp(a, b) == 0;
149}
150
151static int is_truthy(const char *v)
152{
153 return v && (!strcmp(v, "1") || ci_eq(v, "true") || ci_eq(v, "yes") || ci_eq(v, "on"));
154}
155
156static void url_decode_inplace(char *s)
157{
158 char *o = s;
159 while (*s) {
160 if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
161 int hi = tolower((unsigned char)s[1]);
162 int lo = tolower((unsigned char)s[2]);
163 hi = hi <= '9' ? hi - '0' : hi - 'a' + 10;
164 lo = lo <= '9' ? lo - '0' : lo - 'a' + 10;
165 *o++ = (char)((hi << 4) | lo);
166 s += 3;
167 } else if (*s == '+') { *o++ = ' '; s++; }
168 else *o++ = *s++;
169 }
170 *o = '\0';
171}
172
173static int get_query_val(const char *qs, const char *key, char *out, size_t capsz)
174{
175 size_t klen;
176 if (out && capsz) out[0] = '\0';
177 if (!qs || !key || !out || !capsz) return 0;
178 klen = strlen(key);
179 while (*qs) {
180 if (!strncmp(qs, key, klen) && qs[klen] == '=') {
181 const char *v = qs + klen + 1;
182 const char *e = strchr(v, '&');
183 size_t n = e ? (size_t)(e - v) : strlen(v);
184 if (n >= capsz) n = capsz - 1;
185 memcpy(out, v, n);
186 out[n] = '\0';
187 url_decode_inplace(out);
188 return 1;
189 }
190 qs = strchr(qs, '&');
191 if (!qs) break;
192 qs++;
193 }
194 return 0;
195}
196
197static int is_post_request(void)
198{
199 const char *m = getenv("REQUEST_METHOD");
200 return m && ci_eq(m, "POST");
201}
202
203static char *read_post_body(void)
204{
205 static char *cached = NULL;
206 static int tried = 0;
207 const char *cl;
208 long n;
209 char *buf;
210 size_t rd;
211
212 if (tried) return cached;
213 tried = 1;
214 cl = getenv("CONTENT_LENGTH");
215 n = cl ? atol(cl) : 0;
216 if (n <= 0 || n > 1024 * 1024) return NULL;
217 buf = malloc((size_t)n + 1);
218 if (!buf) return NULL;
219 rd = fread(buf, 1, (size_t)n, stdin);
220 buf[rd] = '\0';
221 cached = buf;
222 return buf;
223}
224
225/* JSON body field reader (POST /plugin_ntfy with Content-Type json), then
226 * falls back to the query string. Booleans/ints normalise to "1"/"0" --
227 * lesson (as): a UI that sends {"force":true} must not silently read empty. */
228static int req_field(const char *qs, yyjson_val *jroot, const char *key,
229 char *out, size_t capsz)
230{
231 if (out && capsz) out[0] = '\0';
232 if (jroot && yyjson_is_obj(jroot)) {
233 yyjson_val *v = yyjson_obj_get(jroot, key);
234 if (yyjson_is_str(v)) { snprintf(out, capsz, "%s", yyjson_get_str(v)); return 1; }
235 if (yyjson_is_bool(v)) { snprintf(out, capsz, "%s", yyjson_get_bool(v) ? "1" : "0"); return 1; }
236 if (yyjson_is_int(v)) { snprintf(out, capsz, "%lld", (long long)yyjson_get_sint(v)); return 1; }
237 if (yyjson_is_uint(v)) { snprintf(out, capsz, "%llu", (unsigned long long)yyjson_get_uint(v)); return 1; }
238 if (v) return 0;
239 }
240 if (qs) return get_query_val(qs, key, out, capsz);
241 return 0;
242}
243
244static void json_respond(int status, const char *json)
245{
246 printf("Status: %d\r\n", status);
247 fputs("Content-Type: application/json; charset=utf-8\r\n"
248 "Cache-Control: no-store\r\n"
249 "X-Content-Type-Options: nosniff\r\n"
250 "\r\n", stdout);
251 fputs(json, stdout);
252 fputc('\n', stdout);
253 fflush(stdout);
254}
255
256static void require_node_auth(void)
257{
258 const char *np = getenv("BOT_PASSWORD");
259 const char *xp, *auth, *qs;
260 char qpwd[256];
261
262 if (!np || !*np) return;
263
264 xp = getenv("HTTP_X_BOT_PASSWORD");
265 if (xp && strcmp(xp, np) == 0) return;
266
267 auth = getenv("HTTP_AUTHORIZATION");
268 if (auth) {
269 while (*auth == ' ') auth++;
270 if (strncmp(auth, "Bearer ", 7) == 0) {
271 auth += 7;
272 while (*auth == ' ') auth++;
273 if (strcmp(auth, np) == 0) return;
274 }
275 }
276
277 qs = getenv("QUERY_STRING");
278 if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0)
279 return;
280
281 json_respond(401, "{\"ok\":false,\"error\":\"invalid node password\"}");
282 exit(0);
283}
284
285/* ------------------------------------------------------------------ */
286/* ntfy publish core (shared by --mcp, the UI, and the daemon) */
287/* ------------------------------------------------------------------ */
288
289/* Publishes one notification. Returns 0 on a 2xx answer; on success, if
290 * id_out is non-NULL it receives the message id from the JSON answer so the
291 * caller can add it to the self-echo ledger. */
292static int ntfy_publish(const sx_ntfy_config *cfg, const char *topic,
293 const char *message, const char *title,
294 int priority, const char *tags,
295 char *id_out, size_t id_capsz,
296 char *err, size_t errsz)
297{
298 sx_url u;
299 sx_conn c;
300 char base[512], path[1024];
301 char hdr[8][1200];
302 const char *hdrs[9];
303 int nh = 0;
304 int status = 0;
305 char *body = NULL;
306 size_t blen = 0;
307 char enc_topic[320];
308
309 if (id_out && id_capsz) id_out[0] = '\0';
310 if (!topic || !*topic) { snprintf(err, errsz, "no topic"); return -1; }
311 {
312 size_t i, n = strlen(topic);
313 if (n == 0 || n > 128) { snprintf(err, errsz, "bad topic length"); return -1; }
314 for (i = 0; i < n; i++) {
315 char ch = topic[i];
316 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
317 (ch >= '0' && ch <= '9') || ch == '_' || ch == '-' || ch == '.')) {
318 snprintf(err, errsz, "topic contains forbidden characters");
319 return -1;
320 }
321 }
322 }
323 sx_url_encode(topic, enc_topic, sizeof enc_topic);
324
325 snprintf(base, sizeof base, "%s", cfg->server_url);
326 { /* trim trailing slash so the join below cannot make a double slash */
327 size_t l = strlen(base);
328 while (l > 0 && base[l - 1] == '/') base[--l] = '\0';
329 }
330 snprintf(path, sizeof path, "/%s", enc_topic);
331
332 /* parse scheme://host[:port] out of the configured server base */
333 if (sx_url_parse(base, &u, err, errsz) != 0) return -1;
334 snprintf(u.path, sizeof u.path, "%s", path);
335
336 sx_conn_init(&c);
337 if (sx_conn_open(&c, &u, NULL, cfg->allowed_pins[0] ? cfg->allowed_pins : NULL,
338 cfg->ca_file[0] ? cfg->ca_file : NULL,
339 sx_ntfy_tls_insecure(), 15000, err, errsz) != 0)
340 return -1;
341
342 /* Header assembly. One Tags header, comma-separated: ntfy accepts a
343 * comma list, and repeating the header is server-version dependent, so
344 * our own identification tag is folded into the same list. A value that
345 * carries a control character never reaches the wire -- sx_http refuses
346 * the whole request (header injection guard). */
347 nh = 0;
348 hdrs[nh] = NULL;
349#define SX_ADDH(str) do { if (nh < 7 && (str)[0]) { snprintf(hdr[nh], sizeof hdr[0], "%s", (str)); hdrs[nh] = hdr[nh]; hdrs[++nh] = NULL; } } while (0)
350 if (title && *title) {
351 char t[260];
352 snprintf(t, sizeof t, "Title: %s", title);
353 SX_ADDH(t);
354 }
355 {
356 char tagline[340];
357 if (tags && *tags) {
358 char clean[220];
359 size_t j = 0;
360 const char *t = tags;
361 for (; *t && j + 1 < sizeof clean; t++)
362 if ((unsigned char)*t >= 0x20 && *t != '\r' && *t != '\n') clean[j++] = *t;
363 clean[j] = '\0';
364 snprintf(tagline, sizeof tagline, "Tags: %s," SELF_TAG, clean);
365 } else {
366 snprintf(tagline, sizeof tagline, "Tags: " SELF_TAG);
367 }
368 SX_ADDH(tagline);
369 }
370 if (priority >= 1 && priority <= 5) {
371 char p[32];
372 snprintf(p, sizeof p, "Priority: %d", priority);
373 SX_ADDH(p);
374 }
375 if (cfg->markdown) SX_ADDH("X-Markdown: true");
376 if (cfg->bearer_token[0]) {
377 char a[300];
378 snprintf(a, sizeof a, "Authorization: %s", cfg->bearer_token);
379 SX_ADDH(a);
380 }
381 SX_ADDH("X-Source-Id: " SELF_SOURCE_ID);
382#undef SX_ADDH
383 hdrs[nh] = NULL;
384
385 if (sx_http_request(&c, "POST", path, hdrs, message, message ? strlen(message) : 0,
386 &status, &body, &blen, err, errsz) != 0) {
387 sx_conn_close(&c);
388 return -1;
389 }
390 sx_conn_close(&c);
391
392 if (status < 200 || status >= 300) {
393 char safe[200];
394 if (body) {
395 snprintf(safe, sizeof safe, "%s", body);
396 /* ntfy error bodies are small JSON; anything bigger got truncated */
397 {
398 size_t l = strlen(safe);
399 while (l > 0 && (safe[l-1] == '\n' || safe[l-1] == '\r')) safe[--l] = '\0';
400 }
401 } else safe[0] = '\0';
402 snprintf(err, errsz, "ntfy server answered %d%s%s", status,
403 safe[0] ? ": " : "", safe);
404 free(body);
405 return -1;
406 }
407 if (body && id_out && id_capsz) {
408 yyjson_doc *d = yyjson_read(body, blen, 0);
409 if (d) {
410 yyjson_val *v = yyjson_obj_get(yyjson_doc_get_root(d), "id");
411 if (yyjson_is_str(v)) snprintf(id_out, id_capsz, "%s", yyjson_get_str(v));
412 yyjson_doc_free(d);
413 }
414 }
415 free(body);
416 return 0;
417}
418
419/* ------------------------------------------------------------------ */
420/* mode 1: --meta */
421/* ------------------------------------------------------------------ */
422
423static int mode_meta(void)
424{
425 /* one compact line: the convention every plugin keeps (the node reads
426 * this with yyjson, but scripts grep the raw line) */
427 puts("{\"name\":\"ntfy\",\"desc\":\"Push channel\",\"version\":\"" PLUGIN_VER "\","
428 "\"slug\":\"" PLUGIN_SLUG "\",\"id\":\"" PLUGIN_ID "\",\"kind\":\"hybrid\","
429 "\"mcp\":true,\"daemon\":true,\"menus\":false,\"verified\":\"mock\","
430 "\"category\":\"network\","
431 "\"capabilities\":[\"https_outbound_ntfy_publish\","
432 "\"https_outbound_ntfy_subscribe_stream\",\"loopback_node_inbox_bridge\","
433 "\"pairing_allowlist_state_0600\",\"bundled_root_store_tls_verification\","
434 "\"stdio_mcp_jsonrpc_server\"],"
435 "\"tools\":[\"ntfy_send\"]}");
436 fflush(stdout);
437 return 0;
438}
439
440
441/* ------------------------------------------------------------------ */
442/* mode 2: --mcp (stdio JSON-RPC 2.0) */
443/* ------------------------------------------------------------------ */
444
445#define MCP_PROTOCOL "2024-11-05"
446
447static void mcp_send_raw(const char *json)
448{
449 fputs(json, stdout);
450 fputc('\n', stdout);
451 fflush(stdout);
452}
453
454static void mcp_error(long long id, int code, const char *msg)
455{
456 char esc[512];
457 sx_ntfy_json_escape(msg ? msg : "error", esc, sizeof esc);
458 {
459 char buf[700];
460 snprintf(buf, sizeof buf,
461 "{\"jsonrpc\":\"2.0\",\"id\":%lld,\"error\":{\"code\":%d,\"message\":\"%s\"}}",
462 id, code, esc);
463 mcp_send_raw(buf);
464 }
465}
466
467static void mcp_tool_result(long long id, const char *text, int is_error)
468{
469 /* 6x headroom: the worst case of the JSON escape is \u00XX (6 bytes per
470 * input byte). Truncation is safe (the escape function caps itself), but
471 * sizing this honestly is what keeps an alert body intact. */
472 static char esc[96000];
473 static char buf[97200];
474 sx_ntfy_json_escape(text, esc, sizeof esc);
475 snprintf(buf, sizeof buf,
476 "{\"jsonrpc\":\"2.0\",\"id\":%lld,\"result\":{\"content\":[{\"type\":\"text\",\"text\":\"%s\"}],\"isError\":%s}}",
477 id, esc, is_error ? "true" : "false");
478 mcp_send_raw(buf);
479}
480
481static const char *MCP_TOOLS_JSON =
482"{\"tools\":[{"
483"\"name\":\"ntfy_send\","
484"\"description\":\"Send an ntfy push notification from the agent: alerts, report summaries, 'task finished' pings. Posts to the configured ntfy server (default https://ntfy.sh) and the configured topic. Returns the published message id.\","
485"\"inputSchema\":{"
486" \"type\":\"object\","
487" \"properties\":{"
488" \"message\":{\"type\":\"string\",\"description\":\"Notification body (required).\"},"
489" \"title\":{\"type\":\"string\",\"description\":\"Optional notification title.\"},"
490" \"priority\":{\"type\":\"integer\",\"description\":\"ntfy priority 1..5 (min low .. max urgent). Default 3.\",\"minimum\":1,\"maximum\":5},"
491" \"tags\":{\"type\":\"string\",\"description\":\"Optional comma-separated emoji tag names, e.g. 'warning,bell'.\"},"
492" \"topic\":{\"type\":\"string\",\"description\":\"Optional override topic (defaults to the configured publish topic).\"}"
493" },"
494" \"required\":[\"message\"]"
495"}}]}";
496
497static int mode_mcp(void)
498{
499 char line[65536];
500 sx_ntfy_config cfg;
501 char cerr[256];
502
503 if (sx_ntfy_config_load(&cfg, cerr, sizeof cerr) != 0) {
504 fprintf(stderr, "plugin_ntfy --mcp: config problem: %s\n", cerr);
505 }
506
507#if defined(_WIN32)
508 _setmode(_fileno(stdin), _O_BINARY);
509 _setmode(_fileno(stdout), _O_BINARY);
510#endif
511
512 /* Line-delimited JSON-RPC (one message per line), the stdio MCP framing
513 * scorpiox-mcp and sx-connector-mcp speak (both use Content-Length OR
514 * newline framing; newline is the safe subset -- scorpiox-connector-mcp
515 * reads responses as lines). */
516 while (fgets(line, sizeof line, stdin)) {
517 yyjson_doc *doc;
518 yyjson_val *root, *v;
519 long long id = 0;
520 int has_id = 0;
521 const char *method;
522
523 trim_inplace(line);
524 if (!line[0]) continue;
525 doc = yyjson_read(line, strlen(line), 0);
526 if (!doc) continue;
527 root = yyjson_doc_get_root(doc);
528 v = yyjson_obj_get(root, "id");
529 if (v) {
530 if (yyjson_is_int(v)) { id = yyjson_get_sint(v); has_id = 1; }
531 else if (yyjson_is_uint(v)) { id = (long long)yyjson_get_uint(v); has_id = 1; }
532 }
533 v = yyjson_obj_get(root, "method");
534 method = yyjson_is_str(v) ? yyjson_get_str(v) : "";
535
536 if (!strcmp(method, "initialize")) {
537 if (has_id) {
538 char buf[512];
539 snprintf(buf, sizeof buf,
540 "{\"jsonrpc\":\"2.0\",\"id\":%lld,\"result\":{\"protocolVersion\":\"%s\","
541 "\"capabilities\":{\"tools\":{}},\"serverInfo\":{\"name\":\"plugin_ntfy\",\"version\":\"%s\"},"
542 "\"instructions\":\"ntfy push + channel connector for SCORPIOX BOT. Use ntfy_send to deliver notifications.\"}}",
543 id, MCP_PROTOCOL, PLUGIN_VER);
544 mcp_send_raw(buf);
545 }
546 } else if (!strcmp(method, "notifications/initialized") ||
547 !strncmp(method, "notifications/", 14)) {
548 /* notification: no response */
549 } else if (!strcmp(method, "ping")) {
550 if (has_id) { char b[64]; snprintf(b, sizeof b, "{\"jsonrpc\":\"2.0\",\"id\":%lld,\"result\":{}}", id); mcp_send_raw(b); }
551 } else if (!strcmp(method, "tools/list")) {
552 if (has_id) {
553 /* +64 for the id digits and the closing brace. The closing
554 * brace of the *outer* object is ours to emit: MCP_TOOLS_JSON
555 * is the value of "result", so without it the frame is one
556 * brace short. yyjson then rejects the line, the router
557 * (scorpiox-connector-mcp proc_request) skips it as "noise on
558 * stdout", reads again, hits EOF and reports
559 * "tools/list failed for ntfy: no response" -- the tool would
560 * be invisible to every agent. A substring grep in the suite
561 * passed on the broken frame; the assertion that catches this
562 * now parses every emitted frame. */
563 char *buf = malloc(strlen(MCP_TOOLS_JSON) + 64);
564 if (buf) {
565 sprintf(buf, "{\"jsonrpc\":\"2.0\",\"id\":%lld,\"result\":%s}",
566 id, MCP_TOOLS_JSON);
567 mcp_send_raw(buf);
568 free(buf);
569 }
570 }
571 } else if (!strcmp(method, "tools/call")) {
572 yyjson_val *params = yyjson_obj_get(root, "params");
573 yyjson_val *nv = params ? yyjson_obj_get(params, "name") : NULL;
574 const char *tool = yyjson_is_str(nv) ? yyjson_get_str(nv) : "";
575 yyjson_val *args = params ? yyjson_obj_get(params, "arguments") : NULL;
576 if (!tool || strcmp(tool, "ntfy_send") != 0) {
577 if (has_id) mcp_error(id, -32602, "unknown tool");
578 } else {
579 const char *message = NULL;
580 char title[200] = "", tags[200] = "", topic[160] = "";
581 int prio = cfg.priority;
582 char idout[64] = "", err[512] = "";
583 char out[1200];
584
585 if (args && yyjson_is_obj(args)) {
586 yyjson_val *m = yyjson_obj_get(args, "message");
587 yyjson_val *t = yyjson_obj_get(args, "title");
588 yyjson_val *p = yyjson_obj_get(args, "priority");
589 yyjson_val *g = yyjson_obj_get(args, "tags");
590 yyjson_val *o = yyjson_obj_get(args, "topic");
591 message = yyjson_is_str(m) ? yyjson_get_str(m) : NULL;
592 if (yyjson_is_str(t)) snprintf(title, sizeof title, "%s", yyjson_get_str(t));
593 if (yyjson_is_str(g)) snprintf(tags, sizeof tags, "%s", yyjson_get_str(g));
594 if (yyjson_is_str(o)) snprintf(topic, sizeof topic, "%s", yyjson_get_str(o));
595 if (yyjson_is_int(p)) { int x = (int)yyjson_get_int(p); if (x >= 1 && x <= 5) prio = x; }
596 }
597 if (!message || !*message) {
598 if (has_id) mcp_error(id, -32602, "ntfy_send requires a non-empty 'message'");
599 } else {
600 const char *use_topic = topic[0] ? topic
601 : (cfg.publish_topic[0] ? cfg.publish_topic : cfg.topic);
602 if (!use_topic[0]) {
603 if (has_id) mcp_error(id, -32603, "no topic configured: open the ntfy plugin UI or set NTFY_TOPIC");
604 } else if (ntfy_publish(&cfg, use_topic, message, title, prio, tags,
605 idout, sizeof idout, err, sizeof err) != 0) {
606 snprintf(out, sizeof out, "ntfy_send failed: %s", err);
607 if (has_id) mcp_tool_result(id, out, 1);
608 } else {
609 if (idout[0]) sx_ntfy_sent_note(idout);
610 snprintf(out, sizeof out, "published to %s (id %s, priority %d)",
611 use_topic, idout[0] ? idout : "?", prio);
612 if (has_id) mcp_tool_result(id, out, 0);
613 }
614 }
615 }
616 } else {
617 if (has_id) mcp_error(id, -32601, "method not found");
618 }
619 yyjson_doc_free(doc);
620 }
621 return 0;
622}
623
624static int mode_schema(void)
625{
626 fputs(MCP_TOOLS_JSON, stdout);
627 fputc('\n', stdout);
628 fflush(stdout);
629 return 0;
630}
631
632/* ------------------------------------------------------------------ */
633/* identity + pairing (shared by daemon and UI) */
634/* ------------------------------------------------------------------ */
635
636/*
637 * ntfy has no sender identity: the optional "user" field is the publisher's
638 * own claim (it is only populated by a server that authenticates the
639 * publisher, which plain topics do not), and tags are free text. The
640 * connector therefore derives a stable, opaque identity from everything the
641 * publisher controls and treats it as a NAME TO APPROVE, never as an
642 * authentication result.
643 */
644static void identity_of(const char *topic, const char *user, const char *tags,
645 char out[SX_NTFY_IDENTITY_LEN + 1])
646{
647 char material[512];
648 char joined[256] = "";
649 size_t o = 0;
650 if (tags && *tags) {
651 const char *t = tags;
652 for (; *t && o + 1 < sizeof joined; t++)
653 if ((unsigned char)*t >= 0x20) joined[o++] = (char)tolower((unsigned char)*t);
654 joined[o] = '\0';
655 }
656 snprintf(material, sizeof material, "v1|%s|%s|%s",
657 topic ? topic : "", user ? user : "", joined);
658 sx_sha256_hex(material, strlen(material), out);
659}
660
661static void identity_label(const char *user, const char *tags, const char *topic,
662 char out[160])
663{
664 if (user && *user) {
665 snprintf(out, 160, "user=%s tags=%s topic=%s", user, tags ? tags : "-", topic ? topic : "-");
666 } else if (tags && *tags) {
667 snprintf(out, 160, "tags=%s topic=%s", tags, topic ? topic : "-");
668 } else {
669 snprintf(out, 160, "topic=%s (anonymous)", topic ? topic : "-");
670 }
671}
672
673static const char *g_challenge_prefix = "SCORPIOX BOT pairing";
674
675/* Posts the pairing challenge onto the REPLY topic. Rate limited: one
676 * challenge per identity per 10 minutes so a spammer cannot make us publish
677 * unbounded notifications. */
678static void send_challenge(sx_ntfy_config *cfg, const char *topic,
679 const char *code, int retry_after_min)
680{
681 char msg[420], title[80], err[256];
682 char idout[64];
683 snprintf(title, sizeof title, "%s: pairing required", g_challenge_prefix);
684 snprintf(msg, sizeof msg,
685 "This topic is not paired with this SCORPIOX BOT node yet. "
686 "To pair it, open the ntfy plugin UI on this node and approve the request, "
687 "or reply on this same topic with exactly: PAIR %s",
688 code);
689 if (retry_after_min > 0) {
690 char extra[120];
691 snprintf(extra, sizeof extra,
692 " (this challenge repeats at most once every %d minutes)",
693 retry_after_min);
694 strncat(msg, extra, sizeof msg - strlen(msg) - 1);
695 }
696 if (ntfy_publish(cfg, cfg->publish_topic[0] ? cfg->publish_topic : topic,
697 msg, title, 3, "lock", idout, sizeof idout,
698 err, sizeof err) != 0)
699 sx_ntfy_logf("challenge publish failed: %s", err);
700 else if (idout[0])
701 sx_ntfy_sent_note(idout);
702}
703
704/* Recognises "PAIR <code>" (allowing polite whitespace / a trailing period)
705 * on the subscribe topic. Returns 1 when the text is a pairing submission. */
706static int parse_pair_command(const char *text, char *code_out, size_t capsz)
707{
708 const char *p = text;
709 size_t i = 0;
710 while (*p && isspace((unsigned char)*p)) p++;
711 if (strncasecmp(p, "PAIR", 4) != 0) return 0;
712 p += 4;
713 if (!isspace((unsigned char)*p)) return 0;
714 while (*p && isspace((unsigned char)*p)) p++;
715 while (*p && i + 1 < capsz && !isspace((unsigned char)*p)) {
716 if (!isalnum((unsigned char)*p)) return 0;
717 code_out[i++] = (char)toupper((unsigned char)*p++);
718 }
719 while (*p && isspace((unsigned char)*p)) p++;
720 if (*p == '.') p++;
721 if (*p != '\0') return 0;
722 code_out[i] = '\0';
723 return i >= 4 && i <= 16;
724}
725
726/* ------------------------------------------------------------------ */
727/* mode 3: --daemon (channel gateway) */
728/* ------------------------------------------------------------------ */
729
730#if !defined(_WIN32)
731static volatile sig_atomic_t g_stop = 0;
732static void on_stop_sig(int sig) { (void)sig; g_stop = 1; }
733#define STOP_REQUESTED() (g_stop != 0)
734/* A sleep that wakes early when a signal arrived: a daemon asked to stop
735 * must stop in well under a second, not after its poll interval. */
736static void stop_sleep(long long ms)
737{
738 long long until = sx_now_ms() + ms;
739 while (!STOP_REQUESTED() && sx_now_ms() < until) {
740 struct timespec ts;
741 long left = (long)(until - sx_now_ms());
742 if (left <= 0) break;
743 if (left > 100) left = 100;
744 ts.tv_sec = left / 1000;
745 ts.tv_nsec = (left % 1000) * 1000000L;
746 nanosleep(&ts, NULL);
747 }
748}
749#else
750static volatile LONG g_stop_win = 0;
751static BOOL WINAPI win_console_ctrl(DWORD type)
752{
753 (void)type;
754 InterlockedExchange(&g_stop_win, 1);
755 return TRUE;
756}
757#define STOP_REQUESTED() (InterlockedCompareExchange(&g_stop_win, 0, 0) != 0)
758static void stop_sleep(long long ms)
759{
760 long long until = sx_now_ms() + ms;
761 while (!STOP_REQUESTED() && sx_now_ms() < until)
762 Sleep(50);
763}
764#endif
765
766/* POSTs one inbound message to the node API. Returns 0 on success. */
767static int bot_post_inbox(const sx_ntfy_config *cfg, const char *text,
768 char *err, size_t errsz)
769{
770 sx_url u;
771 sx_conn c;
772 char path[1200], body[16600], hdrs2[360];
773 const char *hdrs[3];
774 int status = 0;
775 char *rbody = NULL;
776 size_t rlen = 0;
777 char enc_session[560];
778 yyjson_mut_doc *doc;
779 yyjson_mut_val *root;
780 char *txt;
781 size_t sz;
782
783 if (sx_url_parse(cfg->bot_api_url, &u, err, errsz) != 0) return -1;
784 if (!u.tls && strcmp(u.host, "127.0.0.1") && strcmp(u.host, "localhost")) {
785 snprintf(err, errsz, "refusing to send the node password to a non-loopback host");
786 return -1;
787 }
788 sx_url_encode(cfg->target_session, enc_session, sizeof enc_session);
789 snprintf(path, sizeof path, "/inbox?id=%s&mode=queue", enc_session);
790
791 doc = yyjson_mut_doc_new(NULL);
792 root = yyjson_mut_obj(doc);
793 yyjson_mut_doc_set_root(doc, root);
794 yyjson_mut_obj_add_strcpy(doc, root, "text", text);
795 yyjson_mut_obj_add_strcpy(doc, root, "mode", "queue");
796 txt = yyjson_mut_write(doc, 0, &sz);
797 yyjson_mut_doc_free(doc);
798 if (!txt) { snprintf(err, errsz, "cannot serialise inbox payload"); return -1; }
799 if (sz >= sizeof body) { free(txt); snprintf(err, errsz, "message too large for the inbox bridge"); return -1; }
800 memcpy(body, txt, sz);
801 body[sz] = '\0';
802 free(txt);
803
804 sx_conn_init(&c);
805 if (sx_conn_open(&c, &u, NULL, NULL, NULL, 0, 5000, err, errsz) != 0)
806 return -1;
807 hdrs[0] = "Content-Type: application/json";
808 if (cfg->bot_password[0]) {
809 snprintf(hdrs2, sizeof hdrs2, "X-Bot-Password: %s", cfg->bot_password);
810 hdrs[1] = hdrs2;
811 hdrs[2] = NULL;
812 } else {
813 hdrs[1] = NULL;
814 }
815 if (sx_http_request(&c, "POST", path, hdrs, body, strlen(body),
816 &status, &rbody, &rlen, err, errsz) != 0) {
817 sx_conn_close(&c);
818 return -1;
819 }
820 sx_conn_close(&c);
821 if (status < 200 || status >= 300) {
822 snprintf(err, errsz, "node /inbox answered %d%s%s", status,
823 (rbody && rbody[0]) ? ": " : "", (rbody && rbody[0]) ? rbody : "");
824 free(rbody);
825 return -1;
826 }
827 free(rbody);
828 (void)u;
829 return 0;
830}
831
832/*
833 * Polls GET /conversation?id=<s>&after=<cursor> and returns the newest
834 * assistant message after the cursor. Cursor polling (not SSE) is the
835 * outbound mechanism on purpose: /hashes_sse is a live stream with no
836 * catch-up, so a daemon that restarts mid-turn would miss the reply forever;
837 * the events-backed conversation endpoint always answers from the persisted
838 * sequence, and the cursor lives in status.json across restarts.
839 */
840static void poll_assistant(const sx_ntfy_config *cfg, long long *cursor,
841 char *reply, size_t capsz, long long *ts_out)
842{
843 sx_url u;
844 sx_conn c;
845 char path[1200], hdrs2[360];
846 const char *hdrs[3];
847 int status = 0;
848 char *body = NULL;
849 size_t blen = 0;
850 char err[256] = "";
851 char enc_session[560];
852 yyjson_doc *doc;
853 yyjson_val *root, *msgs;
854
855 reply[0] = '\0';
856 if (ts_out) *ts_out = 0;
857 if (sx_url_parse(cfg->bot_api_url, &u, err, sizeof err) != 0) return;
858 if (!u.tls && strcmp(u.host, "127.0.0.1") && strcmp(u.host, "localhost"))
859 return;
860 sx_url_encode(cfg->target_session, enc_session, sizeof enc_session);
861 snprintf(path, sizeof path, "/conversation?id=%s&after=%lld&limit=100",
862 enc_session, *cursor);
863
864 sx_conn_init(&c);
865 if (sx_conn_open(&c, &u, NULL, NULL, NULL, 0, 5000, err, sizeof err) != 0) {
866 sx_conn_close(&c);
867 return;
868 }
869 hdrs[0] = "Accept: application/json";
870 if (cfg->bot_password[0]) {
871 snprintf(hdrs2, sizeof hdrs2, "X-Bot-Password: %s", cfg->bot_password);
872 hdrs[1] = hdrs2;
873 hdrs[2] = NULL;
874 } else hdrs[1] = NULL;
875
876 if (sx_http_request(&c, "GET", path, hdrs, NULL, 0, &status, &body, &blen,
877 err, sizeof err) != 0) {
878 sx_conn_close(&c);
879 return;
880 }
881 sx_conn_close(&c);
882 if (status != 200 || !body) { free(body); return; }
883
884 doc = yyjson_read(body, blen, 0);
885 free(body);
886 if (!doc) return;
887 root = yyjson_doc_get_root(doc);
888 msgs = yyjson_obj_get(root, "messages");
889 if (yyjson_is_arr(msgs)) {
890 size_t i, max;
891 yyjson_val *m;
892 long long start_index = 0;
893 yyjson_val *si = yyjson_obj_get(root, "start_index");
894 if (yyjson_is_int(si)) start_index = yyjson_get_sint(si);
895 else if (yyjson_is_uint(si)) start_index = (long long)yyjson_get_uint(si);
896
897 /* Walk the messages; the seq of message k is start_index + k + 1
898 * (the endpoint emits after+1 .. end). Keep the LAST assistant one. */
899 i = 0;
900 yyjson_arr_foreach(msgs, i, max, m) {
901 long long seq = start_index + (long long)i + 1;
902 yyjson_val *rv = yyjson_obj_get(m, "role");
903 yyjson_val *cv = yyjson_obj_get(m, "content");
904 yyjson_val *tv = yyjson_obj_get(m, "timestamp_ms");
905 const char *role = yyjson_is_str(rv) ? yyjson_get_str(rv) : "";
906 const char *content = yyjson_is_str(cv) ? yyjson_get_str(cv) : "";
907 int assistant_like = role && *role &&
908 strcmp(role, "user") != 0 && strcmp(role, "tool_use") != 0 &&
909 strcmp(role, "tool_result") != 0 && strcmp(role, "thinking") != 0 &&
910 strcmp(role, "info") != 0 && strcmp(role, "unknown") != 0;
911 if (seq > *cursor) *cursor = seq;
912 if (!assistant_like || !content[0]) continue;
913 snprintf(reply, capsz, "%s", content);
914 if (ts_out && yyjson_is_int(tv)) *ts_out = yyjson_get_sint(tv);
915 }
916 }
917 yyjson_doc_free(doc);
918}
919
920/* one record from the NDJSON stream */
921typedef struct {
922 char id[48];
923 char event[24];
924 char topic[160];
925 char title[200];
926 char message[8000];
927 char user[120];
928 char tags[200];
929 long long time_sec;
930 int priority;
931} ntfy_event;
932
933static int parse_event_line(const char *line, ntfy_event *ev)
934{
935 yyjson_doc *doc;
936 yyjson_val *root, *v;
937
938 memset(ev, 0, sizeof *ev);
939 while (*line && isspace((unsigned char)*line)) line++;
940 if (*line != '{') return 0; /* keepalive / comment */
941 doc = yyjson_read(line, strlen(line), 0);
942 if (!doc) return 0;
943 root = yyjson_doc_get_root(doc);
944 if (!yyjson_is_obj(root)) { yyjson_doc_free(doc); return 0; }
945
946#define EVSTR(field, key) do { v = yyjson_obj_get(root, key); \
947 if (yyjson_is_str(v)) snprintf(ev->field, sizeof ev->field, "%s", yyjson_get_str(v)); } while (0)
948 EVSTR(id, "id");
949 EVSTR(event, "event");
950 EVSTR(topic, "topic");
951 EVSTR(title, "title");
952 EVSTR(message, "message");
953 EVSTR(user, "user");
954 v = yyjson_obj_get(root, "tags");
955 if (yyjson_is_arr(v)) {
956 /* join tags with commas -- they participate in the identity */
957 size_t i, max;
958 yyjson_val *t;
959 size_t o = 0;
960 ev->tags[0] = '\0';
961 yyjson_arr_foreach(v, i, max, t) {
962 const char *s = yyjson_is_str(t) ? yyjson_get_str(t) : NULL;
963 if (!s) continue;
964 if (o) { if (o + 1 < sizeof ev->tags) ev->tags[o++] = ','; }
965 while (*s && o + 1 < sizeof ev->tags) ev->tags[o++] = *s++;
966 ev->tags[o] = '\0';
967 }
968 } else if (yyjson_is_str(v)) {
969 snprintf(ev->tags, sizeof ev->tags, "%s", yyjson_get_str(v));
970 }
971#undef EVSTR
972 v = yyjson_obj_get(root, "time");
973 if (yyjson_is_int(v)) ev->time_sec = yyjson_get_sint(v);
974 else if (yyjson_is_uint(v)) ev->time_sec = (long long)yyjson_get_uint(v);
975 v = yyjson_obj_get(root, "priority");
976 if (yyjson_is_int(v)) ev->priority = (int)yyjson_get_int(v);
977 yyjson_doc_free(doc);
978 return ev->event[0] ? 1 : 0;
979}
980
981static int event_is_own(const ntfy_event *ev, const sx_ntfy_config *cfg)
982{
983 /* 1. we published it (id ledger), 2. it carries our tag, 3. it is our
984 * visible reply prefix. Any one is enough -- all three together also make
985 * a hand-written imitation of our own replies stop the loop instead of
986 * starting one. */
987 if (ev->id[0] && sx_ntfy_sent_has(ev->id)) return 1;
988 if (strstr(ev->tags, SELF_TAG)) return 1;
989 if (cfg->reply_prefix[0] && !strncmp(ev->message, cfg->reply_prefix,
990 strlen(cfg->reply_prefix))) return 1;
991 return 0;
992}
993
994static int run_daemon(void)
995{
996 sx_ntfy_config cfg;
997 sx_ntfy_status st;
998 char cerr[256];
999 long long backoff;
1000 int first = 1;
1001
1002 if (sx_ntfy_config_load(&cfg, cerr, sizeof cerr) != 0) {
1003 fprintf(stderr, "plugin_ntfy --daemon: %s\n", cerr);
1004 return 2;
1005 }
1006 {
1007 char verr[256];
1008 if (sx_ntfy_config_validate(&cfg, verr, sizeof verr) != 0) {
1009 fprintf(stderr, "plugin_ntfy --daemon: %s\n", verr);
1010 return 2;
1011 }
1012 }
1013 if (sx_ntfy_daemon_running()) {
1014 fprintf(stderr, "plugin_ntfy --daemon: another daemon is already running (daemon.pid)\n");
1015 return 3;
1016 }
1017 sx_ntfy_log_open(1);
1018 sx_ntfy_pidfile_write(
1019#if defined(_WIN32)
1020 (long)_getpid()
1021#else
1022 (long)getpid()
1023#endif
1024 );
1025
1026#if !defined(_WIN32)
1027 {
1028 struct sigaction sa;
1029 memset(&sa, 0, sizeof sa);
1030 sa.sa_handler = on_stop_sig;
1031 sigaction(SIGTERM, &sa, NULL);
1032 sigaction(SIGINT, &sa, NULL);
1033 signal(SIGPIPE, SIG_IGN);
1034 }
1035#else
1036 SetConsoleCtrlHandler(win_console_ctrl, TRUE);
1037#endif
1038
1039 sx_ntfy_status_load(&st);
1040 st.started_at = sx_ntfy_now_epoch();
1041 st.configured = 1;
1042 snprintf(st.topic, sizeof st.topic, "%s", cfg.topic);
1043 snprintf(st.publish_topic, sizeof st.publish_topic, "%s", cfg.publish_topic);
1044 snprintf(st.target_session, sizeof st.target_session, "%s", cfg.target_session);
1045 snprintf(st.server_url, sizeof st.server_url, "%s", cfg.server_url);
1046 st.allow_all = cfg.allow_all;
1047 st.pairing_code_enabled = cfg.pairing_code_enabled;
1048 st.markdown = cfg.markdown;
1049 st.has_bearer = cfg.bearer_token[0] ? 1 : 0;
1050 st.has_bot_password = cfg.bot_password[0] ? 1 : 0;
1051 st.tls_insecure = sx_ntfy_tls_insecure();
1052 st.pinned = cfg.allowed_pins[0] ? 1 : 0;
1053 if (st.conv_cursor <= 0) {
1054 /*
1055 * First run. Seed the reply cursor at the CURRENT tip of the
1056 * conversation and throw the answer away, so a daemon started this
1057 * afternoon cannot publish a reply the agent wrote this morning.
1058 * (poll_assistant writes into `discard`, which is 1 byte, so nothing
1059 * survives; only the cursor moves.)
1060 */
1061 char discard[1];
1062 long long tip = -1;
1063 poll_assistant(&cfg, &tip, discard, sizeof discard, NULL);
1064 st.conv_cursor = tip > 0 ? tip : 0;
1065 st.last_message_time = sx_ntfy_now_epoch();
1066 sx_ntfy_logf("reply cursor seeded at %lld", st.conv_cursor);
1067 }
1068 sx_ntfy_status_save(&st);
1069
1070 if (st.tls_insecure)
1071 sx_ntfy_logf("WARNING NTFY_TLS_INSECURE=1 is set: certificate verification is DISABLED");
1072 sx_ntfy_logf("daemon start topic=%s publish=%s session=%s server=%s allow_all=%d cursor=%lld",
1073 cfg.topic, cfg.publish_topic, cfg.target_session, cfg.server_url,
1074 cfg.allow_all, st.conv_cursor);
1075
1076 backoff = cfg.reconnect_min_ms;
1077 while (!STOP_REQUESTED()) {
1078 sx_url u;
1079 sx_conn c;
1080 char path[600];
1081 const char *hdrs[3];
1082 int status = 0;
1083 char err[512] = "";
1084 /* static, not stack: this is the one big buffer in the process and a
1085 * daemon must not careen into a guard page because of it */
1086 static char line[SX_NTFY_STREAM_CAP + 1];
1087 long long since = st.last_message_time > 0 ? st.last_message_time : 0;
1088
1089 sx_conn_init(&c);
1090 if (sx_url_parse(cfg.server_url, &u, err, sizeof err) != 0) {
1091 sx_ntfy_logf("bad server_url: %s", err);
1092 stop_sleep(cfg.reconnect_max_ms);
1093 continue;
1094 }
1095 {
1096 char enc[320];
1097 sx_url_encode(cfg.topic, enc, sizeof enc);
1098 if (since > 0)
1099 snprintf(path, sizeof path, "/%s/json?since=%lld", enc, since);
1100 else
1101 snprintf(path, sizeof path, "/%s/json", enc);
1102 }
1103 if (sx_conn_open(&c, &u, NULL,
1104 cfg.allowed_pins[0] ? cfg.allowed_pins : NULL,
1105 cfg.ca_file[0] ? cfg.ca_file : NULL,
1106 sx_ntfy_tls_insecure(), 15000, err, sizeof err) != 0) {
1107 sx_ntfy_logf("subscribe connect failed: %s (retry in %lldms)", err, backoff);
1108 st.error_count++;
1109 snprintf(st.last_error, sizeof st.last_error, "%s", err);
1110 sx_ntfy_status_save(&st);
1111 sx_conn_close(&c);
1112 stop_sleep(backoff);
1113 backoff = backoff * 2 < cfg.reconnect_max_ms ? backoff * 2 : cfg.reconnect_max_ms;
1114 continue;
1115 }
1116 hdrs[0] = "Accept: application/x-ndjson";
1117 hdrs[1] = NULL;
1118 if (sx_http_open_stream(&c, "GET", path, hdrs, &status, err, sizeof err) != 0) {
1119 sx_ntfy_logf("subscribe request failed: %s (retry in %lldms)", err, backoff);
1120 st.error_count++;
1121 snprintf(st.last_error, sizeof st.last_error, "%s", err);
1122 sx_ntfy_status_save(&st);
1123 sx_conn_close(&c);
1124 stop_sleep(backoff);
1125 backoff = backoff * 2 < cfg.reconnect_max_ms ? backoff * 2 : cfg.reconnect_max_ms;
1126 continue;
1127 }
1128 if (status != 200) {
1129 sx_ntfy_logf("subscribe answered %d (retry in %lldms)", status, backoff);
1130 st.error_count++;
1131 snprintf(st.last_error, sizeof st.last_error, "subscribe http %d", status);
1132 sx_ntfy_status_save(&st);
1133 sx_conn_close(&c);
1134 stop_sleep(backoff);
1135 backoff = backoff * 2 < cfg.reconnect_max_ms ? backoff * 2 : cfg.reconnect_max_ms;
1136 continue;
1137 }
1138 backoff = cfg.reconnect_min_ms;
1139 st.connected = 1;
1140 st.connect_count++;
1141 st.last_seen_at = sx_ntfy_now_epoch();
1142 snprintf(st.last_error, sizeof st.last_error, "%s", "");
1143 sx_ntfy_status_save(&st);
1144 if (first) { sx_ntfy_logf("subscribed to %s/%s", cfg.server_url, cfg.topic); first = 0; }
1145
1146 while (!STOP_REQUESTED()) {
1147 ntfy_event ev;
1148 int rr;
1149 /* the assistant reply is checked EVERY tick, not only after the
1150 * stream breaks: the ntfy subscription is long-lived and the
1151 * agent's answer arrives while it is still open. */
1152 {
1153 long long cursor = st.conv_cursor;
1154 char reply[12000];
1155 long long rts = 0;
1156 poll_assistant(&cfg, &cursor, reply, sizeof reply, &rts);
1157 if (cursor > st.conv_cursor) st.conv_cursor = cursor;
1158 if (reply[0]) {
1159 char tosend[12300];
1160 char idout[64] = "", err3[300] = "";
1161 if (cfg.reply_prefix[0])
1162 snprintf(tosend, sizeof tosend, "%s%s", cfg.reply_prefix, reply);
1163 else
1164 snprintf(tosend, sizeof tosend, "%s", reply);
1165 if (ntfy_publish(&cfg,
1166 cfg.publish_topic[0] ? cfg.publish_topic : cfg.topic,
1167 tosend,
1168 cfg.title_prefix[0] ? cfg.title_prefix : NULL,
1169 cfg.priority, cfg.tags[0] ? cfg.tags : "robot",
1170 idout, sizeof idout, err3, sizeof err3) == 0) {
1171 if (idout[0]) sx_ntfy_sent_note(idout);
1172 st.outbound_count++;
1173 st.last_outbound_at = sx_ntfy_now_epoch();
1174 sx_ntfy_logf("outbound reply published (id %s, %zu bytes)",
1175 idout[0] ? idout : "?", strlen(tosend));
1176 } else {
1177 st.error_count++;
1178 snprintf(st.last_error, sizeof st.last_error, "publish: %s", err3);
1179 sx_ntfy_logf("reply publish failed: %s", err3);
1180 }
1181 st.last_seen_at = sx_ntfy_now_epoch();
1182 sx_ntfy_status_save(&st);
1183 }
1184 }
1185 rr = sx_http_readline(&c, line, sizeof line, cfg.idle_timeout_ms);
1186 if (rr < 0) { sx_ntfy_logf("stream read timeout/error, reconnecting"); break; }
1187 if (rr == 0) { sx_ntfy_logf("stream closed by server, reconnecting"); break; }
1188
1189 if (!parse_event_line(line, &ev)) continue; /* keepalive / comment */
1190 st.last_seen_at = sx_ntfy_now_epoch();
1191 if (ev.time_sec > st.last_message_time) st.last_message_time = ev.time_sec;
1192
1193 if (strcmp(ev.event, "message") != 0) continue; /* open/closed/etc */
1194 if (!ev.message[0]) continue;
1195 snprintf(st.last_event, sizeof st.last_event, "%s", ev.event);
1196
1197 /* ---- anti-self-loop: never forward our own publish ---- */
1198 if (event_is_own(&ev, &cfg)) {
1199 st.blocked_count++; /* counted, deliberately quiet */
1200 continue;
1201 }
1202 /* only messages from the subscribe topic (a server may multiplex) */
1203 if (ev.topic[0] && strcmp(ev.topic, cfg.topic) != 0) continue;
1204
1205 /* ---- pairing command? ---- */
1206 {
1207 char code[24];
1208 if (cfg.pairing_code_enabled && parse_pair_command(ev.message, code, sizeof code)) {
1209 char key[SX_NTFY_IDENTITY_LEN + 1];
1210 char label[160];
1211 identity_of(ev.topic[0] ? ev.topic : cfg.topic, ev.user, ev.tags, key);
1212 identity_label(ev.user, ev.tags, ev.topic[0] ? ev.topic : cfg.topic, label);
1213 if (sx_ntfy_pending_find_code(code, key, sizeof key)) {
1214 sx_ntfy_approved_add(key, label, 1);
1215 sx_ntfy_pending_remove(key);
1216 {
1217 char idout[64], e2[256];
1218 char msg[200];
1219 snprintf(msg, sizeof msg, "Paired. Your messages now reach the agent.");
1220 if (ntfy_publish(&cfg, cfg.publish_topic[0] ? cfg.publish_topic : cfg.topic,
1221 msg, "SCORPIOX BOT pairing", 3, "white_check_mark",
1222 idout, sizeof idout, e2, sizeof e2) == 0 && idout[0])
1223 sx_ntfy_sent_note(idout);
1224 }
1225 sx_ntfy_logf("paired via code: %s (%s)", key, label);
1226 st.last_seen_at = sx_ntfy_now_epoch();
1227 sx_ntfy_status_save(&st);
1228 } else {
1229 st.blocked_count++;
1230 sx_ntfy_logf("wrong pairing code from %s", key);
1231 }
1232 continue;
1233 }
1234 }
1235
1236 /* ---- default-deny gate ---- */
1237 {
1238 char key[SX_NTFY_IDENTITY_LEN + 1];
1239 char label[160];
1240 identity_of(ev.topic[0] ? ev.topic : cfg.topic, ev.user, ev.tags, key);
1241 identity_label(ev.user, ev.tags, ev.topic[0] ? ev.topic : cfg.topic, label);
1242
1243 if (!cfg.allow_all && !sx_ntfy_approved_has(key)) {
1244 sx_ntfy_pending *items = NULL;
1245 size_t n = 0, cap = 64;
1246 sx_ntfy_pending *pe;
1247 sx_ntfy_pending_load(&items, &n);
1248 pe = sx_ntfy_pending_touch(&items, &n, &cap, key, label, ev.message);
1249 if (pe) {
1250 long long ago = st.last_seen_at - pe->last_challenge_at;
1251 if (pe->last_challenge_at == 0 || ago > 600) {
1252 send_challenge(&cfg, cfg.topic, pe->code, 10);
1253 pe->last_challenge_at = st.last_seen_at;
1254 }
1255 sx_ntfy_pending_save(items, n);
1256 st.pending_count = (long long)n;
1257 }
1258 free(items);
1259 st.blocked_count++;
1260 st.last_seen_at = sx_ntfy_now_epoch();
1261 sx_ntfy_status_save(&st);
1262 sx_ntfy_logf("blocked unapproved sender %s (%s)", key, label);
1263 continue;
1264 }
1265 if (!cfg.allow_all) sx_ntfy_approved_touch_seen(key);
1266
1267 /* ---- approved: bridge to the agent ---- */
1268 {
1269 char text[9300];
1270 char ibody[8000];
1271 char err2[300] = "";
1272 size_t sn = 0;
1273 const char *src = ev.message;
1274
1275 /* sanitise: strip control chars except tab/newline, cap */
1276 for (; *src && sn + 1 < sizeof ibody; src++) {
1277 unsigned char ch = (unsigned char)*src;
1278 if (ch == '\t' || ch == '\n' || (ch >= 0x20 && ch != 0x7F))
1279 ibody[sn++] = (char)ch;
1280 }
1281 ibody[sn] = '\0';
1282
1283 if (ev.user[0] || ev.tags[0])
1284 snprintf(text, sizeof text, "[%s via ntfy%s%s%s] %s",
1285 ev.user[0] ? ev.user : "anonymous",
1286 ev.tags[0] ? " tags=" : "",
1287 ev.tags[0] ? ev.tags : "",
1288 ev.tags[0] ? "" : "",
1289 ibody);
1290 else
1291 snprintf(text, sizeof text, "[ntfy] %s", ibody);
1292
1293 if (ev.title[0]) {
1294 char t2[9500];
1295 snprintf(t2, sizeof t2, "%s\n%s", ev.title, text);
1296 cp_trunc(text, sizeof text, t2);
1297 }
1298
1299 if (bot_post_inbox(&cfg, text, err2, sizeof err2) != 0) {
1300 st.error_count++;
1301 snprintf(st.last_error, sizeof st.last_error, "inbox: %s", err2);
1302 sx_ntfy_logf("inbox post failed: %s", err2);
1303 } else {
1304 st.inbound_count++;
1305 st.last_inbound_at = sx_ntfy_now_epoch();
1306 sx_ntfy_logf("inbound -> /inbox (%zu bytes) from %s", strlen(text), key);
1307 }
1308 sx_ntfy_status_save(&st);
1309 }
1310 }
1311 }
1312 st.connected = 0;
1313 st.last_seen_at = sx_ntfy_now_epoch();
1314 sx_ntfy_status_save(&st);
1315 sx_conn_close(&c);
1316
1317 /* ---- outbound: deliver any new assistant reply ---- */
1318 if (!STOP_REQUESTED()) {
1319 long long cursor = st.conv_cursor;
1320 char reply[12000];
1321 long long rts = 0;
1322 poll_assistant(&cfg, &cursor, reply, sizeof reply, &rts);
1323 if (cursor > st.conv_cursor) st.conv_cursor = cursor;
1324 if (reply[0]) {
1325 char tosend[12300];
1326 char idout[64] = "", err3[300] = "";
1327 if (cfg.reply_prefix[0])
1328 snprintf(tosend, sizeof tosend, "%s%s", cfg.reply_prefix, reply);
1329 else
1330 snprintf(tosend, sizeof tosend, "%s", reply);
1331 if (strlen(reply) > 12000 - 32) tosend[sizeof tosend - 1] = '\0';
1332 if (ntfy_publish(&cfg,
1333 cfg.publish_topic[0] ? cfg.publish_topic : cfg.topic,
1334 tosend,
1335 cfg.title_prefix[0] ? cfg.title_prefix : NULL,
1336 cfg.priority, cfg.tags[0] ? cfg.tags : "robot",
1337 idout, sizeof idout, err3, sizeof err3) == 0) {
1338 if (idout[0]) sx_ntfy_sent_note(idout);
1339 st.outbound_count++;
1340 st.last_outbound_at = sx_ntfy_now_epoch();
1341 sx_ntfy_logf("outbound reply published (id %s, %zu bytes)",
1342 idout[0] ? idout : "?", strlen(tosend));
1343 } else {
1344 st.error_count++;
1345 snprintf(st.last_error, sizeof st.last_error, "publish: %s", err3);
1346 sx_ntfy_logf("reply publish failed: %s", err3);
1347 }
1348 st.last_seen_at = sx_ntfy_now_epoch();
1349 sx_ntfy_status_save(&st);
1350 }
1351 }
1352 if (!STOP_REQUESTED()) stop_sleep(cfg.reply_poll_ms);
1353 }
1354
1355 st.connected = 0;
1356 st.last_seen_at = sx_ntfy_now_epoch();
1357 sx_ntfy_status_save(&st);
1358 sx_ntfy_pidfile_remove();
1359 sx_ntfy_logf("daemon stopped");
1360 return 0;
1361}
1362
1363/* ------------------------------------------------------------------ */
1364/* mode 4: ?action=... node JSON API (behind require_node_auth) */
1365/* ------------------------------------------------------------------ */
1366
1367typedef struct { yyjson_mut_doc *doc; yyjson_mut_val *root; } jout;
1368
1369static void jout_init(jout *j)
1370{
1371 j->doc = yyjson_mut_doc_new(NULL);
1372 j->root = yyjson_mut_obj(j->doc);
1373 yyjson_mut_doc_set_root(j->doc, j->root);
1374 yyjson_mut_obj_add_bool(j->doc, j->root, "ok", true);
1375}
1376
1377static void jout_done(jout *j)
1378{
1379 char *txt = yyjson_mut_write(j->doc, 0, NULL);
1380 json_respond(200, txt ? txt : "{\"ok\":false,\"error\":\"serialise failed\"}");
1381 free(txt);
1382 yyjson_mut_doc_free(j->doc);
1383}
1384
1385static void jfail(int status, const char *err)
1386{
1387 char esc[1024];
1388 char buf[1200];
1389 sx_ntfy_json_escape(err ? err : "error", esc, sizeof esc);
1390 snprintf(buf, sizeof buf, "{\"ok\":false,\"error\":\"%s\"}", esc);
1391 json_respond(status, buf);
1392}
1393
1394static void status_obj(jout *j, const sx_ntfy_status *st, const sx_ntfy_config *cfg,
1395 int running)
1396{
1397 yyjson_mut_doc *d = j->doc;
1398 yyjson_mut_val *o = yyjson_mut_obj(d);
1399 yyjson_mut_obj_add_val(d, j->root, "status", o);
1400 yyjson_mut_obj_add_sint(d, o, "started_at", st->started_at);
1401 yyjson_mut_obj_add_sint(d, o, "last_seen_at", st->last_seen_at);
1402 yyjson_mut_obj_add_sint(d, o, "last_inbound_at", st->last_inbound_at);
1403 yyjson_mut_obj_add_sint(d, o, "last_outbound_at", st->last_outbound_at);
1404 yyjson_mut_obj_add_sint(d, o, "inbound_count", st->inbound_count);
1405 yyjson_mut_obj_add_sint(d, o, "outbound_count", st->outbound_count);
1406 yyjson_mut_obj_add_sint(d, o, "blocked_count", st->blocked_count);
1407 yyjson_mut_obj_add_sint(d, o, "pending_count", st->pending_count);
1408 yyjson_mut_obj_add_sint(d, o, "connect_count", st->connect_count);
1409 yyjson_mut_obj_add_sint(d, o, "error_count", st->error_count);
1410 yyjson_mut_obj_add_int(d, o, "connected", running ? st->connected : 0);
1411 yyjson_mut_obj_add_int(d, o, "running", running);
1412 yyjson_mut_obj_add_sint(d, o, "conv_cursor", st->conv_cursor);
1413 yyjson_mut_obj_add_sint(d, o, "last_message_time", st->last_message_time);
1414 yyjson_mut_obj_add_strcpy(d, o, "last_error", st->last_error);
1415 yyjson_mut_obj_add_strcpy(d, o, "last_event", st->last_event);
1416 yyjson_mut_obj_add_strcpy(d, o, "topic", cfg->topic);
1417 yyjson_mut_obj_add_strcpy(d, o, "publish_topic", cfg->publish_topic[0] ? cfg->publish_topic : cfg->topic);
1418 yyjson_mut_obj_add_strcpy(d, o, "target_session", cfg->target_session);
1419 yyjson_mut_obj_add_strcpy(d, o, "server_url", cfg->server_url);
1420 yyjson_mut_obj_add_bool(d, o, "configured", cfg->topic[0] && cfg->target_session[0]);
1421 yyjson_mut_obj_add_bool(d, o, "allow_all", cfg->allow_all ? true : false);
1422 yyjson_mut_obj_add_bool(d, o, "pairing_code_enabled", cfg->pairing_code_enabled ? true : false);
1423 yyjson_mut_obj_add_bool(d, o, "markdown", cfg->markdown ? true : false);
1424 /* write-only secrets: only ever a boolean comes back */
1425 yyjson_mut_obj_add_bool(d, o, "has_bearer", cfg->bearer_token[0] ? true : false);
1426 yyjson_mut_obj_add_bool(d, o, "has_bot_password", cfg->bot_password[0] ? true : false);
1427 yyjson_mut_obj_add_bool(d, o, "tls_insecure", sx_ntfy_tls_insecure() ? true : false);
1428 yyjson_mut_obj_add_bool(d, o, "pinned", cfg->allowed_pins[0] ? true : false);
1429 yyjson_mut_obj_add_bool(d, o, "tls", strstr(cfg->server_url, "https://") ? true : false);
1430 yyjson_mut_obj_add_int(d, o, "priority", cfg->priority);
1431 yyjson_mut_obj_add_strcpy(d, o, "tags", cfg->tags);
1432 yyjson_mut_obj_add_strcpy(d, o, "reply_prefix", cfg->reply_prefix);
1433 yyjson_mut_obj_add_strcpy(d, o, "title_prefix", cfg->title_prefix);
1434}
1435
1436static void cfg_obj(jout *j, const sx_ntfy_config *cfg)
1437{
1438 yyjson_mut_doc *d = j->doc;
1439 yyjson_mut_val *o = yyjson_mut_obj(d);
1440 yyjson_mut_obj_add_val(d, j->root, "config", o);
1441 yyjson_mut_obj_add_strcpy(d, o, "server_url", cfg->server_url);
1442 yyjson_mut_obj_add_strcpy(d, o, "topic", cfg->topic);
1443 yyjson_mut_obj_add_strcpy(d, o, "publish_topic", cfg->publish_topic);
1444 yyjson_mut_obj_add_strcpy(d, o, "bot_api_url", cfg->bot_api_url);
1445 yyjson_mut_obj_add_strcpy(d, o, "target_session", cfg->target_session);
1446 yyjson_mut_obj_add_strcpy(d, o, "tags", cfg->tags);
1447 yyjson_mut_obj_add_strcpy(d, o, "reply_prefix", cfg->reply_prefix);
1448 yyjson_mut_obj_add_strcpy(d, o, "title_prefix", cfg->title_prefix);
1449 yyjson_mut_obj_add_strcpy(d, o, "ca_file", cfg->ca_file);
1450 yyjson_mut_obj_add_int(d, o, "priority", cfg->priority);
1451 yyjson_mut_obj_add_int(d, o, "markdown", cfg->markdown);
1452 yyjson_mut_obj_add_int(d, o, "allow_all", cfg->allow_all);
1453 yyjson_mut_obj_add_int(d, o, "pairing_code_enabled", cfg->pairing_code_enabled);
1454 yyjson_mut_obj_add_sint(d, o, "reply_poll_ms", cfg->reply_poll_ms);
1455 yyjson_mut_obj_add_sint(d, o, "idle_timeout_ms", cfg->idle_timeout_ms);
1456 yyjson_mut_obj_add_sint(d, o, "updated_at", cfg->updated_at);
1457 /* deliberately NOT serialised: bearer_token, bot_password, allowed_pins
1458 * (a pin list is not a secret, but echoing it invites copy-paste into a
1459 * config that trusts the wrong key; the UI shows "pinned" instead) */
1460}
1461
1462static void send_pending_list(jout *j)
1463{
1464 sx_ntfy_pending *items = NULL;
1465 size_t n = 0, i;
1466 yyjson_mut_val *arr;
1467
1468 sx_ntfy_pending_load(&items, &n);
1469 arr = yyjson_mut_arr(j->doc);
1470 yyjson_mut_obj_add_val(j->doc, j->root, "pending", arr);
1471 for (i = 0; i < n; i++) {
1472 yyjson_mut_val *o = yyjson_mut_obj(j->doc);
1473 yyjson_mut_arr_add_val(arr, o);
1474 yyjson_mut_obj_add_strcpy(j->doc, o, "key", items[i].key);
1475 yyjson_mut_obj_add_strcpy(j->doc, o, "label", items[i].label);
1476 yyjson_mut_obj_add_strcpy(j->doc, o, "code", items[i].code);
1477 yyjson_mut_obj_add_strcpy(j->doc, o, "sample", items[i].sample);
1478 yyjson_mut_obj_add_sint(j->doc, o, "first_seen", items[i].first_seen);
1479 yyjson_mut_obj_add_sint(j->doc, o, "last_seen", items[i].last_seen);
1480 yyjson_mut_obj_add_int(j->doc, o, "count", items[i].count);
1481 }
1482 free(items);
1483}
1484
1485static void send_approved_list(jout *j)
1486{
1487 sx_ntfy_approved *items = NULL;
1488 size_t n = 0, i;
1489 yyjson_mut_val *arr;
1490
1491 sx_ntfy_approved_load(&items, &n);
1492 arr = yyjson_mut_arr(j->doc);
1493 yyjson_mut_obj_add_val(j->doc, j->root, "approved", arr);
1494 for (i = 0; i < n; i++) {
1495 yyjson_mut_val *o = yyjson_mut_obj(j->doc);
1496 yyjson_mut_arr_add_val(arr, o);
1497 yyjson_mut_obj_add_strcpy(j->doc, o, "key", items[i].key);
1498 yyjson_mut_obj_add_strcpy(j->doc, o, "label", items[i].label);
1499 yyjson_mut_obj_add_sint(j->doc, o, "added_at", items[i].added_at);
1500 yyjson_mut_obj_add_sint(j->doc, o, "last_seen", items[i].last_seen);
1501 yyjson_mut_obj_add_int(j->doc, o, "count", items[i].count);
1502 yyjson_mut_obj_add_int(j->doc, o, "via", items[i].via);
1503 }
1504 free(items);
1505}
1506
1507static int valid_key(const char *k)
1508{
1509 size_t i, n = strlen(k);
1510 if (n != SX_NTFY_IDENTITY_LEN) return 0;
1511 for (i = 0; i < n; i++) if (!isxdigit((unsigned char)k[i])) return 0;
1512 return 1;
1513}
1514
1515static void mode_json(const char *qs)
1516{
1517 char action[40] = "";
1518 char tmp[8192];
1519 yyjson_val *jroot = NULL;
1520 sx_ntfy_config cfg;
1521 char cerr[256];
1522 int cfg_loaded;
1523
1524 /* body first: a POST with a JSON body is what the UI sends */
1525 if (is_post_request()) {
1526 char *body = read_post_body();
1527 if (body && *body) {
1528 static yyjson_doc *keep; /* lives for the whole request */
1529 keep = yyjson_read(body, strlen(body), 0);
1530 if (keep) jroot = yyjson_doc_get_root(keep);
1531 }
1532 }
1533 if (!req_field(qs, jroot, "action", action, sizeof action) && !jroot)
1534 snprintf(action, sizeof action, "status");
1535 if (!action[0]) snprintf(action, sizeof action, "status");
1536 trim_inplace(action);
1537
1538 cfg_loaded = (sx_ntfy_config_load(&cfg, cerr, sizeof cerr) == 0);
1539 if (!cfg_loaded) sx_ntfy_config_defaults(&cfg);
1540
1541 /* ---------------- read-only, useful before any configuration -------- */
1542 if (!strcmp(action, "status")) {
1543 jout j;
1544 sx_ntfy_status st;
1545 jout_init(&j);
1546 sx_ntfy_status_load(&st);
1547 status_obj(&j, &st, &cfg, sx_ntfy_daemon_running());
1548 yyjson_mut_obj_add_strcpy(j.doc, j.root, "version", PLUGIN_VER);
1549 yyjson_mut_obj_add_strcpy(j.doc, j.root, "id", PLUGIN_ID);
1550 yyjson_mut_obj_add_bool(j.doc, j.root, "tls_insecure_env", sx_ntfy_tls_insecure() ? true : false);
1551 jout_done(&j);
1552 return;
1553 }
1554 if (!strcmp(action, "config")) {
1555 jout j;
1556 jout_init(&j);
1557 cfg_obj(&j, &cfg);
1558 jout_done(&j);
1559 return;
1560 }
1561 if (!strcmp(action, "pending")) {
1562 jout j;
1563 jout_init(&j);
1564 send_pending_list(&j);
1565 jout_done(&j);
1566 return;
1567 }
1568 if (!strcmp(action, "approved")) {
1569 jout j;
1570 jout_init(&j);
1571 send_approved_list(&j);
1572 jout_done(&j);
1573 return;
1574 }
1575 if (!strcmp(action, "info")) {
1576 jout j;
1577 jout_init(&j);
1578 yyjson_mut_obj_add_strcpy(j.doc, j.root, "id", PLUGIN_ID);
1579 yyjson_mut_obj_add_strcpy(j.doc, j.root, "slug", PLUGIN_SLUG);
1580 yyjson_mut_obj_add_strcpy(j.doc, j.root, "version", PLUGIN_VER);
1581 yyjson_mut_obj_add_strcpy(j.doc, j.root, "kind", "hybrid");
1582 yyjson_mut_obj_add_bool(j.doc, j.root, "mcp", true);
1583 yyjson_mut_obj_add_bool(j.doc, j.root, "daemon", true);
1584 yyjson_mut_obj_add_bool(j.doc, j.root, "menus", false);
1585 yyjson_mut_obj_add_strcpy(j.doc, j.root, "verified", "mock");
1586 yyjson_mut_obj_add_strcpy(j.doc, j.root, "dir_note", "state in ~/.scorpiox/connectors/plugin_ntfy");
1587 {
1588 char dir[1000];
1589 if (sx_ntfy_dir(dir, sizeof dir) == 0)
1590 yyjson_mut_obj_add_strcpy(j.doc, j.root, "connector_dir", dir);
1591 }
1592 jout_done(&j);
1593 return;
1594 }
1595
1596 /* ---------------- writes -------------------------------------------- */
1597 if (!strcmp(action, "save")) {
1598 char v[1024];
1599 jout j;
1600 char verr[256];
1601
1602 if (req_field(qs, jroot, "server_url", v, sizeof v) && v[0]) cp_trunc(cfg.server_url, sizeof cfg.server_url, v);
1603 if (req_field(qs, jroot, "topic", v, sizeof v)) cp_trunc(cfg.topic, sizeof cfg.topic, v);
1604 if (req_field(qs, jroot, "publish_topic", v, sizeof v)) cp_trunc(cfg.publish_topic, sizeof cfg.publish_topic, v);
1605 if (req_field(qs, jroot, "target_session", v, sizeof v)) cp_trunc(cfg.target_session, sizeof cfg.target_session, v);
1606 if (req_field(qs, jroot, "bot_api_url", v, sizeof v) && v[0]) cp_trunc(cfg.bot_api_url, sizeof cfg.bot_api_url, v);
1607 if (req_field(qs, jroot, "tags", v, sizeof v)) cp_trunc(cfg.tags, sizeof cfg.tags, v);
1608 if (req_field(qs, jroot, "reply_prefix", v, sizeof v)) cp_trunc(cfg.reply_prefix, sizeof cfg.reply_prefix, v);
1609 if (req_field(qs, jroot, "title_prefix", v, sizeof v)) cp_trunc(cfg.title_prefix, sizeof cfg.title_prefix, v);
1610 if (req_field(qs, jroot, "ca_file", v, sizeof v)) cp_trunc(cfg.ca_file, sizeof cfg.ca_file, v);
1611 if (req_field(qs, jroot, "allowed_pins", v, sizeof v)) cp_trunc(cfg.allowed_pins, sizeof cfg.allowed_pins, v);
1612 /* a blank token field means "leave it alone"; an explicit __clear__ wipes
1613 * it, so the UI can forget a secret without the operator editing JSON */
1614 if (req_field(qs, jroot, "bearer_token", v, sizeof v) && v[0]) {
1615 if (!strcmp(v, "__clear__")) cfg.bearer_token[0] = '\0';
1616 else cp_trunc(cfg.bearer_token, sizeof cfg.bearer_token, v);
1617 }
1618 if (req_field(qs, jroot, "bot_password", v, sizeof v) && v[0]) {
1619 if (!strcmp(v, "__clear__")) cfg.bot_password[0] = '\0';
1620 else cp_trunc(cfg.bot_password, sizeof cfg.bot_password, v);
1621 }
1622 if (req_field(qs, jroot, "priority", v, sizeof v) && v[0]) {
1623 int p = atoi(v);
1624 if (p < 1) p = 1;
1625 if (p > 5) p = 5;
1626 cfg.priority = p;
1627 }
1628 if (req_field(qs, jroot, "markdown", v, sizeof v)) cfg.markdown = is_truthy(v) ? 1 : 0;
1629 if (req_field(qs, jroot, "allow_all", v, sizeof v)) cfg.allow_all = is_truthy(v) ? 1 : 0;
1630 if (req_field(qs, jroot, "pairing_code_enabled", v, sizeof v))
1631 cfg.pairing_code_enabled = is_truthy(v) ? 1 : 0;
1632 if (req_field(qs, jroot, "reply_poll_ms", v, sizeof v) && v[0]) {
1633 long long x = strtoll(v, NULL, 10);
1634 if (x >= 100 && x <= 60000) cfg.reply_poll_ms = x;
1635 }
1636 if (req_field(qs, jroot, "idle_timeout_ms", v, sizeof v) && v[0]) {
1637 long long x = strtoll(v, NULL, 10);
1638 if (x >= 2000 && x <= 300000) cfg.idle_timeout_ms = x;
1639 }
1640 if (!cfg.publish_topic[0]) cp_trunc(cfg.publish_topic, sizeof cfg.publish_topic, cfg.topic);
1641
1642 /* Save what we were given even if not yet fully valid -- the operator
1643 * fills the form in stages; only start/test refuse an invalid config. */
1644 {
1645 char serr[256];
1646 if (sx_ntfy_config_save(&cfg, serr, sizeof serr) != 0) {
1647 jfail(500, serr);
1648 return;
1649 }
1650 }
1651 jout_init(&j);
1652 cfg_obj(&j, &cfg);
1653 yyjson_mut_obj_add_bool(j.doc, j.root, "valid",
1654 sx_ntfy_config_validate(&cfg, verr, sizeof verr) == 0);
1655 if (sx_ntfy_config_validate(&cfg, verr, sizeof verr) != 0)
1656 yyjson_mut_obj_add_strcpy(j.doc, j.root, "validation", verr);
1657 jout_done(&j);
1658 return;
1659 }
1660
1661 if (!strcmp(action, "test")) {
1662 char err[512] = "", idout[64] = "";
1663 char title[80], msg[200];
1664 jout j;
1665 snprintf(title, sizeof title, "%s test", cfg.title_prefix[0] ? cfg.title_prefix : "SCORPIOX BOT");
1666 snprintf(msg, sizeof msg, "plugin_ntfy test notification from this node. "
1667 "If you can read this, publishing works.");
1668 if (!cfg.topic[0] && !cfg.publish_topic[0]) { jfail(400, "set a topic first"); return; }
1669 if (ntfy_publish(&cfg, cfg.publish_topic[0] ? cfg.publish_topic : cfg.topic,
1670 msg, title, cfg.priority, "bell",
1671 idout, sizeof idout, err, sizeof err) != 0) {
1672 jfail(502, err);
1673 return;
1674 }
1675 if (idout[0]) sx_ntfy_sent_note(idout);
1676 jout_init(&j);
1677 yyjson_mut_obj_add_strcpy(j.doc, j.root, "published_id", idout);
1678 yyjson_mut_obj_add_strcpy(j.doc, j.root, "topic",
1679 cfg.publish_topic[0] ? cfg.publish_topic : cfg.topic);
1680 jout_done(&j);
1681 return;
1682 }
1683
1684 if (!strcmp(action, "send")) {
1685 char msg[8000] = "", title[200] = "", tags[200] = "", topic[160] = "";
1686 char prio[8] = "", idout[64] = "", err[512] = "";
1687 int p = cfg.priority;
1688 jout j;
1689
1690 req_field(qs, jroot, "message", msg, sizeof msg);
1691 req_field(qs, jroot, "title", title, sizeof title);
1692 req_field(qs, jroot, "tags", tags, sizeof tags);
1693 req_field(qs, jroot, "topic", topic, sizeof topic);
1694 if (req_field(qs, jroot, "priority", prio, sizeof prio) && prio[0]) {
1695 int x = atoi(prio);
1696 if (x >= 1 && x <= 5) p = x;
1697 }
1698 trim_inplace(msg);
1699 if (!msg[0]) { jfail(400, "message is required"); return; }
1700 if (!topic[0]) snprintf(topic, sizeof topic, "%s",
1701 cfg.publish_topic[0] ? cfg.publish_topic : cfg.topic);
1702 if (!topic[0]) { jfail(400, "no topic configured"); return; }
1703 if (ntfy_publish(&cfg, topic, msg, title[0] ? title : NULL, p,
1704 tags[0] ? tags : cfg.tags, idout, sizeof idout,
1705 err, sizeof err) != 0) {
1706 jfail(502, err);
1707 return;
1708 }
1709 if (idout[0]) sx_ntfy_sent_note(idout);
1710 jout_init(&j);
1711 yyjson_mut_obj_add_strcpy(j.doc, j.root, "published_id", idout);
1712 yyjson_mut_obj_add_strcpy(j.doc, j.root, "topic", topic);
1713 jout_done(&j);
1714 return;
1715 }
1716
1717 if (!strcmp(action, "approve") || !strcmp(action, "unapprove")) {
1718 char key[SX_NTFY_IDENTITY_LEN + 4] = "", label[160] = "", code[24] = "";
1719 jout j;
1720 int ok;
1721
1722 req_field(qs, jroot, "key", key, sizeof key);
1723 req_field(qs, jroot, "label", label, sizeof label);
1724 trim_inplace(key);
1725 if (!key[0] && req_field(qs, jroot, "code", code, sizeof code)) {
1726 char k[SX_NTFY_IDENTITY_LEN + 1];
1727 if (sx_ntfy_pending_find_code(code, k, sizeof k))
1728 snprintf(key, sizeof key, "%s", k);
1729 }
1730 if (!valid_key(key)) { jfail(400, "key must be the 64-hex identity from ?action=pending"); return; }
1731 if (!strcmp(action, "approve")) {
1732 ok = sx_ntfy_approved_add(key, label, 0);
1733 if (ok == 0) sx_ntfy_pending_remove(key);
1734 } else {
1735 ok = sx_ntfy_approved_remove(key);
1736 }
1737 if (ok != 0) { jfail(500, "cannot write the pairing store"); return; }
1738 jout_init(&j);
1739 yyjson_mut_obj_add_strcpy(j.doc, j.root, "key", key);
1740 yyjson_mut_obj_add_strcpy(j.doc, j.root, "action", action);
1741 jout_done(&j);
1742 return;
1743 }
1744
1745 if (!strcmp(action, "deny")) {
1746 char key[80] = "";
1747 jout j;
1748 req_field(qs, jroot, "key", key, sizeof key);
1749 trim_inplace(key);
1750 if (!valid_key(key)) { jfail(400, "key must be the 64-hex identity from ?action=pending"); return; }
1751 if (sx_ntfy_pending_remove(key) != 0) { jfail(500, "cannot write the pairing queue"); return; }
1752 jout_init(&j);
1753 yyjson_mut_obj_add_strcpy(j.doc, j.root, "key", key);
1754 yyjson_mut_obj_add_strcpy(j.doc, j.root, "action", "deny");
1755 jout_done(&j);
1756 return;
1757 }
1758
1759 if (!strcmp(action, "logs")) {
1760 char path[1100];
1761 char *buf = NULL;
1762 size_t len = 0;
1763 char tail[16000];
1764 jout j;
1765
1766 if (sx_ntfy_path(path, sizeof path, "daemon.log") != 0) { jfail(500, "connector dir unavailable"); return; }
1767 if (sx_ntfy_read_file(path, &buf, &len) != 0) {
1768 jout_init(&j);
1769 yyjson_mut_obj_add_strcpy(j.doc, j.root, "log", "");
1770 yyjson_mut_obj_add_int(j.doc, j.root, "bytes", 0);
1771 jout_done(&j);
1772 return;
1773 }
1774 /* tail: last 16 KB, and never start mid-line */
1775 {
1776 size_t start = len > sizeof tail - 1 ? len - (sizeof tail - 1) : 0;
1777 size_t n = len - start;
1778 while (start < len && buf[start] != '\n' && start < len - 80) start++;
1779 if (start < len && buf[start] == '\n') start++;
1780 n = len - start;
1781 if (n >= sizeof tail) n = sizeof tail - 1;
1782 memcpy(tail, buf + start, n);
1783 tail[n] = '\0';
1784 }
1785 free(buf);
1786 jout_init(&j);
1787 yyjson_mut_obj_add_str(j.doc, j.root, "log", tail);
1788 yyjson_mut_obj_add_int(j.doc, j.root, "bytes", (int)len);
1789 jout_done(&j);
1790 return;
1791 }
1792
1793 /* ---------------- start / stop -------------------------------------- */
1794 if (!strcmp(action, "start")) {
1795 char verr[256];
1796 jout j;
1797
1798 if (sx_ntfy_daemon_running()) { jfail(409, "the daemon is already running"); return; }
1799 if (sx_ntfy_config_validate(&cfg, verr, sizeof verr) != 0) { jfail(400, verr); return; }
1800 {
1801 char lerr[256];
1802 if (sx_ntfy_log_open(1) != 0) { jfail(500, "cannot open the log file"); return; }
1803 (void)lerr;
1804 }
1805#if defined(_WIN32)
1806 {
1807 char exe[1024];
1808 STARTUPINFOA si;
1809 PROCESS_INFORMATION pi;
1810 DWORD got;
1811 memset(&si, 0, sizeof si);
1812 si.cb = sizeof si;
1813 si.dwFlags = STARTF_USESHOWWINDOW;
1814 si.wShowWindow = SW_HIDE;
1815 memset(&pi, 0, sizeof pi);
1816 got = GetModuleFileNameA(NULL, exe, sizeof exe - 1);
1817 if (got == 0) { jfail(500, "cannot resolve this executable path"); return; }
1818 {
1819 char cmd[2200];
1820 snprintf(cmd, sizeof cmd, "\"%s\" --daemon", exe);
1821 if (!CreateProcessA(NULL, cmd, NULL, NULL, FALSE,
1822 CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS,
1823 NULL, NULL, &si, &pi)) {
1824 jfail(500, "CreateProcess failed for the detached daemon");
1825 return;
1826 }
1827 CloseHandle(pi.hThread);
1828 CloseHandle(pi.hProcess);
1829 }
1830 }
1831#else
1832 {
1833 pid_t pid = fork();
1834 if (pid < 0) { jfail(500, "fork failed"); return; }
1835 if (pid == 0) {
1836 /* child: fully detached daemon */
1837 int fd;
1838 setsid();
1839 fd = open("/dev/null", O_RDONLY);
1840 if (fd >= 0) { dup2(fd, 0); if (fd > 2) close(fd); }
1841 fd = open("/dev/null", O_WRONLY);
1842 if (fd >= 0) { dup2(fd, 1); dup2(fd, 2); if (fd > 2) close(fd); }
1843 _exit(run_daemon());
1844 }
1845 }
1846#endif
1847 sx_ntfy_logf("daemon started by the setup UI");
1848 jout_init(&j);
1849 yyjson_mut_obj_add_bool(j.doc, j.root, "started", true);
1850 jout_done(&j);
1851 return;
1852 }
1853
1854 if (!strcmp(action, "stop")) {
1855 long pid = 0;
1856 jout j;
1857 if (sx_ntfy_pidfile_read(&pid) != 0) { jfail(404, "the daemon is not running"); return; }
1858#if defined(_WIN32)
1859 {
1860 HANDLE h = OpenProcess(PROCESS_TERMINATE | SYNCHRONIZE, FALSE, (DWORD)pid);
1861 if (!h) { sx_ntfy_pidfile_remove(); jfail(404, "the daemon is not running"); return; }
1862 TerminateProcess(h, 0);
1863 WaitForSingleObject(h, 3000);
1864 CloseHandle(h);
1865 }
1866#else
1867 {
1868 int waited = 0;
1869 if (kill((pid_t)pid, 0) != 0 && errno == ESRCH) {
1870 sx_ntfy_pidfile_remove();
1871 jfail(404, "the daemon is not running");
1872 return;
1873 }
1874 kill((pid_t)pid, SIGTERM);
1875 while (waited < 5000 && kill((pid_t)pid, 0) == 0) {
1876 struct timespec ts = { 0, 100 * 1000000L };
1877 nanosleep(&ts, NULL);
1878 waited += 100;
1879 }
1880 if (kill((pid_t)pid, 0) == 0) {
1881 kill((pid_t)pid, SIGKILL);
1882 sx_ntfy_logf("daemon %ld ignored SIGTERM, sent SIGKILL", pid);
1883 }
1884 }
1885#endif
1886 sx_ntfy_pidfile_remove();
1887 sx_ntfy_logf("daemon stopped by the setup UI");
1888 jout_init(&j);
1889 yyjson_mut_obj_add_bool(j.doc, j.root, "stopped", true);
1890 jout_done(&j);
1891 return;
1892 }
1893
1894 jfail(400, "unknown action");
1895 (void)tmp;
1896}
1897
1898/* ------------------------------------------------------------------ */
1899/* mode 5: GET the Setup & Topic Pairing UI */
1900/* ------------------------------------------------------------------ */
1901
1902static void emit_ui(void)
1903{
1904 const char *p = UI_HTML;
1905
1906 while (*p) {
1907 if (*p == '\001') {
1908 fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS
1909 ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);--ac:var(--blue)}"
1910 "</style>", stdout);
1911 p++;
1912 } else if (*p == '\002') {
1913 fputs(SX_BOT_THEME_HANDOFF, stdout);
1914 p++;
1915 } else {
1916 putchar(*p++);
1917 }
1918 }
1919}
1920
1921static int mode_html(int embed)
1922{
1923 (void)embed;
1924 fputs("Content-Type: text/html; charset=utf-8\r\n"
1925 "Cache-Control: no-store\r\n"
1926 "X-Content-Type-Options: nosniff\r\n"
1927 "X-Frame-Options: SAMEORIGIN\r\n"
1928 "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
1929 "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; "
1930 "form-action 'none'; base-uri 'none'\r\n\r\n", stdout);
1931 emit_ui();
1932 return 0;
1933}
1934
1935/* ------------------------------------------------------------------ */
1936/* main */
1937/* ------------------------------------------------------------------ */
1938
1939int main(int argc, char **argv)
1940{
1941 const char *qs;
1942 int embed;
1943 int i;
1944
1945#if defined(_WIN32)
1946 /* Winsock has to be up before ANY mode touches the resolver. It used to
1947 * be started only on the CGI path (and separately for --daemon), so
1948 * `plugin_ntfy.exe --mcp` ran with a cold winsock: getaddrinfo() failed
1949 * straight away and every ntfy_send came back "cannot resolve
1950 * ntfy.sh:443". Verified on a real Windows box -- the MCP face is the
1951 * face an agent actually uses. */
1952 { WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); }
1953#endif
1954
1955 for (i = 1; i < argc; i++) {
1956 if (!strcmp(argv[i], "--meta") || !strcmp(argv[i], "-m"))
1957 return mode_meta();
1958 if (!strcmp(argv[i], "--mcp"))
1959 return mode_mcp();
1960 if (!strcmp(argv[i], "--schema"))
1961 return mode_schema();
1962 if (!strcmp(argv[i], "--daemon") || !strcmp(argv[i], "-d")) {
1963#if defined(_WIN32)
1964 { WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); }
1965#endif
1966 return run_daemon();
1967 }
1968 if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) {
1969 fputs("plugin_ntfy " PLUGIN_VER " -- SCORPIOX BOT ntfy channel connector\n"
1970 " --meta JSON discovery metadata (unauthenticated)\n"
1971 " --mcp stdio MCP server exposing the ntfy_send tool\n"
1972 " --schema the tool schema only\n"
1973 " --daemon channel gateway: ntfy <-> node /inbox bridge\n"
1974 " (no args, CGI) Setup & Topic Pairing UI + ?action= JSON API\n",
1975 stdout);
1976 return 0;
1977 }
1978 }
1979 if (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META"))
1980 return mode_meta();
1981
1982#if defined(_WIN32)
1983 /* MinGW translates \n to \r\n on stdout in text mode, which double-CR-
1984 * terminates our own CGI headers and breaks the framing (lesson (bh)). */
1985 _setmode(_fileno(stdout), _O_BINARY);
1986 { WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); }
1987#endif
1988
1989 if (getenv("SX_NTFY_MCP") && *getenv("SX_NTFY_MCP"))
1990 return mode_mcp();
1991
1992 require_node_auth();
1993
1994 qs = getenv("QUERY_STRING");
1995 if (!qs) qs = "";
1996
1997 if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request()) {
1998 mode_json(qs);
1999 return 0;
2000 }
2001
2002 embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL);
2003 return mode_html(embed);
2004}