scorpiox-bot-plugin-websearch
←plugin_websearch.cc
1076 lines · 38 KBHEADBlameDownload
1/*
2 * plugin_websearch.c - entry point and HTTP front end for the SCORPIOX BOT
3 * multi-provider web search connector.
4 *
5 * One binary, five modes, exactly as the plugin_<name> spec requires:
6 *
7 * 1. --meta / SX_PLUGIN_META=1 one line of discovery JSON, exit 0.
8 * Unauthenticated on purpose: /plugins probes it, and the
9 * sx-connector-mcp router probes it before it will run anything else.
10 * 2. --mcp MCP JSON-RPC 2.0 over stdio, one request
11 * per line, one response per line. Through the single sx-connector-mcp
12 * router this is what makes the plugin a tool provider for SCORPIOX CODE
13 * with no clang change and no extra MCP server slot.
14 * 3. --schema the tools/list array, for a human.
15 * 4. ?action=... | ?format=json | POST -> the JSON API the page talks to.
16 * Same two tools as --mcp, so the page can never drift from the agent.
17 * 5. GET (default) the providers / keys / live-search page.
18 *
19 * Modes 4 and 5 sit behind require_node_auth(): a node's :8150 is reachable
20 * from the LAN. --meta and --mcp stay open so discovery and the router work;
21 * neither answers a web request.
22 *
23 * What is never returned: an API key. The page and the JSON API report
24 * `has_key` booleans, and the saved key is written to config.json at 0600 in
25 * the connector directory.
26 *
27 * MIT License. Copyright (c) 2026 SCORPIOX INC.
28 */
29
30#if defined(_WIN32) && !defined(_WIN32_WINNT)
31# define _WIN32_WINNT 0x0601
32#endif
33
34#if !defined(_WIN32)
35# define _POSIX_C_SOURCE 200809L
36# define _DEFAULT_SOURCE 1
37# if defined(__APPLE__)
38# define _DARWIN_C_SOURCE 1
39# endif
40#endif
41
42#include <stdio.h>
43#include <stdlib.h>
44#include <string.h>
45#include <ctype.h>
46
47#if defined(_WIN32)
48# define WIN32_LEAN_AND_MEAN
49# include <windows.h>
50# include <io.h>
51# include <fcntl.h>
52/* MinGW's CRT starts stdout in TEXT mode and rewrites every \n into \r\n. A
53 * CGI header block must end with exactly CRLF CRLF; text mode turns that into
54 * \r\r\n\r\r\n, scorpiox-server never finds the separator, and the whole reply
55 * (headers included) is served as a body. Force binary stdio before main(). */
56__attribute__((constructor))
57static void sx_plugin_binary_stdio(void)
58{
59 _setmode(_fileno(stdout), _O_BINARY);
60 _setmode(_fileno(stdin), _O_BINARY);
61}
62#else
63# include <unistd.h>
64#endif
65
66#include "ws.h"
67#include "bot_theme_plugin.h"
68#include "ui_html.h"
69
70/* ------------------------------------------------------------------ */
71/* --meta */
72/* */
73/* `desc` is 14 characters: the platform contract is <= 15, and the task */
74/* brief's suggested "Multi-web search" is 16 - it would be rejected by */
75/* the discovery-chip rule, so it is shortened rather than kept. */
76/* ------------------------------------------------------------------ */
77
78static int mode_meta(void)
79{
80 printf("{\"name\":\"%s\",\"desc\":\"%s\",\"kind\":\"mcp\",\"mcp\":true,"
81 "\"daemon\":false,\"menus\":false,\"verified\":\"mock\","
82 "\"category\":\"network\",\"version\":\"%s\"}\n",
83 WS_NAME, WS_DESC, WS_VER);
84 fflush(stdout);
85 return 0;
86}
87
88/* ------------------------------------------------------------------ */
89/* MCP over stdio */
90/* ------------------------------------------------------------------ */
91
92static void send_raw(const char *json)
93{
94 fputs(json, stdout);
95 fputc('\n', stdout);
96 fflush(stdout);
97}
98
99static void send_result_raw(const char *id_json, const char *result_json)
100{
101 printf("{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":%s}\n",
102 id_json ? id_json : "null", result_json ? result_json : "{}");
103 fflush(stdout);
104}
105
106static void send_result(yyjson_val *id, const char *result_json)
107{
108 char *js = id ? yyjson_val_write(id, 0, NULL) : NULL;
109 send_result_raw(js ? js : "null", result_json);
110 free(js);
111}
112
113static void send_error(yyjson_val *id, int code, const char *msg)
114{
115 ws_buf b;
116 char *js = id ? yyjson_val_write(id, 0, NULL) : NULL;
117
118 ws_buf_init(&b);
119 ws_buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":");
120 /* A parse error has no id to echo; the spec says answer with null, and a
121 * silent drop makes a broken client look like a hung server. */
122 ws_buf_puts(&b, js ? js : "null");
123 ws_buf_printf(&b, ",\"error\":{\"code\":%d,\"message\":", code);
124 ws_json_str(&b, msg ? msg : "error");
125 ws_buf_puts(&b, "}}");
126 send_raw(ws_buf_str(&b));
127 ws_buf_free(&b);
128 free(js);
129}
130
131/* ---------------------------------------------------------------- tools */
132
133static char *tools_json(void)
134{
135 static const char *const TOOLS =
136 "["
137 "{"
138 "\"name\":\"web_search\","
139 "\"description\":\"Search the web and return ranked results (title, url, "
140 "snippet, published date, site). The provider is chosen by the user's "
141 "configuration unless one is named: duckduckgo needs no key, searxng "
142 "needs a self-hosted base URL, and brave/tavily/exa/perplexity need an "
143 "API key saved on the plugin page or in the environment. Use this for "
144 "anything current (news, releases, prices, documentation that may have "
145 "moved); for reading one specific page in full use a URL-fetch tool "
146 "instead.\","
147 "\"inputSchema\":{"
148 "\"type\":\"object\","
149 "\"properties\":{"
150 "\"query\":{\"type\":\"string\",\"description\":\"The search query.\"},"
151 "\"provider\":{\"type\":\"string\","
152 "\"enum\":[\"duckduckgo\",\"searxng\",\"brave\",\"tavily\",\"exa\",\"perplexity\"],"
153 "\"description\":\"Which backend to use. Omit to use the configured default.\"},"
154 "\"count\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":20,"
155 "\"description\":\"How many results to return (default 5).\"},"
156 "\"country\":{\"type\":\"string\","
157 "\"description\":\"Two-letter country code for region-specific results "
158 "(Brave only), e.g. NZ, US, ALL.\"},"
159 "\"language\":{\"type\":\"string\","
160 "\"description\":\"ISO 639-1 language code, e.g. en, de, fr.\"},"
161 "\"freshness\":{\"type\":\"string\","
162 "\"enum\":[\"day\",\"week\",\"month\",\"year\"],"
163 "\"description\":\"Only results from this recent window (Brave only).\"}"
164 "},"
165 "\"required\":[\"query\"]"
166 "}"
167 "},"
168 "{"
169 "\"name\":\"web_search_providers\","
170 "\"description\":\"List the web-search backends this node can use: which are "
171 "configured, which are missing a key or base URL, and which one is the "
172 "default. Never returns a key, only whether one is present.\","
173 "\"inputSchema\":{\"type\":\"object\",\"properties\":{}}"
174 "}"
175 "]";
176 size_t n = strlen(TOOLS);
177 char *p = (char *)malloc(n + 1);
178 if (!p) return NULL;
179 memcpy(p, TOOLS, n + 1);
180 return p;
181}
182
183/* The providers answer, shared by --mcp and the JSON API. */
184static char *providers_json(const ws_config *cfg)
185{
186 ws_buf b;
187 int i;
188 const char *active = ws_provider_active(cfg);
189
190 ws_buf_init(&b);
191 ws_buf_puts(&b, "{\"active\":");
192 ws_json_str(&b, active);
193 ws_buf_puts(&b, ",\"providers\":[");
194 for (i = 0; i < WS_PROVIDER_COUNT; i++) {
195 const ws_provider_info *p = &WS_PROVIDERS[i];
196 if (i) ws_buf_putc(&b, ',');
197 ws_buf_puts(&b, "{\"id\":");
198 ws_json_str(&b, p->id);
199 ws_buf_puts(&b, ",\"label\":");
200 ws_json_str(&b, p->label);
201 ws_buf_puts(&b, ",\"hint\":");
202 ws_json_str(&b, p->hint);
203 ws_buf_puts(&b, ",\"signup\":");
204 ws_json_str(&b, p->signup);
205 ws_buf_printf(&b, ",\"needs_key\":%s,\"needs_base\":%s,\"has_key\":%s,"
206 "\"ready\":%s",
207 p->needs_key ? "true" : "false",
208 p->needs_base ? "true" : "false",
209 ws_provider_has_key(cfg, p->id) ? "true" : "false",
210 ws_provider_ready(cfg, p->id) ? "true" : "false");
211 if (p->needs_base) {
212 ws_buf_puts(&b, ",\"base\":");
213 ws_json_str(&b, cfg->searxng_base);
214 }
215 ws_buf_putc(&b, '}');
216 }
217 ws_buf_puts(&b, "],\"default_count\":");
218 ws_buf_printf(&b, "%d", cfg->count);
219 ws_buf_puts(&b, ",\"region\":");
220 ws_json_str(&b, cfg->region);
221 ws_buf_puts(&b, ",\"safe\":");
222 ws_json_str(&b, cfg->safe);
223 ws_buf_puts(&b, ",\"language\":");
224 ws_json_str(&b, cfg->language);
225 ws_buf_puts(&b, ",\"searxng_categories\":");
226 ws_json_str(&b, cfg->searxng_categories);
227 ws_buf_printf(&b, ",\"tavily_advanced\":%s,\"tavily_answer\":%s",
228 cfg->tavily_advanced ? "true" : "false",
229 cfg->tavily_answer ? "true" : "false");
230 ws_buf_putc(&b, '}');
231 return b.p;
232}
233
234/* The MCP result envelope: content[] text + structuredContent + isError. */
235static char *mcp_envelope(char *payload, int is_error)
236{
237 ws_buf b;
238 char *escaped = NULL;
239 size_t n;
240
241 ws_buf_init(&b);
242 ws_buf_puts(&b, "{\"content\":[{\"type\":\"text\",\"text\":");
243 if (payload) {
244 ws_json_str(&b, payload);
245 } else {
246 ws_buf_puts(&b, "\"\"");
247 }
248 ws_buf_puts(&b, "}]");
249 if (payload) {
250 ws_buf_puts(&b, ",\"structuredContent\":");
251 ws_buf_puts(&b, payload);
252 }
253 if (is_error) ws_buf_puts(&b, ",\"isError\":true");
254 ws_buf_putc(&b, '}');
255 escaped = b.p;
256 n = b.n;
257 (void)n;
258 return escaped;
259}
260
261/* Render a search as the JSON the agent reads. */
262static char *results_json(const ws_results *r)
263{
264 ws_buf b;
265 int i;
266
267 ws_buf_init(&b);
268 ws_buf_puts(&b, "{\"ok\":true,\"query\":");
269 ws_json_str(&b, r->query);
270 ws_buf_puts(&b, ",\"provider\":");
271 ws_json_str(&b, r->provider);
272 ws_buf_printf(&b, ",\"count\":%d,\"took_ms\":%lld", r->n, r->took_ms);
273 if (r->answer.p && r->answer.n)
274 {
275 ws_buf_puts(&b, ",\"answer\":");
276 ws_json_str(&b, ws_buf_str(&r->answer));
277 }
278 if (r->citations.p && r->citations.n)
279 {
280 ws_buf_puts(&b, ",\"citations\":");
281 ws_json_str(&b, ws_buf_str(&r->citations));
282 }
283 ws_buf_puts(&b, ",\"results\":[");
284 for (i = 0; i < r->n; i++) {
285 const ws_result *it = &r->items[i];
286 if (i) ws_buf_putc(&b, ',');
287 ws_buf_puts(&b, "{\"title\":");
288 ws_json_str(&b, it->title);
289 ws_buf_puts(&b, ",\"url\":");
290 ws_json_str(&b, it->url);
291 ws_buf_puts(&b, ",\"snippet\":");
292 ws_json_str(&b, it->snippet);
293 if (it->published[0]) {
294 ws_buf_puts(&b, ",\"published\":");
295 ws_json_str(&b, it->published);
296 }
297 if (it->site[0]) {
298 ws_buf_puts(&b, ",\"site\":");
299 ws_json_str(&b, it->site);
300 }
301 ws_buf_putc(&b, '}');
302 }
303 ws_buf_puts(&b, "]}");
304 return b.p;
305}
306
307/* A one-line human summary for the MCP text block. */
308static char *results_text(const ws_results *r)
309{
310 ws_buf b;
311 int i;
312
313 ws_buf_init(&b);
314 ws_buf_printf(&b, "%d result(s) from %s for \"%s\" in %lld ms\n",
315 r->n, r->provider, r->query, r->took_ms);
316 if (r->answer.p && r->answer.n) {
317 ws_buf_puts(&b, "\nAnswer: ");
318 ws_buf_puts(&b, ws_buf_str(&r->answer));
319 ws_buf_putc(&b, '\n');
320 }
321 for (i = 0; i < r->n; i++) {
322 const ws_result *it = &r->items[i];
323 ws_buf_printf(&b, "\n%d. %s\n %s\n", i + 1,
324 it->title[0] ? it->title : "(untitled)", it->url);
325 if (it->snippet[0]) ws_buf_printf(&b, " %s\n", it->snippet);
326 if (it->published[0]) ws_buf_printf(&b, " published: %s\n", it->published);
327 }
328 return b.p;
329}
330
331/* --------------------------------------------------------- tool dispatch */
332
333/* A tool result: 0 ok, 1 tool-level failure (err set), 2 unknown tool. */
334static int run_web_search(const ws_config *cfg, yyjson_val *args, ws_results *r,
335 long *status_out, char *err, size_t errsz)
336{
337 char query[512];
338 char provider[WS_ID_MAX];
339 char country[16];
340 char language[16];
341 char freshness[16];
342 int count = 0;
343
344 query[0] = provider[0] = country[0] = language[0] = freshness[0] = '\0';
345 if (args && yyjson_is_obj(args)) {
346 yyjson_val *v;
347 v = yyjson_obj_get(args, "query");
348 if (v && yyjson_is_str(v)) ws_copy(query, sizeof query, yyjson_get_str(v));
349 v = yyjson_obj_get(args, "provider");
350 if (v && yyjson_is_str(v)) ws_copy(provider, sizeof provider, yyjson_get_str(v));
351 v = yyjson_obj_get(args, "country");
352 if (v && yyjson_is_str(v)) ws_copy(country, sizeof country, yyjson_get_str(v));
353 v = yyjson_obj_get(args, "language");
354 if (v && yyjson_is_str(v)) ws_copy(language, sizeof language, yyjson_get_str(v));
355 v = yyjson_obj_get(args, "freshness");
356 if (v && yyjson_is_str(v)) ws_copy(freshness, sizeof freshness, yyjson_get_str(v));
357 v = yyjson_obj_get(args, "count");
358 if (v) {
359 if (yyjson_is_int(v)) count = (int)yyjson_get_int(v);
360 else if (yyjson_is_str(v)) count = atoi(yyjson_get_str(v));
361 }
362 }
363 if (!query[0]) {
364 ws_copy(err, errsz, "query is required");
365 return 1;
366 }
367 if (ws_search(cfg, provider, query, count, country, language, freshness,
368 NULL, r, status_out, err, errsz) != 0)
369 return 1;
370 return 0;
371}
372
373static void handle_request(const ws_config *cfg, yyjson_val *root,
374 yyjson_val *id, const char *method)
375{
376 if (strcmp(method, "initialize") == 0) {
377 ws_buf b;
378 ws_buf_init(&b);
379 ws_buf_puts(&b, "{\"protocolVersion\":\"" WS_MCP_PROTOCOL "\","
380 "\"capabilities\":{\"tools\":{\"listChanged\":false}},"
381 "\"serverInfo\":{\"name\":\"" WS_SERVER_NAME "\","
382 "\"version\":\"" WS_VER "\"},\"instructions\":");
383 ws_buf_printf(&b,
384 "\"Web search across six backends: duckduckgo (no key), searxng "
385 "(self-hosted), brave, tavily, exa and perplexity (API key). The "
386 "default provider on this node is %s. web_search returns ranked "
387 "title/url/snippet results; web_search_providers reports which "
388 "backends are configured. A key is never returned, only "
389 "has_key.\"", ws_provider_active(cfg));
390 ws_buf_putc(&b, '}');
391 send_result(id, ws_buf_str(&b));
392 ws_buf_free(&b);
393 return;
394 }
395 if (strcmp(method, "ping") == 0) {
396 send_result(id, "{}");
397 return;
398 }
399 if (strcmp(method, "tools/list") == 0) {
400 char *tools = tools_json();
401 ws_buf b;
402 ws_buf_init(&b);
403 ws_buf_puts(&b, "{\"tools\":");
404 ws_buf_puts(&b, tools ? tools : "[]");
405 ws_buf_puts(&b, "}");
406 send_result(id, ws_buf_str(&b));
407 ws_buf_free(&b);
408 free(tools);
409 return;
410 }
411 if (strcmp(method, "tools/call") == 0) {
412 yyjson_val *params = yyjson_obj_get(root, "params");
413 const char *name = NULL;
414 yyjson_val *args = NULL;
415
416 if (params && yyjson_is_obj(params)) {
417 yyjson_val *nv = yyjson_obj_get(params, "name");
418 if (nv && yyjson_is_str(nv)) name = yyjson_get_str(nv);
419 args = yyjson_obj_get(params, "arguments");
420 if (args && !yyjson_is_obj(args)) args = NULL;
421 }
422 if (!name) {
423 send_error(id, -32602, "tools/call needs params.name");
424 return;
425 }
426 if (strcmp(name, "web_search_providers") == 0) {
427 char *p = providers_json(cfg);
428 char *env = mcp_envelope(p, 0);
429 send_result(id, env ? env : "{\"content\":[]}");
430 free(env);
431 free(p);
432 return;
433 }
434 if (strcmp(name, "web_search") == 0) {
435 ws_results r;
436 char err[512];
437 char *payload, *text, *env;
438 long status = 0;
439 int rc;
440
441 ws_results_init(&r);
442 err[0] = '\0';
443 rc = run_web_search(cfg, args, &r, &status, err, sizeof err);
444 if (rc != 0) {
445 ws_buf b;
446 ws_buf_init(&b);
447 ws_buf_puts(&b, "{\"ok\":false,\"error\":");
448 ws_json_str(&b, err);
449 if (status) ws_buf_printf(&b, ",\"status\":%ld", status);
450 ws_buf_putc(&b, '}');
451 env = mcp_envelope(b.p, 1);
452 send_result(id, env ? env : "{\"content\":[],\"isError\":true}");
453 free(env);
454 ws_buf_free(&b);
455 ws_results_free(&r);
456 return;
457 }
458 payload = results_json(&r);
459 text = results_text(&r);
460 {
461 ws_buf b;
462 ws_buf_init(&b);
463 ws_buf_puts(&b, "{\"content\":[{\"type\":\"text\",\"text\":");
464 ws_json_str(&b, text ? text : "");
465 ws_buf_puts(&b, "}],\"structuredContent\":");
466 ws_buf_puts(&b, payload ? payload : "{}");
467 ws_buf_putc(&b, '}');
468 send_result(id, ws_buf_str(&b));
469 ws_buf_free(&b);
470 }
471 free(text);
472 free(payload);
473 ws_results_free(&r);
474 return;
475 }
476 send_error(id, -32602, "unknown tool");
477 return;
478 }
479 if (strcmp(method, "resources/list") == 0) {
480 send_result(id, "{\"resources\":[]}");
481 return;
482 }
483 if (strcmp(method, "resources/templates/list") == 0) {
484 send_result(id, "{\"resourceTemplates\":[]}");
485 return;
486 }
487 if (strcmp(method, "prompts/list") == 0) {
488 send_result(id, "{\"prompts\":[]}");
489 return;
490 }
491 send_error(id, -32601, "Method not found");
492}
493
494static int mode_mcp(void)
495{
496 ws_config cfg;
497 char *line = (char *)malloc((size_t)WS_STDIN_LINE_MAX);
498
499 if (!line) return 1;
500 ws_config_load(&cfg);
501
502 for (;;) {
503 size_t n = 0;
504 int c;
505
506 /* Byte at a time, not fgets: a fixed buffer truncates a long arguments
507 * object and the truncated line parses as valid-but-wrong JSON. */
508 for (;;) {
509 c = fgetc(stdin);
510 if (c == EOF) break;
511 if (c == '\n') break;
512 if (n + 1 < (size_t)WS_STDIN_LINE_MAX) line[n++] = (char)c;
513 }
514 line[n] = '\0';
515 if (n == 0) {
516 if (c == EOF) { free(line); return 0; }
517 continue;
518 }
519 {
520 yyjson_doc *doc = yyjson_read(line, n, 0);
521 yyjson_val *root, *mv, *id;
522 const char *method;
523
524 if (!doc) {
525 send_error(NULL, -32700, "Parse error: not valid JSON");
526 continue;
527 }
528 root = yyjson_doc_get_root(doc);
529 if (!root || !yyjson_is_obj(root)) {
530 yyjson_doc_free(doc);
531 send_error(NULL, -32600, "Invalid request: expected an object");
532 continue;
533 }
534 mv = yyjson_obj_get(root, "method");
535 method = (mv && yyjson_is_str(mv)) ? yyjson_get_str(mv) : NULL;
536 id = yyjson_obj_get(root, "id");
537 if (!method) {
538 /* A notification (no method, no id) is not an error; a request
539 * without a method is. A jsonrpc 2.0 notification has a method
540 * and no id, so this branch is only reached by garbage. */
541 if (id) send_error(id, -32600, "Invalid request: missing method");
542 yyjson_doc_free(doc);
543 continue;
544 }
545 if (!id) {
546 /* notifications/initialized and friends: no response at all. */
547 yyjson_doc_free(doc);
548 continue;
549 }
550 handle_request(&cfg, root, id, method);
551 yyjson_doc_free(doc);
552 }
553 }
554}
555
556static int mode_schema(void)
557{
558 char *tools = tools_json();
559 if (!tools) return 1;
560 printf("{\"tools\":%s}\n", tools);
561 fflush(stdout);
562 free(tools);
563 return 0;
564}
565
566static void print_help(void)
567{
568 fputs("plugin_websearch " WS_VER " - SCORPIOX BOT multi-provider web search\n"
569 "\n"
570 " plugin_websearch --meta discovery JSON (unauthenticated)\n"
571 " plugin_websearch --mcp MCP JSON-RPC 2.0 over stdio\n"
572 " plugin_websearch --schema the tools/list array\n"
573 " plugin_websearch --selftest resolve the configuration and exit\n"
574 "\n"
575 "Tools: web_search (query, provider, count, country, language,\n"
576 " freshness)\n"
577 " web_search_providers\n"
578 "\n"
579 "CGI: GET (page), ?action=providers|search|config|save|info,\n"
580 " ?format=json, POST {\"action\":...}\n"
581 "\n"
582 "Environment: BRAVE_API_KEY TAVILY_API_KEY EXA_API_KEY\n"
583 " PERPLEXITY_API_KEY SEARXNG_URL WEBSEARCH_PROVIDER\n"
584 " WEBSEARCH_SEARXNG_BASE WEBSEARCH_{PROVIDER}_BASE\n"
585 " WEBSEARCH_MOCK_BASE (tests) SWEBSEARCH_CONFIG_DIR\n",
586 stdout);
587}
588
589/* ------------------------------------------------------------------ */
590/* CGI helpers */
591/* ------------------------------------------------------------------ */
592
593static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
594{
595 size_t klen;
596
597 if (!qs || !key || !out || outsz == 0) return 0;
598 out[0] = '\0';
599 klen = strlen(key);
600 while (*qs) {
601 if (strncmp(qs, key, klen) == 0 && qs[klen] == '=') {
602 /* Copy the RAW value up to the next '&' first, then decode. Decoding
603 * straight out of the query would turn an encoded %26 inside a
604 * value into a terminator and silently truncate it. */
605 const char *p = qs + klen + 1;
606 char raw[2048];
607 size_t n = 0;
608 while (*p && *p != '&' && n + 1 < sizeof raw) raw[n++] = *p++;
609 raw[n] = '\0';
610 ws_url_decode(out, outsz, raw);
611 return 1;
612 }
613 qs = strchr(qs, '&');
614 if (!qs) break;
615 qs++;
616 }
617 return 0;
618}
619
620/* The node's :8150 is LAN-reachable, so the page and the JSON API must not
621 * answer a bare curl. Three credential forms because three callers differ:
622 * bot-web proxies with a header, the plugin iframe appends ?pwd=, and a script
623 * may send a bearer token. --meta and --mcp return above this, so discovery
624 * and the router stay open. */
625static void require_node_auth(void)
626{
627 const char *np = getenv("BOT_PASSWORD");
628 const char *xp, *auth, *qs;
629 char qpwd[256];
630
631 if (!np || !*np) return;
632
633 xp = getenv("HTTP_X_BOT_PASSWORD");
634 if (xp && strcmp(xp, np) == 0) return;
635
636 auth = getenv("HTTP_AUTHORIZATION");
637 if (auth) {
638 while (*auth == ' ') auth++;
639 if (strncmp(auth, "Bearer ", 7) == 0) {
640 auth += 7;
641 while (*auth == ' ') auth++;
642 if (strcmp(auth, np) == 0) return;
643 }
644 }
645
646 qs = getenv("QUERY_STRING");
647 if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) &&
648 strcmp(qpwd, np) == 0) return;
649
650 fputs("Status: 401 Unauthorized\r\n"
651 "Content-Type: application/json; charset=utf-8\r\n"
652 "Cache-Control: no-store\r\n"
653 "X-Content-Type-Options: nosniff\r\n\r\n"
654 "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
655 exit(0);
656}
657
658static void json_header(void)
659{
660 fputs("Content-Type: application/json; charset=utf-8\r\n"
661 "Cache-Control: no-store\r\n"
662 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
663}
664
665static void json_raw(const char *json)
666{
667 json_header();
668 fputs(json ? json : "{\"ok\":true}", stdout);
669 fputc('\n', stdout);
670 fflush(stdout);
671}
672
673static void json_err(int code, const char *msg)
674{
675 ws_buf b;
676 const char *status = "Status: 500 Internal Server Error\r\n";
677
678 if (code == 400) status = "Status: 400 Bad Request\r\n";
679 else if (code == 401) status = "Status: 401 Unauthorized\r\n";
680 else if (code == 404) status = "Status: 404 Not Found\r\n";
681 else if (code == 413) status = "Status: 413 Payload Too Large\r\n";
682 else if (code == 422) status = "Status: 422 Unprocessable Entity\r\n";
683
684 ws_buf_init(&b);
685 ws_buf_puts(&b, status);
686 ws_buf_puts(&b, "Content-Type: application/json; charset=utf-8\r\n"
687 "Cache-Control: no-store\r\n"
688 "X-Content-Type-Options: nosniff\r\n\r\n"
689 "{\"ok\":false,\"error\":");
690 ws_json_str(&b, msg ? msg : "error");
691 ws_buf_puts(&b, "}\n");
692 fputs(ws_buf_str(&b), stdout);
693 fflush(stdout);
694 ws_buf_free(&b);
695}
696
697static char *read_body(size_t *len_out)
698{
699 const char *cl = getenv("CONTENT_LENGTH");
700 long want = (cl && *cl) ? atol(cl) : 0;
701 char *buf;
702 size_t got = 0;
703
704 if (len_out) *len_out = 0;
705 if (want <= 0) return NULL;
706 if (want > WS_BODY_MAX) return NULL;
707 buf = (char *)malloc((size_t)want + 1);
708 if (!buf) return NULL;
709 while (got < (size_t)want) {
710 size_t r = fread(buf + got, 1, (size_t)want - got, stdin);
711 if (r == 0) break;
712 got += r;
713 }
714 buf[got] = '\0';
715 if (len_out) *len_out = got;
716 return buf;
717}
718
719/* Look a field up in the POST body (JSON object) then the query string. The
720 * page posts JSON, so a checkbox arrives as `true`, not "1" — a reader that
721 * only understands strings reports "not set" for every boolean field. */
722static int field_str(const char *qs, yyjson_val *body, const char *key,
723 char *out, size_t outsz)
724{
725 yyjson_val *v;
726
727 out[0] = '\0';
728 if (body && yyjson_is_obj(body)) {
729 v = yyjson_obj_get(body, key);
730 if (v) {
731 if (yyjson_is_str(v)) { ws_copy(out, outsz, yyjson_get_str(v)); return 1; }
732 if (yyjson_is_bool(v)) {
733 ws_copy(out, outsz, yyjson_get_bool(v) ? "1" : "0");
734 return 1;
735 }
736 if (yyjson_is_int(v)) {
737 snprintf(out, outsz, "%lld", (long long)yyjson_get_int(v));
738 return 1;
739 }
740 }
741 }
742 return get_query_val(qs, key, out, outsz);
743}
744
745/* Bound a free-text base URL to something ws_http_do will accept, and refuse
746 * a non-http(s) scheme here rather than at connect time. */
747static int valid_base(const char *s)
748{
749 if (!s || !*s) return 1; /* empty = "use the default" */
750 if (!ws_iprefix(s, "http://") && !ws_iprefix(s, "https://")) return 0;
751 if (strchr(s, ' ') || strchr(s, '\n') || strchr(s, '\r')) return 0;
752 return 1;
753}
754
755/* ------------------------------------------------------------------ */
756/* JSON API */
757/* ------------------------------------------------------------------ */
758
759static void api_search(const ws_config *cfg, const char *qs, yyjson_val *body)
760{
761 char query[512], provider[WS_ID_MAX], country[16], language[16], freshness[16];
762 char countbuf[16];
763 int count = 0;
764 ws_results r;
765 char err[512];
766 long status = 0;
767
768 if (!field_str(qs, body, "q", query, sizeof query) &&
769 !field_str(qs, body, "query", query, sizeof query)) {
770 json_err(400, "q is required");
771 return;
772 }
773 field_str(qs, body, "provider", provider, sizeof provider);
774 field_str(qs, body, "country", country, sizeof country);
775 field_str(qs, body, "language", language, sizeof language);
776 field_str(qs, body, "freshness", freshness, sizeof freshness);
777 if (field_str(qs, body, "count", countbuf, sizeof countbuf)) count = atoi(countbuf);
778
779 ws_results_init(&r);
780 err[0] = '\0';
781 if (ws_search(cfg, provider, query, count, country, language, freshness,
782 NULL, &r, &status, err, sizeof err) != 0) {
783 ws_buf b;
784 ws_buf_init(&b);
785 ws_buf_puts(&b, "{\"ok\":false,\"error\":");
786 ws_json_str(&b, err);
787 if (status) ws_buf_printf(&b, ",\"status\":%ld", status);
788 ws_buf_puts(&b, ",\"provider\":");
789 ws_json_str(&b, provider[0] ? provider : ws_provider_active(cfg));
790 ws_buf_putc(&b, '}');
791 json_header();
792 fputs(ws_buf_str(&b), stdout);
793 fputc('\n', stdout);
794 fflush(stdout);
795 ws_buf_free(&b);
796 ws_results_free(&r);
797 return;
798 }
799 {
800 char *js = results_json(&r);
801 json_raw(js ? js : "{\"ok\":true}");
802 free(js);
803 }
804 ws_results_free(&r);
805}
806
807static void api_config(const ws_config *cfg)
808{
809 char *js = providers_json(cfg);
810 json_raw(js ? js : "{\"ok\":true}");
811 free(js);
812}
813
814static void api_save(const ws_config *cfg_in, const char *qs, yyjson_val *body)
815{
816 ws_config c = *cfg_in;
817 char tmp[WS_URL_MAX];
818 char keyOnly[WS_KEY_MAX];
819 yyjson_val *v;
820
821 field_str(qs, body, "provider", c.active, sizeof c.active);
822 if (!ws_provider_known(c.active))
823 ws_copy(c.active, sizeof c.active, "duckduckgo");
824
825 if (field_str(qs, body, "count", tmp, sizeof tmp)) {
826 int n = atoi(tmp);
827 if (n < 1) n = 1;
828 if (n > WS_MAX_COUNT) n = WS_MAX_COUNT;
829 c.count = n;
830 }
831 field_str(qs, body, "region", c.region, sizeof c.region);
832 field_str(qs, body, "safe", tmp, sizeof tmp);
833 if (tmp[0]) {
834 if (!ws_ieq(tmp, "strict") && !ws_ieq(tmp, "moderate") && !ws_ieq(tmp, "off")) {
835 json_err(400, "safe must be strict, moderate or off");
836 return;
837 }
838 ws_copy(c.safe, sizeof c.safe, tmp);
839 }
840 field_str(qs, body, "language", c.language, sizeof c.language);
841 field_str(qs, body, "searxng_categories", c.searxng_categories,
842 sizeof c.searxng_categories);
843
844 if (field_str(qs, body, "tavily_advanced", tmp, sizeof tmp))
845 c.tavily_advanced = atoi(tmp) ? 1 : 0;
846 if (field_str(qs, body, "tavily_answer", tmp, sizeof tmp))
847 c.tavily_answer = atoi(tmp) ? 1 : 0;
848
849 /* A key is only overwritten when a non-empty value arrives; an empty field
850 * means "leave it alone", and `clear_<x>_key` is the explicit removal. */
851 {
852 struct { const char *field; char *dst; size_t cap; const char *clear; } k[] = {
853 { "brave_key", c.brave_key, sizeof c.brave_key, "clear_brave_key" },
854 { "tavily_key", c.tavily_key, sizeof c.tavily_key, "clear_tavily_key" },
855 { "exa_key", c.exa_key, sizeof c.exa_key, "clear_exa_key" },
856 { "pplx_key", c.pplx_key, sizeof c.pplx_key, "clear_pplx_key" }
857 };
858 size_t i;
859 for (i = 0; i < sizeof k / sizeof k[0]; i++) {
860 if (field_str(qs, body, k[i].clear, keyOnly, sizeof keyOnly) &&
861 atoi(keyOnly))
862 k[i].dst[0] = '\0';
863 if (field_str(qs, body, k[i].field, keyOnly, sizeof keyOnly) && keyOnly[0])
864 ws_copy(k[i].dst, k[i].cap, keyOnly);
865 }
866 }
867
868 {
869 struct { const char *field; char *dst; size_t cap; } b[] = {
870 { "ddg_base", c.ddg_base, sizeof c.ddg_base },
871 { "searxng_base", c.searxng_base, sizeof c.searxng_base },
872 { "brave_base", c.brave_base, sizeof c.brave_base },
873 { "tavily_base", c.tavily_base, sizeof c.tavily_base },
874 { "exa_base", c.exa_base, sizeof c.exa_base },
875 { "pplx_base", c.pplx_base, sizeof c.pplx_base }
876 };
877 size_t i;
878 for (i = 0; i < sizeof b / sizeof b[0]; i++) {
879 if (field_str(qs, body, b[i].field, tmp, sizeof tmp)) {
880 if (!valid_base(tmp)) {
881 json_err(400, "a base URL must start with http:// or https://");
882 return;
883 }
884 /* An emptied base means "back to the compiled default" for the
885 * keyed providers, and "not configured" for SearXNG. */
886 if (tmp[0]) ws_copy(b[i].dst, b[i].cap, tmp);
887 else if (strcmp(b[i].field, "searxng_base") == 0) b[i].dst[0] = '\0';
888 else if (strcmp(b[i].field, "ddg_base") == 0)
889 ws_copy(b[i].dst, b[i].cap, "https://html.duckduckgo.com");
890 else if (strcmp(b[i].field, "brave_base") == 0)
891 ws_copy(b[i].dst, b[i].cap, "https://api.search.brave.com");
892 else if (strcmp(b[i].field, "tavily_base") == 0)
893 ws_copy(b[i].dst, b[i].cap, "https://api.tavily.com");
894 else if (strcmp(b[i].field, "exa_base") == 0)
895 ws_copy(b[i].dst, b[i].cap, "https://api.exa.ai");
896 else if (strcmp(b[i].field, "pplx_base") == 0)
897 ws_copy(b[i].dst, b[i].cap, "https://api.perplexity.ai");
898 }
899 }
900 }
901 /* A JSON body may send the whole provider map at once. */
902 v = body && yyjson_is_obj(body) ? yyjson_obj_get(body, "provider") : NULL;
903 (void)v;
904
905 if (ws_config_save(&c) != 0) {
906 json_err(500, "could not write config.json");
907 return;
908 }
909 api_config(&c);
910}
911
912static void api_handle(const ws_config *cfg, const char *qs, const char *action,
913 yyjson_val *body)
914{
915 if (!action || !*action) {
916 json_err(400, "action is required");
917 return;
918 }
919 if (strcmp(action, "providers") == 0 || strcmp(action, "config") == 0) {
920 api_config(cfg);
921 return;
922 }
923 if (strcmp(action, "save") == 0) {
924 api_save(cfg, qs, body);
925 return;
926 }
927 if (strcmp(action, "search") == 0) {
928 api_search(cfg, qs, body);
929 return;
930 }
931 if (strcmp(action, "info") == 0) {
932 ws_buf b;
933 ws_buf_init(&b);
934 ws_buf_puts(&b, "{\"ok\":true,\"id\":\"" WS_ID "\",\"version\":\"" WS_VER "\","
935 "\"kind\":\"mcp\",\"providers\":[");
936 {
937 int i;
938 for (i = 0; i < WS_PROVIDER_COUNT; i++) {
939 if (i) ws_buf_putc(&b, ',');
940 ws_buf_puts(&b, "\"");
941 ws_buf_puts(&b, WS_PROVIDERS[i].id);
942 ws_buf_puts(&b, "\"");
943 }
944 }
945 ws_buf_puts(&b, "],\"active\":");
946 ws_json_str(&b, ws_provider_active(cfg));
947 ws_buf_puts(&b, "}");
948 json_raw(ws_buf_str(&b));
949 ws_buf_free(&b);
950 return;
951 }
952 json_err(404, "unknown action");
953}
954
955/* ------------------------------------------------------------------ */
956/* Page */
957/* ------------------------------------------------------------------ */
958
959static void emit_ui(void)
960{
961 const char *p = UI_HTML;
962
963 while (*p) {
964 if (*p == '\001') {
965 fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS
966 ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);--ac:var(--blue)}"
967 "</style>", stdout);
968 p++;
969 } else if (*p == '\002') {
970 fputs(SX_BOT_THEME_HANDOFF, stdout);
971 p++;
972 } else {
973 putchar(*p++);
974 }
975 }
976}
977
978static void mode_html(void)
979{
980 fputs("Content-Type: text/html; charset=utf-8\r\n"
981 "Cache-Control: no-store\r\n"
982 "X-Content-Type-Options: nosniff\r\n"
983 "X-Frame-Options: SAMEORIGIN\r\n"
984 "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
985 "style-src 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; "
986 "form-action 'none'; base-uri 'none'\r\n\r\n", stdout);
987 emit_ui();
988}
989
990/* ------------------------------------------------------------------ */
991/* main */
992/* ------------------------------------------------------------------ */
993
994int main(int argc, char **argv)
995{
996 ws_config cfg;
997 const char *qs = getenv("QUERY_STRING");
998 const char *method = getenv("REQUEST_METHOD");
999
1000 {
1001 const char *meta = getenv("SX_PLUGIN_META");
1002 const char *help = getenv("PLUGIN_HELP");
1003 int i;
1004 for (i = 1; i < argc; i++) {
1005 if (strcmp(argv[i], "--meta") == 0) return mode_meta();
1006 if (strcmp(argv[i], "--mcp") == 0) return mode_mcp();
1007 if (strcmp(argv[i], "--schema") == 0) return mode_schema();
1008 if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
1009 print_help();
1010 return 0;
1011 }
1012 if (strcmp(argv[i], "--version") == 0) {
1013 printf("%s\n", WS_VER);
1014 return 0;
1015 }
1016 if (strcmp(argv[i], "--selftest") == 0) {
1017 ws_config_load(&cfg);
1018 printf("provider=%s count=%d searxng=%s brave_key=%d\n",
1019 ws_provider_active(&cfg), cfg.count,
1020 cfg.searxng_base[0] ? cfg.searxng_base : "(unset)",
1021 cfg.brave_key[0] ? 1 : 0);
1022 return 0;
1023 }
1024 }
1025 if (meta && *meta && !(qs && *qs)) return mode_meta();
1026 if (help && *help) { print_help(); return 0; }
1027 }
1028
1029 ws_config_load(&cfg);
1030
1031 if (!qs) qs = "";
1032 if (!method) method = "GET";
1033
1034 /* MCP mode is also reachable through the environment, which is how a
1035 * supervisor that cannot pass argv uses it. */
1036 if (getenv("SX_PLUGIN_MCP")) return mode_mcp();
1037
1038 {
1039 char action[64];
1040 int has_action = get_query_val(qs, "action", action, sizeof action);
1041 int is_json = has_action || strstr(qs, "format=json") ||
1042 (method && ws_ieq(method, "POST"));
1043
1044 if (!is_json) {
1045 require_node_auth();
1046 mode_html();
1047 return 0;
1048 }
1049 require_node_auth();
1050
1051 {
1052 char *body = read_body(NULL);
1053 yyjson_doc *doc = body ? yyjson_read(body, strlen(body), 0) : NULL;
1054 yyjson_val *root = doc ? yyjson_doc_get_root(doc) : NULL;
1055
1056 if (!has_action && root && yyjson_is_obj(root)) {
1057 yyjson_val *av = yyjson_obj_get(root, "action");
1058 if (av && yyjson_is_str(av))
1059 ws_copy(action, sizeof action, yyjson_get_str(av));
1060 else if (av) action[0] = '\0';
1061 has_action = action[0] ? 1 : 0;
1062 }
1063 if (!has_action && !strstr(qs, "format=json")) {
1064 json_err(400, "action is required");
1065 yyjson_doc_free(doc);
1066 free(body);
1067 return 0;
1068 }
1069 api_handle(&cfg, qs, has_action ? action : "config",
1070 root && yyjson_is_obj(root) ? root : NULL);
1071 yyjson_doc_free(doc);
1072 free(body);
1073 }
1074 }
1075 return 0;
1076}