/* * plugin_ntfy -- SCORPIOX BOT open-source ntfy push & pub/sub channel connector. * * A single clean-room C99 binary with FIVE modes: * * 1. --meta / SX_PLUGIN_META=1 JSON discovery metadata (unauthenticated, * so /plugins can probe it). * 2. --mcp stdio MCP JSON-RPC 2.0 server exposing the * ntfy_send tool for agents (alerts, reports). * 3. --daemon long-lived channel gateway: subscribes to * //json, applies the * default-deny pairing policy, forwards * approved senders' messages to the SCORPIOX * BOT node API (POST /inbox?id=), * and publishes the agent's replies back to * the publish topic over TLS. * 4. ?action=... or ?format=json the node JSON API (status/config/test/ * send/pending/approve/deny/start/stop/logs), * everything behind require_node_auth(). * 5. GET (default) the Setup & Topic Pairing UI, bot-themed, * embeddable, zero external resources. * * Security posture, in one paragraph: the connector is default-deny. ntfy has * no sender-identity primitive -- anyone who knows a topic can publish to it, * and the optional "user" field is publisher-controlled -- so every inbound * identity (sha256 of user + tags + topic) is held in a pairing queue until * the owner approves it in this UI or the sender types "PAIR " (the * code is delivered out-of-band through the challenge the connector posts on * the reply topic). Nothing reaches /inbox before that. The one exception is * NTFY_ALLOW_ALL=1, an explicitly opt-in dev mode, loudly reported in the UI * and in the status JSON. Own publications are remembered by message id in a * ledger and filtered from the subscription, and replies carry a visible * prefix, so the bridge cannot loop on itself even when subscribe == publish. * TLS fails closed against the bundled root store (src/ca_bundle_pem.h) with * hostname verification; a private-CA relay needs an explicit ca_file or an * explicit SPKI pin, and the only no-verify mode is NTFY_TLS_INSECURE=1 in * the environment -- never a stored value, never an HTTP parameter. The node * password and the ntfy bearer token are write-only: no response ever echoes * them, only "has_bearer"/"has_bot_password" booleans. * * Ported from the protocol semantics of NousResearch/hermes-agent * plugins/platforms/ntfy (server_url/topic/publish_topic/token/markdown/ * allowlist) reimplemented here from scratch in pure C99 with the ntfy * publish/subscribe contract verified against the reference server * (documented headers Title/Priority/Tags + X- variants, Authorization, * NDJSON /json stream with keepalives and poll/since parameters). * * Zero external runtime dependencies. The only vendored code is yyjson and * mbedTLS (see vendor/, LICENSE-yyjson, src/sx_ntfy_mbedtls_config.h). * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #if defined(_WIN32) # ifndef _WIN32_WINNT # define _WIN32_WINNT 0x0601 # endif # define WIN32_LEAN_AND_MEAN #else # if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200809L # undef _POSIX_C_SOURCE # define _POSIX_C_SOURCE 200809L # endif # ifndef _DEFAULT_SOURCE # define _DEFAULT_SOURCE 1 # endif # if defined(__APPLE__) # undef _DARWIN_C_SOURCE # define _DARWIN_C_SOURCE 1 # endif #endif #include #include #include #include #include #include #include #include #if defined(_WIN32) # include # include # include /* _setmode / _fileno on MinGW */ # include /* _O_BINARY (lives here, not in ) */ # include # define sx_sleep_ms(ms) Sleep(ms) #else # include # include # define sx_sleep_ms(ms) usleep((ms) * 1000) #endif #include "sx_http.h" #include "sx_connectors.h" #include "bot_theme_plugin.h" #include "ui_html.h" #include "yyjson.h" #define PLUGIN_SLUG "ntfy" #define PLUGIN_ID "plugin_ntfy" #define PLUGIN_VER "1.0.3" #define SELF_SOURCE_ID "scorpiox-bot-plugin-ntfy" /* The tag every notification THIS plugin publishes carries. A second, * human-visible layer of the anti-self-loop rule: a message with our tag on * the subscribe topic is by construction our own echo. */ #define SELF_TAG "scorpiox" /* Cap for one NDJSON record on the subscription. ntfy caps a message body at * 4 KB by default; 256 KB per record absorbs attachments metadata and a * hostile relay while keeping the daemon's footprint bounded. */ #define SX_NTFY_STREAM_CAP (256 * 1024) /* ------------------------------------------------------------------ */ /* Small helpers */ /* ------------------------------------------------------------------ */ static void trim_inplace(char *s) { size_t n; char *p = s; while (*p && isspace((unsigned char)*p)) p++; if (p != s) memmove(s, p, strlen(p) + 1); n = strlen(s); while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0'; } /* Explicit truncating copy. The form fields and the inbound message body are * longer than the config slots by design (a 1024-byte form field into a * 256-byte server_url, a 9 KB notification into an 8 KB bridge body): the * truncation IS the intended behaviour, so it is written as a memcpy the * compiler cannot mis-read as an accident. */ static void cp_trunc(char *dst, size_t capsz, const char *src) { size_t n; if (!capsz) return; if (!src) { dst[0] = '\0'; return; } n = strlen(src); if (n > capsz - 1) n = capsz - 1; memcpy(dst, src, n); dst[n] = '\0'; } static int ci_eq(const char *a, const char *b) { return strcasecmp(a, b) == 0; } static int is_truthy(const char *v) { return v && (!strcmp(v, "1") || ci_eq(v, "true") || ci_eq(v, "yes") || ci_eq(v, "on")); } static void url_decode_inplace(char *s) { char *o = s; while (*s) { if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { int hi = tolower((unsigned char)s[1]); int lo = tolower((unsigned char)s[2]); hi = hi <= '9' ? hi - '0' : hi - 'a' + 10; lo = lo <= '9' ? lo - '0' : lo - 'a' + 10; *o++ = (char)((hi << 4) | lo); s += 3; } else if (*s == '+') { *o++ = ' '; s++; } else *o++ = *s++; } *o = '\0'; } static int get_query_val(const char *qs, const char *key, char *out, size_t capsz) { size_t klen; if (out && capsz) out[0] = '\0'; if (!qs || !key || !out || !capsz) return 0; klen = strlen(key); while (*qs) { if (!strncmp(qs, key, klen) && qs[klen] == '=') { const char *v = qs + klen + 1; const char *e = strchr(v, '&'); size_t n = e ? (size_t)(e - v) : strlen(v); if (n >= capsz) n = capsz - 1; memcpy(out, v, n); out[n] = '\0'; url_decode_inplace(out); return 1; } qs = strchr(qs, '&'); if (!qs) break; qs++; } return 0; } static int is_post_request(void) { const char *m = getenv("REQUEST_METHOD"); return m && ci_eq(m, "POST"); } static char *read_post_body(void) { static char *cached = NULL; static int tried = 0; const char *cl; long n; char *buf; size_t rd; if (tried) return cached; tried = 1; cl = getenv("CONTENT_LENGTH"); n = cl ? atol(cl) : 0; if (n <= 0 || n > 1024 * 1024) return NULL; buf = malloc((size_t)n + 1); if (!buf) return NULL; rd = fread(buf, 1, (size_t)n, stdin); buf[rd] = '\0'; cached = buf; return buf; } /* JSON body field reader (POST /plugin_ntfy with Content-Type json), then * falls back to the query string. Booleans/ints normalise to "1"/"0" -- * lesson (as): a UI that sends {"force":true} must not silently read empty. */ static int req_field(const char *qs, yyjson_val *jroot, const char *key, char *out, size_t capsz) { if (out && capsz) out[0] = '\0'; if (jroot && yyjson_is_obj(jroot)) { yyjson_val *v = yyjson_obj_get(jroot, key); if (yyjson_is_str(v)) { snprintf(out, capsz, "%s", yyjson_get_str(v)); return 1; } if (yyjson_is_bool(v)) { snprintf(out, capsz, "%s", yyjson_get_bool(v) ? "1" : "0"); return 1; } if (yyjson_is_int(v)) { snprintf(out, capsz, "%lld", (long long)yyjson_get_sint(v)); return 1; } if (yyjson_is_uint(v)) { snprintf(out, capsz, "%llu", (unsigned long long)yyjson_get_uint(v)); return 1; } if (v) return 0; } if (qs) return get_query_val(qs, key, out, capsz); return 0; } static void json_respond(int status, const char *json) { printf("Status: %d\r\n", status); fputs("Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n" "\r\n", stdout); fputs(json, stdout); fputc('\n', stdout); fflush(stdout); } static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp, *auth, *qs; char qpwd[256]; if (!np || !*np) return; xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (strncmp(auth, "Bearer ", 7) == 0) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } qs = getenv("QUERY_STRING"); if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) return; json_respond(401, "{\"ok\":false,\"error\":\"invalid node password\"}"); exit(0); } /* ------------------------------------------------------------------ */ /* ntfy publish core (shared by --mcp, the UI, and the daemon) */ /* ------------------------------------------------------------------ */ /* Publishes one notification. Returns 0 on a 2xx answer; on success, if * id_out is non-NULL it receives the message id from the JSON answer so the * caller can add it to the self-echo ledger. */ static int ntfy_publish(const sx_ntfy_config *cfg, const char *topic, const char *message, const char *title, int priority, const char *tags, char *id_out, size_t id_capsz, char *err, size_t errsz) { sx_url u; sx_conn c; char base[512], path[1024]; char hdr[8][1200]; const char *hdrs[9]; int nh = 0; int status = 0; char *body = NULL; size_t blen = 0; char enc_topic[320]; if (id_out && id_capsz) id_out[0] = '\0'; if (!topic || !*topic) { snprintf(err, errsz, "no topic"); return -1; } { size_t i, n = strlen(topic); if (n == 0 || n > 128) { snprintf(err, errsz, "bad topic length"); return -1; } for (i = 0; i < n; i++) { char ch = topic[i]; if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '-' || ch == '.')) { snprintf(err, errsz, "topic contains forbidden characters"); return -1; } } } sx_url_encode(topic, enc_topic, sizeof enc_topic); snprintf(base, sizeof base, "%s", cfg->server_url); { /* trim trailing slash so the join below cannot make a double slash */ size_t l = strlen(base); while (l > 0 && base[l - 1] == '/') base[--l] = '\0'; } snprintf(path, sizeof path, "/%s", enc_topic); /* parse scheme://host[:port] out of the configured server base */ if (sx_url_parse(base, &u, err, errsz) != 0) return -1; snprintf(u.path, sizeof u.path, "%s", path); sx_conn_init(&c); if (sx_conn_open(&c, &u, NULL, cfg->allowed_pins[0] ? cfg->allowed_pins : NULL, cfg->ca_file[0] ? cfg->ca_file : NULL, sx_ntfy_tls_insecure(), 15000, err, errsz) != 0) return -1; /* Header assembly. One Tags header, comma-separated: ntfy accepts a * comma list, and repeating the header is server-version dependent, so * our own identification tag is folded into the same list. A value that * carries a control character never reaches the wire -- sx_http refuses * the whole request (header injection guard). */ nh = 0; hdrs[nh] = NULL; #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) if (title && *title) { char t[260]; snprintf(t, sizeof t, "Title: %s", title); SX_ADDH(t); } { char tagline[340]; if (tags && *tags) { char clean[220]; size_t j = 0; const char *t = tags; for (; *t && j + 1 < sizeof clean; t++) if ((unsigned char)*t >= 0x20 && *t != '\r' && *t != '\n') clean[j++] = *t; clean[j] = '\0'; snprintf(tagline, sizeof tagline, "Tags: %s," SELF_TAG, clean); } else { snprintf(tagline, sizeof tagline, "Tags: " SELF_TAG); } SX_ADDH(tagline); } if (priority >= 1 && priority <= 5) { char p[32]; snprintf(p, sizeof p, "Priority: %d", priority); SX_ADDH(p); } if (cfg->markdown) SX_ADDH("X-Markdown: true"); if (cfg->bearer_token[0]) { char a[300]; snprintf(a, sizeof a, "Authorization: %s", cfg->bearer_token); SX_ADDH(a); } SX_ADDH("X-Source-Id: " SELF_SOURCE_ID); #undef SX_ADDH hdrs[nh] = NULL; if (sx_http_request(&c, "POST", path, hdrs, message, message ? strlen(message) : 0, &status, &body, &blen, err, errsz) != 0) { sx_conn_close(&c); return -1; } sx_conn_close(&c); if (status < 200 || status >= 300) { char safe[200]; if (body) { snprintf(safe, sizeof safe, "%s", body); /* ntfy error bodies are small JSON; anything bigger got truncated */ { size_t l = strlen(safe); while (l > 0 && (safe[l-1] == '\n' || safe[l-1] == '\r')) safe[--l] = '\0'; } } else safe[0] = '\0'; snprintf(err, errsz, "ntfy server answered %d%s%s", status, safe[0] ? ": " : "", safe); free(body); return -1; } if (body && id_out && id_capsz) { yyjson_doc *d = yyjson_read(body, blen, 0); if (d) { yyjson_val *v = yyjson_obj_get(yyjson_doc_get_root(d), "id"); if (yyjson_is_str(v)) snprintf(id_out, id_capsz, "%s", yyjson_get_str(v)); yyjson_doc_free(d); } } free(body); return 0; } /* ------------------------------------------------------------------ */ /* mode 1: --meta */ /* ------------------------------------------------------------------ */ static int mode_meta(void) { /* one compact line: the convention every plugin keeps (the node reads * this with yyjson, but scripts grep the raw line) */ puts("{\"name\":\"ntfy\",\"desc\":\"Push channel\",\"version\":\"" PLUGIN_VER "\"," "\"slug\":\"" PLUGIN_SLUG "\",\"id\":\"" PLUGIN_ID "\",\"kind\":\"hybrid\"," "\"mcp\":true,\"daemon\":true,\"menus\":false,\"verified\":\"mock\"," "\"category\":\"network\"," "\"capabilities\":[\"https_outbound_ntfy_publish\"," "\"https_outbound_ntfy_subscribe_stream\",\"loopback_node_inbox_bridge\"," "\"pairing_allowlist_state_0600\",\"bundled_root_store_tls_verification\"," "\"stdio_mcp_jsonrpc_server\"]," "\"tools\":[\"ntfy_send\"]}"); fflush(stdout); return 0; } /* ------------------------------------------------------------------ */ /* mode 2: --mcp (stdio JSON-RPC 2.0) */ /* ------------------------------------------------------------------ */ #define MCP_PROTOCOL "2024-11-05" static void mcp_send_raw(const char *json) { fputs(json, stdout); fputc('\n', stdout); fflush(stdout); } static void mcp_error(long long id, int code, const char *msg) { char esc[512]; sx_ntfy_json_escape(msg ? msg : "error", esc, sizeof esc); { char buf[700]; snprintf(buf, sizeof buf, "{\"jsonrpc\":\"2.0\",\"id\":%lld,\"error\":{\"code\":%d,\"message\":\"%s\"}}", id, code, esc); mcp_send_raw(buf); } } static void mcp_tool_result(long long id, const char *text, int is_error) { /* 6x headroom: the worst case of the JSON escape is \u00XX (6 bytes per * input byte). Truncation is safe (the escape function caps itself), but * sizing this honestly is what keeps an alert body intact. */ static char esc[96000]; static char buf[97200]; sx_ntfy_json_escape(text, esc, sizeof esc); snprintf(buf, sizeof buf, "{\"jsonrpc\":\"2.0\",\"id\":%lld,\"result\":{\"content\":[{\"type\":\"text\",\"text\":\"%s\"}],\"isError\":%s}}", id, esc, is_error ? "true" : "false"); mcp_send_raw(buf); } static const char *MCP_TOOLS_JSON = "{\"tools\":[{" "\"name\":\"ntfy_send\"," "\"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.\"," "\"inputSchema\":{" " \"type\":\"object\"," " \"properties\":{" " \"message\":{\"type\":\"string\",\"description\":\"Notification body (required).\"}," " \"title\":{\"type\":\"string\",\"description\":\"Optional notification title.\"}," " \"priority\":{\"type\":\"integer\",\"description\":\"ntfy priority 1..5 (min low .. max urgent). Default 3.\",\"minimum\":1,\"maximum\":5}," " \"tags\":{\"type\":\"string\",\"description\":\"Optional comma-separated emoji tag names, e.g. 'warning,bell'.\"}," " \"topic\":{\"type\":\"string\",\"description\":\"Optional override topic (defaults to the configured publish topic).\"}" " }," " \"required\":[\"message\"]" "}}]}"; static int mode_mcp(void) { char line[65536]; sx_ntfy_config cfg; char cerr[256]; if (sx_ntfy_config_load(&cfg, cerr, sizeof cerr) != 0) { fprintf(stderr, "plugin_ntfy --mcp: config problem: %s\n", cerr); } #if defined(_WIN32) _setmode(_fileno(stdin), _O_BINARY); _setmode(_fileno(stdout), _O_BINARY); #endif /* Line-delimited JSON-RPC (one message per line), the stdio MCP framing * scorpiox-mcp and sx-connector-mcp speak (both use Content-Length OR * newline framing; newline is the safe subset -- scorpiox-connector-mcp * reads responses as lines). */ while (fgets(line, sizeof line, stdin)) { yyjson_doc *doc; yyjson_val *root, *v; long long id = 0; int has_id = 0; const char *method; trim_inplace(line); if (!line[0]) continue; doc = yyjson_read(line, strlen(line), 0); if (!doc) continue; root = yyjson_doc_get_root(doc); v = yyjson_obj_get(root, "id"); if (v) { if (yyjson_is_int(v)) { id = yyjson_get_sint(v); has_id = 1; } else if (yyjson_is_uint(v)) { id = (long long)yyjson_get_uint(v); has_id = 1; } } v = yyjson_obj_get(root, "method"); method = yyjson_is_str(v) ? yyjson_get_str(v) : ""; if (!strcmp(method, "initialize")) { if (has_id) { char buf[512]; snprintf(buf, sizeof buf, "{\"jsonrpc\":\"2.0\",\"id\":%lld,\"result\":{\"protocolVersion\":\"%s\"," "\"capabilities\":{\"tools\":{}},\"serverInfo\":{\"name\":\"plugin_ntfy\",\"version\":\"%s\"}," "\"instructions\":\"ntfy push + channel connector for SCORPIOX BOT. Use ntfy_send to deliver notifications.\"}}", id, MCP_PROTOCOL, PLUGIN_VER); mcp_send_raw(buf); } } else if (!strcmp(method, "notifications/initialized") || !strncmp(method, "notifications/", 14)) { /* notification: no response */ } else if (!strcmp(method, "ping")) { if (has_id) { char b[64]; snprintf(b, sizeof b, "{\"jsonrpc\":\"2.0\",\"id\":%lld,\"result\":{}}", id); mcp_send_raw(b); } } else if (!strcmp(method, "tools/list")) { if (has_id) { /* +64 for the id digits and the closing brace. The closing * brace of the *outer* object is ours to emit: MCP_TOOLS_JSON * is the value of "result", so without it the frame is one * brace short. yyjson then rejects the line, the router * (scorpiox-connector-mcp proc_request) skips it as "noise on * stdout", reads again, hits EOF and reports * "tools/list failed for ntfy: no response" -- the tool would * be invisible to every agent. A substring grep in the suite * passed on the broken frame; the assertion that catches this * now parses every emitted frame. */ char *buf = malloc(strlen(MCP_TOOLS_JSON) + 64); if (buf) { sprintf(buf, "{\"jsonrpc\":\"2.0\",\"id\":%lld,\"result\":%s}", id, MCP_TOOLS_JSON); mcp_send_raw(buf); free(buf); } } } else if (!strcmp(method, "tools/call")) { yyjson_val *params = yyjson_obj_get(root, "params"); yyjson_val *nv = params ? yyjson_obj_get(params, "name") : NULL; const char *tool = yyjson_is_str(nv) ? yyjson_get_str(nv) : ""; yyjson_val *args = params ? yyjson_obj_get(params, "arguments") : NULL; if (!tool || strcmp(tool, "ntfy_send") != 0) { if (has_id) mcp_error(id, -32602, "unknown tool"); } else { const char *message = NULL; char title[200] = "", tags[200] = "", topic[160] = ""; int prio = cfg.priority; char idout[64] = "", err[512] = ""; char out[1200]; if (args && yyjson_is_obj(args)) { yyjson_val *m = yyjson_obj_get(args, "message"); yyjson_val *t = yyjson_obj_get(args, "title"); yyjson_val *p = yyjson_obj_get(args, "priority"); yyjson_val *g = yyjson_obj_get(args, "tags"); yyjson_val *o = yyjson_obj_get(args, "topic"); message = yyjson_is_str(m) ? yyjson_get_str(m) : NULL; if (yyjson_is_str(t)) snprintf(title, sizeof title, "%s", yyjson_get_str(t)); if (yyjson_is_str(g)) snprintf(tags, sizeof tags, "%s", yyjson_get_str(g)); if (yyjson_is_str(o)) snprintf(topic, sizeof topic, "%s", yyjson_get_str(o)); if (yyjson_is_int(p)) { int x = (int)yyjson_get_int(p); if (x >= 1 && x <= 5) prio = x; } } if (!message || !*message) { if (has_id) mcp_error(id, -32602, "ntfy_send requires a non-empty 'message'"); } else { const char *use_topic = topic[0] ? topic : (cfg.publish_topic[0] ? cfg.publish_topic : cfg.topic); if (!use_topic[0]) { if (has_id) mcp_error(id, -32603, "no topic configured: open the ntfy plugin UI or set NTFY_TOPIC"); } else if (ntfy_publish(&cfg, use_topic, message, title, prio, tags, idout, sizeof idout, err, sizeof err) != 0) { snprintf(out, sizeof out, "ntfy_send failed: %s", err); if (has_id) mcp_tool_result(id, out, 1); } else { if (idout[0]) sx_ntfy_sent_note(idout); snprintf(out, sizeof out, "published to %s (id %s, priority %d)", use_topic, idout[0] ? idout : "?", prio); if (has_id) mcp_tool_result(id, out, 0); } } } } else { if (has_id) mcp_error(id, -32601, "method not found"); } yyjson_doc_free(doc); } return 0; } static int mode_schema(void) { fputs(MCP_TOOLS_JSON, stdout); fputc('\n', stdout); fflush(stdout); return 0; } /* ------------------------------------------------------------------ */ /* identity + pairing (shared by daemon and UI) */ /* ------------------------------------------------------------------ */ /* * ntfy has no sender identity: the optional "user" field is the publisher's * own claim (it is only populated by a server that authenticates the * publisher, which plain topics do not), and tags are free text. The * connector therefore derives a stable, opaque identity from everything the * publisher controls and treats it as a NAME TO APPROVE, never as an * authentication result. */ static void identity_of(const char *topic, const char *user, const char *tags, char out[SX_NTFY_IDENTITY_LEN + 1]) { char material[512]; char joined[256] = ""; size_t o = 0; if (tags && *tags) { const char *t = tags; for (; *t && o + 1 < sizeof joined; t++) if ((unsigned char)*t >= 0x20) joined[o++] = (char)tolower((unsigned char)*t); joined[o] = '\0'; } snprintf(material, sizeof material, "v1|%s|%s|%s", topic ? topic : "", user ? user : "", joined); sx_sha256_hex(material, strlen(material), out); } static void identity_label(const char *user, const char *tags, const char *topic, char out[160]) { if (user && *user) { snprintf(out, 160, "user=%s tags=%s topic=%s", user, tags ? tags : "-", topic ? topic : "-"); } else if (tags && *tags) { snprintf(out, 160, "tags=%s topic=%s", tags, topic ? topic : "-"); } else { snprintf(out, 160, "topic=%s (anonymous)", topic ? topic : "-"); } } static const char *g_challenge_prefix = "SCORPIOX BOT pairing"; /* Posts the pairing challenge onto the REPLY topic. Rate limited: one * challenge per identity per 10 minutes so a spammer cannot make us publish * unbounded notifications. */ static void send_challenge(sx_ntfy_config *cfg, const char *topic, const char *code, int retry_after_min) { char msg[420], title[80], err[256]; char idout[64]; snprintf(title, sizeof title, "%s: pairing required", g_challenge_prefix); snprintf(msg, sizeof msg, "This topic is not paired with this SCORPIOX BOT node yet. " "To pair it, open the ntfy plugin UI on this node and approve the request, " "or reply on this same topic with exactly: PAIR %s", code); if (retry_after_min > 0) { char extra[120]; snprintf(extra, sizeof extra, " (this challenge repeats at most once every %d minutes)", retry_after_min); strncat(msg, extra, sizeof msg - strlen(msg) - 1); } if (ntfy_publish(cfg, cfg->publish_topic[0] ? cfg->publish_topic : topic, msg, title, 3, "lock", idout, sizeof idout, err, sizeof err) != 0) sx_ntfy_logf("challenge publish failed: %s", err); else if (idout[0]) sx_ntfy_sent_note(idout); } /* Recognises "PAIR " (allowing polite whitespace / a trailing period) * on the subscribe topic. Returns 1 when the text is a pairing submission. */ static int parse_pair_command(const char *text, char *code_out, size_t capsz) { const char *p = text; size_t i = 0; while (*p && isspace((unsigned char)*p)) p++; if (strncasecmp(p, "PAIR", 4) != 0) return 0; p += 4; if (!isspace((unsigned char)*p)) return 0; while (*p && isspace((unsigned char)*p)) p++; while (*p && i + 1 < capsz && !isspace((unsigned char)*p)) { if (!isalnum((unsigned char)*p)) return 0; code_out[i++] = (char)toupper((unsigned char)*p++); } while (*p && isspace((unsigned char)*p)) p++; if (*p == '.') p++; if (*p != '\0') return 0; code_out[i] = '\0'; return i >= 4 && i <= 16; } /* ------------------------------------------------------------------ */ /* mode 3: --daemon (channel gateway) */ /* ------------------------------------------------------------------ */ #if !defined(_WIN32) static volatile sig_atomic_t g_stop = 0; static void on_stop_sig(int sig) { (void)sig; g_stop = 1; } #define STOP_REQUESTED() (g_stop != 0) /* A sleep that wakes early when a signal arrived: a daemon asked to stop * must stop in well under a second, not after its poll interval. */ static void stop_sleep(long long ms) { long long until = sx_now_ms() + ms; while (!STOP_REQUESTED() && sx_now_ms() < until) { struct timespec ts; long left = (long)(until - sx_now_ms()); if (left <= 0) break; if (left > 100) left = 100; ts.tv_sec = left / 1000; ts.tv_nsec = (left % 1000) * 1000000L; nanosleep(&ts, NULL); } } #else static volatile LONG g_stop_win = 0; static BOOL WINAPI win_console_ctrl(DWORD type) { (void)type; InterlockedExchange(&g_stop_win, 1); return TRUE; } #define STOP_REQUESTED() (InterlockedCompareExchange(&g_stop_win, 0, 0) != 0) static void stop_sleep(long long ms) { long long until = sx_now_ms() + ms; while (!STOP_REQUESTED() && sx_now_ms() < until) Sleep(50); } #endif /* POSTs one inbound message to the node API. Returns 0 on success. */ static int bot_post_inbox(const sx_ntfy_config *cfg, const char *text, char *err, size_t errsz) { sx_url u; sx_conn c; char path[1200], body[16600], hdrs2[360]; const char *hdrs[3]; int status = 0; char *rbody = NULL; size_t rlen = 0; char enc_session[560]; yyjson_mut_doc *doc; yyjson_mut_val *root; char *txt; size_t sz; if (sx_url_parse(cfg->bot_api_url, &u, err, errsz) != 0) return -1; if (!u.tls && strcmp(u.host, "127.0.0.1") && strcmp(u.host, "localhost")) { snprintf(err, errsz, "refusing to send the node password to a non-loopback host"); return -1; } sx_url_encode(cfg->target_session, enc_session, sizeof enc_session); snprintf(path, sizeof path, "/inbox?id=%s&mode=queue", enc_session); doc = yyjson_mut_doc_new(NULL); root = yyjson_mut_obj(doc); yyjson_mut_doc_set_root(doc, root); yyjson_mut_obj_add_strcpy(doc, root, "text", text); yyjson_mut_obj_add_strcpy(doc, root, "mode", "queue"); txt = yyjson_mut_write(doc, 0, &sz); yyjson_mut_doc_free(doc); if (!txt) { snprintf(err, errsz, "cannot serialise inbox payload"); return -1; } if (sz >= sizeof body) { free(txt); snprintf(err, errsz, "message too large for the inbox bridge"); return -1; } memcpy(body, txt, sz); body[sz] = '\0'; free(txt); sx_conn_init(&c); if (sx_conn_open(&c, &u, NULL, NULL, NULL, 0, 5000, err, errsz) != 0) return -1; hdrs[0] = "Content-Type: application/json"; if (cfg->bot_password[0]) { snprintf(hdrs2, sizeof hdrs2, "X-Bot-Password: %s", cfg->bot_password); hdrs[1] = hdrs2; hdrs[2] = NULL; } else { hdrs[1] = NULL; } if (sx_http_request(&c, "POST", path, hdrs, body, strlen(body), &status, &rbody, &rlen, err, errsz) != 0) { sx_conn_close(&c); return -1; } sx_conn_close(&c); if (status < 200 || status >= 300) { snprintf(err, errsz, "node /inbox answered %d%s%s", status, (rbody && rbody[0]) ? ": " : "", (rbody && rbody[0]) ? rbody : ""); free(rbody); return -1; } free(rbody); (void)u; return 0; } /* * Polls GET /conversation?id=&after= and returns the newest * assistant message after the cursor. Cursor polling (not SSE) is the * outbound mechanism on purpose: /hashes_sse is a live stream with no * catch-up, so a daemon that restarts mid-turn would miss the reply forever; * the events-backed conversation endpoint always answers from the persisted * sequence, and the cursor lives in status.json across restarts. */ static void poll_assistant(const sx_ntfy_config *cfg, long long *cursor, char *reply, size_t capsz, long long *ts_out) { sx_url u; sx_conn c; char path[1200], hdrs2[360]; const char *hdrs[3]; int status = 0; char *body = NULL; size_t blen = 0; char err[256] = ""; char enc_session[560]; yyjson_doc *doc; yyjson_val *root, *msgs; reply[0] = '\0'; if (ts_out) *ts_out = 0; if (sx_url_parse(cfg->bot_api_url, &u, err, sizeof err) != 0) return; if (!u.tls && strcmp(u.host, "127.0.0.1") && strcmp(u.host, "localhost")) return; sx_url_encode(cfg->target_session, enc_session, sizeof enc_session); snprintf(path, sizeof path, "/conversation?id=%s&after=%lld&limit=100", enc_session, *cursor); sx_conn_init(&c); if (sx_conn_open(&c, &u, NULL, NULL, NULL, 0, 5000, err, sizeof err) != 0) { sx_conn_close(&c); return; } hdrs[0] = "Accept: application/json"; if (cfg->bot_password[0]) { snprintf(hdrs2, sizeof hdrs2, "X-Bot-Password: %s", cfg->bot_password); hdrs[1] = hdrs2; hdrs[2] = NULL; } else hdrs[1] = NULL; if (sx_http_request(&c, "GET", path, hdrs, NULL, 0, &status, &body, &blen, err, sizeof err) != 0) { sx_conn_close(&c); return; } sx_conn_close(&c); if (status != 200 || !body) { free(body); return; } doc = yyjson_read(body, blen, 0); free(body); if (!doc) return; root = yyjson_doc_get_root(doc); msgs = yyjson_obj_get(root, "messages"); if (yyjson_is_arr(msgs)) { size_t i, max; yyjson_val *m; long long start_index = 0; yyjson_val *si = yyjson_obj_get(root, "start_index"); if (yyjson_is_int(si)) start_index = yyjson_get_sint(si); else if (yyjson_is_uint(si)) start_index = (long long)yyjson_get_uint(si); /* Walk the messages; the seq of message k is start_index + k + 1 * (the endpoint emits after+1 .. end). Keep the LAST assistant one. */ i = 0; yyjson_arr_foreach(msgs, i, max, m) { long long seq = start_index + (long long)i + 1; yyjson_val *rv = yyjson_obj_get(m, "role"); yyjson_val *cv = yyjson_obj_get(m, "content"); yyjson_val *tv = yyjson_obj_get(m, "timestamp_ms"); const char *role = yyjson_is_str(rv) ? yyjson_get_str(rv) : ""; const char *content = yyjson_is_str(cv) ? yyjson_get_str(cv) : ""; int assistant_like = role && *role && strcmp(role, "user") != 0 && strcmp(role, "tool_use") != 0 && strcmp(role, "tool_result") != 0 && strcmp(role, "thinking") != 0 && strcmp(role, "info") != 0 && strcmp(role, "unknown") != 0; if (seq > *cursor) *cursor = seq; if (!assistant_like || !content[0]) continue; snprintf(reply, capsz, "%s", content); if (ts_out && yyjson_is_int(tv)) *ts_out = yyjson_get_sint(tv); } } yyjson_doc_free(doc); } /* one record from the NDJSON stream */ typedef struct { char id[48]; char event[24]; char topic[160]; char title[200]; char message[8000]; char user[120]; char tags[200]; long long time_sec; int priority; } ntfy_event; static int parse_event_line(const char *line, ntfy_event *ev) { yyjson_doc *doc; yyjson_val *root, *v; memset(ev, 0, sizeof *ev); while (*line && isspace((unsigned char)*line)) line++; if (*line != '{') return 0; /* keepalive / comment */ doc = yyjson_read(line, strlen(line), 0); if (!doc) return 0; root = yyjson_doc_get_root(doc); if (!yyjson_is_obj(root)) { yyjson_doc_free(doc); return 0; } #define EVSTR(field, key) do { v = yyjson_obj_get(root, key); \ if (yyjson_is_str(v)) snprintf(ev->field, sizeof ev->field, "%s", yyjson_get_str(v)); } while (0) EVSTR(id, "id"); EVSTR(event, "event"); EVSTR(topic, "topic"); EVSTR(title, "title"); EVSTR(message, "message"); EVSTR(user, "user"); v = yyjson_obj_get(root, "tags"); if (yyjson_is_arr(v)) { /* join tags with commas -- they participate in the identity */ size_t i, max; yyjson_val *t; size_t o = 0; ev->tags[0] = '\0'; yyjson_arr_foreach(v, i, max, t) { const char *s = yyjson_is_str(t) ? yyjson_get_str(t) : NULL; if (!s) continue; if (o) { if (o + 1 < sizeof ev->tags) ev->tags[o++] = ','; } while (*s && o + 1 < sizeof ev->tags) ev->tags[o++] = *s++; ev->tags[o] = '\0'; } } else if (yyjson_is_str(v)) { snprintf(ev->tags, sizeof ev->tags, "%s", yyjson_get_str(v)); } #undef EVSTR v = yyjson_obj_get(root, "time"); if (yyjson_is_int(v)) ev->time_sec = yyjson_get_sint(v); else if (yyjson_is_uint(v)) ev->time_sec = (long long)yyjson_get_uint(v); v = yyjson_obj_get(root, "priority"); if (yyjson_is_int(v)) ev->priority = (int)yyjson_get_int(v); yyjson_doc_free(doc); return ev->event[0] ? 1 : 0; } static int event_is_own(const ntfy_event *ev, const sx_ntfy_config *cfg) { /* 1. we published it (id ledger), 2. it carries our tag, 3. it is our * visible reply prefix. Any one is enough -- all three together also make * a hand-written imitation of our own replies stop the loop instead of * starting one. */ if (ev->id[0] && sx_ntfy_sent_has(ev->id)) return 1; if (strstr(ev->tags, SELF_TAG)) return 1; if (cfg->reply_prefix[0] && !strncmp(ev->message, cfg->reply_prefix, strlen(cfg->reply_prefix))) return 1; return 0; } static int run_daemon(void) { sx_ntfy_config cfg; sx_ntfy_status st; char cerr[256]; long long backoff; int first = 1; if (sx_ntfy_config_load(&cfg, cerr, sizeof cerr) != 0) { fprintf(stderr, "plugin_ntfy --daemon: %s\n", cerr); return 2; } { char verr[256]; if (sx_ntfy_config_validate(&cfg, verr, sizeof verr) != 0) { fprintf(stderr, "plugin_ntfy --daemon: %s\n", verr); return 2; } } if (sx_ntfy_daemon_running()) { fprintf(stderr, "plugin_ntfy --daemon: another daemon is already running (daemon.pid)\n"); return 3; } sx_ntfy_log_open(1); sx_ntfy_pidfile_write( #if defined(_WIN32) (long)_getpid() #else (long)getpid() #endif ); #if !defined(_WIN32) { struct sigaction sa; memset(&sa, 0, sizeof sa); sa.sa_handler = on_stop_sig; sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); signal(SIGPIPE, SIG_IGN); } #else SetConsoleCtrlHandler(win_console_ctrl, TRUE); #endif sx_ntfy_status_load(&st); st.started_at = sx_ntfy_now_epoch(); st.configured = 1; snprintf(st.topic, sizeof st.topic, "%s", cfg.topic); snprintf(st.publish_topic, sizeof st.publish_topic, "%s", cfg.publish_topic); snprintf(st.target_session, sizeof st.target_session, "%s", cfg.target_session); snprintf(st.server_url, sizeof st.server_url, "%s", cfg.server_url); st.allow_all = cfg.allow_all; st.pairing_code_enabled = cfg.pairing_code_enabled; st.markdown = cfg.markdown; st.has_bearer = cfg.bearer_token[0] ? 1 : 0; st.has_bot_password = cfg.bot_password[0] ? 1 : 0; st.tls_insecure = sx_ntfy_tls_insecure(); st.pinned = cfg.allowed_pins[0] ? 1 : 0; if (st.conv_cursor <= 0) { /* * First run. Seed the reply cursor at the CURRENT tip of the * conversation and throw the answer away, so a daemon started this * afternoon cannot publish a reply the agent wrote this morning. * (poll_assistant writes into `discard`, which is 1 byte, so nothing * survives; only the cursor moves.) */ char discard[1]; long long tip = -1; poll_assistant(&cfg, &tip, discard, sizeof discard, NULL); st.conv_cursor = tip > 0 ? tip : 0; st.last_message_time = sx_ntfy_now_epoch(); sx_ntfy_logf("reply cursor seeded at %lld", st.conv_cursor); } sx_ntfy_status_save(&st); if (st.tls_insecure) sx_ntfy_logf("WARNING NTFY_TLS_INSECURE=1 is set: certificate verification is DISABLED"); sx_ntfy_logf("daemon start topic=%s publish=%s session=%s server=%s allow_all=%d cursor=%lld", cfg.topic, cfg.publish_topic, cfg.target_session, cfg.server_url, cfg.allow_all, st.conv_cursor); backoff = cfg.reconnect_min_ms; while (!STOP_REQUESTED()) { sx_url u; sx_conn c; char path[600]; const char *hdrs[3]; int status = 0; char err[512] = ""; /* static, not stack: this is the one big buffer in the process and a * daemon must not careen into a guard page because of it */ static char line[SX_NTFY_STREAM_CAP + 1]; long long since = st.last_message_time > 0 ? st.last_message_time : 0; sx_conn_init(&c); if (sx_url_parse(cfg.server_url, &u, err, sizeof err) != 0) { sx_ntfy_logf("bad server_url: %s", err); stop_sleep(cfg.reconnect_max_ms); continue; } { char enc[320]; sx_url_encode(cfg.topic, enc, sizeof enc); if (since > 0) snprintf(path, sizeof path, "/%s/json?since=%lld", enc, since); else snprintf(path, sizeof path, "/%s/json", enc); } if (sx_conn_open(&c, &u, NULL, cfg.allowed_pins[0] ? cfg.allowed_pins : NULL, cfg.ca_file[0] ? cfg.ca_file : NULL, sx_ntfy_tls_insecure(), 15000, err, sizeof err) != 0) { sx_ntfy_logf("subscribe connect failed: %s (retry in %lldms)", err, backoff); st.error_count++; snprintf(st.last_error, sizeof st.last_error, "%s", err); sx_ntfy_status_save(&st); sx_conn_close(&c); stop_sleep(backoff); backoff = backoff * 2 < cfg.reconnect_max_ms ? backoff * 2 : cfg.reconnect_max_ms; continue; } hdrs[0] = "Accept: application/x-ndjson"; hdrs[1] = NULL; if (sx_http_open_stream(&c, "GET", path, hdrs, &status, err, sizeof err) != 0) { sx_ntfy_logf("subscribe request failed: %s (retry in %lldms)", err, backoff); st.error_count++; snprintf(st.last_error, sizeof st.last_error, "%s", err); sx_ntfy_status_save(&st); sx_conn_close(&c); stop_sleep(backoff); backoff = backoff * 2 < cfg.reconnect_max_ms ? backoff * 2 : cfg.reconnect_max_ms; continue; } if (status != 200) { sx_ntfy_logf("subscribe answered %d (retry in %lldms)", status, backoff); st.error_count++; snprintf(st.last_error, sizeof st.last_error, "subscribe http %d", status); sx_ntfy_status_save(&st); sx_conn_close(&c); stop_sleep(backoff); backoff = backoff * 2 < cfg.reconnect_max_ms ? backoff * 2 : cfg.reconnect_max_ms; continue; } backoff = cfg.reconnect_min_ms; st.connected = 1; st.connect_count++; st.last_seen_at = sx_ntfy_now_epoch(); snprintf(st.last_error, sizeof st.last_error, "%s", ""); sx_ntfy_status_save(&st); if (first) { sx_ntfy_logf("subscribed to %s/%s", cfg.server_url, cfg.topic); first = 0; } while (!STOP_REQUESTED()) { ntfy_event ev; int rr; /* the assistant reply is checked EVERY tick, not only after the * stream breaks: the ntfy subscription is long-lived and the * agent's answer arrives while it is still open. */ { long long cursor = st.conv_cursor; char reply[12000]; long long rts = 0; poll_assistant(&cfg, &cursor, reply, sizeof reply, &rts); if (cursor > st.conv_cursor) st.conv_cursor = cursor; if (reply[0]) { char tosend[12300]; char idout[64] = "", err3[300] = ""; if (cfg.reply_prefix[0]) snprintf(tosend, sizeof tosend, "%s%s", cfg.reply_prefix, reply); else snprintf(tosend, sizeof tosend, "%s", reply); if (ntfy_publish(&cfg, cfg.publish_topic[0] ? cfg.publish_topic : cfg.topic, tosend, cfg.title_prefix[0] ? cfg.title_prefix : NULL, cfg.priority, cfg.tags[0] ? cfg.tags : "robot", idout, sizeof idout, err3, sizeof err3) == 0) { if (idout[0]) sx_ntfy_sent_note(idout); st.outbound_count++; st.last_outbound_at = sx_ntfy_now_epoch(); sx_ntfy_logf("outbound reply published (id %s, %zu bytes)", idout[0] ? idout : "?", strlen(tosend)); } else { st.error_count++; snprintf(st.last_error, sizeof st.last_error, "publish: %s", err3); sx_ntfy_logf("reply publish failed: %s", err3); } st.last_seen_at = sx_ntfy_now_epoch(); sx_ntfy_status_save(&st); } } rr = sx_http_readline(&c, line, sizeof line, cfg.idle_timeout_ms); if (rr < 0) { sx_ntfy_logf("stream read timeout/error, reconnecting"); break; } if (rr == 0) { sx_ntfy_logf("stream closed by server, reconnecting"); break; } if (!parse_event_line(line, &ev)) continue; /* keepalive / comment */ st.last_seen_at = sx_ntfy_now_epoch(); if (ev.time_sec > st.last_message_time) st.last_message_time = ev.time_sec; if (strcmp(ev.event, "message") != 0) continue; /* open/closed/etc */ if (!ev.message[0]) continue; snprintf(st.last_event, sizeof st.last_event, "%s", ev.event); /* ---- anti-self-loop: never forward our own publish ---- */ if (event_is_own(&ev, &cfg)) { st.blocked_count++; /* counted, deliberately quiet */ continue; } /* only messages from the subscribe topic (a server may multiplex) */ if (ev.topic[0] && strcmp(ev.topic, cfg.topic) != 0) continue; /* ---- pairing command? ---- */ { char code[24]; if (cfg.pairing_code_enabled && parse_pair_command(ev.message, code, sizeof code)) { char key[SX_NTFY_IDENTITY_LEN + 1]; char label[160]; identity_of(ev.topic[0] ? ev.topic : cfg.topic, ev.user, ev.tags, key); identity_label(ev.user, ev.tags, ev.topic[0] ? ev.topic : cfg.topic, label); if (sx_ntfy_pending_find_code(code, key, sizeof key)) { sx_ntfy_approved_add(key, label, 1); sx_ntfy_pending_remove(key); { char idout[64], e2[256]; char msg[200]; snprintf(msg, sizeof msg, "Paired. Your messages now reach the agent."); if (ntfy_publish(&cfg, cfg.publish_topic[0] ? cfg.publish_topic : cfg.topic, msg, "SCORPIOX BOT pairing", 3, "white_check_mark", idout, sizeof idout, e2, sizeof e2) == 0 && idout[0]) sx_ntfy_sent_note(idout); } sx_ntfy_logf("paired via code: %s (%s)", key, label); st.last_seen_at = sx_ntfy_now_epoch(); sx_ntfy_status_save(&st); } else { st.blocked_count++; sx_ntfy_logf("wrong pairing code from %s", key); } continue; } } /* ---- default-deny gate ---- */ { char key[SX_NTFY_IDENTITY_LEN + 1]; char label[160]; identity_of(ev.topic[0] ? ev.topic : cfg.topic, ev.user, ev.tags, key); identity_label(ev.user, ev.tags, ev.topic[0] ? ev.topic : cfg.topic, label); if (!cfg.allow_all && !sx_ntfy_approved_has(key)) { sx_ntfy_pending *items = NULL; size_t n = 0, cap = 64; sx_ntfy_pending *pe; sx_ntfy_pending_load(&items, &n); pe = sx_ntfy_pending_touch(&items, &n, &cap, key, label, ev.message); if (pe) { long long ago = st.last_seen_at - pe->last_challenge_at; if (pe->last_challenge_at == 0 || ago > 600) { send_challenge(&cfg, cfg.topic, pe->code, 10); pe->last_challenge_at = st.last_seen_at; } sx_ntfy_pending_save(items, n); st.pending_count = (long long)n; } free(items); st.blocked_count++; st.last_seen_at = sx_ntfy_now_epoch(); sx_ntfy_status_save(&st); sx_ntfy_logf("blocked unapproved sender %s (%s)", key, label); continue; } if (!cfg.allow_all) sx_ntfy_approved_touch_seen(key); /* ---- approved: bridge to the agent ---- */ { char text[9300]; char ibody[8000]; char err2[300] = ""; size_t sn = 0; const char *src = ev.message; /* sanitise: strip control chars except tab/newline, cap */ for (; *src && sn + 1 < sizeof ibody; src++) { unsigned char ch = (unsigned char)*src; if (ch == '\t' || ch == '\n' || (ch >= 0x20 && ch != 0x7F)) ibody[sn++] = (char)ch; } ibody[sn] = '\0'; if (ev.user[0] || ev.tags[0]) snprintf(text, sizeof text, "[%s via ntfy%s%s%s] %s", ev.user[0] ? ev.user : "anonymous", ev.tags[0] ? " tags=" : "", ev.tags[0] ? ev.tags : "", ev.tags[0] ? "" : "", ibody); else snprintf(text, sizeof text, "[ntfy] %s", ibody); if (ev.title[0]) { char t2[9500]; snprintf(t2, sizeof t2, "%s\n%s", ev.title, text); cp_trunc(text, sizeof text, t2); } if (bot_post_inbox(&cfg, text, err2, sizeof err2) != 0) { st.error_count++; snprintf(st.last_error, sizeof st.last_error, "inbox: %s", err2); sx_ntfy_logf("inbox post failed: %s", err2); } else { st.inbound_count++; st.last_inbound_at = sx_ntfy_now_epoch(); sx_ntfy_logf("inbound -> /inbox (%zu bytes) from %s", strlen(text), key); } sx_ntfy_status_save(&st); } } } st.connected = 0; st.last_seen_at = sx_ntfy_now_epoch(); sx_ntfy_status_save(&st); sx_conn_close(&c); /* ---- outbound: deliver any new assistant reply ---- */ if (!STOP_REQUESTED()) { long long cursor = st.conv_cursor; char reply[12000]; long long rts = 0; poll_assistant(&cfg, &cursor, reply, sizeof reply, &rts); if (cursor > st.conv_cursor) st.conv_cursor = cursor; if (reply[0]) { char tosend[12300]; char idout[64] = "", err3[300] = ""; if (cfg.reply_prefix[0]) snprintf(tosend, sizeof tosend, "%s%s", cfg.reply_prefix, reply); else snprintf(tosend, sizeof tosend, "%s", reply); if (strlen(reply) > 12000 - 32) tosend[sizeof tosend - 1] = '\0'; if (ntfy_publish(&cfg, cfg.publish_topic[0] ? cfg.publish_topic : cfg.topic, tosend, cfg.title_prefix[0] ? cfg.title_prefix : NULL, cfg.priority, cfg.tags[0] ? cfg.tags : "robot", idout, sizeof idout, err3, sizeof err3) == 0) { if (idout[0]) sx_ntfy_sent_note(idout); st.outbound_count++; st.last_outbound_at = sx_ntfy_now_epoch(); sx_ntfy_logf("outbound reply published (id %s, %zu bytes)", idout[0] ? idout : "?", strlen(tosend)); } else { st.error_count++; snprintf(st.last_error, sizeof st.last_error, "publish: %s", err3); sx_ntfy_logf("reply publish failed: %s", err3); } st.last_seen_at = sx_ntfy_now_epoch(); sx_ntfy_status_save(&st); } } if (!STOP_REQUESTED()) stop_sleep(cfg.reply_poll_ms); } st.connected = 0; st.last_seen_at = sx_ntfy_now_epoch(); sx_ntfy_status_save(&st); sx_ntfy_pidfile_remove(); sx_ntfy_logf("daemon stopped"); return 0; } /* ------------------------------------------------------------------ */ /* mode 4: ?action=... node JSON API (behind require_node_auth) */ /* ------------------------------------------------------------------ */ typedef struct { yyjson_mut_doc *doc; yyjson_mut_val *root; } jout; static void jout_init(jout *j) { j->doc = yyjson_mut_doc_new(NULL); j->root = yyjson_mut_obj(j->doc); yyjson_mut_doc_set_root(j->doc, j->root); yyjson_mut_obj_add_bool(j->doc, j->root, "ok", true); } static void jout_done(jout *j) { char *txt = yyjson_mut_write(j->doc, 0, NULL); json_respond(200, txt ? txt : "{\"ok\":false,\"error\":\"serialise failed\"}"); free(txt); yyjson_mut_doc_free(j->doc); } static void jfail(int status, const char *err) { char esc[1024]; char buf[1200]; sx_ntfy_json_escape(err ? err : "error", esc, sizeof esc); snprintf(buf, sizeof buf, "{\"ok\":false,\"error\":\"%s\"}", esc); json_respond(status, buf); } static void status_obj(jout *j, const sx_ntfy_status *st, const sx_ntfy_config *cfg, int running) { yyjson_mut_doc *d = j->doc; yyjson_mut_val *o = yyjson_mut_obj(d); yyjson_mut_obj_add_val(d, j->root, "status", o); yyjson_mut_obj_add_sint(d, o, "started_at", st->started_at); yyjson_mut_obj_add_sint(d, o, "last_seen_at", st->last_seen_at); yyjson_mut_obj_add_sint(d, o, "last_inbound_at", st->last_inbound_at); yyjson_mut_obj_add_sint(d, o, "last_outbound_at", st->last_outbound_at); yyjson_mut_obj_add_sint(d, o, "inbound_count", st->inbound_count); yyjson_mut_obj_add_sint(d, o, "outbound_count", st->outbound_count); yyjson_mut_obj_add_sint(d, o, "blocked_count", st->blocked_count); yyjson_mut_obj_add_sint(d, o, "pending_count", st->pending_count); yyjson_mut_obj_add_sint(d, o, "connect_count", st->connect_count); yyjson_mut_obj_add_sint(d, o, "error_count", st->error_count); yyjson_mut_obj_add_int(d, o, "connected", running ? st->connected : 0); yyjson_mut_obj_add_int(d, o, "running", running); yyjson_mut_obj_add_sint(d, o, "conv_cursor", st->conv_cursor); yyjson_mut_obj_add_sint(d, o, "last_message_time", st->last_message_time); yyjson_mut_obj_add_strcpy(d, o, "last_error", st->last_error); yyjson_mut_obj_add_strcpy(d, o, "last_event", st->last_event); yyjson_mut_obj_add_strcpy(d, o, "topic", cfg->topic); yyjson_mut_obj_add_strcpy(d, o, "publish_topic", cfg->publish_topic[0] ? cfg->publish_topic : cfg->topic); yyjson_mut_obj_add_strcpy(d, o, "target_session", cfg->target_session); yyjson_mut_obj_add_strcpy(d, o, "server_url", cfg->server_url); yyjson_mut_obj_add_bool(d, o, "configured", cfg->topic[0] && cfg->target_session[0]); yyjson_mut_obj_add_bool(d, o, "allow_all", cfg->allow_all ? true : false); yyjson_mut_obj_add_bool(d, o, "pairing_code_enabled", cfg->pairing_code_enabled ? true : false); yyjson_mut_obj_add_bool(d, o, "markdown", cfg->markdown ? true : false); /* write-only secrets: only ever a boolean comes back */ yyjson_mut_obj_add_bool(d, o, "has_bearer", cfg->bearer_token[0] ? true : false); yyjson_mut_obj_add_bool(d, o, "has_bot_password", cfg->bot_password[0] ? true : false); yyjson_mut_obj_add_bool(d, o, "tls_insecure", sx_ntfy_tls_insecure() ? true : false); yyjson_mut_obj_add_bool(d, o, "pinned", cfg->allowed_pins[0] ? true : false); yyjson_mut_obj_add_bool(d, o, "tls", strstr(cfg->server_url, "https://") ? true : false); yyjson_mut_obj_add_int(d, o, "priority", cfg->priority); yyjson_mut_obj_add_strcpy(d, o, "tags", cfg->tags); yyjson_mut_obj_add_strcpy(d, o, "reply_prefix", cfg->reply_prefix); yyjson_mut_obj_add_strcpy(d, o, "title_prefix", cfg->title_prefix); } static void cfg_obj(jout *j, const sx_ntfy_config *cfg) { yyjson_mut_doc *d = j->doc; yyjson_mut_val *o = yyjson_mut_obj(d); yyjson_mut_obj_add_val(d, j->root, "config", o); yyjson_mut_obj_add_strcpy(d, o, "server_url", cfg->server_url); yyjson_mut_obj_add_strcpy(d, o, "topic", cfg->topic); yyjson_mut_obj_add_strcpy(d, o, "publish_topic", cfg->publish_topic); yyjson_mut_obj_add_strcpy(d, o, "bot_api_url", cfg->bot_api_url); yyjson_mut_obj_add_strcpy(d, o, "target_session", cfg->target_session); yyjson_mut_obj_add_strcpy(d, o, "tags", cfg->tags); yyjson_mut_obj_add_strcpy(d, o, "reply_prefix", cfg->reply_prefix); yyjson_mut_obj_add_strcpy(d, o, "title_prefix", cfg->title_prefix); yyjson_mut_obj_add_strcpy(d, o, "ca_file", cfg->ca_file); yyjson_mut_obj_add_int(d, o, "priority", cfg->priority); yyjson_mut_obj_add_int(d, o, "markdown", cfg->markdown); yyjson_mut_obj_add_int(d, o, "allow_all", cfg->allow_all); yyjson_mut_obj_add_int(d, o, "pairing_code_enabled", cfg->pairing_code_enabled); yyjson_mut_obj_add_sint(d, o, "reply_poll_ms", cfg->reply_poll_ms); yyjson_mut_obj_add_sint(d, o, "idle_timeout_ms", cfg->idle_timeout_ms); yyjson_mut_obj_add_sint(d, o, "updated_at", cfg->updated_at); /* deliberately NOT serialised: bearer_token, bot_password, allowed_pins * (a pin list is not a secret, but echoing it invites copy-paste into a * config that trusts the wrong key; the UI shows "pinned" instead) */ } static void send_pending_list(jout *j) { sx_ntfy_pending *items = NULL; size_t n = 0, i; yyjson_mut_val *arr; sx_ntfy_pending_load(&items, &n); arr = yyjson_mut_arr(j->doc); yyjson_mut_obj_add_val(j->doc, j->root, "pending", arr); for (i = 0; i < n; i++) { yyjson_mut_val *o = yyjson_mut_obj(j->doc); yyjson_mut_arr_add_val(arr, o); yyjson_mut_obj_add_strcpy(j->doc, o, "key", items[i].key); yyjson_mut_obj_add_strcpy(j->doc, o, "label", items[i].label); yyjson_mut_obj_add_strcpy(j->doc, o, "code", items[i].code); yyjson_mut_obj_add_strcpy(j->doc, o, "sample", items[i].sample); yyjson_mut_obj_add_sint(j->doc, o, "first_seen", items[i].first_seen); yyjson_mut_obj_add_sint(j->doc, o, "last_seen", items[i].last_seen); yyjson_mut_obj_add_int(j->doc, o, "count", items[i].count); } free(items); } static void send_approved_list(jout *j) { sx_ntfy_approved *items = NULL; size_t n = 0, i; yyjson_mut_val *arr; sx_ntfy_approved_load(&items, &n); arr = yyjson_mut_arr(j->doc); yyjson_mut_obj_add_val(j->doc, j->root, "approved", arr); for (i = 0; i < n; i++) { yyjson_mut_val *o = yyjson_mut_obj(j->doc); yyjson_mut_arr_add_val(arr, o); yyjson_mut_obj_add_strcpy(j->doc, o, "key", items[i].key); yyjson_mut_obj_add_strcpy(j->doc, o, "label", items[i].label); yyjson_mut_obj_add_sint(j->doc, o, "added_at", items[i].added_at); yyjson_mut_obj_add_sint(j->doc, o, "last_seen", items[i].last_seen); yyjson_mut_obj_add_int(j->doc, o, "count", items[i].count); yyjson_mut_obj_add_int(j->doc, o, "via", items[i].via); } free(items); } static int valid_key(const char *k) { size_t i, n = strlen(k); if (n != SX_NTFY_IDENTITY_LEN) return 0; for (i = 0; i < n; i++) if (!isxdigit((unsigned char)k[i])) return 0; return 1; } static void mode_json(const char *qs) { char action[40] = ""; char tmp[8192]; yyjson_val *jroot = NULL; sx_ntfy_config cfg; char cerr[256]; int cfg_loaded; /* body first: a POST with a JSON body is what the UI sends */ if (is_post_request()) { char *body = read_post_body(); if (body && *body) { static yyjson_doc *keep; /* lives for the whole request */ keep = yyjson_read(body, strlen(body), 0); if (keep) jroot = yyjson_doc_get_root(keep); } } if (!req_field(qs, jroot, "action", action, sizeof action) && !jroot) snprintf(action, sizeof action, "status"); if (!action[0]) snprintf(action, sizeof action, "status"); trim_inplace(action); cfg_loaded = (sx_ntfy_config_load(&cfg, cerr, sizeof cerr) == 0); if (!cfg_loaded) sx_ntfy_config_defaults(&cfg); /* ---------------- read-only, useful before any configuration -------- */ if (!strcmp(action, "status")) { jout j; sx_ntfy_status st; jout_init(&j); sx_ntfy_status_load(&st); status_obj(&j, &st, &cfg, sx_ntfy_daemon_running()); yyjson_mut_obj_add_strcpy(j.doc, j.root, "version", PLUGIN_VER); yyjson_mut_obj_add_strcpy(j.doc, j.root, "id", PLUGIN_ID); yyjson_mut_obj_add_bool(j.doc, j.root, "tls_insecure_env", sx_ntfy_tls_insecure() ? true : false); jout_done(&j); return; } if (!strcmp(action, "config")) { jout j; jout_init(&j); cfg_obj(&j, &cfg); jout_done(&j); return; } if (!strcmp(action, "pending")) { jout j; jout_init(&j); send_pending_list(&j); jout_done(&j); return; } if (!strcmp(action, "approved")) { jout j; jout_init(&j); send_approved_list(&j); jout_done(&j); return; } if (!strcmp(action, "info")) { jout j; jout_init(&j); yyjson_mut_obj_add_strcpy(j.doc, j.root, "id", PLUGIN_ID); yyjson_mut_obj_add_strcpy(j.doc, j.root, "slug", PLUGIN_SLUG); yyjson_mut_obj_add_strcpy(j.doc, j.root, "version", PLUGIN_VER); yyjson_mut_obj_add_strcpy(j.doc, j.root, "kind", "hybrid"); yyjson_mut_obj_add_bool(j.doc, j.root, "mcp", true); yyjson_mut_obj_add_bool(j.doc, j.root, "daemon", true); yyjson_mut_obj_add_bool(j.doc, j.root, "menus", false); yyjson_mut_obj_add_strcpy(j.doc, j.root, "verified", "mock"); yyjson_mut_obj_add_strcpy(j.doc, j.root, "dir_note", "state in ~/.scorpiox/connectors/plugin_ntfy"); { char dir[1000]; if (sx_ntfy_dir(dir, sizeof dir) == 0) yyjson_mut_obj_add_strcpy(j.doc, j.root, "connector_dir", dir); } jout_done(&j); return; } /* ---------------- writes -------------------------------------------- */ if (!strcmp(action, "save")) { char v[1024]; jout j; char verr[256]; if (req_field(qs, jroot, "server_url", v, sizeof v) && v[0]) cp_trunc(cfg.server_url, sizeof cfg.server_url, v); if (req_field(qs, jroot, "topic", v, sizeof v)) cp_trunc(cfg.topic, sizeof cfg.topic, v); if (req_field(qs, jroot, "publish_topic", v, sizeof v)) cp_trunc(cfg.publish_topic, sizeof cfg.publish_topic, v); if (req_field(qs, jroot, "target_session", v, sizeof v)) cp_trunc(cfg.target_session, sizeof cfg.target_session, v); 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); if (req_field(qs, jroot, "tags", v, sizeof v)) cp_trunc(cfg.tags, sizeof cfg.tags, v); if (req_field(qs, jroot, "reply_prefix", v, sizeof v)) cp_trunc(cfg.reply_prefix, sizeof cfg.reply_prefix, v); if (req_field(qs, jroot, "title_prefix", v, sizeof v)) cp_trunc(cfg.title_prefix, sizeof cfg.title_prefix, v); if (req_field(qs, jroot, "ca_file", v, sizeof v)) cp_trunc(cfg.ca_file, sizeof cfg.ca_file, v); if (req_field(qs, jroot, "allowed_pins", v, sizeof v)) cp_trunc(cfg.allowed_pins, sizeof cfg.allowed_pins, v); /* a blank token field means "leave it alone"; an explicit __clear__ wipes * it, so the UI can forget a secret without the operator editing JSON */ if (req_field(qs, jroot, "bearer_token", v, sizeof v) && v[0]) { if (!strcmp(v, "__clear__")) cfg.bearer_token[0] = '\0'; else cp_trunc(cfg.bearer_token, sizeof cfg.bearer_token, v); } if (req_field(qs, jroot, "bot_password", v, sizeof v) && v[0]) { if (!strcmp(v, "__clear__")) cfg.bot_password[0] = '\0'; else cp_trunc(cfg.bot_password, sizeof cfg.bot_password, v); } if (req_field(qs, jroot, "priority", v, sizeof v) && v[0]) { int p = atoi(v); if (p < 1) p = 1; if (p > 5) p = 5; cfg.priority = p; } if (req_field(qs, jroot, "markdown", v, sizeof v)) cfg.markdown = is_truthy(v) ? 1 : 0; if (req_field(qs, jroot, "allow_all", v, sizeof v)) cfg.allow_all = is_truthy(v) ? 1 : 0; if (req_field(qs, jroot, "pairing_code_enabled", v, sizeof v)) cfg.pairing_code_enabled = is_truthy(v) ? 1 : 0; if (req_field(qs, jroot, "reply_poll_ms", v, sizeof v) && v[0]) { long long x = strtoll(v, NULL, 10); if (x >= 100 && x <= 60000) cfg.reply_poll_ms = x; } if (req_field(qs, jroot, "idle_timeout_ms", v, sizeof v) && v[0]) { long long x = strtoll(v, NULL, 10); if (x >= 2000 && x <= 300000) cfg.idle_timeout_ms = x; } if (!cfg.publish_topic[0]) cp_trunc(cfg.publish_topic, sizeof cfg.publish_topic, cfg.topic); /* Save what we were given even if not yet fully valid -- the operator * fills the form in stages; only start/test refuse an invalid config. */ { char serr[256]; if (sx_ntfy_config_save(&cfg, serr, sizeof serr) != 0) { jfail(500, serr); return; } } jout_init(&j); cfg_obj(&j, &cfg); yyjson_mut_obj_add_bool(j.doc, j.root, "valid", sx_ntfy_config_validate(&cfg, verr, sizeof verr) == 0); if (sx_ntfy_config_validate(&cfg, verr, sizeof verr) != 0) yyjson_mut_obj_add_strcpy(j.doc, j.root, "validation", verr); jout_done(&j); return; } if (!strcmp(action, "test")) { char err[512] = "", idout[64] = ""; char title[80], msg[200]; jout j; snprintf(title, sizeof title, "%s test", cfg.title_prefix[0] ? cfg.title_prefix : "SCORPIOX BOT"); snprintf(msg, sizeof msg, "plugin_ntfy test notification from this node. " "If you can read this, publishing works."); if (!cfg.topic[0] && !cfg.publish_topic[0]) { jfail(400, "set a topic first"); return; } if (ntfy_publish(&cfg, cfg.publish_topic[0] ? cfg.publish_topic : cfg.topic, msg, title, cfg.priority, "bell", idout, sizeof idout, err, sizeof err) != 0) { jfail(502, err); return; } if (idout[0]) sx_ntfy_sent_note(idout); jout_init(&j); yyjson_mut_obj_add_strcpy(j.doc, j.root, "published_id", idout); yyjson_mut_obj_add_strcpy(j.doc, j.root, "topic", cfg.publish_topic[0] ? cfg.publish_topic : cfg.topic); jout_done(&j); return; } if (!strcmp(action, "send")) { char msg[8000] = "", title[200] = "", tags[200] = "", topic[160] = ""; char prio[8] = "", idout[64] = "", err[512] = ""; int p = cfg.priority; jout j; req_field(qs, jroot, "message", msg, sizeof msg); req_field(qs, jroot, "title", title, sizeof title); req_field(qs, jroot, "tags", tags, sizeof tags); req_field(qs, jroot, "topic", topic, sizeof topic); if (req_field(qs, jroot, "priority", prio, sizeof prio) && prio[0]) { int x = atoi(prio); if (x >= 1 && x <= 5) p = x; } trim_inplace(msg); if (!msg[0]) { jfail(400, "message is required"); return; } if (!topic[0]) snprintf(topic, sizeof topic, "%s", cfg.publish_topic[0] ? cfg.publish_topic : cfg.topic); if (!topic[0]) { jfail(400, "no topic configured"); return; } if (ntfy_publish(&cfg, topic, msg, title[0] ? title : NULL, p, tags[0] ? tags : cfg.tags, idout, sizeof idout, err, sizeof err) != 0) { jfail(502, err); return; } if (idout[0]) sx_ntfy_sent_note(idout); jout_init(&j); yyjson_mut_obj_add_strcpy(j.doc, j.root, "published_id", idout); yyjson_mut_obj_add_strcpy(j.doc, j.root, "topic", topic); jout_done(&j); return; } if (!strcmp(action, "approve") || !strcmp(action, "unapprove")) { char key[SX_NTFY_IDENTITY_LEN + 4] = "", label[160] = "", code[24] = ""; jout j; int ok; req_field(qs, jroot, "key", key, sizeof key); req_field(qs, jroot, "label", label, sizeof label); trim_inplace(key); if (!key[0] && req_field(qs, jroot, "code", code, sizeof code)) { char k[SX_NTFY_IDENTITY_LEN + 1]; if (sx_ntfy_pending_find_code(code, k, sizeof k)) snprintf(key, sizeof key, "%s", k); } if (!valid_key(key)) { jfail(400, "key must be the 64-hex identity from ?action=pending"); return; } if (!strcmp(action, "approve")) { ok = sx_ntfy_approved_add(key, label, 0); if (ok == 0) sx_ntfy_pending_remove(key); } else { ok = sx_ntfy_approved_remove(key); } if (ok != 0) { jfail(500, "cannot write the pairing store"); return; } jout_init(&j); yyjson_mut_obj_add_strcpy(j.doc, j.root, "key", key); yyjson_mut_obj_add_strcpy(j.doc, j.root, "action", action); jout_done(&j); return; } if (!strcmp(action, "deny")) { char key[80] = ""; jout j; req_field(qs, jroot, "key", key, sizeof key); trim_inplace(key); if (!valid_key(key)) { jfail(400, "key must be the 64-hex identity from ?action=pending"); return; } if (sx_ntfy_pending_remove(key) != 0) { jfail(500, "cannot write the pairing queue"); return; } jout_init(&j); yyjson_mut_obj_add_strcpy(j.doc, j.root, "key", key); yyjson_mut_obj_add_strcpy(j.doc, j.root, "action", "deny"); jout_done(&j); return; } if (!strcmp(action, "logs")) { char path[1100]; char *buf = NULL; size_t len = 0; char tail[16000]; jout j; if (sx_ntfy_path(path, sizeof path, "daemon.log") != 0) { jfail(500, "connector dir unavailable"); return; } if (sx_ntfy_read_file(path, &buf, &len) != 0) { jout_init(&j); yyjson_mut_obj_add_strcpy(j.doc, j.root, "log", ""); yyjson_mut_obj_add_int(j.doc, j.root, "bytes", 0); jout_done(&j); return; } /* tail: last 16 KB, and never start mid-line */ { size_t start = len > sizeof tail - 1 ? len - (sizeof tail - 1) : 0; size_t n = len - start; while (start < len && buf[start] != '\n' && start < len - 80) start++; if (start < len && buf[start] == '\n') start++; n = len - start; if (n >= sizeof tail) n = sizeof tail - 1; memcpy(tail, buf + start, n); tail[n] = '\0'; } free(buf); jout_init(&j); yyjson_mut_obj_add_str(j.doc, j.root, "log", tail); yyjson_mut_obj_add_int(j.doc, j.root, "bytes", (int)len); jout_done(&j); return; } /* ---------------- start / stop -------------------------------------- */ if (!strcmp(action, "start")) { char verr[256]; jout j; if (sx_ntfy_daemon_running()) { jfail(409, "the daemon is already running"); return; } if (sx_ntfy_config_validate(&cfg, verr, sizeof verr) != 0) { jfail(400, verr); return; } { char lerr[256]; if (sx_ntfy_log_open(1) != 0) { jfail(500, "cannot open the log file"); return; } (void)lerr; } #if defined(_WIN32) { char exe[1024]; STARTUPINFOA si; PROCESS_INFORMATION pi; DWORD got; memset(&si, 0, sizeof si); si.cb = sizeof si; si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; memset(&pi, 0, sizeof pi); got = GetModuleFileNameA(NULL, exe, sizeof exe - 1); if (got == 0) { jfail(500, "cannot resolve this executable path"); return; } { char cmd[2200]; snprintf(cmd, sizeof cmd, "\"%s\" --daemon", exe); if (!CreateProcessA(NULL, cmd, NULL, NULL, FALSE, CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS, NULL, NULL, &si, &pi)) { jfail(500, "CreateProcess failed for the detached daemon"); return; } CloseHandle(pi.hThread); CloseHandle(pi.hProcess); } } #else { pid_t pid = fork(); if (pid < 0) { jfail(500, "fork failed"); return; } if (pid == 0) { /* child: fully detached daemon */ int fd; setsid(); fd = open("/dev/null", O_RDONLY); if (fd >= 0) { dup2(fd, 0); if (fd > 2) close(fd); } fd = open("/dev/null", O_WRONLY); if (fd >= 0) { dup2(fd, 1); dup2(fd, 2); if (fd > 2) close(fd); } _exit(run_daemon()); } } #endif sx_ntfy_logf("daemon started by the setup UI"); jout_init(&j); yyjson_mut_obj_add_bool(j.doc, j.root, "started", true); jout_done(&j); return; } if (!strcmp(action, "stop")) { long pid = 0; jout j; if (sx_ntfy_pidfile_read(&pid) != 0) { jfail(404, "the daemon is not running"); return; } #if defined(_WIN32) { HANDLE h = OpenProcess(PROCESS_TERMINATE | SYNCHRONIZE, FALSE, (DWORD)pid); if (!h) { sx_ntfy_pidfile_remove(); jfail(404, "the daemon is not running"); return; } TerminateProcess(h, 0); WaitForSingleObject(h, 3000); CloseHandle(h); } #else { int waited = 0; if (kill((pid_t)pid, 0) != 0 && errno == ESRCH) { sx_ntfy_pidfile_remove(); jfail(404, "the daemon is not running"); return; } kill((pid_t)pid, SIGTERM); while (waited < 5000 && kill((pid_t)pid, 0) == 0) { struct timespec ts = { 0, 100 * 1000000L }; nanosleep(&ts, NULL); waited += 100; } if (kill((pid_t)pid, 0) == 0) { kill((pid_t)pid, SIGKILL); sx_ntfy_logf("daemon %ld ignored SIGTERM, sent SIGKILL", pid); } } #endif sx_ntfy_pidfile_remove(); sx_ntfy_logf("daemon stopped by the setup UI"); jout_init(&j); yyjson_mut_obj_add_bool(j.doc, j.root, "stopped", true); jout_done(&j); return; } jfail(400, "unknown action"); (void)tmp; } /* ------------------------------------------------------------------ */ /* mode 5: GET the Setup & Topic Pairing UI */ /* ------------------------------------------------------------------ */ static void emit_ui(void) { const char *p = UI_HTML; while (*p) { if (*p == '\001') { fputs(SX_BOT_THEME_PREPAINT "", stdout); p++; } else if (*p == '\002') { fputs(SX_BOT_THEME_HANDOFF, stdout); p++; } else { putchar(*p++); } } } static int mode_html(int embed) { (void)embed; fputs("Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n" "X-Frame-Options: SAMEORIGIN\r\n" "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); emit_ui(); return 0; } /* ------------------------------------------------------------------ */ /* main */ /* ------------------------------------------------------------------ */ int main(int argc, char **argv) { const char *qs; int embed; int i; #if defined(_WIN32) /* Winsock has to be up before ANY mode touches the resolver. It used to * be started only on the CGI path (and separately for --daemon), so * `plugin_ntfy.exe --mcp` ran with a cold winsock: getaddrinfo() failed * straight away and every ntfy_send came back "cannot resolve * ntfy.sh:443". Verified on a real Windows box -- the MCP face is the * face an agent actually uses. */ { WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); } #endif for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "--meta") || !strcmp(argv[i], "-m")) return mode_meta(); if (!strcmp(argv[i], "--mcp")) return mode_mcp(); if (!strcmp(argv[i], "--schema")) return mode_schema(); if (!strcmp(argv[i], "--daemon") || !strcmp(argv[i], "-d")) { #if defined(_WIN32) { WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); } #endif return run_daemon(); } if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) { fputs("plugin_ntfy " PLUGIN_VER " -- SCORPIOX BOT ntfy channel connector\n" " --meta JSON discovery metadata (unauthenticated)\n" " --mcp stdio MCP server exposing the ntfy_send tool\n" " --schema the tool schema only\n" " --daemon channel gateway: ntfy <-> node /inbox bridge\n" " (no args, CGI) Setup & Topic Pairing UI + ?action= JSON API\n", stdout); return 0; } } if (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META")) return mode_meta(); #if defined(_WIN32) /* MinGW translates \n to \r\n on stdout in text mode, which double-CR- * terminates our own CGI headers and breaks the framing (lesson (bh)). */ _setmode(_fileno(stdout), _O_BINARY); { WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); } #endif if (getenv("SX_NTFY_MCP") && *getenv("SX_NTFY_MCP")) return mode_mcp(); require_node_auth(); qs = getenv("QUERY_STRING"); if (!qs) qs = ""; if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request()) { mode_json(qs); return 0; } embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); return mode_html(embed); }