| 1 | /* |
| 2 | * plugin_webhook - SCORPIOX BOT open-source named webhook & REST trigger |
| 3 | * MCP connector. |
| 4 | * |
| 5 | * One clean-room C99 binary carrying the five contracts a SCORPIOX BOT |
| 6 | * connector plugin implements: |
| 7 | * |
| 8 | * --meta / SX_PLUGIN_META=1 one line of JSON discovery metadata |
| 9 | * --mcp MCP JSON-RPC 2.0 over stdio |
| 10 | * --schema the tool list (compatibility) |
| 11 | * GET the bot-themed setup / test page |
| 12 | * ?action=… (+ POST body) the node-auth-gated JSON control API |
| 13 | * |
| 14 | * The idea, clean-room from Hermes Agent's `gateway/platforms/webhook*.py` |
| 15 | * and OpenClaw's `extensions/admin-http-rpc`: |
| 16 | * |
| 17 | * A user defines NAMED endpoints - Slack, Discord, Zapier, n8n, IFTTT, a |
| 18 | * home-grown REST trigger - each with its own method, headers (an |
| 19 | * Authorization token, an API key) and optional HMAC-SHA256 signature. |
| 20 | * The agent then fires them by NAME with a JSON payload. The secret lives |
| 21 | * in one 0600 file on the node and is never in the prompt, never in a tool |
| 22 | * result, and never in an HTTP response: both the MCP surface and the page |
| 23 | * see `has_secret: true` and nothing else. |
| 24 | * |
| 25 | * Why two tools instead of one tool per endpoint: a connector that publishes |
| 26 | * every user-defined hook as its own MCP tool floods the agent's context with |
| 27 | * names it will never call. webhook_list is the routing table; webhook_trigger |
| 28 | * is the single verb. That also means adding a hook needs no restart. |
| 29 | * |
| 30 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 31 | */ |
| 32 | |
| 33 | /* Before every include: MinGW defaults _WIN32_WINNT to 0x502 (hides |
| 34 | * InetPton and friends); Apple needs _DARWIN_C_SOURCE under strict c99; |
| 35 | * MinGW needs its own printf for %zu. */ |
| 36 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 37 | # define _WIN32_WINNT 0x0601 |
| 38 | #endif |
| 39 | #if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) |
| 40 | # define _DARWIN_C_SOURCE 1 |
| 41 | #endif |
| 42 | #if defined(__MINGW32__) && !defined(__USE_MINGW_ANSI_STDIO) |
| 43 | # define __USE_MINGW_ANSI_STDIO 1 |
| 44 | #endif |
| 45 | #ifndef _POSIX_C_SOURCE |
| 46 | # define _POSIX_C_SOURCE 200809L |
| 47 | #endif |
| 48 | |
| 49 | #include <ctype.h> |
| 50 | #include <stdio.h> |
| 51 | #include <stdlib.h> |
| 52 | #include <string.h> |
| 53 | #include <time.h> |
| 54 | |
| 55 | #if defined(_WIN32) |
| 56 | # include <io.h> |
| 57 | # include <fcntl.h> |
| 58 | # include <windows.h> |
| 59 | #else |
| 60 | # include <errno.h> |
| 61 | # include <signal.h> |
| 62 | # include <sys/stat.h> |
| 63 | # include <unistd.h> |
| 64 | #endif |
| 65 | |
| 66 | #include "bot_theme_plugin.h" |
| 67 | #include "sha256.h" |
| 68 | #include "ui_html.h" |
| 69 | #include "wh_buf.h" |
| 70 | #include "wh_http.h" |
| 71 | #include "wh_store.h" |
| 72 | #include "yyjson.h" |
| 73 | |
| 74 | #define PLUGIN_SLUG "webhook" |
| 75 | #define PLUGIN_ID "plugin_webhook" |
| 76 | #define PLUGIN_NAME "webhook" |
| 77 | #define PLUGIN_DESC "HTTP triggers" |
| 78 | #define PLUGIN_VER "1.0.3" |
| 79 | #define PLUGIN_KIND "mcp" |
| 80 | |
| 81 | /* ===================================================================== |
| 82 | * 1. Small shared helpers |
| 83 | * ===================================================================== */ |
| 84 | |
| 85 | static void copy_trunc(char *dst, size_t capsz, const char *src) |
| 86 | { |
| 87 | size_t n; |
| 88 | if (!capsz) return; |
| 89 | if (!src) { dst[0] = '\0'; return; } |
| 90 | n = strlen(src); |
| 91 | if (n >= capsz) n = capsz - 1; |
| 92 | memcpy(dst, src, n); |
| 93 | dst[n] = '\0'; |
| 94 | } |
| 95 | |
| 96 | static int ieq(const char *a, const char *b) |
| 97 | { |
| 98 | if (!a || !b) return 0; |
| 99 | while (*a && *b) { |
| 100 | if (tolower((unsigned char)*a) != tolower((unsigned char)*b)) return 0; |
| 101 | a++; b++; |
| 102 | } |
| 103 | return *a == 0 && *b == 0; |
| 104 | } |
| 105 | |
| 106 | static void iso_now(char *out, size_t outsz) |
| 107 | { |
| 108 | time_t now = time(NULL); |
| 109 | struct tm tmv; |
| 110 | #if defined(_WIN32) |
| 111 | gmtime_s(&tmv, &now); |
| 112 | #else |
| 113 | gmtime_r(&now, &tmv); |
| 114 | #endif |
| 115 | strftime(out, outsz, "%Y-%m-%dT%H:%M:%SZ", &tmv); |
| 116 | } |
| 117 | |
| 118 | /* Percent-decode in place (also turns '+' into a space). */ |
| 119 | static void url_decode(char *s) |
| 120 | { |
| 121 | char *w = s; |
| 122 | char *r = s; |
| 123 | while (*r) { |
| 124 | if (*r == '%' && isxdigit((unsigned char)r[1]) && isxdigit((unsigned char)r[2])) { |
| 125 | int hi = isdigit((unsigned char)r[1]) ? r[1] - '0' : (tolower((unsigned char)r[1]) - 'a' + 10); |
| 126 | int lo = isdigit((unsigned char)r[2]) ? r[2] - '0' : (tolower((unsigned char)r[2]) - 'a' + 10); |
| 127 | *w++ = (char)((hi << 4) | lo); |
| 128 | r += 3; |
| 129 | } else if (*r == '+') { |
| 130 | *w++ = ' '; |
| 131 | r++; |
| 132 | } else { |
| 133 | *w++ = *r++; |
| 134 | } |
| 135 | } |
| 136 | *w = '\0'; |
| 137 | } |
| 138 | |
| 139 | /* Parse one QUERY_STRING value. Returns 1 when found. */ |
| 140 | static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) |
| 141 | { |
| 142 | size_t klen; |
| 143 | const char *p; |
| 144 | |
| 145 | if (!qs || !key || !out || outsz == 0) return 0; |
| 146 | out[0] = '\0'; |
| 147 | klen = strlen(key); |
| 148 | p = qs; |
| 149 | while (*p) { |
| 150 | if (strncmp(p, key, klen) == 0 && p[klen] == '=') { |
| 151 | size_t i = 0; |
| 152 | p += klen + 1; |
| 153 | while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; |
| 154 | out[i] = '\0'; |
| 155 | url_decode(out); |
| 156 | return 1; |
| 157 | } |
| 158 | { |
| 159 | const char *next = strchr(p, '&'); |
| 160 | if (!next) break; |
| 161 | p = next + 1; |
| 162 | } |
| 163 | } |
| 164 | return 0; |
| 165 | } |
| 166 | |
| 167 | static void cgi_header(long status, const char *ctype) |
| 168 | { |
| 169 | if (status != 200) printf("Status: %ld\r\n", status); |
| 170 | printf("Content-Type: %s\r\n" |
| 171 | "Cache-Control: no-store\r\n" |
| 172 | "X-Content-Type-Options: nosniff\r\n" |
| 173 | "Referrer-Policy: no-referrer\r\n" |
| 174 | "Content-Security-Policy: default-src 'self' 'unsafe-inline'; " |
| 175 | "img-src 'self' data:; connect-src 'self'\r\n\r\n", |
| 176 | ctype); |
| 177 | } |
| 178 | |
| 179 | /* ===================================================================== |
| 180 | * 2. Node authentication |
| 181 | * |
| 182 | * Every route that reveals node state - the page included, because it lists |
| 183 | * the URLs of the operator's endpoints - is gated. --meta, --mcp and --schema |
| 184 | * return before this is called, so discovery and the tool surface keep |
| 185 | * working on a locked node. |
| 186 | * ===================================================================== */ |
| 187 | |
| 188 | static void require_node_auth(void) |
| 189 | { |
| 190 | const char *np = getenv("BOT_PASSWORD"); |
| 191 | const char *xp, *auth, *qs; |
| 192 | char qpwd[256]; |
| 193 | |
| 194 | if (!np || !*np) return; /* node explicitly open */ |
| 195 | |
| 196 | xp = getenv("HTTP_X_BOT_PASSWORD"); |
| 197 | if (xp && strcmp(xp, np) == 0) return; |
| 198 | |
| 199 | auth = getenv("HTTP_AUTHORIZATION"); |
| 200 | if (auth) { |
| 201 | while (*auth == ' ') auth++; |
| 202 | if (strncmp(auth, "Bearer ", 7) == 0) { |
| 203 | const char *t = auth + 7; |
| 204 | while (*t == ' ') t++; |
| 205 | if (strcmp(t, np) == 0) return; |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | qs = getenv("QUERY_STRING"); |
| 210 | if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) |
| 211 | return; |
| 212 | |
| 213 | cgi_header(401, "application/json; charset=utf-8"); |
| 214 | fputs("{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); |
| 215 | fflush(stdout); |
| 216 | exit(0); |
| 217 | } |
| 218 | |
| 219 | /* ===================================================================== |
| 220 | * 3. Signing a body |
| 221 | * ===================================================================== */ |
| 222 | |
| 223 | /* Compose the signature headers for this hook. `body` gave the payload; the |
| 224 | * timestamp used for v2 is the same one that goes on the wire, so a verifier |
| 225 | * can recompute exactly what we signed. */ |
| 226 | static int sign_request(const wh_hook *h, const char *body, size_t blen, |
| 227 | wh_header *out, int maxout, char *err, size_t errsz) |
| 228 | { |
| 229 | if (err && errsz) err[0] = '\0'; |
| 230 | if (!h->sig[0]) return 0; |
| 231 | if (maxout < 2) { if (err) snprintf(err, errsz, "no room for signature headers"); return -1; } |
| 232 | |
| 233 | if (strcmp(h->sig, WH_SIG_GITHUB) == 0) { |
| 234 | char hex[65]; |
| 235 | sx_hmac_sha256_hex(h->secret, strlen(h->secret), body, blen, hex); |
| 236 | copy_trunc(out[0].name, sizeof out[0].name, "X-Hub-Signature-256"); |
| 237 | snprintf(out[0].value, sizeof out[0].value, "sha256=%s", hex); |
| 238 | return 1; |
| 239 | } |
| 240 | if (strcmp(h->sig, WH_SIG_GITLAB) == 0) { |
| 241 | copy_trunc(out[0].name, sizeof out[0].name, "X-Gitlab-Token"); |
| 242 | copy_trunc(out[0].value, sizeof out[0].value, h->secret); |
| 243 | return 1; |
| 244 | } |
| 245 | if (strcmp(h->sig, WH_SIG_V2) == 0) { |
| 246 | /* HMAC over "<unix-seconds>.<body>": a captured request stops being |
| 247 | * valid once the verifier's window closes, which a body-only |
| 248 | * signature never does. */ |
| 249 | char ts[24], hex[65], signed_buf[64 + WH_BODY_CAP]; |
| 250 | long long now = (long long)time(NULL); |
| 251 | int n; |
| 252 | snprintf(ts, sizeof ts, "%lld", now); |
| 253 | n = snprintf(signed_buf, 32, "%s.", ts); |
| 254 | if (blen > sizeof signed_buf - (size_t)n) { |
| 255 | if (err) snprintf(err, errsz, "payload too large to sign"); |
| 256 | return -1; |
| 257 | } |
| 258 | memcpy(signed_buf + n, body, blen); |
| 259 | sx_hmac_sha256_hex(h->secret, strlen(h->secret), signed_buf, |
| 260 | (size_t)n + blen, hex); |
| 261 | copy_trunc(out[0].name, sizeof out[0].name, "X-Webhook-Timestamp"); |
| 262 | copy_trunc(out[0].value, sizeof out[0].value, ts); |
| 263 | copy_trunc(out[1].name, sizeof out[1].name, "X-Webhook-Signature"); |
| 264 | snprintf(out[1].value, sizeof out[1].value, "t=%s,v1=%s", ts, hex); |
| 265 | return 2; |
| 266 | } |
| 267 | if (err) snprintf(err, errsz, "unknown signature scheme '%s'", h->sig); |
| 268 | return -1; |
| 269 | } |
| 270 | |
| 271 | /* Decide whether this response status counts as a success. */ |
| 272 | static int status_is_ok(int status) |
| 273 | { |
| 274 | return status >= 200 && status < 300; |
| 275 | } |
| 276 | |
| 277 | /* ===================================================================== |
| 278 | * 4. Firing a hook |
| 279 | * ===================================================================== */ |
| 280 | |
| 281 | typedef struct { |
| 282 | int sent; /* 1 = a response arrived */ |
| 283 | int status; |
| 284 | char error[512]; |
| 285 | char body[WH_PREVIEW_CAP + 1]; |
| 286 | size_t body_len; |
| 287 | int truncated; |
| 288 | long ms; |
| 289 | } fire_result; |
| 290 | |
| 291 | /* Fire a stored hook with `payload` as the JSON body and `query` appended to |
| 292 | * the URL. Returns 0 when the request completed (whatever the status), -1 when |
| 293 | * it could not be sent at all (refused address, TLS, timeout). */ |
| 294 | static int fire_hook(const wh_hook *h, const char *payload, size_t plen, |
| 295 | const char *query, fire_result *res) |
| 296 | { |
| 297 | wh_url u; |
| 298 | char uerr[256]; |
| 299 | char full_url[WH_URL_MAX + 512]; |
| 300 | wh_header hdrs[WH_MAX_HEADERS + 4]; |
| 301 | int n = 0, i, sig_n = 0; |
| 302 | wh_response r; |
| 303 | long long t0, t1; |
| 304 | |
| 305 | memset(res, 0, sizeof *res); |
| 306 | |
| 307 | snprintf(full_url, sizeof full_url, "%s", h->url); |
| 308 | if (query && *query) { |
| 309 | size_t l = strlen(full_url); |
| 310 | if (l + 1 < sizeof full_url) { |
| 311 | int has_q = strchr(full_url, '?') != NULL; |
| 312 | snprintf(full_url + l, sizeof full_url - l, "%s%s", has_q ? "&" : "?", query); |
| 313 | } |
| 314 | } |
| 315 | if (wh_url_parse(full_url, &u, uerr, sizeof uerr) != 0) { |
| 316 | snprintf(res->error, sizeof res->error, "%s", uerr); |
| 317 | return -1; |
| 318 | } |
| 319 | |
| 320 | for (i = 0; i < h->nheaders && n < WH_MAX_HEADERS; i++) hdrs[n++] = h->headers[i]; |
| 321 | if (plen || strcmp(h->method, "GET") != 0) { |
| 322 | int have_ct = 0; |
| 323 | for (i = 0; i < n; i++) if (ieq(hdrs[i].name, "Content-Type")) have_ct = 1; |
| 324 | if (!have_ct) { |
| 325 | copy_trunc(hdrs[n].name, sizeof hdrs[n].name, "Content-Type"); |
| 326 | copy_trunc(hdrs[n].value, sizeof hdrs[n].value, |
| 327 | "application/json; charset=utf-8"); |
| 328 | n++; |
| 329 | } |
| 330 | } |
| 331 | { |
| 332 | wh_header sig[2]; |
| 333 | char serr[160]; |
| 334 | sig_n = sign_request(h, payload, plen, sig, 2, serr, sizeof serr); |
| 335 | if (sig_n < 0) { |
| 336 | snprintf(res->error, sizeof res->error, "%s", serr); |
| 337 | return -1; |
| 338 | } |
| 339 | for (i = 0; i < sig_n && n < (int)(sizeof hdrs / sizeof hdrs[0]); i++) hdrs[n++] = sig[i]; |
| 340 | } |
| 341 | |
| 342 | t0 = (long long)(clock() / (CLOCKS_PER_SEC / 1000)); |
| 343 | if (wh_http_request(h->method, &u, hdrs, n, |
| 344 | (strcmp(h->method, "GET") == 0 || strcmp(h->method, "HEAD") == 0) |
| 345 | ? NULL : payload, |
| 346 | (strcmp(h->method, "GET") == 0 || strcmp(h->method, "HEAD") == 0) |
| 347 | ? 0 : plen, |
| 348 | WH_CONNECT_MS + WH_READ_MS, &r) != 0) { |
| 349 | t1 = (long long)(clock() / (CLOCKS_PER_SEC / 1000)); |
| 350 | res->ms = (long)(t1 - t0); |
| 351 | snprintf(res->error, sizeof res->error, "%s", r.error); |
| 352 | return -1; |
| 353 | } |
| 354 | t1 = (long long)(clock() / (CLOCKS_PER_SEC / 1000)); |
| 355 | res->ms = (long)(t1 - t0); |
| 356 | res->sent = 1; |
| 357 | res->status = r.status; |
| 358 | res->body_len = r.body_len; |
| 359 | res->truncated = r.truncated; |
| 360 | memcpy(res->body, r.body, r.body_len < sizeof res->body ? r.body_len : sizeof res->body - 1); |
| 361 | res->body[res->body_len < sizeof res->body ? res->body_len : sizeof res->body - 1] = '\0'; |
| 362 | return 0; |
| 363 | } |
| 364 | |
| 365 | /* ===================================================================== |
| 366 | * 5. Insert / update a hook from a request body |
| 367 | * ===================================================================== */ |
| 368 | |
| 369 | typedef struct { |
| 370 | int ok; |
| 371 | char error[320]; |
| 372 | char name[WH_NAME_MAX]; |
| 373 | } store_op; |
| 374 | |
| 375 | static int save_hook_from_json(wh_store *s, const char *json, const char *forced_name, |
| 376 | store_op *op) |
| 377 | { |
| 378 | wh_hook scratch; |
| 379 | wh_hook *existing = NULL; |
| 380 | char err[320]; |
| 381 | |
| 382 | memset(op, 0, sizeof *op); |
| 383 | memset(&scratch, 0, sizeof scratch); |
| 384 | copy_trunc(scratch.method, sizeof scratch.method, "POST"); |
| 385 | |
| 386 | if (forced_name && *forced_name) { |
| 387 | existing = wh_hook_find(s, forced_name); |
| 388 | if (existing) scratch = *existing; /* edit in place */ |
| 389 | } |
| 390 | |
| 391 | if (wh_hook_apply(&scratch, json, existing, err, sizeof err) != 0) { |
| 392 | snprintf(op->error, sizeof op->error, "%s", err); |
| 393 | return -1; |
| 394 | } |
| 395 | |
| 396 | /* An edit may rename nothing, but a create must not silently replace a |
| 397 | * different hook that already owns the name. */ |
| 398 | { |
| 399 | wh_hook *clash = wh_hook_find(s, scratch.name); |
| 400 | if (clash && (!existing || clash != existing)) { |
| 401 | snprintf(op->error, sizeof op->error, |
| 402 | "a hook named '%s' already exists", scratch.name); |
| 403 | return -1; |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | if (existing) { |
| 408 | *existing = scratch; |
| 409 | copy_trunc(op->name, sizeof op->name, scratch.name); |
| 410 | } else { |
| 411 | if (s->nhooks >= WH_MAX_HOOKS) { |
| 412 | snprintf(op->error, sizeof op->error, |
| 413 | "the store already holds %d hooks (the maximum)", WH_MAX_HOOKS); |
| 414 | return -1; |
| 415 | } |
| 416 | s->hooks[s->nhooks++] = scratch; |
| 417 | copy_trunc(op->name, sizeof op->name, scratch.name); |
| 418 | } |
| 419 | |
| 420 | if (wh_store_save(s, err, sizeof err) != 0) { |
| 421 | snprintf(op->error, sizeof op->error, "%s", err); |
| 422 | return -1; |
| 423 | } |
| 424 | op->ok = 1; |
| 425 | return 0; |
| 426 | } |
| 427 | |
| 428 | /* ===================================================================== |
| 429 | * 6. MCP surface |
| 430 | * ===================================================================== */ |
| 431 | |
| 432 | static const char TOOL_LIST_SCHEMA[] = |
| 433 | "{\"type\":\"object\",\"properties\":{" |
| 434 | "\"redact_url\":{\"type\":\"boolean\",\"description\":" |
| 435 | "\"Return only the endpoint host and path without the query string " |
| 436 | "(default true). Set false only when you must see the exact URL, and " |
| 437 | "remember the answer may then contain a provider token.\"}}," |
| 438 | "\"additionalProperties\":false}"; |
| 439 | |
| 440 | static const char TOOL_TRIGGER_SCHEMA[] = |
| 441 | "{\"type\":\"object\",\"properties\":{" |
| 442 | "\"name\":{\"type\":\"string\",\"description\":" |
| 443 | "\"The name of a stored hook, exactly as webhook_list reported it.\"}," |
| 444 | "\"payload\":{\"type\":\"string\",\"description\":" |
| 445 | "\"The request body. A JSON object or array is sent as-is; a bare string " |
| 446 | "is sent as a JSON string literal. Defaults to {}.\"}," |
| 447 | "\"query\":{\"type\":\"string\",\"description\":" |
| 448 | "\"Optional query string appended to the hook's URL, without a leading " |
| 449 | "? (for example event=deploy&env=prod).\"}}," |
| 450 | "\"required\":[\"name\"],\"additionalProperties\":false}"; |
| 451 | |
| 452 | /* webhook_list */ |
| 453 | static int tool_list(const char *args, char *out, size_t outsz) |
| 454 | { |
| 455 | wh_store s; |
| 456 | char err[320]; |
| 457 | wh_buf b; |
| 458 | int i, redact = 1; |
| 459 | yyjson_doc *doc = NULL; |
| 460 | |
| 461 | if (args && *args) { |
| 462 | doc = yyjson_read(args, strlen(args), 0); |
| 463 | if (doc) { |
| 464 | yyjson_val *v = yyjson_obj_get(yyjson_doc_get_root(doc), "redact_url"); |
| 465 | if (v && yyjson_is_bool(v)) redact = yyjson_get_bool(v) ? 1 : 0; |
| 466 | } |
| 467 | } |
| 468 | wh_store_load(&s, err, sizeof err); |
| 469 | |
| 470 | wh_buf_init(&b); |
| 471 | if (s.nhooks == 0) { |
| 472 | wh_buf_str(&b, "No webhooks are configured on this node. Ask the owner to " |
| 473 | "add one in the webhook plugin page (Settings -> Plugins), " |
| 474 | "then call webhook_list again."); |
| 475 | } else { |
| 476 | wh_buf_printf(&b, "%d configured webhook%s\n\n", s.nhooks, |
| 477 | s.nhooks == 1 ? "" : "s"); |
| 478 | for (i = 0; i < s.nhooks; i++) { |
| 479 | const wh_hook *h = &s.hooks[i]; |
| 480 | char clean[WH_URL_MAX + 32]; |
| 481 | if (redact) { |
| 482 | wh_url u; |
| 483 | char uerr[160]; |
| 484 | clean[0] = '\0'; |
| 485 | if (wh_url_parse(h->url, &u, uerr, sizeof uerr) == 0) |
| 486 | wh_url_redact(&u, clean, sizeof clean); |
| 487 | else |
| 488 | copy_trunc(clean, sizeof clean, "(invalid url)"); |
| 489 | } else { |
| 490 | copy_trunc(clean, sizeof clean, h->url); |
| 491 | } |
| 492 | wh_buf_printf(&b, "- %s %s %s", h->name, h->method, clean); |
| 493 | if (h->sig[0]) wh_buf_printf(&b, " [signed: %s]", h->sig); |
| 494 | if (h->nheaders) wh_buf_printf(&b, " [%d header%s]", h->nheaders, |
| 495 | h->nheaders == 1 ? "" : "s"); |
| 496 | wh_buf_str(&b, "\n"); |
| 497 | if (h->desc[0]) wh_buf_printf(&b, " %s\n", h->desc); |
| 498 | } |
| 499 | wh_buf_str(&b, "\nUse webhook_trigger with one of these names. Secrets are " |
| 500 | "stored on the node and never returned.\n"); |
| 501 | } |
| 502 | if (err[0]) wh_buf_printf(&b, "\nStore warning: %s\n", err); |
| 503 | |
| 504 | snprintf(out, outsz, "%s", wh_buf_cstr(&b)); |
| 505 | wh_buf_free(&b); |
| 506 | if (doc) yyjson_doc_free(doc); |
| 507 | return 0; |
| 508 | } |
| 509 | |
| 510 | /* webhook_trigger */ |
| 511 | static int tool_trigger(const char *args, char *out, size_t outsz, |
| 512 | char *err, size_t errsz) |
| 513 | { |
| 514 | yyjson_doc *doc; |
| 515 | yyjson_val *root, *v; |
| 516 | char namebuf[WH_NAME_MAX]; |
| 517 | char payload[WH_BODY_CAP]; |
| 518 | char query[512]; |
| 519 | size_t plen = 0; |
| 520 | wh_store s; |
| 521 | wh_hook *h; |
| 522 | char serr[320]; |
| 523 | fire_result res; |
| 524 | |
| 525 | if (err && errsz) err[0] = '\0'; |
| 526 | if (!args || !*args) { |
| 527 | snprintf(err, errsz, "missing arguments: {\"name\":\"...\"}"); |
| 528 | return 1; |
| 529 | } |
| 530 | doc = yyjson_read(args, strlen(args), 0); |
| 531 | if (!doc) { snprintf(err, errsz, "arguments are not valid JSON"); return 1; } |
| 532 | root = yyjson_doc_get_root(doc); |
| 533 | /* Copy the name out of the document before it is freed: yyjson strings |
| 534 | * point into the document's own buffer, not into a copy. */ |
| 535 | namebuf[0] = '\0'; |
| 536 | v = yyjson_obj_get(root, "name"); |
| 537 | if (v && yyjson_is_str(v)) copy_trunc(namebuf, sizeof namebuf, yyjson_get_str(v)); |
| 538 | if (!namebuf[0]) { |
| 539 | yyjson_doc_free(doc); |
| 540 | snprintf(err, errsz, "missing required argument: name"); |
| 541 | return 1; |
| 542 | } |
| 543 | |
| 544 | /* `payload` may arrive as a string (the schema says so, because MCP |
| 545 | * arguments are JSON and a caller that already has a serialized body |
| 546 | * should not have to re-encode it) or as an object/array, which is what a |
| 547 | * model naturally sends. Both are accepted. */ |
| 548 | v = yyjson_obj_get(root, "payload"); |
| 549 | if (v) { |
| 550 | if (yyjson_is_str(v)) { |
| 551 | const char *s = yyjson_get_str(v); |
| 552 | size_t n = strlen(s); |
| 553 | if (n >= sizeof payload) { |
| 554 | yyjson_doc_free(doc); |
| 555 | snprintf(err, errsz, "payload is larger than the %u byte limit", |
| 556 | (unsigned)sizeof payload); |
| 557 | return 1; |
| 558 | } |
| 559 | memcpy(payload, s, n); |
| 560 | plen = n; |
| 561 | } else { |
| 562 | char *ser = yyjson_val_write(v, 0, NULL); |
| 563 | if (!ser) { |
| 564 | yyjson_doc_free(doc); |
| 565 | snprintf(err, errsz, "could not serialize payload"); |
| 566 | return 1; |
| 567 | } |
| 568 | plen = strlen(ser); |
| 569 | if (plen >= sizeof payload) { |
| 570 | free(ser); |
| 571 | yyjson_doc_free(doc); |
| 572 | snprintf(err, errsz, "payload is larger than the %u byte limit", |
| 573 | (unsigned)sizeof payload); |
| 574 | return 1; |
| 575 | } |
| 576 | memcpy(payload, ser, plen); |
| 577 | free(ser); |
| 578 | } |
| 579 | } |
| 580 | query[0] = '\0'; |
| 581 | v = yyjson_obj_get(root, "query"); |
| 582 | if (v && yyjson_is_str(v)) copy_trunc(query, sizeof query, yyjson_get_str(v)); |
| 583 | yyjson_doc_free(doc); |
| 584 | |
| 585 | if (wh_store_load(&s, serr, sizeof serr) != 0) { |
| 586 | snprintf(err, errsz, "%s", serr); |
| 587 | return 1; |
| 588 | } |
| 589 | if (!plen) { memcpy(payload, "{}", 2); plen = 2; } |
| 590 | |
| 591 | h = wh_hook_find(&s, namebuf); |
| 592 | if (!h) { |
| 593 | wh_buf b; |
| 594 | int i; |
| 595 | wh_buf_init(&b); |
| 596 | wh_buf_printf(&b, "no webhook named '%s'. Configured: ", namebuf); |
| 597 | if (s.nhooks == 0) wh_buf_str(&b, "(none)"); |
| 598 | for (i = 0; i < s.nhooks; i++) { |
| 599 | if (i) wh_buf_str(&b, ", "); |
| 600 | wh_buf_str(&b, s.hooks[i].name); |
| 601 | } |
| 602 | snprintf(err, errsz, "%s", wh_buf_cstr(&b)); |
| 603 | wh_buf_free(&b); |
| 604 | return 1; |
| 605 | } |
| 606 | |
| 607 | if (fire_hook(h, payload, plen, query, &res) != 0) { |
| 608 | snprintf(err, errsz, "could not deliver to '%s': %s", namebuf, res.error); |
| 609 | return 1; |
| 610 | } |
| 611 | |
| 612 | { |
| 613 | wh_buf b; |
| 614 | wh_logent le; |
| 615 | wh_buf_init(&b); |
| 616 | wh_buf_printf(&b, "%s %s -> HTTP %d in %ld ms\n", h->method, namebuf, |
| 617 | res.status, res.ms); |
| 618 | wh_buf_printf(&b, "ok: %s\n", status_is_ok(res.status) ? "yes" : "no"); |
| 619 | if (res.truncated) |
| 620 | wh_buf_printf(&b, "body (first %u bytes of a larger response):\n", |
| 621 | (unsigned)res.body_len); |
| 622 | else |
| 623 | wh_buf_printf(&b, "body:\n"); |
| 624 | wh_buf_str(&b, res.body_len ? res.body : "(empty)"); |
| 625 | snprintf(out, outsz, "%s", wh_buf_cstr(&b)); |
| 626 | wh_buf_free(&b); |
| 627 | |
| 628 | /* Record the delivery, newest first, in the same file. */ |
| 629 | iso_now(le.at, sizeof le.at); |
| 630 | copy_trunc(le.name, sizeof le.name, namebuf); |
| 631 | le.status = res.status; |
| 632 | le.ok = status_is_ok(res.status) ? 1 : 0; |
| 633 | le.bytes = (long)res.body_len; |
| 634 | le.ms = res.ms; |
| 635 | le.error[0] = '\0'; |
| 636 | wh_store_log_add(&s, &le); |
| 637 | wh_store_save(&s, serr, sizeof serr); |
| 638 | } |
| 639 | return 0; |
| 640 | } |
| 641 | |
| 642 | static const struct { |
| 643 | const char *name; |
| 644 | const char *desc; |
| 645 | const char *schema; |
| 646 | int (*call)(const char *args, char *out, size_t outsz, char *err, size_t errsz); |
| 647 | } TOOLS[] = { |
| 648 | { "webhook_list", |
| 649 | "List the named webhooks configured on this node: name, method, endpoint " |
| 650 | "(query string redacted), whether it is HMAC-signed and how many secret " |
| 651 | "headers it carries. Secrets are never returned. Call this first to learn " |
| 652 | "which names webhook_trigger accepts.", |
| 653 | TOOL_LIST_SCHEMA, NULL }, |
| 654 | { "webhook_trigger", |
| 655 | "Send one stored webhook by name with a JSON payload. The stored headers, " |
| 656 | "bearer tokens and HMAC signature are applied on the node; the secret never " |
| 657 | "enters this conversation. Returns the HTTP status, latency and the first " |
| 658 | "4 KiB of the response body.", |
| 659 | TOOL_TRIGGER_SCHEMA, tool_trigger } |
| 660 | }; |
| 661 | |
| 662 | /* Minimal MCP server. Newline-delimited JSON-RPC 2.0, with Content-Length |
| 663 | * framing accepted because some clients send LSP-style headers. Reads with |
| 664 | * read(2), never fread(2): on a pipe fread blocks until its whole buffer fills, |
| 665 | * which turns a client that writes the body and the newline as two separate |
| 666 | * writes into a hang. That exact shape is what the connector router uses. */ |
| 667 | static int read_request_line(wh_buf *line) |
| 668 | { |
| 669 | static char rb[16384]; |
| 670 | static size_t rn, rp; |
| 671 | long long want = -1; |
| 672 | |
| 673 | line->n = 0; |
| 674 | for (;;) { |
| 675 | if (rp < rn) { |
| 676 | size_t i = rp; |
| 677 | int nl = 0; |
| 678 | while (i < rn && rb[i] != '\n') i++; |
| 679 | if (i < rn) nl = 1; |
| 680 | { |
| 681 | size_t take = i - rp; |
| 682 | char tmp[16385]; |
| 683 | if (take > 0) memcpy(tmp, rb + rp, take); |
| 684 | rp = i + (nl ? 1 : 0); |
| 685 | tmp[take] = '\0'; |
| 686 | while (take > 0 && (tmp[take - 1] == '\r' || tmp[take - 1] == ' ')) |
| 687 | tmp[--take] = '\0'; |
| 688 | if (want < 0 && strncmp(tmp, "Content-Length:", 15) == 0) { |
| 689 | want = strtoll(tmp + 15, NULL, 10); |
| 690 | continue; |
| 691 | } |
| 692 | if (want < 0 && take == 0 && !nl) continue; /* header blank */ |
| 693 | wh_buf_add(line, tmp, take); |
| 694 | if (want < 0) { |
| 695 | if (nl) return 1; |
| 696 | continue; |
| 697 | } |
| 698 | if ((long long)line->n >= want) { |
| 699 | if (line->p && (size_t)want < line->cap) line->p[want] = '\0'; |
| 700 | line->n = (size_t)want; |
| 701 | want = -1; |
| 702 | return 1; |
| 703 | } |
| 704 | wh_buf_add(line, "\n", 1); |
| 705 | continue; |
| 706 | } |
| 707 | } |
| 708 | if (rp >= rn) { rn = 0; rp = 0; } |
| 709 | for (;;) { |
| 710 | #if defined(_WIN32) |
| 711 | long got = (long)_read(_fileno(stdin), rb, (unsigned)sizeof rb); |
| 712 | #else |
| 713 | long got = (long)read(fileno(stdin), rb, sizeof rb); |
| 714 | #endif |
| 715 | if (got > 0) { rn = (size_t)got; break; } |
| 716 | if (got == 0) return line->n ? 1 : 0; |
| 717 | #if !defined(_WIN32) |
| 718 | if (errno == EINTR) continue; |
| 719 | #endif |
| 720 | return line->n ? 1 : 0; |
| 721 | } |
| 722 | } |
| 723 | } |
| 724 | |
| 725 | static void mcp_send(wh_buf *b) |
| 726 | { |
| 727 | fputs(wh_buf_cstr(b), stdout); |
| 728 | fputc('\n', stdout); |
| 729 | fflush(stdout); |
| 730 | } |
| 731 | |
| 732 | static void mcp_error(const char *id_json, long code, const char *msg) |
| 733 | { |
| 734 | wh_buf b; |
| 735 | wh_buf_init(&b); |
| 736 | wh_buf_str(&b, "{\"jsonrpc\":\"2.0\",\"id\":"); |
| 737 | wh_buf_str(&b, id_json ? id_json : "null"); |
| 738 | wh_buf_printf(&b, ",\"error\":{\"code\":%ld,\"message\":", code); |
| 739 | wh_buf_json_str(&b, msg ? msg : "error"); |
| 740 | wh_buf_str(&b, "}}"); |
| 741 | mcp_send(&b); |
| 742 | wh_buf_free(&b); |
| 743 | } |
| 744 | |
| 745 | static void mcp_result(const char *id_json, const char *result_json) |
| 746 | { |
| 747 | wh_buf b; |
| 748 | wh_buf_init(&b); |
| 749 | wh_buf_str(&b, "{\"jsonrpc\":\"2.0\",\"id\":"); |
| 750 | wh_buf_str(&b, id_json ? id_json : "null"); |
| 751 | wh_buf_str(&b, ",\"result\":"); |
| 752 | wh_buf_str(&b, result_json ? result_json : "{}"); |
| 753 | wh_buf_str(&b, "}"); |
| 754 | mcp_send(&b); |
| 755 | wh_buf_free(&b); |
| 756 | } |
| 757 | |
| 758 | static void mcp_tool_content(const char *id_json, const char *text, int is_error) |
| 759 | { |
| 760 | wh_buf b; |
| 761 | wh_buf_init(&b); |
| 762 | wh_buf_str(&b, "{\"content\":[{\"type\":\"text\",\"text\":"); |
| 763 | wh_buf_json_str(&b, text ? text : ""); |
| 764 | wh_buf_str(&b, "}]"); |
| 765 | if (is_error) wh_buf_str(&b, ",\"isError\":true"); |
| 766 | wh_buf_str(&b, "}"); |
| 767 | mcp_result(id_json, wh_buf_cstr(&b)); |
| 768 | wh_buf_free(&b); |
| 769 | } |
| 770 | |
| 771 | static void mcp_tools_list(const char *id_json) |
| 772 | { |
| 773 | wh_buf b; |
| 774 | size_t i; |
| 775 | wh_buf_init(&b); |
| 776 | wh_buf_str(&b, "{\"tools\":["); |
| 777 | for (i = 0; i < sizeof TOOLS / sizeof TOOLS[0]; i++) { |
| 778 | int f = 1; |
| 779 | if (i) wh_buf_str(&b, ","); |
| 780 | wh_buf_str(&b, "{"); |
| 781 | wh_buf_key(&b, "name", &f); |
| 782 | wh_buf_json_str(&b, TOOLS[i].name); |
| 783 | wh_buf_key(&b, "description", &f); |
| 784 | wh_buf_json_str(&b, TOOLS[i].desc); |
| 785 | wh_buf_key(&b, "inputSchema", &f); |
| 786 | wh_buf_str(&b, TOOLS[i].schema); |
| 787 | wh_buf_str(&b, "}"); |
| 788 | } |
| 789 | wh_buf_str(&b, "]}"); |
| 790 | mcp_result(id_json, wh_buf_cstr(&b)); |
| 791 | wh_buf_free(&b); |
| 792 | } |
| 793 | |
| 794 | static void mcp_call_tool(const char *id_json, yyjson_val *params) |
| 795 | { |
| 796 | yyjson_val *v; |
| 797 | const char *name = NULL; |
| 798 | char args[WH_BODY_CAP]; |
| 799 | size_t i; |
| 800 | char out[WH_BODY_CAP + WH_PREVIEW_CAP + 4096]; |
| 801 | char err[512]; |
| 802 | |
| 803 | args[0] = '\0'; |
| 804 | if (params) { |
| 805 | v = yyjson_obj_get(params, "name"); |
| 806 | if (v && yyjson_is_str(v)) name = yyjson_get_str(v); |
| 807 | v = yyjson_obj_get(params, "arguments"); |
| 808 | if (v && yyjson_is_obj(v)) { |
| 809 | char *ser = yyjson_val_write(v, 0, NULL); |
| 810 | if (ser) { |
| 811 | copy_trunc(args, sizeof args, ser); |
| 812 | free(ser); |
| 813 | } |
| 814 | } |
| 815 | } |
| 816 | if (!name || !*name) { |
| 817 | mcp_error(id_json, -32602, "invalid params: missing tool name"); |
| 818 | return; |
| 819 | } |
| 820 | for (i = 0; i < sizeof TOOLS / sizeof TOOLS[0]; i++) { |
| 821 | if (strcmp(TOOLS[i].name, name) != 0) continue; |
| 822 | out[0] = '\0'; |
| 823 | err[0] = '\0'; |
| 824 | if (i == 0) { |
| 825 | tool_list(args[0] ? args : "{}", out, sizeof out); |
| 826 | mcp_tool_content(id_json, out, 0); |
| 827 | } else if (TOOLS[i].call) { |
| 828 | int rc = TOOLS[i].call(args, out, sizeof out, err, sizeof err); |
| 829 | if (rc != 0) mcp_tool_content(id_json, err[0] ? err : "tool failed", 1); |
| 830 | else mcp_tool_content(id_json, out, 0); |
| 831 | } |
| 832 | return; |
| 833 | } |
| 834 | mcp_error(id_json, -32602, "unknown tool"); |
| 835 | } |
| 836 | |
| 837 | static void mcp_handle_line(const char *line) |
| 838 | { |
| 839 | yyjson_doc *doc; |
| 840 | yyjson_val *root, *method, *id, *params; |
| 841 | char *id_json = NULL; |
| 842 | const char *m; |
| 843 | |
| 844 | doc = yyjson_read(line, strlen(line), 0); |
| 845 | if (!doc) { mcp_error("null", -32700, "parse error"); return; } |
| 846 | root = yyjson_doc_get_root(doc); |
| 847 | if (!yyjson_is_obj(root)) { |
| 848 | yyjson_doc_free(doc); |
| 849 | mcp_error("null", -32600, "invalid request: not an object"); |
| 850 | return; |
| 851 | } |
| 852 | method = yyjson_obj_get(root, "method"); |
| 853 | id = yyjson_obj_get(root, "id"); |
| 854 | params = yyjson_obj_get(root, "params"); |
| 855 | if (id) { |
| 856 | id_json = yyjson_val_write(id, 0, NULL); |
| 857 | if (!id_json) id_json = strdup("null"); |
| 858 | } |
| 859 | m = (method && yyjson_is_str(method)) ? yyjson_get_str(method) : NULL; |
| 860 | if (!m) { |
| 861 | if (id_json) mcp_error(id_json, -32600, "invalid request: missing method"); |
| 862 | goto done; |
| 863 | } |
| 864 | |
| 865 | if (strcmp(m, "initialize") == 0) { |
| 866 | wh_buf b; |
| 867 | int f = 1; |
| 868 | wh_buf_init(&b); |
| 869 | wh_buf_str(&b, "{"); |
| 870 | wh_buf_key(&b, "protocolVersion", &f); |
| 871 | wh_buf_json_str(&b, "2024-11-05"); |
| 872 | wh_buf_key(&b, "capabilities", &f); |
| 873 | wh_buf_str(&b, "{\"tools\":{}}"); |
| 874 | wh_buf_key(&b, "serverInfo", &f); |
| 875 | wh_buf_str(&b, "{"); |
| 876 | { |
| 877 | int g = 1; |
| 878 | wh_buf_key(&b, "name", &g); |
| 879 | wh_buf_json_str(&b, PLUGIN_ID); |
| 880 | wh_buf_key(&b, "version", &g); |
| 881 | wh_buf_json_str(&b, PLUGIN_VER); |
| 882 | } |
| 883 | wh_buf_str(&b, "}}"); |
| 884 | mcp_result(id_json, wh_buf_cstr(&b)); |
| 885 | wh_buf_free(&b); |
| 886 | } else if (strcmp(m, "notifications/initialized") == 0 || |
| 887 | strcmp(m, "initialized") == 0) { |
| 888 | /* notification: no reply */ |
| 889 | } else if (strcmp(m, "ping") == 0) { |
| 890 | if (id_json) mcp_result(id_json, "{}"); |
| 891 | } else if (strcmp(m, "tools/list") == 0) { |
| 892 | mcp_tools_list(id_json); |
| 893 | } else if (strcmp(m, "tools/call") == 0) { |
| 894 | mcp_call_tool(id_json, params); |
| 895 | } else if (strcmp(m, "prompts/list") == 0) { |
| 896 | if (id_json) mcp_result(id_json, "{\"prompts\":[]}"); |
| 897 | } else if (strcmp(m, "resources/list") == 0) { |
| 898 | if (id_json) mcp_result(id_json, "{\"resources\":[]}"); |
| 899 | } else if (strcmp(m, "logging/setLevel") == 0) { |
| 900 | if (id_json) mcp_result(id_json, "{}"); |
| 901 | } else { |
| 902 | if (id_json) mcp_error(id_json, -32601, "method not found"); |
| 903 | } |
| 904 | |
| 905 | done: |
| 906 | free(id_json); |
| 907 | yyjson_doc_free(doc); |
| 908 | } |
| 909 | |
| 910 | static int mode_mcp(void) |
| 911 | { |
| 912 | wh_buf line; |
| 913 | #if defined(_WIN32) |
| 914 | _setmode(_fileno(stdout), _O_BINARY); |
| 915 | _setmode(_fileno(stdin), _O_BINARY); |
| 916 | #endif |
| 917 | wh_buf_init(&line); |
| 918 | while (read_request_line(&line)) { |
| 919 | if (line.n > 4u * 1024u * 1024u) { |
| 920 | mcp_error("null", -32600, "request too large"); |
| 921 | continue; |
| 922 | } |
| 923 | if (line.n) mcp_handle_line(wh_buf_cstr(&line)); |
| 924 | } |
| 925 | wh_buf_free(&line); |
| 926 | return 0; |
| 927 | } |
| 928 | |
| 929 | static int mode_schema(void) |
| 930 | { |
| 931 | wh_buf b; |
| 932 | size_t i; |
| 933 | wh_buf_init(&b); |
| 934 | wh_buf_str(&b, "{\"tools\":["); |
| 935 | for (i = 0; i < sizeof TOOLS / sizeof TOOLS[0]; i++) { |
| 936 | int f = 1; |
| 937 | if (i) wh_buf_str(&b, ","); |
| 938 | wh_buf_str(&b, "{"); |
| 939 | wh_buf_key(&b, "name", &f); |
| 940 | wh_buf_json_str(&b, TOOLS[i].name); |
| 941 | wh_buf_key(&b, "description", &f); |
| 942 | wh_buf_json_str(&b, TOOLS[i].desc); |
| 943 | wh_buf_key(&b, "inputSchema", &f); |
| 944 | wh_buf_str(&b, TOOLS[i].schema); |
| 945 | wh_buf_str(&b, "}"); |
| 946 | } |
| 947 | wh_buf_str(&b, "]}"); |
| 948 | fputs(wh_buf_cstr(&b), stdout); |
| 949 | fputc('\n', stdout); |
| 950 | wh_buf_free(&b); |
| 951 | return 0; |
| 952 | } |
| 953 | |
| 954 | /* ===================================================================== |
| 955 | * 7. --meta |
| 956 | * ===================================================================== */ |
| 957 | |
| 958 | static int mode_meta(void) |
| 959 | { |
| 960 | printf("{\"name\":\"%s\",\"desc\":\"%s\",\"kind\":\"%s\"," |
| 961 | "\"mcp\":true,\"daemon\":false,\"menus\":false," |
| 962 | "\"verified\":\"live\",\"version\":\"%s\"}\n", |
| 963 | PLUGIN_NAME, PLUGIN_DESC, PLUGIN_KIND, PLUGIN_VER); |
| 964 | return 0; |
| 965 | } |
| 966 | |
| 967 | /* ===================================================================== |
| 968 | * 8. JSON API (?action=…) |
| 969 | * ===================================================================== */ |
| 970 | |
| 971 | static char *read_cgi_body(void) |
| 972 | { |
| 973 | const char *bp = getenv("POST_BODY_FILE"); |
| 974 | const char *cl = getenv("CONTENT_LENGTH"); |
| 975 | wh_buf b; |
| 976 | long want = -1; |
| 977 | char chunk[4096]; |
| 978 | |
| 979 | if (bp && *bp) { |
| 980 | FILE *f = fopen(bp, "rb"); |
| 981 | wh_buf out; |
| 982 | size_t got; |
| 983 | if (!f) return NULL; |
| 984 | wh_buf_init(&out); |
| 985 | while ((got = fread(chunk, 1, sizeof chunk, f)) > 0) wh_buf_add(&out, chunk, got); |
| 986 | fclose(f); |
| 987 | if (!out.p) { |
| 988 | char *e = (char *)malloc(1); |
| 989 | if (e) e[0] = '\0'; |
| 990 | return e; |
| 991 | } |
| 992 | return out.p; |
| 993 | } |
| 994 | if (!cl || !*cl) return NULL; |
| 995 | want = strtol(cl, NULL, 10); |
| 996 | if (want <= 0) return NULL; |
| 997 | if (want > 8 * 1024 * 1024) return NULL; |
| 998 | |
| 999 | wh_buf_init(&b); |
| 1000 | while ((long)b.n < want) { |
| 1001 | size_t ask = sizeof chunk; |
| 1002 | size_t got; |
| 1003 | if ((long)(b.n + ask) > want) ask = (size_t)(want - (long)b.n); |
| 1004 | got = fread(chunk, 1, ask, stdin); |
| 1005 | if (got == 0) break; |
| 1006 | wh_buf_add(&b, chunk, got); |
| 1007 | } |
| 1008 | if (!b.p) { |
| 1009 | char *e = (char *)malloc(1); |
| 1010 | if (e) e[0] = '\0'; |
| 1011 | return e; |
| 1012 | } |
| 1013 | return b.p; |
| 1014 | } |
| 1015 | |
| 1016 | static void api_ok(const char *json) |
| 1017 | { |
| 1018 | cgi_header(200, "application/json; charset=utf-8"); |
| 1019 | fputs(json, stdout); |
| 1020 | fputc('\n', stdout); |
| 1021 | fflush(stdout); |
| 1022 | } |
| 1023 | |
| 1024 | static void api_err(int status, const char *msg) |
| 1025 | { |
| 1026 | wh_buf b; |
| 1027 | int f = 1; |
| 1028 | wh_buf_init(&b); |
| 1029 | wh_buf_str(&b, "{"); |
| 1030 | wh_buf_key(&b, "ok", &f); |
| 1031 | wh_buf_str(&b, "false"); |
| 1032 | wh_buf_key(&b, "error", &f); |
| 1033 | wh_buf_json_str(&b, msg ? msg : "error"); |
| 1034 | wh_buf_str(&b, "}"); |
| 1035 | cgi_header(status, "application/json; charset=utf-8"); |
| 1036 | fputs(wh_buf_cstr(&b), stdout); |
| 1037 | fputc('\n', stdout); |
| 1038 | fflush(stdout); |
| 1039 | wh_buf_free(&b); |
| 1040 | } |
| 1041 | |
| 1042 | static int mode_api(const char *qs, const char *action) |
| 1043 | { |
| 1044 | wh_store s; |
| 1045 | char err[320]; |
| 1046 | char *body; |
| 1047 | int rc = 0; |
| 1048 | |
| 1049 | body = read_cgi_body(); |
| 1050 | memset(&s, 0, sizeof s); |
| 1051 | if (wh_store_load(&s, err, sizeof err) != 0) { |
| 1052 | api_err(500, err); |
| 1053 | free(body); |
| 1054 | return 0; |
| 1055 | } |
| 1056 | |
| 1057 | if (!action || !*action || strcmp(action, "list") == 0 || |
| 1058 | strcmp(action, "status") == 0) { |
| 1059 | char *out = (char *)malloc(256 * 1024); |
| 1060 | if (!out) { api_err(500, "out of memory"); free(body); return 0; } |
| 1061 | wh_store_list_json(&s, out, 256 * 1024); |
| 1062 | api_ok(out); |
| 1063 | free(out); |
| 1064 | } else if (strcmp(action, "save") == 0) { |
| 1065 | store_op op; |
| 1066 | char edit[WH_NAME_MAX]; |
| 1067 | edit[0] = '\0'; |
| 1068 | get_query_val(qs, "name", edit, sizeof edit); |
| 1069 | if (!body || !*body) { |
| 1070 | api_err(400, "save needs a JSON body"); |
| 1071 | } else if (save_hook_from_json(&s, body, edit, &op) != 0) { |
| 1072 | api_err(400, op.error); |
| 1073 | } else { |
| 1074 | wh_buf b; |
| 1075 | int f = 1; |
| 1076 | wh_buf_init(&b); |
| 1077 | wh_buf_str(&b, "{"); |
| 1078 | wh_buf_key(&b, "ok", &f); |
| 1079 | wh_buf_str(&b, "true"); |
| 1080 | wh_buf_key(&b, "saved", &f); |
| 1081 | wh_buf_json_str(&b, op.name); |
| 1082 | wh_buf_str(&b, "}"); |
| 1083 | api_ok(wh_buf_cstr(&b)); |
| 1084 | wh_buf_free(&b); |
| 1085 | } |
| 1086 | } else if (strcmp(action, "delete") == 0 || strcmp(action, "remove") == 0) { |
| 1087 | char name[WH_NAME_MAX]; |
| 1088 | wh_hook *h; |
| 1089 | name[0] = '\0'; |
| 1090 | get_query_val(qs, "name", name, sizeof name); |
| 1091 | if (!name[0] && body && *body) { |
| 1092 | yyjson_doc *doc = yyjson_read(body, strlen(body), 0); |
| 1093 | if (doc) { |
| 1094 | yyjson_val *v = yyjson_obj_get(yyjson_doc_get_root(doc), "name"); |
| 1095 | if (v && yyjson_is_str(v)) copy_trunc(name, sizeof name, yyjson_get_str(v)); |
| 1096 | yyjson_doc_free(doc); |
| 1097 | } |
| 1098 | } |
| 1099 | if (!name[0]) { api_err(400, "delete needs a name"); } |
| 1100 | else { |
| 1101 | int idx = -1, i; |
| 1102 | for (i = 0; i < s.nhooks; i++) |
| 1103 | if (strcmp(s.hooks[i].name, name) == 0) { idx = i; break; } |
| 1104 | if (idx < 0) { api_err(404, "no such hook"); } |
| 1105 | else { |
| 1106 | wh_hook_remove(&s, idx); |
| 1107 | if (wh_store_save(&s, err, sizeof err) != 0) api_err(500, err); |
| 1108 | else api_ok("{\"ok\":true,\"deleted\":true}"); |
| 1109 | } |
| 1110 | } |
| 1111 | (void)h; |
| 1112 | } else if (strcmp(action, "fire") == 0 || strcmp(action, "trigger") == 0 || |
| 1113 | strcmp(action, "test") == 0) { |
| 1114 | char name[WH_NAME_MAX], payload[WH_BODY_CAP], query[512]; |
| 1115 | wh_hook *h; |
| 1116 | fire_result res; |
| 1117 | |
| 1118 | name[0] = '\0'; payload[0] = '\0'; query[0] = '\0'; |
| 1119 | get_query_val(qs, "name", name, sizeof name); |
| 1120 | get_query_val(qs, "query", query, sizeof query); |
| 1121 | get_query_val(qs, "payload", payload, sizeof payload); |
| 1122 | if (!payload[0] && body && *body) { |
| 1123 | yyjson_doc *doc = yyjson_read(body, strlen(body), 0); |
| 1124 | if (doc) { |
| 1125 | yyjson_val *root = yyjson_doc_get_root(doc), *v; |
| 1126 | v = yyjson_obj_get(root, "name"); |
| 1127 | if (!name[0] && v && yyjson_is_str(v)) |
| 1128 | copy_trunc(name, sizeof name, yyjson_get_str(v)); |
| 1129 | v = yyjson_obj_get(root, "query"); |
| 1130 | if (!query[0] && v && yyjson_is_str(v)) |
| 1131 | copy_trunc(query, sizeof query, yyjson_get_str(v)); |
| 1132 | v = yyjson_obj_get(root, "payload"); |
| 1133 | if (v) { |
| 1134 | if (yyjson_is_str(v)) copy_trunc(payload, sizeof payload, yyjson_get_str(v)); |
| 1135 | else { |
| 1136 | char *ser = yyjson_val_write(v, 0, NULL); |
| 1137 | if (ser) { copy_trunc(payload, sizeof payload, ser); free(ser); } |
| 1138 | } |
| 1139 | } |
| 1140 | yyjson_doc_free(doc); |
| 1141 | } |
| 1142 | } |
| 1143 | if (!name[0]) { |
| 1144 | api_err(400, "fire needs a hook name"); |
| 1145 | } else if (!(h = wh_hook_find(&s, name))) { |
| 1146 | api_err(404, "no such hook"); |
| 1147 | } else { |
| 1148 | wh_buf b; |
| 1149 | int f = 1; |
| 1150 | wh_logent le; |
| 1151 | |
| 1152 | if (!payload[0]) copy_trunc(payload, sizeof payload, "{}"); |
| 1153 | if (fire_hook(h, payload, strlen(payload), query, &res) != 0) { |
| 1154 | wh_buf_init(&b); |
| 1155 | wh_buf_str(&b, "{"); |
| 1156 | wh_buf_key(&b, "ok", &f); wh_buf_str(&b, "false"); |
| 1157 | wh_buf_key(&b, "delivered", &f); wh_buf_str(&b, "false"); |
| 1158 | wh_buf_key(&b, "error", &f); wh_buf_json_str(&b, res.error); |
| 1159 | wh_buf_str(&b, "}"); |
| 1160 | iso_now(le.at, sizeof le.at); |
| 1161 | copy_trunc(le.name, sizeof le.name, name); |
| 1162 | le.status = 0; |
| 1163 | le.ok = 0; |
| 1164 | le.bytes = 0; |
| 1165 | le.ms = res.ms; |
| 1166 | copy_trunc(le.error, sizeof le.error, res.error); |
| 1167 | wh_store_log_add(&s, &le); |
| 1168 | wh_store_save(&s, err, sizeof err); |
| 1169 | cgi_header(502, "application/json; charset=utf-8"); |
| 1170 | fputs(wh_buf_cstr(&b), stdout); |
| 1171 | fputc('\n', stdout); |
| 1172 | wh_buf_free(&b); |
| 1173 | } else { |
| 1174 | wh_buf_init(&b); |
| 1175 | wh_buf_str(&b, "{"); |
| 1176 | wh_buf_key(&b, "ok", &f); wh_buf_str(&b, "true"); |
| 1177 | wh_buf_key(&b, "delivered", &f); wh_buf_str(&b, "true"); |
| 1178 | wh_buf_key(&b, "status", &f); wh_buf_printf(&b, "%d", res.status); |
| 1179 | wh_buf_key(&b, "ok_status", &f); wh_buf_str(&b, status_is_ok(res.status) ? "true" : "false"); |
| 1180 | wh_buf_key(&b, "ms", &f); wh_buf_printf(&b, "%ld", res.ms); |
| 1181 | wh_buf_key(&b, "bytes", &f); wh_buf_printf(&b, "%lu", (unsigned long)res.body_len); |
| 1182 | wh_buf_key(&b, "truncated", &f); wh_buf_str(&b, res.truncated ? "true" : "false"); |
| 1183 | wh_buf_key(&b, "body_preview", &f); wh_buf_json_str(&b, res.body); |
| 1184 | wh_buf_str(&b, "}"); |
| 1185 | api_ok(wh_buf_cstr(&b)); |
| 1186 | wh_buf_free(&b); |
| 1187 | |
| 1188 | iso_now(le.at, sizeof le.at); |
| 1189 | copy_trunc(le.name, sizeof le.name, name); |
| 1190 | le.status = res.status; |
| 1191 | le.ok = status_is_ok(res.status) ? 1 : 0; |
| 1192 | le.bytes = (long)res.body_len; |
| 1193 | le.ms = res.ms; |
| 1194 | le.error[0] = '\0'; |
| 1195 | wh_store_log_add(&s, &le); |
| 1196 | wh_store_save(&s, err, sizeof err); |
| 1197 | } |
| 1198 | } |
| 1199 | } else { |
| 1200 | api_err(400, "unknown action"); |
| 1201 | } |
| 1202 | |
| 1203 | free(body); |
| 1204 | return rc; |
| 1205 | } |
| 1206 | |
| 1207 | /* ===================================================================== |
| 1208 | * 9. HTML page |
| 1209 | * ===================================================================== */ |
| 1210 | |
| 1211 | static int mode_html(const char *qs, int embed, const char *theme) |
| 1212 | { |
| 1213 | const char *p = UI_HTML; |
| 1214 | |
| 1215 | cgi_header(200, "text/html; charset=utf-8"); |
| 1216 | while (*p) { |
| 1217 | /* 0x01 -> the theme block (prepaint + tokens), 0x02 -> the handoff. */ |
| 1218 | if ((unsigned char)*p == 0x01) { |
| 1219 | fputs(SX_BOT_THEME_PREPAINT, stdout); |
| 1220 | if (theme && strcmp(theme, "light") == 0) |
| 1221 | fputs("<script>document.documentElement.setAttribute('data-theme','light');</script>", stdout); |
| 1222 | fputs("<style>", stdout); |
| 1223 | fputs(SX_BOT_THEME_TOKENS, stdout); |
| 1224 | fputs("</style>\n", stdout); |
| 1225 | p++; |
| 1226 | continue; |
| 1227 | } |
| 1228 | if ((unsigned char)*p == 0x02) { |
| 1229 | fputs(SX_BOT_THEME_HANDOFF, stdout); |
| 1230 | fputs(SX_BOT_THEME_TOGGLE_JS, stdout); |
| 1231 | p++; |
| 1232 | continue; |
| 1233 | } |
| 1234 | fputc(*p, stdout); |
| 1235 | p++; |
| 1236 | } |
| 1237 | (void)qs; |
| 1238 | (void)embed; |
| 1239 | return 0; |
| 1240 | } |
| 1241 | |
| 1242 | /* ===================================================================== |
| 1243 | * 10. main |
| 1244 | * ===================================================================== */ |
| 1245 | |
| 1246 | int main(int argc, char **argv) |
| 1247 | { |
| 1248 | int i, meta = 0, mcp = 0, schema = 0, embed = 0; |
| 1249 | const char *qs, *theme; |
| 1250 | char qs2[4096], action[64]; |
| 1251 | char *qmark; |
| 1252 | |
| 1253 | /* MinGW: \n must stay \n. A plugin that writes its own CRLF headers in |
| 1254 | * text mode emits CR CR LF and the CGI parser splits the head in the wrong |
| 1255 | * place. Applies to every mode, not just --mcp. */ |
| 1256 | #if defined(_WIN32) |
| 1257 | _setmode(_fileno(stdout), _O_BINARY); |
| 1258 | _setmode(_fileno(stdin), _O_BINARY); |
| 1259 | #endif |
| 1260 | |
| 1261 | for (i = 1; i < argc; i++) { |
| 1262 | if (strcmp(argv[i], "--meta") == 0) meta = 1; |
| 1263 | else if (strcmp(argv[i], "--mcp") == 0) mcp = 1; |
| 1264 | else if (strcmp(argv[i], "--schema") == 0) schema = 1; |
| 1265 | else if (strcmp(argv[i], "--version") == 0) { |
| 1266 | printf("%s %s (%s)\n", PLUGIN_ID, PLUGIN_VER, PLUGIN_NAME); |
| 1267 | return 0; |
| 1268 | } |
| 1269 | } |
| 1270 | |
| 1271 | if (meta || getenv("SX_PLUGIN_META")) return mode_meta(); |
| 1272 | if (schema) return mode_schema(); |
| 1273 | if (mcp) return mode_mcp(); |
| 1274 | |
| 1275 | qs = getenv("QUERY_STRING"); |
| 1276 | if (!qs) qs = ""; |
| 1277 | copy_trunc(qs2, sizeof qs2, qs); |
| 1278 | qmark = strchr(qs2, '?'); |
| 1279 | if (qmark) memmove(qs2, qmark + 1, strlen(qmark)); |
| 1280 | |
| 1281 | action[0] = '\0'; |
| 1282 | get_query_val(qs2, "action", action, sizeof action); |
| 1283 | embed = 0; |
| 1284 | { |
| 1285 | char e[16]; |
| 1286 | if (get_query_val(qs2, "embed", e, sizeof e)) |
| 1287 | embed = strcmp(e, "1") == 0 || ieq(e, "true"); |
| 1288 | } |
| 1289 | theme = "dark"; |
| 1290 | { |
| 1291 | char t[16]; |
| 1292 | if (get_query_val(qs2, "theme", t, sizeof t)) theme = ieq(t, "light") ? "light" : "dark"; |
| 1293 | } |
| 1294 | |
| 1295 | if (action[0] || strstr(qs2, "format=json") || |
| 1296 | (getenv("REQUEST_METHOD") && ieq(getenv("REQUEST_METHOD"), "POST"))) { |
| 1297 | require_node_auth(); |
| 1298 | return mode_api(qs2, action); |
| 1299 | } |
| 1300 | |
| 1301 | require_node_auth(); |
| 1302 | return mode_html(qs2, embed, theme); |
| 1303 | } |