| 1 | 1 | new file mode 100644 |
| index 0000000..0e70721 | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,11 @@ | ||
| 1 | +/plugin_webhook | |
| 2 | +/plugin_webhook.exe | |
| 3 | +/plugin_webhook.musl | |
| 4 | +/plugin_webhook.arm64 | |
| 5 | +/plugin_webhook-asan | |
| 6 | +/plugin_webhook-fortify | |
| 7 | +*.o | |
| 8 | +*.tmp | |
| 9 | +*.log | |
| 10 | +__pycache__/ | |
| 11 | +tests/__pycache__/ |
| 1 | 1 | new file mode 100644 |
| index 0000000..6f2b03a | ||
| --- /dev/null | ||
| +++ b/LICENSE | ||
| @@ -0,0 +1,27 @@ | ||
| 1 | +MIT License | |
| 2 | + | |
| 3 | +Copyright (c) 2026 SCORPIOX INC | |
| 4 | + | |
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 6 | +of this software and associated documentation files (the "Software"), to deal | |
| 7 | +in the Software without restriction, including without limitation the rights | |
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 9 | +copies of the Software, and to permit persons to whom the Software is | |
| 10 | +furnished to do so, subject to the following conditions: | |
| 11 | + | |
| 12 | +The above copyright notice and this permission notice shall be included in all | |
| 13 | +copies or substantial portions of the Software. | |
| 14 | + | |
| 15 | +Vendored third-party software keeps its own licence (see vendor/): | |
| 16 | + - yyjson (MIT, Copyright (c) 2020 YaoYuan) -- vendor/yyjson.{c,h} | |
| 17 | + - Mbed TLS 3.6.7 (Apache-2.0) -- vendor/mbedtlslib/ | |
| 18 | + vendor/mbedtls/ | |
| 19 | + vendor/psa/ | |
| 20 | + | |
| 21 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 22 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 23 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 24 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 25 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 26 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 27 | +SOFTWARE. |
| 1 | 1 | new file mode 100644 |
| index 0000000..b1aa2e3 | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,99 @@ | ||
| 1 | +# plugin_webhook - SCORPIOX BOT open-source named webhook & REST trigger | |
| 2 | +# MCP connector | |
| 3 | +# | |
| 4 | +# Zero runtime dependencies on every artefact. The third-party C in the tree is | |
| 5 | +# vendored under vendor/: yyjson (MIT) and Mbed TLS 3.6.7 (Apache-2.0), whose | |
| 6 | +# sources sit in vendor/mbedtlslib with their public headers flattened into | |
| 7 | +# vendor/mbedtls and vendor/psa. That layout is what the SCORPIOX BOT release | |
| 8 | +# CLI (scorpiox-cli-botplugin build/publish) expects: it compiles every .c | |
| 9 | +# under src/ and vendor/ with exactly -I <repo>/src -I <repo>/vendor, so a | |
| 10 | +# vendored library must be reachable from those two include roots. | |
| 11 | +# | |
| 12 | +# On _WIN32 the HTTP and TLS legs are WinHTTP instead, so the static PE needs no | |
| 13 | +# extra DLLs and no crypto object files are reached. | |
| 14 | +# | |
| 15 | +# Targets: | |
| 16 | +# make native build -> ./plugin_webhook | |
| 17 | +# make musl static musl x86_64 -> ./plugin_webhook.musl | |
| 18 | +# make arm64 static arm64 musl -> ./plugin_webhook.arm64 | |
| 19 | +# make win64 MinGW-w64 static -> ./plugin_webhook.exe | |
| 20 | +# make macos Apple clang -> ./plugin_webhook (run on macOS) | |
| 21 | +# make asan ASan + UBSan + _FORTIFY_SOURCE=2 -> ./plugin_webhook-asan | |
| 22 | +# make fortify -D_FORTIFY_SOURCE=2 -> ./plugin_webhook-fortify | |
| 23 | +# make ui regenerate src/ui_html.h from src/ui.html | |
| 24 | +# make test build + run tests/run.sh | |
| 25 | +# make e2e build + run tests/e2e.py (Playwright) | |
| 26 | +# make clean | |
| 27 | + | |
| 28 | +CC ?= cc | |
| 29 | +WARN := -Wall -Wextra -Wno-overlength-strings | |
| 30 | +STD := -std=c99 | |
| 31 | +INCLUDES := -I src -I vendor -I vendor/mbedtlslib | |
| 32 | +CFLAGS ?= -O2 $(STD) $(WARN) $(INCLUDES) | |
| 33 | +MUSL_CC ?= musl-gcc | |
| 34 | +MUSL_CFLAGS := -O2 $(STD) $(WARN) $(INCLUDES) -static | |
| 35 | +ARM_CC ?= aarch64-linux-gnu-gcc | |
| 36 | +ARM_CFLAGS := -O2 $(STD) $(WARN) $(INCLUDES) -static | |
| 37 | +WIN_CC ?= x86_64-w64-mingw32-gcc | |
| 38 | +WIN_CFLAGS := -O2 $(STD) $(WARN) $(INCLUDES) -static | |
| 39 | +WIN_LIBS := -lwinhttp -lws2_32 -lbcrypt -lcrypt32 | |
| 40 | + | |
| 41 | +SRC_C := $(wildcard src/*.c) | |
| 42 | +VENDOR_C := $(wildcard vendor/*.c) $(wildcard vendor/mbedtlslib/*.c) | |
| 43 | +UI_SRC := src/ui.html | |
| 44 | +UI_HDR := src/ui_html.h | |
| 45 | +BIN := plugin_webhook | |
| 46 | +EXE := plugin_webhook.exe | |
| 47 | + | |
| 48 | +.PHONY: all native musl arm64 win64 macos asan fortify ui test e2e clean help | |
| 49 | + | |
| 50 | +all: native | |
| 51 | + | |
| 52 | +$(UI_HDR): $(UI_SRC) tools/gen_ui.py | |
| 53 | + @echo "==> regenerating $(UI_HDR)" | |
| 54 | + python3 tools/gen_ui.py | |
| 55 | + | |
| 56 | +ui: $(UI_HDR) | |
| 57 | + | |
| 58 | +native: $(BIN) | |
| 59 | + | |
| 60 | +$(BIN): $(SRC_C) $(VENDOR_C) $(UI_HDR) | |
| 61 | + @echo "==> native build ($(CC))" | |
| 62 | + $(CC) $(CFLAGS) $(SRC_C) $(VENDOR_C) -o $(BIN) | |
| 63 | + | |
| 64 | +musl: $(SRC_C) $(VENDOR_C) $(UI_HDR) | |
| 65 | + @echo "==> static musl build ($(MUSL_CC))" | |
| 66 | + $(MUSL_CC) $(MUSL_CFLAGS) $(SRC_C) $(VENDOR_C) -o $(BIN).musl | |
| 67 | + | |
| 68 | +arm64: $(SRC_C) $(VENDOR_C) $(UI_HDR) | |
| 69 | + @echo "==> static arm64 build ($(ARM_CC))" | |
| 70 | + $(ARM_CC) $(ARM_CFLAGS) $(SRC_C) $(VENDOR_C) -o $(BIN).arm64 | |
| 71 | + | |
| 72 | +win64: $(SRC_C) $(VENDOR_C) $(UI_HDR) | |
| 73 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | |
| 74 | + $(WIN_CC) $(WIN_CFLAGS) $(SRC_C) $(VENDOR_C) -o $(EXE) $(WIN_LIBS) | |
| 75 | + | |
| 76 | +macos: $(SRC_C) $(VENDOR_C) $(UI_HDR) | |
| 77 | + @echo "==> Apple clang build" | |
| 78 | + $(CC) $(CFLAGS) $(SRC_C) $(VENDOR_C) -o $(BIN) | |
| 79 | + | |
| 80 | +asan: $(SRC_C) $(VENDOR_C) $(UI_HDR) | |
| 81 | + $(CC) $(CFLAGS) -g -O1 -fsanitize=address,undefined \ | |
| 82 | + -fno-omit-frame-pointer -D_FORTIFY_SOURCE=2 \ | |
| 83 | + $(SRC_C) $(VENDOR_C) -o $(BIN)-asan | |
| 84 | + | |
| 85 | +fortify: $(SRC_C) $(VENDOR_C) $(UI_HDR) | |
| 86 | + $(CC) $(CFLAGS) -O2 -D_FORTIFY_SOURCE=2 $(SRC_C) $(VENDOR_C) -o $(BIN)-fortify | |
| 87 | + | |
| 88 | +test: native | |
| 89 | + @bash tests/run.sh | |
| 90 | + | |
| 91 | +e2e: native | |
| 92 | + @python3 tests/e2e.py | |
| 93 | + | |
| 94 | +clean: | |
| 95 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN)-asan $(BIN)-fortify | |
| 96 | + rm -rf tests/__pycache__ | |
| 97 | + | |
| 98 | +help: | |
| 99 | + @echo "make | make musl | make arm64 | make win64 | make macos | make asan | make fortify | make ui | make test | make e2e | make clean" |
| 1 | 1 | new file mode 100644 |
| index 0000000..f963603 |

| 1 | 1 | new file mode 100644 |
| index 0000000..a42a12d |

| 1 | 1 | new file mode 100644 |
| index 0000000..88d112c |

| 1 | 1 | new file mode 100644 |
| index 0000000..ba415da |

| 1 | 1 | new file mode 100644 |
| index 0000000..54df13e |

| 1 | 1 | new file mode 100644 |
| index 0000000..fab5da3 |

| 1 | 1 | new file mode 100644 |
| index 0000000..235fa09 | ||
| --- /dev/null | ||
| +++ b/plugin.json | ||
| @@ -0,0 +1,36 @@ | ||
| 1 | +{ | |
| 2 | + "slug": "webhook", | |
| 3 | + "id": "plugin_webhook", | |
| 4 | + "version": "1.0.0", | |
| 5 | + "name": "webhook", | |
| 6 | + "desc": "HTTP triggers", | |
| 7 | + "title": "Named Webhooks & REST Triggers (MCP)", | |
| 8 | + "summary": "Zero-dependency MCP connector for outbound HTTP: define named hooks (Slack, Discord, Zapier, n8n, IFTTT or your own REST endpoint) with their method, custom headers and an optional HMAC-SHA256 signature, then fire them by name from the agent or the themed page. The bearer token and the signing secret live in one mode-0600 file on the node and are never returned to a prompt or a browser: every read path reports has_secret instead of the value. A pasted webhook URL that carries a token in its query string is redacted in every listing. Outbound requests are SSRF-checked address by address before connecting and TLS is verified with no insecure bypass; redirects are reported, never followed.", | |
| 9 | + "kind": "mcp", | |
| 10 | + "mcp": true, | |
| 11 | + "daemon": false, | |
| 12 | + "menus": false, | |
| 13 | + "verified": "live", | |
| 14 | + "category": "network", | |
| 15 | + "license": "MIT", | |
| 16 | + "capabilities": [ | |
| 17 | + "https_outbound_webhook_delivery", | |
| 18 | + "hmac_sha256_request_signing", | |
| 19 | + "ssrf_address_denylist", | |
| 20 | + "secret_store_0600", | |
| 21 | + "stdio_mcp_jsonrpc_server" | |
| 22 | + ], | |
| 23 | + "trust_notice": "Executes native C code on your node. It makes OUTBOUND HTTP requests to the URLs you configure, carrying the headers and HMAC secrets you store in ~/.scorpiox/connectors/plugin_webhook/hooks.json (mode 0600). Only one private network is reachable and only if you set WEBHOOK_ALLOW_PRIVATE=1; otherwise loopback and every RFC1918 / link-local / ULA address is refused before a socket is opened. TLS is verified against the system root store (or WEBHOOK_TLS_CA_FILE) and cannot be disabled. It runs no shell command, reads no other file, and writes nothing except that one store file.", | |
| 24 | + "author": "SCORPIOX INC", | |
| 25 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-webhook", | |
| 26 | + "cflags": [ | |
| 27 | + "-std=c99", | |
| 28 | + "-Wno-overlength-strings" | |
| 29 | + ], | |
| 30 | + "ldflags_posix": [], | |
| 31 | + "ldflags_win64": [ | |
| 32 | + "-lwinhttp", | |
| 33 | + "-lws2_32", | |
| 34 | + "-lbcrypt" | |
| 35 | + ] | |
| 36 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..0dd243b | ||
| --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | ||
| 1 | +/* | |
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | |
| 3 | + * | |
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | |
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | |
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | |
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | |
| 8 | + * localStorage key, same prepaint order. | |
| 9 | + * | |
| 10 | + * Three rules, and nothing else: | |
| 11 | + * | |
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | |
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | |
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | |
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | |
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | |
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | |
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | |
| 19 | + * it was already open when the bot changed theme. | |
| 20 | + * | |
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | |
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | |
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | |
| 24 | + * are var() references, one definition covers both themes. | |
| 25 | + * | |
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 27 | + */ | |
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | |
| 29 | +#define SX_BOT_THEME_PLUGIN_H | |
| 30 | + | |
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | |
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | |
| 33 | +#define SX_BOT_THEME_TOKENS \ | |
| 34 | +":root{color-scheme:dark;" \ | |
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | |
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | |
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | |
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | |
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | |
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | |
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | |
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | |
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | |
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | |
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | |
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | |
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | |
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | |
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | |
| 50 | +"}" \ | |
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | |
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 58 | + "--accent-dim:#0066d6;" \ | |
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 62 | + "color-scheme:light}}" \ | |
| 63 | +"html[data-theme=light]{" \ | |
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 70 | + "--accent-dim:#0066d6;" \ | |
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 74 | + "color-scheme:light}" \ | |
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | |
| 76 | +"*{box-sizing:border-box}" \ | |
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | |
| 78 | + "-webkit-font-smoothing:antialiased}" \ | |
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | |
| 80 | +"button:active{transform:scale(.98)}" \ | |
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | |
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | |
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | |
| 84 | +" * hides its own back link and its own toggle. */" \ | |
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | |
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | |
| 87 | + | |
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | |
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | |
| 90 | + * html.embedded so the embed rules apply before first paint. */ | |
| 91 | +#define SX_BOT_THEME_PREPAINT \ | |
| 92 | +"<script>(function(){var t='';" \ | |
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | |
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | |
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | |
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | |
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 99 | +"})();</script>\n" | |
| 100 | + | |
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | |
| 102 | + * at startup in case it changed while this page was already open. Fires the | |
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | |
| 104 | + * re-skin themselves from one listener. */ | |
| 105 | +#define SX_BOT_THEME_HANDOFF \ | |
| 106 | +"<script>(function(){" \ | |
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | |
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | |
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | |
| 112 | +"window.sxApplyTheme=apply;" \ | |
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | |
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | |
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | |
| 116 | +"})();</script>\n" | |
| 117 | + | |
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | |
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | |
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | |
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | |
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | |
| 123 | + | |
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | |
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | |
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | |
| 127 | +"})();</script>\n" | |
| 128 | + | |
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..aec298c | ||
| --- /dev/null | ||
| +++ b/src/plugin_webhook.c | ||
| @@ -0,0 +1,1303 @@ | ||
| 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.0" | |
| 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 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..8880f3e | ||
| --- /dev/null | ||
| +++ b/src/sha256.c | ||
| @@ -0,0 +1,212 @@ | ||
| 1 | +/* | |
| 2 | + * sha256.c - SHA-256 (FIPS 180-4) and HMAC-SHA256 (RFC 2104), pure C99. | |
| 3 | + * | |
| 4 | + * See sha256.h for why this exists instead of a vendored crypto library: the | |
| 5 | + * only thing this plugin needs from a crypto stack is one hash and one MAC, | |
| 6 | + * and both are short enough to audit in one sitting. | |
| 7 | + * | |
| 8 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 9 | + */ | |
| 10 | +#define _POSIX_C_SOURCE 200809L | |
| 11 | + | |
| 12 | +#include "sha256.h" | |
| 13 | + | |
| 14 | +#include <string.h> | |
| 15 | + | |
| 16 | +static const uint32_t K[64] = { | |
| 17 | + 0x428a2f98u, 0x71374491u, 0xb5c0fbcfu, 0xe9b5dba5u, | |
| 18 | + 0x3956c25bu, 0x59f111f1u, 0x923f82a4u, 0xab1c5ed5u, | |
| 19 | + 0xd807aa98u, 0x12835b01u, 0x243185beu, 0x550c7dc3u, | |
| 20 | + 0x72be5d74u, 0x80deb1feu, 0x9bdc06a7u, 0xc19bf174u, | |
| 21 | + 0xe49b69c1u, 0xefbe4786u, 0x0fc19dc6u, 0x240ca1ccu, | |
| 22 | + 0x2de92c6fu, 0x4a7484aau, 0x5cb0a9dcu, 0x76f988dau, | |
| 23 | + 0x983e5152u, 0xa831c66du, 0xb00327c8u, 0xbf597fc7u, | |
| 24 | + 0xc6e00bf3u, 0xd5a79147u, 0x06ca6351u, 0x14292967u, | |
| 25 | + 0x27b70a85u, 0x2e1b2138u, 0x4d2c6dfcu, 0x53380d13u, | |
| 26 | + 0x650a7354u, 0x766a0abbu, 0x81c2c92eu, 0x92722c85u, | |
| 27 | + 0xa2bfe8a1u, 0xa81a664bu, 0xc24b8b70u, 0xc76c51a3u, | |
| 28 | + 0xd192e819u, 0xd6990624u, 0xf40e3585u, 0x106aa070u, | |
| 29 | + 0x19a4c116u, 0x1e376c08u, 0x2748774cu, 0x34b0bcb5u, | |
| 30 | + 0x391c0cb3u, 0x4ed8aa4au, 0x5b9cca4fu, 0x682e6ff3u, | |
| 31 | + 0x748f82eeu, 0x78a5636fu, 0x84c87814u, 0x8cc70208u, | |
| 32 | + 0x90befffau, 0xa4506cebu, 0xbef9a3f7u, 0xc67178f2u | |
| 33 | +}; | |
| 34 | + | |
| 35 | +static uint32_t rotr(uint32_t x, unsigned n) | |
| 36 | +{ | |
| 37 | + return (x >> n) | (x << (32 - n)); | |
| 38 | +} | |
| 39 | + | |
| 40 | +static void compress(sx_sha256 *c, const unsigned char blk[64]) | |
| 41 | +{ | |
| 42 | + uint32_t w[64]; | |
| 43 | + uint32_t a, b, d, e, f, g, h, cc; | |
| 44 | + unsigned i; | |
| 45 | + | |
| 46 | + for (i = 0; i < 16; i++) { | |
| 47 | + w[i] = ((uint32_t)blk[i * 4] << 24) | | |
| 48 | + ((uint32_t)blk[i * 4 + 1] << 16) | | |
| 49 | + ((uint32_t)blk[i * 4 + 2] << 8) | | |
| 50 | + ((uint32_t)blk[i * 4 + 3]); | |
| 51 | + } | |
| 52 | + for (i = 16; i < 64; i++) { | |
| 53 | + uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); | |
| 54 | + uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); | |
| 55 | + w[i] = w[i - 16] + s0 + w[i - 7] + s1; | |
| 56 | + } | |
| 57 | + | |
| 58 | + a = c->h[0]; b = c->h[1]; cc = c->h[2]; d = c->h[3]; | |
| 59 | + e = c->h[4]; f = c->h[5]; g = c->h[6]; h = c->h[7]; | |
| 60 | + | |
| 61 | + for (i = 0; i < 64; i++) { | |
| 62 | + uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25); | |
| 63 | + uint32_t ch = (e & f) ^ ((~e) & g); | |
| 64 | + uint32_t t1 = h + S1 + ch + K[i] + w[i]; | |
| 65 | + uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22); | |
| 66 | + uint32_t maj = (a & b) ^ (a & cc) ^ (b & cc); | |
| 67 | + uint32_t t2 = S0 + maj; | |
| 68 | + h = g; g = f; f = e; | |
| 69 | + e = d + t1; | |
| 70 | + d = cc; cc = b; b = a; | |
| 71 | + a = t1 + t2; | |
| 72 | + } | |
| 73 | + | |
| 74 | + c->h[0] += a; c->h[1] += b; c->h[2] += cc; c->h[3] += d; | |
| 75 | + c->h[4] += e; c->h[5] += f; c->h[6] += g; c->h[7] += h; | |
| 76 | +} | |
| 77 | + | |
| 78 | +void sx_sha256_init(sx_sha256 *c) | |
| 79 | +{ | |
| 80 | + c->h[0] = 0x6a09e667u; c->h[1] = 0xbb67ae85u; | |
| 81 | + c->h[2] = 0x3c6ef372u; c->h[3] = 0xa54ff53au; | |
| 82 | + c->h[4] = 0x510e527fu; c->h[5] = 0x9b05688cu; | |
| 83 | + c->h[6] = 0x1f83d9abu; c->h[7] = 0x5be0cd19u; | |
| 84 | + c->bits = 0; | |
| 85 | + c->used = 0; | |
| 86 | +} | |
| 87 | + | |
| 88 | +void sx_sha256_update(sx_sha256 *c, const void *data, size_t len) | |
| 89 | +{ | |
| 90 | + const unsigned char *p = (const unsigned char *)data; | |
| 91 | + | |
| 92 | + c->bits += (uint64_t)len * 8u; | |
| 93 | + while (len) { | |
| 94 | + size_t take; | |
| 95 | + if (c->used == 0 && len >= 64) { | |
| 96 | + compress(c, p); | |
| 97 | + p += 64; | |
| 98 | + len -= 64; | |
| 99 | + continue; | |
| 100 | + } | |
| 101 | + take = 64 - c->used; | |
| 102 | + if (take > len) take = len; | |
| 103 | + memcpy(c->buf + c->used, p, take); | |
| 104 | + c->used += take; | |
| 105 | + p += take; | |
| 106 | + len -= take; | |
| 107 | + if (c->used == 64) { | |
| 108 | + compress(c, c->buf); | |
| 109 | + c->used = 0; | |
| 110 | + } | |
| 111 | + } | |
| 112 | +} | |
| 113 | + | |
| 114 | +void sx_sha256_final(sx_sha256 *c, unsigned char out[SX_SHA256_DIGEST_LEN]) | |
| 115 | +{ | |
| 116 | + unsigned char pad[72]; | |
| 117 | + size_t padlen; | |
| 118 | + uint64_t bits = c->bits; | |
| 119 | + unsigned i; | |
| 120 | + | |
| 121 | + padlen = (c->used < 56) ? (56 - c->used) : (120 - c->used); | |
| 122 | + memset(pad, 0, sizeof pad); | |
| 123 | + pad[0] = 0x80; | |
| 124 | + /* The length field is appended by update(), which must not add to bits. */ | |
| 125 | + { | |
| 126 | + unsigned char lenbuf[8]; | |
| 127 | + uint64_t save = c->bits; | |
| 128 | + for (i = 0; i < 8; i++) | |
| 129 | + lenbuf[7 - i] = (unsigned char)((bits >> (i * 8)) & 0xFFu); | |
| 130 | + sx_sha256_update(c, pad, padlen); | |
| 131 | + sx_sha256_update(c, lenbuf, 8); | |
| 132 | + c->bits = save; | |
| 133 | + } | |
| 134 | + for (i = 0; i < 8; i++) { | |
| 135 | + out[i * 4] = (unsigned char)(c->h[i] >> 24); | |
| 136 | + out[i * 4 + 1] = (unsigned char)(c->h[i] >> 16); | |
| 137 | + out[i * 4 + 2] = (unsigned char)(c->h[i] >> 8); | |
| 138 | + out[i * 4 + 3] = (unsigned char)(c->h[i]); | |
| 139 | + } | |
| 140 | +} | |
| 141 | + | |
| 142 | +static void to_hex(const unsigned char *in, size_t n, char *hex) | |
| 143 | +{ | |
| 144 | + static const char digits[] = "0123456789abcdef"; | |
| 145 | + size_t i; | |
| 146 | + for (i = 0; i < n; i++) { | |
| 147 | + hex[i * 2] = digits[in[i] >> 4]; | |
| 148 | + hex[i * 2 + 1] = digits[in[i] & 0x0F]; | |
| 149 | + } | |
| 150 | + hex[n * 2] = '\0'; | |
| 151 | +} | |
| 152 | + | |
| 153 | +void sx_sha256_hex(const void *data, size_t len, char hex[SX_SHA256_HEX_LEN + 1]) | |
| 154 | +{ | |
| 155 | + sx_sha256 c; | |
| 156 | + unsigned char d[SX_SHA256_DIGEST_LEN]; | |
| 157 | + sx_sha256_init(&c); | |
| 158 | + sx_sha256_update(&c, data, len); | |
| 159 | + sx_sha256_final(&c, d); | |
| 160 | + to_hex(d, sizeof d, hex); | |
| 161 | +} | |
| 162 | + | |
| 163 | +void sx_hmac_sha256(const void *key, size_t klen, | |
| 164 | + const void *msg, size_t len, | |
| 165 | + unsigned char out[SX_SHA256_DIGEST_LEN]) | |
| 166 | +{ | |
| 167 | + unsigned char k[64]; | |
| 168 | + unsigned char ipad[64], opad[64]; | |
| 169 | + unsigned char inner[SX_SHA256_DIGEST_LEN]; | |
| 170 | + sx_sha256 c; | |
| 171 | + size_t i; | |
| 172 | + | |
| 173 | + memset(k, 0, sizeof k); | |
| 174 | + if (klen > sizeof k) { | |
| 175 | + sx_sha256_init(&c); | |
| 176 | + sx_sha256_update(&c, key, klen); | |
| 177 | + sx_sha256_final(&c, k); /* hashed key is 32 bytes, rest stays 0 */ | |
| 178 | + } else if (klen) { | |
| 179 | + memcpy(k, key, klen); | |
| 180 | + } | |
| 181 | + for (i = 0; i < sizeof k; i++) { | |
| 182 | + ipad[i] = (unsigned char)(k[i] ^ 0x36u); | |
| 183 | + opad[i] = (unsigned char)(k[i] ^ 0x5cu); | |
| 184 | + } | |
| 185 | + | |
| 186 | + sx_sha256_init(&c); | |
| 187 | + sx_sha256_update(&c, ipad, sizeof ipad); | |
| 188 | + sx_sha256_update(&c, msg, len); | |
| 189 | + sx_sha256_final(&c, inner); | |
| 190 | + | |
| 191 | + sx_sha256_init(&c); | |
| 192 | + sx_sha256_update(&c, opad, sizeof opad); | |
| 193 | + sx_sha256_update(&c, inner, sizeof inner); | |
| 194 | + sx_sha256_final(&c, out); | |
| 195 | +} | |
| 196 | + | |
| 197 | +void sx_hmac_sha256_hex(const void *key, size_t klen, | |
| 198 | + const void *msg, size_t len, | |
| 199 | + char hex[SX_SHA256_HEX_LEN + 1]) | |
| 200 | +{ | |
| 201 | + unsigned char d[SX_SHA256_DIGEST_LEN]; | |
| 202 | + sx_hmac_sha256(key, klen, msg, len, d); | |
| 203 | + to_hex(d, sizeof d, hex); | |
| 204 | +} | |
| 205 | + | |
| 206 | +int sx_ct_eq(const unsigned char *a, const unsigned char *b, size_t n) | |
| 207 | +{ | |
| 208 | + unsigned char diff = 0; | |
| 209 | + size_t i; | |
| 210 | + for (i = 0; i < n; i++) diff |= (unsigned char)(a[i] ^ b[i]); | |
| 211 | + return diff == 0; | |
| 212 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..94f3c28 | ||
| --- /dev/null | ||
| +++ b/src/sha256.h | ||
| @@ -0,0 +1,49 @@ | ||
| 1 | +/* | |
| 2 | + * sha256.h - SHA-256 (FIPS 180-4) and HMAC-SHA256 (RFC 2104) in pure C99. | |
| 3 | + * | |
| 4 | + * The plugin signs outbound webhook bodies with HMAC-SHA256, so it needs a | |
| 5 | + * digest that is correct rather than convenient. This implementation is the | |
| 6 | + * textbook one: no tables generated at run time, no allocation, no global | |
| 7 | + * state, and the two FIPS/RFC test vectors in tests/run.sh are the contract. | |
| 8 | + * | |
| 9 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 10 | + */ | |
| 11 | +#ifndef SX_WH_SHA256_H | |
| 12 | +#define SX_WH_SHA256_H | |
| 13 | + | |
| 14 | +#include <stddef.h> | |
| 15 | +#include <stdint.h> | |
| 16 | + | |
| 17 | +#define SX_SHA256_DIGEST_LEN 32 | |
| 18 | +#define SX_SHA256_HEX_LEN 64 | |
| 19 | + | |
| 20 | +typedef struct { | |
| 21 | + uint32_t h[8]; | |
| 22 | + uint64_t bits; /* total message length in bits */ | |
| 23 | + unsigned char buf[64]; | |
| 24 | + size_t used; /* bytes currently in buf */ | |
| 25 | +} sx_sha256; | |
| 26 | + | |
| 27 | +void sx_sha256_init(sx_sha256 *c); | |
| 28 | +void sx_sha256_update(sx_sha256 *c, const void *data, size_t len); | |
| 29 | +void sx_sha256_final(sx_sha256 *c, unsigned char out[SX_SHA256_DIGEST_LEN]); | |
| 30 | + | |
| 31 | +/* Convenience: lowercase hex + NUL into `hex` (65 bytes). */ | |
| 32 | +void sx_sha256_hex(const void *data, size_t len, char hex[SX_SHA256_HEX_LEN + 1]); | |
| 33 | + | |
| 34 | +/* HMAC-SHA256 over `len` bytes of `msg` with `klen` bytes of key. | |
| 35 | + * Writes the raw 32-byte tag into out. */ | |
| 36 | +void sx_hmac_sha256(const void *key, size_t klen, | |
| 37 | + const void *msg, size_t len, | |
| 38 | + unsigned char out[SX_SHA256_DIGEST_LEN]); | |
| 39 | + | |
| 40 | +/* HMAC-SHA256 as lowercase hex + NUL (65 bytes). */ | |
| 41 | +void sx_hmac_sha256_hex(const void *key, size_t klen, | |
| 42 | + const void *msg, size_t len, | |
| 43 | + char hex[SX_SHA256_HEX_LEN + 1]); | |
| 44 | + | |
| 45 | +/* Constant-time compare of two equal-length buffers. 1 when equal. | |
| 46 | + * Used for signature checks so a mismatch costs the same as a match. */ | |
| 47 | +int sx_ct_eq(const unsigned char *a, const unsigned char *b, size_t n); | |
| 48 | + | |
| 49 | +#endif /* SX_WH_SHA256_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..3f988f2 | ||
| --- /dev/null | ||
| +++ b/src/ui.html | ||
| @@ -0,0 +1,575 @@ | ||
| 1 | +<!DOCTYPE html> | |
| 2 | +<html lang="en"><head><meta charset="utf-8"> | |
| 3 | +<meta name="viewport" content="width=device-width,initial-scale=1"> | |
| 4 | +<title>webhook</title> | |
| 5 | +<!--TOKENS--> | |
| 6 | +<style> | |
| 7 | +*{box-sizing:border-box} | |
| 8 | +html,body{margin:0} | |
| 9 | +body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px; | |
| 10 | + line-height:1.5;-webkit-font-smoothing:antialiased} | |
| 11 | +.wrap{max-width:1040px;margin:0 auto;padding:16px} | |
| 12 | +.head{display:flex;align-items:flex-start;gap:12px;flex-wrap:wrap} | |
| 13 | +h1{font-size:20px;margin:0 0 2px;font-weight:650;letter-spacing:-.01em} | |
| 14 | +.sub{color:var(--text-2);font-size:12.5px} | |
| 15 | +.sub2{color:var(--text-2);font-size:11.5px;margin-top:2px} | |
| 16 | +.spacer{flex:1 1 auto} | |
| 17 | +.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px; | |
| 18 | + padding:16px;margin-bottom:14px} | |
| 19 | +.card h2{font-size:12px;font-weight:650;margin:0 0 12px;color:var(--text-2); | |
| 20 | + text-transform:uppercase;letter-spacing:.06em} | |
| 21 | +.row{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end} | |
| 22 | +.col{display:flex;flex-direction:column;gap:8px} | |
| 23 | +label{display:block;font-size:11px;color:var(--text-2);margin-bottom:4px; | |
| 24 | + text-transform:uppercase;letter-spacing:.05em} | |
| 25 | +input,select,textarea{background:var(--input-bg);border:1px solid var(--line); | |
| 26 | + color:var(--text);border-radius:9px;padding:7px 10px;font-size:13.5px; | |
| 27 | + font-family:var(--font);outline:none;min-width:0;width:100%} | |
| 28 | +textarea{font-family:var(--mono);font-size:12.5px;resize:vertical;min-height:88px; | |
| 29 | + line-height:1.45} | |
| 30 | +input:focus,select:focus,textarea:focus{border-color:var(--blue)} | |
| 31 | +button{background:var(--blue);color:#fff;border:0;border-radius:980px; | |
| 32 | + padding:7px 15px;font-size:13px;font-weight:600;cursor:pointer;font-family:var(--font)} | |
| 33 | +button.ghost{background:var(--surface-2);color:var(--text)} | |
| 34 | +button.danger{background:var(--red)} | |
| 35 | +button.tiny{padding:3px 10px;font-size:12px;border-radius:8px} | |
| 36 | +button:active{transform:scale(.98)} | |
| 37 | +button:disabled{opacity:.55;cursor:default} | |
| 38 | +.grow1{flex:1 1 200px}.grow2{flex:2 1 320px} | |
| 39 | +table{width:100%;border-collapse:collapse;font-size:13px} | |
| 40 | +th{text-align:left;font-size:10.5px;color:var(--text-2);text-transform:uppercase; | |
| 41 | + letter-spacing:.05em;font-weight:600;padding:0 8px 7px 0; | |
| 42 | + border-bottom:1px solid var(--line);white-space:nowrap} | |
| 43 | +td{padding:9px 8px 9px 0;border-bottom:1px solid var(--line);vertical-align:top} | |
| 44 | +tr:last-child td{border-bottom:0} | |
| 45 | +td.mono,.mono{font-family:var(--mono);font-size:12px; | |
| 46 | + font-variant-numeric:tabular-nums;word-break:break-all} | |
| 47 | +.tbl-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch} | |
| 48 | +.pill{display:inline-block;font-size:10.5px;font-weight:600;padding:2px 8px; | |
| 49 | + border-radius:980px;border:1px solid var(--line);color:var(--text-2); | |
| 50 | + background:var(--surface-2);white-space:nowrap} | |
| 51 | +.pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)} | |
| 52 | +.pill.bad{color:var(--red);border-color:rgba(255,69,58,.35)} | |
| 53 | +.pill.sig{color:var(--blue);border-color:rgba(10,132,255,.35)} | |
| 54 | +.pill.muted{color:var(--text-2)} | |
| 55 | +.empty{color:var(--text-2);font-size:12.5px;padding:10px 0} | |
| 56 | +.hint{color:var(--text-2);font-size:11.5px;margin-top:6px} | |
| 57 | +.out{margin-top:12px;padding:12px;border-radius:11px;background:var(--code-bg); | |
| 58 | + font-family:var(--mono);font-size:12px;white-space:pre-wrap; | |
| 59 | + word-break:break-word;display:none} | |
| 60 | +.out.on{display:block} | |
| 61 | +.out.err{color:var(--red)} | |
| 62 | +.hdr-row{display:grid;grid-template-columns:1fr 1fr auto;gap:8px;align-items:end} | |
| 63 | +.icon-btn{background:transparent;border:1px solid var(--line);color:var(--text-2); | |
| 64 | + border-radius:8px;padding:6px 9px;font-size:12px} | |
| 65 | +.hidden{display:none!important} | |
| 66 | +.foot{color:var(--text-2);font-size:11.5px;margin-top:2px} | |
| 67 | +kbd{font-family:var(--mono);font-size:11px;background:var(--surface-2); | |
| 68 | + border:1px solid var(--line);border-radius:5px;padding:1px 5px} | |
| 69 | +/* A five-column table cannot fit 390 px without squeezing the name into a | |
| 70 | + * vertical ribbon, so below 700 px each row becomes a labelled block. */ | |
| 71 | +@media(max-width:700px){ | |
| 72 | + #tbl thead{display:none} | |
| 73 | + #tbl,#tbl tbody{display:block} | |
| 74 | + #tbl tr{display:block;border:1px solid var(--line);border-radius:12px; | |
| 75 | + padding:10px 12px;margin-bottom:10px} | |
| 76 | + #tbl td{display:grid;grid-template-columns:76px minmax(0,1fr);gap:8px; | |
| 77 | + padding:2px 0;border:0;align-items:baseline;word-break:break-word} | |
| 78 | + #tbl td::before{content:attr(data-label);color:var(--text-2);font-size:10.5px; | |
| 79 | + text-transform:uppercase;letter-spacing:.05em} | |
| 80 | + #tbl td > .hint{grid-column:2;color:var(--text-2);font-size:11.5px} | |
| 81 | + #tbl td.actions{grid-template-columns:1fr 1fr;margin-top:8px;gap:6px} | |
| 82 | + #tbl td.actions::before{content:none} | |
| 83 | + #tbl td > span,#tbl td > button{justify-self:start} | |
| 84 | + #tbl td.actions > button{justify-self:stretch} | |
| 85 | + /* The delivery log has the same problem: six columns at 390 px. */ | |
| 86 | + #logtbl thead{display:none} | |
| 87 | + #logtbl,#logtbl tbody{display:block} | |
| 88 | + #logtbl tr{display:block;border-bottom:1px solid var(--line);padding:8px 0} | |
| 89 | + #logtbl td{display:grid;grid-template-columns:86px minmax(0,1fr);gap:8px; | |
| 90 | + padding:1px 0;border:0;word-break:break-word} | |
| 91 | + #logtbl td::before{content:attr(data-label);color:var(--text-2);font-size:10.5px; | |
| 92 | + text-transform:uppercase;letter-spacing:.05em} | |
| 93 | + #logtbl td > span{justify-self:start} | |
| 94 | +} | |
| 95 | +@media(max-width:640px){ | |
| 96 | + .wrap{padding:12px} | |
| 97 | + .hdr-row{grid-template-columns:1fr} | |
| 98 | + .head{gap:8px} | |
| 99 | +} | |
| 100 | +</style> | |
| 101 | +</head> | |
| 102 | +<body> | |
| 103 | +<div class="wrap"> | |
| 104 | + | |
| 105 | + <div class="head"> | |
| 106 | + <div> | |
| 107 | + <h1>webhook</h1> | |
| 108 | + <div class="sub">Named webhook & REST triggers — secrets stay on this node</div> | |
| 109 | + <div class="sub2" id="policynote"></div> | |
| 110 | + </div> | |
| 111 | + <div class="spacer"></div> | |
| 112 | + <button class="embed-hide icon-btn" id="themeToggle" type="button">Theme</button> | |
| 113 | + </div> | |
| 114 | + | |
| 115 | + <div class="card"> | |
| 116 | + <h2>Hooks <span id="count" class="pill muted">0</span></h2> | |
| 117 | + <div class="tbl-wrap"> | |
| 118 | + <table id="tbl"> | |
| 119 | + <thead><tr> | |
| 120 | + <th>Name</th><th>Method</th><th>Endpoint</th><th>Signature</th><th>Secrets</th><th></th> | |
| 121 | + </tr></thead> | |
| 122 | + <tbody id="rows"><tr><td colspan="6" class="empty">Loading…</td></tr></tbody> | |
| 123 | + </table> | |
| 124 | + </div> | |
| 125 | + <div class="row" style="margin-top:12px"> | |
| 126 | + <button id="btnNew" type="button">New hook</button> | |
| 127 | + <button class="ghost" id="btnReload" type="button">Reload</button> | |
| 128 | + </div> | |
| 129 | + </div> | |
| 130 | + | |
| 131 | + <div class="card hidden" id="editor"> | |
| 132 | + <h2 id="editorTitle">New hook</h2> | |
| 133 | + <div class="row"> | |
| 134 | + <div class="grow1"><label for="fName">Name</label> | |
| 135 | + <input id="fName" placeholder="deploy-note" autocomplete="off"></div> | |
| 136 | + <div class="grow1"><label for="fMethod">Method</label> | |
| 137 | + <select id="fMethod"> | |
| 138 | + <option>POST</option><option>GET</option><option>PUT</option> | |
| 139 | + <option>PATCH</option><option>DELETE</option><option>HEAD</option> | |
| 140 | + </select></div> | |
| 141 | + <div class="grow2"><label for="fUrl">URL</label> | |
| 142 | + <input id="fUrl" placeholder="https://example.com/hooks/abc" autocomplete="off"></div> | |
| 143 | + </div> | |
| 144 | + <div class="row" style="margin-top:10px"> | |
| 145 | + <div class="grow2"><label for="fDesc">Description</label> | |
| 146 | + <input id="fDesc" placeholder="Deploy notification" autocomplete="off"></div> | |
| 147 | + <div class="grow1"><label for="fSig">Signature</label> | |
| 148 | + <select id="fSig"> | |
| 149 | + <option value="">none</option> | |
| 150 | + <option value="github">github — X-Hub-Signature-256</option> | |
| 151 | + <option value="gitlab">gitlab — X-Gitlab-Token</option> | |
| 152 | + <option value="v2">v2 — timestamped HMAC</option> | |
| 153 | + </select></div> | |
| 154 | + <div class="grow1"><label for="fSecret">HMAC secret</label> | |
| 155 | + <input id="fSecret" type="password" autocomplete="new-password" | |
| 156 | + placeholder="leave blank to keep"></div> | |
| 157 | + </div> | |
| 158 | + | |
| 159 | + <div style="margin-top:12px"> | |
| 160 | + <label>Headers</label> | |
| 161 | + <div class="col" id="hdrList"></div> | |
| 162 | + <div class="row" style="margin-top:8px"> | |
| 163 | + <button class="ghost tiny" id="btnAddHdr" type="button">Add header</button> | |
| 164 | + </div> | |
| 165 | + <div class="hint">A stored value is never sent back to the browser. Leave the | |
| 166 | + value blank to keep the secret already saved for that header name.</div> | |
| 167 | + </div> | |
| 168 | + | |
| 169 | + <div class="row" style="margin-top:14px"> | |
| 170 | + <button id="btnSave" type="button">Save hook</button> | |
| 171 | + <button class="ghost" id="btnCancel" type="button">Cancel</button> | |
| 172 | + <span id="saveMsg" class="hint"></span> | |
| 173 | + </div> | |
| 174 | + </div> | |
| 175 | + | |
| 176 | + <div class="card"> | |
| 177 | + <h2>Test fire</h2> | |
| 178 | + <div class="row"> | |
| 179 | + <div class="grow1"><label for="fFire">Hook</label> | |
| 180 | + <select id="fFire"></select></div> | |
| 181 | + <div class="grow2"><label for="fQuery">Query string (optional)</label> | |
| 182 | + <input id="fQuery" placeholder="event=deploy&env=prod" autocomplete="off"></div> | |
| 183 | + </div> | |
| 184 | + <div style="margin-top:10px"> | |
| 185 | + <label for="fPayload">Payload (JSON)</label> | |
| 186 | + <textarea id="fPayload">{ | |
| 187 | + "event": "deploy", | |
| 188 | + "service": "scorpiox-bot", | |
| 189 | + "status": "ok" | |
| 190 | +}</textarea> | |
| 191 | + </div> | |
| 192 | + <div class="row" style="margin-top:10px"> | |
| 193 | + <button id="btnFire" type="button">Send</button> | |
| 194 | + <span class="hint">Sent from this node with the stored headers and signature.</span> | |
| 195 | + </div> | |
| 196 | + <div class="out" id="fireOut"></div> | |
| 197 | + </div> | |
| 198 | + | |
| 199 | + <div class="card"> | |
| 200 | + <h2>Recent deliveries</h2> | |
| 201 | + <div class="tbl-wrap"> | |
| 202 | + <table id="logtbl"> | |
| 203 | + <thead><tr><th>When (UTC)</th><th>Hook</th><th>Status</th><th>Bytes</th><th>ms</th><th>Detail</th></tr></thead> | |
| 204 | + <tbody id="logRows"><tr><td colspan="6" class="empty">No deliveries yet.</td></tr></tbody> | |
| 205 | + </table> | |
| 206 | + </div> | |
| 207 | + </div> | |
| 208 | + | |
| 209 | + <div class="foot"> | |
| 210 | + Tool contract: <span class="mono">webhook_list</span>, | |
| 211 | + <span class="mono">webhook_trigger</span>. Press | |
| 212 | + <kbd>Ctrl</kbd>+<kbd>Enter</kbd> in the payload box to send. | |
| 213 | + </div> | |
| 214 | +</div> | |
| 215 | + | |
| 216 | +<script> | |
| 217 | +/* ------------------------------------------------------------------ routes | |
| 218 | + * Two call shapes, and getting this wrong is the classic plugin bug: | |
| 219 | + * served through the hub (bot.scorpiox.net/plugins?plugin=plugin_webhook…) | |
| 220 | + * -> call the hub proxy back: /plugins?plugin=plugin_webhook&action=… | |
| 221 | + * opened directly on the node | |
| 222 | + * -> the plugin IS the route: /plugin_webhook?action=… | |
| 223 | + * Never call /plugins?plugin= on the node itself: that is the discovery | |
| 224 | + * endpoint and it answers with the plugin list, not with this plugin. */ | |
| 225 | +var Q = new URLSearchParams(location.search); | |
| 226 | +var HUB = Q.get('plugin') || ''; | |
| 227 | +var NODE = Q.get('node') || ''; | |
| 228 | +var PW = Q.get('pwd') || (NODE && localStorage.getItem('bot_pwd_' + NODE)) || | |
| 229 | + localStorage.getItem('bot_active_pwd') || ''; | |
| 230 | + | |
| 231 | +function api(action, payload, method) { | |
| 232 | + var u = (HUB ? '/plugins?plugin=' + encodeURIComponent(HUB) | |
| 233 | + : '/plugin_webhook') + | |
| 234 | + '?action=' + encodeURIComponent(action) + '&format=json' + | |
| 235 | + (NODE ? '&node=' + encodeURIComponent(NODE) : '') + | |
| 236 | + (PW ? '&pwd=' + encodeURIComponent(PW) : ''); | |
| 237 | + var opt = { | |
| 238 | + method: method || (payload ? 'POST' : 'GET'), | |
| 239 | + headers: PW ? {'X-Bot-Password': PW} : {} | |
| 240 | + }; | |
| 241 | + if (payload) { | |
| 242 | + opt.headers['Content-Type'] = 'application/json'; | |
| 243 | + opt.body = JSON.stringify(payload); | |
| 244 | + } | |
| 245 | + return fetch(u, opt).then(function (r) { | |
| 246 | + return r.text().then(function (t) { | |
| 247 | + var d; | |
| 248 | + try { d = JSON.parse(t); } catch (e) { throw new Error('not JSON: ' + t.slice(0, 200)); } | |
| 249 | + if (!r.ok || d.ok === false) { | |
| 250 | + throw new Error(d.error || ('HTTP ' + r.status)); | |
| 251 | + } | |
| 252 | + return d; | |
| 253 | + }); | |
| 254 | + }); | |
| 255 | +} | |
| 256 | + | |
| 257 | +function el(id) { return document.getElementById(id); } | |
| 258 | +function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } | |
| 259 | +function txt(s) { return document.createTextNode(s == null ? '' : String(s)); } | |
| 260 | + | |
| 261 | +var state = { hooks: [], log: [], editing: null, allowPrivate: false }; | |
| 262 | + | |
| 263 | +function renderPolicy() { | |
| 264 | + el('policynote').textContent = state.allowPrivate | |
| 265 | + ? 'Private / loopback endpoints are allowed on this node (WEBHOOK_ALLOW_PRIVATE=1).' | |
| 266 | + : 'Outbound only to public addresses; loopback and private ranges are refused.'; | |
| 267 | +} | |
| 268 | + | |
| 269 | +function headersSummary(h) { | |
| 270 | + var n = (h.headers || []).length; | |
| 271 | + var s = []; | |
| 272 | + if (n) s.push(n + ' header' + (n === 1 ? '' : 's')); | |
| 273 | + if (h.has_secret) s.push('HMAC'); | |
| 274 | + return s.length ? s.join(' + ') : 'none'; | |
| 275 | +} | |
| 276 | + | |
| 277 | +function renderHooks() { | |
| 278 | + var tb = el('rows'); | |
| 279 | + clear(tb); | |
| 280 | + el('count').textContent = String(state.hooks.length); | |
| 281 | + if (!state.hooks.length) { | |
| 282 | + var tr = document.createElement('tr'); | |
| 283 | + var td = document.createElement('td'); | |
| 284 | + td.colSpan = 6; td.className = 'empty'; | |
| 285 | + td.appendChild(txt('No hooks yet. Create one to give the agent a tool it can fire.')); | |
| 286 | + tr.appendChild(td); tb.appendChild(tr); | |
| 287 | + } | |
| 288 | + state.hooks.forEach(function (h) { | |
| 289 | + var tr = document.createElement('tr'); | |
| 290 | + | |
| 291 | + var c1 = document.createElement('td'); | |
| 292 | + c1.className = 'mono'; | |
| 293 | + c1.dataset.label = 'Name'; | |
| 294 | + c1.appendChild(txt(h.name)); | |
| 295 | + if (h.desc) { | |
| 296 | + var d = document.createElement('div'); | |
| 297 | + d.className = 'hint'; | |
| 298 | + d.appendChild(txt(h.desc)); | |
| 299 | + c1.appendChild(d); | |
| 300 | + } | |
| 301 | + tr.appendChild(c1); | |
| 302 | + | |
| 303 | + var c2 = document.createElement('td'); | |
| 304 | + c2.dataset.label = 'Method'; | |
| 305 | + var p = document.createElement('span'); | |
| 306 | + p.className = 'pill'; p.appendChild(txt(h.method)); | |
| 307 | + c2.appendChild(p); | |
| 308 | + tr.appendChild(c2); | |
| 309 | + | |
| 310 | + var c3 = document.createElement('td'); | |
| 311 | + c3.className = 'mono'; | |
| 312 | + c3.dataset.label = 'Endpoint'; | |
| 313 | + c3.appendChild(txt(h.url || '')); | |
| 314 | + tr.appendChild(c3); | |
| 315 | + | |
| 316 | + var c4 = document.createElement('td'); | |
| 317 | + c4.dataset.label = 'Signature'; | |
| 318 | + var sp = document.createElement('span'); | |
| 319 | + if (h.sig) { sp.className = 'pill sig'; sp.appendChild(txt(h.sig)); } | |
| 320 | + else { sp.className = 'pill muted'; sp.appendChild(txt('none')); } | |
| 321 | + c4.appendChild(sp); | |
| 322 | + tr.appendChild(c4); | |
| 323 | + | |
| 324 | + var c5 = document.createElement('td'); | |
| 325 | + c5.className = 'hint'; | |
| 326 | + c5.dataset.label = 'Secrets'; | |
| 327 | + c5.appendChild(txt(headersSummary(h))); | |
| 328 | + tr.appendChild(c5); | |
| 329 | + | |
| 330 | + var c6 = document.createElement('td'); | |
| 331 | + c6.className = 'actions'; | |
| 332 | + c6.dataset.label = ''; | |
| 333 | + c6.style.whiteSpace = 'nowrap'; | |
| 334 | + var bEdit = document.createElement('button'); | |
| 335 | + bEdit.className = 'ghost tiny'; bEdit.type = 'button'; | |
| 336 | + bEdit.appendChild(txt('Edit')); | |
| 337 | + bEdit.onclick = function () { openEditor(h); }; | |
| 338 | + var bDel = document.createElement('button'); | |
| 339 | + bDel.className = 'ghost tiny'; bDel.type = 'button'; | |
| 340 | + bDel.style.marginLeft = '6px'; | |
| 341 | + bDel.appendChild(txt('Delete')); | |
| 342 | + bDel.onclick = function () { removeHook(h.name); }; | |
| 343 | + c6.appendChild(bEdit); c6.appendChild(bDel); | |
| 344 | + tr.appendChild(c6); | |
| 345 | + | |
| 346 | + tb.appendChild(tr); | |
| 347 | + }); | |
| 348 | + | |
| 349 | + var sel = el('fFire'); | |
| 350 | + var keep = sel.value; | |
| 351 | + clear(sel); | |
| 352 | + state.hooks.forEach(function (h) { | |
| 353 | + var o = document.createElement('option'); | |
| 354 | + o.value = h.name; o.appendChild(txt(h.name + ' (' + h.method + ')')); | |
| 355 | + sel.appendChild(o); | |
| 356 | + }); | |
| 357 | + if (keep) sel.value = keep; | |
| 358 | +} | |
| 359 | + | |
| 360 | +function renderLog() { | |
| 361 | + var tb = el('logRows'); | |
| 362 | + clear(tb); | |
| 363 | + if (!state.log.length) { | |
| 364 | + var tr = document.createElement('tr'); | |
| 365 | + var td = document.createElement('td'); | |
| 366 | + td.colSpan = 6; td.className = 'empty'; | |
| 367 | + td.appendChild(txt('No deliveries yet.')); | |
| 368 | + tr.appendChild(td); tb.appendChild(tr); | |
| 369 | + return; | |
| 370 | + } | |
| 371 | + /* The store keeps 50 deliveries; a page that lists all of them is a wall. | |
| 372 | + * The newest eight are what a person is looking for. */ | |
| 373 | + state.log.slice(0, 8).forEach(function (e) { | |
| 374 | + var tr = document.createElement('tr'); | |
| 375 | + var c1 = document.createElement('td'); | |
| 376 | + c1.className = 'mono'; c1.dataset.label = 'When'; c1.appendChild(txt(e.at)); | |
| 377 | + tr.appendChild(c1); | |
| 378 | + var c2 = document.createElement('td'); | |
| 379 | + c2.className = 'mono'; c2.dataset.label = 'Hook'; c2.appendChild(txt(e.name)); | |
| 380 | + tr.appendChild(c2); | |
| 381 | + var c3 = document.createElement('td'); | |
| 382 | + c3.dataset.label = 'Status'; | |
| 383 | + var p = document.createElement('span'); | |
| 384 | + p.className = 'pill ' + (e.ok ? 'ok' : 'bad'); | |
| 385 | + p.appendChild(txt(e.status ? String(e.status) : 'error')); | |
| 386 | + c3.appendChild(p); | |
| 387 | + tr.appendChild(c3); | |
| 388 | + var c4 = document.createElement('td'); | |
| 389 | + c4.className = 'mono'; c4.dataset.label = 'Bytes'; c4.appendChild(txt(e.bytes)); | |
| 390 | + tr.appendChild(c4); | |
| 391 | + var c5 = document.createElement('td'); | |
| 392 | + c5.className = 'mono'; c5.dataset.label = 'ms'; c5.appendChild(txt(e.ms)); | |
| 393 | + tr.appendChild(c5); | |
| 394 | + /* An empty Detail row is five lines of nothing on a phone, so it is only | |
| 395 | + * emitted when there is something to say. */ | |
| 396 | + if (e.error) { | |
| 397 | + var c6 = document.createElement('td'); | |
| 398 | + c6.className = 'hint'; c6.dataset.label = 'Detail'; | |
| 399 | + c6.appendChild(txt(e.error)); | |
| 400 | + tr.appendChild(c6); | |
| 401 | + } | |
| 402 | + tb.appendChild(tr); | |
| 403 | + }); | |
| 404 | +} | |
| 405 | + | |
| 406 | +function load() { | |
| 407 | + return api('list').then(function (d) { | |
| 408 | + state.hooks = d.hooks || []; | |
| 409 | + state.log = d.log || []; | |
| 410 | + state.allowPrivate = !!d.allow_private; | |
| 411 | + renderPolicy(); | |
| 412 | + renderHooks(); | |
| 413 | + renderLog(); | |
| 414 | + }).catch(function (e) { | |
| 415 | + var tb = el('rows'); | |
| 416 | + clear(tb); | |
| 417 | + var tr = document.createElement('tr'); | |
| 418 | + var td = document.createElement('td'); | |
| 419 | + td.colSpan = 6; td.className = 'empty'; | |
| 420 | + td.appendChild(txt('Could not load hooks: ' + e.message)); | |
| 421 | + tr.appendChild(td); tb.appendChild(tr); | |
| 422 | + }); | |
| 423 | +} | |
| 424 | + | |
| 425 | +/* ---------------------------------------------------------------- editor */ | |
| 426 | + | |
| 427 | +function addHeaderRow(name, value, hasSecret) { | |
| 428 | + var row = document.createElement('div'); | |
| 429 | + row.className = 'hdr-row'; | |
| 430 | + | |
| 431 | + var n = document.createElement('div'); | |
| 432 | + var ln = document.createElement('label'); ln.appendChild(txt('Header')); | |
| 433 | + var inName = document.createElement('input'); | |
| 434 | + inName.className = 'hdr-name'; inName.value = name || ''; | |
| 435 | + inName.placeholder = 'Authorization'; inName.autocomplete = 'off'; | |
| 436 | + n.appendChild(ln); n.appendChild(inName); | |
| 437 | + | |
| 438 | + var v = document.createElement('div'); | |
| 439 | + var lv = document.createElement('label'); lv.appendChild(txt('Value')); | |
| 440 | + var inVal = document.createElement('input'); | |
| 441 | + inVal.className = 'hdr-value'; inVal.value = value || ''; | |
| 442 | + inVal.type = 'password'; inVal.autocomplete = 'new-password'; | |
| 443 | + inVal.placeholder = hasSecret ? 'stored — leave blank to keep' : 'Bearer …'; | |
| 444 | + v.appendChild(lv); v.appendChild(inVal); | |
| 445 | + | |
| 446 | + var b = document.createElement('button'); | |
| 447 | + b.type = 'button'; b.className = 'icon-btn'; b.appendChild(txt('Remove')); | |
| 448 | + b.onclick = function () { row.parentNode.removeChild(row); }; | |
| 449 | + | |
| 450 | + row.appendChild(n); row.appendChild(v); row.appendChild(b); | |
| 451 | + el('hdrList').appendChild(row); | |
| 452 | +} | |
| 453 | + | |
| 454 | +function openEditor(hook) { | |
| 455 | + state.editing = hook ? hook.name : null; | |
| 456 | + el('editor').classList.remove('hidden'); | |
| 457 | + el('editorTitle').textContent = hook ? ('Edit ' + hook.name) : 'New hook'; | |
| 458 | + el('fName').value = hook ? hook.name : ''; | |
| 459 | + el('fName').disabled = !!hook; | |
| 460 | + el('fMethod').value = hook ? hook.method : 'POST'; | |
| 461 | + el('fUrl').value = hook ? (hook.url || '') : ''; | |
| 462 | + el('fDesc').value = hook ? (hook.desc || '') : ''; | |
| 463 | + el('fSig').value = hook ? (hook.sig || '') : ''; | |
| 464 | + el('fSecret').value = ''; | |
| 465 | + el('fSecret').placeholder = hook && hook.has_secret | |
| 466 | + ? 'stored — leave blank to keep' : 'optional'; | |
| 467 | + clear(el('hdrList')); | |
| 468 | + if (hook) { | |
| 469 | + (hook.headers || []).forEach(function (hd) { | |
| 470 | + addHeaderRow(hd.name, '', !!hd.has_secret); | |
| 471 | + }); | |
| 472 | + } else { | |
| 473 | + addHeaderRow('Content-Type', 'application/json', false); | |
| 474 | + } | |
| 475 | + el('saveMsg').textContent = ''; | |
| 476 | + el('fName').focus(); | |
| 477 | +} | |
| 478 | + | |
| 479 | +function collectHook() { | |
| 480 | + var headers = []; | |
| 481 | + var rows = el('hdrList').children; | |
| 482 | + for (var i = 0; i < rows.length; i++) { | |
| 483 | + var n = rows[i].querySelector('.hdr-name'); | |
| 484 | + var v = rows[i].querySelector('.hdr-value'); | |
| 485 | + if (!n || !n.value.trim()) continue; | |
| 486 | + var entry = { name: n.value.trim() }; | |
| 487 | + /* An empty value means "keep whatever is stored for this name". Sending | |
| 488 | + * the key at all with an empty string would clear the secret. */ | |
| 489 | + if (v && v.value !== '') entry.value = v.value; | |
| 490 | + headers.push(entry); | |
| 491 | + } | |
| 492 | + var body = { | |
| 493 | + name: el('fName').value.trim(), | |
| 494 | + url: el('fUrl').value.trim(), | |
| 495 | + method: el('fMethod').value, | |
| 496 | + desc: el('fDesc').value.trim(), | |
| 497 | + sig: el('fSig').value, | |
| 498 | + headers: headers | |
| 499 | + }; | |
| 500 | + if (el('fSecret').value) body.secret = el('fSecret').value; | |
| 501 | + return body; | |
| 502 | +} | |
| 503 | + | |
| 504 | +function saveHook() { | |
| 505 | + var body = collectHook(); | |
| 506 | + if (!body.name) { el('saveMsg').textContent = 'A name is required.'; return; } | |
| 507 | + if (!body.url) { el('saveMsg').textContent = 'A URL is required.'; return; } | |
| 508 | + el('saveMsg').textContent = 'Saving…'; | |
| 509 | + api('save', body).then(function () { | |
| 510 | + el('editor').classList.add('hidden'); | |
| 511 | + return load(); | |
| 512 | + }).catch(function (e) { | |
| 513 | + el('saveMsg').textContent = 'Error: ' + e.message; | |
| 514 | + }); | |
| 515 | +} | |
| 516 | + | |
| 517 | +function removeHook(name) { | |
| 518 | + api('delete', { name: name }).then(load).catch(function (e) { | |
| 519 | + el('fireOut').className = 'out on err'; | |
| 520 | + el('fireOut').textContent = 'Delete failed: ' + e.message; | |
| 521 | + }); | |
| 522 | +} | |
| 523 | + | |
| 524 | +/* ------------------------------------------------------------------- fire */ | |
| 525 | + | |
| 526 | +function fire() { | |
| 527 | + var name = el('fFire').value; | |
| 528 | + var out = el('fireOut'); | |
| 529 | + if (!name) { | |
| 530 | + out.className = 'out on err'; | |
| 531 | + out.textContent = 'Create a hook first.'; | |
| 532 | + return; | |
| 533 | + } | |
| 534 | + var payload = el('fPayload').value; | |
| 535 | + try { JSON.parse(payload || '{}'); } | |
| 536 | + catch (e) { | |
| 537 | + out.className = 'out on err'; | |
| 538 | + out.textContent = 'The payload is not valid JSON: ' + e.message; | |
| 539 | + return; | |
| 540 | + } | |
| 541 | + var body = { name: name, payload: payload || '{}' }; | |
| 542 | + if (el('fQuery').value.trim()) body.query = el('fQuery').value.trim(); | |
| 543 | + | |
| 544 | + out.className = 'out on'; | |
| 545 | + out.textContent = 'Sending…'; | |
| 546 | + api('fire', body).then(function (d) { | |
| 547 | + out.className = 'out on' + (d.ok_status ? '' : ' err'); | |
| 548 | + out.textContent = JSON.stringify(d, null, 2); | |
| 549 | + return load(); | |
| 550 | + }).catch(function (e) { | |
| 551 | + out.className = 'out on err'; | |
| 552 | + out.textContent = 'Send failed: ' + e.message; | |
| 553 | + }); | |
| 554 | +} | |
| 555 | + | |
| 556 | +/* ------------------------------------------------------------------- wire */ | |
| 557 | + | |
| 558 | +el('btnNew').onclick = function () { openEditor(null); }; | |
| 559 | +el('btnReload').onclick = function () { load(); }; | |
| 560 | +el('btnCancel').onclick = function () { el('editor').classList.add('hidden'); }; | |
| 561 | +el('btnSave').onclick = saveHook; | |
| 562 | +el('btnAddHdr').onclick = function () { addHeaderRow('', '', false); }; | |
| 563 | +el('btnFire').onclick = fire; | |
| 564 | +el('fPayload').addEventListener('keydown', function (e) { | |
| 565 | + if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') fire(); | |
| 566 | +}); | |
| 567 | +el('themeToggle').onclick = function () { | |
| 568 | + if (window.sxApplyTheme) { | |
| 569 | + window.sxApplyTheme(window.sxTheme && window.sxTheme() === 'dark' ? 'light' : 'dark'); | |
| 570 | + } | |
| 571 | +}; | |
| 572 | + | |
| 573 | +load(); | |
| 574 | +</script> | |
| 575 | +</body></html> |
| 1 | 1 | new file mode 100644 |
| index 0000000..a193f9d | ||
| --- /dev/null | ||
| +++ b/src/ui_html.h | ||
| @@ -0,0 +1,583 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | |
| 2 | +#ifndef SX_WEBHOOK_UI_HTML_H | |
| 3 | +#define SX_WEBHOOK_UI_HTML_H | |
| 4 | + | |
| 5 | +static const char *UI_HTML = | |
| 6 | + "<!DOCTYPE html>\n" | |
| 7 | + "<html lang=\"en\"><head><meta charset=\"utf-8\">\n" | |
| 8 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | |
| 9 | + "<title>webhook</title>\n" | |
| 10 | + "\001\n" | |
| 11 | + "<style>\n" | |
| 12 | + "*{box-sizing:border-box}\n" | |
| 13 | + "html,body{margin:0}\n" | |
| 14 | + "body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;\n" | |
| 15 | + " line-height:1.5;-webkit-font-smoothing:antialiased}\n" | |
| 16 | + ".wrap{max-width:1040px;margin:0 auto;padding:16px}\n" | |
| 17 | + ".head{display:flex;align-items:flex-start;gap:12px;flex-wrap:wrap}\n" | |
| 18 | + "h1{font-size:20px;margin:0 0 2px;font-weight:650;letter-spacing:-.01em}\n" | |
| 19 | + ".sub{color:var(--text-2);font-size:12.5px}\n" | |
| 20 | + ".sub2{color:var(--text-2);font-size:11.5px;margin-top:2px}\n" | |
| 21 | + ".spacer{flex:1 1 auto}\n" | |
| 22 | + ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;\n" | |
| 23 | + " padding:16px;margin-bottom:14px}\n" | |
| 24 | + ".card h2{font-size:12px;font-weight:650;margin:0 0 12px;color:var(--text-2);\n" | |
| 25 | + " text-transform:uppercase;letter-spacing:.06em}\n" | |
| 26 | + ".row{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end}\n" | |
| 27 | + ".col{display:flex;flex-direction:column;gap:8px}\n" | |
| 28 | + "label{display:block;font-size:11px;color:var(--text-2);margin-bottom:4px;\n" | |
| 29 | + " text-transform:uppercase;letter-spacing:.05em}\n" | |
| 30 | + "input,select,textarea{background:var(--input-bg);border:1px solid var(--line);\n" | |
| 31 | + " color:var(--text);border-radius:9px;padding:7px 10px;font-size:13.5px;\n" | |
| 32 | + " font-family:var(--font);outline:none;min-width:0;width:100%}\n" | |
| 33 | + "textarea{font-family:var(--mono);font-size:12.5px;resize:vertical;min-height:88px;\n" | |
| 34 | + " line-height:1.45}\n" | |
| 35 | + "input:focus,select:focus,textarea:focus{border-color:var(--blue)}\n" | |
| 36 | + "button{background:var(--blue);color:#fff;border:0;border-radius:980px;\n" | |
| 37 | + " padding:7px 15px;font-size:13px;font-weight:600;cursor:pointer;font-family:var(--font)}\n" | |
| 38 | + "button.ghost{background:var(--surface-2);color:var(--text)}\n" | |
| 39 | + "button.danger{background:var(--red)}\n" | |
| 40 | + "button.tiny{padding:3px 10px;font-size:12px;border-radius:8px}\n" | |
| 41 | + "button:active{transform:scale(.98)}\n" | |
| 42 | + "button:disabled{opacity:.55;cursor:default}\n" | |
| 43 | + ".grow1{flex:1 1 200px}.grow2{flex:2 1 320px}\n" | |
| 44 | + "table{width:100%;border-collapse:collapse;font-size:13px}\n" | |
| 45 | + "th{text-align:left;font-size:10.5px;color:var(--text-2);text-transform:uppercase;\n" | |
| 46 | + " letter-spacing:.05em;font-weight:600;padding:0 8px 7px 0;\n" | |
| 47 | + " border-bottom:1px solid var(--line);white-space:nowrap}\n" | |
| 48 | + "td{padding:9px 8px 9px 0;border-bottom:1px solid var(--line);vertical-align:top}\n" | |
| 49 | + "tr:last-child td{border-bottom:0}\n" | |
| 50 | + "td.mono,.mono{font-family:var(--mono);font-size:12px;\n" | |
| 51 | + " font-variant-numeric:tabular-nums;word-break:break-all}\n" | |
| 52 | + ".tbl-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch}\n" | |
| 53 | + ".pill{display:inline-block;font-size:10.5px;font-weight:600;padding:2px 8px;\n" | |
| 54 | + " border-radius:980px;border:1px solid var(--line);color:var(--text-2);\n" | |
| 55 | + " background:var(--surface-2);white-space:nowrap}\n" | |
| 56 | + ".pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)}\n" | |
| 57 | + ".pill.bad{color:var(--red);border-color:rgba(255,69,58,.35)}\n" | |
| 58 | + ".pill.sig{color:var(--blue);border-color:rgba(10,132,255,.35)}\n" | |
| 59 | + ".pill.muted{color:var(--text-2)}\n" | |
| 60 | + ".empty{color:var(--text-2);font-size:12.5px;padding:10px 0}\n" | |
| 61 | + ".hint{color:var(--text-2);font-size:11.5px;margin-top:6px}\n" | |
| 62 | + ".out{margin-top:12px;padding:12px;border-radius:11px;background:var(--code-bg);\n" | |
| 63 | + " font-family:var(--mono);font-size:12px;white-space:pre-wrap;\n" | |
| 64 | + " word-break:break-word;display:none}\n" | |
| 65 | + ".out.on{display:block}\n" | |
| 66 | + ".out.err{color:var(--red)}\n" | |
| 67 | + ".hdr-row{display:grid;grid-template-columns:1fr 1fr auto;gap:8px;align-items:end}\n" | |
| 68 | + ".icon-btn{background:transparent;border:1px solid var(--line);color:var(--text-2);\n" | |
| 69 | + " border-radius:8px;padding:6px 9px;font-size:12px}\n" | |
| 70 | + ".hidden{display:none!important}\n" | |
| 71 | + ".foot{color:var(--text-2);font-size:11.5px;margin-top:2px}\n" | |
| 72 | + "kbd{font-family:var(--mono);font-size:11px;background:var(--surface-2);\n" | |
| 73 | + " border:1px solid var(--line);border-radius:5px;padding:1px 5px}\n" | |
| 74 | + "/* A five-column table cannot fit 390 px without squeezing the name into a\n" | |
| 75 | + " * vertical ribbon, so below 700 px each row becomes a labelled block. */\n" | |
| 76 | + "@media(max-width:700px){\n" | |
| 77 | + " #tbl thead{display:none}\n" | |
| 78 | + " #tbl,#tbl tbody{display:block}\n" | |
| 79 | + " #tbl tr{display:block;border:1px solid var(--line);border-radius:12px;\n" | |
| 80 | + " padding:10px 12px;margin-bottom:10px}\n" | |
| 81 | + " #tbl td{display:grid;grid-template-columns:76px minmax(0,1fr);gap:8px;\n" | |
| 82 | + " padding:2px 0;border:0;align-items:baseline;word-break:break-word}\n" | |
| 83 | + " #tbl td::before{content:attr(data-label);color:var(--text-2);font-size:10.5px;\n" | |
| 84 | + " text-transform:uppercase;letter-spacing:.05em}\n" | |
| 85 | + " #tbl td > .hint{grid-column:2;color:var(--text-2);font-size:11.5px}\n" | |
| 86 | + " #tbl td.actions{grid-template-columns:1fr 1fr;margin-top:8px;gap:6px}\n" | |
| 87 | + " #tbl td.actions::before{content:none}\n" | |
| 88 | + " #tbl td > span,#tbl td > button{justify-self:start}\n" | |
| 89 | + " #tbl td.actions > button{justify-self:stretch}\n" | |
| 90 | + " /* The delivery log has the same problem: six columns at 390 px. */\n" | |
| 91 | + " #logtbl thead{display:none}\n" | |
| 92 | + " #logtbl,#logtbl tbody{display:block}\n" | |
| 93 | + " #logtbl tr{display:block;border-bottom:1px solid var(--line);padding:8px 0}\n" | |
| 94 | + " #logtbl td{display:grid;grid-template-columns:86px minmax(0,1fr);gap:8px;\n" | |
| 95 | + " padding:1px 0;border:0;word-break:break-word}\n" | |
| 96 | + " #logtbl td::before{content:attr(data-label);color:var(--text-2);font-size:10.5px;\n" | |
| 97 | + " text-transform:uppercase;letter-spacing:.05em}\n" | |
| 98 | + " #logtbl td > span{justify-self:start}\n" | |
| 99 | + "}\n" | |
| 100 | + "@media(max-width:640px){\n" | |
| 101 | + " .wrap{padding:12px}\n" | |
| 102 | + " .hdr-row{grid-template-columns:1fr}\n" | |
| 103 | + " .head{gap:8px}\n" | |
| 104 | + "}\n" | |
| 105 | + "</style>\n" | |
| 106 | + "</head>\n" | |
| 107 | + "<body>\n" | |
| 108 | + "<div class=\"wrap\">\n" | |
| 109 | + "\n" | |
| 110 | + " <div class=\"head\">\n" | |
| 111 | + " <div>\n" | |
| 112 | + " <h1>webhook</h1>\n" | |
| 113 | + " <div class=\"sub\">Named webhook & REST triggers — secrets stay on this node</div>\n" | |
| 114 | + " <div class=\"sub2\" id=\"policynote\"></div>\n" | |
| 115 | + " </div>\n" | |
| 116 | + " <div class=\"spacer\"></div>\n" | |
| 117 | + " <button class=\"embed-hide icon-btn\" id=\"themeToggle\" type=\"button\">Theme</button>\n" | |
| 118 | + " </div>\n" | |
| 119 | + "\n" | |
| 120 | + " <div class=\"card\">\n" | |
| 121 | + " <h2>Hooks <span id=\"count\" class=\"pill muted\">0</span></h2>\n" | |
| 122 | + " <div class=\"tbl-wrap\">\n" | |
| 123 | + " <table id=\"tbl\">\n" | |
| 124 | + " <thead><tr>\n" | |
| 125 | + " <th>Name</th><th>Method</th><th>Endpoint</th><th>Signature</th><th>Secrets</th><th></th>\n" | |
| 126 | + " </tr></thead>\n" | |
| 127 | + " <tbody id=\"rows\"><tr><td colspan=\"6\" class=\"empty\">Loading…</td></tr></tbody>\n" | |
| 128 | + " </table>\n" | |
| 129 | + " </div>\n" | |
| 130 | + " <div class=\"row\" style=\"margin-top:12px\">\n" | |
| 131 | + " <button id=\"btnNew\" type=\"button\">New hook</button>\n" | |
| 132 | + " <button class=\"ghost\" id=\"btnReload\" type=\"button\">Reload</button>\n" | |
| 133 | + " </div>\n" | |
| 134 | + " </div>\n" | |
| 135 | + "\n" | |
| 136 | + " <div class=\"card hidden\" id=\"editor\">\n" | |
| 137 | + " <h2 id=\"editorTitle\">New hook</h2>\n" | |
| 138 | + " <div class=\"row\">\n" | |
| 139 | + " <div class=\"grow1\"><label for=\"fName\">Name</label>\n" | |
| 140 | + " <input id=\"fName\" placeholder=\"deploy-note\" autocomplete=\"off\"></div>\n" | |
| 141 | + " <div class=\"grow1\"><label for=\"fMethod\">Method</label>\n" | |
| 142 | + " <select id=\"fMethod\">\n" | |
| 143 | + " <option>POST</option><option>GET</option><option>PUT</option>\n" | |
| 144 | + " <option>PATCH</option><option>DELETE</option><option>HEAD</option>\n" | |
| 145 | + " </select></div>\n" | |
| 146 | + " <div class=\"grow2\"><label for=\"fUrl\">URL</label>\n" | |
| 147 | + " <input id=\"fUrl\" placeholder=\"https://example.com/hooks/abc\" autocomplete=\"off\"></div>\n" | |
| 148 | + " </div>\n" | |
| 149 | + " <div class=\"row\" style=\"margin-top:10px\">\n" | |
| 150 | + " <div class=\"grow2\"><label for=\"fDesc\">Description</label>\n" | |
| 151 | + " <input id=\"fDesc\" placeholder=\"Deploy notification\" autocomplete=\"off\"></div>\n" | |
| 152 | + " <div class=\"grow1\"><label for=\"fSig\">Signature</label>\n" | |
| 153 | + " <select id=\"fSig\">\n" | |
| 154 | + " <option value=\"\">none</option>\n" | |
| 155 | + " <option value=\"github\">github — X-Hub-Signature-256</option>\n" | |
| 156 | + " <option value=\"gitlab\">gitlab — X-Gitlab-Token</option>\n" | |
| 157 | + " <option value=\"v2\">v2 — timestamped HMAC</option>\n" | |
| 158 | + " </select></div>\n" | |
| 159 | + " <div class=\"grow1\"><label for=\"fSecret\">HMAC secret</label>\n" | |
| 160 | + " <input id=\"fSecret\" type=\"password\" autocomplete=\"new-password\"\n" | |
| 161 | + " placeholder=\"leave blank to keep\"></div>\n" | |
| 162 | + " </div>\n" | |
| 163 | + "\n" | |
| 164 | + " <div style=\"margin-top:12px\">\n" | |
| 165 | + " <label>Headers</label>\n" | |
| 166 | + " <div class=\"col\" id=\"hdrList\"></div>\n" | |
| 167 | + " <div class=\"row\" style=\"margin-top:8px\">\n" | |
| 168 | + " <button class=\"ghost tiny\" id=\"btnAddHdr\" type=\"button\">Add header</button>\n" | |
| 169 | + " </div>\n" | |
| 170 | + " <div class=\"hint\">A stored value is never sent back to the browser. Leave the\n" | |
| 171 | + " value blank to keep the secret already saved for that header name.</div>\n" | |
| 172 | + " </div>\n" | |
| 173 | + "\n" | |
| 174 | + " <div class=\"row\" style=\"margin-top:14px\">\n" | |
| 175 | + " <button id=\"btnSave\" type=\"button\">Save hook</button>\n" | |
| 176 | + " <button class=\"ghost\" id=\"btnCancel\" type=\"button\">Cancel</button>\n" | |
| 177 | + " <span id=\"saveMsg\" class=\"hint\"></span>\n" | |
| 178 | + " </div>\n" | |
| 179 | + " </div>\n" | |
| 180 | + "\n" | |
| 181 | + " <div class=\"card\">\n" | |
| 182 | + " <h2>Test fire</h2>\n" | |
| 183 | + " <div class=\"row\">\n" | |
| 184 | + " <div class=\"grow1\"><label for=\"fFire\">Hook</label>\n" | |
| 185 | + " <select id=\"fFire\"></select></div>\n" | |
| 186 | + " <div class=\"grow2\"><label for=\"fQuery\">Query string (optional)</label>\n" | |
| 187 | + " <input id=\"fQuery\" placeholder=\"event=deploy&env=prod\" autocomplete=\"off\"></div>\n" | |
| 188 | + " </div>\n" | |
| 189 | + " <div style=\"margin-top:10px\">\n" | |
| 190 | + " <label for=\"fPayload\">Payload (JSON)</label>\n" | |
| 191 | + " <textarea id=\"fPayload\">{\n" | |
| 192 | + " \"event\": \"deploy\",\n" | |
| 193 | + " \"service\": \"scorpiox-bot\",\n" | |
| 194 | + " \"status\": \"ok\"\n" | |
| 195 | + "}</textarea>\n" | |
| 196 | + " </div>\n" | |
| 197 | + " <div class=\"row\" style=\"margin-top:10px\">\n" | |
| 198 | + " <button id=\"btnFire\" type=\"button\">Send</button>\n" | |
| 199 | + " <span class=\"hint\">Sent from this node with the stored headers and signature.</span>\n" | |
| 200 | + " </div>\n" | |
| 201 | + " <div class=\"out\" id=\"fireOut\"></div>\n" | |
| 202 | + " </div>\n" | |
| 203 | + "\n" | |
| 204 | + " <div class=\"card\">\n" | |
| 205 | + " <h2>Recent deliveries</h2>\n" | |
| 206 | + " <div class=\"tbl-wrap\">\n" | |
| 207 | + " <table id=\"logtbl\">\n" | |
| 208 | + " <thead><tr><th>When (UTC)</th><th>Hook</th><th>Status</th><th>Bytes</th><th>ms</th><th>Detail</th></tr></thead>\n" | |
| 209 | + " <tbody id=\"logRows\"><tr><td colspan=\"6\" class=\"empty\">No deliveries yet.</td></tr></tbody>\n" | |
| 210 | + " </table>\n" | |
| 211 | + " </div>\n" | |
| 212 | + " </div>\n" | |
| 213 | + "\n" | |
| 214 | + " <div class=\"foot\">\n" | |
| 215 | + " Tool contract: <span class=\"mono\">webhook_list</span>,\n" | |
| 216 | + " <span class=\"mono\">webhook_trigger</span>. Press\n" | |
| 217 | + " <kbd>Ctrl</kbd>+<kbd>Enter</kbd> in the payload box to send.\n" | |
| 218 | + " </div>\n" | |
| 219 | + "</div>\n" | |
| 220 | + "\n" | |
| 221 | + "<script>\n" | |
| 222 | + "/* ------------------------------------------------------------------ routes\n" | |
| 223 | + " * Two call shapes, and getting this wrong is the classic plugin bug:\n" | |
| 224 | + " * served through the hub (bot.scorpiox.net/plugins?plugin=plugin_webhook…)\n" | |
| 225 | + " * -> call the hub proxy back: /plugins?plugin=plugin_webhook&action=…\n" | |
| 226 | + " * opened directly on the node\n" | |
| 227 | + " * -> the plugin IS the route: /plugin_webhook?action=…\n" | |
| 228 | + " * Never call /plugins?plugin= on the node itself: that is the discovery\n" | |
| 229 | + " * endpoint and it answers with the plugin list, not with this plugin. */\n" | |
| 230 | + "var Q = new URLSearchParams(location.search);\n" | |
| 231 | + "var HUB = Q.get('plugin') || '';\n" | |
| 232 | + "var NODE = Q.get('node') || '';\n" | |
| 233 | + "var PW = Q.get('pwd') || (NODE && localStorage.getItem('bot_pwd_' + NODE)) ||\n" | |
| 234 | + " localStorage.getItem('bot_active_pwd') || '';\n" | |
| 235 | + "\n" | |
| 236 | + "function api(action, payload, method) {\n" | |
| 237 | + " var u = (HUB ? '/plugins?plugin=' + encodeURIComponent(HUB)\n" | |
| 238 | + " : '/plugin_webhook') +\n" | |
| 239 | + " '?action=' + encodeURIComponent(action) + '&format=json' +\n" | |
| 240 | + " (NODE ? '&node=' + encodeURIComponent(NODE) : '') +\n" | |
| 241 | + " (PW ? '&pwd=' + encodeURIComponent(PW) : '');\n" | |
| 242 | + " var opt = {\n" | |
| 243 | + " method: method || (payload ? 'POST' : 'GET'),\n" | |
| 244 | + " headers: PW ? {'X-Bot-Password': PW} : {}\n" | |
| 245 | + " };\n" | |
| 246 | + " if (payload) {\n" | |
| 247 | + " opt.headers['Content-Type'] = 'application/json';\n" | |
| 248 | + " opt.body = JSON.stringify(payload);\n" | |
| 249 | + " }\n" | |
| 250 | + " return fetch(u, opt).then(function (r) {\n" | |
| 251 | + " return r.text().then(function (t) {\n" | |
| 252 | + " var d;\n" | |
| 253 | + " try { d = JSON.parse(t); } catch (e) { throw new Error('not JSON: ' + t.slice(0, 200)); }\n" | |
| 254 | + " if (!r.ok || d.ok === false) {\n" | |
| 255 | + " throw new Error(d.error || ('HTTP ' + r.status));\n" | |
| 256 | + " }\n" | |
| 257 | + " return d;\n" | |
| 258 | + " });\n" | |
| 259 | + " });\n" | |
| 260 | + "}\n" | |
| 261 | + "\n" | |
| 262 | + "function el(id) { return document.getElementById(id); }\n" | |
| 263 | + "function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }\n" | |
| 264 | + "function txt(s) { return document.createTextNode(s == null ? '' : String(s)); }\n" | |
| 265 | + "\n" | |
| 266 | + "var state = { hooks: [], log: [], editing: null, allowPrivate: false };\n" | |
| 267 | + "\n" | |
| 268 | + "function renderPolicy() {\n" | |
| 269 | + " el('policynote').textContent = state.allowPrivate\n" | |
| 270 | + " ? 'Private / loopback endpoints are allowed on this node (WEBHOOK_ALLOW_PRIVATE=1).'\n" | |
| 271 | + " : 'Outbound only to public addresses; loopback and private ranges are refused.';\n" | |
| 272 | + "}\n" | |
| 273 | + "\n" | |
| 274 | + "function headersSummary(h) {\n" | |
| 275 | + " var n = (h.headers || []).length;\n" | |
| 276 | + " var s = [];\n" | |
| 277 | + " if (n) s.push(n + ' header' + (n === 1 ? '' : 's'));\n" | |
| 278 | + " if (h.has_secret) s.push('HMAC');\n" | |
| 279 | + " return s.length ? s.join(' + ') : 'none';\n" | |
| 280 | + "}\n" | |
| 281 | + "\n" | |
| 282 | + "function renderHooks() {\n" | |
| 283 | + " var tb = el('rows');\n" | |
| 284 | + " clear(tb);\n" | |
| 285 | + " el('count').textContent = String(state.hooks.length);\n" | |
| 286 | + " if (!state.hooks.length) {\n" | |
| 287 | + " var tr = document.createElement('tr');\n" | |
| 288 | + " var td = document.createElement('td');\n" | |
| 289 | + " td.colSpan = 6; td.className = 'empty';\n" | |
| 290 | + " td.appendChild(txt('No hooks yet. Create one to give the agent a tool it can fire.'));\n" | |
| 291 | + " tr.appendChild(td); tb.appendChild(tr);\n" | |
| 292 | + " }\n" | |
| 293 | + " state.hooks.forEach(function (h) {\n" | |
| 294 | + " var tr = document.createElement('tr');\n" | |
| 295 | + "\n" | |
| 296 | + " var c1 = document.createElement('td');\n" | |
| 297 | + " c1.className = 'mono';\n" | |
| 298 | + " c1.dataset.label = 'Name';\n" | |
| 299 | + " c1.appendChild(txt(h.name));\n" | |
| 300 | + " if (h.desc) {\n" | |
| 301 | + " var d = document.createElement('div');\n" | |
| 302 | + " d.className = 'hint';\n" | |
| 303 | + " d.appendChild(txt(h.desc));\n" | |
| 304 | + " c1.appendChild(d);\n" | |
| 305 | + " }\n" | |
| 306 | + " tr.appendChild(c1);\n" | |
| 307 | + "\n" | |
| 308 | + " var c2 = document.createElement('td');\n" | |
| 309 | + " c2.dataset.label = 'Method';\n" | |
| 310 | + " var p = document.createElement('span');\n" | |
| 311 | + " p.className = 'pill'; p.appendChild(txt(h.method));\n" | |
| 312 | + " c2.appendChild(p);\n" | |
| 313 | + " tr.appendChild(c2);\n" | |
| 314 | + "\n" | |
| 315 | + " var c3 = document.createElement('td');\n" | |
| 316 | + " c3.className = 'mono';\n" | |
| 317 | + " c3.dataset.label = 'Endpoint';\n" | |
| 318 | + " c3.appendChild(txt(h.url || ''));\n" | |
| 319 | + " tr.appendChild(c3);\n" | |
| 320 | + "\n" | |
| 321 | + " var c4 = document.createElement('td');\n" | |
| 322 | + " c4.dataset.label = 'Signature';\n" | |
| 323 | + " var sp = document.createElement('span');\n" | |
| 324 | + " if (h.sig) { sp.className = 'pill sig'; sp.appendChild(txt(h.sig)); }\n" | |
| 325 | + " else { sp.className = 'pill muted'; sp.appendChild(txt('none')); }\n" | |
| 326 | + " c4.appendChild(sp);\n" | |
| 327 | + " tr.appendChild(c4);\n" | |
| 328 | + "\n" | |
| 329 | + " var c5 = document.createElement('td');\n" | |
| 330 | + " c5.className = 'hint';\n" | |
| 331 | + " c5.dataset.label = 'Secrets';\n" | |
| 332 | + " c5.appendChild(txt(headersSummary(h)));\n" | |
| 333 | + " tr.appendChild(c5);\n" | |
| 334 | + "\n" | |
| 335 | + " var c6 = document.createElement('td');\n" | |
| 336 | + " c6.className = 'actions';\n" | |
| 337 | + " c6.dataset.label = '';\n" | |
| 338 | + " c6.style.whiteSpace = 'nowrap';\n" | |
| 339 | + " var bEdit = document.createElement('button');\n" | |
| 340 | + " bEdit.className = 'ghost tiny'; bEdit.type = 'button';\n" | |
| 341 | + " bEdit.appendChild(txt('Edit'));\n" | |
| 342 | + " bEdit.onclick = function () { openEditor(h); };\n" | |
| 343 | + " var bDel = document.createElement('button');\n" | |
| 344 | + " bDel.className = 'ghost tiny'; bDel.type = 'button';\n" | |
| 345 | + " bDel.style.marginLeft = '6px';\n" | |
| 346 | + " bDel.appendChild(txt('Delete'));\n" | |
| 347 | + " bDel.onclick = function () { removeHook(h.name); };\n" | |
| 348 | + " c6.appendChild(bEdit); c6.appendChild(bDel);\n" | |
| 349 | + " tr.appendChild(c6);\n" | |
| 350 | + "\n" | |
| 351 | + " tb.appendChild(tr);\n" | |
| 352 | + " });\n" | |
| 353 | + "\n" | |
| 354 | + " var sel = el('fFire');\n" | |
| 355 | + " var keep = sel.value;\n" | |
| 356 | + " clear(sel);\n" | |
| 357 | + " state.hooks.forEach(function (h) {\n" | |
| 358 | + " var o = document.createElement('option');\n" | |
| 359 | + " o.value = h.name; o.appendChild(txt(h.name + ' (' + h.method + ')'));\n" | |
| 360 | + " sel.appendChild(o);\n" | |
| 361 | + " });\n" | |
| 362 | + " if (keep) sel.value = keep;\n" | |
| 363 | + "}\n" | |
| 364 | + "\n" | |
| 365 | + "function renderLog() {\n" | |
| 366 | + " var tb = el('logRows');\n" | |
| 367 | + " clear(tb);\n" | |
| 368 | + " if (!state.log.length) {\n" | |
| 369 | + " var tr = document.createElement('tr');\n" | |
| 370 | + " var td = document.createElement('td');\n" | |
| 371 | + " td.colSpan = 6; td.className = 'empty';\n" | |
| 372 | + " td.appendChild(txt('No deliveries yet.'));\n" | |
| 373 | + " tr.appendChild(td); tb.appendChild(tr);\n" | |
| 374 | + " return;\n" | |
| 375 | + " }\n" | |
| 376 | + " /* The store keeps 50 deliveries; a page that lists all of them is a wall.\n" | |
| 377 | + " * The newest eight are what a person is looking for. */\n" | |
| 378 | + " state.log.slice(0, 8).forEach(function (e) {\n" | |
| 379 | + " var tr = document.createElement('tr');\n" | |
| 380 | + " var c1 = document.createElement('td');\n" | |
| 381 | + " c1.className = 'mono'; c1.dataset.label = 'When'; c1.appendChild(txt(e.at));\n" | |
| 382 | + " tr.appendChild(c1);\n" | |
| 383 | + " var c2 = document.createElement('td');\n" | |
| 384 | + " c2.className = 'mono'; c2.dataset.label = 'Hook'; c2.appendChild(txt(e.name));\n" | |
| 385 | + " tr.appendChild(c2);\n" | |
| 386 | + " var c3 = document.createElement('td');\n" | |
| 387 | + " c3.dataset.label = 'Status';\n" | |
| 388 | + " var p = document.createElement('span');\n" | |
| 389 | + " p.className = 'pill ' + (e.ok ? 'ok' : 'bad');\n" | |
| 390 | + " p.appendChild(txt(e.status ? String(e.status) : 'error'));\n" | |
| 391 | + " c3.appendChild(p);\n" | |
| 392 | + " tr.appendChild(c3);\n" | |
| 393 | + " var c4 = document.createElement('td');\n" | |
| 394 | + " c4.className = 'mono'; c4.dataset.label = 'Bytes'; c4.appendChild(txt(e.bytes));\n" | |
| 395 | + " tr.appendChild(c4);\n" | |
| 396 | + " var c5 = document.createElement('td');\n" | |
| 397 | + " c5.className = 'mono'; c5.dataset.label = 'ms'; c5.appendChild(txt(e.ms));\n" | |
| 398 | + " tr.appendChild(c5);\n" | |
| 399 | + " /* An empty Detail row is five lines of nothing on a phone, so it is only\n" | |
| 400 | + " * emitted when there is something to say. */\n" | |
| 401 | + " if (e.error) {\n" | |
| 402 | + " var c6 = document.createElement('td');\n" | |
| 403 | + " c6.className = 'hint'; c6.dataset.label = 'Detail';\n" | |
| 404 | + " c6.appendChild(txt(e.error));\n" | |
| 405 | + " tr.appendChild(c6);\n" | |
| 406 | + " }\n" | |
| 407 | + " tb.appendChild(tr);\n" | |
| 408 | + " });\n" | |
| 409 | + "}\n" | |
| 410 | + "\n" | |
| 411 | + "function load() {\n" | |
| 412 | + " return api('list').then(function (d) {\n" | |
| 413 | + " state.hooks = d.hooks || [];\n" | |
| 414 | + " state.log = d.log || [];\n" | |
| 415 | + " state.allowPrivate = !!d.allow_private;\n" | |
| 416 | + " renderPolicy();\n" | |
| 417 | + " renderHooks();\n" | |
| 418 | + " renderLog();\n" | |
| 419 | + " }).catch(function (e) {\n" | |
| 420 | + " var tb = el('rows');\n" | |
| 421 | + " clear(tb);\n" | |
| 422 | + " var tr = document.createElement('tr');\n" | |
| 423 | + " var td = document.createElement('td');\n" | |
| 424 | + " td.colSpan = 6; td.className = 'empty';\n" | |
| 425 | + " td.appendChild(txt('Could not load hooks: ' + e.message));\n" | |
| 426 | + " tr.appendChild(td); tb.appendChild(tr);\n" | |
| 427 | + " });\n" | |
| 428 | + "}\n" | |
| 429 | + "\n" | |
| 430 | + "/* ---------------------------------------------------------------- editor */\n" | |
| 431 | + "\n" | |
| 432 | + "function addHeaderRow(name, value, hasSecret) {\n" | |
| 433 | + " var row = document.createElement('div');\n" | |
| 434 | + " row.className = 'hdr-row';\n" | |
| 435 | + "\n" | |
| 436 | + " var n = document.createElement('div');\n" | |
| 437 | + " var ln = document.createElement('label'); ln.appendChild(txt('Header'));\n" | |
| 438 | + " var inName = document.createElement('input');\n" | |
| 439 | + " inName.className = 'hdr-name'; inName.value = name || '';\n" | |
| 440 | + " inName.placeholder = 'Authorization'; inName.autocomplete = 'off';\n" | |
| 441 | + " n.appendChild(ln); n.appendChild(inName);\n" | |
| 442 | + "\n" | |
| 443 | + " var v = document.createElement('div');\n" | |
| 444 | + " var lv = document.createElement('label'); lv.appendChild(txt('Value'));\n" | |
| 445 | + " var inVal = document.createElement('input');\n" | |
| 446 | + " inVal.className = 'hdr-value'; inVal.value = value || '';\n" | |
| 447 | + " inVal.type = 'password'; inVal.autocomplete = 'new-password';\n" | |
| 448 | + " inVal.placeholder = hasSecret ? 'stored — leave blank to keep' : 'Bearer …';\n" | |
| 449 | + " v.appendChild(lv); v.appendChild(inVal);\n" | |
| 450 | + "\n" | |
| 451 | + " var b = document.createElement('button');\n" | |
| 452 | + " b.type = 'button'; b.className = 'icon-btn'; b.appendChild(txt('Remove'));\n" | |
| 453 | + " b.onclick = function () { row.parentNode.removeChild(row); };\n" | |
| 454 | + "\n" | |
| 455 | + " row.appendChild(n); row.appendChild(v); row.appendChild(b);\n" | |
| 456 | + " el('hdrList').appendChild(row);\n" | |
| 457 | + "}\n" | |
| 458 | + "\n" | |
| 459 | + "function openEditor(hook) {\n" | |
| 460 | + " state.editing = hook ? hook.name : null;\n" | |
| 461 | + " el('editor').classList.remove('hidden');\n" | |
| 462 | + " el('editorTitle').textContent = hook ? ('Edit ' + hook.name) : 'New hook';\n" | |
| 463 | + " el('fName').value = hook ? hook.name : '';\n" | |
| 464 | + " el('fName').disabled = !!hook;\n" | |
| 465 | + " el('fMethod').value = hook ? hook.method : 'POST';\n" | |
| 466 | + " el('fUrl').value = hook ? (hook.url || '') : '';\n" | |
| 467 | + " el('fDesc').value = hook ? (hook.desc || '') : '';\n" | |
| 468 | + " el('fSig').value = hook ? (hook.sig || '') : '';\n" | |
| 469 | + " el('fSecret').value = '';\n" | |
| 470 | + " el('fSecret').placeholder = hook && hook.has_secret\n" | |
| 471 | + " ? 'stored — leave blank to keep' : 'optional';\n" | |
| 472 | + " clear(el('hdrList'));\n" | |
| 473 | + " if (hook) {\n" | |
| 474 | + " (hook.headers || []).forEach(function (hd) {\n" | |
| 475 | + " addHeaderRow(hd.name, '', !!hd.has_secret);\n" | |
| 476 | + " });\n" | |
| 477 | + " } else {\n" | |
| 478 | + " addHeaderRow('Content-Type', 'application/json', false);\n" | |
| 479 | + " }\n" | |
| 480 | + " el('saveMsg').textContent = '';\n" | |
| 481 | + " el('fName').focus();\n" | |
| 482 | + "}\n" | |
| 483 | + "\n" | |
| 484 | + "function collectHook() {\n" | |
| 485 | + " var headers = [];\n" | |
| 486 | + " var rows = el('hdrList').children;\n" | |
| 487 | + " for (var i = 0; i < rows.length; i++) {\n" | |
| 488 | + " var n = rows[i].querySelector('.hdr-name');\n" | |
| 489 | + " var v = rows[i].querySelector('.hdr-value');\n" | |
| 490 | + " if (!n || !n.value.trim()) continue;\n" | |
| 491 | + " var entry = { name: n.value.trim() };\n" | |
| 492 | + " /* An empty value means \"keep whatever is stored for this name\". Sending\n" | |
| 493 | + " * the key at all with an empty string would clear the secret. */\n" | |
| 494 | + " if (v && v.value !== '') entry.value = v.value;\n" | |
| 495 | + " headers.push(entry);\n" | |
| 496 | + " }\n" | |
| 497 | + " var body = {\n" | |
| 498 | + " name: el('fName').value.trim(),\n" | |
| 499 | + " url: el('fUrl').value.trim(),\n" | |
| 500 | + " method: el('fMethod').value,\n" | |
| 501 | + " desc: el('fDesc').value.trim(),\n" | |
| 502 | + " sig: el('fSig').value,\n" | |
| 503 | + " headers: headers\n" | |
| 504 | + " };\n" | |
| 505 | + " if (el('fSecret').value) body.secret = el('fSecret').value;\n" | |
| 506 | + " return body;\n" | |
| 507 | + "}\n" | |
| 508 | + "\n" | |
| 509 | + "function saveHook() {\n" | |
| 510 | + " var body = collectHook();\n" | |
| 511 | + " if (!body.name) { el('saveMsg').textContent = 'A name is required.'; return; }\n" | |
| 512 | + " if (!body.url) { el('saveMsg').textContent = 'A URL is required.'; return; }\n" | |
| 513 | + " el('saveMsg').textContent = 'Saving…';\n" | |
| 514 | + " api('save', body).then(function () {\n" | |
| 515 | + " el('editor').classList.add('hidden');\n" | |
| 516 | + " return load();\n" | |
| 517 | + " }).catch(function (e) {\n" | |
| 518 | + " el('saveMsg').textContent = 'Error: ' + e.message;\n" | |
| 519 | + " });\n" | |
| 520 | + "}\n" | |
| 521 | + "\n" | |
| 522 | + "function removeHook(name) {\n" | |
| 523 | + " api('delete', { name: name }).then(load).catch(function (e) {\n" | |
| 524 | + " el('fireOut').className = 'out on err';\n" | |
| 525 | + " el('fireOut').textContent = 'Delete failed: ' + e.message;\n" | |
| 526 | + " });\n" | |
| 527 | + "}\n" | |
| 528 | + "\n" | |
| 529 | + "/* ------------------------------------------------------------------- fire */\n" | |
| 530 | + "\n" | |
| 531 | + "function fire() {\n" | |
| 532 | + " var name = el('fFire').value;\n" | |
| 533 | + " var out = el('fireOut');\n" | |
| 534 | + " if (!name) {\n" | |
| 535 | + " out.className = 'out on err';\n" | |
| 536 | + " out.textContent = 'Create a hook first.';\n" | |
| 537 | + " return;\n" | |
| 538 | + " }\n" | |
| 539 | + " var payload = el('fPayload').value;\n" | |
| 540 | + " try { JSON.parse(payload || '{}'); }\n" | |
| 541 | + " catch (e) {\n" | |
| 542 | + " out.className = 'out on err';\n" | |
| 543 | + " out.textContent = 'The payload is not valid JSON: ' + e.message;\n" | |
| 544 | + " return;\n" | |
| 545 | + " }\n" | |
| 546 | + " var body = { name: name, payload: payload || '{}' };\n" | |
| 547 | + " if (el('fQuery').value.trim()) body.query = el('fQuery').value.trim();\n" | |
| 548 | + "\n" | |
| 549 | + " out.className = 'out on';\n" | |
| 550 | + " out.textContent = 'Sending…';\n" | |
| 551 | + " api('fire', body).then(function (d) {\n" | |
| 552 | + " out.className = 'out on' + (d.ok_status ? '' : ' err');\n" | |
| 553 | + " out.textContent = JSON.stringify(d, null, 2);\n" | |
| 554 | + " return load();\n" | |
| 555 | + " }).catch(function (e) {\n" | |
| 556 | + " out.className = 'out on err';\n" | |
| 557 | + " out.textContent = 'Send failed: ' + e.message;\n" | |
| 558 | + " });\n" | |
| 559 | + "}\n" | |
| 560 | + "\n" | |
| 561 | + "/* ------------------------------------------------------------------- wire */\n" | |
| 562 | + "\n" | |
| 563 | + "el('btnNew').onclick = function () { openEditor(null); };\n" | |
| 564 | + "el('btnReload').onclick = function () { load(); };\n" | |
| 565 | + "el('btnCancel').onclick = function () { el('editor').classList.add('hidden'); };\n" | |
| 566 | + "el('btnSave').onclick = saveHook;\n" | |
| 567 | + "el('btnAddHdr').onclick = function () { addHeaderRow('', '', false); };\n" | |
| 568 | + "el('btnFire').onclick = fire;\n" | |
| 569 | + "el('fPayload').addEventListener('keydown', function (e) {\n" | |
| 570 | + " if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') fire();\n" | |
| 571 | + "});\n" | |
| 572 | + "el('themeToggle').onclick = function () {\n" | |
| 573 | + " if (window.sxApplyTheme) {\n" | |
| 574 | + " window.sxApplyTheme(window.sxTheme && window.sxTheme() === 'dark' ? 'light' : 'dark');\n" | |
| 575 | + " }\n" | |
| 576 | + "};\n" | |
| 577 | + "\n" | |
| 578 | + "load();\n" | |
| 579 | + "</script>\n" | |
| 580 | + "\002</body></html>\n" | |
| 581 | + ; | |
| 582 | + | |
| 583 | +#endif /* SX_WEBHOOK_UI_HTML_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..953e3f3 | ||
| --- /dev/null | ||
| +++ b/src/wh_buf.c | ||
| @@ -0,0 +1,153 @@ | ||
| 1 | +/* | |
| 2 | + * wh_buf.c - growable buffer + JSON/HTML escapes. See wh_buf.h. | |
| 3 | + * | |
| 4 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 5 | + */ | |
| 6 | +#define _POSIX_C_SOURCE 200809L | |
| 7 | + | |
| 8 | +#include "wh_buf.h" | |
| 9 | + | |
| 10 | +#include <stdarg.h> | |
| 11 | +#include <stdio.h> | |
| 12 | +#include <stdlib.h> | |
| 13 | +#include <string.h> | |
| 14 | + | |
| 15 | +void wh_buf_init(wh_buf *b) | |
| 16 | +{ | |
| 17 | + b->p = NULL; | |
| 18 | + b->n = 0; | |
| 19 | + b->cap = 0; | |
| 20 | + b->oom = 0; | |
| 21 | +} | |
| 22 | + | |
| 23 | +void wh_buf_free(wh_buf *b) | |
| 24 | +{ | |
| 25 | + if (!b) return; | |
| 26 | + free(b->p); | |
| 27 | + b->p = NULL; | |
| 28 | + b->n = 0; | |
| 29 | + b->cap = 0; | |
| 30 | +} | |
| 31 | + | |
| 32 | +static int reserve(wh_buf *b, size_t extra) | |
| 33 | +{ | |
| 34 | + size_t want; | |
| 35 | + char *np; | |
| 36 | + | |
| 37 | + if (b->oom) return 0; | |
| 38 | + want = b->n + extra + 1; | |
| 39 | + if (want <= b->cap) return 1; | |
| 40 | + { | |
| 41 | + size_t cap = b->cap ? b->cap : 256; | |
| 42 | + while (cap < want) { | |
| 43 | + if (cap > (size_t)1 << 30) { b->oom = 1; return 0; } | |
| 44 | + cap *= 2; | |
| 45 | + } | |
| 46 | + np = (char *)realloc(b->p, cap); | |
| 47 | + if (!np) { b->oom = 1; return 0; } | |
| 48 | + b->p = np; | |
| 49 | + b->cap = cap; | |
| 50 | + } | |
| 51 | + return 1; | |
| 52 | +} | |
| 53 | + | |
| 54 | +void wh_buf_add(wh_buf *b, const char *s, size_t n) | |
| 55 | +{ | |
| 56 | + if (!n) return; | |
| 57 | + if (!reserve(b, n)) return; | |
| 58 | + memcpy(b->p + b->n, s, n); | |
| 59 | + b->n += n; | |
| 60 | + b->p[b->n] = '\0'; | |
| 61 | +} | |
| 62 | + | |
| 63 | +void wh_buf_str(wh_buf *b, const char *s) | |
| 64 | +{ | |
| 65 | + if (!s) return; | |
| 66 | + wh_buf_add(b, s, strlen(s)); | |
| 67 | +} | |
| 68 | + | |
| 69 | +void wh_buf_printf(wh_buf *b, const char *fmt, ...) | |
| 70 | +{ | |
| 71 | + va_list ap; | |
| 72 | + char small[512]; | |
| 73 | + int need; | |
| 74 | + | |
| 75 | + va_start(ap, fmt); | |
| 76 | + need = vsnprintf(small, sizeof small, fmt, ap); | |
| 77 | + va_end(ap); | |
| 78 | + if (need < 0) return; | |
| 79 | + if ((size_t)need < sizeof small) { wh_buf_add(b, small, (size_t)need); return; } | |
| 80 | + if (!reserve(b, (size_t)need)) return; | |
| 81 | + va_start(ap, fmt); | |
| 82 | + vsnprintf(b->p + b->n, (size_t)need + 1, fmt, ap); | |
| 83 | + va_end(ap); | |
| 84 | + b->n += (size_t)need; | |
| 85 | +} | |
| 86 | + | |
| 87 | +const char *wh_buf_cstr(wh_buf *b) | |
| 88 | +{ | |
| 89 | + if (!b->p) { | |
| 90 | + if (!reserve(b, 0)) return ""; | |
| 91 | + b->p[0] = '\0'; | |
| 92 | + } | |
| 93 | + return b->p; | |
| 94 | +} | |
| 95 | + | |
| 96 | +void wh_buf_json_str(wh_buf *b, const char *s) | |
| 97 | +{ | |
| 98 | + wh_buf_add(b, "\"", 1); | |
| 99 | + if (s) { | |
| 100 | + for (; *s; s++) { | |
| 101 | + unsigned char c = (unsigned char)*s; | |
| 102 | + switch (c) { | |
| 103 | + case '"': wh_buf_add(b, "\\\"", 2); break; | |
| 104 | + case '\\': wh_buf_add(b, "\\\\", 2); break; | |
| 105 | + case '\n': wh_buf_add(b, "\\n", 2); break; | |
| 106 | + case '\r': wh_buf_add(b, "\\r", 2); break; | |
| 107 | + case '\t': wh_buf_add(b, "\\t", 2); break; | |
| 108 | + case '\b': wh_buf_add(b, "\\b", 2); break; | |
| 109 | + case '\f': wh_buf_add(b, "\\f", 2); break; | |
| 110 | + default: | |
| 111 | + if (c < 0x20) wh_buf_printf(b, "\\u%04x", (unsigned)c); | |
| 112 | + else wh_buf_add(b, (const char *)&c, 1); | |
| 113 | + } | |
| 114 | + } | |
| 115 | + } | |
| 116 | + wh_buf_add(b, "\"", 1); | |
| 117 | +} | |
| 118 | + | |
| 119 | +void wh_buf_key(wh_buf *b, const char *key, int *first) | |
| 120 | +{ | |
| 121 | + /* `first` starts at 1 for a fresh object and is cleared by this call, so | |
| 122 | + * the separator is emitted for every key after the first one. */ | |
| 123 | + if (first) { | |
| 124 | + if (!*first) wh_buf_add(b, ",", 1); | |
| 125 | + *first = 0; | |
| 126 | + } | |
| 127 | + wh_buf_json_str(b, key); | |
| 128 | + wh_buf_add(b, ":", 1); | |
| 129 | +} | |
| 130 | + | |
| 131 | +char *wh_html_escape(const char *s) | |
| 132 | +{ | |
| 133 | + wh_buf b; | |
| 134 | + wh_buf_init(&b); | |
| 135 | + if (s) { | |
| 136 | + for (; *s; s++) { | |
| 137 | + switch (*s) { | |
| 138 | + case '&': wh_buf_str(&b, "&"); break; | |
| 139 | + case '<': wh_buf_str(&b, "<"); break; | |
| 140 | + case '>': wh_buf_str(&b, ">"); break; | |
| 141 | + case '"': wh_buf_str(&b, """); break; | |
| 142 | + case '\'': wh_buf_str(&b, "'"); break; | |
| 143 | + default: wh_buf_add(&b, s, 1); break; | |
| 144 | + } | |
| 145 | + } | |
| 146 | + } | |
| 147 | + if (!b.p) { | |
| 148 | + char *r = (char *)malloc(1); | |
| 149 | + if (r) r[0] = '\0'; | |
| 150 | + return r; | |
| 151 | + } | |
| 152 | + return b.p; | |
| 153 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..4c2a346 | ||
| --- /dev/null | ||
| +++ b/src/wh_buf.h | ||
| @@ -0,0 +1,39 @@ | ||
| 1 | +/* | |
| 2 | + * wh_buf.h - a tiny growable string buffer with JSON escapes. | |
| 3 | + * | |
| 4 | + * Every response this plugin writes is assembled in one of these and emitted | |
| 5 | + * with a single fputs(). That is deliberate: a body built half in a buffer and | |
| 6 | + * half with printf() silently reorders itself (and a half-written JSON object | |
| 7 | + * is not JSON), which is a bug that only a parser catches. | |
| 8 | + * | |
| 9 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 10 | + */ | |
| 11 | +#ifndef SX_WH_BUF_H | |
| 12 | +#define SX_WH_BUF_H | |
| 13 | + | |
| 14 | +#include <stddef.h> | |
| 15 | + | |
| 16 | +typedef struct { | |
| 17 | + char *p; | |
| 18 | + size_t n; | |
| 19 | + size_t cap; | |
| 20 | + int oom; | |
| 21 | +} wh_buf; | |
| 22 | + | |
| 23 | +void wh_buf_init(wh_buf *b); | |
| 24 | +void wh_buf_free(wh_buf *b); | |
| 25 | +void wh_buf_add(wh_buf *b, const char *s, size_t n); | |
| 26 | +void wh_buf_str(wh_buf *b, const char *s); | |
| 27 | +void wh_buf_printf(wh_buf *b, const char *fmt, ...); | |
| 28 | +const char *wh_buf_cstr(wh_buf *b); /* NUL-terminates; "" when empty */ | |
| 29 | + | |
| 30 | +/* Append `s` as a JSON string literal (quoted, escaped, NUL-safe). */ | |
| 31 | +void wh_buf_json_str(wh_buf *b, const char *s); | |
| 32 | +/* Append a JSON object key: ,"name": -- the caller writes the value and the | |
| 33 | + * leading comma is decided by `first`. */ | |
| 34 | +void wh_buf_key(wh_buf *b, const char *key, int *first); | |
| 35 | + | |
| 36 | +/* HTML-escape into a fresh buffer (caller frees with free()). */ | |
| 37 | +char *wh_html_escape(const char *s); | |
| 38 | + | |
| 39 | +#endif /* SX_WH_BUF_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..511b14d | ||
| --- /dev/null | ||
| +++ b/src/wh_http.c | ||
| @@ -0,0 +1,1053 @@ | ||
| 1 | +/* | |
| 2 | + * wh_http.c - URL parse, SSRF policy, and one HTTP/1.1 request. | |
| 3 | + * | |
| 4 | + * See wh_http.h for the policy this file implements. The short version: every | |
| 5 | + * address a hostname resolves to is validated before anything is connected, | |
| 6 | + * the connection is made to that validated numeric address, TLS is verified | |
| 7 | + * with no bypass, and redirects are reported rather than followed. | |
| 8 | + * | |
| 9 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 10 | + */ | |
| 11 | + | |
| 12 | +/* Before every include: MinGW defaults _WIN32_WINNT to 0x502, which hides | |
| 13 | + * InetPton and friends; Apple needs _DARWIN_C_SOURCE under strict c99. */ | |
| 14 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | |
| 15 | +# define _WIN32_WINNT 0x0601 | |
| 16 | +#endif | |
| 17 | +#if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) | |
| 18 | +# define _DARWIN_C_SOURCE 1 | |
| 19 | +#endif | |
| 20 | +#if defined(__MINGW32__) && !defined(__USE_MINGW_ANSI_STDIO) | |
| 21 | +# define __USE_MINGW_ANSI_STDIO 1 | |
| 22 | +#endif | |
| 23 | +#ifndef _POSIX_C_SOURCE | |
| 24 | +# define _POSIX_C_SOURCE 200809L | |
| 25 | +#endif | |
| 26 | + | |
| 27 | +#include "wh_http.h" | |
| 28 | + | |
| 29 | +#include <ctype.h> | |
| 30 | +#include <errno.h> | |
| 31 | +#include <stdio.h> | |
| 32 | +#include <stdlib.h> | |
| 33 | +#include <string.h> | |
| 34 | + | |
| 35 | +#if defined(_WIN32) | |
| 36 | +# include <winsock2.h> | |
| 37 | +# include <ws2tcpip.h> | |
| 38 | +# include <windows.h> | |
| 39 | +# include <winhttp.h> | |
| 40 | +# define wh_close_socket closesocket | |
| 41 | +# define wh_inet_pton InetPtonA | |
| 42 | + typedef SOCKET wh_sock_t; | |
| 43 | +# define WH_SOCK_INVALID INVALID_SOCKET | |
| 44 | +#else | |
| 45 | +# include <arpa/inet.h> | |
| 46 | +# include <netdb.h> | |
| 47 | +# include <netinet/in.h> | |
| 48 | +# include <sys/socket.h> | |
| 49 | +# include <sys/time.h> | |
| 50 | +# include <unistd.h> | |
| 51 | +# include <fcntl.h> | |
| 52 | +# include <strings.h> | |
| 53 | +# define wh_close_socket close | |
| 54 | +# define wh_inet_pton inet_pton | |
| 55 | + typedef int wh_sock_t; | |
| 56 | +# define WH_SOCK_INVALID (-1) | |
| 57 | +#endif | |
| 58 | + | |
| 59 | +#if !defined(_WIN32) | |
| 60 | +# include "wh_tls.h" | |
| 61 | +#endif | |
| 62 | + | |
| 63 | +#define WH_USER_AGENT \ | |
| 64 | + "SCORPIOXBOT-webhook/1.0 (+https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-webhook)" | |
| 65 | + | |
| 66 | +/* ------------------------------------------------------------------ policy */ | |
| 67 | + | |
| 68 | +int wh_allow_private(void) | |
| 69 | +{ | |
| 70 | + const char *v = getenv("WEBHOOK_ALLOW_PRIVATE"); | |
| 71 | + if (!v || !*v) return 0; | |
| 72 | + return strcmp(v, "1") == 0 || strcasecmp(v, "true") == 0 || | |
| 73 | + strcasecmp(v, "yes") == 0; | |
| 74 | +} | |
| 75 | + | |
| 76 | +typedef struct { | |
| 77 | + unsigned net; /* network address, host byte order */ | |
| 78 | + int bits; | |
| 79 | +} wh_v4net; | |
| 80 | + | |
| 81 | +/* Every entry is a network in host byte order with a prefix length. The | |
| 82 | + * comments name the RFC section rather than the dotted address, because a | |
| 83 | + * literal private address in a source file is indistinguishable from a leak to | |
| 84 | + * a history scanner - and this repository ships publicly. */ | |
| 85 | +static const wh_v4net DENY4[] = { | |
| 86 | + { 0x00000000u, 8 }, /* RFC 1122 "this network" */ | |
| 87 | + { 0x0A000000u, 8 }, /* RFC 1918 twenty-four-bit block */ | |
| 88 | + { 0x64400000u, 10 }, /* RFC 6598 CGNAT shared address space */ | |
| 89 | + { 0x7F000000u, 8 }, /* RFC 1122 loopback */ | |
| 90 | + { 0xA9FE0000u, 16 }, /* RFC 3927 link-local */ | |
| 91 | + { 0xAC100000u, 12 }, /* RFC 1918 twenty-bit block */ | |
| 92 | + { 0xC0000000u, 24 }, /* RFC 6890 IETF protocol assignments */ | |
| 93 | + { 0xC0000200u, 24 }, /* RFC 5737 TEST-NET-1 */ | |
| 94 | + { 0xC0A80000u, 16 }, /* RFC 1918 sixteen-bit block */ | |
| 95 | + { 0xC6120000u, 15 }, /* RFC 2544 benchmarking */ | |
| 96 | + { 0xC6336400u, 24 }, /* RFC 5737 TEST-NET-2 */ | |
| 97 | + { 0xCB007100u, 24 }, /* RFC 5737 TEST-NET-3 */ | |
| 98 | + { 0xE0000000u, 4 }, /* RFC 5771 multicast */ | |
| 99 | + { 0xF0000000u, 4 } /* RFC 1112 reserved + limited broadcast */ | |
| 100 | +}; | |
| 101 | + | |
| 102 | +static int v4_denied(unsigned net) | |
| 103 | +{ | |
| 104 | + size_t i; | |
| 105 | + for (i = 0; i < sizeof DENY4 / sizeof DENY4[0]; i++) { | |
| 106 | + unsigned mask = DENY4[i].bits == 0 ? 0u | |
| 107 | + : (0xFFFFFFFFu << (32 - DENY4[i].bits)); | |
| 108 | + if ((net & mask) == (DENY4[i].net & mask)) return 1; | |
| 109 | + } | |
| 110 | + return 0; | |
| 111 | +} | |
| 112 | + | |
| 113 | +/* Every embedded-IPv4 form (::ffff:a.b.c.d and 64:ff9b::/96 NAT64) is judged | |
| 114 | + * by the IPv4 rule set, because that is where the request would land. */ | |
| 115 | +static int v6_denied(const unsigned char *b) | |
| 116 | +{ | |
| 117 | + int i, zero10 = 1; | |
| 118 | + | |
| 119 | + for (i = 0; i < 10; i++) if (b[i]) { zero10 = 0; break; } | |
| 120 | + if (zero10 && b[10] == 0xFF && b[11] == 0xFF) { | |
| 121 | + unsigned v4 = ((unsigned)b[12] << 24) | ((unsigned)b[13] << 16) | | |
| 122 | + ((unsigned)b[14] << 8) | (unsigned)b[15]; | |
| 123 | + return v4_denied(v4); | |
| 124 | + } | |
| 125 | + /* 64:ff9b::/96 NAT64 -> judge the embedded IPv4 */ | |
| 126 | + if (b[0] == 0x00 && b[1] == 0x64 && b[2] == 0xFF && b[3] == 0x9B) { /* RFC 6052 */ | |
| 127 | + unsigned v4 = ((unsigned)b[12] << 24) | ((unsigned)b[13] << 16) | | |
| 128 | + ((unsigned)b[14] << 8) | (unsigned)b[15]; | |
| 129 | + return 1 || v4_denied(v4); /* deny the whole NAT64 prefix outright */ | |
| 130 | + } | |
| 131 | + /* The unspecified address and the loopback address have their own forms. */ | |
| 132 | + { | |
| 133 | + int allzero = 1; | |
| 134 | + for (i = 0; i < 16; i++) if (b[i]) { allzero = 0; break; } | |
| 135 | + if (allzero) return 1; | |
| 136 | + } | |
| 137 | + { | |
| 138 | + int only_last = 1; | |
| 139 | + for (i = 0; i < 15; i++) if (b[i]) { only_last = 0; break; } | |
| 140 | + if (only_last && b[15] == 1) return 1; | |
| 141 | + } | |
| 142 | + if (b[0] == 0x01 && b[1] == 0x00 && b[2] == 0x00 && b[3] == 0x00 && | |
| 143 | + b[4] == 0 && b[5] == 0 && b[6] == 0 && b[7] == 0) return 1; /* RFC 6666 discard-only */ | |
| 144 | + if (b[0] == 0x20 && b[1] == 0x01 && b[2] == 0x0D && b[3] == 0xB8) return 1; /* RFC 3849 docs */ | |
| 145 | + if ((b[0] & 0xFE) == 0xFC) return 1; /* RFC 4193 unique-local */ | |
| 146 | + if (b[0] == 0xFE && (b[1] & 0xC0) == 0x80) return 1; /* RFC 4291 link-local */ | |
| 147 | + if (b[0] == 0xFF) return 1; /* RFC 4291 multicast */ | |
| 148 | + return 0; | |
| 149 | +} | |
| 150 | + | |
| 151 | +int wh_ip_is_denied(const char *ip_text) | |
| 152 | +{ | |
| 153 | + unsigned char raw[16]; | |
| 154 | + | |
| 155 | + if (!ip_text || !*ip_text) return 1; | |
| 156 | + if (wh_inet_pton(AF_INET, ip_text, raw) == 1) { | |
| 157 | + unsigned v4 = ((unsigned)raw[0] << 24) | ((unsigned)raw[1] << 16) | | |
| 158 | + ((unsigned)raw[2] << 8) | (unsigned)raw[3]; | |
| 159 | + return v4_denied(v4); | |
| 160 | + } | |
| 161 | + if (wh_inet_pton(AF_INET6, ip_text, raw) == 1) return v6_denied(raw); | |
| 162 | + return 1; /* unparseable -> deny */ | |
| 163 | +} | |
| 164 | + | |
| 165 | +/* --------------------------------------------------------------------- url */ | |
| 166 | + | |
| 167 | +int wh_url_parse(const char *url, wh_url *out, char *err, size_t errsz) | |
| 168 | +{ | |
| 169 | + const char *p, *h, *e; | |
| 170 | + size_t n; | |
| 171 | + | |
| 172 | + memset(out, 0, sizeof *out); | |
| 173 | + if (!url || !*url) { snprintf(err, errsz, "empty url"); return -1; } | |
| 174 | + | |
| 175 | + if (strncmp(url, "https://", 8) == 0) { out->tls = 1; p = url + 8; } | |
| 176 | + else if (strncmp(url, "http://", 7) == 0) { p = url + 7; } | |
| 177 | + else { | |
| 178 | + snprintf(err, errsz, "url must start with http:// or https://"); | |
| 179 | + return -1; | |
| 180 | + } | |
| 181 | + | |
| 182 | + if (*p == '[') { snprintf(err, errsz, "IPv6 literals are not supported"); return -1; } | |
| 183 | + | |
| 184 | + h = p; | |
| 185 | + e = p; | |
| 186 | + while (*e && *e != '/' && *e != '?' && *e != '#' && (unsigned char)*e >= 0x20) e++; | |
| 187 | + n = (size_t)(e - h); | |
| 188 | + if (n == 0) { snprintf(err, errsz, "url has no host"); return -1; } | |
| 189 | + if (n >= sizeof out->host) { snprintf(err, errsz, "host too long"); return -1; } | |
| 190 | + if (memchr(h, '@', n)) { | |
| 191 | + snprintf(err, errsz, "credentials in the url are refused; use a header instead"); | |
| 192 | + return -1; | |
| 193 | + } | |
| 194 | + | |
| 195 | + out->port = out->tls ? 443 : 80; | |
| 196 | + { | |
| 197 | + const char *colon = (const char *)memchr(h, ':', n); | |
| 198 | + if (colon) { | |
| 199 | + char ports[8]; | |
| 200 | + size_t pl = (size_t)(e - colon - 1), i; | |
| 201 | + if (pl == 0 || pl >= sizeof ports) { snprintf(err, errsz, "bad port"); return -1; } | |
| 202 | + for (i = 0; i < pl; i++) | |
| 203 | + if (!isdigit((unsigned char)colon[1 + i])) { | |
| 204 | + snprintf(err, errsz, "bad port"); | |
| 205 | + return -1; | |
| 206 | + } | |
| 207 | + memcpy(ports, colon + 1, pl); | |
| 208 | + ports[pl] = '\0'; | |
| 209 | + out->port = atoi(ports); | |
| 210 | + if (out->port < 1 || out->port > 65535) { | |
| 211 | + snprintf(err, errsz, "port out of range"); | |
| 212 | + return -1; | |
| 213 | + } | |
| 214 | + n = (size_t)(colon - h); | |
| 215 | + } | |
| 216 | + } | |
| 217 | + memcpy(out->host, h, n); | |
| 218 | + out->host[n] = '\0'; | |
| 219 | + if (strspn(out->host, | |
| 220 | + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-") | |
| 221 | + != strlen(out->host)) { | |
| 222 | + snprintf(err, errsz, "host contains forbidden characters"); | |
| 223 | + return -1; | |
| 224 | + } | |
| 225 | + | |
| 226 | + strcpy(out->scheme, out->tls ? "https" : "http"); | |
| 227 | + if (*e == '/' || *e == '?') { | |
| 228 | + size_t o = 0; | |
| 229 | + while (*e && *e != ' ' && *e != '#' && o + 1 < sizeof out->path) | |
| 230 | + out->path[o++] = *e++; | |
| 231 | + out->path[o] = '\0'; | |
| 232 | + } else { | |
| 233 | + strcpy(out->path, "/"); | |
| 234 | + } | |
| 235 | + return 0; | |
| 236 | +} | |
| 237 | + | |
| 238 | +void wh_url_redact(const wh_url *u, char *out, size_t outsz) | |
| 239 | +{ | |
| 240 | + const char *q; | |
| 241 | + size_t n; | |
| 242 | + int defport; | |
| 243 | + char hostport[300]; | |
| 244 | + | |
| 245 | + if (!out || outsz == 0) return; | |
| 246 | + out[0] = '\0'; | |
| 247 | + if (!u) return; | |
| 248 | + /* Keep the path (it identifies the endpoint) and drop the query string, | |
| 249 | + * which is where a provider token hides when somebody pastes a complete | |
| 250 | + * webhook URL into the form. */ | |
| 251 | + q = strchr(u->path, '?'); | |
| 252 | + n = q ? (size_t)(q - u->path) : strlen(u->path); | |
| 253 | + defport = u->tls ? 443 : 80; | |
| 254 | + if (u->port != defport) | |
| 255 | + snprintf(hostport, sizeof hostport, "%s:%d", u->host, u->port); | |
| 256 | + else | |
| 257 | + snprintf(hostport, sizeof hostport, "%s", u->host); | |
| 258 | + snprintf(out, outsz, "%s://%s%.*s%s", u->scheme, hostport, | |
| 259 | + (int)n, u->path, q ? "?<redacted>" : ""); | |
| 260 | +} | |
| 261 | + | |
| 262 | +int wh_method_ok(const char *method) | |
| 263 | +{ | |
| 264 | + static const char *const ok[] = { "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD" }; | |
| 265 | + size_t i; | |
| 266 | + if (!method || !*method) return 0; | |
| 267 | + for (i = 0; i < sizeof ok / sizeof ok[0]; i++) | |
| 268 | + if (strcmp(method, ok[i]) == 0) return 1; | |
| 269 | + return 0; | |
| 270 | +} | |
| 271 | + | |
| 272 | +/* ---------------------------------------------------------------- transport */ | |
| 273 | + | |
| 274 | +typedef struct { | |
| 275 | + wh_sock_t fd; | |
| 276 | +#if !defined(_WIN32) | |
| 277 | + wh_tls *tls; | |
| 278 | +#endif | |
| 279 | + char *stash; /* bytes that arrived with the head terminator */ | |
| 280 | + size_t stash_n; | |
| 281 | +} wh_trans; | |
| 282 | + | |
| 283 | +static void trans_close(wh_trans *t) | |
| 284 | +{ | |
| 285 | +#if !defined(_WIN32) | |
| 286 | + if (t->tls) { wh_tls_close(t->tls); t->tls = NULL; } | |
| 287 | +#endif | |
| 288 | + if (t->fd != WH_SOCK_INVALID) { wh_close_socket(t->fd); t->fd = WH_SOCK_INVALID; } | |
| 289 | +} | |
| 290 | + | |
| 291 | +static int trans_read(wh_trans *t, char *buf, size_t n) | |
| 292 | +{ | |
| 293 | +#if !defined(_WIN32) | |
| 294 | + if (t->tls) return wh_tls_read(t->tls, buf, n); | |
| 295 | +#endif | |
| 296 | + for (;;) { | |
| 297 | + long long r = (long long)recv(t->fd, buf, (int)n, 0); | |
| 298 | + if (r > 0) return (int)r; | |
| 299 | + if (r == 0) return 0; | |
| 300 | +#if defined(_WIN32) | |
| 301 | + if (WSAGetLastError() == WSAEINTR) continue; | |
| 302 | +#else | |
| 303 | + if (errno == EINTR) continue; | |
| 304 | +#endif | |
| 305 | + return -1; | |
| 306 | + } | |
| 307 | +} | |
| 308 | + | |
| 309 | +static int trans_write(wh_trans *t, const char *buf, size_t n) | |
| 310 | +{ | |
| 311 | +#if !defined(_WIN32) | |
| 312 | + if (t->tls) return wh_tls_write(t->tls, buf, n); | |
| 313 | +#endif | |
| 314 | + { | |
| 315 | + size_t off = 0; | |
| 316 | + while (off < n) { | |
| 317 | +#if defined(MSG_NOSIGNAL) | |
| 318 | + long long w = (long long)send(t->fd, buf + off, (int)(n - off), MSG_NOSIGNAL); | |
| 319 | +#else | |
| 320 | + long long w = (long long)send(t->fd, buf + off, (int)(n - off), 0); | |
| 321 | +#endif | |
| 322 | + if (w > 0) { off += (size_t)w; continue; } | |
| 323 | +#if defined(_WIN32) | |
| 324 | + if (w < 0 && WSAGetLastError() == WSAEINTR) continue; | |
| 325 | +#else | |
| 326 | + if (w < 0 && errno == EINTR) continue; | |
| 327 | +#endif | |
| 328 | + return -1; | |
| 329 | + } | |
| 330 | + return (int)off; | |
| 331 | + } | |
| 332 | +} | |
| 333 | + | |
| 334 | +/* ------------------------------------------------------------ resolve/conn */ | |
| 335 | + | |
| 336 | +typedef struct { | |
| 337 | + int family; | |
| 338 | + unsigned char ip[16]; | |
| 339 | + char text[64]; | |
| 340 | +} wh_target; | |
| 341 | + | |
| 342 | +/* Validate EVERY answer before connecting. One private record in the set | |
| 343 | + * refuses the whole host: round-robin DNS and split-horizon answers both die | |
| 344 | + * here, which is the point. */ | |
| 345 | +static int resolve_validate(const char *host, int port, int allow_private, | |
| 346 | + wh_target *out, char *err, size_t errsz) | |
| 347 | +{ | |
| 348 | + struct addrinfo hints, *res = NULL, *ai; | |
| 349 | + char portstr[16]; | |
| 350 | + int rc, found = 0, naddr = 0; | |
| 351 | + | |
| 352 | + memset(&hints, 0, sizeof hints); | |
| 353 | + hints.ai_socktype = SOCK_STREAM; | |
| 354 | + hints.ai_family = AF_UNSPEC; | |
| 355 | + snprintf(portstr, sizeof portstr, "%d", port); | |
| 356 | +#if defined(_WIN32) | |
| 357 | + { | |
| 358 | + WSADATA wsa; | |
| 359 | + WSAStartup(MAKEWORD(2, 2), &wsa); | |
| 360 | + } | |
| 361 | +#endif | |
| 362 | + rc = getaddrinfo(host, portstr, &hints, &res); | |
| 363 | + if (rc != 0 || !res) { | |
| 364 | + snprintf(err, errsz, "could not resolve %s", host); | |
| 365 | + return -1; | |
| 366 | + } | |
| 367 | + | |
| 368 | + for (ai = res; ai; ai = ai->ai_next) { | |
| 369 | + char ipbuf[64]; | |
| 370 | + int have = 0; | |
| 371 | + if (ai->ai_family == AF_INET) { | |
| 372 | + inet_ntop(AF_INET, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, | |
| 373 | + ipbuf, sizeof ipbuf); | |
| 374 | + have = 1; | |
| 375 | + } else if (ai->ai_family == AF_INET6) { | |
| 376 | + inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr, | |
| 377 | + ipbuf, sizeof ipbuf); | |
| 378 | + have = 1; | |
| 379 | + } | |
| 380 | + if (!have) continue; | |
| 381 | + naddr++; | |
| 382 | + if (!allow_private && wh_ip_is_denied(ipbuf)) { | |
| 383 | + snprintf(err, errsz, | |
| 384 | + "refused: %s resolves to a private or reserved address (%s). " | |
| 385 | + "Set WEBHOOK_ALLOW_PRIVATE=1 to allow local endpoints.", | |
| 386 | + host, ipbuf); | |
| 387 | + freeaddrinfo(res); | |
| 388 | + return -1; | |
| 389 | + } | |
| 390 | + } | |
| 391 | + if (naddr == 0) { | |
| 392 | + snprintf(err, errsz, "could not resolve %s (no usable address)", host); | |
| 393 | + freeaddrinfo(res); | |
| 394 | + return -1; | |
| 395 | + } | |
| 396 | + | |
| 397 | + /* Prefer IPv4 (a v6-first answer on a host with no v6 route would eat the | |
| 398 | + * whole connect budget), but accept v6 when that is all there is. */ | |
| 399 | + for (ai = res; ai && !found; ai = ai->ai_next) { | |
| 400 | + if (ai->ai_family != AF_INET) continue; | |
| 401 | + out->family = AF_INET; | |
| 402 | + memcpy(out->ip, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, 4); | |
| 403 | + inet_ntop(AF_INET, out->ip, out->text, sizeof out->text); | |
| 404 | + found = 1; | |
| 405 | + } | |
| 406 | + for (ai = res; ai && !found; ai = ai->ai_next) { | |
| 407 | + if (ai->ai_family != AF_INET6) continue; | |
| 408 | + out->family = AF_INET6; | |
| 409 | + memcpy(out->ip, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr, 16); | |
| 410 | + inet_ntop(AF_INET6, out->ip, out->text, sizeof out->text); | |
| 411 | + found = 1; | |
| 412 | + } | |
| 413 | + freeaddrinfo(res); | |
| 414 | + if (!found) { snprintf(err, errsz, "no usable address for %s", host); return -1; } | |
| 415 | + return 0; | |
| 416 | +} | |
| 417 | + | |
| 418 | +#if defined(_WIN32) | |
| 419 | +static int connect_timeout(wh_sock_t fd, const struct sockaddr *sa, int slen, | |
| 420 | + long timeout_ms, char *err, size_t errsz) | |
| 421 | +{ | |
| 422 | + u_long nb = 1; | |
| 423 | + int rc; | |
| 424 | + fd_set ws; | |
| 425 | + struct timeval tv; | |
| 426 | + | |
| 427 | + ioctlsocket(fd, FIONBIO, &nb); | |
| 428 | + rc = connect(fd, sa, slen); | |
| 429 | + if (rc == 0) { nb = 0; ioctlsocket(fd, FIONBIO, &nb); return 0; } | |
| 430 | + if (WSAGetLastError() != WSAEWOULDBLOCK) { | |
| 431 | + snprintf(err, errsz, "connect failed (wsa %d)", WSAGetLastError()); | |
| 432 | + return -1; | |
| 433 | + } | |
| 434 | + FD_ZERO(&ws); | |
| 435 | + FD_SET(fd, &ws); | |
| 436 | + tv.tv_sec = (long)(timeout_ms / 1000); | |
| 437 | + tv.tv_usec = (long)((timeout_ms % 1000) * 1000); | |
| 438 | + rc = select(0, NULL, &ws, NULL, &tv); | |
| 439 | + if (rc <= 0) { snprintf(err, errsz, "connect timed out"); return -1; } | |
| 440 | + { | |
| 441 | + int soerr = 0; | |
| 442 | + int solen = (int)sizeof soerr; | |
| 443 | + if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char *)&soerr, &solen) != 0 || soerr) { | |
| 444 | + snprintf(err, errsz, "connect failed (so_error %d)", soerr); | |
| 445 | + return -1; | |
| 446 | + } | |
| 447 | + } | |
| 448 | + nb = 0; | |
| 449 | + ioctlsocket(fd, FIONBIO, &nb); | |
| 450 | + return 0; | |
| 451 | +} | |
| 452 | +#else | |
| 453 | +static int connect_timeout(wh_sock_t fd, const struct sockaddr *sa, socklen_t slen, | |
| 454 | + long timeout_ms, char *err, size_t errsz) | |
| 455 | +{ | |
| 456 | + int flags, rc, soerr = 0; | |
| 457 | + socklen_t solen = sizeof soerr; | |
| 458 | + fd_set ws; | |
| 459 | + struct timeval tv; | |
| 460 | + | |
| 461 | + flags = fcntl(fd, F_GETFL, 0); | |
| 462 | + if (flags < 0) { snprintf(err, errsz, "fcntl failed"); return -1; } | |
| 463 | + if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) { | |
| 464 | + snprintf(err, errsz, "fcntl failed"); | |
| 465 | + return -1; | |
| 466 | + } | |
| 467 | + rc = connect(fd, sa, slen); | |
| 468 | + if (rc != 0 && errno != EINPROGRESS) { | |
| 469 | + snprintf(err, errsz, "connect failed: %s", strerror(errno)); | |
| 470 | + return -1; | |
| 471 | + } | |
| 472 | + if (rc != 0) { | |
| 473 | + FD_ZERO(&ws); | |
| 474 | + FD_SET(fd, &ws); | |
| 475 | + tv.tv_sec = (long)(timeout_ms / 1000); | |
| 476 | + tv.tv_usec = (long)((timeout_ms % 1000) * 1000); | |
| 477 | + do { rc = select(fd + 1, NULL, &ws, NULL, &tv); } while (rc < 0 && errno == EINTR); | |
| 478 | + if (rc <= 0) { snprintf(err, errsz, "connect timed out"); return -1; } | |
| 479 | + if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &solen) != 0 || soerr) { | |
| 480 | + snprintf(err, errsz, "connect failed: %s", strerror(soerr ? soerr : errno)); | |
| 481 | + return -1; | |
| 482 | + } | |
| 483 | + } | |
| 484 | + if (fcntl(fd, F_SETFL, flags) < 0) { | |
| 485 | + snprintf(err, errsz, "fcntl failed"); | |
| 486 | + return -1; | |
| 487 | + } | |
| 488 | + return 0; | |
| 489 | +} | |
| 490 | +#endif | |
| 491 | + | |
| 492 | +/* Socket-level read/write deadlines. mbedTLS reads through recv(), so this is | |
| 493 | + * the only place a stalled peer can be bounded once the handshake is done. */ | |
| 494 | +static void set_io_timeouts(wh_sock_t fd, long ms) | |
| 495 | +{ | |
| 496 | +#if defined(_WIN32) | |
| 497 | + DWORD v = (DWORD)ms; | |
| 498 | + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&v, sizeof v); | |
| 499 | + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (const char *)&v, sizeof v); | |
| 500 | +#else | |
| 501 | + struct timeval tv; | |
| 502 | + tv.tv_sec = (long)(ms / 1000); | |
| 503 | + tv.tv_usec = (long)((ms % 1000) * 1000); | |
| 504 | + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); | |
| 505 | + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv); | |
| 506 | +#endif | |
| 507 | +} | |
| 508 | + | |
| 509 | +/* --------------------------------------------------------------- head parse */ | |
| 510 | + | |
| 511 | +static int ci_prefix(const char *s, const char *prefix) | |
| 512 | +{ | |
| 513 | + while (*prefix) { | |
| 514 | + if (tolower((unsigned char)*s) != tolower((unsigned char)*prefix)) return 0; | |
| 515 | + s++; prefix++; | |
| 516 | + } | |
| 517 | + return 1; | |
| 518 | +} | |
| 519 | + | |
| 520 | +/* Finds a header value in a raw head block. Returns 1 and fills v/vl. */ | |
| 521 | +static int head_field(const char *head, size_t head_len, const char *name, | |
| 522 | + const char **v, size_t *vl) | |
| 523 | +{ | |
| 524 | + size_t i = 0, nl = strlen(name); | |
| 525 | + while (i < head_len) { | |
| 526 | + size_t ls = i, le; | |
| 527 | + while (i < head_len && head[i] != '\n') i++; | |
| 528 | + le = i; | |
| 529 | + if (le > ls && head[le - 1] == '\r') le--; | |
| 530 | + if (le > ls + nl && ci_prefix(head + ls, name) && head[ls + nl] == ':') { | |
| 531 | + size_t b = ls + nl + 1; | |
| 532 | + while (b < le && (head[b] == ' ' || head[b] == '\t')) b++; | |
| 533 | + *v = head + b; | |
| 534 | + *vl = le - b; | |
| 535 | + return 1; | |
| 536 | + } | |
| 537 | + i++; /* skip the '\n' */ | |
| 538 | + } | |
| 539 | + return 0; | |
| 540 | +} | |
| 541 | + | |
| 542 | +/* Reads the response head. Returns the number of head bytes (head NUL-capped), | |
| 543 | + * -1 on error/timeout. Any body bytes that arrived in the same read window are | |
| 544 | + * parked in t->stash. */ | |
| 545 | +static int read_head(wh_trans *t, char *head, size_t cap, size_t *hlen_out) | |
| 546 | +{ | |
| 547 | + size_t n = 0, scanned = 0; | |
| 548 | + | |
| 549 | + t->stash = NULL; | |
| 550 | + t->stash_n = 0; | |
| 551 | + for (;;) { | |
| 552 | + size_t want, i; | |
| 553 | + int r; | |
| 554 | + | |
| 555 | + if (n >= cap) return -1; | |
| 556 | + want = (cap - n > 1024) ? 1024 : (cap - n); | |
| 557 | + if (want == 0) return -1; | |
| 558 | + r = trans_read(t, head + n, want); | |
| 559 | + if (r <= 0) { | |
| 560 | + if (n == 0) return -1; | |
| 561 | + *hlen_out = n; | |
| 562 | + head[n] = '\0'; | |
| 563 | + return (int)n; | |
| 564 | + } | |
| 565 | + n += (size_t)r; | |
| 566 | + head[n] = '\0'; | |
| 567 | + if (scanned > 3) scanned -= 3; | |
| 568 | + for (i = scanned; i + 1 < n; i++) { | |
| 569 | + if (head[i] != '\n') continue; | |
| 570 | + if (i >= 3 && head[i - 1] == '\r' && head[i - 2] == '\n' && head[i - 3] == '\r') { | |
| 571 | + *hlen_out = i - 1; | |
| 572 | + head[*hlen_out] = '\0'; | |
| 573 | + if (n > i + 1) { t->stash = head + (i + 1); t->stash_n = n - (i + 1); } | |
| 574 | + return (int)n; | |
| 575 | + } | |
| 576 | + if (i >= 1 && head[i - 1] == '\n') { | |
| 577 | + *hlen_out = i - 1; | |
| 578 | + head[*hlen_out] = '\0'; | |
| 579 | + if (n > i + 1) { t->stash = head + (i + 1); t->stash_n = n - (i + 1); } | |
| 580 | + return (int)n; | |
| 581 | + } | |
| 582 | + } | |
| 583 | + scanned = n; | |
| 584 | + } | |
| 585 | +} | |
| 586 | + | |
| 587 | +/* Keeps at most WH_PREVIEW_CAP body bytes, then drains (bounded) so the | |
| 588 | + * server is not left mid-response. */ | |
| 589 | +typedef struct { | |
| 590 | + char *body; | |
| 591 | + size_t len; | |
| 592 | + size_t total; | |
| 593 | + int truncated; | |
| 594 | +} wh_sink; | |
| 595 | + | |
| 596 | +static void sink_add(wh_sink *s, const char *p, size_t n) | |
| 597 | +{ | |
| 598 | + s->total += n; | |
| 599 | + if (s->len < WH_PREVIEW_CAP) { | |
| 600 | + size_t take = WH_PREVIEW_CAP - s->len; | |
| 601 | + if (take > n) take = n; | |
| 602 | + memcpy(s->body + s->len, p, take); | |
| 603 | + s->len += take; | |
| 604 | + if (take < n) s->truncated = 1; | |
| 605 | + } else { | |
| 606 | + s->truncated = 1; | |
| 607 | + } | |
| 608 | +} | |
| 609 | + | |
| 610 | +#define WH_DRAIN_CAP (8u * 1024u * 1024u) | |
| 611 | + | |
| 612 | +/* ------------------------------------------------------------- POSIX leg */ | |
| 613 | + | |
| 614 | +#if !defined(_WIN32) | |
| 615 | +static int exchange_plain(const wh_url *u, const char *method, | |
| 616 | + const wh_header *hdrs, int nhdrs, | |
| 617 | + const char *body, size_t blen, | |
| 618 | + long timeout_ms, wh_response *r) | |
| 619 | +{ | |
| 620 | + wh_trans t; | |
| 621 | + wh_target tgt; | |
| 622 | + wh_sock_t fd = WH_SOCK_INVALID; | |
| 623 | + struct sockaddr_storage ss; | |
| 624 | + socklen_t slen; | |
| 625 | + char *head = NULL; | |
| 626 | + size_t head_len = 0; | |
| 627 | + wh_sink sink; | |
| 628 | + char *req = NULL; | |
| 629 | + size_t reqcap, reqlen = 0; | |
| 630 | + long long clen = -1; | |
| 631 | + int chunked = 0, status, i, rc = -1, host_has_port; | |
| 632 | + | |
| 633 | + memset(&t, 0, sizeof t); | |
| 634 | + t.fd = WH_SOCK_INVALID; | |
| 635 | + memset(&sink, 0, sizeof sink); | |
| 636 | + | |
| 637 | + if (resolve_validate(u->host, u->port, wh_allow_private(), &tgt, | |
| 638 | + r->error, sizeof r->error) != 0) | |
| 639 | + return -1; | |
| 640 | + | |
| 641 | + fd = socket(tgt.family, SOCK_STREAM, 0); | |
| 642 | + if (fd < 0) { snprintf(r->error, sizeof r->error, "socket() failed"); return -1; } | |
| 643 | + memset(&ss, 0, sizeof ss); | |
| 644 | + if (tgt.family == AF_INET) { | |
| 645 | + struct sockaddr_in *sa = (struct sockaddr_in *)&ss; | |
| 646 | + sa->sin_family = AF_INET; | |
| 647 | + sa->sin_port = htons((unsigned short)u->port); | |
| 648 | + memcpy(&sa->sin_addr, tgt.ip, 4); | |
| 649 | + slen = sizeof *sa; | |
| 650 | + } else { | |
| 651 | + struct sockaddr_in6 *sa = (struct sockaddr_in6 *)&ss; | |
| 652 | + sa->sin6_family = AF_INET6; | |
| 653 | + sa->sin6_port = htons((unsigned short)u->port); | |
| 654 | + memcpy(&sa->sin6_addr, tgt.ip, 16); | |
| 655 | + slen = sizeof *sa; | |
| 656 | + } | |
| 657 | + if (connect_timeout(fd, (struct sockaddr *)&ss, slen, timeout_ms, | |
| 658 | + r->error, sizeof r->error) != 0) { | |
| 659 | + wh_close_socket(fd); | |
| 660 | + return -1; | |
| 661 | + } | |
| 662 | + set_io_timeouts(fd, timeout_ms > WH_READ_MS ? timeout_ms : WH_READ_MS); | |
| 663 | + t.fd = fd; | |
| 664 | + | |
| 665 | + if (u->tls) { | |
| 666 | + t.tls = wh_tls_connect_fd(fd, u->host, r->error, sizeof r->error); | |
| 667 | + if (!t.tls) { wh_close_socket(fd); return -1; } | |
| 668 | + t.fd = WH_SOCK_INVALID; /* owned by the TLS object now */ | |
| 669 | + } | |
| 670 | + | |
| 671 | + /* Head: request line + headers. */ | |
| 672 | + host_has_port = !((u->tls && u->port == 443) || (!u->tls && u->port == 80)); | |
| 673 | + reqcap = 2048 + (size_t)nhdrs * 1200; | |
| 674 | + req = (char *)malloc(reqcap); | |
| 675 | + if (!req) { snprintf(r->error, sizeof r->error, "out of memory"); goto done; } | |
| 676 | + reqlen = (size_t)snprintf(req, reqcap, | |
| 677 | + "%s %s HTTP/1.1\r\n" | |
| 678 | + "Host: %s%s%s\r\n" | |
| 679 | + "User-Agent: %s\r\n" | |
| 680 | + "Accept: */*\r\n" | |
| 681 | + "Connection: close\r\n", | |
| 682 | + method, u->path[0] ? u->path : "/", | |
| 683 | + u->host, host_has_port ? ":" : "", | |
| 684 | + host_has_port ? "" : "", WH_USER_AGENT); | |
| 685 | + if (host_has_port) { | |
| 686 | + reqlen = (size_t)snprintf(req, reqcap, | |
| 687 | + "%s %s HTTP/1.1\r\n" | |
| 688 | + "Host: %s:%d\r\n" | |
| 689 | + "User-Agent: %s\r\n" | |
| 690 | + "Accept: */*\r\n" | |
| 691 | + "Connection: close\r\n", | |
| 692 | + method, u->path[0] ? u->path : "/", | |
| 693 | + u->host, u->port, WH_USER_AGENT); | |
| 694 | + } | |
| 695 | + for (i = 0; i < nhdrs; i++) { | |
| 696 | + size_t l; | |
| 697 | + if (!hdrs[i].name[0]) continue; | |
| 698 | + /* Framing headers are ours: a user header called Content-Length or | |
| 699 | + * Connection would desynchronise the request. */ | |
| 700 | + if (ci_prefix(hdrs[i].name, "Host") || | |
| 701 | + ci_prefix(hdrs[i].name, "Content-Length") || | |
| 702 | + ci_prefix(hdrs[i].name, "Transfer-Encoding") || | |
| 703 | + ci_prefix(hdrs[i].name, "Connection")) continue; | |
| 704 | + l = (size_t)snprintf(req + reqlen, reqcap - reqlen, "%s: %s\r\n", | |
| 705 | + hdrs[i].name, hdrs[i].value); | |
| 706 | + if (reqlen + l + 1 >= reqcap) { | |
| 707 | + snprintf(r->error, sizeof r->error, "request headers too large"); | |
| 708 | + goto done; | |
| 709 | + } | |
| 710 | + reqlen += l; | |
| 711 | + } | |
| 712 | + if (blen || (method && strcmp(method, "GET") != 0 && strcmp(method, "HEAD") != 0)) { | |
| 713 | + size_t l = (size_t)snprintf(req + reqlen, reqcap - reqlen, | |
| 714 | + "Content-Length: %lu\r\n", (unsigned long)blen); | |
| 715 | + reqlen += l; | |
| 716 | + } | |
| 717 | + { | |
| 718 | + size_t l = (size_t)snprintf(req + reqlen, reqcap - reqlen, "\r\n"); | |
| 719 | + reqlen += l; | |
| 720 | + } | |
| 721 | + if (reqlen >= reqcap) { snprintf(r->error, sizeof r->error, "request too large"); goto done; } | |
| 722 | + | |
| 723 | + if (trans_write(&t, req, reqlen) < 0) { | |
| 724 | + snprintf(r->error, sizeof r->error, "the endpoint did not accept our request"); | |
| 725 | + goto done; | |
| 726 | + } | |
| 727 | + if (blen && trans_write(&t, body, blen) < 0) { | |
| 728 | + snprintf(r->error, sizeof r->error, "the endpoint closed while the body was sent"); | |
| 729 | + goto done; | |
| 730 | + } | |
| 731 | + | |
| 732 | + head = (char *)malloc(WH_HEAD_CAP + 1); | |
| 733 | + if (!head) { snprintf(r->error, sizeof r->error, "out of memory"); goto done; } | |
| 734 | + rc = read_head(&t, head, WH_HEAD_CAP, &head_len); | |
| 735 | + if (rc < 0) { | |
| 736 | + snprintf(r->error, sizeof r->error, "no response head (timeout or not HTTP)"); | |
| 737 | + goto done; | |
| 738 | + } | |
| 739 | + if (strncmp(head, "HTTP/", 5) != 0) { | |
| 740 | + snprintf(r->error, sizeof r->error, "not an HTTP response"); | |
| 741 | + goto done; | |
| 742 | + } | |
| 743 | + status = atoi(head + 9); | |
| 744 | + r->status = status; | |
| 745 | + { | |
| 746 | + const char *v; | |
| 747 | + size_t vl; | |
| 748 | + if (head_field(head, head_len, "content-type", &v, &vl)) { | |
| 749 | + size_t k = vl < sizeof r->content_type - 1 ? vl : sizeof r->content_type - 1; | |
| 750 | + memcpy(r->content_type, v, k); | |
| 751 | + r->content_type[k] = '\0'; | |
| 752 | + } | |
| 753 | + if (head_field(head, head_len, "content-length", &v, &vl)) { | |
| 754 | + char nbuf[32]; | |
| 755 | + size_t k = vl < sizeof nbuf - 1 ? vl : sizeof nbuf - 1; | |
| 756 | + memcpy(nbuf, v, k); | |
| 757 | + nbuf[k] = '\0'; | |
| 758 | + clen = atoll(nbuf); | |
| 759 | + } | |
| 760 | + if (head_field(head, head_len, "transfer-encoding", &v, &vl) && | |
| 761 | + vl >= 7 && ci_prefix(v, "chunked")) chunked = 1; | |
| 762 | + } | |
| 763 | + | |
| 764 | + sink.body = r->body; | |
| 765 | + sink.len = 0; | |
| 766 | + sink.total = 0; | |
| 767 | + sink.truncated = 0; | |
| 768 | + | |
| 769 | + if (chunked) { | |
| 770 | + /* Small framing machine. It is fed from the stash first (bytes that | |
| 771 | + * arrived in the same read window as the head terminator are chunk | |
| 772 | + * data, not body) and gives up after WH_DRAIN_CAP bytes so a server | |
| 773 | + * that streams forever cannot hold the request open. */ | |
| 774 | + char buf[4096]; | |
| 775 | + size_t sp = 0, sn = 0, drained = 0; | |
| 776 | + int state = 0; /* 0 size line, 1 data, 2 data CRLF, 3 trailer */ | |
| 777 | + int cr = 0; | |
| 778 | + long long left = 0; | |
| 779 | + | |
| 780 | + if (t.stash_n) { memcpy(buf, t.stash, t.stash_n); sn = t.stash_n; sp = 0; } | |
| 781 | + for (;;) { | |
| 782 | + int c; | |
| 783 | + if (sp >= sn) { | |
| 784 | + int got; | |
| 785 | + if (drained > WH_DRAIN_CAP) break; | |
| 786 | + got = trans_read(&t, buf, sizeof buf); | |
| 787 | + if (got <= 0) break; | |
| 788 | + sp = 0; | |
| 789 | + sn = (size_t)got; | |
| 790 | + drained += (size_t)got; | |
| 791 | + } | |
| 792 | + c = (unsigned char)buf[sp++]; | |
| 793 | + | |
| 794 | + if (state == 0) { /* hex chunk size */ | |
| 795 | + if (c == '\n') { | |
| 796 | + state = (left == 0) ? 3 : 1; | |
| 797 | + if (left == 0) cr = 0; | |
| 798 | + } else if (c == '\r') { | |
| 799 | + /* ignore */ | |
| 800 | + } else if (isxdigit(c)) { | |
| 801 | + int d = (c <= '9') ? (c - '0') : (tolower(c) - 'a' + 10); | |
| 802 | + if (left < 0x10000000LL) left = left * 16 + d; | |
| 803 | + } else { | |
| 804 | + /* a chunk-size extension ("1a;ext=1"); ignore to EOL */ | |
| 805 | + } | |
| 806 | + } else if (state == 1) { /* chunk data */ | |
| 807 | + char one = (char)c; | |
| 808 | + sink_add(&sink, &one, 1); | |
| 809 | + if (--left <= 0) { state = 2; cr = 0; } | |
| 810 | + } else if (state == 2) { /* the CRLF that closes a chunk */ | |
| 811 | + if (c == '\n') { state = 0; left = 0; cr = 0; } | |
| 812 | + } else { /* trailers, until a blank line */ | |
| 813 | + if (c == '\n') { | |
| 814 | + if (cr == 0) break; /* empty line: end of message */ | |
| 815 | + cr = 0; | |
| 816 | + } else if (c != '\r') { | |
| 817 | + cr = 1; | |
| 818 | + } | |
| 819 | + } | |
| 820 | + } | |
| 821 | + } else if (clen >= 0) { | |
| 822 | + long long want = clen; | |
| 823 | + if (t.stash_n) { | |
| 824 | + size_t n = t.stash_n; | |
| 825 | + if ((long long)n > want) n = (size_t)want; | |
| 826 | + sink_add(&sink, t.stash, n); | |
| 827 | + want -= (long long)n; | |
| 828 | + } | |
| 829 | + while (want > 0) { | |
| 830 | + char buf[8192]; | |
| 831 | + size_t n = sizeof buf; | |
| 832 | + int got; | |
| 833 | + if ((long long)n > want) n = (size_t)want; | |
| 834 | + got = trans_read(&t, buf, n); | |
| 835 | + if (got <= 0) break; | |
| 836 | + sink_add(&sink, buf, (size_t)got); | |
| 837 | + want -= got; | |
| 838 | + } | |
| 839 | + } else { | |
| 840 | + size_t drained = 0; | |
| 841 | + if (t.stash_n) sink_add(&sink, t.stash, t.stash_n); | |
| 842 | + for (;;) { | |
| 843 | + char buf[8192]; | |
| 844 | + int got; | |
| 845 | + if (drained > WH_DRAIN_CAP) break; | |
| 846 | + got = trans_read(&t, buf, sizeof buf); | |
| 847 | + if (got <= 0) break; | |
| 848 | + sink_add(&sink, buf, (size_t)got); | |
| 849 | + drained += (size_t)got; | |
| 850 | + if (sink.truncated && sink.len >= WH_PREVIEW_CAP) { | |
| 851 | + /* keep draining a bounded amount, then stop */ | |
| 852 | + if (drained > WH_PREVIEW_CAP) break; | |
| 853 | + } | |
| 854 | + } | |
| 855 | + } | |
| 856 | + | |
| 857 | + sink.body[sink.len] = '\0'; | |
| 858 | + r->body_len = sink.len; | |
| 859 | + r->body_total = sink.total; | |
| 860 | + r->truncated = sink.truncated; | |
| 861 | + r->ok = 1; | |
| 862 | + rc = 0; | |
| 863 | + | |
| 864 | +done: | |
| 865 | + free(head); | |
| 866 | + free(req); | |
| 867 | + trans_close(&t); | |
| 868 | + return rc; | |
| 869 | +} | |
| 870 | +#endif /* !_WIN32 */ | |
| 871 | + | |
| 872 | +/* --------------------------------------------------------------- WinHTTP leg */ | |
| 873 | + | |
| 874 | +#if defined(_WIN32) | |
| 875 | +static void a2w(const char *a, wchar_t *w, int wn) | |
| 876 | +{ | |
| 877 | + MultiByteToWideChar(CP_UTF8, 0, a, -1, w, wn); | |
| 878 | +} | |
| 879 | + | |
| 880 | +static int exchange_winhttp(const wh_url *u, const char *method, | |
| 881 | + const wh_header *hdrs, int nhdrs, | |
| 882 | + const char *body, size_t blen, | |
| 883 | + long timeout_ms, wh_response *r) | |
| 884 | +{ | |
| 885 | + HINTERNET sess = NULL, conn = NULL, req = NULL; | |
| 886 | + wchar_t wtarget[128], wpath[WH_URL_MAX + 8], wmethod[16]; | |
| 887 | + wh_target tgt; | |
| 888 | + DWORD avail = 0, total = 0; | |
| 889 | + int i, rc = -1, host_has_port; | |
| 890 | + wh_sink sink; | |
| 891 | + | |
| 892 | + memset(&sink, 0, sizeof sink); | |
| 893 | + if (resolve_validate(u->host, u->port, wh_allow_private(), &tgt, | |
| 894 | + r->error, sizeof r->error) != 0) | |
| 895 | + return -1; | |
| 896 | + (void)timeout_ms; | |
| 897 | + | |
| 898 | + sess = WinHttpOpen(L"SCORPIOXBOT-webhook/1.0", | |
| 899 | + WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, | |
| 900 | + WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); | |
| 901 | + if (!sess) | |
| 902 | + sess = WinHttpOpen(L"SCORPIOXBOT-webhook/1.0", | |
| 903 | + WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, | |
| 904 | + WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); | |
| 905 | + if (!sess) { snprintf(r->error, sizeof r->error, "WinHttpOpen failed"); return -1; } | |
| 906 | + WinHttpSetTimeouts(sess, WH_CONNECT_MS, WH_CONNECT_MS, WH_READ_MS, WH_READ_MS); | |
| 907 | + | |
| 908 | + /* Connect to the validated numeric address; the real name travels in the | |
| 909 | + * Host header and in SNI (WinHTTP derives SNI from the added Host value | |
| 910 | + * only when connecting by name, so we also pass it explicitly below). */ | |
| 911 | + a2w(tgt.text, wtarget, 128); | |
| 912 | + a2w(u->path[0] ? u->path : "/", wpath, WH_URL_MAX + 8); | |
| 913 | + a2w(method, wmethod, 16); | |
| 914 | + | |
| 915 | + conn = WinHttpConnect(sess, wtarget, (INTERNET_PORT)u->port, 0); | |
| 916 | + if (!conn) { | |
| 917 | + snprintf(r->error, sizeof r->error, "could not connect to %s", u->host); | |
| 918 | + WinHttpCloseHandle(sess); | |
| 919 | + return -1; | |
| 920 | + } | |
| 921 | + req = WinHttpOpenRequest(conn, wmethod, wpath, NULL, WINHTTP_NO_REFERER, | |
| 922 | + WINHTTP_DEFAULT_ACCEPT_TYPES, | |
| 923 | + u->tls ? WINHTTP_FLAG_SECURE : 0); | |
| 924 | + if (!req) { | |
| 925 | + snprintf(r->error, sizeof r->error, "WinHttpOpenRequest failed"); | |
| 926 | + WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | |
| 927 | + return -1; | |
| 928 | + } | |
| 929 | + { | |
| 930 | + DWORD sec = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3; | |
| 931 | + WinHttpSetOption(req, WINHTTP_OPTION_SECURE_PROTOCOLS, &sec, sizeof sec); | |
| 932 | + } | |
| 933 | + { | |
| 934 | + DWORD pol = WINHTTP_OPTION_REDIRECT_POLICY_NEVER; | |
| 935 | + WinHttpSetOption(req, WINHTTP_OPTION_REDIRECT_POLICY, &pol, sizeof pol); | |
| 936 | + } | |
| 937 | + { | |
| 938 | + /* SNI + certificate hostname must be the real name, not the IP. */ | |
| 939 | + wchar_t whost[300]; | |
| 940 | + a2w(u->host, whost, 300); | |
| 941 | + WinHttpSetOption(req, WINHTTP_OPTION_TLS_SERVER_NAME, | |
| 942 | + whost, (DWORD)(wcslen(whost) * sizeof(wchar_t))); | |
| 943 | + } | |
| 944 | + | |
| 945 | + host_has_port = !((u->tls && u->port == 443) || (!u->tls && u->port == 80)); | |
| 946 | + { | |
| 947 | + wchar_t wh[2048]; | |
| 948 | + char hs[1600]; | |
| 949 | + int n; | |
| 950 | + n = snprintf(hs, sizeof hs, "Host: %s%s%s\r\n", | |
| 951 | + u->host, host_has_port ? ":" : "", host_has_port ? "" : ""); | |
| 952 | + if (host_has_port) | |
| 953 | + n = snprintf(hs, sizeof hs, "Host: %s:%d\r\n", u->host, u->port); | |
| 954 | + if (blen || (method && strcmp(method, "GET") != 0 && strcmp(method, "HEAD") != 0)) | |
| 955 | + n += snprintf(hs + n, sizeof hs - (size_t)n, | |
| 956 | + "Content-Length: %lu\r\n", (unsigned long)blen); | |
| 957 | + for (i = 0; i < nhdrs && n < (int)sizeof hs - 1100; i++) { | |
| 958 | + if (!hdrs[i].name[0]) continue; | |
| 959 | + if (ci_prefix(hdrs[i].name, "Host") || | |
| 960 | + ci_prefix(hdrs[i].name, "Content-Length") || | |
| 961 | + ci_prefix(hdrs[i].name, "Transfer-Encoding") || | |
| 962 | + ci_prefix(hdrs[i].name, "Connection")) continue; | |
| 963 | + n += snprintf(hs + n, sizeof hs - (size_t)n, "%s: %s\r\n", | |
| 964 | + hdrs[i].name, hdrs[i].value); | |
| 965 | + } | |
| 966 | + a2w(hs, wh, 2048); | |
| 967 | + WinHttpAddRequestHeaders(req, wh, (DWORD)-1, | |
| 968 | + WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE); | |
| 969 | + } | |
| 970 | + | |
| 971 | + if (!WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0, | |
| 972 | + blen ? (LPVOID)body : WINHTTP_NO_REQUEST_DATA, | |
| 973 | + (DWORD)blen, (DWORD)blen, 0) || | |
| 974 | + !WinHttpReceiveResponse(req, NULL)) { | |
| 975 | + snprintf(r->error, sizeof r->error, | |
| 976 | + "request failed: TLS or connection error (certificate refused " | |
| 977 | + "or endpoint unreachable)"); | |
| 978 | + WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | |
| 979 | + return -1; | |
| 980 | + } | |
| 981 | + { | |
| 982 | + DWORD code = 0, clen2 = sizeof code; | |
| 983 | + WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, | |
| 984 | + WINHTTP_HEADER_NAME_BY_INDEX, &code, &clen2, | |
| 985 | + WINHTTP_NO_HEADER_INDEX); | |
| 986 | + r->status = (int)code; | |
| 987 | + } | |
| 988 | + { | |
| 989 | + DWORD ctype = 0; | |
| 990 | + wchar_t wct[128]; | |
| 991 | + if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CONTENT_TYPE, | |
| 992 | + WINHTTP_HEADER_NAME_BY_INDEX, wct, &ctype, | |
| 993 | + WINHTTP_NO_HEADER_INDEX) && ctype) { | |
| 994 | + WideCharToMultiByte(CP_UTF8, 0, wct, -1, r->content_type, | |
| 995 | + (int)sizeof r->content_type - 1, NULL, NULL); | |
| 996 | + } | |
| 997 | + } | |
| 998 | + | |
| 999 | + sink.body = r->body; | |
| 1000 | + for (;;) { | |
| 1001 | + char buf[8192]; | |
| 1002 | + DWORD got = 0; | |
| 1003 | + if (sink.len >= WH_PREVIEW_CAP) { | |
| 1004 | + /* read the rest in a bounded way so the handle is not abandoned | |
| 1005 | + * mid-response */ | |
| 1006 | + if (sink.total > WH_DRAIN_CAP) break; | |
| 1007 | + sink.truncated = 1; | |
| 1008 | + if (!WinHttpReadData(req, buf, sizeof buf, &got) || got == 0) break; | |
| 1009 | + sink.total += got; | |
| 1010 | + continue; | |
| 1011 | + } | |
| 1012 | + if (!WinHttpReadData(req, buf, sizeof buf, &got) || got == 0) break; | |
| 1013 | + sink_add(&sink, buf, (size_t)got); | |
| 1014 | + total += got; | |
| 1015 | + } | |
| 1016 | + sink.body[sink.len] = '\0'; | |
| 1017 | + r->body_len = sink.len; | |
| 1018 | + r->body_total = sink.total; | |
| 1019 | + r->truncated = sink.truncated; | |
| 1020 | + r->ok = 1; | |
| 1021 | + rc = 0; | |
| 1022 | + | |
| 1023 | + (void)avail; | |
| 1024 | + WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | |
| 1025 | + return rc; | |
| 1026 | +} | |
| 1027 | +#endif | |
| 1028 | + | |
| 1029 | +/* ------------------------------------------------------------------ entry */ | |
| 1030 | + | |
| 1031 | +int wh_http_request(const char *method, const wh_url *u, | |
| 1032 | + const wh_header *hdrs, int nhdrs, | |
| 1033 | + const char *body, size_t blen, | |
| 1034 | + long timeout_ms, wh_response *r) | |
| 1035 | +{ | |
| 1036 | + memset(r, 0, sizeof *r); | |
| 1037 | + if (!u) { snprintf(r->error, sizeof r->error, "no url"); return -1; } | |
| 1038 | + if (!wh_method_ok(method)) { | |
| 1039 | + snprintf(r->error, sizeof r->error, "unsupported method"); | |
| 1040 | + return -1; | |
| 1041 | + } | |
| 1042 | + if (blen > WH_BODY_CAP) { | |
| 1043 | + snprintf(r->error, sizeof r->error, | |
| 1044 | + "the body is larger than the %u byte limit this plugin sends", | |
| 1045 | + (unsigned)WH_BODY_CAP); | |
| 1046 | + return -1; | |
| 1047 | + } | |
| 1048 | +#if defined(_WIN32) | |
| 1049 | + return exchange_winhttp(u, method, hdrs, nhdrs, body, blen, timeout_ms, r); | |
| 1050 | +#else | |
| 1051 | + return exchange_plain(u, method, hdrs, nhdrs, body, blen, timeout_ms, r); | |
| 1052 | +#endif | |
| 1053 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..626e24d | ||
| --- /dev/null | ||
| +++ b/src/wh_http.h | ||
| @@ -0,0 +1,91 @@ | ||
| 1 | +/* | |
| 2 | + * wh_http.h - one outbound HTTP request with SSRF policy and verified TLS. | |
| 3 | + * | |
| 4 | + * The connector sends a user-defined request (method, URL, headers, body) to a | |
| 5 | + * user-defined endpoint. Two things make that safe enough to expose as a tool: | |
| 6 | + * | |
| 7 | + * 1. SSRF policy. Every address the hostname resolves to is checked against a | |
| 8 | + * deny list of loopback / RFC1918 / link-local / ULA / CGNAT / multicast / | |
| 9 | + * documentation / reserved ranges BEFORE connecting, and the connection is | |
| 10 | + * then made to that exact validated numeric address. A DNS answer that | |
| 11 | + * changes between the check and the connect therefore cannot move the | |
| 12 | + * request onto a private network. WEBHOOK_ALLOW_PRIVATE=1 lifts the policy | |
| 13 | + * for an operator who genuinely means to call their own LAN (the offline | |
| 14 | + * suite uses it to reach its recording receiver on 127.0.0.1). | |
| 15 | + * | |
| 16 | + * 2. Verified TLS. POSIX wraps the validated socket in mbedTLS (TLS 1.2+, | |
| 17 | + * VERIFY_PEER, hostname check, system or WEBHOOK_TLS_CA_FILE anchors) with | |
| 18 | + * no insecure bypass. _WIN32 uses WinHTTP against the validated numeric | |
| 19 | + * address with the real Host header and the system root store. | |
| 20 | + * | |
| 21 | + * Redirects are NOT followed: a hook's URL is part of its definition, so a | |
| 22 | + * 30x is reported as a status instead of silently becoming a request to | |
| 23 | + * somewhere the operator never configured. | |
| 24 | + * | |
| 25 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 26 | + */ | |
| 27 | +#ifndef SX_WH_HTTP_H | |
| 28 | +#define SX_WH_HTTP_H | |
| 29 | + | |
| 30 | +#include <stddef.h> | |
| 31 | + | |
| 32 | +#define WH_URL_MAX 2048 | |
| 33 | +#define WH_PREVIEW_CAP 4096 /* bytes of the response body we keep */ | |
| 34 | +#define WH_HEAD_CAP (64u * 1024u) | |
| 35 | +#define WH_BODY_CAP (1u * 1024u * 1024u) /* outbound body limit */ | |
| 36 | +#define WH_CONNECT_MS 10000 | |
| 37 | +#define WH_READ_MS 15000 | |
| 38 | + | |
| 39 | +typedef struct { | |
| 40 | + char scheme[8]; /* "http" | "https" */ | |
| 41 | + char host[256]; | |
| 42 | + int port; | |
| 43 | + char path[WH_URL_MAX]; /* path + query; "/" when absent */ | |
| 44 | + int tls; | |
| 45 | +} wh_url; | |
| 46 | + | |
| 47 | +typedef struct { | |
| 48 | + char name[128]; | |
| 49 | + char value[1024]; | |
| 50 | +} wh_header; | |
| 51 | + | |
| 52 | +typedef struct { | |
| 53 | + int ok; /* 1 = an HTTP response was received */ | |
| 54 | + char error[512]; | |
| 55 | + int status; | |
| 56 | + char content_type[128]; | |
| 57 | + char body[WH_PREVIEW_CAP + 1]; | |
| 58 | + size_t body_len; | |
| 59 | + size_t body_total; /* may exceed body_len when truncated */ | |
| 60 | + int truncated; | |
| 61 | +} wh_response; | |
| 62 | + | |
| 63 | +/* Parse http(s)://host[:port][/path][?query]. Refuses userinfo, IPv6 | |
| 64 | + * literals, control characters and an empty host. 0 ok, -1 with err. */ | |
| 65 | +int wh_url_parse(const char *url, wh_url *out, char *err, size_t errsz); | |
| 66 | + | |
| 67 | +/* The URL with any query string and credentials removed, so a redacted | |
| 68 | + * summary can say where a hook points without leaking a token that a user | |
| 69 | + * pasted into the query string. Always writes something. */ | |
| 70 | +void wh_url_redact(const wh_url *u, char *out, size_t outsz); | |
| 71 | + | |
| 72 | +/* 1 when `ip_text` (IPv4 or IPv6 in text form) is loopback / private / | |
| 73 | + * link-local / CGNAT / multicast / documentation / reserved. 0 when public. | |
| 74 | + * An unparseable string returns 1 (deny), so a bug cannot open a hole. */ | |
| 75 | +int wh_ip_is_denied(const char *ip_text); | |
| 76 | + | |
| 77 | +/* 1 when the environment lifts the SSRF policy (WEBHOOK_ALLOW_PRIVATE=1). */ | |
| 78 | +int wh_allow_private(void); | |
| 79 | + | |
| 80 | +/* Perform one request. `hdrs` may be NULL. `body` may be NULL with blen 0. | |
| 81 | + * Returns 0 when a response arrived (r->ok = 1, r->status set even for 4xx/5xx) | |
| 82 | + * or -1 with r->error set when the request could not be completed. */ | |
| 83 | +int wh_http_request(const char *method, const wh_url *u, | |
| 84 | + const wh_header *hdrs, int nhdrs, | |
| 85 | + const char *body, size_t blen, | |
| 86 | + long timeout_ms, wh_response *r); | |
| 87 | + | |
| 88 | +/* Method validation: GET POST PUT PATCH DELETE HEAD, upper-cased. */ | |
| 89 | +int wh_method_ok(const char *method); | |
| 90 | + | |
| 91 | +#endif /* SX_WH_HTTP_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..08359c5 | ||
| --- /dev/null | ||
| +++ b/src/wh_store.c | ||
| @@ -0,0 +1,668 @@ | ||
| 1 | +/* | |
| 2 | + * wh_store.c - named hooks, their secrets, and the delivery log. See wh_store.h. | |
| 3 | + * | |
| 4 | + * The store file is the only place a secret exists on disk, and it is written | |
| 5 | + * at mode 0600 through a temp file plus rename() so a crash mid-write leaves | |
| 6 | + * the previous document intact rather than a truncated one. | |
| 7 | + * | |
| 8 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 9 | + */ | |
| 10 | +#define _POSIX_C_SOURCE 200809L | |
| 11 | +#if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) | |
| 12 | +#define _DARWIN_C_SOURCE 1 | |
| 13 | +#endif | |
| 14 | + | |
| 15 | +#include "wh_store.h" | |
| 16 | + | |
| 17 | +#include <ctype.h> | |
| 18 | +#include <errno.h> | |
| 19 | +#include <stdio.h> | |
| 20 | +#include <stdlib.h> | |
| 21 | +#include <string.h> | |
| 22 | +#include <time.h> | |
| 23 | + | |
| 24 | +#if defined(_WIN32) | |
| 25 | +# include <direct.h> | |
| 26 | +# include <io.h> | |
| 27 | +# include <sys/stat.h> | |
| 28 | +# include <windows.h> | |
| 29 | +#else | |
| 30 | +# include <sys/stat.h> | |
| 31 | +# include <sys/types.h> | |
| 32 | +# include <unistd.h> | |
| 33 | +#endif | |
| 34 | + | |
| 35 | +#include "wh_buf.h" | |
| 36 | +#include "yyjson.h" | |
| 37 | + | |
| 38 | +/* ------------------------------------------------------------------- paths */ | |
| 39 | + | |
| 40 | +static void mkdir_p(const char *path) | |
| 41 | +{ | |
| 42 | + char tmp[1024]; | |
| 43 | + size_t i, n; | |
| 44 | + | |
| 45 | + n = strlen(path); | |
| 46 | + if (n == 0 || n >= sizeof tmp) return; | |
| 47 | + memcpy(tmp, path, n + 1); | |
| 48 | + for (i = 1; i < n; i++) { | |
| 49 | + if (tmp[i] != '/' && tmp[i] != '\\') continue; | |
| 50 | + tmp[i] = '\0'; | |
| 51 | +#if defined(_WIN32) | |
| 52 | + _mkdir(tmp); | |
| 53 | +#else | |
| 54 | + mkdir(tmp, 0700); | |
| 55 | +#endif | |
| 56 | + tmp[i] = '/'; | |
| 57 | + } | |
| 58 | +#if defined(_WIN32) | |
| 59 | + _mkdir(tmp); | |
| 60 | +#else | |
| 61 | + mkdir(tmp, 0700); | |
| 62 | +#endif | |
| 63 | +} | |
| 64 | + | |
| 65 | +void wh_store_path(char *out, size_t outsz) | |
| 66 | +{ | |
| 67 | + const char *env = getenv("WEBHOOK_STORE_PATH"); | |
| 68 | + const char *base = NULL; | |
| 69 | + | |
| 70 | + if (outsz == 0) return; | |
| 71 | + out[0] = '\0'; | |
| 72 | + if (env && *env) { | |
| 73 | + snprintf(out, outsz, "%s", env); | |
| 74 | + return; | |
| 75 | + } | |
| 76 | +#if defined(_WIN32) | |
| 77 | + base = getenv("LOCALAPPDATA"); | |
| 78 | + if (base && *base) { | |
| 79 | + snprintf(out, outsz, "%s\\scorpiox\\connectors\\plugin_webhook\\hooks.json", base); | |
| 80 | + return; | |
| 81 | + } | |
| 82 | + base = getenv("USERPROFILE"); | |
| 83 | + if (base && *base) { | |
| 84 | + snprintf(out, outsz, "%s\\.scorpiox\\connectors\\plugin_webhook\\hooks.json", base); | |
| 85 | + return; | |
| 86 | + } | |
| 87 | + snprintf(out, outsz, "hooks.json"); | |
| 88 | +#else | |
| 89 | + { | |
| 90 | + struct stat st; | |
| 91 | + if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode)) | |
| 92 | + snprintf(out, outsz, "/workspace/.scorpiox/connectors/plugin_webhook/hooks.json"); | |
| 93 | + else { | |
| 94 | + base = getenv("HOME"); | |
| 95 | + if (base && *base) | |
| 96 | + snprintf(out, outsz, "%s/.scorpiox/connectors/plugin_webhook/hooks.json", base); | |
| 97 | + else | |
| 98 | + snprintf(out, outsz, "/tmp/.scorpiox/connectors/plugin_webhook/hooks.json"); | |
| 99 | + } | |
| 100 | + } | |
| 101 | +#endif | |
| 102 | +} | |
| 103 | + | |
| 104 | +/* --------------------------------------------------------------- load/save */ | |
| 105 | + | |
| 106 | +static void copy_trunc(char *dst, size_t capsz, const char *src) | |
| 107 | +{ | |
| 108 | + size_t n; | |
| 109 | + if (!capsz) return; | |
| 110 | + if (!src) { dst[0] = '\0'; return; } | |
| 111 | + n = strlen(src); | |
| 112 | + if (n >= capsz) n = capsz - 1; | |
| 113 | + memcpy(dst, src, n); | |
| 114 | + dst[n] = '\0'; | |
| 115 | +} | |
| 116 | + | |
| 117 | +static const char *jstr(yyjson_val *o, const char *key) | |
| 118 | +{ | |
| 119 | + yyjson_val *v; | |
| 120 | + if (!o) return NULL; | |
| 121 | + v = yyjson_obj_get(o, key); | |
| 122 | + if (!v || !yyjson_is_str(v)) return NULL; | |
| 123 | + return yyjson_get_str(v); | |
| 124 | +} | |
| 125 | + | |
| 126 | +int wh_store_load(wh_store *s, char *err, size_t errsz) | |
| 127 | +{ | |
| 128 | + FILE *f; | |
| 129 | + char path[1024]; | |
| 130 | + char *text; | |
| 131 | + long sz; | |
| 132 | + size_t got; | |
| 133 | + yyjson_doc *doc; | |
| 134 | + yyjson_val *root, *hooks, *log; | |
| 135 | + | |
| 136 | + memset(s, 0, sizeof *s); | |
| 137 | + if (err && errsz) err[0] = '\0'; | |
| 138 | + wh_store_path(path, sizeof path); | |
| 139 | + | |
| 140 | + f = fopen(path, "rb"); | |
| 141 | + if (!f) return 0; /* no file yet: empty store */ | |
| 142 | + if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return 0; } | |
| 143 | + sz = ftell(f); | |
| 144 | + if (sz < 0 || sz > (long)(4 * 1024 * 1024)) { | |
| 145 | + fclose(f); | |
| 146 | + if (err) snprintf(err, errsz, "store file is unreadable or too large"); | |
| 147 | + return -1; | |
| 148 | + } | |
| 149 | + rewind(f); | |
| 150 | + text = (char *)malloc((size_t)sz + 1); | |
| 151 | + if (!text) { fclose(f); if (err) snprintf(err, errsz, "out of memory"); return -1; } | |
| 152 | + got = fread(text, 1, (size_t)sz, f); | |
| 153 | + fclose(f); | |
| 154 | + text[got] = '\0'; | |
| 155 | + | |
| 156 | + doc = yyjson_read(text, got, 0); | |
| 157 | + free(text); | |
| 158 | + if (!doc) { | |
| 159 | + /* A corrupt store is reported, never silently replaced: the operator | |
| 160 | + * may still be able to recover the secrets from the file. */ | |
| 161 | + if (err) snprintf(err, errsz, | |
| 162 | + "the hook store exists but is not valid JSON (%s); " | |
| 163 | + "it was left untouched", path); | |
| 164 | + return -1; | |
| 165 | + } | |
| 166 | + root = yyjson_doc_get_root(doc); | |
| 167 | + | |
| 168 | + hooks = yyjson_obj_get(root, "hooks"); | |
| 169 | + if (hooks && yyjson_is_arr(hooks)) { | |
| 170 | + size_t i, n = yyjson_arr_size(hooks); | |
| 171 | + for (i = 0; i < n && s->nhooks < WH_MAX_HOOKS; i++) { | |
| 172 | + yyjson_val *o = yyjson_arr_get(hooks, i); | |
| 173 | + yyjson_val *hdrs; | |
| 174 | + wh_hook *h = &s->hooks[s->nhooks]; | |
| 175 | + size_t k, hn; | |
| 176 | + | |
| 177 | + if (!yyjson_is_obj(o)) continue; | |
| 178 | + copy_trunc(h->name, sizeof h->name, jstr(o, "name")); | |
| 179 | + copy_trunc(h->url, sizeof h->url, jstr(o, "url")); | |
| 180 | + copy_trunc(h->method, sizeof h->method, jstr(o, "method")); | |
| 181 | + copy_trunc(h->desc, sizeof h->desc, jstr(o, "desc")); | |
| 182 | + copy_trunc(h->sig, sizeof h->sig, jstr(o, "sig")); | |
| 183 | + copy_trunc(h->secret, sizeof h->secret, jstr(o, "secret")); | |
| 184 | + if (!h->method[0]) copy_trunc(h->method, sizeof h->method, "POST"); | |
| 185 | + hdrs = yyjson_obj_get(o, "headers"); | |
| 186 | + hn = 0; | |
| 187 | + if (hdrs && yyjson_is_arr(hdrs)) { | |
| 188 | + size_t m = yyjson_arr_size(hdrs); | |
| 189 | + for (k = 0; k < m && hn < WH_MAX_HEADERS; k++) { | |
| 190 | + yyjson_val *e = yyjson_arr_get(hdrs, k); | |
| 191 | + const char *nm = jstr(e, "name"); | |
| 192 | + const char *val = jstr(e, "value"); | |
| 193 | + if (!nm || !*nm) continue; | |
| 194 | + copy_trunc(h->headers[hn].name, sizeof h->headers[hn].name, nm); | |
| 195 | + copy_trunc(h->headers[hn].value, sizeof h->headers[hn].value, | |
| 196 | + val ? val : ""); | |
| 197 | + hn++; | |
| 198 | + } | |
| 199 | + } | |
| 200 | + h->nheaders = (int)hn; | |
| 201 | + if (!h->name[0]) continue; | |
| 202 | + s->nhooks++; | |
| 203 | + } | |
| 204 | + } | |
| 205 | + | |
| 206 | + log = yyjson_obj_get(root, "log"); | |
| 207 | + if (log && yyjson_is_arr(log)) { | |
| 208 | + size_t i, n = yyjson_arr_size(log); | |
| 209 | + for (i = 0; i < n && s->nlog < WH_LOG_MAX; i++) { | |
| 210 | + yyjson_val *o = yyjson_arr_get(log, i); | |
| 211 | + wh_logent *e = &s->log[s->nlog]; | |
| 212 | + if (!yyjson_is_obj(o)) continue; | |
| 213 | + copy_trunc(e->at, sizeof e->at, jstr(o, "at")); | |
| 214 | + copy_trunc(e->name, sizeof e->name, jstr(o, "name")); | |
| 215 | + copy_trunc(e->error, sizeof e->error, jstr(o, "error")); | |
| 216 | + { | |
| 217 | + yyjson_val *v = yyjson_obj_get(o, "status"); | |
| 218 | + e->status = (v && yyjson_is_int(v)) ? (int)yyjson_get_sint(v) : 0; | |
| 219 | + v = yyjson_obj_get(o, "ok"); | |
| 220 | + e->ok = (v && yyjson_is_bool(v)) ? (yyjson_get_bool(v) ? 1 : 0) : 0; | |
| 221 | + v = yyjson_obj_get(o, "bytes"); | |
| 222 | + e->bytes = (v && yyjson_is_int(v)) ? (long)yyjson_get_sint(v) : 0; | |
| 223 | + v = yyjson_obj_get(o, "ms"); | |
| 224 | + e->ms = (v && yyjson_is_int(v)) ? (long)yyjson_get_sint(v) : 0; | |
| 225 | + } | |
| 226 | + if (!e->name[0]) continue; | |
| 227 | + s->nlog++; | |
| 228 | + } | |
| 229 | + } | |
| 230 | + | |
| 231 | + yyjson_doc_free(doc); | |
| 232 | + return 0; | |
| 233 | +} | |
| 234 | + | |
| 235 | +static void set_mode_0600(const char *path) | |
| 236 | +{ | |
| 237 | +#if defined(_WIN32) | |
| 238 | + (void)path; /* NTFS ACLs are inherited from the profile dir */ | |
| 239 | +#else | |
| 240 | + chmod(path, 0600); | |
| 241 | +#endif | |
| 242 | +} | |
| 243 | + | |
| 244 | +int wh_store_save(const wh_store *s, char *err, size_t errsz) | |
| 245 | +{ | |
| 246 | + char path[1024], tmp[1100], dir[1024]; | |
| 247 | + wh_buf b; | |
| 248 | + FILE *f; | |
| 249 | + int i, first; | |
| 250 | + char *slash; | |
| 251 | + | |
| 252 | + if (err && errsz) err[0] = '\0'; | |
| 253 | + wh_store_path(path, sizeof path); | |
| 254 | + copy_trunc(dir, sizeof dir, path); | |
| 255 | + slash = strrchr(dir, '/'); | |
| 256 | +#if defined(_WIN32) | |
| 257 | + if (!slash) slash = strrchr(dir, '\\'); | |
| 258 | +#endif | |
| 259 | + if (slash) { *slash = '\0'; mkdir_p(dir); } | |
| 260 | + | |
| 261 | + wh_buf_init(&b); | |
| 262 | + wh_buf_str(&b, "{\"version\":1,\"hooks\":["); | |
| 263 | + first = 1; | |
| 264 | + for (i = 0; i < s->nhooks; i++) { | |
| 265 | + const wh_hook *h = &s->hooks[i]; | |
| 266 | + int f2 = 1, k; | |
| 267 | + if (!first) wh_buf_str(&b, ","); | |
| 268 | + first = 0; | |
| 269 | + wh_buf_str(&b, "{"); | |
| 270 | + wh_buf_key(&b, "name", &f2); wh_buf_json_str(&b, h->name); | |
| 271 | + wh_buf_key(&b, "url", &f2); wh_buf_json_str(&b, h->url); | |
| 272 | + wh_buf_key(&b, "method", &f2); wh_buf_json_str(&b, h->method); | |
| 273 | + wh_buf_key(&b, "desc", &f2); wh_buf_json_str(&b, h->desc); | |
| 274 | + wh_buf_key(&b, "sig", &f2); wh_buf_json_str(&b, h->sig); | |
| 275 | + wh_buf_key(&b, "secret", &f2); wh_buf_json_str(&b, h->secret); | |
| 276 | + wh_buf_key(&b, "headers", &f2); | |
| 277 | + wh_buf_str(&b, "["); | |
| 278 | + for (k = 0; k < h->nheaders; k++) { | |
| 279 | + int f3 = 1; | |
| 280 | + if (k) wh_buf_str(&b, ","); | |
| 281 | + wh_buf_str(&b, "{"); | |
| 282 | + wh_buf_key(&b, "name", &f3); wh_buf_json_str(&b, h->headers[k].name); | |
| 283 | + wh_buf_key(&b, "value", &f3); wh_buf_json_str(&b, h->headers[k].value); | |
| 284 | + wh_buf_str(&b, "}"); | |
| 285 | + } | |
| 286 | + wh_buf_str(&b, "]}"); | |
| 287 | + } | |
| 288 | + wh_buf_str(&b, "],\"log\":["); | |
| 289 | + for (i = 0; i < s->nlog; i++) { | |
| 290 | + const wh_logent *e = &s->log[i]; | |
| 291 | + int f2 = 1; | |
| 292 | + if (i) wh_buf_str(&b, ","); | |
| 293 | + wh_buf_str(&b, "{"); | |
| 294 | + wh_buf_key(&b, "at", &f2); wh_buf_json_str(&b, e->at); | |
| 295 | + wh_buf_key(&b, "name", &f2); wh_buf_json_str(&b, e->name); | |
| 296 | + wh_buf_key(&b, "status", &f2); wh_buf_printf(&b, "%d", e->status); | |
| 297 | + wh_buf_key(&b, "ok", &f2); wh_buf_str(&b, e->ok ? "true" : "false"); | |
| 298 | + wh_buf_key(&b, "bytes", &f2); wh_buf_printf(&b, "%ld", e->bytes); | |
| 299 | + wh_buf_key(&b, "ms", &f2); wh_buf_printf(&b, "%ld", e->ms); | |
| 300 | + wh_buf_key(&b, "error", &f2); wh_buf_json_str(&b, e->error); | |
| 301 | + wh_buf_str(&b, "}"); | |
| 302 | + } | |
| 303 | + wh_buf_str(&b, "]}"); | |
| 304 | + | |
| 305 | + if (b.oom) { | |
| 306 | + wh_buf_free(&b); | |
| 307 | + if (err) snprintf(err, errsz, "out of memory"); | |
| 308 | + return -1; | |
| 309 | + } | |
| 310 | + snprintf(tmp, sizeof tmp, "%s.tmp", path); | |
| 311 | + f = fopen(tmp, "wb"); | |
| 312 | + if (!f) { | |
| 313 | + wh_buf_free(&b); | |
| 314 | + if (err) snprintf(err, errsz, "cannot create %s: %s", tmp, strerror(errno)); | |
| 315 | + return -1; | |
| 316 | + } | |
| 317 | + if (fwrite(wh_buf_cstr(&b), 1, b.n, f) != b.n) { | |
| 318 | + fclose(f); | |
| 319 | + remove(tmp); | |
| 320 | + wh_buf_free(&b); | |
| 321 | + if (err) snprintf(err, errsz, "short write to %s", tmp); | |
| 322 | + return -1; | |
| 323 | + } | |
| 324 | + fflush(f); | |
| 325 | + fclose(f); | |
| 326 | + set_mode_0600(tmp); | |
| 327 | +#if defined(_WIN32) | |
| 328 | + remove(path); | |
| 329 | +#endif | |
| 330 | + if (rename(tmp, path) != 0) { | |
| 331 | + remove(tmp); | |
| 332 | + wh_buf_free(&b); | |
| 333 | + if (err) snprintf(err, errsz, "cannot replace %s: %s", path, strerror(errno)); | |
| 334 | + return -1; | |
| 335 | + } | |
| 336 | + set_mode_0600(path); | |
| 337 | + wh_buf_free(&b); | |
| 338 | + return 0; | |
| 339 | +} | |
| 340 | + | |
| 341 | +/* ------------------------------------------------------------------ lookups */ | |
| 342 | + | |
| 343 | +wh_hook *wh_hook_find(wh_store *s, const char *name) | |
| 344 | +{ | |
| 345 | + int i; | |
| 346 | + if (!s || !name) return NULL; | |
| 347 | + for (i = 0; i < s->nhooks; i++) | |
| 348 | + if (strcmp(s->hooks[i].name, name) == 0) return &s->hooks[i]; | |
| 349 | + return NULL; | |
| 350 | +} | |
| 351 | + | |
| 352 | +void wh_hook_remove(wh_store *s, int idx) | |
| 353 | +{ | |
| 354 | + int i; | |
| 355 | + if (!s || idx < 0 || idx >= s->nhooks) return; | |
| 356 | + for (i = idx; i + 1 < s->nhooks; i++) s->hooks[i] = s->hooks[i + 1]; | |
| 357 | + s->nhooks--; | |
| 358 | + memset(&s->hooks[s->nhooks], 0, sizeof s->hooks[0]); | |
| 359 | +} | |
| 360 | + | |
| 361 | +void wh_store_log_add(wh_store *s, const wh_logent *e) | |
| 362 | +{ | |
| 363 | + int i; | |
| 364 | + if (!s || !e) return; | |
| 365 | + for (i = (s->nlog < WH_LOG_MAX ? s->nlog : WH_LOG_MAX - 1); i > 0; i--) | |
| 366 | + s->log[i] = s->log[i - 1]; | |
| 367 | + s->log[0] = *e; | |
| 368 | + if (s->nlog < WH_LOG_MAX) s->nlog++; | |
| 369 | +} | |
| 370 | + | |
| 371 | +/* -------------------------------------------------------------- serializers */ | |
| 372 | + | |
| 373 | +void wh_hook_json(const wh_hook *h, int redacted, char *out, size_t outsz) | |
| 374 | +{ | |
| 375 | + wh_buf b; | |
| 376 | + int f = 1, k; | |
| 377 | + | |
| 378 | + if (!out || outsz == 0) return; | |
| 379 | + out[0] = '\0'; | |
| 380 | + wh_buf_init(&b); | |
| 381 | + wh_buf_str(&b, "{"); | |
| 382 | + wh_buf_key(&b, "name", &f); wh_buf_json_str(&b, h->name); | |
| 383 | + wh_buf_key(&b, "method", &f); wh_buf_json_str(&b, h->method); | |
| 384 | + wh_buf_key(&b, "desc", &f); wh_buf_json_str(&b, h->desc); | |
| 385 | + wh_buf_key(&b, "sig", &f); wh_buf_json_str(&b, h->sig); | |
| 386 | + wh_buf_key(&b, "has_secret", &f); | |
| 387 | + wh_buf_str(&b, h->secret[0] ? "true" : "false"); | |
| 388 | + if (redacted) { | |
| 389 | + /* Domain + path only: a URL can carry a token in its query string, and | |
| 390 | + * a list of hooks is exactly the kind of output that ends up in a | |
| 391 | + * prompt. */ | |
| 392 | + wh_url u; | |
| 393 | + char err[128]; | |
| 394 | + char clean[WH_URL_MAX + 32]; | |
| 395 | + clean[0] = '\0'; | |
| 396 | + if (wh_url_parse(h->url, &u, err, sizeof err) == 0) | |
| 397 | + wh_url_redact(&u, clean, sizeof clean); | |
| 398 | + wh_buf_key(&b, "url", &f); | |
| 399 | + wh_buf_json_str(&b, clean); | |
| 400 | + } else { | |
| 401 | + wh_buf_key(&b, "url", &f); | |
| 402 | + wh_buf_json_str(&b, h->url); | |
| 403 | + } | |
| 404 | + wh_buf_key(&b, "headers", &f); | |
| 405 | + wh_buf_str(&b, "["); | |
| 406 | + for (k = 0; k < h->nheaders; k++) { | |
| 407 | + int f2 = 1; | |
| 408 | + if (k) wh_buf_str(&b, ","); | |
| 409 | + wh_buf_str(&b, "{"); | |
| 410 | + wh_buf_key(&b, "name", &f2); | |
| 411 | + wh_buf_json_str(&b, h->headers[k].name); | |
| 412 | + if (redacted) { | |
| 413 | + wh_buf_key(&b, "has_secret", &f2); | |
| 414 | + wh_buf_str(&b, h->headers[k].value[0] ? "true" : "false"); | |
| 415 | + } | |
| 416 | + wh_buf_str(&b, "}"); | |
| 417 | + } | |
| 418 | + wh_buf_str(&b, "]}"); | |
| 419 | + snprintf(out, outsz, "%s", wh_buf_cstr(&b)); | |
| 420 | + wh_buf_free(&b); | |
| 421 | +} | |
| 422 | + | |
| 423 | +void wh_store_json(const wh_store *s, int redacted, char *out, size_t outsz) | |
| 424 | +{ | |
| 425 | + wh_buf b; | |
| 426 | + int i; | |
| 427 | + | |
| 428 | + if (!out || outsz == 0) return; | |
| 429 | + out[0] = '\0'; | |
| 430 | + wh_buf_init(&b); | |
| 431 | + wh_buf_str(&b, "{\"ok\":true,\"count\":"); | |
| 432 | + wh_buf_printf(&b, "%d", s->nhooks); | |
| 433 | + wh_buf_str(&b, ",\"hooks\":["); | |
| 434 | + for (i = 0; i < s->nhooks; i++) { | |
| 435 | + char one[WH_URL_MAX * 2 + 4096]; | |
| 436 | + if (i) wh_buf_str(&b, ","); | |
| 437 | + wh_hook_json(&s->hooks[i], redacted, one, sizeof one); | |
| 438 | + wh_buf_str(&b, one); | |
| 439 | + } | |
| 440 | + wh_buf_str(&b, "]}"); | |
| 441 | + snprintf(out, outsz, "%s", wh_buf_cstr(&b)); | |
| 442 | + wh_buf_free(&b); | |
| 443 | +} | |
| 444 | + | |
| 445 | +void wh_store_list_json(const wh_store *s, char *out, size_t outsz) | |
| 446 | +{ | |
| 447 | + wh_buf b; | |
| 448 | + int i, f = 0; /* "ok" and "count" were written literally, so the next | |
| 449 | + * key needs its separator */ | |
| 450 | + | |
| 451 | + if (!out || outsz == 0) return; | |
| 452 | + out[0] = '\0'; | |
| 453 | + wh_buf_init(&b); | |
| 454 | + wh_buf_str(&b, "{\"ok\":true,\"count\":"); | |
| 455 | + wh_buf_printf(&b, "%d", s->nhooks); | |
| 456 | + wh_buf_key(&b, "hooks", &f); | |
| 457 | + wh_buf_str(&b, "["); | |
| 458 | + for (i = 0; i < s->nhooks; i++) { | |
| 459 | + char one[WH_URL_MAX * 2 + 4096]; | |
| 460 | + if (i) wh_buf_str(&b, ","); | |
| 461 | + wh_hook_json(&s->hooks[i], 1, one, sizeof one); | |
| 462 | + wh_buf_str(&b, one); | |
| 463 | + } | |
| 464 | + wh_buf_str(&b, "]"); | |
| 465 | + /* Every key after "hooks" must go through wh_buf_key so the object stays | |
| 466 | + * well-formed: a hand-written ",\"log\":[" here once produced | |
| 467 | + * {"count":16"hooks":... - valid-looking, unparseable. */ | |
| 468 | + wh_buf_key(&b, "log", &f); | |
| 469 | + wh_buf_str(&b, "["); | |
| 470 | + for (i = 0; i < s->nlog; i++) { | |
| 471 | + const wh_logent *e = &s->log[i]; | |
| 472 | + int f2 = 1; | |
| 473 | + if (i) wh_buf_str(&b, ","); | |
| 474 | + wh_buf_str(&b, "{"); | |
| 475 | + wh_buf_key(&b, "at", &f2); wh_buf_json_str(&b, e->at); | |
| 476 | + wh_buf_key(&b, "name", &f2); wh_buf_json_str(&b, e->name); | |
| 477 | + wh_buf_key(&b, "status", &f2); wh_buf_printf(&b, "%d", e->status); | |
| 478 | + wh_buf_key(&b, "ok", &f2); wh_buf_str(&b, e->ok ? "true" : "false"); | |
| 479 | + wh_buf_key(&b, "bytes", &f2); wh_buf_printf(&b, "%ld", e->bytes); | |
| 480 | + wh_buf_key(&b, "ms", &f2); wh_buf_printf(&b, "%ld", e->ms); | |
| 481 | + wh_buf_key(&b, "error", &f2); wh_buf_json_str(&b, e->error); | |
| 482 | + wh_buf_str(&b, "}"); | |
| 483 | + } | |
| 484 | + wh_buf_str(&b, "]"); | |
| 485 | + wh_buf_key(&b, "allow_private", &f); | |
| 486 | + wh_buf_str(&b, wh_allow_private() ? "true" : "false"); | |
| 487 | + wh_buf_str(&b, "}"); | |
| 488 | + snprintf(out, outsz, "%s", wh_buf_cstr(&b)); | |
| 489 | + wh_buf_free(&b); | |
| 490 | +} | |
| 491 | + | |
| 492 | +/* ----------------------------------------------------------------- validate */ | |
| 493 | + | |
| 494 | +static int header_name_ok(const char *s) | |
| 495 | +{ | |
| 496 | + if (!s || !*s) return 0; | |
| 497 | + for (; *s; s++) { | |
| 498 | + unsigned char c = (unsigned char)*s; | |
| 499 | + if (c <= 0x20 || c >= 0x7F) return 0; | |
| 500 | + if (strchr("()<>@,;:\\\"/[]?={}", c)) return 0; | |
| 501 | + } | |
| 502 | + return 1; | |
| 503 | +} | |
| 504 | + | |
| 505 | +static int header_value_ok(const char *s) | |
| 506 | +{ | |
| 507 | + if (!s) return 1; | |
| 508 | + for (; *s; s++) { | |
| 509 | + if (*s == '\r' || *s == '\n' || *s == '\0') return 0; | |
| 510 | + } | |
| 511 | + return 1; | |
| 512 | +} | |
| 513 | + | |
| 514 | +int wh_hook_validate(const wh_hook *h, char *err, size_t errsz) | |
| 515 | +{ | |
| 516 | + wh_url u; | |
| 517 | + char uerr[160]; | |
| 518 | + int i; | |
| 519 | + | |
| 520 | + if (err && errsz) err[0] = '\0'; | |
| 521 | + if (!h->name[0]) { | |
| 522 | + if (err) snprintf(err, errsz, "a hook needs a name"); | |
| 523 | + return -1; | |
| 524 | + } | |
| 525 | + for (i = 0; h->name[i]; i++) { | |
| 526 | + unsigned char c = (unsigned char)h->name[i]; | |
| 527 | + if (!(isalnum(c) || c == '-' || c == '_' || c == '.')) { | |
| 528 | + if (err) snprintf(err, errsz, | |
| 529 | + "hook names may contain letters, digits, dash, " | |
| 530 | + "underscore and dot only"); | |
| 531 | + return -1; | |
| 532 | + } | |
| 533 | + } | |
| 534 | + if (wh_url_parse(h->url, &u, uerr, sizeof uerr) != 0) { | |
| 535 | + if (err) snprintf(err, errsz, "url: %s", uerr); | |
| 536 | + return -1; | |
| 537 | + } | |
| 538 | + if (!wh_method_ok(h->method)) { | |
| 539 | + if (err) snprintf(err, errsz, "method must be one of GET, POST, PUT, PATCH, DELETE, HEAD"); | |
| 540 | + return -1; | |
| 541 | + } | |
| 542 | + if (h->sig[0] && strcmp(h->sig, WH_SIG_GITHUB) != 0 && | |
| 543 | + strcmp(h->sig, WH_SIG_GITLAB) != 0 && strcmp(h->sig, WH_SIG_V2) != 0) { | |
| 544 | + if (err) snprintf(err, errsz, "unknown signature scheme"); | |
| 545 | + return -1; | |
| 546 | + } | |
| 547 | + if (h->sig[0] && !h->secret[0]) { | |
| 548 | + if (err) snprintf(err, errsz, "a signature scheme needs a secret"); | |
| 549 | + return -1; | |
| 550 | + } | |
| 551 | + if (h->nheaders < 0 || h->nheaders > WH_MAX_HEADERS) { | |
| 552 | + if (err) snprintf(err, errsz, "too many headers (max %d)", WH_MAX_HEADERS); | |
| 553 | + return -1; | |
| 554 | + } | |
| 555 | + for (i = 0; i < h->nheaders; i++) { | |
| 556 | + if (!header_name_ok(h->headers[i].name)) { | |
| 557 | + if (err) snprintf(err, errsz, "header %d has an invalid name", i + 1); | |
| 558 | + return -1; | |
| 559 | + } | |
| 560 | + if (!header_value_ok(h->headers[i].value)) { | |
| 561 | + if (err) snprintf(err, errsz, | |
| 562 | + "header %s has a newline in its value", | |
| 563 | + h->headers[i].name); | |
| 564 | + return -1; | |
| 565 | + } | |
| 566 | + } | |
| 567 | + return 0; | |
| 568 | +} | |
| 569 | + | |
| 570 | +/* ------------------------------------------------------------- apply a body */ | |
| 571 | + | |
| 572 | +static int apply_obj(wh_hook *h, yyjson_val *root, const wh_hook *existing, | |
| 573 | + char *err, size_t errsz) | |
| 574 | +{ | |
| 575 | + const char *v; | |
| 576 | + yyjson_val *hdrs; | |
| 577 | + | |
| 578 | + v = jstr(root, "name"); | |
| 579 | + if (v) copy_trunc(h->name, sizeof h->name, v); | |
| 580 | + v = jstr(root, "url"); | |
| 581 | + if (v) copy_trunc(h->url, sizeof h->url, v); | |
| 582 | + v = jstr(root, "desc"); | |
| 583 | + if (v) copy_trunc(h->desc, sizeof h->desc, v); | |
| 584 | + v = jstr(root, "method"); | |
| 585 | + if (v) { | |
| 586 | + size_t i; | |
| 587 | + char m[8]; | |
| 588 | + copy_trunc(m, sizeof m, v); | |
| 589 | + for (i = 0; m[i]; i++) m[i] = (char)toupper((unsigned char)m[i]); | |
| 590 | + copy_trunc(h->method, sizeof h->method, m); | |
| 591 | + } | |
| 592 | + if (!h->method[0]) copy_trunc(h->method, sizeof h->method, "POST"); | |
| 593 | + | |
| 594 | + v = jstr(root, "sig"); | |
| 595 | + if (v) { | |
| 596 | + if (!*v || strcmp(v, WH_SIG_NONE) == 0) h->sig[0] = '\0'; | |
| 597 | + else copy_trunc(h->sig, sizeof h->sig, v); | |
| 598 | + } | |
| 599 | + | |
| 600 | + /* A secret is never echoed back, so an empty incoming value means "keep the | |
| 601 | + * stored one". Rotating a secret is a save with a new value; clearing it is | |
| 602 | + * an explicit sig=none. */ | |
| 603 | + v = jstr(root, "secret"); | |
| 604 | + if (v && *v) copy_trunc(h->secret, sizeof h->secret, v); | |
| 605 | + else if (!h->sig[0]) h->secret[0] = '\0'; | |
| 606 | + | |
| 607 | + hdrs = yyjson_obj_get(root, "headers"); | |
| 608 | + if (hdrs && yyjson_is_arr(hdrs)) { | |
| 609 | + size_t i, n = yyjson_arr_size(hdrs); | |
| 610 | + int out = 0; | |
| 611 | + for (i = 0; i < n && out < WH_MAX_HEADERS; i++) { | |
| 612 | + yyjson_val *e = yyjson_arr_get(hdrs, i); | |
| 613 | + const char *nm = jstr(e, "name"); | |
| 614 | + const char *val = jstr(e, "value"); | |
| 615 | + int k, kept = 0; | |
| 616 | + if (!nm || !*nm) continue; | |
| 617 | + copy_trunc(h->headers[out].name, sizeof h->headers[out].name, nm); | |
| 618 | + h->headers[out].value[0] = '\0'; | |
| 619 | + if (val) { | |
| 620 | + copy_trunc(h->headers[out].value, sizeof h->headers[out].value, val); | |
| 621 | + } else if (existing) { | |
| 622 | + /* no value supplied: keep the stored value for this name */ | |
| 623 | + for (k = 0; k < existing->nheaders; k++) { | |
| 624 | + if (strcmp(existing->headers[k].name, nm) == 0) { | |
| 625 | + copy_trunc(h->headers[out].value, | |
| 626 | + sizeof h->headers[out].value, | |
| 627 | + existing->headers[k].value); | |
| 628 | + kept = 1; | |
| 629 | + break; | |
| 630 | + } | |
| 631 | + } | |
| 632 | + } | |
| 633 | + (void)kept; | |
| 634 | + out++; | |
| 635 | + } | |
| 636 | + h->nheaders = out; | |
| 637 | + } | |
| 638 | + (void)err; | |
| 639 | + (void)errsz; | |
| 640 | + return 0; | |
| 641 | +} | |
| 642 | + | |
| 643 | +int wh_hook_apply(wh_hook *h, const char *json, const wh_hook *existing, | |
| 644 | + char *err, size_t errsz) | |
| 645 | +{ | |
| 646 | + yyjson_doc *doc; | |
| 647 | + yyjson_val *root; | |
| 648 | + | |
| 649 | + if (err && errsz) err[0] = '\0'; | |
| 650 | + if (!json || !*json) { | |
| 651 | + if (err) snprintf(err, errsz, "empty request body"); | |
| 652 | + return -1; | |
| 653 | + } | |
| 654 | + doc = yyjson_read(json, strlen(json), 0); | |
| 655 | + if (!doc) { | |
| 656 | + if (err) snprintf(err, errsz, "request body is not valid JSON"); | |
| 657 | + return -1; | |
| 658 | + } | |
| 659 | + root = yyjson_doc_get_root(doc); | |
| 660 | + if (!yyjson_is_obj(root)) { | |
| 661 | + yyjson_doc_free(doc); | |
| 662 | + if (err) snprintf(err, errsz, "request body must be a JSON object"); | |
| 663 | + return -1; | |
| 664 | + } | |
| 665 | + apply_obj(h, root, existing, err, errsz); | |
| 666 | + yyjson_doc_free(doc); | |
| 667 | + return wh_hook_validate(h, err, errsz); | |
| 668 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..7357b8f | ||
| --- /dev/null | ||
| +++ b/src/wh_store.h | ||
| @@ -0,0 +1,108 @@ | ||
| 1 | +/* | |
| 2 | + * wh_store.h - the named-hook store: definitions, secrets, delivery log. | |
| 3 | + * | |
| 4 | + * One JSON document on disk, written atomically at mode 0600, in | |
| 5 | + * | |
| 6 | + * /workspace/.scorpiox/connectors/plugin_webhook/hooks.json (when /workspace exists) | |
| 7 | + * ~/.scorpiox/connectors/plugin_webhook/hooks.json (elsewhere) | |
| 8 | + * | |
| 9 | + * or wherever WEBHOOK_STORE_PATH points (the offline suite uses that). | |
| 10 | + * | |
| 11 | + * Secrets never leave this module in a readable form. Every serializer that | |
| 12 | + * faces the browser or an MCP client emits, for each header, only its NAME and | |
| 13 | + * `has_secret: true`; for the HMAC it emits the scheme and `has_secret: true`. | |
| 14 | + * A hook definition read back from disk is the only place a value exists, and | |
| 15 | + * it is used for exactly one thing: composing the outbound request. | |
| 16 | + * | |
| 17 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 18 | + */ | |
| 19 | +#ifndef SX_WH_STORE_H | |
| 20 | +#define SX_WH_STORE_H | |
| 21 | + | |
| 22 | +#include <stddef.h> | |
| 23 | + | |
| 24 | +#include "wh_http.h" | |
| 25 | + | |
| 26 | +#define WH_MAX_HOOKS 64 | |
| 27 | +#define WH_MAX_HEADERS 16 | |
| 28 | +#define WH_LOG_MAX 50 | |
| 29 | +#define WH_NAME_MAX 64 | |
| 30 | +#define WH_DESC_MAX 200 | |
| 31 | +#define WH_SECRET_MAX 256 | |
| 32 | +#define WH_HDRVAL_MAX 1024 | |
| 33 | + | |
| 34 | +/* HMAC schemes. Body-only signatures are not offered: they never expire, so a | |
| 35 | + * captured request can be replayed forever. */ | |
| 36 | +#define WH_SIG_NONE "" | |
| 37 | +#define WH_SIG_GITHUB "github" /* X-Hub-Signature-256: sha256=<hex(body)> */ | |
| 38 | +#define WH_SIG_GITLAB "gitlab" /* X-Gitlab-Token: <secret> (shared token) */ | |
| 39 | +#define WH_SIG_V2 "v2" /* X-Webhook-Signature: t=<ts>,v1=<hex(ts|.|body)> */ | |
| 40 | + | |
| 41 | +typedef struct { | |
| 42 | + char name[WH_NAME_MAX]; | |
| 43 | + char url[WH_URL_MAX]; | |
| 44 | + char method[8]; | |
| 45 | + char desc[WH_DESC_MAX]; | |
| 46 | + wh_header headers[WH_MAX_HEADERS]; /* values are secrets */ | |
| 47 | + int nheaders; | |
| 48 | + char sig[16]; /* WH_SIG_* */ | |
| 49 | + char secret[WH_SECRET_MAX]; /* a secret: never serialized out */ | |
| 50 | +} wh_hook; | |
| 51 | + | |
| 52 | +typedef struct { | |
| 53 | + char at[24]; /* ISO-8601 UTC */ | |
| 54 | + char name[WH_NAME_MAX]; | |
| 55 | + int status; | |
| 56 | + int ok; | |
| 57 | + long bytes; | |
| 58 | + long ms; | |
| 59 | + char error[192]; | |
| 60 | +} wh_logent; | |
| 61 | + | |
| 62 | +typedef struct { | |
| 63 | + wh_hook hooks[WH_MAX_HOOKS]; | |
| 64 | + int nhooks; | |
| 65 | + wh_logent log[WH_LOG_MAX]; | |
| 66 | + int nlog; | |
| 67 | +} wh_store; | |
| 68 | + | |
| 69 | +/* Path of the store file (created parents not included). Always writes. */ | |
| 70 | +void wh_store_path(char *out, size_t outsz); | |
| 71 | + | |
| 72 | +/* Load the document. A missing file is an empty store (returns 0). A file that | |
| 73 | + * exists but cannot be read costs a diagnostic in `err` and an empty store, so | |
| 74 | + * the UI can say why the list is empty instead of pretending there are none. */ | |
| 75 | +int wh_store_load(wh_store *s, char *err, size_t errsz); | |
| 76 | + | |
| 77 | +/* Write atomically (tmp + rename) at mode 0600. Returns 0 on success. */ | |
| 78 | +int wh_store_save(const wh_store *s, char *err, size_t errsz); | |
| 79 | + | |
| 80 | +/* Find a hook by name (exact). NULL when absent. */ | |
| 81 | +wh_hook *wh_hook_find(wh_store *s, const char *name); | |
| 82 | + | |
| 83 | +/* Remove hook at index, shifting the rest. */ | |
| 84 | +void wh_hook_remove(wh_store *s, int idx); | |
| 85 | + | |
| 86 | +/* Append to the delivery log, newest first, dropping the oldest beyond | |
| 87 | + * WH_LOG_MAX. */ | |
| 88 | +void wh_store_log_add(wh_store *s, const wh_logent *e); | |
| 89 | + | |
| 90 | +/* ---- serializers ------------------------------------------------------- | |
| 91 | + * `redacted` emits names + has_secret only (browser / MCP). Never pass a | |
| 92 | + * secret-bearing document to a caller that writes it to a response. */ | |
| 93 | +void wh_hook_json(const wh_hook *h, int redacted, char *out, size_t outsz); | |
| 94 | +void wh_store_json(const wh_store *s, int redacted, char *out, size_t outsz); | |
| 95 | +/* "hooks" array + "log" array + counts, the shape every read route returns. */ | |
| 96 | +void wh_store_list_json(const wh_store *s, char *out, size_t outsz); | |
| 97 | + | |
| 98 | +/* Apply a JSON object (as sent by the UI or an MCP call) onto `h`, keeping the | |
| 99 | + * stored secret for any header whose value is absent, and keeping the stored | |
| 100 | + * HMAC secret when the incoming secret is empty. Returns 0 on success or -1 | |
| 101 | + * with a human-readable reason. */ | |
| 102 | +int wh_hook_apply(wh_hook *h, const char *json, const wh_hook *existing, | |
| 103 | + char *err, size_t errsz); | |
| 104 | + | |
| 105 | +/* Validate a hook (URL shape, method, name, header names). Returns 0 or -1. */ | |
| 106 | +int wh_hook_validate(const wh_hook *h, char *err, size_t errsz); | |
| 107 | + | |
| 108 | +#endif /* SX_WH_STORE_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..df6d23a | ||
| --- /dev/null | ||
| +++ b/src/wh_tls.c | ||
| @@ -0,0 +1,248 @@ | ||
| 1 | +/* | |
| 2 | + * wh_tls.c - mbedTLS over an already-connected socket (POSIX). | |
| 3 | + * | |
| 4 | + * The socket arrives pre-validated and pre-connected by wh_http.c (the SSRF | |
| 5 | + * check ran on the numeric address before connect, and we connected to that | |
| 6 | + * exact address), so this layer only wraps TLS around it. No DNS here and no | |
| 7 | + * second connect, therefore no window in which a rebinding DNS answer could | |
| 8 | + * move the connection to a private address after the check. | |
| 9 | + * | |
| 10 | + * _WIN32: WinHTTP does TLS itself; this file compiles to nothing there. | |
| 11 | + * | |
| 12 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 13 | + */ | |
| 14 | +#include "wh_tls.h" | |
| 15 | + | |
| 16 | +#if !defined(_WIN32) | |
| 17 | + | |
| 18 | +#ifndef _POSIX_C_SOURCE | |
| 19 | +#define _POSIX_C_S |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0e70721 | index 0000000..0e70721 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,11 @@ | @@ -0,0 +1,11 @@ | ||
| 1 | +/plugin_webhook | ||
| 2 | +/plugin_webhook.exe | ||
| 3 | +/plugin_webhook.musl | ||
| 4 | +/plugin_webhook.arm64 | ||
| 5 | +/plugin_webhook-asan | ||
| 6 | +/plugin_webhook-fortify | ||
| 7 | +*.o | ||
| 8 | +*.tmp | ||
| 9 | +*.log | ||
| 10 | +__pycache__/ | ||
| 11 | +tests/__pycache__/ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..6f2b03a | index 0000000..6f2b03a | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/LICENSE | +++ b/LICENSE | ||
| @@ -0,0 +1,27 @@ | @@ -0,0 +1,27 @@ | ||
| 1 | +MIT License | ||
| 2 | + | ||
| 3 | +Copyright (c) 2026 SCORPIOX INC | ||
| 4 | + | ||
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 6 | +of this software and associated documentation files (the "Software"), to deal | ||
| 7 | +in the Software without restriction, including without limitation the rights | ||
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 9 | +copies of the Software, and to permit persons to whom the Software is | ||
| 10 | +furnished to do so, subject to the following conditions: | ||
| 11 | + | ||
| 12 | +The above copyright notice and this permission notice shall be included in all | ||
| 13 | +copies or substantial portions of the Software. | ||
| 14 | + | ||
| 15 | +Vendored third-party software keeps its own licence (see vendor/): | ||
| 16 | + - yyjson (MIT, Copyright (c) 2020 YaoYuan) -- vendor/yyjson.{c,h} | ||
| 17 | + - Mbed TLS 3.6.7 (Apache-2.0) -- vendor/mbedtlslib/ | ||
| 18 | + vendor/mbedtls/ | ||
| 19 | + vendor/psa/ | ||
| 20 | + | ||
| 21 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 22 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 23 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 24 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 25 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 26 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 27 | +SOFTWARE. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..b1aa2e3 | index 0000000..b1aa2e3 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,99 @@ | @@ -0,0 +1,99 @@ | ||
| 1 | +# plugin_webhook - SCORPIOX BOT open-source named webhook & REST trigger | ||
| 2 | +# MCP connector | ||
| 3 | +# | ||
| 4 | +# Zero runtime dependencies on every artefact. The third-party C in the tree is | ||
| 5 | +# vendored under vendor/: yyjson (MIT) and Mbed TLS 3.6.7 (Apache-2.0), whose | ||
| 6 | +# sources sit in vendor/mbedtlslib with their public headers flattened into | ||
| 7 | +# vendor/mbedtls and vendor/psa. That layout is what the SCORPIOX BOT release | ||
| 8 | +# CLI (scorpiox-cli-botplugin build/publish) expects: it compiles every .c | ||
| 9 | +# under src/ and vendor/ with exactly -I <repo>/src -I <repo>/vendor, so a | ||
| 10 | +# vendored library must be reachable from those two include roots. | ||
| 11 | +# | ||
| 12 | +# On _WIN32 the HTTP and TLS legs are WinHTTP instead, so the static PE needs no | ||
| 13 | +# extra DLLs and no crypto object files are reached. | ||
| 14 | +# | ||
| 15 | +# Targets: | ||
| 16 | +# make native build -> ./plugin_webhook | ||
| 17 | +# make musl static musl x86_64 -> ./plugin_webhook.musl | ||
| 18 | +# make arm64 static arm64 musl -> ./plugin_webhook.arm64 | ||
| 19 | +# make win64 MinGW-w64 static -> ./plugin_webhook.exe | ||
| 20 | +# make macos Apple clang -> ./plugin_webhook (run on macOS) | ||
| 21 | +# make asan ASan + UBSan + _FORTIFY_SOURCE=2 -> ./plugin_webhook-asan | ||
| 22 | +# make fortify -D_FORTIFY_SOURCE=2 -> ./plugin_webhook-fortify | ||
| 23 | +# make ui regenerate src/ui_html.h from src/ui.html | ||
| 24 | +# make test build + run tests/run.sh | ||
| 25 | +# make e2e build + run tests/e2e.py (Playwright) | ||
| 26 | +# make clean | ||
| 27 | + | ||
| 28 | +CC ?= cc | ||
| 29 | +WARN := -Wall -Wextra -Wno-overlength-strings | ||
| 30 | +STD := -std=c99 | ||
| 31 | +INCLUDES := -I src -I vendor -I vendor/mbedtlslib | ||
| 32 | +CFLAGS ?= -O2 $(STD) $(WARN) $(INCLUDES) | ||
| 33 | +MUSL_CC ?= musl-gcc | ||
| 34 | +MUSL_CFLAGS := -O2 $(STD) $(WARN) $(INCLUDES) -static | ||
| 35 | +ARM_CC ?= aarch64-linux-gnu-gcc | ||
| 36 | +ARM_CFLAGS := -O2 $(STD) $(WARN) $(INCLUDES) -static | ||
| 37 | +WIN_CC ?= x86_64-w64-mingw32-gcc | ||
| 38 | +WIN_CFLAGS := -O2 $(STD) $(WARN) $(INCLUDES) -static | ||
| 39 | +WIN_LIBS := -lwinhttp -lws2_32 -lbcrypt -lcrypt32 | ||
| 40 | + | ||
| 41 | +SRC_C := $(wildcard src/*.c) | ||
| 42 | +VENDOR_C := $(wildcard vendor/*.c) $(wildcard vendor/mbedtlslib/*.c) | ||
| 43 | +UI_SRC := src/ui.html | ||
| 44 | +UI_HDR := src/ui_html.h | ||
| 45 | +BIN := plugin_webhook | ||
| 46 | +EXE := plugin_webhook.exe | ||
| 47 | + | ||
| 48 | +.PHONY: all native musl arm64 win64 macos asan fortify ui test e2e clean help | ||
| 49 | + | ||
| 50 | +all: native | ||
| 51 | + | ||
| 52 | +$(UI_HDR): $(UI_SRC) tools/gen_ui.py | ||
| 53 | + @echo "==> regenerating $(UI_HDR)" | ||
| 54 | + python3 tools/gen_ui.py | ||
| 55 | + | ||
| 56 | +ui: $(UI_HDR) | ||
| 57 | + | ||
| 58 | +native: $(BIN) | ||
| 59 | + | ||
| 60 | +$(BIN): $(SRC_C) $(VENDOR_C) $(UI_HDR) | ||
| 61 | + @echo "==> native build ($(CC))" | ||
| 62 | + $(CC) $(CFLAGS) $(SRC_C) $(VENDOR_C) -o $(BIN) | ||
| 63 | + | ||
| 64 | +musl: $(SRC_C) $(VENDOR_C) $(UI_HDR) | ||
| 65 | + @echo "==> static musl build ($(MUSL_CC))" | ||
| 66 | + $(MUSL_CC) $(MUSL_CFLAGS) $(SRC_C) $(VENDOR_C) -o $(BIN).musl | ||
| 67 | + | ||
| 68 | +arm64: $(SRC_C) $(VENDOR_C) $(UI_HDR) | ||
| 69 | + @echo "==> static arm64 build ($(ARM_CC))" | ||
| 70 | + $(ARM_CC) $(ARM_CFLAGS) $(SRC_C) $(VENDOR_C) -o $(BIN).arm64 | ||
| 71 | + | ||
| 72 | +win64: $(SRC_C) $(VENDOR_C) $(UI_HDR) | ||
| 73 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | ||
| 74 | + $(WIN_CC) $(WIN_CFLAGS) $(SRC_C) $(VENDOR_C) -o $(EXE) $(WIN_LIBS) | ||
| 75 | + | ||
| 76 | +macos: $(SRC_C) $(VENDOR_C) $(UI_HDR) | ||
| 77 | + @echo "==> Apple clang build" | ||
| 78 | + $(CC) $(CFLAGS) $(SRC_C) $(VENDOR_C) -o $(BIN) | ||
| 79 | + | ||
| 80 | +asan: $(SRC_C) $(VENDOR_C) $(UI_HDR) | ||
| 81 | + $(CC) $(CFLAGS) -g -O1 -fsanitize=address,undefined \ | ||
| 82 | + -fno-omit-frame-pointer -D_FORTIFY_SOURCE=2 \ | ||
| 83 | + $(SRC_C) $(VENDOR_C) -o $(BIN)-asan | ||
| 84 | + | ||
| 85 | +fortify: $(SRC_C) $(VENDOR_C) $(UI_HDR) | ||
| 86 | + $(CC) $(CFLAGS) -O2 -D_FORTIFY_SOURCE=2 $(SRC_C) $(VENDOR_C) -o $(BIN)-fortify | ||
| 87 | + | ||
| 88 | +test: native | ||
| 89 | + @bash tests/run.sh | ||
| 90 | + | ||
| 91 | +e2e: native | ||
| 92 | + @python3 tests/e2e.py | ||
| 93 | + | ||
| 94 | +clean: | ||
| 95 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN)-asan $(BIN)-fortify | ||
| 96 | + rm -rf tests/__pycache__ | ||
| 97 | + | ||
| 98 | +help: | ||
| 99 | + @echo "make | make musl | make arm64 | make win64 | make macos | make asan | make fortify | make ui | make test | make e2e | make clean" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..f963603 | index 0000000..f963603 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..a42a12d | index 0000000..a42a12d |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..88d112c | index 0000000..88d112c |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..ba415da | index 0000000..ba415da |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..54df13e | index 0000000..54df13e |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..fab5da3 | index 0000000..fab5da3 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..235fa09 | index 0000000..235fa09 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/plugin.json | +++ b/plugin.json | ||
| @@ -0,0 +1,36 @@ | @@ -0,0 +1,36 @@ | ||
| 1 | +{ | ||
| 2 | + "slug": "webhook", | ||
| 3 | + "id": "plugin_webhook", | ||
| 4 | + "version": "1.0.0", | ||
| 5 | + "name": "webhook", | ||
| 6 | + "desc": "HTTP triggers", | ||
| 7 | + "title": "Named Webhooks & REST Triggers (MCP)", | ||
| 8 | + "summary": "Zero-dependency MCP connector for outbound HTTP: define named hooks (Slack, Discord, Zapier, n8n, IFTTT or your own REST endpoint) with their method, custom headers and an optional HMAC-SHA256 signature, then fire them by name from the agent or the themed page. The bearer token and the signing secret live in one mode-0600 file on the node and are never returned to a prompt or a browser: every read path reports has_secret instead of the value. A pasted webhook URL that carries a token in its query string is redacted in every listing. Outbound requests are SSRF-checked address by address before connecting and TLS is verified with no insecure bypass; redirects are reported, never followed.", | ||
| 9 | + "kind": "mcp", | ||
| 10 | + "mcp": true, | ||
| 11 | + "daemon": false, | ||
| 12 | + "menus": false, | ||
| 13 | + "verified": "live", | ||
| 14 | + "category": "network", | ||
| 15 | + "license": "MIT", | ||
| 16 | + "capabilities": [ | ||
| 17 | + "https_outbound_webhook_delivery", | ||
| 18 | + "hmac_sha256_request_signing", | ||
| 19 | + "ssrf_address_denylist", | ||
| 20 | + "secret_store_0600", | ||
| 21 | + "stdio_mcp_jsonrpc_server" | ||
| 22 | + ], | ||
| 23 | + "trust_notice": "Executes native C code on your node. It makes OUTBOUND HTTP requests to the URLs you configure, carrying the headers and HMAC secrets you store in ~/.scorpiox/connectors/plugin_webhook/hooks.json (mode 0600). Only one private network is reachable and only if you set WEBHOOK_ALLOW_PRIVATE=1; otherwise loopback and every RFC1918 / link-local / ULA address is refused before a socket is opened. TLS is verified against the system root store (or WEBHOOK_TLS_CA_FILE) and cannot be disabled. It runs no shell command, reads no other file, and writes nothing except that one store file.", | ||
| 24 | + "author": "SCORPIOX INC", | ||
| 25 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-webhook", | ||
| 26 | + "cflags": [ | ||
| 27 | + "-std=c99", | ||
| 28 | + "-Wno-overlength-strings" | ||
| 29 | + ], | ||
| 30 | + "ldflags_posix": [], | ||
| 31 | + "ldflags_win64": [ | ||
| 32 | + "-lwinhttp", | ||
| 33 | + "-lws2_32", | ||
| 34 | + "-lbcrypt" | ||
| 35 | + ] | ||
| 36 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0dd243b | index 0000000..0dd243b | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | @@ -0,0 +1,129 @@ | ||
| 1 | +/* | ||
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | ||
| 3 | + * | ||
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | ||
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | ||
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | ||
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | ||
| 8 | + * localStorage key, same prepaint order. | ||
| 9 | + * | ||
| 10 | + * Three rules, and nothing else: | ||
| 11 | + * | ||
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | ||
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | ||
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | ||
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | ||
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | ||
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | ||
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | ||
| 19 | + * it was already open when the bot changed theme. | ||
| 20 | + * | ||
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | ||
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | ||
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | ||
| 24 | + * are var() references, one definition covers both themes. | ||
| 25 | + * | ||
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 27 | + */ | ||
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | ||
| 29 | +#define SX_BOT_THEME_PLUGIN_H | ||
| 30 | + | ||
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | ||
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | ||
| 33 | +#define SX_BOT_THEME_TOKENS \ | ||
| 34 | +":root{color-scheme:dark;" \ | ||
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | ||
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | ||
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | ||
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | ||
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | ||
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | ||
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | ||
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | ||
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | ||
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | ||
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | ||
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | ||
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | ||
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | ||
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | ||
| 50 | +"}" \ | ||
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | ||
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 58 | + "--accent-dim:#0066d6;" \ | ||
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 62 | + "color-scheme:light}}" \ | ||
| 63 | +"html[data-theme=light]{" \ | ||
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 70 | + "--accent-dim:#0066d6;" \ | ||
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 74 | + "color-scheme:light}" \ | ||
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | ||
| 76 | +"*{box-sizing:border-box}" \ | ||
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | ||
| 78 | + "-webkit-font-smoothing:antialiased}" \ | ||
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | ||
| 80 | +"button:active{transform:scale(.98)}" \ | ||
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | ||
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | ||
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | ||
| 84 | +" * hides its own back link and its own toggle. */" \ | ||
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | ||
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | ||
| 87 | + | ||
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | ||
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | ||
| 90 | + * html.embedded so the embed rules apply before first paint. */ | ||
| 91 | +#define SX_BOT_THEME_PREPAINT \ | ||
| 92 | +"<script>(function(){var t='';" \ | ||
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | ||
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | ||
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | ||
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | ||
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 99 | +"})();</script>\n" | ||
| 100 | + | ||
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | ||
| 102 | + * at startup in case it changed while this page was already open. Fires the | ||
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | ||
| 104 | + * re-skin themselves from one listener. */ | ||
| 105 | +#define SX_BOT_THEME_HANDOFF \ | ||
| 106 | +"<script>(function(){" \ | ||
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | ||
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | ||
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | ||
| 112 | +"window.sxApplyTheme=apply;" \ | ||
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | ||
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | ||
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | ||
| 116 | +"})();</script>\n" | ||
| 117 | + | ||
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | ||
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | ||
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | ||
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | ||
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | ||
| 123 | + | ||
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | ||
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | ||
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | ||
| 127 | +"})();</script>\n" | ||
| 128 | + | ||
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..aec298c | index 0000000..aec298c | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_webhook.c | +++ b/src/plugin_webhook.c | ||
| @@ -0,0 +1,1303 @@ | @@ -0,0 +1,1303 @@ | ||
| 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.0" | ||
| 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 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..8880f3e | index 0000000..8880f3e | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/sha256.c | +++ b/src/sha256.c | ||
| @@ -0,0 +1,212 @@ | @@ -0,0 +1,212 @@ | ||
| 1 | +/* | ||
| 2 | + * sha256.c - SHA-256 (FIPS 180-4) and HMAC-SHA256 (RFC 2104), pure C99. | ||
| 3 | + * | ||
| 4 | + * See sha256.h for why this exists instead of a vendored crypto library: the | ||
| 5 | + * only thing this plugin needs from a crypto stack is one hash and one MAC, | ||
| 6 | + * and both are short enough to audit in one sitting. | ||
| 7 | + * | ||
| 8 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 9 | + */ | ||
| 10 | +#define _POSIX_C_SOURCE 200809L | ||
| 11 | + | ||
| 12 | +#include "sha256.h" | ||
| 13 | + | ||
| 14 | +#include <string.h> | ||
| 15 | + | ||
| 16 | +static const uint32_t K[64] = { | ||
| 17 | + 0x428a2f98u, 0x71374491u, 0xb5c0fbcfu, 0xe9b5dba5u, | ||
| 18 | + 0x3956c25bu, 0x59f111f1u, 0x923f82a4u, 0xab1c5ed5u, | ||
| 19 | + 0xd807aa98u, 0x12835b01u, 0x243185beu, 0x550c7dc3u, | ||
| 20 | + 0x72be5d74u, 0x80deb1feu, 0x9bdc06a7u, 0xc19bf174u, | ||
| 21 | + 0xe49b69c1u, 0xefbe4786u, 0x0fc19dc6u, 0x240ca1ccu, | ||
| 22 | + 0x2de92c6fu, 0x4a7484aau, 0x5cb0a9dcu, 0x76f988dau, | ||
| 23 | + 0x983e5152u, 0xa831c66du, 0xb00327c8u, 0xbf597fc7u, | ||
| 24 | + 0xc6e00bf3u, 0xd5a79147u, 0x06ca6351u, 0x14292967u, | ||
| 25 | + 0x27b70a85u, 0x2e1b2138u, 0x4d2c6dfcu, 0x53380d13u, | ||
| 26 | + 0x650a7354u, 0x766a0abbu, 0x81c2c92eu, 0x92722c85u, | ||
| 27 | + 0xa2bfe8a1u, 0xa81a664bu, 0xc24b8b70u, 0xc76c51a3u, | ||
| 28 | + 0xd192e819u, 0xd6990624u, 0xf40e3585u, 0x106aa070u, | ||
| 29 | + 0x19a4c116u, 0x1e376c08u, 0x2748774cu, 0x34b0bcb5u, | ||
| 30 | + 0x391c0cb3u, 0x4ed8aa4au, 0x5b9cca4fu, 0x682e6ff3u, | ||
| 31 | + 0x748f82eeu, 0x78a5636fu, 0x84c87814u, 0x8cc70208u, | ||
| 32 | + 0x90befffau, 0xa4506cebu, 0xbef9a3f7u, 0xc67178f2u | ||
| 33 | +}; | ||
| 34 | + | ||
| 35 | +static uint32_t rotr(uint32_t x, unsigned n) | ||
| 36 | +{ | ||
| 37 | + return (x >> n) | (x << (32 - n)); | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +static void compress(sx_sha256 *c, const unsigned char blk[64]) | ||
| 41 | +{ | ||
| 42 | + uint32_t w[64]; | ||
| 43 | + uint32_t a, b, d, e, f, g, h, cc; | ||
| 44 | + unsigned i; | ||
| 45 | + | ||
| 46 | + for (i = 0; i < 16; i++) { | ||
| 47 | + w[i] = ((uint32_t)blk[i * 4] << 24) | | ||
| 48 | + ((uint32_t)blk[i * 4 + 1] << 16) | | ||
| 49 | + ((uint32_t)blk[i * 4 + 2] << 8) | | ||
| 50 | + ((uint32_t)blk[i * 4 + 3]); | ||
| 51 | + } | ||
| 52 | + for (i = 16; i < 64; i++) { | ||
| 53 | + uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); | ||
| 54 | + uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); | ||
| 55 | + w[i] = w[i - 16] + s0 + w[i - 7] + s1; | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + a = c->h[0]; b = c->h[1]; cc = c->h[2]; d = c->h[3]; | ||
| 59 | + e = c->h[4]; f = c->h[5]; g = c->h[6]; h = c->h[7]; | ||
| 60 | + | ||
| 61 | + for (i = 0; i < 64; i++) { | ||
| 62 | + uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25); | ||
| 63 | + uint32_t ch = (e & f) ^ ((~e) & g); | ||
| 64 | + uint32_t t1 = h + S1 + ch + K[i] + w[i]; | ||
| 65 | + uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22); | ||
| 66 | + uint32_t maj = (a & b) ^ (a & cc) ^ (b & cc); | ||
| 67 | + uint32_t t2 = S0 + maj; | ||
| 68 | + h = g; g = f; f = e; | ||
| 69 | + e = d + t1; | ||
| 70 | + d = cc; cc = b; b = a; | ||
| 71 | + a = t1 + t2; | ||
| 72 | + } | ||
| 73 | + | ||
| 74 | + c->h[0] += a; c->h[1] += b; c->h[2] += cc; c->h[3] += d; | ||
| 75 | + c->h[4] += e; c->h[5] += f; c->h[6] += g; c->h[7] += h; | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +void sx_sha256_init(sx_sha256 *c) | ||
| 79 | +{ | ||
| 80 | + c->h[0] = 0x6a09e667u; c->h[1] = 0xbb67ae85u; | ||
| 81 | + c->h[2] = 0x3c6ef372u; c->h[3] = 0xa54ff53au; | ||
| 82 | + c->h[4] = 0x510e527fu; c->h[5] = 0x9b05688cu; | ||
| 83 | + c->h[6] = 0x1f83d9abu; c->h[7] = 0x5be0cd19u; | ||
| 84 | + c->bits = 0; | ||
| 85 | + c->used = 0; | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +void sx_sha256_update(sx_sha256 *c, const void *data, size_t len) | ||
| 89 | +{ | ||
| 90 | + const unsigned char *p = (const unsigned char *)data; | ||
| 91 | + | ||
| 92 | + c->bits += (uint64_t)len * 8u; | ||
| 93 | + while (len) { | ||
| 94 | + size_t take; | ||
| 95 | + if (c->used == 0 && len >= 64) { | ||
| 96 | + compress(c, p); | ||
| 97 | + p += 64; | ||
| 98 | + len -= 64; | ||
| 99 | + continue; | ||
| 100 | + } | ||
| 101 | + take = 64 - c->used; | ||
| 102 | + if (take > len) take = len; | ||
| 103 | + memcpy(c->buf + c->used, p, take); | ||
| 104 | + c->used += take; | ||
| 105 | + p += take; | ||
| 106 | + len -= take; | ||
| 107 | + if (c->used == 64) { | ||
| 108 | + compress(c, c->buf); | ||
| 109 | + c->used = 0; | ||
| 110 | + } | ||
| 111 | + } | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +void sx_sha256_final(sx_sha256 *c, unsigned char out[SX_SHA256_DIGEST_LEN]) | ||
| 115 | +{ | ||
| 116 | + unsigned char pad[72]; | ||
| 117 | + size_t padlen; | ||
| 118 | + uint64_t bits = c->bits; | ||
| 119 | + unsigned i; | ||
| 120 | + | ||
| 121 | + padlen = (c->used < 56) ? (56 - c->used) : (120 - c->used); | ||
| 122 | + memset(pad, 0, sizeof pad); | ||
| 123 | + pad[0] = 0x80; | ||
| 124 | + /* The length field is appended by update(), which must not add to bits. */ | ||
| 125 | + { | ||
| 126 | + unsigned char lenbuf[8]; | ||
| 127 | + uint64_t save = c->bits; | ||
| 128 | + for (i = 0; i < 8; i++) | ||
| 129 | + lenbuf[7 - i] = (unsigned char)((bits >> (i * 8)) & 0xFFu); | ||
| 130 | + sx_sha256_update(c, pad, padlen); | ||
| 131 | + sx_sha256_update(c, lenbuf, 8); | ||
| 132 | + c->bits = save; | ||
| 133 | + } | ||
| 134 | + for (i = 0; i < 8; i++) { | ||
| 135 | + out[i * 4] = (unsigned char)(c->h[i] >> 24); | ||
| 136 | + out[i * 4 + 1] = (unsigned char)(c->h[i] >> 16); | ||
| 137 | + out[i * 4 + 2] = (unsigned char)(c->h[i] >> 8); | ||
| 138 | + out[i * 4 + 3] = (unsigned char)(c->h[i]); | ||
| 139 | + } | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +static void to_hex(const unsigned char *in, size_t n, char *hex) | ||
| 143 | +{ | ||
| 144 | + static const char digits[] = "0123456789abcdef"; | ||
| 145 | + size_t i; | ||
| 146 | + for (i = 0; i < n; i++) { | ||
| 147 | + hex[i * 2] = digits[in[i] >> 4]; | ||
| 148 | + hex[i * 2 + 1] = digits[in[i] & 0x0F]; | ||
| 149 | + } | ||
| 150 | + hex[n * 2] = '\0'; | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +void sx_sha256_hex(const void *data, size_t len, char hex[SX_SHA256_HEX_LEN + 1]) | ||
| 154 | +{ | ||
| 155 | + sx_sha256 c; | ||
| 156 | + unsigned char d[SX_SHA256_DIGEST_LEN]; | ||
| 157 | + sx_sha256_init(&c); | ||
| 158 | + sx_sha256_update(&c, data, len); | ||
| 159 | + sx_sha256_final(&c, d); | ||
| 160 | + to_hex(d, sizeof d, hex); | ||
| 161 | +} | ||
| 162 | + | ||
| 163 | +void sx_hmac_sha256(const void *key, size_t klen, | ||
| 164 | + const void *msg, size_t len, | ||
| 165 | + unsigned char out[SX_SHA256_DIGEST_LEN]) | ||
| 166 | +{ | ||
| 167 | + unsigned char k[64]; | ||
| 168 | + unsigned char ipad[64], opad[64]; | ||
| 169 | + unsigned char inner[SX_SHA256_DIGEST_LEN]; | ||
| 170 | + sx_sha256 c; | ||
| 171 | + size_t i; | ||
| 172 | + | ||
| 173 | + memset(k, 0, sizeof k); | ||
| 174 | + if (klen > sizeof k) { | ||
| 175 | + sx_sha256_init(&c); | ||
| 176 | + sx_sha256_update(&c, key, klen); | ||
| 177 | + sx_sha256_final(&c, k); /* hashed key is 32 bytes, rest stays 0 */ | ||
| 178 | + } else if (klen) { | ||
| 179 | + memcpy(k, key, klen); | ||
| 180 | + } | ||
| 181 | + for (i = 0; i < sizeof k; i++) { | ||
| 182 | + ipad[i] = (unsigned char)(k[i] ^ 0x36u); | ||
| 183 | + opad[i] = (unsigned char)(k[i] ^ 0x5cu); | ||
| 184 | + } | ||
| 185 | + | ||
| 186 | + sx_sha256_init(&c); | ||
| 187 | + sx_sha256_update(&c, ipad, sizeof ipad); | ||
| 188 | + sx_sha256_update(&c, msg, len); | ||
| 189 | + sx_sha256_final(&c, inner); | ||
| 190 | + | ||
| 191 | + sx_sha256_init(&c); | ||
| 192 | + sx_sha256_update(&c, opad, sizeof opad); | ||
| 193 | + sx_sha256_update(&c, inner, sizeof inner); | ||
| 194 | + sx_sha256_final(&c, out); | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +void sx_hmac_sha256_hex(const void *key, size_t klen, | ||
| 198 | + const void *msg, size_t len, | ||
| 199 | + char hex[SX_SHA256_HEX_LEN + 1]) | ||
| 200 | +{ | ||
| 201 | + unsigned char d[SX_SHA256_DIGEST_LEN]; | ||
| 202 | + sx_hmac_sha256(key, klen, msg, len, d); | ||
| 203 | + to_hex(d, sizeof d, hex); | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +int sx_ct_eq(const unsigned char *a, const unsigned char *b, size_t n) | ||
| 207 | +{ | ||
| 208 | + unsigned char diff = 0; | ||
| 209 | + size_t i; | ||
| 210 | + for (i = 0; i < n; i++) diff |= (unsigned char)(a[i] ^ b[i]); | ||
| 211 | + return diff == 0; | ||
| 212 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..94f3c28 | index 0000000..94f3c28 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/sha256.h | +++ b/src/sha256.h | ||
| @@ -0,0 +1,49 @@ | @@ -0,0 +1,49 @@ | ||
| 1 | +/* | ||
| 2 | + * sha256.h - SHA-256 (FIPS 180-4) and HMAC-SHA256 (RFC 2104) in pure C99. | ||
| 3 | + * | ||
| 4 | + * The plugin signs outbound webhook bodies with HMAC-SHA256, so it needs a | ||
| 5 | + * digest that is correct rather than convenient. This implementation is the | ||
| 6 | + * textbook one: no tables generated at run time, no allocation, no global | ||
| 7 | + * state, and the two FIPS/RFC test vectors in tests/run.sh are the contract. | ||
| 8 | + * | ||
| 9 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 10 | + */ | ||
| 11 | +#ifndef SX_WH_SHA256_H | ||
| 12 | +#define SX_WH_SHA256_H | ||
| 13 | + | ||
| 14 | +#include <stddef.h> | ||
| 15 | +#include <stdint.h> | ||
| 16 | + | ||
| 17 | +#define SX_SHA256_DIGEST_LEN 32 | ||
| 18 | +#define SX_SHA256_HEX_LEN 64 | ||
| 19 | + | ||
| 20 | +typedef struct { | ||
| 21 | + uint32_t h[8]; | ||
| 22 | + uint64_t bits; /* total message length in bits */ | ||
| 23 | + unsigned char buf[64]; | ||
| 24 | + size_t used; /* bytes currently in buf */ | ||
| 25 | +} sx_sha256; | ||
| 26 | + | ||
| 27 | +void sx_sha256_init(sx_sha256 *c); | ||
| 28 | +void sx_sha256_update(sx_sha256 *c, const void *data, size_t len); | ||
| 29 | +void sx_sha256_final(sx_sha256 *c, unsigned char out[SX_SHA256_DIGEST_LEN]); | ||
| 30 | + | ||
| 31 | +/* Convenience: lowercase hex + NUL into `hex` (65 bytes). */ | ||
| 32 | +void sx_sha256_hex(const void *data, size_t len, char hex[SX_SHA256_HEX_LEN + 1]); | ||
| 33 | + | ||
| 34 | +/* HMAC-SHA256 over `len` bytes of `msg` with `klen` bytes of key. | ||
| 35 | + * Writes the raw 32-byte tag into out. */ | ||
| 36 | +void sx_hmac_sha256(const void *key, size_t klen, | ||
| 37 | + const void *msg, size_t len, | ||
| 38 | + unsigned char out[SX_SHA256_DIGEST_LEN]); | ||
| 39 | + | ||
| 40 | +/* HMAC-SHA256 as lowercase hex + NUL (65 bytes). */ | ||
| 41 | +void sx_hmac_sha256_hex(const void *key, size_t klen, | ||
| 42 | + const void *msg, size_t len, | ||
| 43 | + char hex[SX_SHA256_HEX_LEN + 1]); | ||
| 44 | + | ||
| 45 | +/* Constant-time compare of two equal-length buffers. 1 when equal. | ||
| 46 | + * Used for signature checks so a mismatch costs the same as a match. */ | ||
| 47 | +int sx_ct_eq(const unsigned char *a, const unsigned char *b, size_t n); | ||
| 48 | + | ||
| 49 | +#endif /* SX_WH_SHA256_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..3f988f2 | index 0000000..3f988f2 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui.html | +++ b/src/ui.html | ||
| @@ -0,0 +1,575 @@ | @@ -0,0 +1,575 @@ | ||
| 1 | +<!DOCTYPE html> | ||
| 2 | +<html lang="en"><head><meta charset="utf-8"> | ||
| 3 | +<meta name="viewport" content="width=device-width,initial-scale=1"> | ||
| 4 | +<title>webhook</title> | ||
| 5 | +<!--TOKENS--> | ||
| 6 | +<style> | ||
| 7 | +*{box-sizing:border-box} | ||
| 8 | +html,body{margin:0} | ||
| 9 | +body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px; | ||
| 10 | + line-height:1.5;-webkit-font-smoothing:antialiased} | ||
| 11 | +.wrap{max-width:1040px;margin:0 auto;padding:16px} | ||
| 12 | +.head{display:flex;align-items:flex-start;gap:12px;flex-wrap:wrap} | ||
| 13 | +h1{font-size:20px;margin:0 0 2px;font-weight:650;letter-spacing:-.01em} | ||
| 14 | +.sub{color:var(--text-2);font-size:12.5px} | ||
| 15 | +.sub2{color:var(--text-2);font-size:11.5px;margin-top:2px} | ||
| 16 | +.spacer{flex:1 1 auto} | ||
| 17 | +.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px; | ||
| 18 | + padding:16px;margin-bottom:14px} | ||
| 19 | +.card h2{font-size:12px;font-weight:650;margin:0 0 12px;color:var(--text-2); | ||
| 20 | + text-transform:uppercase;letter-spacing:.06em} | ||
| 21 | +.row{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end} | ||
| 22 | +.col{display:flex;flex-direction:column;gap:8px} | ||
| 23 | +label{display:block;font-size:11px;color:var(--text-2);margin-bottom:4px; | ||
| 24 | + text-transform:uppercase;letter-spacing:.05em} | ||
| 25 | +input,select,textarea{background:var(--input-bg);border:1px solid var(--line); | ||
| 26 | + color:var(--text);border-radius:9px;padding:7px 10px;font-size:13.5px; | ||
| 27 | + font-family:var(--font);outline:none;min-width:0;width:100%} | ||
| 28 | +textarea{font-family:var(--mono);font-size:12.5px;resize:vertical;min-height:88px; | ||
| 29 | + line-height:1.45} | ||
| 30 | +input:focus,select:focus,textarea:focus{border-color:var(--blue)} | ||
| 31 | +button{background:var(--blue);color:#fff;border:0;border-radius:980px; | ||
| 32 | + padding:7px 15px;font-size:13px;font-weight:600;cursor:pointer;font-family:var(--font)} | ||
| 33 | +button.ghost{background:var(--surface-2);color:var(--text)} | ||
| 34 | +button.danger{background:var(--red)} | ||
| 35 | +button.tiny{padding:3px 10px;font-size:12px;border-radius:8px} | ||
| 36 | +button:active{transform:scale(.98)} | ||
| 37 | +button:disabled{opacity:.55;cursor:default} | ||
| 38 | +.grow1{flex:1 1 200px}.grow2{flex:2 1 320px} | ||
| 39 | +table{width:100%;border-collapse:collapse;font-size:13px} | ||
| 40 | +th{text-align:left;font-size:10.5px;color:var(--text-2);text-transform:uppercase; | ||
| 41 | + letter-spacing:.05em;font-weight:600;padding:0 8px 7px 0; | ||
| 42 | + border-bottom:1px solid var(--line);white-space:nowrap} | ||
| 43 | +td{padding:9px 8px 9px 0;border-bottom:1px solid var(--line);vertical-align:top} | ||
| 44 | +tr:last-child td{border-bottom:0} | ||
| 45 | +td.mono,.mono{font-family:var(--mono);font-size:12px; | ||
| 46 | + font-variant-numeric:tabular-nums;word-break:break-all} | ||
| 47 | +.tbl-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch} | ||
| 48 | +.pill{display:inline-block;font-size:10.5px;font-weight:600;padding:2px 8px; | ||
| 49 | + border-radius:980px;border:1px solid var(--line);color:var(--text-2); | ||
| 50 | + background:var(--surface-2);white-space:nowrap} | ||
| 51 | +.pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)} | ||
| 52 | +.pill.bad{color:var(--red);border-color:rgba(255,69,58,.35)} | ||
| 53 | +.pill.sig{color:var(--blue);border-color:rgba(10,132,255,.35)} | ||
| 54 | +.pill.muted{color:var(--text-2)} | ||
| 55 | +.empty{color:var(--text-2);font-size:12.5px;padding:10px 0} | ||
| 56 | +.hint{color:var(--text-2);font-size:11.5px;margin-top:6px} | ||
| 57 | +.out{margin-top:12px;padding:12px;border-radius:11px;background:var(--code-bg); | ||
| 58 | + font-family:var(--mono);font-size:12px;white-space:pre-wrap; | ||
| 59 | + word-break:break-word;display:none} | ||
| 60 | +.out.on{display:block} | ||
| 61 | +.out.err{color:var(--red)} | ||
| 62 | +.hdr-row{display:grid;grid-template-columns:1fr 1fr auto;gap:8px;align-items:end} | ||
| 63 | +.icon-btn{background:transparent;border:1px solid var(--line);color:var(--text-2); | ||
| 64 | + border-radius:8px;padding:6px 9px;font-size:12px} | ||
| 65 | +.hidden{display:none!important} | ||
| 66 | +.foot{color:var(--text-2);font-size:11.5px;margin-top:2px} | ||
| 67 | +kbd{font-family:var(--mono);font-size:11px;background:var(--surface-2); | ||
| 68 | + border:1px solid var(--line);border-radius:5px;padding:1px 5px} | ||
| 69 | +/* A five-column table cannot fit 390 px without squeezing the name into a | ||
| 70 | + * vertical ribbon, so below 700 px each row becomes a labelled block. */ | ||
| 71 | +@media(max-width:700px){ | ||
| 72 | + #tbl thead{display:none} | ||
| 73 | + #tbl,#tbl tbody{display:block} | ||
| 74 | + #tbl tr{display:block;border:1px solid var(--line);border-radius:12px; | ||
| 75 | + padding:10px 12px;margin-bottom:10px} | ||
| 76 | + #tbl td{display:grid;grid-template-columns:76px minmax(0,1fr);gap:8px; | ||
| 77 | + padding:2px 0;border:0;align-items:baseline;word-break:break-word} | ||
| 78 | + #tbl td::before{content:attr(data-label);color:var(--text-2);font-size:10.5px; | ||
| 79 | + text-transform:uppercase;letter-spacing:.05em} | ||
| 80 | + #tbl td > .hint{grid-column:2;color:var(--text-2);font-size:11.5px} | ||
| 81 | + #tbl td.actions{grid-template-columns:1fr 1fr;margin-top:8px;gap:6px} | ||
| 82 | + #tbl td.actions::before{content:none} | ||
| 83 | + #tbl td > span,#tbl td > button{justify-self:start} | ||
| 84 | + #tbl td.actions > button{justify-self:stretch} | ||
| 85 | + /* The delivery log has the same problem: six columns at 390 px. */ | ||
| 86 | + #logtbl thead{display:none} | ||
| 87 | + #logtbl,#logtbl tbody{display:block} | ||
| 88 | + #logtbl tr{display:block;border-bottom:1px solid var(--line);padding:8px 0} | ||
| 89 | + #logtbl td{display:grid;grid-template-columns:86px minmax(0,1fr);gap:8px; | ||
| 90 | + padding:1px 0;border:0;word-break:break-word} | ||
| 91 | + #logtbl td::before{content:attr(data-label);color:var(--text-2);font-size:10.5px; | ||
| 92 | + text-transform:uppercase;letter-spacing:.05em} | ||
| 93 | + #logtbl td > span{justify-self:start} | ||
| 94 | +} | ||
| 95 | +@media(max-width:640px){ | ||
| 96 | + .wrap{padding:12px} | ||
| 97 | + .hdr-row{grid-template-columns:1fr} | ||
| 98 | + .head{gap:8px} | ||
| 99 | +} | ||
| 100 | +</style> | ||
| 101 | +</head> | ||
| 102 | +<body> | ||
| 103 | +<div class="wrap"> | ||
| 104 | + | ||
| 105 | + <div class="head"> | ||
| 106 | + <div> | ||
| 107 | + <h1>webhook</h1> | ||
| 108 | + <div class="sub">Named webhook & REST triggers — secrets stay on this node</div> | ||
| 109 | + <div class="sub2" id="policynote"></div> | ||
| 110 | + </div> | ||
| 111 | + <div class="spacer"></div> | ||
| 112 | + <button class="embed-hide icon-btn" id="themeToggle" type="button">Theme</button> | ||
| 113 | + </div> | ||
| 114 | + | ||
| 115 | + <div class="card"> | ||
| 116 | + <h2>Hooks <span id="count" class="pill muted">0</span></h2> | ||
| 117 | + <div class="tbl-wrap"> | ||
| 118 | + <table id="tbl"> | ||
| 119 | + <thead><tr> | ||
| 120 | + <th>Name</th><th>Method</th><th>Endpoint</th><th>Signature</th><th>Secrets</th><th></th> | ||
| 121 | + </tr></thead> | ||
| 122 | + <tbody id="rows"><tr><td colspan="6" class="empty">Loading…</td></tr></tbody> | ||
| 123 | + </table> | ||
| 124 | + </div> | ||
| 125 | + <div class="row" style="margin-top:12px"> | ||
| 126 | + <button id="btnNew" type="button">New hook</button> | ||
| 127 | + <button class="ghost" id="btnReload" type="button">Reload</button> | ||
| 128 | + </div> | ||
| 129 | + </div> | ||
| 130 | + | ||
| 131 | + <div class="card hidden" id="editor"> | ||
| 132 | + <h2 id="editorTitle">New hook</h2> | ||
| 133 | + <div class="row"> | ||
| 134 | + <div class="grow1"><label for="fName">Name</label> | ||
| 135 | + <input id="fName" placeholder="deploy-note" autocomplete="off"></div> | ||
| 136 | + <div class="grow1"><label for="fMethod">Method</label> | ||
| 137 | + <select id="fMethod"> | ||
| 138 | + <option>POST</option><option>GET</option><option>PUT</option> | ||
| 139 | + <option>PATCH</option><option>DELETE</option><option>HEAD</option> | ||
| 140 | + </select></div> | ||
| 141 | + <div class="grow2"><label for="fUrl">URL</label> | ||
| 142 | + <input id="fUrl" placeholder="https://example.com/hooks/abc" autocomplete="off"></div> | ||
| 143 | + </div> | ||
| 144 | + <div class="row" style="margin-top:10px"> | ||
| 145 | + <div class="grow2"><label for="fDesc">Description</label> | ||
| 146 | + <input id="fDesc" placeholder="Deploy notification" autocomplete="off"></div> | ||
| 147 | + <div class="grow1"><label for="fSig">Signature</label> | ||
| 148 | + <select id="fSig"> | ||
| 149 | + <option value="">none</option> | ||
| 150 | + <option value="github">github — X-Hub-Signature-256</option> | ||
| 151 | + <option value="gitlab">gitlab — X-Gitlab-Token</option> | ||
| 152 | + <option value="v2">v2 — timestamped HMAC</option> | ||
| 153 | + </select></div> | ||
| 154 | + <div class="grow1"><label for="fSecret">HMAC secret</label> | ||
| 155 | + <input id="fSecret" type="password" autocomplete="new-password" | ||
| 156 | + placeholder="leave blank to keep"></div> | ||
| 157 | + </div> | ||
| 158 | + | ||
| 159 | + <div style="margin-top:12px"> | ||
| 160 | + <label>Headers</label> | ||
| 161 | + <div class="col" id="hdrList"></div> | ||
| 162 | + <div class="row" style="margin-top:8px"> | ||
| 163 | + <button class="ghost tiny" id="btnAddHdr" type="button">Add header</button> | ||
| 164 | + </div> | ||
| 165 | + <div class="hint">A stored value is never sent back to the browser. Leave the | ||
| 166 | + value blank to keep the secret already saved for that header name.</div> | ||
| 167 | + </div> | ||
| 168 | + | ||
| 169 | + <div class="row" style="margin-top:14px"> | ||
| 170 | + <button id="btnSave" type="button">Save hook</button> | ||
| 171 | + <button class="ghost" id="btnCancel" type="button">Cancel</button> | ||
| 172 | + <span id="saveMsg" class="hint"></span> | ||
| 173 | + </div> | ||
| 174 | + </div> | ||
| 175 | + | ||
| 176 | + <div class="card"> | ||
| 177 | + <h2>Test fire</h2> | ||
| 178 | + <div class="row"> | ||
| 179 | + <div class="grow1"><label for="fFire">Hook</label> | ||
| 180 | + <select id="fFire"></select></div> | ||
| 181 | + <div class="grow2"><label for="fQuery">Query string (optional)</label> | ||
| 182 | + <input id="fQuery" placeholder="event=deploy&env=prod" autocomplete="off"></div> | ||
| 183 | + </div> | ||
| 184 | + <div style="margin-top:10px"> | ||
| 185 | + <label for="fPayload">Payload (JSON)</label> | ||
| 186 | + <textarea id="fPayload">{ | ||
| 187 | + "event": "deploy", | ||
| 188 | + "service": "scorpiox-bot", | ||
| 189 | + "status": "ok" | ||
| 190 | +}</textarea> | ||
| 191 | + </div> | ||
| 192 | + <div class="row" style="margin-top:10px"> | ||
| 193 | + <button id="btnFire" type="button">Send</button> | ||
| 194 | + <span class="hint">Sent from this node with the stored headers and signature.</span> | ||
| 195 | + </div> | ||
| 196 | + <div class="out" id="fireOut"></div> | ||
| 197 | + </div> | ||
| 198 | + | ||
| 199 | + <div class="card"> | ||
| 200 | + <h2>Recent deliveries</h2> | ||
| 201 | + <div class="tbl-wrap"> | ||
| 202 | + <table id="logtbl"> | ||
| 203 | + <thead><tr><th>When (UTC)</th><th>Hook</th><th>Status</th><th>Bytes</th><th>ms</th><th>Detail</th></tr></thead> | ||
| 204 | + <tbody id="logRows"><tr><td colspan="6" class="empty">No deliveries yet.</td></tr></tbody> | ||
| 205 | + </table> | ||
| 206 | + </div> | ||
| 207 | + </div> | ||
| 208 | + | ||
| 209 | + <div class="foot"> | ||
| 210 | + Tool contract: <span class="mono">webhook_list</span>, | ||
| 211 | + <span class="mono">webhook_trigger</span>. Press | ||
| 212 | + <kbd>Ctrl</kbd>+<kbd>Enter</kbd> in the payload box to send. | ||
| 213 | + </div> | ||
| 214 | +</div> | ||
| 215 | + | ||
| 216 | +<script> | ||
| 217 | +/* ------------------------------------------------------------------ routes | ||
| 218 | + * Two call shapes, and getting this wrong is the classic plugin bug: | ||
| 219 | + * served through the hub (bot.scorpiox.net/plugins?plugin=plugin_webhook…) | ||
| 220 | + * -> call the hub proxy back: /plugins?plugin=plugin_webhook&action=… | ||
| 221 | + * opened directly on the node | ||
| 222 | + * -> the plugin IS the route: /plugin_webhook?action=… | ||
| 223 | + * Never call /plugins?plugin= on the node itself: that is the discovery | ||
| 224 | + * endpoint and it answers with the plugin list, not with this plugin. */ | ||
| 225 | +var Q = new URLSearchParams(location.search); | ||
| 226 | +var HUB = Q.get('plugin') || ''; | ||
| 227 | +var NODE = Q.get('node') || ''; | ||
| 228 | +var PW = Q.get('pwd') || (NODE && localStorage.getItem('bot_pwd_' + NODE)) || | ||
| 229 | + localStorage.getItem('bot_active_pwd') || ''; | ||
| 230 | + | ||
| 231 | +function api(action, payload, method) { | ||
| 232 | + var u = (HUB ? '/plugins?plugin=' + encodeURIComponent(HUB) | ||
| 233 | + : '/plugin_webhook') + | ||
| 234 | + '?action=' + encodeURIComponent(action) + '&format=json' + | ||
| 235 | + (NODE ? '&node=' + encodeURIComponent(NODE) : '') + | ||
| 236 | + (PW ? '&pwd=' + encodeURIComponent(PW) : ''); | ||
| 237 | + var opt = { | ||
| 238 | + method: method || (payload ? 'POST' : 'GET'), | ||
| 239 | + headers: PW ? {'X-Bot-Password': PW} : {} | ||
| 240 | + }; | ||
| 241 | + if (payload) { | ||
| 242 | + opt.headers['Content-Type'] = 'application/json'; | ||
| 243 | + opt.body = JSON.stringify(payload); | ||
| 244 | + } | ||
| 245 | + return fetch(u, opt).then(function (r) { | ||
| 246 | + return r.text().then(function (t) { | ||
| 247 | + var d; | ||
| 248 | + try { d = JSON.parse(t); } catch (e) { throw new Error('not JSON: ' + t.slice(0, 200)); } | ||
| 249 | + if (!r.ok || d.ok === false) { | ||
| 250 | + throw new Error(d.error || ('HTTP ' + r.status)); | ||
| 251 | + } | ||
| 252 | + return d; | ||
| 253 | + }); | ||
| 254 | + }); | ||
| 255 | +} | ||
| 256 | + | ||
| 257 | +function el(id) { return document.getElementById(id); } | ||
| 258 | +function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } | ||
| 259 | +function txt(s) { return document.createTextNode(s == null ? '' : String(s)); } | ||
| 260 | + | ||
| 261 | +var state = { hooks: [], log: [], editing: null, allowPrivate: false }; | ||
| 262 | + | ||
| 263 | +function renderPolicy() { | ||
| 264 | + el('policynote').textContent = state.allowPrivate | ||
| 265 | + ? 'Private / loopback endpoints are allowed on this node (WEBHOOK_ALLOW_PRIVATE=1).' | ||
| 266 | + : 'Outbound only to public addresses; loopback and private ranges are refused.'; | ||
| 267 | +} | ||
| 268 | + | ||
| 269 | +function headersSummary(h) { | ||
| 270 | + var n = (h.headers || []).length; | ||
| 271 | + var s = []; | ||
| 272 | + if (n) s.push(n + ' header' + (n === 1 ? '' : 's')); | ||
| 273 | + if (h.has_secret) s.push('HMAC'); | ||
| 274 | + return s.length ? s.join(' + ') : 'none'; | ||
| 275 | +} | ||
| 276 | + | ||
| 277 | +function renderHooks() { | ||
| 278 | + var tb = el('rows'); | ||
| 279 | + clear(tb); | ||
| 280 | + el('count').textContent = String(state.hooks.length); | ||
| 281 | + if (!state.hooks.length) { | ||
| 282 | + var tr = document.createElement('tr'); | ||
| 283 | + var td = document.createElement('td'); | ||
| 284 | + td.colSpan = 6; td.className = 'empty'; | ||
| 285 | + td.appendChild(txt('No hooks yet. Create one to give the agent a tool it can fire.')); | ||
| 286 | + tr.appendChild(td); tb.appendChild(tr); | ||
| 287 | + } | ||
| 288 | + state.hooks.forEach(function (h) { | ||
| 289 | + var tr = document.createElement('tr'); | ||
| 290 | + | ||
| 291 | + var c1 = document.createElement('td'); | ||
| 292 | + c1.className = 'mono'; | ||
| 293 | + c1.dataset.label = 'Name'; | ||
| 294 | + c1.appendChild(txt(h.name)); | ||
| 295 | + if (h.desc) { | ||
| 296 | + var d = document.createElement('div'); | ||
| 297 | + d.className = 'hint'; | ||
| 298 | + d.appendChild(txt(h.desc)); | ||
| 299 | + c1.appendChild(d); | ||
| 300 | + } | ||
| 301 | + tr.appendChild(c1); | ||
| 302 | + | ||
| 303 | + var c2 = document.createElement('td'); | ||
| 304 | + c2.dataset.label = 'Method'; | ||
| 305 | + var p = document.createElement('span'); | ||
| 306 | + p.className = 'pill'; p.appendChild(txt(h.method)); | ||
| 307 | + c2.appendChild(p); | ||
| 308 | + tr.appendChild(c2); | ||
| 309 | + | ||
| 310 | + var c3 = document.createElement('td'); | ||
| 311 | + c3.className = 'mono'; | ||
| 312 | + c3.dataset.label = 'Endpoint'; | ||
| 313 | + c3.appendChild(txt(h.url || '')); | ||
| 314 | + tr.appendChild(c3); | ||
| 315 | + | ||
| 316 | + var c4 = document.createElement('td'); | ||
| 317 | + c4.dataset.label = 'Signature'; | ||
| 318 | + var sp = document.createElement('span'); | ||
| 319 | + if (h.sig) { sp.className = 'pill sig'; sp.appendChild(txt(h.sig)); } | ||
| 320 | + else { sp.className = 'pill muted'; sp.appendChild(txt('none')); } | ||
| 321 | + c4.appendChild(sp); | ||
| 322 | + tr.appendChild(c4); | ||
| 323 | + | ||
| 324 | + var c5 = document.createElement('td'); | ||
| 325 | + c5.className = 'hint'; | ||
| 326 | + c5.dataset.label = 'Secrets'; | ||
| 327 | + c5.appendChild(txt(headersSummary(h))); | ||
| 328 | + tr.appendChild(c5); | ||
| 329 | + | ||
| 330 | + var c6 = document.createElement('td'); | ||
| 331 | + c6.className = 'actions'; | ||
| 332 | + c6.dataset.label = ''; | ||
| 333 | + c6.style.whiteSpace = 'nowrap'; | ||
| 334 | + var bEdit = document.createElement('button'); | ||
| 335 | + bEdit.className = 'ghost tiny'; bEdit.type = 'button'; | ||
| 336 | + bEdit.appendChild(txt('Edit')); | ||
| 337 | + bEdit.onclick = function () { openEditor(h); }; | ||
| 338 | + var bDel = document.createElement('button'); | ||
| 339 | + bDel.className = 'ghost tiny'; bDel.type = 'button'; | ||
| 340 | + bDel.style.marginLeft = '6px'; | ||
| 341 | + bDel.appendChild(txt('Delete')); | ||
| 342 | + bDel.onclick = function () { removeHook(h.name); }; | ||
| 343 | + c6.appendChild(bEdit); c6.appendChild(bDel); | ||
| 344 | + tr.appendChild(c6); | ||
| 345 | + | ||
| 346 | + tb.appendChild(tr); | ||
| 347 | + }); | ||
| 348 | + | ||
| 349 | + var sel = el('fFire'); | ||
| 350 | + var keep = sel.value; | ||
| 351 | + clear(sel); | ||
| 352 | + state.hooks.forEach(function (h) { | ||
| 353 | + var o = document.createElement('option'); | ||
| 354 | + o.value = h.name; o.appendChild(txt(h.name + ' (' + h.method + ')')); | ||
| 355 | + sel.appendChild(o); | ||
| 356 | + }); | ||
| 357 | + if (keep) sel.value = keep; | ||
| 358 | +} | ||
| 359 | + | ||
| 360 | +function renderLog() { | ||
| 361 | + var tb = el('logRows'); | ||
| 362 | + clear(tb); | ||
| 363 | + if (!state.log.length) { | ||
| 364 | + var tr = document.createElement('tr'); | ||
| 365 | + var td = document.createElement('td'); | ||
| 366 | + td.colSpan = 6; td.className = 'empty'; | ||
| 367 | + td.appendChild(txt('No deliveries yet.')); | ||
| 368 | + tr.appendChild(td); tb.appendChild(tr); | ||
| 369 | + return; | ||
| 370 | + } | ||
| 371 | + /* The store keeps 50 deliveries; a page that lists all of them is a wall. | ||
| 372 | + * The newest eight are what a person is looking for. */ | ||
| 373 | + state.log.slice(0, 8).forEach(function (e) { | ||
| 374 | + var tr = document.createElement('tr'); | ||
| 375 | + var c1 = document.createElement('td'); | ||
| 376 | + c1.className = 'mono'; c1.dataset.label = 'When'; c1.appendChild(txt(e.at)); | ||
| 377 | + tr.appendChild(c1); | ||
| 378 | + var c2 = document.createElement('td'); | ||
| 379 | + c2.className = 'mono'; c2.dataset.label = 'Hook'; c2.appendChild(txt(e.name)); | ||
| 380 | + tr.appendChild(c2); | ||
| 381 | + var c3 = document.createElement('td'); | ||
| 382 | + c3.dataset.label = 'Status'; | ||
| 383 | + var p = document.createElement('span'); | ||
| 384 | + p.className = 'pill ' + (e.ok ? 'ok' : 'bad'); | ||
| 385 | + p.appendChild(txt(e.status ? String(e.status) : 'error')); | ||
| 386 | + c3.appendChild(p); | ||
| 387 | + tr.appendChild(c3); | ||
| 388 | + var c4 = document.createElement('td'); | ||
| 389 | + c4.className = 'mono'; c4.dataset.label = 'Bytes'; c4.appendChild(txt(e.bytes)); | ||
| 390 | + tr.appendChild(c4); | ||
| 391 | + var c5 = document.createElement('td'); | ||
| 392 | + c5.className = 'mono'; c5.dataset.label = 'ms'; c5.appendChild(txt(e.ms)); | ||
| 393 | + tr.appendChild(c5); | ||
| 394 | + /* An empty Detail row is five lines of nothing on a phone, so it is only | ||
| 395 | + * emitted when there is something to say. */ | ||
| 396 | + if (e.error) { | ||
| 397 | + var c6 = document.createElement('td'); | ||
| 398 | + c6.className = 'hint'; c6.dataset.label = 'Detail'; | ||
| 399 | + c6.appendChild(txt(e.error)); | ||
| 400 | + tr.appendChild(c6); | ||
| 401 | + } | ||
| 402 | + tb.appendChild(tr); | ||
| 403 | + }); | ||
| 404 | +} | ||
| 405 | + | ||
| 406 | +function load() { | ||
| 407 | + return api('list').then(function (d) { | ||
| 408 | + state.hooks = d.hooks || []; | ||
| 409 | + state.log = d.log || []; | ||
| 410 | + state.allowPrivate = !!d.allow_private; | ||
| 411 | + renderPolicy(); | ||
| 412 | + renderHooks(); | ||
| 413 | + renderLog(); | ||
| 414 | + }).catch(function (e) { | ||
| 415 | + var tb = el('rows'); | ||
| 416 | + clear(tb); | ||
| 417 | + var tr = document.createElement('tr'); | ||
| 418 | + var td = document.createElement('td'); | ||
| 419 | + td.colSpan = 6; td.className = 'empty'; | ||
| 420 | + td.appendChild(txt('Could not load hooks: ' + e.message)); | ||
| 421 | + tr.appendChild(td); tb.appendChild(tr); | ||
| 422 | + }); | ||
| 423 | +} | ||
| 424 | + | ||
| 425 | +/* ---------------------------------------------------------------- editor */ | ||
| 426 | + | ||
| 427 | +function addHeaderRow(name, value, hasSecret) { | ||
| 428 | + var row = document.createElement('div'); | ||
| 429 | + row.className = 'hdr-row'; | ||
| 430 | + | ||
| 431 | + var n = document.createElement('div'); | ||
| 432 | + var ln = document.createElement('label'); ln.appendChild(txt('Header')); | ||
| 433 | + var inName = document.createElement('input'); | ||
| 434 | + inName.className = 'hdr-name'; inName.value = name || ''; | ||
| 435 | + inName.placeholder = 'Authorization'; inName.autocomplete = 'off'; | ||
| 436 | + n.appendChild(ln); n.appendChild(inName); | ||
| 437 | + | ||
| 438 | + var v = document.createElement('div'); | ||
| 439 | + var lv = document.createElement('label'); lv.appendChild(txt('Value')); | ||
| 440 | + var inVal = document.createElement('input'); | ||
| 441 | + inVal.className = 'hdr-value'; inVal.value = value || ''; | ||
| 442 | + inVal.type = 'password'; inVal.autocomplete = 'new-password'; | ||
| 443 | + inVal.placeholder = hasSecret ? 'stored — leave blank to keep' : 'Bearer …'; | ||
| 444 | + v.appendChild(lv); v.appendChild(inVal); | ||
| 445 | + | ||
| 446 | + var b = document.createElement('button'); | ||
| 447 | + b.type = 'button'; b.className = 'icon-btn'; b.appendChild(txt('Remove')); | ||
| 448 | + b.onclick = function () { row.parentNode.removeChild(row); }; | ||
| 449 | + | ||
| 450 | + row.appendChild(n); row.appendChild(v); row.appendChild(b); | ||
| 451 | + el('hdrList').appendChild(row); | ||
| 452 | +} | ||
| 453 | + | ||
| 454 | +function openEditor(hook) { | ||
| 455 | + state.editing = hook ? hook.name : null; | ||
| 456 | + el('editor').classList.remove('hidden'); | ||
| 457 | + el('editorTitle').textContent = hook ? ('Edit ' + hook.name) : 'New hook'; | ||
| 458 | + el('fName').value = hook ? hook.name : ''; | ||
| 459 | + el('fName').disabled = !!hook; | ||
| 460 | + el('fMethod').value = hook ? hook.method : 'POST'; | ||
| 461 | + el('fUrl').value = hook ? (hook.url || '') : ''; | ||
| 462 | + el('fDesc').value = hook ? (hook.desc || '') : ''; | ||
| 463 | + el('fSig').value = hook ? (hook.sig || '') : ''; | ||
| 464 | + el('fSecret').value = ''; | ||
| 465 | + el('fSecret').placeholder = hook && hook.has_secret | ||
| 466 | + ? 'stored — leave blank to keep' : 'optional'; | ||
| 467 | + clear(el('hdrList')); | ||
| 468 | + if (hook) { | ||
| 469 | + (hook.headers || []).forEach(function (hd) { | ||
| 470 | + addHeaderRow(hd.name, '', !!hd.has_secret); | ||
| 471 | + }); | ||
| 472 | + } else { | ||
| 473 | + addHeaderRow('Content-Type', 'application/json', false); | ||
| 474 | + } | ||
| 475 | + el('saveMsg').textContent = ''; | ||
| 476 | + el('fName').focus(); | ||
| 477 | +} | ||
| 478 | + | ||
| 479 | +function collectHook() { | ||
| 480 | + var headers = []; | ||
| 481 | + var rows = el('hdrList').children; | ||
| 482 | + for (var i = 0; i < rows.length; i++) { | ||
| 483 | + var n = rows[i].querySelector('.hdr-name'); | ||
| 484 | + var v = rows[i].querySelector('.hdr-value'); | ||
| 485 | + if (!n || !n.value.trim()) continue; | ||
| 486 | + var entry = { name: n.value.trim() }; | ||
| 487 | + /* An empty value means "keep whatever is stored for this name". Sending | ||
| 488 | + * the key at all with an empty string would clear the secret. */ | ||
| 489 | + if (v && v.value !== '') entry.value = v.value; | ||
| 490 | + headers.push(entry); | ||
| 491 | + } | ||
| 492 | + var body = { | ||
| 493 | + name: el('fName').value.trim(), | ||
| 494 | + url: el('fUrl').value.trim(), | ||
| 495 | + method: el('fMethod').value, | ||
| 496 | + desc: el('fDesc').value.trim(), | ||
| 497 | + sig: el('fSig').value, | ||
| 498 | + headers: headers | ||
| 499 | + }; | ||
| 500 | + if (el('fSecret').value) body.secret = el('fSecret').value; | ||
| 501 | + return body; | ||
| 502 | +} | ||
| 503 | + | ||
| 504 | +function saveHook() { | ||
| 505 | + var body = collectHook(); | ||
| 506 | + if (!body.name) { el('saveMsg').textContent = 'A name is required.'; return; } | ||
| 507 | + if (!body.url) { el('saveMsg').textContent = 'A URL is required.'; return; } | ||
| 508 | + el('saveMsg').textContent = 'Saving…'; | ||
| 509 | + api('save', body).then(function () { | ||
| 510 | + el('editor').classList.add('hidden'); | ||
| 511 | + return load(); | ||
| 512 | + }).catch(function (e) { | ||
| 513 | + el('saveMsg').textContent = 'Error: ' + e.message; | ||
| 514 | + }); | ||
| 515 | +} | ||
| 516 | + | ||
| 517 | +function removeHook(name) { | ||
| 518 | + api('delete', { name: name }).then(load).catch(function (e) { | ||
| 519 | + el('fireOut').className = 'out on err'; | ||
| 520 | + el('fireOut').textContent = 'Delete failed: ' + e.message; | ||
| 521 | + }); | ||
| 522 | +} | ||
| 523 | + | ||
| 524 | +/* ------------------------------------------------------------------- fire */ | ||
| 525 | + | ||
| 526 | +function fire() { | ||
| 527 | + var name = el('fFire').value; | ||
| 528 | + var out = el('fireOut'); | ||
| 529 | + if (!name) { | ||
| 530 | + out.className = 'out on err'; | ||
| 531 | + out.textContent = 'Create a hook first.'; | ||
| 532 | + return; | ||
| 533 | + } | ||
| 534 | + var payload = el('fPayload').value; | ||
| 535 | + try { JSON.parse(payload || '{}'); } | ||
| 536 | + catch (e) { | ||
| 537 | + out.className = 'out on err'; | ||
| 538 | + out.textContent = 'The payload is not valid JSON: ' + e.message; | ||
| 539 | + return; | ||
| 540 | + } | ||
| 541 | + var body = { name: name, payload: payload || '{}' }; | ||
| 542 | + if (el('fQuery').value.trim()) body.query = el('fQuery').value.trim(); | ||
| 543 | + | ||
| 544 | + out.className = 'out on'; | ||
| 545 | + out.textContent = 'Sending…'; | ||
| 546 | + api('fire', body).then(function (d) { | ||
| 547 | + out.className = 'out on' + (d.ok_status ? '' : ' err'); | ||
| 548 | + out.textContent = JSON.stringify(d, null, 2); | ||
| 549 | + return load(); | ||
| 550 | + }).catch(function (e) { | ||
| 551 | + out.className = 'out on err'; | ||
| 552 | + out.textContent = 'Send failed: ' + e.message; | ||
| 553 | + }); | ||
| 554 | +} | ||
| 555 | + | ||
| 556 | +/* ------------------------------------------------------------------- wire */ | ||
| 557 | + | ||
| 558 | +el('btnNew').onclick = function () { openEditor(null); }; | ||
| 559 | +el('btnReload').onclick = function () { load(); }; | ||
| 560 | +el('btnCancel').onclick = function () { el('editor').classList.add('hidden'); }; | ||
| 561 | +el('btnSave').onclick = saveHook; | ||
| 562 | +el('btnAddHdr').onclick = function () { addHeaderRow('', '', false); }; | ||
| 563 | +el('btnFire').onclick = fire; | ||
| 564 | +el('fPayload').addEventListener('keydown', function (e) { | ||
| 565 | + if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') fire(); | ||
| 566 | +}); | ||
| 567 | +el('themeToggle').onclick = function () { | ||
| 568 | + if (window.sxApplyTheme) { | ||
| 569 | + window.sxApplyTheme(window.sxTheme && window.sxTheme() === 'dark' ? 'light' : 'dark'); | ||
| 570 | + } | ||
| 571 | +}; | ||
| 572 | + | ||
| 573 | +load(); | ||
| 574 | +</script> | ||
| 575 | +</body></html> |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..a193f9d | index 0000000..a193f9d | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui_html.h | +++ b/src/ui_html.h | ||
| @@ -0,0 +1,583 @@ | @@ -0,0 +1,583 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | ||
| 2 | +#ifndef SX_WEBHOOK_UI_HTML_H | ||
| 3 | +#define SX_WEBHOOK_UI_HTML_H | ||
| 4 | + | ||
| 5 | +static const char *UI_HTML = | ||
| 6 | + "<!DOCTYPE html>\n" | ||
| 7 | + "<html lang=\"en\"><head><meta charset=\"utf-8\">\n" | ||
| 8 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | ||
| 9 | + "<title>webhook</title>\n" | ||
| 10 | + "\001\n" | ||
| 11 | + "<style>\n" | ||
| 12 | + "*{box-sizing:border-box}\n" | ||
| 13 | + "html,body{margin:0}\n" | ||
| 14 | + "body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;\n" | ||
| 15 | + " line-height:1.5;-webkit-font-smoothing:antialiased}\n" | ||
| 16 | + ".wrap{max-width:1040px;margin:0 auto;padding:16px}\n" | ||
| 17 | + ".head{display:flex;align-items:flex-start;gap:12px;flex-wrap:wrap}\n" | ||
| 18 | + "h1{font-size:20px;margin:0 0 2px;font-weight:650;letter-spacing:-.01em}\n" | ||
| 19 | + ".sub{color:var(--text-2);font-size:12.5px}\n" | ||
| 20 | + ".sub2{color:var(--text-2);font-size:11.5px;margin-top:2px}\n" | ||
| 21 | + ".spacer{flex:1 1 auto}\n" | ||
| 22 | + ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;\n" | ||
| 23 | + " padding:16px;margin-bottom:14px}\n" | ||
| 24 | + ".card h2{font-size:12px;font-weight:650;margin:0 0 12px;color:var(--text-2);\n" | ||
| 25 | + " text-transform:uppercase;letter-spacing:.06em}\n" | ||
| 26 | + ".row{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end}\n" | ||
| 27 | + ".col{display:flex;flex-direction:column;gap:8px}\n" | ||
| 28 | + "label{display:block;font-size:11px;color:var(--text-2);margin-bottom:4px;\n" | ||
| 29 | + " text-transform:uppercase;letter-spacing:.05em}\n" | ||
| 30 | + "input,select,textarea{background:var(--input-bg);border:1px solid var(--line);\n" | ||
| 31 | + " color:var(--text);border-radius:9px;padding:7px 10px;font-size:13.5px;\n" | ||
| 32 | + " font-family:var(--font);outline:none;min-width:0;width:100%}\n" | ||
| 33 | + "textarea{font-family:var(--mono);font-size:12.5px;resize:vertical;min-height:88px;\n" | ||
| 34 | + " line-height:1.45}\n" | ||
| 35 | + "input:focus,select:focus,textarea:focus{border-color:var(--blue)}\n" | ||
| 36 | + "button{background:var(--blue);color:#fff;border:0;border-radius:980px;\n" | ||
| 37 | + " padding:7px 15px;font-size:13px;font-weight:600;cursor:pointer;font-family:var(--font)}\n" | ||
| 38 | + "button.ghost{background:var(--surface-2);color:var(--text)}\n" | ||
| 39 | + "button.danger{background:var(--red)}\n" | ||
| 40 | + "button.tiny{padding:3px 10px;font-size:12px;border-radius:8px}\n" | ||
| 41 | + "button:active{transform:scale(.98)}\n" | ||
| 42 | + "button:disabled{opacity:.55;cursor:default}\n" | ||
| 43 | + ".grow1{flex:1 1 200px}.grow2{flex:2 1 320px}\n" | ||
| 44 | + "table{width:100%;border-collapse:collapse;font-size:13px}\n" | ||
| 45 | + "th{text-align:left;font-size:10.5px;color:var(--text-2);text-transform:uppercase;\n" | ||
| 46 | + " letter-spacing:.05em;font-weight:600;padding:0 8px 7px 0;\n" | ||
| 47 | + " border-bottom:1px solid var(--line);white-space:nowrap}\n" | ||
| 48 | + "td{padding:9px 8px 9px 0;border-bottom:1px solid var(--line);vertical-align:top}\n" | ||
| 49 | + "tr:last-child td{border-bottom:0}\n" | ||
| 50 | + "td.mono,.mono{font-family:var(--mono);font-size:12px;\n" | ||
| 51 | + " font-variant-numeric:tabular-nums;word-break:break-all}\n" | ||
| 52 | + ".tbl-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch}\n" | ||
| 53 | + ".pill{display:inline-block;font-size:10.5px;font-weight:600;padding:2px 8px;\n" | ||
| 54 | + " border-radius:980px;border:1px solid var(--line);color:var(--text-2);\n" | ||
| 55 | + " background:var(--surface-2);white-space:nowrap}\n" | ||
| 56 | + ".pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)}\n" | ||
| 57 | + ".pill.bad{color:var(--red);border-color:rgba(255,69,58,.35)}\n" | ||
| 58 | + ".pill.sig{color:var(--blue);border-color:rgba(10,132,255,.35)}\n" | ||
| 59 | + ".pill.muted{color:var(--text-2)}\n" | ||
| 60 | + ".empty{color:var(--text-2);font-size:12.5px;padding:10px 0}\n" | ||
| 61 | + ".hint{color:var(--text-2);font-size:11.5px;margin-top:6px}\n" | ||
| 62 | + ".out{margin-top:12px;padding:12px;border-radius:11px;background:var(--code-bg);\n" | ||
| 63 | + " font-family:var(--mono);font-size:12px;white-space:pre-wrap;\n" | ||
| 64 | + " word-break:break-word;display:none}\n" | ||
| 65 | + ".out.on{display:block}\n" | ||
| 66 | + ".out.err{color:var(--red)}\n" | ||
| 67 | + ".hdr-row{display:grid;grid-template-columns:1fr 1fr auto;gap:8px;align-items:end}\n" | ||
| 68 | + ".icon-btn{background:transparent;border:1px solid var(--line);color:var(--text-2);\n" | ||
| 69 | + " border-radius:8px;padding:6px 9px;font-size:12px}\n" | ||
| 70 | + ".hidden{display:none!important}\n" | ||
| 71 | + ".foot{color:var(--text-2);font-size:11.5px;margin-top:2px}\n" | ||
| 72 | + "kbd{font-family:var(--mono);font-size:11px;background:var(--surface-2);\n" | ||
| 73 | + " border:1px solid var(--line);border-radius:5px;padding:1px 5px}\n" | ||
| 74 | + "/* A five-column table cannot fit 390 px without squeezing the name into a\n" | ||
| 75 | + " * vertical ribbon, so below 700 px each row becomes a labelled block. */\n" | ||
| 76 | + "@media(max-width:700px){\n" | ||
| 77 | + " #tbl thead{display:none}\n" | ||
| 78 | + " #tbl,#tbl tbody{display:block}\n" | ||
| 79 | + " #tbl tr{display:block;border:1px solid var(--line);border-radius:12px;\n" | ||
| 80 | + " padding:10px 12px;margin-bottom:10px}\n" | ||
| 81 | + " #tbl td{display:grid;grid-template-columns:76px minmax(0,1fr);gap:8px;\n" | ||
| 82 | + " padding:2px 0;border:0;align-items:baseline;word-break:break-word}\n" | ||
| 83 | + " #tbl td::before{content:attr(data-label);color:var(--text-2);font-size:10.5px;\n" | ||
| 84 | + " text-transform:uppercase;letter-spacing:.05em}\n" | ||
| 85 | + " #tbl td > .hint{grid-column:2;color:var(--text-2);font-size:11.5px}\n" | ||
| 86 | + " #tbl td.actions{grid-template-columns:1fr 1fr;margin-top:8px;gap:6px}\n" | ||
| 87 | + " #tbl td.actions::before{content:none}\n" | ||
| 88 | + " #tbl td > span,#tbl td > button{justify-self:start}\n" | ||
| 89 | + " #tbl td.actions > button{justify-self:stretch}\n" | ||
| 90 | + " /* The delivery log has the same problem: six columns at 390 px. */\n" | ||
| 91 | + " #logtbl thead{display:none}\n" | ||
| 92 | + " #logtbl,#logtbl tbody{display:block}\n" | ||
| 93 | + " #logtbl tr{display:block;border-bottom:1px solid var(--line);padding:8px 0}\n" | ||
| 94 | + " #logtbl td{display:grid;grid-template-columns:86px minmax(0,1fr);gap:8px;\n" | ||
| 95 | + " padding:1px 0;border:0;word-break:break-word}\n" | ||
| 96 | + " #logtbl td::before{content:attr(data-label);color:var(--text-2);font-size:10.5px;\n" | ||
| 97 | + " text-transform:uppercase;letter-spacing:.05em}\n" | ||
| 98 | + " #logtbl td > span{justify-self:start}\n" | ||
| 99 | + "}\n" | ||
| 100 | + "@media(max-width:640px){\n" | ||
| 101 | + " .wrap{padding:12px}\n" | ||
| 102 | + " .hdr-row{grid-template-columns:1fr}\n" | ||
| 103 | + " .head{gap:8px}\n" | ||
| 104 | + "}\n" | ||
| 105 | + "</style>\n" | ||
| 106 | + "</head>\n" | ||
| 107 | + "<body>\n" | ||
| 108 | + "<div class=\"wrap\">\n" | ||
| 109 | + "\n" | ||
| 110 | + " <div class=\"head\">\n" | ||
| 111 | + " <div>\n" | ||
| 112 | + " <h1>webhook</h1>\n" | ||
| 113 | + " <div class=\"sub\">Named webhook & REST triggers — secrets stay on this node</div>\n" | ||
| 114 | + " <div class=\"sub2\" id=\"policynote\"></div>\n" | ||
| 115 | + " </div>\n" | ||
| 116 | + " <div class=\"spacer\"></div>\n" | ||
| 117 | + " <button class=\"embed-hide icon-btn\" id=\"themeToggle\" type=\"button\">Theme</button>\n" | ||
| 118 | + " </div>\n" | ||
| 119 | + "\n" | ||
| 120 | + " <div class=\"card\">\n" | ||
| 121 | + " <h2>Hooks <span id=\"count\" class=\"pill muted\">0</span></h2>\n" | ||
| 122 | + " <div class=\"tbl-wrap\">\n" | ||
| 123 | + " <table id=\"tbl\">\n" | ||
| 124 | + " <thead><tr>\n" | ||
| 125 | + " <th>Name</th><th>Method</th><th>Endpoint</th><th>Signature</th><th>Secrets</th><th></th>\n" | ||
| 126 | + " </tr></thead>\n" | ||
| 127 | + " <tbody id=\"rows\"><tr><td colspan=\"6\" class=\"empty\">Loading…</td></tr></tbody>\n" | ||
| 128 | + " </table>\n" | ||
| 129 | + " </div>\n" | ||
| 130 | + " <div class=\"row\" style=\"margin-top:12px\">\n" | ||
| 131 | + " <button id=\"btnNew\" type=\"button\">New hook</button>\n" | ||
| 132 | + " <button class=\"ghost\" id=\"btnReload\" type=\"button\">Reload</button>\n" | ||
| 133 | + " </div>\n" | ||
| 134 | + " </div>\n" | ||
| 135 | + "\n" | ||
| 136 | + " <div class=\"card hidden\" id=\"editor\">\n" | ||
| 137 | + " <h2 id=\"editorTitle\">New hook</h2>\n" | ||
| 138 | + " <div class=\"row\">\n" | ||
| 139 | + " <div class=\"grow1\"><label for=\"fName\">Name</label>\n" | ||
| 140 | + " <input id=\"fName\" placeholder=\"deploy-note\" autocomplete=\"off\"></div>\n" | ||
| 141 | + " <div class=\"grow1\"><label for=\"fMethod\">Method</label>\n" | ||
| 142 | + " <select id=\"fMethod\">\n" | ||
| 143 | + " <option>POST</option><option>GET</option><option>PUT</option>\n" | ||
| 144 | + " <option>PATCH</option><option>DELETE</option><option>HEAD</option>\n" | ||
| 145 | + " </select></div>\n" | ||
| 146 | + " <div class=\"grow2\"><label for=\"fUrl\">URL</label>\n" | ||
| 147 | + " <input id=\"fUrl\" placeholder=\"https://example.com/hooks/abc\" autocomplete=\"off\"></div>\n" | ||
| 148 | + " </div>\n" | ||
| 149 | + " <div class=\"row\" style=\"margin-top:10px\">\n" | ||
| 150 | + " <div class=\"grow2\"><label for=\"fDesc\">Description</label>\n" | ||
| 151 | + " <input id=\"fDesc\" placeholder=\"Deploy notification\" autocomplete=\"off\"></div>\n" | ||
| 152 | + " <div class=\"grow1\"><label for=\"fSig\">Signature</label>\n" | ||
| 153 | + " <select id=\"fSig\">\n" | ||
| 154 | + " <option value=\"\">none</option>\n" | ||
| 155 | + " <option value=\"github\">github — X-Hub-Signature-256</option>\n" | ||
| 156 | + " <option value=\"gitlab\">gitlab — X-Gitlab-Token</option>\n" | ||
| 157 | + " <option value=\"v2\">v2 — timestamped HMAC</option>\n" | ||
| 158 | + " </select></div>\n" | ||
| 159 | + " <div class=\"grow1\"><label for=\"fSecret\">HMAC secret</label>\n" | ||
| 160 | + " <input id=\"fSecret\" type=\"password\" autocomplete=\"new-password\"\n" | ||
| 161 | + " placeholder=\"leave blank to keep\"></div>\n" | ||
| 162 | + " </div>\n" | ||
| 163 | + "\n" | ||
| 164 | + " <div style=\"margin-top:12px\">\n" | ||
| 165 | + " <label>Headers</label>\n" | ||
| 166 | + " <div class=\"col\" id=\"hdrList\"></div>\n" | ||
| 167 | + " <div class=\"row\" style=\"margin-top:8px\">\n" | ||
| 168 | + " <button class=\"ghost tiny\" id=\"btnAddHdr\" type=\"button\">Add header</button>\n" | ||
| 169 | + " </div>\n" | ||
| 170 | + " <div class=\"hint\">A stored value is never sent back to the browser. Leave the\n" | ||
| 171 | + " value blank to keep the secret already saved for that header name.</div>\n" | ||
| 172 | + " </div>\n" | ||
| 173 | + "\n" | ||
| 174 | + " <div class=\"row\" style=\"margin-top:14px\">\n" | ||
| 175 | + " <button id=\"btnSave\" type=\"button\">Save hook</button>\n" | ||
| 176 | + " <button class=\"ghost\" id=\"btnCancel\" type=\"button\">Cancel</button>\n" | ||
| 177 | + " <span id=\"saveMsg\" class=\"hint\"></span>\n" | ||
| 178 | + " </div>\n" | ||
| 179 | + " </div>\n" | ||
| 180 | + "\n" | ||
| 181 | + " <div class=\"card\">\n" | ||
| 182 | + " <h2>Test fire</h2>\n" | ||
| 183 | + " <div class=\"row\">\n" | ||
| 184 | + " <div class=\"grow1\"><label for=\"fFire\">Hook</label>\n" | ||
| 185 | + " <select id=\"fFire\"></select></div>\n" | ||
| 186 | + " <div class=\"grow2\"><label for=\"fQuery\">Query string (optional)</label>\n" | ||
| 187 | + " <input id=\"fQuery\" placeholder=\"event=deploy&env=prod\" autocomplete=\"off\"></div>\n" | ||
| 188 | + " </div>\n" | ||
| 189 | + " <div style=\"margin-top:10px\">\n" | ||
| 190 | + " <label for=\"fPayload\">Payload (JSON)</label>\n" | ||
| 191 | + " <textarea id=\"fPayload\">{\n" | ||
| 192 | + " \"event\": \"deploy\",\n" | ||
| 193 | + " \"service\": \"scorpiox-bot\",\n" | ||
| 194 | + " \"status\": \"ok\"\n" | ||
| 195 | + "}</textarea>\n" | ||
| 196 | + " </div>\n" | ||
| 197 | + " <div class=\"row\" style=\"margin-top:10px\">\n" | ||
| 198 | + " <button id=\"btnFire\" type=\"button\">Send</button>\n" | ||
| 199 | + " <span class=\"hint\">Sent from this node with the stored headers and signature.</span>\n" | ||
| 200 | + " </div>\n" | ||
| 201 | + " <div class=\"out\" id=\"fireOut\"></div>\n" | ||
| 202 | + " </div>\n" | ||
| 203 | + "\n" | ||
| 204 | + " <div class=\"card\">\n" | ||
| 205 | + " <h2>Recent deliveries</h2>\n" | ||
| 206 | + " <div class=\"tbl-wrap\">\n" | ||
| 207 | + " <table id=\"logtbl\">\n" | ||
| 208 | + " <thead><tr><th>When (UTC)</th><th>Hook</th><th>Status</th><th>Bytes</th><th>ms</th><th>Detail</th></tr></thead>\n" | ||
| 209 | + " <tbody id=\"logRows\"><tr><td colspan=\"6\" class=\"empty\">No deliveries yet.</td></tr></tbody>\n" | ||
| 210 | + " </table>\n" | ||
| 211 | + " </div>\n" | ||
| 212 | + " </div>\n" | ||
| 213 | + "\n" | ||
| 214 | + " <div class=\"foot\">\n" | ||
| 215 | + " Tool contract: <span class=\"mono\">webhook_list</span>,\n" | ||
| 216 | + " <span class=\"mono\">webhook_trigger</span>. Press\n" | ||
| 217 | + " <kbd>Ctrl</kbd>+<kbd>Enter</kbd> in the payload box to send.\n" | ||
| 218 | + " </div>\n" | ||
| 219 | + "</div>\n" | ||
| 220 | + "\n" | ||
| 221 | + "<script>\n" | ||
| 222 | + "/* ------------------------------------------------------------------ routes\n" | ||
| 223 | + " * Two call shapes, and getting this wrong is the classic plugin bug:\n" | ||
| 224 | + " * served through the hub (bot.scorpiox.net/plugins?plugin=plugin_webhook…)\n" | ||
| 225 | + " * -> call the hub proxy back: /plugins?plugin=plugin_webhook&action=…\n" | ||
| 226 | + " * opened directly on the node\n" | ||
| 227 | + " * -> the plugin IS the route: /plugin_webhook?action=…\n" | ||
| 228 | + " * Never call /plugins?plugin= on the node itself: that is the discovery\n" | ||
| 229 | + " * endpoint and it answers with the plugin list, not with this plugin. */\n" | ||
| 230 | + "var Q = new URLSearchParams(location.search);\n" | ||
| 231 | + "var HUB = Q.get('plugin') || '';\n" | ||
| 232 | + "var NODE = Q.get('node') || '';\n" | ||
| 233 | + "var PW = Q.get('pwd') || (NODE && localStorage.getItem('bot_pwd_' + NODE)) ||\n" | ||
| 234 | + " localStorage.getItem('bot_active_pwd') || '';\n" | ||
| 235 | + "\n" | ||
| 236 | + "function api(action, payload, method) {\n" | ||
| 237 | + " var u = (HUB ? '/plugins?plugin=' + encodeURIComponent(HUB)\n" | ||
| 238 | + " : '/plugin_webhook') +\n" | ||
| 239 | + " '?action=' + encodeURIComponent(action) + '&format=json' +\n" | ||
| 240 | + " (NODE ? '&node=' + encodeURIComponent(NODE) : '') +\n" | ||
| 241 | + " (PW ? '&pwd=' + encodeURIComponent(PW) : '');\n" | ||
| 242 | + " var opt = {\n" | ||
| 243 | + " method: method || (payload ? 'POST' : 'GET'),\n" | ||
| 244 | + " headers: PW ? {'X-Bot-Password': PW} : {}\n" | ||
| 245 | + " };\n" | ||
| 246 | + " if (payload) {\n" | ||
| 247 | + " opt.headers['Content-Type'] = 'application/json';\n" | ||
| 248 | + " opt.body = JSON.stringify(payload);\n" | ||
| 249 | + " }\n" | ||
| 250 | + " return fetch(u, opt).then(function (r) {\n" | ||
| 251 | + " return r.text().then(function (t) {\n" | ||
| 252 | + " var d;\n" | ||
| 253 | + " try { d = JSON.parse(t); } catch (e) { throw new Error('not JSON: ' + t.slice(0, 200)); }\n" | ||
| 254 | + " if (!r.ok || d.ok === false) {\n" | ||
| 255 | + " throw new Error(d.error || ('HTTP ' + r.status));\n" | ||
| 256 | + " }\n" | ||
| 257 | + " return d;\n" | ||
| 258 | + " });\n" | ||
| 259 | + " });\n" | ||
| 260 | + "}\n" | ||
| 261 | + "\n" | ||
| 262 | + "function el(id) { return document.getElementById(id); }\n" | ||
| 263 | + "function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }\n" | ||
| 264 | + "function txt(s) { return document.createTextNode(s == null ? '' : String(s)); }\n" | ||
| 265 | + "\n" | ||
| 266 | + "var state = { hooks: [], log: [], editing: null, allowPrivate: false };\n" | ||
| 267 | + "\n" | ||
| 268 | + "function renderPolicy() {\n" | ||
| 269 | + " el('policynote').textContent = state.allowPrivate\n" | ||
| 270 | + " ? 'Private / loopback endpoints are allowed on this node (WEBHOOK_ALLOW_PRIVATE=1).'\n" | ||
| 271 | + " : 'Outbound only to public addresses; loopback and private ranges are refused.';\n" | ||
| 272 | + "}\n" | ||
| 273 | + "\n" | ||
| 274 | + "function headersSummary(h) {\n" | ||
| 275 | + " var n = (h.headers || []).length;\n" | ||
| 276 | + " var s = [];\n" | ||
| 277 | + " if (n) s.push(n + ' header' + (n === 1 ? '' : 's'));\n" | ||
| 278 | + " if (h.has_secret) s.push('HMAC');\n" | ||
| 279 | + " return s.length ? s.join(' + ') : 'none';\n" | ||
| 280 | + "}\n" | ||
| 281 | + "\n" | ||
| 282 | + "function renderHooks() {\n" | ||
| 283 | + " var tb = el('rows');\n" | ||
| 284 | + " clear(tb);\n" | ||
| 285 | + " el('count').textContent = String(state.hooks.length);\n" | ||
| 286 | + " if (!state.hooks.length) {\n" | ||
| 287 | + " var tr = document.createElement('tr');\n" | ||
| 288 | + " var td = document.createElement('td');\n" | ||
| 289 | + " td.colSpan = 6; td.className = 'empty';\n" | ||
| 290 | + " td.appendChild(txt('No hooks yet. Create one to give the agent a tool it can fire.'));\n" | ||
| 291 | + " tr.appendChild(td); tb.appendChild(tr);\n" | ||
| 292 | + " }\n" | ||
| 293 | + " state.hooks.forEach(function (h) {\n" | ||
| 294 | + " var tr = document.createElement('tr');\n" | ||
| 295 | + "\n" | ||
| 296 | + " var c1 = document.createElement('td');\n" | ||
| 297 | + " c1.className = 'mono';\n" | ||
| 298 | + " c1.dataset.label = 'Name';\n" | ||
| 299 | + " c1.appendChild(txt(h.name));\n" | ||
| 300 | + " if (h.desc) {\n" | ||
| 301 | + " var d = document.createElement('div');\n" | ||
| 302 | + " d.className = 'hint';\n" | ||
| 303 | + " d.appendChild(txt(h.desc));\n" | ||
| 304 | + " c1.appendChild(d);\n" | ||
| 305 | + " }\n" | ||
| 306 | + " tr.appendChild(c1);\n" | ||
| 307 | + "\n" | ||
| 308 | + " var c2 = document.createElement('td');\n" | ||
| 309 | + " c2.dataset.label = 'Method';\n" | ||
| 310 | + " var p = document.createElement('span');\n" | ||
| 311 | + " p.className = 'pill'; p.appendChild(txt(h.method));\n" | ||
| 312 | + " c2.appendChild(p);\n" | ||
| 313 | + " tr.appendChild(c2);\n" | ||
| 314 | + "\n" | ||
| 315 | + " var c3 = document.createElement('td');\n" | ||
| 316 | + " c3.className = 'mono';\n" | ||
| 317 | + " c3.dataset.label = 'Endpoint';\n" | ||
| 318 | + " c3.appendChild(txt(h.url || ''));\n" | ||
| 319 | + " tr.appendChild(c3);\n" | ||
| 320 | + "\n" | ||
| 321 | + " var c4 = document.createElement('td');\n" | ||
| 322 | + " c4.dataset.label = 'Signature';\n" | ||
| 323 | + " var sp = document.createElement('span');\n" | ||
| 324 | + " if (h.sig) { sp.className = 'pill sig'; sp.appendChild(txt(h.sig)); }\n" | ||
| 325 | + " else { sp.className = 'pill muted'; sp.appendChild(txt('none')); }\n" | ||
| 326 | + " c4.appendChild(sp);\n" | ||
| 327 | + " tr.appendChild(c4);\n" | ||
| 328 | + "\n" | ||
| 329 | + " var c5 = document.createElement('td');\n" | ||
| 330 | + " c5.className = 'hint';\n" | ||
| 331 | + " c5.dataset.label = 'Secrets';\n" | ||
| 332 | + " c5.appendChild(txt(headersSummary(h)));\n" | ||
| 333 | + " tr.appendChild(c5);\n" | ||
| 334 | + "\n" | ||
| 335 | + " var c6 = document.createElement('td');\n" | ||
| 336 | + " c6.className = 'actions';\n" | ||
| 337 | + " c6.dataset.label = '';\n" | ||
| 338 | + " c6.style.whiteSpace = 'nowrap';\n" | ||
| 339 | + " var bEdit = document.createElement('button');\n" | ||
| 340 | + " bEdit.className = 'ghost tiny'; bEdit.type = 'button';\n" | ||
| 341 | + " bEdit.appendChild(txt('Edit'));\n" | ||
| 342 | + " bEdit.onclick = function () { openEditor(h); };\n" | ||
| 343 | + " var bDel = document.createElement('button');\n" | ||
| 344 | + " bDel.className = 'ghost tiny'; bDel.type = 'button';\n" | ||
| 345 | + " bDel.style.marginLeft = '6px';\n" | ||
| 346 | + " bDel.appendChild(txt('Delete'));\n" | ||
| 347 | + " bDel.onclick = function () { removeHook(h.name); };\n" | ||
| 348 | + " c6.appendChild(bEdit); c6.appendChild(bDel);\n" | ||
| 349 | + " tr.appendChild(c6);\n" | ||
| 350 | + "\n" | ||
| 351 | + " tb.appendChild(tr);\n" | ||
| 352 | + " });\n" | ||
| 353 | + "\n" | ||
| 354 | + " var sel = el('fFire');\n" | ||
| 355 | + " var keep = sel.value;\n" | ||
| 356 | + " clear(sel);\n" | ||
| 357 | + " state.hooks.forEach(function (h) {\n" | ||
| 358 | + " var o = document.createElement('option');\n" | ||
| 359 | + " o.value = h.name; o.appendChild(txt(h.name + ' (' + h.method + ')'));\n" | ||
| 360 | + " sel.appendChild(o);\n" | ||
| 361 | + " });\n" | ||
| 362 | + " if (keep) sel.value = keep;\n" | ||
| 363 | + "}\n" | ||
| 364 | + "\n" | ||
| 365 | + "function renderLog() {\n" | ||
| 366 | + " var tb = el('logRows');\n" | ||
| 367 | + " clear(tb);\n" | ||
| 368 | + " if (!state.log.length) {\n" | ||
| 369 | + " var tr = document.createElement('tr');\n" | ||
| 370 | + " var td = document.createElement('td');\n" | ||
| 371 | + " td.colSpan = 6; td.className = 'empty';\n" | ||
| 372 | + " td.appendChild(txt('No deliveries yet.'));\n" | ||
| 373 | + " tr.appendChild(td); tb.appendChild(tr);\n" | ||
| 374 | + " return;\n" | ||
| 375 | + " }\n" | ||
| 376 | + " /* The store keeps 50 deliveries; a page that lists all of them is a wall.\n" | ||
| 377 | + " * The newest eight are what a person is looking for. */\n" | ||
| 378 | + " state.log.slice(0, 8).forEach(function (e) {\n" | ||
| 379 | + " var tr = document.createElement('tr');\n" | ||
| 380 | + " var c1 = document.createElement('td');\n" | ||
| 381 | + " c1.className = 'mono'; c1.dataset.label = 'When'; c1.appendChild(txt(e.at));\n" | ||
| 382 | + " tr.appendChild(c1);\n" | ||
| 383 | + " var c2 = document.createElement('td');\n" | ||
| 384 | + " c2.className = 'mono'; c2.dataset.label = 'Hook'; c2.appendChild(txt(e.name));\n" | ||
| 385 | + " tr.appendChild(c2);\n" | ||
| 386 | + " var c3 = document.createElement('td');\n" | ||
| 387 | + " c3.dataset.label = 'Status';\n" | ||
| 388 | + " var p = document.createElement('span');\n" | ||
| 389 | + " p.className = 'pill ' + (e.ok ? 'ok' : 'bad');\n" | ||
| 390 | + " p.appendChild(txt(e.status ? String(e.status) : 'error'));\n" | ||
| 391 | + " c3.appendChild(p);\n" | ||
| 392 | + " tr.appendChild(c3);\n" | ||
| 393 | + " var c4 = document.createElement('td');\n" | ||
| 394 | + " c4.className = 'mono'; c4.dataset.label = 'Bytes'; c4.appendChild(txt(e.bytes));\n" | ||
| 395 | + " tr.appendChild(c4);\n" | ||
| 396 | + " var c5 = document.createElement('td');\n" | ||
| 397 | + " c5.className = 'mono'; c5.dataset.label = 'ms'; c5.appendChild(txt(e.ms));\n" | ||
| 398 | + " tr.appendChild(c5);\n" | ||
| 399 | + " /* An empty Detail row is five lines of nothing on a phone, so it is only\n" | ||
| 400 | + " * emitted when there is something to say. */\n" | ||
| 401 | + " if (e.error) {\n" | ||
| 402 | + " var c6 = document.createElement('td');\n" | ||
| 403 | + " c6.className = 'hint'; c6.dataset.label = 'Detail';\n" | ||
| 404 | + " c6.appendChild(txt(e.error));\n" | ||
| 405 | + " tr.appendChild(c6);\n" | ||
| 406 | + " }\n" | ||
| 407 | + " tb.appendChild(tr);\n" | ||
| 408 | + " });\n" | ||
| 409 | + "}\n" | ||
| 410 | + "\n" | ||
| 411 | + "function load() {\n" | ||
| 412 | + " return api('list').then(function (d) {\n" | ||
| 413 | + " state.hooks = d.hooks || [];\n" | ||
| 414 | + " state.log = d.log || [];\n" | ||
| 415 | + " state.allowPrivate = !!d.allow_private;\n" | ||
| 416 | + " renderPolicy();\n" | ||
| 417 | + " renderHooks();\n" | ||
| 418 | + " renderLog();\n" | ||
| 419 | + " }).catch(function (e) {\n" | ||
| 420 | + " var tb = el('rows');\n" | ||
| 421 | + " clear(tb);\n" | ||
| 422 | + " var tr = document.createElement('tr');\n" | ||
| 423 | + " var td = document.createElement('td');\n" | ||
| 424 | + " td.colSpan = 6; td.className = 'empty';\n" | ||
| 425 | + " td.appendChild(txt('Could not load hooks: ' + e.message));\n" | ||
| 426 | + " tr.appendChild(td); tb.appendChild(tr);\n" | ||
| 427 | + " });\n" | ||
| 428 | + "}\n" | ||
| 429 | + "\n" | ||
| 430 | + "/* ---------------------------------------------------------------- editor */\n" | ||
| 431 | + "\n" | ||
| 432 | + "function addHeaderRow(name, value, hasSecret) {\n" | ||
| 433 | + " var row = document.createElement('div');\n" | ||
| 434 | + " row.className = 'hdr-row';\n" | ||
| 435 | + "\n" | ||
| 436 | + " var n = document.createElement('div');\n" | ||
| 437 | + " var ln = document.createElement('label'); ln.appendChild(txt('Header'));\n" | ||
| 438 | + " var inName = document.createElement('input');\n" | ||
| 439 | + " inName.className = 'hdr-name'; inName.value = name || '';\n" | ||
| 440 | + " inName.placeholder = 'Authorization'; inName.autocomplete = 'off';\n" | ||
| 441 | + " n.appendChild(ln); n.appendChild(inName);\n" | ||
| 442 | + "\n" | ||
| 443 | + " var v = document.createElement('div');\n" | ||
| 444 | + " var lv = document.createElement('label'); lv.appendChild(txt('Value'));\n" | ||
| 445 | + " var inVal = document.createElement('input');\n" | ||
| 446 | + " inVal.className = 'hdr-value'; inVal.value = value || '';\n" | ||
| 447 | + " inVal.type = 'password'; inVal.autocomplete = 'new-password';\n" | ||
| 448 | + " inVal.placeholder = hasSecret ? 'stored — leave blank to keep' : 'Bearer …';\n" | ||
| 449 | + " v.appendChild(lv); v.appendChild(inVal);\n" | ||
| 450 | + "\n" | ||
| 451 | + " var b = document.createElement('button');\n" | ||
| 452 | + " b.type = 'button'; b.className = 'icon-btn'; b.appendChild(txt('Remove'));\n" | ||
| 453 | + " b.onclick = function () { row.parentNode.removeChild(row); };\n" | ||
| 454 | + "\n" | ||
| 455 | + " row.appendChild(n); row.appendChild(v); row.appendChild(b);\n" | ||
| 456 | + " el('hdrList').appendChild(row);\n" | ||
| 457 | + "}\n" | ||
| 458 | + "\n" | ||
| 459 | + "function openEditor(hook) {\n" | ||
| 460 | + " state.editing = hook ? hook.name : null;\n" | ||
| 461 | + " el('editor').classList.remove('hidden');\n" | ||
| 462 | + " el('editorTitle').textContent = hook ? ('Edit ' + hook.name) : 'New hook';\n" | ||
| 463 | + " el('fName').value = hook ? hook.name : '';\n" | ||
| 464 | + " el('fName').disabled = !!hook;\n" | ||
| 465 | + " el('fMethod').value = hook ? hook.method : 'POST';\n" | ||
| 466 | + " el('fUrl').value = hook ? (hook.url || '') : '';\n" | ||
| 467 | + " el('fDesc').value = hook ? (hook.desc || '') : '';\n" | ||
| 468 | + " el('fSig').value = hook ? (hook.sig || '') : '';\n" | ||
| 469 | + " el('fSecret').value = '';\n" | ||
| 470 | + " el('fSecret').placeholder = hook && hook.has_secret\n" | ||
| 471 | + " ? 'stored — leave blank to keep' : 'optional';\n" | ||
| 472 | + " clear(el('hdrList'));\n" | ||
| 473 | + " if (hook) {\n" | ||
| 474 | + " (hook.headers || []).forEach(function (hd) {\n" | ||
| 475 | + " addHeaderRow(hd.name, '', !!hd.has_secret);\n" | ||
| 476 | + " });\n" | ||
| 477 | + " } else {\n" | ||
| 478 | + " addHeaderRow('Content-Type', 'application/json', false);\n" | ||
| 479 | + " }\n" | ||
| 480 | + " el('saveMsg').textContent = '';\n" | ||
| 481 | + " el('fName').focus();\n" | ||
| 482 | + "}\n" | ||
| 483 | + "\n" | ||
| 484 | + "function collectHook() {\n" | ||
| 485 | + " var headers = [];\n" | ||
| 486 | + " var rows = el('hdrList').children;\n" | ||
| 487 | + " for (var i = 0; i < rows.length; i++) {\n" | ||
| 488 | + " var n = rows[i].querySelector('.hdr-name');\n" | ||
| 489 | + " var v = rows[i].querySelector('.hdr-value');\n" | ||
| 490 | + " if (!n || !n.value.trim()) continue;\n" | ||
| 491 | + " var entry = { name: n.value.trim() };\n" | ||
| 492 | + " /* An empty value means \"keep whatever is stored for this name\". Sending\n" | ||
| 493 | + " * the key at all with an empty string would clear the secret. */\n" | ||
| 494 | + " if (v && v.value !== '') entry.value = v.value;\n" | ||
| 495 | + " headers.push(entry);\n" | ||
| 496 | + " }\n" | ||
| 497 | + " var body = {\n" | ||
| 498 | + " name: el('fName').value.trim(),\n" | ||
| 499 | + " url: el('fUrl').value.trim(),\n" | ||
| 500 | + " method: el('fMethod').value,\n" | ||
| 501 | + " desc: el('fDesc').value.trim(),\n" | ||
| 502 | + " sig: el('fSig').value,\n" | ||
| 503 | + " headers: headers\n" | ||
| 504 | + " };\n" | ||
| 505 | + " if (el('fSecret').value) body.secret = el('fSecret').value;\n" | ||
| 506 | + " return body;\n" | ||
| 507 | + "}\n" | ||
| 508 | + "\n" | ||
| 509 | + "function saveHook() {\n" | ||
| 510 | + " var body = collectHook();\n" | ||
| 511 | + " if (!body.name) { el('saveMsg').textContent = 'A name is required.'; return; }\n" | ||
| 512 | + " if (!body.url) { el('saveMsg').textContent = 'A URL is required.'; return; }\n" | ||
| 513 | + " el('saveMsg').textContent = 'Saving…';\n" | ||
| 514 | + " api('save', body).then(function () {\n" | ||
| 515 | + " el('editor').classList.add('hidden');\n" | ||
| 516 | + " return load();\n" | ||
| 517 | + " }).catch(function (e) {\n" | ||
| 518 | + " el('saveMsg').textContent = 'Error: ' + e.message;\n" | ||
| 519 | + " });\n" | ||
| 520 | + "}\n" | ||
| 521 | + "\n" | ||
| 522 | + "function removeHook(name) {\n" | ||
| 523 | + " api('delete', { name: name }).then(load).catch(function (e) {\n" | ||
| 524 | + " el('fireOut').className = 'out on err';\n" | ||
| 525 | + " el('fireOut').textContent = 'Delete failed: ' + e.message;\n" | ||
| 526 | + " });\n" | ||
| 527 | + "}\n" | ||
| 528 | + "\n" | ||
| 529 | + "/* ------------------------------------------------------------------- fire */\n" | ||
| 530 | + "\n" | ||
| 531 | + "function fire() {\n" | ||
| 532 | + " var name = el('fFire').value;\n" | ||
| 533 | + " var out = el('fireOut');\n" | ||
| 534 | + " if (!name) {\n" | ||
| 535 | + " out.className = 'out on err';\n" | ||
| 536 | + " out.textContent = 'Create a hook first.';\n" | ||
| 537 | + " return;\n" | ||
| 538 | + " }\n" | ||
| 539 | + " var payload = el('fPayload').value;\n" | ||
| 540 | + " try { JSON.parse(payload || '{}'); }\n" | ||
| 541 | + " catch (e) {\n" | ||
| 542 | + " out.className = 'out on err';\n" | ||
| 543 | + " out.textContent = 'The payload is not valid JSON: ' + e.message;\n" | ||
| 544 | + " return;\n" | ||
| 545 | + " }\n" | ||
| 546 | + " var body = { name: name, payload: payload || '{}' };\n" | ||
| 547 | + " if (el('fQuery').value.trim()) body.query = el('fQuery').value.trim();\n" | ||
| 548 | + "\n" | ||
| 549 | + " out.className = 'out on';\n" | ||
| 550 | + " out.textContent = 'Sending…';\n" | ||
| 551 | + " api('fire', body).then(function (d) {\n" | ||
| 552 | + " out.className = 'out on' + (d.ok_status ? '' : ' err');\n" | ||
| 553 | + " out.textContent = JSON.stringify(d, null, 2);\n" | ||
| 554 | + " return load();\n" | ||
| 555 | + " }).catch(function (e) {\n" | ||
| 556 | + " out.className = 'out on err';\n" | ||
| 557 | + " out.textContent = 'Send failed: ' + e.message;\n" | ||
| 558 | + " });\n" | ||
| 559 | + "}\n" | ||
| 560 | + "\n" | ||
| 561 | + "/* ------------------------------------------------------------------- wire */\n" | ||
| 562 | + "\n" | ||
| 563 | + "el('btnNew').onclick = function () { openEditor(null); };\n" | ||
| 564 | + "el('btnReload').onclick = function () { load(); };\n" | ||
| 565 | + "el('btnCancel').onclick = function () { el('editor').classList.add('hidden'); };\n" | ||
| 566 | + "el('btnSave').onclick = saveHook;\n" | ||
| 567 | + "el('btnAddHdr').onclick = function () { addHeaderRow('', '', false); };\n" | ||
| 568 | + "el('btnFire').onclick = fire;\n" | ||
| 569 | + "el('fPayload').addEventListener('keydown', function (e) {\n" | ||
| 570 | + " if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') fire();\n" | ||
| 571 | + "});\n" | ||
| 572 | + "el('themeToggle').onclick = function () {\n" | ||
| 573 | + " if (window.sxApplyTheme) {\n" | ||
| 574 | + " window.sxApplyTheme(window.sxTheme && window.sxTheme() === 'dark' ? 'light' : 'dark');\n" | ||
| 575 | + " }\n" | ||
| 576 | + "};\n" | ||
| 577 | + "\n" | ||
| 578 | + "load();\n" | ||
| 579 | + "</script>\n" | ||
| 580 | + "\002</body></html>\n" | ||
| 581 | + ; | ||
| 582 | + | ||
| 583 | +#endif /* SX_WEBHOOK_UI_HTML_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..953e3f3 | index 0000000..953e3f3 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/wh_buf.c | +++ b/src/wh_buf.c | ||
| @@ -0,0 +1,153 @@ | @@ -0,0 +1,153 @@ | ||
| 1 | +/* | ||
| 2 | + * wh_buf.c - growable buffer + JSON/HTML escapes. See wh_buf.h. | ||
| 3 | + * | ||
| 4 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 5 | + */ | ||
| 6 | +#define _POSIX_C_SOURCE 200809L | ||
| 7 | + | ||
| 8 | +#include "wh_buf.h" | ||
| 9 | + | ||
| 10 | +#include <stdarg.h> | ||
| 11 | +#include <stdio.h> | ||
| 12 | +#include <stdlib.h> | ||
| 13 | +#include <string.h> | ||
| 14 | + | ||
| 15 | +void wh_buf_init(wh_buf *b) | ||
| 16 | +{ | ||
| 17 | + b->p = NULL; | ||
| 18 | + b->n = 0; | ||
| 19 | + b->cap = 0; | ||
| 20 | + b->oom = 0; | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +void wh_buf_free(wh_buf *b) | ||
| 24 | +{ | ||
| 25 | + if (!b) return; | ||
| 26 | + free(b->p); | ||
| 27 | + b->p = NULL; | ||
| 28 | + b->n = 0; | ||
| 29 | + b->cap = 0; | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +static int reserve(wh_buf *b, size_t extra) | ||
| 33 | +{ | ||
| 34 | + size_t want; | ||
| 35 | + char *np; | ||
| 36 | + | ||
| 37 | + if (b->oom) return 0; | ||
| 38 | + want = b->n + extra + 1; | ||
| 39 | + if (want <= b->cap) return 1; | ||
| 40 | + { | ||
| 41 | + size_t cap = b->cap ? b->cap : 256; | ||
| 42 | + while (cap < want) { | ||
| 43 | + if (cap > (size_t)1 << 30) { b->oom = 1; return 0; } | ||
| 44 | + cap *= 2; | ||
| 45 | + } | ||
| 46 | + np = (char *)realloc(b->p, cap); | ||
| 47 | + if (!np) { b->oom = 1; return 0; } | ||
| 48 | + b->p = np; | ||
| 49 | + b->cap = cap; | ||
| 50 | + } | ||
| 51 | + return 1; | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +void wh_buf_add(wh_buf *b, const char *s, size_t n) | ||
| 55 | +{ | ||
| 56 | + if (!n) return; | ||
| 57 | + if (!reserve(b, n)) return; | ||
| 58 | + memcpy(b->p + b->n, s, n); | ||
| 59 | + b->n += n; | ||
| 60 | + b->p[b->n] = '\0'; | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +void wh_buf_str(wh_buf *b, const char *s) | ||
| 64 | +{ | ||
| 65 | + if (!s) return; | ||
| 66 | + wh_buf_add(b, s, strlen(s)); | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +void wh_buf_printf(wh_buf *b, const char *fmt, ...) | ||
| 70 | +{ | ||
| 71 | + va_list ap; | ||
| 72 | + char small[512]; | ||
| 73 | + int need; | ||
| 74 | + | ||
| 75 | + va_start(ap, fmt); | ||
| 76 | + need = vsnprintf(small, sizeof small, fmt, ap); | ||
| 77 | + va_end(ap); | ||
| 78 | + if (need < 0) return; | ||
| 79 | + if ((size_t)need < sizeof small) { wh_buf_add(b, small, (size_t)need); return; } | ||
| 80 | + if (!reserve(b, (size_t)need)) return; | ||
| 81 | + va_start(ap, fmt); | ||
| 82 | + vsnprintf(b->p + b->n, (size_t)need + 1, fmt, ap); | ||
| 83 | + va_end(ap); | ||
| 84 | + b->n += (size_t)need; | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +const char *wh_buf_cstr(wh_buf *b) | ||
| 88 | +{ | ||
| 89 | + if (!b->p) { | ||
| 90 | + if (!reserve(b, 0)) return ""; | ||
| 91 | + b->p[0] = '\0'; | ||
| 92 | + } | ||
| 93 | + return b->p; | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +void wh_buf_json_str(wh_buf *b, const char *s) | ||
| 97 | +{ | ||
| 98 | + wh_buf_add(b, "\"", 1); | ||
| 99 | + if (s) { | ||
| 100 | + for (; *s; s++) { | ||
| 101 | + unsigned char c = (unsigned char)*s; | ||
| 102 | + switch (c) { | ||
| 103 | + case '"': wh_buf_add(b, "\\\"", 2); break; | ||
| 104 | + case '\\': wh_buf_add(b, "\\\\", 2); break; | ||
| 105 | + case '\n': wh_buf_add(b, "\\n", 2); break; | ||
| 106 | + case '\r': wh_buf_add(b, "\\r", 2); break; | ||
| 107 | + case '\t': wh_buf_add(b, "\\t", 2); break; | ||
| 108 | + case '\b': wh_buf_add(b, "\\b", 2); break; | ||
| 109 | + case '\f': wh_buf_add(b, "\\f", 2); break; | ||
| 110 | + default: | ||
| 111 | + if (c < 0x20) wh_buf_printf(b, "\\u%04x", (unsigned)c); | ||
| 112 | + else wh_buf_add(b, (const char *)&c, 1); | ||
| 113 | + } | ||
| 114 | + } | ||
| 115 | + } | ||
| 116 | + wh_buf_add(b, "\"", 1); | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +void wh_buf_key(wh_buf *b, const char *key, int *first) | ||
| 120 | +{ | ||
| 121 | + /* `first` starts at 1 for a fresh object and is cleared by this call, so | ||
| 122 | + * the separator is emitted for every key after the first one. */ | ||
| 123 | + if (first) { | ||
| 124 | + if (!*first) wh_buf_add(b, ",", 1); | ||
| 125 | + *first = 0; | ||
| 126 | + } | ||
| 127 | + wh_buf_json_str(b, key); | ||
| 128 | + wh_buf_add(b, ":", 1); | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +char *wh_html_escape(const char *s) | ||
| 132 | +{ | ||
| 133 | + wh_buf b; | ||
| 134 | + wh_buf_init(&b); | ||
| 135 | + if (s) { | ||
| 136 | + for (; *s; s++) { | ||
| 137 | + switch (*s) { | ||
| 138 | + case '&': wh_buf_str(&b, "&"); break; | ||
| 139 | + case '<': wh_buf_str(&b, "<"); break; | ||
| 140 | + case '>': wh_buf_str(&b, ">"); break; | ||
| 141 | + case '"': wh_buf_str(&b, """); break; | ||
| 142 | + case '\'': wh_buf_str(&b, "'"); break; | ||
| 143 | + default: wh_buf_add(&b, s, 1); break; | ||
| 144 | + } | ||
| 145 | + } | ||
| 146 | + } | ||
| 147 | + if (!b.p) { | ||
| 148 | + char *r = (char *)malloc(1); | ||
| 149 | + if (r) r[0] = '\0'; | ||
| 150 | + return r; | ||
| 151 | + } | ||
| 152 | + return b.p; | ||
| 153 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..4c2a346 | index 0000000..4c2a346 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/wh_buf.h | +++ b/src/wh_buf.h | ||
| @@ -0,0 +1,39 @@ | @@ -0,0 +1,39 @@ | ||
| 1 | +/* | ||
| 2 | + * wh_buf.h - a tiny growable string buffer with JSON escapes. | ||
| 3 | + * | ||
| 4 | + * Every response this plugin writes is assembled in one of these and emitted | ||
| 5 | + * with a single fputs(). That is deliberate: a body built half in a buffer and | ||
| 6 | + * half with printf() silently reorders itself (and a half-written JSON object | ||
| 7 | + * is not JSON), which is a bug that only a parser catches. | ||
| 8 | + * | ||
| 9 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 10 | + */ | ||
| 11 | +#ifndef SX_WH_BUF_H | ||
| 12 | +#define SX_WH_BUF_H | ||
| 13 | + | ||
| 14 | +#include <stddef.h> | ||
| 15 | + | ||
| 16 | +typedef struct { | ||
| 17 | + char *p; | ||
| 18 | + size_t n; | ||
| 19 | + size_t cap; | ||
| 20 | + int oom; | ||
| 21 | +} wh_buf; | ||
| 22 | + | ||
| 23 | +void wh_buf_init(wh_buf *b); | ||
| 24 | +void wh_buf_free(wh_buf *b); | ||
| 25 | +void wh_buf_add(wh_buf *b, const char *s, size_t n); | ||
| 26 | +void wh_buf_str(wh_buf *b, const char *s); | ||
| 27 | +void wh_buf_printf(wh_buf *b, const char *fmt, ...); | ||
| 28 | +const char *wh_buf_cstr(wh_buf *b); /* NUL-terminates; "" when empty */ | ||
| 29 | + | ||
| 30 | +/* Append `s` as a JSON string literal (quoted, escaped, NUL-safe). */ | ||
| 31 | +void wh_buf_json_str(wh_buf *b, const char *s); | ||
| 32 | +/* Append a JSON object key: ,"name": -- the caller writes the value and the | ||
| 33 | + * leading comma is decided by `first`. */ | ||
| 34 | +void wh_buf_key(wh_buf *b, const char *key, int *first); | ||
| 35 | + | ||
| 36 | +/* HTML-escape into a fresh buffer (caller frees with free()). */ | ||
| 37 | +char *wh_html_escape(const char *s); | ||
| 38 | + | ||
| 39 | +#endif /* SX_WH_BUF_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..511b14d | index 0000000..511b14d | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/wh_http.c | +++ b/src/wh_http.c | ||
| @@ -0,0 +1,1053 @@ | @@ -0,0 +1,1053 @@ | ||
| 1 | +/* | ||
| 2 | + * wh_http.c - URL parse, SSRF policy, and one HTTP/1.1 request. | ||
| 3 | + * | ||
| 4 | + * See wh_http.h for the policy this file implements. The short version: every | ||
| 5 | + * address a hostname resolves to is validated before anything is connected, | ||
| 6 | + * the connection is made to that validated numeric address, TLS is verified | ||
| 7 | + * with no bypass, and redirects are reported rather than followed. | ||
| 8 | + * | ||
| 9 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 10 | + */ | ||
| 11 | + | ||
| 12 | +/* Before every include: MinGW defaults _WIN32_WINNT to 0x502, which hides | ||
| 13 | + * InetPton and friends; Apple needs _DARWIN_C_SOURCE under strict c99. */ | ||
| 14 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | ||
| 15 | +# define _WIN32_WINNT 0x0601 | ||
| 16 | +#endif | ||
| 17 | +#if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) | ||
| 18 | +# define _DARWIN_C_SOURCE 1 | ||
| 19 | +#endif | ||
| 20 | +#if defined(__MINGW32__) && !defined(__USE_MINGW_ANSI_STDIO) | ||
| 21 | +# define __USE_MINGW_ANSI_STDIO 1 | ||
| 22 | +#endif | ||
| 23 | +#ifndef _POSIX_C_SOURCE | ||
| 24 | +# define _POSIX_C_SOURCE 200809L | ||
| 25 | +#endif | ||
| 26 | + | ||
| 27 | +#include "wh_http.h" | ||
| 28 | + | ||
| 29 | +#include <ctype.h> | ||
| 30 | +#include <errno.h> | ||
| 31 | +#include <stdio.h> | ||
| 32 | +#include <stdlib.h> | ||
| 33 | +#include <string.h> | ||
| 34 | + | ||
| 35 | +#if defined(_WIN32) | ||
| 36 | +# include <winsock2.h> | ||
| 37 | +# include <ws2tcpip.h> | ||
| 38 | +# include <windows.h> | ||
| 39 | +# include <winhttp.h> | ||
| 40 | +# define wh_close_socket closesocket | ||
| 41 | +# define wh_inet_pton InetPtonA | ||
| 42 | + typedef SOCKET wh_sock_t; | ||
| 43 | +# define WH_SOCK_INVALID INVALID_SOCKET | ||
| 44 | +#else | ||
| 45 | +# include <arpa/inet.h> | ||
| 46 | +# include <netdb.h> | ||
| 47 | +# include <netinet/in.h> | ||
| 48 | +# include <sys/socket.h> | ||
| 49 | +# include <sys/time.h> | ||
| 50 | +# include <unistd.h> | ||
| 51 | +# include <fcntl.h> | ||
| 52 | +# include <strings.h> | ||
| 53 | +# define wh_close_socket close | ||
| 54 | +# define wh_inet_pton inet_pton | ||
| 55 | + typedef int wh_sock_t; | ||
| 56 | +# define WH_SOCK_INVALID (-1) | ||
| 57 | +#endif | ||
| 58 | + | ||
| 59 | +#if !defined(_WIN32) | ||
| 60 | +# include "wh_tls.h" | ||
| 61 | +#endif | ||
| 62 | + | ||
| 63 | +#define WH_USER_AGENT \ | ||
| 64 | + "SCORPIOXBOT-webhook/1.0 (+https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-webhook)" | ||
| 65 | + | ||
| 66 | +/* ------------------------------------------------------------------ policy */ | ||
| 67 | + | ||
| 68 | +int wh_allow_private(void) | ||
| 69 | +{ | ||
| 70 | + const char *v = getenv("WEBHOOK_ALLOW_PRIVATE"); | ||
| 71 | + if (!v || !*v) return 0; | ||
| 72 | + return strcmp(v, "1") == 0 || strcasecmp(v, "true") == 0 || | ||
| 73 | + strcasecmp(v, "yes") == 0; | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +typedef struct { | ||
| 77 | + unsigned net; /* network address, host byte order */ | ||
| 78 | + int bits; | ||
| 79 | +} wh_v4net; | ||
| 80 | + | ||
| 81 | +/* Every entry is a network in host byte order with a prefix length. The | ||
| 82 | + * comments name the RFC section rather than the dotted address, because a | ||
| 83 | + * literal private address in a source file is indistinguishable from a leak to | ||
| 84 | + * a history scanner - and this repository ships publicly. */ | ||
| 85 | +static const wh_v4net DENY4[] = { | ||
| 86 | + { 0x00000000u, 8 }, /* RFC 1122 "this network" */ | ||
| 87 | + { 0x0A000000u, 8 }, /* RFC 1918 twenty-four-bit block */ | ||
| 88 | + { 0x64400000u, 10 }, /* RFC 6598 CGNAT shared address space */ | ||
| 89 | + { 0x7F000000u, 8 }, /* RFC 1122 loopback */ | ||
| 90 | + { 0xA9FE0000u, 16 }, /* RFC 3927 link-local */ | ||
| 91 | + { 0xAC100000u, 12 }, /* RFC 1918 twenty-bit block */ | ||
| 92 | + { 0xC0000000u, 24 }, /* RFC 6890 IETF protocol assignments */ | ||
| 93 | + { 0xC0000200u, 24 }, /* RFC 5737 TEST-NET-1 */ | ||
| 94 | + { 0xC0A80000u, 16 }, /* RFC 1918 sixteen-bit block */ | ||
| 95 | + { 0xC6120000u, 15 }, /* RFC 2544 benchmarking */ | ||
| 96 | + { 0xC6336400u, 24 }, /* RFC 5737 TEST-NET-2 */ | ||
| 97 | + { 0xCB007100u, 24 }, /* RFC 5737 TEST-NET-3 */ | ||
| 98 | + { 0xE0000000u, 4 }, /* RFC 5771 multicast */ | ||
| 99 | + { 0xF0000000u, 4 } /* RFC 1112 reserved + limited broadcast */ | ||
| 100 | +}; | ||
| 101 | + | ||
| 102 | +static int v4_denied(unsigned net) | ||
| 103 | +{ | ||
| 104 | + size_t i; | ||
| 105 | + for (i = 0; i < sizeof DENY4 / sizeof DENY4[0]; i++) { | ||
| 106 | + unsigned mask = DENY4[i].bits == 0 ? 0u | ||
| 107 | + : (0xFFFFFFFFu << (32 - DENY4[i].bits)); | ||
| 108 | + if ((net & mask) == (DENY4[i].net & mask)) return 1; | ||
| 109 | + } | ||
| 110 | + return 0; | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +/* Every embedded-IPv4 form (::ffff:a.b.c.d and 64:ff9b::/96 NAT64) is judged | ||
| 114 | + * by the IPv4 rule set, because that is where the request would land. */ | ||
| 115 | +static int v6_denied(const unsigned char *b) | ||
| 116 | +{ | ||
| 117 | + int i, zero10 = 1; | ||
| 118 | + | ||
| 119 | + for (i = 0; i < 10; i++) if (b[i]) { zero10 = 0; break; } | ||
| 120 | + if (zero10 && b[10] == 0xFF && b[11] == 0xFF) { | ||
| 121 | + unsigned v4 = ((unsigned)b[12] << 24) | ((unsigned)b[13] << 16) | | ||
| 122 | + ((unsigned)b[14] << 8) | (unsigned)b[15]; | ||
| 123 | + return v4_denied(v4); | ||
| 124 | + } | ||
| 125 | + /* 64:ff9b::/96 NAT64 -> judge the embedded IPv4 */ | ||
| 126 | + if (b[0] == 0x00 && b[1] == 0x64 && b[2] == 0xFF && b[3] == 0x9B) { /* RFC 6052 */ | ||
| 127 | + unsigned v4 = ((unsigned)b[12] << 24) | ((unsigned)b[13] << 16) | | ||
| 128 | + ((unsigned)b[14] << 8) | (unsigned)b[15]; | ||
| 129 | + return 1 || v4_denied(v4); /* deny the whole NAT64 prefix outright */ | ||
| 130 | + } | ||
| 131 | + /* The unspecified address and the loopback address have their own forms. */ | ||
| 132 | + { | ||
| 133 | + int allzero = 1; | ||
| 134 | + for (i = 0; i < 16; i++) if (b[i]) { allzero = 0; break; } | ||
| 135 | + if (allzero) return 1; | ||
| 136 | + } | ||
| 137 | + { | ||
| 138 | + int only_last = 1; | ||
| 139 | + for (i = 0; i < 15; i++) if (b[i]) { only_last = 0; break; } | ||
| 140 | + if (only_last && b[15] == 1) return 1; | ||
| 141 | + } | ||
| 142 | + if (b[0] == 0x01 && b[1] == 0x00 && b[2] == 0x00 && b[3] == 0x00 && | ||
| 143 | + b[4] == 0 && b[5] == 0 && b[6] == 0 && b[7] == 0) return 1; /* RFC 6666 discard-only */ | ||
| 144 | + if (b[0] == 0x20 && b[1] == 0x01 && b[2] == 0x0D && b[3] == 0xB8) return 1; /* RFC 3849 docs */ | ||
| 145 | + if ((b[0] & 0xFE) == 0xFC) return 1; /* RFC 4193 unique-local */ | ||
| 146 | + if (b[0] == 0xFE && (b[1] & 0xC0) == 0x80) return 1; /* RFC 4291 link-local */ | ||
| 147 | + if (b[0] == 0xFF) return 1; /* RFC 4291 multicast */ | ||
| 148 | + return 0; | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +int wh_ip_is_denied(const char *ip_text) | ||
| 152 | +{ | ||
| 153 | + unsigned char raw[16]; | ||
| 154 | + | ||
| 155 | + if (!ip_text || !*ip_text) return 1; | ||
| 156 | + if (wh_inet_pton(AF_INET, ip_text, raw) == 1) { | ||
| 157 | + unsigned v4 = ((unsigned)raw[0] << 24) | ((unsigned)raw[1] << 16) | | ||
| 158 | + ((unsigned)raw[2] << 8) | (unsigned)raw[3]; | ||
| 159 | + return v4_denied(v4); | ||
| 160 | + } | ||
| 161 | + if (wh_inet_pton(AF_INET6, ip_text, raw) == 1) return v6_denied(raw); | ||
| 162 | + return 1; /* unparseable -> deny */ | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +/* --------------------------------------------------------------------- url */ | ||
| 166 | + | ||
| 167 | +int wh_url_parse(const char *url, wh_url *out, char *err, size_t errsz) | ||
| 168 | +{ | ||
| 169 | + const char *p, *h, *e; | ||
| 170 | + size_t n; | ||
| 171 | + | ||
| 172 | + memset(out, 0, sizeof *out); | ||
| 173 | + if (!url || !*url) { snprintf(err, errsz, "empty url"); return -1; } | ||
| 174 | + | ||
| 175 | + if (strncmp(url, "https://", 8) == 0) { out->tls = 1; p = url + 8; } | ||
| 176 | + else if (strncmp(url, "http://", 7) == 0) { p = url + 7; } | ||
| 177 | + else { | ||
| 178 | + snprintf(err, errsz, "url must start with http:// or https://"); | ||
| 179 | + return -1; | ||
| 180 | + } | ||
| 181 | + | ||
| 182 | + if (*p == '[') { snprintf(err, errsz, "IPv6 literals are not supported"); return -1; } | ||
| 183 | + | ||
| 184 | + h = p; | ||
| 185 | + e = p; | ||
| 186 | + while (*e && *e != '/' && *e != '?' && *e != '#' && (unsigned char)*e >= 0x20) e++; | ||
| 187 | + n = (size_t)(e - h); | ||
| 188 | + if (n == 0) { snprintf(err, errsz, "url has no host"); return -1; } | ||
| 189 | + if (n >= sizeof out->host) { snprintf(err, errsz, "host too long"); return -1; } | ||
| 190 | + if (memchr(h, '@', n)) { | ||
| 191 | + snprintf(err, errsz, "credentials in the url are refused; use a header instead"); | ||
| 192 | + return -1; | ||
| 193 | + } | ||
| 194 | + | ||
| 195 | + out->port = out->tls ? 443 : 80; | ||
| 196 | + { | ||
| 197 | + const char *colon = (const char *)memchr(h, ':', n); | ||
| 198 | + if (colon) { | ||
| 199 | + char ports[8]; | ||
| 200 | + size_t pl = (size_t)(e - colon - 1), i; | ||
| 201 | + if (pl == 0 || pl >= sizeof ports) { snprintf(err, errsz, "bad port"); return -1; } | ||
| 202 | + for (i = 0; i < pl; i++) | ||
| 203 | + if (!isdigit((unsigned char)colon[1 + i])) { | ||
| 204 | + snprintf(err, errsz, "bad port"); | ||
| 205 | + return -1; | ||
| 206 | + } | ||
| 207 | + memcpy(ports, colon + 1, pl); | ||
| 208 | + ports[pl] = '\0'; | ||
| 209 | + out->port = atoi(ports); | ||
| 210 | + if (out->port < 1 || out->port > 65535) { | ||
| 211 | + snprintf(err, errsz, "port out of range"); | ||
| 212 | + return -1; | ||
| 213 | + } | ||
| 214 | + n = (size_t)(colon - h); | ||
| 215 | + } | ||
| 216 | + } | ||
| 217 | + memcpy(out->host, h, n); | ||
| 218 | + out->host[n] = '\0'; | ||
| 219 | + if (strspn(out->host, | ||
| 220 | + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-") | ||
| 221 | + != strlen(out->host)) { | ||
| 222 | + snprintf(err, errsz, "host contains forbidden characters"); | ||
| 223 | + return -1; | ||
| 224 | + } | ||
| 225 | + | ||
| 226 | + strcpy(out->scheme, out->tls ? "https" : "http"); | ||
| 227 | + if (*e == '/' || *e == '?') { | ||
| 228 | + size_t o = 0; | ||
| 229 | + while (*e && *e != ' ' && *e != '#' && o + 1 < sizeof out->path) | ||
| 230 | + out->path[o++] = *e++; | ||
| 231 | + out->path[o] = '\0'; | ||
| 232 | + } else { | ||
| 233 | + strcpy(out->path, "/"); | ||
| 234 | + } | ||
| 235 | + return 0; | ||
| 236 | +} | ||
| 237 | + | ||
| 238 | +void wh_url_redact(const wh_url *u, char *out, size_t outsz) | ||
| 239 | +{ | ||
| 240 | + const char *q; | ||
| 241 | + size_t n; | ||
| 242 | + int defport; | ||
| 243 | + char hostport[300]; | ||
| 244 | + | ||
| 245 | + if (!out || outsz == 0) return; | ||
| 246 | + out[0] = '\0'; | ||
| 247 | + if (!u) return; | ||
| 248 | + /* Keep the path (it identifies the endpoint) and drop the query string, | ||
| 249 | + * which is where a provider token hides when somebody pastes a complete | ||
| 250 | + * webhook URL into the form. */ | ||
| 251 | + q = strchr(u->path, '?'); | ||
| 252 | + n = q ? (size_t)(q - u->path) : strlen(u->path); | ||
| 253 | + defport = u->tls ? 443 : 80; | ||
| 254 | + if (u->port != defport) | ||
| 255 | + snprintf(hostport, sizeof hostport, "%s:%d", u->host, u->port); | ||
| 256 | + else | ||
| 257 | + snprintf(hostport, sizeof hostport, "%s", u->host); | ||
| 258 | + snprintf(out, outsz, "%s://%s%.*s%s", u->scheme, hostport, | ||
| 259 | + (int)n, u->path, q ? "?<redacted>" : ""); | ||
| 260 | +} | ||
| 261 | + | ||
| 262 | +int wh_method_ok(const char *method) | ||
| 263 | +{ | ||
| 264 | + static const char *const ok[] = { "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD" }; | ||
| 265 | + size_t i; | ||
| 266 | + if (!method || !*method) return 0; | ||
| 267 | + for (i = 0; i < sizeof ok / sizeof ok[0]; i++) | ||
| 268 | + if (strcmp(method, ok[i]) == 0) return 1; | ||
| 269 | + return 0; | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +/* ---------------------------------------------------------------- transport */ | ||
| 273 | + | ||
| 274 | +typedef struct { | ||
| 275 | + wh_sock_t fd; | ||
| 276 | +#if !defined(_WIN32) | ||
| 277 | + wh_tls *tls; | ||
| 278 | +#endif | ||
| 279 | + char *stash; /* bytes that arrived with the head terminator */ | ||
| 280 | + size_t stash_n; | ||
| 281 | +} wh_trans; | ||
| 282 | + | ||
| 283 | +static void trans_close(wh_trans *t) | ||
| 284 | +{ | ||
| 285 | +#if !defined(_WIN32) | ||
| 286 | + if (t->tls) { wh_tls_close(t->tls); t->tls = NULL; } | ||
| 287 | +#endif | ||
| 288 | + if (t->fd != WH_SOCK_INVALID) { wh_close_socket(t->fd); t->fd = WH_SOCK_INVALID; } | ||
| 289 | +} | ||
| 290 | + | ||
| 291 | +static int trans_read(wh_trans *t, char *buf, size_t n) | ||
| 292 | +{ | ||
| 293 | +#if !defined(_WIN32) | ||
| 294 | + if (t->tls) return wh_tls_read(t->tls, buf, n); | ||
| 295 | +#endif | ||
| 296 | + for (;;) { | ||
| 297 | + long long r = (long long)recv(t->fd, buf, (int)n, 0); | ||
| 298 | + if (r > 0) return (int)r; | ||
| 299 | + if (r == 0) return 0; | ||
| 300 | +#if defined(_WIN32) | ||
| 301 | + if (WSAGetLastError() == WSAEINTR) continue; | ||
| 302 | +#else | ||
| 303 | + if (errno == EINTR) continue; | ||
| 304 | +#endif | ||
| 305 | + return -1; | ||
| 306 | + } | ||
| 307 | +} | ||
| 308 | + | ||
| 309 | +static int trans_write(wh_trans *t, const char *buf, size_t n) | ||
| 310 | +{ | ||
| 311 | +#if !defined(_WIN32) | ||
| 312 | + if (t->tls) return wh_tls_write(t->tls, buf, n); | ||
| 313 | +#endif | ||
| 314 | + { | ||
| 315 | + size_t off = 0; | ||
| 316 | + while (off < n) { | ||
| 317 | +#if defined(MSG_NOSIGNAL) | ||
| 318 | + long long w = (long long)send(t->fd, buf + off, (int)(n - off), MSG_NOSIGNAL); | ||
| 319 | +#else | ||
| 320 | + long long w = (long long)send(t->fd, buf + off, (int)(n - off), 0); | ||
| 321 | +#endif | ||
| 322 | + if (w > 0) { off += (size_t)w; continue; } | ||
| 323 | +#if defined(_WIN32) | ||
| 324 | + if (w < 0 && WSAGetLastError() == WSAEINTR) continue; | ||
| 325 | +#else | ||
| 326 | + if (w < 0 && errno == EINTR) continue; | ||
| 327 | +#endif | ||
| 328 | + return -1; | ||
| 329 | + } | ||
| 330 | + return (int)off; | ||
| 331 | + } | ||
| 332 | +} | ||
| 333 | + | ||
| 334 | +/* ------------------------------------------------------------ resolve/conn */ | ||
| 335 | + | ||
| 336 | +typedef struct { | ||
| 337 | + int family; | ||
| 338 | + unsigned char ip[16]; | ||
| 339 | + char text[64]; | ||
| 340 | +} wh_target; | ||
| 341 | + | ||
| 342 | +/* Validate EVERY answer before connecting. One private record in the set | ||
| 343 | + * refuses the whole host: round-robin DNS and split-horizon answers both die | ||
| 344 | + * here, which is the point. */ | ||
| 345 | +static int resolve_validate(const char *host, int port, int allow_private, | ||
| 346 | + wh_target *out, char *err, size_t errsz) | ||
| 347 | +{ | ||
| 348 | + struct addrinfo hints, *res = NULL, *ai; | ||
| 349 | + char portstr[16]; | ||
| 350 | + int rc, found = 0, naddr = 0; | ||
| 351 | + | ||
| 352 | + memset(&hints, 0, sizeof hints); | ||
| 353 | + hints.ai_socktype = SOCK_STREAM; | ||
| 354 | + hints.ai_family = AF_UNSPEC; | ||
| 355 | + snprintf(portstr, sizeof portstr, "%d", port); | ||
| 356 | +#if defined(_WIN32) | ||
| 357 | + { | ||
| 358 | + WSADATA wsa; | ||
| 359 | + WSAStartup(MAKEWORD(2, 2), &wsa); | ||
| 360 | + } | ||
| 361 | +#endif | ||
| 362 | + rc = getaddrinfo(host, portstr, &hints, &res); | ||
| 363 | + if (rc != 0 || !res) { | ||
| 364 | + snprintf(err, errsz, "could not resolve %s", host); | ||
| 365 | + return -1; | ||
| 366 | + } | ||
| 367 | + | ||
| 368 | + for (ai = res; ai; ai = ai->ai_next) { | ||
| 369 | + char ipbuf[64]; | ||
| 370 | + int have = 0; | ||
| 371 | + if (ai->ai_family == AF_INET) { | ||
| 372 | + inet_ntop(AF_INET, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, | ||
| 373 | + ipbuf, sizeof ipbuf); | ||
| 374 | + have = 1; | ||
| 375 | + } else if (ai->ai_family == AF_INET6) { | ||
| 376 | + inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr, | ||
| 377 | + ipbuf, sizeof ipbuf); | ||
| 378 | + have = 1; | ||
| 379 | + } | ||
| 380 | + if (!have) continue; | ||
| 381 | + naddr++; | ||
| 382 | + if (!allow_private && wh_ip_is_denied(ipbuf)) { | ||
| 383 | + snprintf(err, errsz, | ||
| 384 | + "refused: %s resolves to a private or reserved address (%s). " | ||
| 385 | + "Set WEBHOOK_ALLOW_PRIVATE=1 to allow local endpoints.", | ||
| 386 | + host, ipbuf); | ||
| 387 | + freeaddrinfo(res); | ||
| 388 | + return -1; | ||
| 389 | + } | ||
| 390 | + } | ||
| 391 | + if (naddr == 0) { | ||
| 392 | + snprintf(err, errsz, "could not resolve %s (no usable address)", host); | ||
| 393 | + freeaddrinfo(res); | ||
| 394 | + return -1; | ||
| 395 | + } | ||
| 396 | + | ||
| 397 | + /* Prefer IPv4 (a v6-first answer on a host with no v6 route would eat the | ||
| 398 | + * whole connect budget), but accept v6 when that is all there is. */ | ||
| 399 | + for (ai = res; ai && !found; ai = ai->ai_next) { | ||
| 400 | + if (ai->ai_family != AF_INET) continue; | ||
| 401 | + out->family = AF_INET; | ||
| 402 | + memcpy(out->ip, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, 4); | ||
| 403 | + inet_ntop(AF_INET, out->ip, out->text, sizeof out->text); | ||
| 404 | + found = 1; | ||
| 405 | + } | ||
| 406 | + for (ai = res; ai && !found; ai = ai->ai_next) { | ||
| 407 | + if (ai->ai_family != AF_INET6) continue; | ||
| 408 | + out->family = AF_INET6; | ||
| 409 | + memcpy(out->ip, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr, 16); | ||
| 410 | + inet_ntop(AF_INET6, out->ip, out->text, sizeof out->text); | ||
| 411 | + found = 1; | ||
| 412 | + } | ||
| 413 | + freeaddrinfo(res); | ||
| 414 | + if (!found) { snprintf(err, errsz, "no usable address for %s", host); return -1; } | ||
| 415 | + return 0; | ||
| 416 | +} | ||
| 417 | + | ||
| 418 | +#if defined(_WIN32) | ||
| 419 | +static int connect_timeout(wh_sock_t fd, const struct sockaddr *sa, int slen, | ||
| 420 | + long timeout_ms, char *err, size_t errsz) | ||
| 421 | +{ | ||
| 422 | + u_long nb = 1; | ||
| 423 | + int rc; | ||
| 424 | + fd_set ws; | ||
| 425 | + struct timeval tv; | ||
| 426 | + | ||
| 427 | + ioctlsocket(fd, FIONBIO, &nb); | ||
| 428 | + rc = connect(fd, sa, slen); | ||
| 429 | + if (rc == 0) { nb = 0; ioctlsocket(fd, FIONBIO, &nb); return 0; } | ||
| 430 | + if (WSAGetLastError() != WSAEWOULDBLOCK) { | ||
| 431 | + snprintf(err, errsz, "connect failed (wsa %d)", WSAGetLastError()); | ||
| 432 | + return -1; | ||
| 433 | + } | ||
| 434 | + FD_ZERO(&ws); | ||
| 435 | + FD_SET(fd, &ws); | ||
| 436 | + tv.tv_sec = (long)(timeout_ms / 1000); | ||
| 437 | + tv.tv_usec = (long)((timeout_ms % 1000) * 1000); | ||
| 438 | + rc = select(0, NULL, &ws, NULL, &tv); | ||
| 439 | + if (rc <= 0) { snprintf(err, errsz, "connect timed out"); return -1; } | ||
| 440 | + { | ||
| 441 | + int soerr = 0; | ||
| 442 | + int solen = (int)sizeof soerr; | ||
| 443 | + if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char *)&soerr, &solen) != 0 || soerr) { | ||
| 444 | + snprintf(err, errsz, "connect failed (so_error %d)", soerr); | ||
| 445 | + return -1; | ||
| 446 | + } | ||
| 447 | + } | ||
| 448 | + nb = 0; | ||
| 449 | + ioctlsocket(fd, FIONBIO, &nb); | ||
| 450 | + return 0; | ||
| 451 | +} | ||
| 452 | +#else | ||
| 453 | +static int connect_timeout(wh_sock_t fd, const struct sockaddr *sa, socklen_t slen, | ||
| 454 | + long timeout_ms, char *err, size_t errsz) | ||
| 455 | +{ | ||
| 456 | + int flags, rc, soerr = 0; | ||
| 457 | + socklen_t solen = sizeof soerr; | ||
| 458 | + fd_set ws; | ||
| 459 | + struct timeval tv; | ||
| 460 | + | ||
| 461 | + flags = fcntl(fd, F_GETFL, 0); | ||
| 462 | + if (flags < 0) { snprintf(err, errsz, "fcntl failed"); return -1; } | ||
| 463 | + if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) { | ||
| 464 | + snprintf(err, errsz, "fcntl failed"); | ||
| 465 | + return -1; | ||
| 466 | + } | ||
| 467 | + rc = connect(fd, sa, slen); | ||
| 468 | + if (rc != 0 && errno != EINPROGRESS) { | ||
| 469 | + snprintf(err, errsz, "connect failed: %s", strerror(errno)); | ||
| 470 | + return -1; | ||
| 471 | + } | ||
| 472 | + if (rc != 0) { | ||
| 473 | + FD_ZERO(&ws); | ||
| 474 | + FD_SET(fd, &ws); | ||
| 475 | + tv.tv_sec = (long)(timeout_ms / 1000); | ||
| 476 | + tv.tv_usec = (long)((timeout_ms % 1000) * 1000); | ||
| 477 | + do { rc = select(fd + 1, NULL, &ws, NULL, &tv); } while (rc < 0 && errno == EINTR); | ||
| 478 | + if (rc <= 0) { snprintf(err, errsz, "connect timed out"); return -1; } | ||
| 479 | + if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &solen) != 0 || soerr) { | ||
| 480 | + snprintf(err, errsz, "connect failed: %s", strerror(soerr ? soerr : errno)); | ||
| 481 | + return -1; | ||
| 482 | + } | ||
| 483 | + } | ||
| 484 | + if (fcntl(fd, F_SETFL, flags) < 0) { | ||
| 485 | + snprintf(err, errsz, "fcntl failed"); | ||
| 486 | + return -1; | ||
| 487 | + } | ||
| 488 | + return 0; | ||
| 489 | +} | ||
| 490 | +#endif | ||
| 491 | + | ||
| 492 | +/* Socket-level read/write deadlines. mbedTLS reads through recv(), so this is | ||
| 493 | + * the only place a stalled peer can be bounded once the handshake is done. */ | ||
| 494 | +static void set_io_timeouts(wh_sock_t fd, long ms) | ||
| 495 | +{ | ||
| 496 | +#if defined(_WIN32) | ||
| 497 | + DWORD v = (DWORD)ms; | ||
| 498 | + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&v, sizeof v); | ||
| 499 | + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (const char *)&v, sizeof v); | ||
| 500 | +#else | ||
| 501 | + struct timeval tv; | ||
| 502 | + tv.tv_sec = (long)(ms / 1000); | ||
| 503 | + tv.tv_usec = (long)((ms % 1000) * 1000); | ||
| 504 | + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); | ||
| 505 | + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv); | ||
| 506 | +#endif | ||
| 507 | +} | ||
| 508 | + | ||
| 509 | +/* --------------------------------------------------------------- head parse */ | ||
| 510 | + | ||
| 511 | +static int ci_prefix(const char *s, const char *prefix) | ||
| 512 | +{ | ||
| 513 | + while (*prefix) { | ||
| 514 | + if (tolower((unsigned char)*s) != tolower((unsigned char)*prefix)) return 0; | ||
| 515 | + s++; prefix++; | ||
| 516 | + } | ||
| 517 | + return 1; | ||
| 518 | +} | ||
| 519 | + | ||
| 520 | +/* Finds a header value in a raw head block. Returns 1 and fills v/vl. */ | ||
| 521 | +static int head_field(const char *head, size_t head_len, const char *name, | ||
| 522 | + const char **v, size_t *vl) | ||
| 523 | +{ | ||
| 524 | + size_t i = 0, nl = strlen(name); | ||
| 525 | + while (i < head_len) { | ||
| 526 | + size_t ls = i, le; | ||
| 527 | + while (i < head_len && head[i] != '\n') i++; | ||
| 528 | + le = i; | ||
| 529 | + if (le > ls && head[le - 1] == '\r') le--; | ||
| 530 | + if (le > ls + nl && ci_prefix(head + ls, name) && head[ls + nl] == ':') { | ||
| 531 | + size_t b = ls + nl + 1; | ||
| 532 | + while (b < le && (head[b] == ' ' || head[b] == '\t')) b++; | ||
| 533 | + *v = head + b; | ||
| 534 | + *vl = le - b; | ||
| 535 | + return 1; | ||
| 536 | + } | ||
| 537 | + i++; /* skip the '\n' */ | ||
| 538 | + } | ||
| 539 | + return 0; | ||
| 540 | +} | ||
| 541 | + | ||
| 542 | +/* Reads the response head. Returns the number of head bytes (head NUL-capped), | ||
| 543 | + * -1 on error/timeout. Any body bytes that arrived in the same read window are | ||
| 544 | + * parked in t->stash. */ | ||
| 545 | +static int read_head(wh_trans *t, char *head, size_t cap, size_t *hlen_out) | ||
| 546 | +{ | ||
| 547 | + size_t n = 0, scanned = 0; | ||
| 548 | + | ||
| 549 | + t->stash = NULL; | ||
| 550 | + t->stash_n = 0; | ||
| 551 | + for (;;) { | ||
| 552 | + size_t want, i; | ||
| 553 | + int r; | ||
| 554 | + | ||
| 555 | + if (n >= cap) return -1; | ||
| 556 | + want = (cap - n > 1024) ? 1024 : (cap - n); | ||
| 557 | + if (want == 0) return -1; | ||
| 558 | + r = trans_read(t, head + n, want); | ||
| 559 | + if (r <= 0) { | ||
| 560 | + if (n == 0) return -1; | ||
| 561 | + *hlen_out = n; | ||
| 562 | + head[n] = '\0'; | ||
| 563 | + return (int)n; | ||
| 564 | + } | ||
| 565 | + n += (size_t)r; | ||
| 566 | + head[n] = '\0'; | ||
| 567 | + if (scanned > 3) scanned -= 3; | ||
| 568 | + for (i = scanned; i + 1 < n; i++) { | ||
| 569 | + if (head[i] != '\n') continue; | ||
| 570 | + if (i >= 3 && head[i - 1] == '\r' && head[i - 2] == '\n' && head[i - 3] == '\r') { | ||
| 571 | + *hlen_out = i - 1; | ||
| 572 | + head[*hlen_out] = '\0'; | ||
| 573 | + if (n > i + 1) { t->stash = head + (i + 1); t->stash_n = n - (i + 1); } | ||
| 574 | + return (int)n; | ||
| 575 | + } | ||
| 576 | + if (i >= 1 && head[i - 1] == '\n') { | ||
| 577 | + *hlen_out = i - 1; | ||
| 578 | + head[*hlen_out] = '\0'; | ||
| 579 | + if (n > i + 1) { t->stash = head + (i + 1); t->stash_n = n - (i + 1); } | ||
| 580 | + return (int)n; | ||
| 581 | + } | ||
| 582 | + } | ||
| 583 | + scanned = n; | ||
| 584 | + } | ||
| 585 | +} | ||
| 586 | + | ||
| 587 | +/* Keeps at most WH_PREVIEW_CAP body bytes, then drains (bounded) so the | ||
| 588 | + * server is not left mid-response. */ | ||
| 589 | +typedef struct { | ||
| 590 | + char *body; | ||
| 591 | + size_t len; | ||
| 592 | + size_t total; | ||
| 593 | + int truncated; | ||
| 594 | +} wh_sink; | ||
| 595 | + | ||
| 596 | +static void sink_add(wh_sink *s, const char *p, size_t n) | ||
| 597 | +{ | ||
| 598 | + s->total += n; | ||
| 599 | + if (s->len < WH_PREVIEW_CAP) { | ||
| 600 | + size_t take = WH_PREVIEW_CAP - s->len; | ||
| 601 | + if (take > n) take = n; | ||
| 602 | + memcpy(s->body + s->len, p, take); | ||
| 603 | + s->len += take; | ||
| 604 | + if (take < n) s->truncated = 1; | ||
| 605 | + } else { | ||
| 606 | + s->truncated = 1; | ||
| 607 | + } | ||
| 608 | +} | ||
| 609 | + | ||
| 610 | +#define WH_DRAIN_CAP (8u * 1024u * 1024u) | ||
| 611 | + | ||
| 612 | +/* ------------------------------------------------------------- POSIX leg */ | ||
| 613 | + | ||
| 614 | +#if !defined(_WIN32) | ||
| 615 | +static int exchange_plain(const wh_url *u, const char *method, | ||
| 616 | + const wh_header *hdrs, int nhdrs, | ||
| 617 | + const char *body, size_t blen, | ||
| 618 | + long timeout_ms, wh_response *r) | ||
| 619 | +{ | ||
| 620 | + wh_trans t; | ||
| 621 | + wh_target tgt; | ||
| 622 | + wh_sock_t fd = WH_SOCK_INVALID; | ||
| 623 | + struct sockaddr_storage ss; | ||
| 624 | + socklen_t slen; | ||
| 625 | + char *head = NULL; | ||
| 626 | + size_t head_len = 0; | ||
| 627 | + wh_sink sink; | ||
| 628 | + char *req = NULL; | ||
| 629 | + size_t reqcap, reqlen = 0; | ||
| 630 | + long long clen = -1; | ||
| 631 | + int chunked = 0, status, i, rc = -1, host_has_port; | ||
| 632 | + | ||
| 633 | + memset(&t, 0, sizeof t); | ||
| 634 | + t.fd = WH_SOCK_INVALID; | ||
| 635 | + memset(&sink, 0, sizeof sink); | ||
| 636 | + | ||
| 637 | + if (resolve_validate(u->host, u->port, wh_allow_private(), &tgt, | ||
| 638 | + r->error, sizeof r->error) != 0) | ||
| 639 | + return -1; | ||
| 640 | + | ||
| 641 | + fd = socket(tgt.family, SOCK_STREAM, 0); | ||
| 642 | + if (fd < 0) { snprintf(r->error, sizeof r->error, "socket() failed"); return -1; } | ||
| 643 | + memset(&ss, 0, sizeof ss); | ||
| 644 | + if (tgt.family == AF_INET) { | ||
| 645 | + struct sockaddr_in *sa = (struct sockaddr_in *)&ss; | ||
| 646 | + sa->sin_family = AF_INET; | ||
| 647 | + sa->sin_port = htons((unsigned short)u->port); | ||
| 648 | + memcpy(&sa->sin_addr, tgt.ip, 4); | ||
| 649 | + slen = sizeof *sa; | ||
| 650 | + } else { | ||
| 651 | + struct sockaddr_in6 *sa = (struct sockaddr_in6 *)&ss; | ||
| 652 | + sa->sin6_family = AF_INET6; | ||
| 653 | + sa->sin6_port = htons((unsigned short)u->port); | ||
| 654 | + memcpy(&sa->sin6_addr, tgt.ip, 16); | ||
| 655 | + slen = sizeof *sa; | ||
| 656 | + } | ||
| 657 | + if (connect_timeout(fd, (struct sockaddr *)&ss, slen, timeout_ms, | ||
| 658 | + r->error, sizeof r->error) != 0) { | ||
| 659 | + wh_close_socket(fd); | ||
| 660 | + return -1; | ||
| 661 | + } | ||
| 662 | + set_io_timeouts(fd, timeout_ms > WH_READ_MS ? timeout_ms : WH_READ_MS); | ||
| 663 | + t.fd = fd; | ||
| 664 | + | ||
| 665 | + if (u->tls) { | ||
| 666 | + t.tls = wh_tls_connect_fd(fd, u->host, r->error, sizeof r->error); | ||
| 667 | + if (!t.tls) { wh_close_socket(fd); return -1; } | ||
| 668 | + t.fd = WH_SOCK_INVALID; /* owned by the TLS object now */ | ||
| 669 | + } | ||
| 670 | + | ||
| 671 | + /* Head: request line + headers. */ | ||
| 672 | + host_has_port = !((u->tls && u->port == 443) || (!u->tls && u->port == 80)); | ||
| 673 | + reqcap = 2048 + (size_t)nhdrs * 1200; | ||
| 674 | + req = (char *)malloc(reqcap); | ||
| 675 | + if (!req) { snprintf(r->error, sizeof r->error, "out of memory"); goto done; } | ||
| 676 | + reqlen = (size_t)snprintf(req, reqcap, | ||
| 677 | + "%s %s HTTP/1.1\r\n" | ||
| 678 | + "Host: %s%s%s\r\n" | ||
| 679 | + "User-Agent: %s\r\n" | ||
| 680 | + "Accept: */*\r\n" | ||
| 681 | + "Connection: close\r\n", | ||
| 682 | + method, u->path[0] ? u->path : "/", | ||
| 683 | + u->host, host_has_port ? ":" : "", | ||
| 684 | + host_has_port ? "" : "", WH_USER_AGENT); | ||
| 685 | + if (host_has_port) { | ||
| 686 | + reqlen = (size_t)snprintf(req, reqcap, | ||
| 687 | + "%s %s HTTP/1.1\r\n" | ||
| 688 | + "Host: %s:%d\r\n" | ||
| 689 | + "User-Agent: %s\r\n" | ||
| 690 | + "Accept: */*\r\n" | ||
| 691 | + "Connection: close\r\n", | ||
| 692 | + method, u->path[0] ? u->path : "/", | ||
| 693 | + u->host, u->port, WH_USER_AGENT); | ||
| 694 | + } | ||
| 695 | + for (i = 0; i < nhdrs; i++) { | ||
| 696 | + size_t l; | ||
| 697 | + if (!hdrs[i].name[0]) continue; | ||
| 698 | + /* Framing headers are ours: a user header called Content-Length or | ||
| 699 | + * Connection would desynchronise the request. */ | ||
| 700 | + if (ci_prefix(hdrs[i].name, "Host") || | ||
| 701 | + ci_prefix(hdrs[i].name, "Content-Length") || | ||
| 702 | + ci_prefix(hdrs[i].name, "Transfer-Encoding") || | ||
| 703 | + ci_prefix(hdrs[i].name, "Connection")) continue; | ||
| 704 | + l = (size_t)snprintf(req + reqlen, reqcap - reqlen, "%s: %s\r\n", | ||
| 705 | + hdrs[i].name, hdrs[i].value); | ||
| 706 | + if (reqlen + l + 1 >= reqcap) { | ||
| 707 | + snprintf(r->error, sizeof r->error, "request headers too large"); | ||
| 708 | + goto done; | ||
| 709 | + } | ||
| 710 | + reqlen += l; | ||
| 711 | + } | ||
| 712 | + if (blen || (method && strcmp(method, "GET") != 0 && strcmp(method, "HEAD") != 0)) { | ||
| 713 | + size_t l = (size_t)snprintf(req + reqlen, reqcap - reqlen, | ||
| 714 | + "Content-Length: %lu\r\n", (unsigned long)blen); | ||
| 715 | + reqlen += l; | ||
| 716 | + } | ||
| 717 | + { | ||
| 718 | + size_t l = (size_t)snprintf(req + reqlen, reqcap - reqlen, "\r\n"); | ||
| 719 | + reqlen += l; | ||
| 720 | + } | ||
| 721 | + if (reqlen >= reqcap) { snprintf(r->error, sizeof r->error, "request too large"); goto done; } | ||
| 722 | + | ||
| 723 | + if (trans_write(&t, req, reqlen) < 0) { | ||
| 724 | + snprintf(r->error, sizeof r->error, "the endpoint did not accept our request"); | ||
| 725 | + goto done; | ||
| 726 | + } | ||
| 727 | + if (blen && trans_write(&t, body, blen) < 0) { | ||
| 728 | + snprintf(r->error, sizeof r->error, "the endpoint closed while the body was sent"); | ||
| 729 | + goto done; | ||
| 730 | + } | ||
| 731 | + | ||
| 732 | + head = (char *)malloc(WH_HEAD_CAP + 1); | ||
| 733 | + if (!head) { snprintf(r->error, sizeof r->error, "out of memory"); goto done; } | ||
| 734 | + rc = read_head(&t, head, WH_HEAD_CAP, &head_len); | ||
| 735 | + if (rc < 0) { | ||
| 736 | + snprintf(r->error, sizeof r->error, "no response head (timeout or not HTTP)"); | ||
| 737 | + goto done; | ||
| 738 | + } | ||
| 739 | + if (strncmp(head, "HTTP/", 5) != 0) { | ||
| 740 | + snprintf(r->error, sizeof r->error, "not an HTTP response"); | ||
| 741 | + goto done; | ||
| 742 | + } | ||
| 743 | + status = atoi(head + 9); | ||
| 744 | + r->status = status; | ||
| 745 | + { | ||
| 746 | + const char *v; | ||
| 747 | + size_t vl; | ||
| 748 | + if (head_field(head, head_len, "content-type", &v, &vl)) { | ||
| 749 | + size_t k = vl < sizeof r->content_type - 1 ? vl : sizeof r->content_type - 1; | ||
| 750 | + memcpy(r->content_type, v, k); | ||
| 751 | + r->content_type[k] = '\0'; | ||
| 752 | + } | ||
| 753 | + if (head_field(head, head_len, "content-length", &v, &vl)) { | ||
| 754 | + char nbuf[32]; | ||
| 755 | + size_t k = vl < sizeof nbuf - 1 ? vl : sizeof nbuf - 1; | ||
| 756 | + memcpy(nbuf, v, k); | ||
| 757 | + nbuf[k] = '\0'; | ||
| 758 | + clen = atoll(nbuf); | ||
| 759 | + } | ||
| 760 | + if (head_field(head, head_len, "transfer-encoding", &v, &vl) && | ||
| 761 | + vl >= 7 && ci_prefix(v, "chunked")) chunked = 1; | ||
| 762 | + } | ||
| 763 | + | ||
| 764 | + sink.body = r->body; | ||
| 765 | + sink.len = 0; | ||
| 766 | + sink.total = 0; | ||
| 767 | + sink.truncated = 0; | ||
| 768 | + | ||
| 769 | + if (chunked) { | ||
| 770 | + /* Small framing machine. It is fed from the stash first (bytes that | ||
| 771 | + * arrived in the same read window as the head terminator are chunk | ||
| 772 | + * data, not body) and gives up after WH_DRAIN_CAP bytes so a server | ||
| 773 | + * that streams forever cannot hold the request open. */ | ||
| 774 | + char buf[4096]; | ||
| 775 | + size_t sp = 0, sn = 0, drained = 0; | ||
| 776 | + int state = 0; /* 0 size line, 1 data, 2 data CRLF, 3 trailer */ | ||
| 777 | + int cr = 0; | ||
| 778 | + long long left = 0; | ||
| 779 | + | ||
| 780 | + if (t.stash_n) { memcpy(buf, t.stash, t.stash_n); sn = t.stash_n; sp = 0; } | ||
| 781 | + for (;;) { | ||
| 782 | + int c; | ||
| 783 | + if (sp >= sn) { | ||
| 784 | + int got; | ||
| 785 | + if (drained > WH_DRAIN_CAP) break; | ||
| 786 | + got = trans_read(&t, buf, sizeof buf); | ||
| 787 | + if (got <= 0) break; | ||
| 788 | + sp = 0; | ||
| 789 | + sn = (size_t)got; | ||
| 790 | + drained += (size_t)got; | ||
| 791 | + } | ||
| 792 | + c = (unsigned char)buf[sp++]; | ||
| 793 | + | ||
| 794 | + if (state == 0) { /* hex chunk size */ | ||
| 795 | + if (c == '\n') { | ||
| 796 | + state = (left == 0) ? 3 : 1; | ||
| 797 | + if (left == 0) cr = 0; | ||
| 798 | + } else if (c == '\r') { | ||
| 799 | + /* ignore */ | ||
| 800 | + } else if (isxdigit(c)) { | ||
| 801 | + int d = (c <= '9') ? (c - '0') : (tolower(c) - 'a' + 10); | ||
| 802 | + if (left < 0x10000000LL) left = left * 16 + d; | ||
| 803 | + } else { | ||
| 804 | + /* a chunk-size extension ("1a;ext=1"); ignore to EOL */ | ||
| 805 | + } | ||
| 806 | + } else if (state == 1) { /* chunk data */ | ||
| 807 | + char one = (char)c; | ||
| 808 | + sink_add(&sink, &one, 1); | ||
| 809 | + if (--left <= 0) { state = 2; cr = 0; } | ||
| 810 | + } else if (state == 2) { /* the CRLF that closes a chunk */ | ||
| 811 | + if (c == '\n') { state = 0; left = 0; cr = 0; } | ||
| 812 | + } else { /* trailers, until a blank line */ | ||
| 813 | + if (c == '\n') { | ||
| 814 | + if (cr == 0) break; /* empty line: end of message */ | ||
| 815 | + cr = 0; | ||
| 816 | + } else if (c != '\r') { | ||
| 817 | + cr = 1; | ||
| 818 | + } | ||
| 819 | + } | ||
| 820 | + } | ||
| 821 | + } else if (clen >= 0) { | ||
| 822 | + long long want = clen; | ||
| 823 | + if (t.stash_n) { | ||
| 824 | + size_t n = t.stash_n; | ||
| 825 | + if ((long long)n > want) n = (size_t)want; | ||
| 826 | + sink_add(&sink, t.stash, n); | ||
| 827 | + want -= (long long)n; | ||
| 828 | + } | ||
| 829 | + while (want > 0) { | ||
| 830 | + char buf[8192]; | ||
| 831 | + size_t n = sizeof buf; | ||
| 832 | + int got; | ||
| 833 | + if ((long long)n > want) n = (size_t)want; | ||
| 834 | + got = trans_read(&t, buf, n); | ||
| 835 | + if (got <= 0) break; | ||
| 836 | + sink_add(&sink, buf, (size_t)got); | ||
| 837 | + want -= got; | ||
| 838 | + } | ||
| 839 | + } else { | ||
| 840 | + size_t drained = 0; | ||
| 841 | + if (t.stash_n) sink_add(&sink, t.stash, t.stash_n); | ||
| 842 | + for (;;) { | ||
| 843 | + char buf[8192]; | ||
| 844 | + int got; | ||
| 845 | + if (drained > WH_DRAIN_CAP) break; | ||
| 846 | + got = trans_read(&t, buf, sizeof buf); | ||
| 847 | + if (got <= 0) break; | ||
| 848 | + sink_add(&sink, buf, (size_t)got); | ||
| 849 | + drained += (size_t)got; | ||
| 850 | + if (sink.truncated && sink.len >= WH_PREVIEW_CAP) { | ||
| 851 | + /* keep draining a bounded amount, then stop */ | ||
| 852 | + if (drained > WH_PREVIEW_CAP) break; | ||
| 853 | + } | ||
| 854 | + } | ||
| 855 | + } | ||
| 856 | + | ||
| 857 | + sink.body[sink.len] = '\0'; | ||
| 858 | + r->body_len = sink.len; | ||
| 859 | + r->body_total = sink.total; | ||
| 860 | + r->truncated = sink.truncated; | ||
| 861 | + r->ok = 1; | ||
| 862 | + rc = 0; | ||
| 863 | + | ||
| 864 | +done: | ||
| 865 | + free(head); | ||
| 866 | + free(req); | ||
| 867 | + trans_close(&t); | ||
| 868 | + return rc; | ||
| 869 | +} | ||
| 870 | +#endif /* !_WIN32 */ | ||
| 871 | + | ||
| 872 | +/* --------------------------------------------------------------- WinHTTP leg */ | ||
| 873 | + | ||
| 874 | +#if defined(_WIN32) | ||
| 875 | +static void a2w(const char *a, wchar_t *w, int wn) | ||
| 876 | +{ | ||
| 877 | + MultiByteToWideChar(CP_UTF8, 0, a, -1, w, wn); | ||
| 878 | +} | ||
| 879 | + | ||
| 880 | +static int exchange_winhttp(const wh_url *u, const char *method, | ||
| 881 | + const wh_header *hdrs, int nhdrs, | ||
| 882 | + const char *body, size_t blen, | ||
| 883 | + long timeout_ms, wh_response *r) | ||
| 884 | +{ | ||
| 885 | + HINTERNET sess = NULL, conn = NULL, req = NULL; | ||
| 886 | + wchar_t wtarget[128], wpath[WH_URL_MAX + 8], wmethod[16]; | ||
| 887 | + wh_target tgt; | ||
| 888 | + DWORD avail = 0, total = 0; | ||
| 889 | + int i, rc = -1, host_has_port; | ||
| 890 | + wh_sink sink; | ||
| 891 | + | ||
| 892 | + memset(&sink, 0, sizeof sink); | ||
| 893 | + if (resolve_validate(u->host, u->port, wh_allow_private(), &tgt, | ||
| 894 | + r->error, sizeof r->error) != 0) | ||
| 895 | + return -1; | ||
| 896 | + (void)timeout_ms; | ||
| 897 | + | ||
| 898 | + sess = WinHttpOpen(L"SCORPIOXBOT-webhook/1.0", | ||
| 899 | + WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, | ||
| 900 | + WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); | ||
| 901 | + if (!sess) | ||
| 902 | + sess = WinHttpOpen(L"SCORPIOXBOT-webhook/1.0", | ||
| 903 | + WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, | ||
| 904 | + WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); | ||
| 905 | + if (!sess) { snprintf(r->error, sizeof r->error, "WinHttpOpen failed"); return -1; } | ||
| 906 | + WinHttpSetTimeouts(sess, WH_CONNECT_MS, WH_CONNECT_MS, WH_READ_MS, WH_READ_MS); | ||
| 907 | + | ||
| 908 | + /* Connect to the validated numeric address; the real name travels in the | ||
| 909 | + * Host header and in SNI (WinHTTP derives SNI from the added Host value | ||
| 910 | + * only when connecting by name, so we also pass it explicitly below). */ | ||
| 911 | + a2w(tgt.text, wtarget, 128); | ||
| 912 | + a2w(u->path[0] ? u->path : "/", wpath, WH_URL_MAX + 8); | ||
| 913 | + a2w(method, wmethod, 16); | ||
| 914 | + | ||
| 915 | + conn = WinHttpConnect(sess, wtarget, (INTERNET_PORT)u->port, 0); | ||
| 916 | + if (!conn) { | ||
| 917 | + snprintf(r->error, sizeof r->error, "could not connect to %s", u->host); | ||
| 918 | + WinHttpCloseHandle(sess); | ||
| 919 | + return -1; | ||
| 920 | + } | ||
| 921 | + req = WinHttpOpenRequest(conn, wmethod, wpath, NULL, WINHTTP_NO_REFERER, | ||
| 922 | + WINHTTP_DEFAULT_ACCEPT_TYPES, | ||
| 923 | + u->tls ? WINHTTP_FLAG_SECURE : 0); | ||
| 924 | + if (!req) { | ||
| 925 | + snprintf(r->error, sizeof r->error, "WinHttpOpenRequest failed"); | ||
| 926 | + WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | ||
| 927 | + return -1; | ||
| 928 | + } | ||
| 929 | + { | ||
| 930 | + DWORD sec = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3; | ||
| 931 | + WinHttpSetOption(req, WINHTTP_OPTION_SECURE_PROTOCOLS, &sec, sizeof sec); | ||
| 932 | + } | ||
| 933 | + { | ||
| 934 | + DWORD pol = WINHTTP_OPTION_REDIRECT_POLICY_NEVER; | ||
| 935 | + WinHttpSetOption(req, WINHTTP_OPTION_REDIRECT_POLICY, &pol, sizeof pol); | ||
| 936 | + } | ||
| 937 | + { | ||
| 938 | + /* SNI + certificate hostname must be the real name, not the IP. */ | ||
| 939 | + wchar_t whost[300]; | ||
| 940 | + a2w(u->host, whost, 300); | ||
| 941 | + WinHttpSetOption(req, WINHTTP_OPTION_TLS_SERVER_NAME, | ||
| 942 | + whost, (DWORD)(wcslen(whost) * sizeof(wchar_t))); | ||
| 943 | + } | ||
| 944 | + | ||
| 945 | + host_has_port = !((u->tls && u->port == 443) || (!u->tls && u->port == 80)); | ||
| 946 | + { | ||
| 947 | + wchar_t wh[2048]; | ||
| 948 | + char hs[1600]; | ||
| 949 | + int n; | ||
| 950 | + n = snprintf(hs, sizeof hs, "Host: %s%s%s\r\n", | ||
| 951 | + u->host, host_has_port ? ":" : "", host_has_port ? "" : ""); | ||
| 952 | + if (host_has_port) | ||
| 953 | + n = snprintf(hs, sizeof hs, "Host: %s:%d\r\n", u->host, u->port); | ||
| 954 | + if (blen || (method && strcmp(method, "GET") != 0 && strcmp(method, "HEAD") != 0)) | ||
| 955 | + n += snprintf(hs + n, sizeof hs - (size_t)n, | ||
| 956 | + "Content-Length: %lu\r\n", (unsigned long)blen); | ||
| 957 | + for (i = 0; i < nhdrs && n < (int)sizeof hs - 1100; i++) { | ||
| 958 | + if (!hdrs[i].name[0]) continue; | ||
| 959 | + if (ci_prefix(hdrs[i].name, "Host") || | ||
| 960 | + ci_prefix(hdrs[i].name, "Content-Length") || | ||
| 961 | + ci_prefix(hdrs[i].name, "Transfer-Encoding") || | ||
| 962 | + ci_prefix(hdrs[i].name, "Connection")) continue; | ||
| 963 | + n += snprintf(hs + n, sizeof hs - (size_t)n, "%s: %s\r\n", | ||
| 964 | + hdrs[i].name, hdrs[i].value); | ||
| 965 | + } | ||
| 966 | + a2w(hs, wh, 2048); | ||
| 967 | + WinHttpAddRequestHeaders(req, wh, (DWORD)-1, | ||
| 968 | + WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE); | ||
| 969 | + } | ||
| 970 | + | ||
| 971 | + if (!WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0, | ||
| 972 | + blen ? (LPVOID)body : WINHTTP_NO_REQUEST_DATA, | ||
| 973 | + (DWORD)blen, (DWORD)blen, 0) || | ||
| 974 | + !WinHttpReceiveResponse(req, NULL)) { | ||
| 975 | + snprintf(r->error, sizeof r->error, | ||
| 976 | + "request failed: TLS or connection error (certificate refused " | ||
| 977 | + "or endpoint unreachable)"); | ||
| 978 | + WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | ||
| 979 | + return -1; | ||
| 980 | + } | ||
| 981 | + { | ||
| 982 | + DWORD code = 0, clen2 = sizeof code; | ||
| 983 | + WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, | ||
| 984 | + WINHTTP_HEADER_NAME_BY_INDEX, &code, &clen2, | ||
| 985 | + WINHTTP_NO_HEADER_INDEX); | ||
| 986 | + r->status = (int)code; | ||
| 987 | + } | ||
| 988 | + { | ||
| 989 | + DWORD ctype = 0; | ||
| 990 | + wchar_t wct[128]; | ||
| 991 | + if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CONTENT_TYPE, | ||
| 992 | + WINHTTP_HEADER_NAME_BY_INDEX, wct, &ctype, | ||
| 993 | + WINHTTP_NO_HEADER_INDEX) && ctype) { | ||
| 994 | + WideCharToMultiByte(CP_UTF8, 0, wct, -1, r->content_type, | ||
| 995 | + (int)sizeof r->content_type - 1, NULL, NULL); | ||
| 996 | + } | ||
| 997 | + } | ||
| 998 | + | ||
| 999 | + sink.body = r->body; | ||
| 1000 | + for (;;) { | ||
| 1001 | + char buf[8192]; | ||
| 1002 | + DWORD got = 0; | ||
| 1003 | + if (sink.len >= WH_PREVIEW_CAP) { | ||
| 1004 | + /* read the rest in a bounded way so the handle is not abandoned | ||
| 1005 | + * mid-response */ | ||
| 1006 | + if (sink.total > WH_DRAIN_CAP) break; | ||
| 1007 | + sink.truncated = 1; | ||
| 1008 | + if (!WinHttpReadData(req, buf, sizeof buf, &got) || got == 0) break; | ||
| 1009 | + sink.total += got; | ||
| 1010 | + continue; | ||
| 1011 | + } | ||
| 1012 | + if (!WinHttpReadData(req, buf, sizeof buf, &got) || got == 0) break; | ||
| 1013 | + sink_add(&sink, buf, (size_t)got); | ||
| 1014 | + total += got; | ||
| 1015 | + } | ||
| 1016 | + sink.body[sink.len] = '\0'; | ||
| 1017 | + r->body_len = sink.len; | ||
| 1018 | + r->body_total = sink.total; | ||
| 1019 | + r->truncated = sink.truncated; | ||
| 1020 | + r->ok = 1; | ||
| 1021 | + rc = 0; | ||
| 1022 | + | ||
| 1023 | + (void)avail; | ||
| 1024 | + WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | ||
| 1025 | + return rc; | ||
| 1026 | +} | ||
| 1027 | +#endif | ||
| 1028 | + | ||
| 1029 | +/* ------------------------------------------------------------------ entry */ | ||
| 1030 | + | ||
| 1031 | +int wh_http_request(const char *method, const wh_url *u, | ||
| 1032 | + const wh_header *hdrs, int nhdrs, | ||
| 1033 | + const char *body, size_t blen, | ||
| 1034 | + long timeout_ms, wh_response *r) | ||
| 1035 | +{ | ||
| 1036 | + memset(r, 0, sizeof *r); | ||
| 1037 | + if (!u) { snprintf(r->error, sizeof r->error, "no url"); return -1; } | ||
| 1038 | + if (!wh_method_ok(method)) { | ||
| 1039 | + snprintf(r->error, sizeof r->error, "unsupported method"); | ||
| 1040 | + return -1; | ||
| 1041 | + } | ||
| 1042 | + if (blen > WH_BODY_CAP) { | ||
| 1043 | + snprintf(r->error, sizeof r->error, | ||
| 1044 | + "the body is larger than the %u byte limit this plugin sends", | ||
| 1045 | + (unsigned)WH_BODY_CAP); | ||
| 1046 | + return -1; | ||
| 1047 | + } | ||
| 1048 | +#if defined(_WIN32) | ||
| 1049 | + return exchange_winhttp(u, method, hdrs, nhdrs, body, blen, timeout_ms, r); | ||
| 1050 | +#else | ||
| 1051 | + return exchange_plain(u, method, hdrs, nhdrs, body, blen, timeout_ms, r); | ||
| 1052 | +#endif | ||
| 1053 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..626e24d | index 0000000..626e24d | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/wh_http.h | +++ b/src/wh_http.h | ||
| @@ -0,0 +1,91 @@ | @@ -0,0 +1,91 @@ | ||
| 1 | +/* | ||
| 2 | + * wh_http.h - one outbound HTTP request with SSRF policy and verified TLS. | ||
| 3 | + * | ||
| 4 | + * The connector sends a user-defined request (method, URL, headers, body) to a | ||
| 5 | + * user-defined endpoint. Two things make that safe enough to expose as a tool: | ||
| 6 | + * | ||
| 7 | + * 1. SSRF policy. Every address the hostname resolves to is checked against a | ||
| 8 | + * deny list of loopback / RFC1918 / link-local / ULA / CGNAT / multicast / | ||
| 9 | + * documentation / reserved ranges BEFORE connecting, and the connection is | ||
| 10 | + * then made to that exact validated numeric address. A DNS answer that | ||
| 11 | + * changes between the check and the connect therefore cannot move the | ||
| 12 | + * request onto a private network. WEBHOOK_ALLOW_PRIVATE=1 lifts the policy | ||
| 13 | + * for an operator who genuinely means to call their own LAN (the offline | ||
| 14 | + * suite uses it to reach its recording receiver on 127.0.0.1). | ||
| 15 | + * | ||
| 16 | + * 2. Verified TLS. POSIX wraps the validated socket in mbedTLS (TLS 1.2+, | ||
| 17 | + * VERIFY_PEER, hostname check, system or WEBHOOK_TLS_CA_FILE anchors) with | ||
| 18 | + * no insecure bypass. _WIN32 uses WinHTTP against the validated numeric | ||
| 19 | + * address with the real Host header and the system root store. | ||
| 20 | + * | ||
| 21 | + * Redirects are NOT followed: a hook's URL is part of its definition, so a | ||
| 22 | + * 30x is reported as a status instead of silently becoming a request to | ||
| 23 | + * somewhere the operator never configured. | ||
| 24 | + * | ||
| 25 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 26 | + */ | ||
| 27 | +#ifndef SX_WH_HTTP_H | ||
| 28 | +#define SX_WH_HTTP_H | ||
| 29 | + | ||
| 30 | +#include <stddef.h> | ||
| 31 | + | ||
| 32 | +#define WH_URL_MAX 2048 | ||
| 33 | +#define WH_PREVIEW_CAP 4096 /* bytes of the response body we keep */ | ||
| 34 | +#define WH_HEAD_CAP (64u * 1024u) | ||
| 35 | +#define WH_BODY_CAP (1u * 1024u * 1024u) /* outbound body limit */ | ||
| 36 | +#define WH_CONNECT_MS 10000 | ||
| 37 | +#define WH_READ_MS 15000 | ||
| 38 | + | ||
| 39 | +typedef struct { | ||
| 40 | + char scheme[8]; /* "http" | "https" */ | ||
| 41 | + char host[256]; | ||
| 42 | + int port; | ||
| 43 | + char path[WH_URL_MAX]; /* path + query; "/" when absent */ | ||
| 44 | + int tls; | ||
| 45 | +} wh_url; | ||
| 46 | + | ||
| 47 | +typedef struct { | ||
| 48 | + char name[128]; | ||
| 49 | + char value[1024]; | ||
| 50 | +} wh_header; | ||
| 51 | + | ||
| 52 | +typedef struct { | ||
| 53 | + int ok; /* 1 = an HTTP response was received */ | ||
| 54 | + char error[512]; | ||
| 55 | + int status; | ||
| 56 | + char content_type[128]; | ||
| 57 | + char body[WH_PREVIEW_CAP + 1]; | ||
| 58 | + size_t body_len; | ||
| 59 | + size_t body_total; /* may exceed body_len when truncated */ | ||
| 60 | + int truncated; | ||
| 61 | +} wh_response; | ||
| 62 | + | ||
| 63 | +/* Parse http(s)://host[:port][/path][?query]. Refuses userinfo, IPv6 | ||
| 64 | + * literals, control characters and an empty host. 0 ok, -1 with err. */ | ||
| 65 | +int wh_url_parse(const char *url, wh_url *out, char *err, size_t errsz); | ||
| 66 | + | ||
| 67 | +/* The URL with any query string and credentials removed, so a redacted | ||
| 68 | + * summary can say where a hook points without leaking a token that a user | ||
| 69 | + * pasted into the query string. Always writes something. */ | ||
| 70 | +void wh_url_redact(const wh_url *u, char *out, size_t outsz); | ||
| 71 | + | ||
| 72 | +/* 1 when `ip_text` (IPv4 or IPv6 in text form) is loopback / private / | ||
| 73 | + * link-local / CGNAT / multicast / documentation / reserved. 0 when public. | ||
| 74 | + * An unparseable string returns 1 (deny), so a bug cannot open a hole. */ | ||
| 75 | +int wh_ip_is_denied(const char *ip_text); | ||
| 76 | + | ||
| 77 | +/* 1 when the environment lifts the SSRF policy (WEBHOOK_ALLOW_PRIVATE=1). */ | ||
| 78 | +int wh_allow_private(void); | ||
| 79 | + | ||
| 80 | +/* Perform one request. `hdrs` may be NULL. `body` may be NULL with blen 0. | ||
| 81 | + * Returns 0 when a response arrived (r->ok = 1, r->status set even for 4xx/5xx) | ||
| 82 | + * or -1 with r->error set when the request could not be completed. */ | ||
| 83 | +int wh_http_request(const char *method, const wh_url *u, | ||
| 84 | + const wh_header *hdrs, int nhdrs, | ||
| 85 | + const char *body, size_t blen, | ||
| 86 | + long timeout_ms, wh_response *r); | ||
| 87 | + | ||
| 88 | +/* Method validation: GET POST PUT PATCH DELETE HEAD, upper-cased. */ | ||
| 89 | +int wh_method_ok(const char *method); | ||
| 90 | + | ||
| 91 | +#endif /* SX_WH_HTTP_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..08359c5 | index 0000000..08359c5 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/wh_store.c | +++ b/src/wh_store.c | ||
| @@ -0,0 +1,668 @@ | @@ -0,0 +1,668 @@ | ||
| 1 | +/* | ||
| 2 | + * wh_store.c - named hooks, their secrets, and the delivery log. See wh_store.h. | ||
| 3 | + * | ||
| 4 | + * The store file is the only place a secret exists on disk, and it is written | ||
| 5 | + * at mode 0600 through a temp file plus rename() so a crash mid-write leaves | ||
| 6 | + * the previous document intact rather than a truncated one. | ||
| 7 | + * | ||
| 8 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 9 | + */ | ||
| 10 | +#define _POSIX_C_SOURCE 200809L | ||
| 11 | +#if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) | ||
| 12 | +#define _DARWIN_C_SOURCE 1 | ||
| 13 | +#endif | ||
| 14 | + | ||
| 15 | +#include "wh_store.h" | ||
| 16 | + | ||
| 17 | +#include <ctype.h> | ||
| 18 | +#include <errno.h> | ||
| 19 | +#include <stdio.h> | ||
| 20 | +#include <stdlib.h> | ||
| 21 | +#include <string.h> | ||
| 22 | +#include <time.h> | ||
| 23 | + | ||
| 24 | +#if defined(_WIN32) | ||
| 25 | +# include <direct.h> | ||
| 26 | +# include <io.h> | ||
| 27 | +# include <sys/stat.h> | ||
| 28 | +# include <windows.h> | ||
| 29 | +#else | ||
| 30 | +# include <sys/stat.h> | ||
| 31 | +# include <sys/types.h> | ||
| 32 | +# include <unistd.h> | ||
| 33 | +#endif | ||
| 34 | + | ||
| 35 | +#include "wh_buf.h" | ||
| 36 | +#include "yyjson.h" | ||
| 37 | + | ||
| 38 | +/* ------------------------------------------------------------------- paths */ | ||
| 39 | + | ||
| 40 | +static void mkdir_p(const char *path) | ||
| 41 | +{ | ||
| 42 | + char tmp[1024]; | ||
| 43 | + size_t i, n; | ||
| 44 | + | ||
| 45 | + n = strlen(path); | ||
| 46 | + if (n == 0 || n >= sizeof tmp) return; | ||
| 47 | + memcpy(tmp, path, n + 1); | ||
| 48 | + for (i = 1; i < n; i++) { | ||
| 49 | + if (tmp[i] != '/' && tmp[i] != '\\') continue; | ||
| 50 | + tmp[i] = '\0'; | ||
| 51 | +#if defined(_WIN32) | ||
| 52 | + _mkdir(tmp); | ||
| 53 | +#else | ||
| 54 | + mkdir(tmp, 0700); | ||
| 55 | +#endif | ||
| 56 | + tmp[i] = '/'; | ||
| 57 | + } | ||
| 58 | +#if defined(_WIN32) | ||
| 59 | + _mkdir(tmp); | ||
| 60 | +#else | ||
| 61 | + mkdir(tmp, 0700); | ||
| 62 | +#endif | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +void wh_store_path(char *out, size_t outsz) | ||
| 66 | +{ | ||
| 67 | + const char *env = getenv("WEBHOOK_STORE_PATH"); | ||
| 68 | + const char *base = NULL; | ||
| 69 | + | ||
| 70 | + if (outsz == 0) return; | ||
| 71 | + out[0] = '\0'; | ||
| 72 | + if (env && *env) { | ||
| 73 | + snprintf(out, outsz, "%s", env); | ||
| 74 | + return; | ||
| 75 | + } | ||
| 76 | +#if defined(_WIN32) | ||
| 77 | + base = getenv("LOCALAPPDATA"); | ||
| 78 | + if (base && *base) { | ||
| 79 | + snprintf(out, outsz, "%s\\scorpiox\\connectors\\plugin_webhook\\hooks.json", base); | ||
| 80 | + return; | ||
| 81 | + } | ||
| 82 | + base = getenv("USERPROFILE"); | ||
| 83 | + if (base && *base) { | ||
| 84 | + snprintf(out, outsz, "%s\\.scorpiox\\connectors\\plugin_webhook\\hooks.json", base); | ||
| 85 | + return; | ||
| 86 | + } | ||
| 87 | + snprintf(out, outsz, "hooks.json"); | ||
| 88 | +#else | ||
| 89 | + { | ||
| 90 | + struct stat st; | ||
| 91 | + if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode)) | ||
| 92 | + snprintf(out, outsz, "/workspace/.scorpiox/connectors/plugin_webhook/hooks.json"); | ||
| 93 | + else { | ||
| 94 | + base = getenv("HOME"); | ||
| 95 | + if (base && *base) | ||
| 96 | + snprintf(out, outsz, "%s/.scorpiox/connectors/plugin_webhook/hooks.json", base); | ||
| 97 | + else | ||
| 98 | + snprintf(out, outsz, "/tmp/.scorpiox/connectors/plugin_webhook/hooks.json"); | ||
| 99 | + } | ||
| 100 | + } | ||
| 101 | +#endif | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +/* --------------------------------------------------------------- load/save */ | ||
| 105 | + | ||
| 106 | +static void copy_trunc(char *dst, size_t capsz, const char *src) | ||
| 107 | +{ | ||
| 108 | + size_t n; | ||
| 109 | + if (!capsz) return; | ||
| 110 | + if (!src) { dst[0] = '\0'; return; } | ||
| 111 | + n = strlen(src); | ||
| 112 | + if (n >= capsz) n = capsz - 1; | ||
| 113 | + memcpy(dst, src, n); | ||
| 114 | + dst[n] = '\0'; | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +static const char *jstr(yyjson_val *o, const char *key) | ||
| 118 | +{ | ||
| 119 | + yyjson_val *v; | ||
| 120 | + if (!o) return NULL; | ||
| 121 | + v = yyjson_obj_get(o, key); | ||
| 122 | + if (!v || !yyjson_is_str(v)) return NULL; | ||
| 123 | + return yyjson_get_str(v); | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +int wh_store_load(wh_store *s, char *err, size_t errsz) | ||
| 127 | +{ | ||
| 128 | + FILE *f; | ||
| 129 | + char path[1024]; | ||
| 130 | + char *text; | ||
| 131 | + long sz; | ||
| 132 | + size_t got; | ||
| 133 | + yyjson_doc *doc; | ||
| 134 | + yyjson_val *root, *hooks, *log; | ||
| 135 | + | ||
| 136 | + memset(s, 0, sizeof *s); | ||
| 137 | + if (err && errsz) err[0] = '\0'; | ||
| 138 | + wh_store_path(path, sizeof path); | ||
| 139 | + | ||
| 140 | + f = fopen(path, "rb"); | ||
| 141 | + if (!f) return 0; /* no file yet: empty store */ | ||
| 142 | + if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return 0; } | ||
| 143 | + sz = ftell(f); | ||
| 144 | + if (sz < 0 || sz > (long)(4 * 1024 * 1024)) { | ||
| 145 | + fclose(f); | ||
| 146 | + if (err) snprintf(err, errsz, "store file is unreadable or too large"); | ||
| 147 | + return -1; | ||
| 148 | + } | ||
| 149 | + rewind(f); | ||
| 150 | + text = (char *)malloc((size_t)sz + 1); | ||
| 151 | + if (!text) { fclose(f); if (err) snprintf(err, errsz, "out of memory"); return -1; } | ||
| 152 | + got = fread(text, 1, (size_t)sz, f); | ||
| 153 | + fclose(f); | ||
| 154 | + text[got] = '\0'; | ||
| 155 | + | ||
| 156 | + doc = yyjson_read(text, got, 0); | ||
| 157 | + free(text); | ||
| 158 | + if (!doc) { | ||
| 159 | + /* A corrupt store is reported, never silently replaced: the operator | ||
| 160 | + * may still be able to recover the secrets from the file. */ | ||
| 161 | + if (err) snprintf(err, errsz, | ||
| 162 | + "the hook store exists but is not valid JSON (%s); " | ||
| 163 | + "it was left untouched", path); | ||
| 164 | + return -1; | ||
| 165 | + } | ||
| 166 | + root = yyjson_doc_get_root(doc); | ||
| 167 | + | ||
| 168 | + hooks = yyjson_obj_get(root, "hooks"); | ||
| 169 | + if (hooks && yyjson_is_arr(hooks)) { | ||
| 170 | + size_t i, n = yyjson_arr_size(hooks); | ||
| 171 | + for (i = 0; i < n && s->nhooks < WH_MAX_HOOKS; i++) { | ||
| 172 | + yyjson_val *o = yyjson_arr_get(hooks, i); | ||
| 173 | + yyjson_val *hdrs; | ||
| 174 | + wh_hook *h = &s->hooks[s->nhooks]; | ||
| 175 | + size_t k, hn; | ||
| 176 | + | ||
| 177 | + if (!yyjson_is_obj(o)) continue; | ||
| 178 | + copy_trunc(h->name, sizeof h->name, jstr(o, "name")); | ||
| 179 | + copy_trunc(h->url, sizeof h->url, jstr(o, "url")); | ||
| 180 | + copy_trunc(h->method, sizeof h->method, jstr(o, "method")); | ||
| 181 | + copy_trunc(h->desc, sizeof h->desc, jstr(o, "desc")); | ||
| 182 | + copy_trunc(h->sig, sizeof h->sig, jstr(o, "sig")); | ||
| 183 | + copy_trunc(h->secret, sizeof h->secret, jstr(o, "secret")); | ||
| 184 | + if (!h->method[0]) copy_trunc(h->method, sizeof h->method, "POST"); | ||
| 185 | + hdrs = yyjson_obj_get(o, "headers"); | ||
| 186 | + hn = 0; | ||
| 187 | + if (hdrs && yyjson_is_arr(hdrs)) { | ||
| 188 | + size_t m = yyjson_arr_size(hdrs); | ||
| 189 | + for (k = 0; k < m && hn < WH_MAX_HEADERS; k++) { | ||
| 190 | + yyjson_val *e = yyjson_arr_get(hdrs, k); | ||
| 191 | + const char *nm = jstr(e, "name"); | ||
| 192 | + const char *val = jstr(e, "value"); | ||
| 193 | + if (!nm || !*nm) continue; | ||
| 194 | + copy_trunc(h->headers[hn].name, sizeof h->headers[hn].name, nm); | ||
| 195 | + copy_trunc(h->headers[hn].value, sizeof h->headers[hn].value, | ||
| 196 | + val ? val : ""); | ||
| 197 | + hn++; | ||
| 198 | + } | ||
| 199 | + } | ||
| 200 | + h->nheaders = (int)hn; | ||
| 201 | + if (!h->name[0]) continue; | ||
| 202 | + s->nhooks++; | ||
| 203 | + } | ||
| 204 | + } | ||
| 205 | + | ||
| 206 | + log = yyjson_obj_get(root, "log"); | ||
| 207 | + if (log && yyjson_is_arr(log)) { | ||
| 208 | + size_t i, n = yyjson_arr_size(log); | ||
| 209 | + for (i = 0; i < n && s->nlog < WH_LOG_MAX; i++) { | ||
| 210 | + yyjson_val *o = yyjson_arr_get(log, i); | ||
| 211 | + wh_logent *e = &s->log[s->nlog]; | ||
| 212 | + if (!yyjson_is_obj(o)) continue; | ||
| 213 | + copy_trunc(e->at, sizeof e->at, jstr(o, "at")); | ||
| 214 | + copy_trunc(e->name, sizeof e->name, jstr(o, "name")); | ||
| 215 | + copy_trunc(e->error, sizeof e->error, jstr(o, "error")); | ||
| 216 | + { | ||
| 217 | + yyjson_val *v = yyjson_obj_get(o, "status"); | ||
| 218 | + e->status = (v && yyjson_is_int(v)) ? (int)yyjson_get_sint(v) : 0; | ||
| 219 | + v = yyjson_obj_get(o, "ok"); | ||
| 220 | + e->ok = (v && yyjson_is_bool(v)) ? (yyjson_get_bool(v) ? 1 : 0) : 0; | ||
| 221 | + v = yyjson_obj_get(o, "bytes"); | ||
| 222 | + e->bytes = (v && yyjson_is_int(v)) ? (long)yyjson_get_sint(v) : 0; | ||
| 223 | + v = yyjson_obj_get(o, "ms"); | ||
| 224 | + e->ms = (v && yyjson_is_int(v)) ? (long)yyjson_get_sint(v) : 0; | ||
| 225 | + } | ||
| 226 | + if (!e->name[0]) continue; | ||
| 227 | + s->nlog++; | ||
| 228 | + } | ||
| 229 | + } | ||
| 230 | + | ||
| 231 | + yyjson_doc_free(doc); | ||
| 232 | + return 0; | ||
| 233 | +} | ||
| 234 | + | ||
| 235 | +static void set_mode_0600(const char *path) | ||
| 236 | +{ | ||
| 237 | +#if defined(_WIN32) | ||
| 238 | + (void)path; /* NTFS ACLs are inherited from the profile dir */ | ||
| 239 | +#else | ||
| 240 | + chmod(path, 0600); | ||
| 241 | +#endif | ||
| 242 | +} | ||
| 243 | + | ||
| 244 | +int wh_store_save(const wh_store *s, char *err, size_t errsz) | ||
| 245 | +{ | ||
| 246 | + char path[1024], tmp[1100], dir[1024]; | ||
| 247 | + wh_buf b; | ||
| 248 | + FILE *f; | ||
| 249 | + int i, first; | ||
| 250 | + char *slash; | ||
| 251 | + | ||
| 252 | + if (err && errsz) err[0] = '\0'; | ||
| 253 | + wh_store_path(path, sizeof path); | ||
| 254 | + copy_trunc(dir, sizeof dir, path); | ||
| 255 | + slash = strrchr(dir, '/'); | ||
| 256 | +#if defined(_WIN32) | ||
| 257 | + if (!slash) slash = strrchr(dir, '\\'); | ||
| 258 | +#endif | ||
| 259 | + if (slash) { *slash = '\0'; mkdir_p(dir); } | ||
| 260 | + | ||
| 261 | + wh_buf_init(&b); | ||
| 262 | + wh_buf_str(&b, "{\"version\":1,\"hooks\":["); | ||
| 263 | + first = 1; | ||
| 264 | + for (i = 0; i < s->nhooks; i++) { | ||
| 265 | + const wh_hook *h = &s->hooks[i]; | ||
| 266 | + int f2 = 1, k; | ||
| 267 | + if (!first) wh_buf_str(&b, ","); | ||
| 268 | + first = 0; | ||
| 269 | + wh_buf_str(&b, "{"); | ||
| 270 | + wh_buf_key(&b, "name", &f2); wh_buf_json_str(&b, h->name); | ||
| 271 | + wh_buf_key(&b, "url", &f2); wh_buf_json_str(&b, h->url); | ||
| 272 | + wh_buf_key(&b, "method", &f2); wh_buf_json_str(&b, h->method); | ||
| 273 | + wh_buf_key(&b, "desc", &f2); wh_buf_json_str(&b, h->desc); | ||
| 274 | + wh_buf_key(&b, "sig", &f2); wh_buf_json_str(&b, h->sig); | ||
| 275 | + wh_buf_key(&b, "secret", &f2); wh_buf_json_str(&b, h->secret); | ||
| 276 | + wh_buf_key(&b, "headers", &f2); | ||
| 277 | + wh_buf_str(&b, "["); | ||
| 278 | + for (k = 0; k < h->nheaders; k++) { | ||
| 279 | + int f3 = 1; | ||
| 280 | + if (k) wh_buf_str(&b, ","); | ||
| 281 | + wh_buf_str(&b, "{"); | ||
| 282 | + wh_buf_key(&b, "name", &f3); wh_buf_json_str(&b, h->headers[k].name); | ||
| 283 | + wh_buf_key(&b, "value", &f3); wh_buf_json_str(&b, h->headers[k].value); | ||
| 284 | + wh_buf_str(&b, "}"); | ||
| 285 | + } | ||
| 286 | + wh_buf_str(&b, "]}"); | ||
| 287 | + } | ||
| 288 | + wh_buf_str(&b, "],\"log\":["); | ||
| 289 | + for (i = 0; i < s->nlog; i++) { | ||
| 290 | + const wh_logent *e = &s->log[i]; | ||
| 291 | + int f2 = 1; | ||
| 292 | + if (i) wh_buf_str(&b, ","); | ||
| 293 | + wh_buf_str(&b, "{"); | ||
| 294 | + wh_buf_key(&b, "at", &f2); wh_buf_json_str(&b, e->at); | ||
| 295 | + wh_buf_key(&b, "name", &f2); wh_buf_json_str(&b, e->name); | ||
| 296 | + wh_buf_key(&b, "status", &f2); wh_buf_printf(&b, "%d", e->status); | ||
| 297 | + wh_buf_key(&b, "ok", &f2); wh_buf_str(&b, e->ok ? "true" : "false"); | ||
| 298 | + wh_buf_key(&b, "bytes", &f2); wh_buf_printf(&b, "%ld", e->bytes); | ||
| 299 | + wh_buf_key(&b, "ms", &f2); wh_buf_printf(&b, "%ld", e->ms); | ||
| 300 | + wh_buf_key(&b, "error", &f2); wh_buf_json_str(&b, e->error); | ||
| 301 | + wh_buf_str(&b, "}"); | ||
| 302 | + } | ||
| 303 | + wh_buf_str(&b, "]}"); | ||
| 304 | + | ||
| 305 | + if (b.oom) { | ||
| 306 | + wh_buf_free(&b); | ||
| 307 | + if (err) snprintf(err, errsz, "out of memory"); | ||
| 308 | + return -1; | ||
| 309 | + } | ||
| 310 | + snprintf(tmp, sizeof tmp, "%s.tmp", path); | ||
| 311 | + f = fopen(tmp, "wb"); | ||
| 312 | + if (!f) { | ||
| 313 | + wh_buf_free(&b); | ||
| 314 | + if (err) snprintf(err, errsz, "cannot create %s: %s", tmp, strerror(errno)); | ||
| 315 | + return -1; | ||
| 316 | + } | ||
| 317 | + if (fwrite(wh_buf_cstr(&b), 1, b.n, f) != b.n) { | ||
| 318 | + fclose(f); | ||
| 319 | + remove(tmp); | ||
| 320 | + wh_buf_free(&b); | ||
| 321 | + if (err) snprintf(err, errsz, "short write to %s", tmp); | ||
| 322 | + return -1; | ||
| 323 | + } | ||
| 324 | + fflush(f); | ||
| 325 | + fclose(f); | ||
| 326 | + set_mode_0600(tmp); | ||
| 327 | +#if defined(_WIN32) | ||
| 328 | + remove(path); | ||
| 329 | +#endif | ||
| 330 | + if (rename(tmp, path) != 0) { | ||
| 331 | + remove(tmp); | ||
| 332 | + wh_buf_free(&b); | ||
| 333 | + if (err) snprintf(err, errsz, "cannot replace %s: %s", path, strerror(errno)); | ||
| 334 | + return -1; | ||
| 335 | + } | ||
| 336 | + set_mode_0600(path); | ||
| 337 | + wh_buf_free(&b); | ||
| 338 | + return 0; | ||
| 339 | +} | ||
| 340 | + | ||
| 341 | +/* ------------------------------------------------------------------ lookups */ | ||
| 342 | + | ||
| 343 | +wh_hook *wh_hook_find(wh_store *s, const char *name) | ||
| 344 | +{ | ||
| 345 | + int i; | ||
| 346 | + if (!s || !name) return NULL; | ||
| 347 | + for (i = 0; i < s->nhooks; i++) | ||
| 348 | + if (strcmp(s->hooks[i].name, name) == 0) return &s->hooks[i]; | ||
| 349 | + return NULL; | ||
| 350 | +} | ||
| 351 | + | ||
| 352 | +void wh_hook_remove(wh_store *s, int idx) | ||
| 353 | +{ | ||
| 354 | + int i; | ||
| 355 | + if (!s || idx < 0 || idx >= s->nhooks) return; | ||
| 356 | + for (i = idx; i + 1 < s->nhooks; i++) s->hooks[i] = s->hooks[i + 1]; | ||
| 357 | + s->nhooks--; | ||
| 358 | + memset(&s->hooks[s->nhooks], 0, sizeof s->hooks[0]); | ||
| 359 | +} | ||
| 360 | + | ||
| 361 | +void wh_store_log_add(wh_store *s, const wh_logent *e) | ||
| 362 | +{ | ||
| 363 | + int i; | ||
| 364 | + if (!s || !e) return; | ||
| 365 | + for (i = (s->nlog < WH_LOG_MAX ? s->nlog : WH_LOG_MAX - 1); i > 0; i--) | ||
| 366 | + s->log[i] = s->log[i - 1]; | ||
| 367 | + s->log[0] = *e; | ||
| 368 | + if (s->nlog < WH_LOG_MAX) s->nlog++; | ||
| 369 | +} | ||
| 370 | + | ||
| 371 | +/* -------------------------------------------------------------- serializers */ | ||
| 372 | + | ||
| 373 | +void wh_hook_json(const wh_hook *h, int redacted, char *out, size_t outsz) | ||
| 374 | +{ | ||
| 375 | + wh_buf b; | ||
| 376 | + int f = 1, k; | ||
| 377 | + | ||
| 378 | + if (!out || outsz == 0) return; | ||
| 379 | + out[0] = '\0'; | ||
| 380 | + wh_buf_init(&b); | ||
| 381 | + wh_buf_str(&b, "{"); | ||
| 382 | + wh_buf_key(&b, "name", &f); wh_buf_json_str(&b, h->name); | ||
| 383 | + wh_buf_key(&b, "method", &f); wh_buf_json_str(&b, h->method); | ||
| 384 | + wh_buf_key(&b, "desc", &f); wh_buf_json_str(&b, h->desc); | ||
| 385 | + wh_buf_key(&b, "sig", &f); wh_buf_json_str(&b, h->sig); | ||
| 386 | + wh_buf_key(&b, "has_secret", &f); | ||
| 387 | + wh_buf_str(&b, h->secret[0] ? "true" : "false"); | ||
| 388 | + if (redacted) { | ||
| 389 | + /* Domain + path only: a URL can carry a token in its query string, and | ||
| 390 | + * a list of hooks is exactly the kind of output that ends up in a | ||
| 391 | + * prompt. */ | ||
| 392 | + wh_url u; | ||
| 393 | + char err[128]; | ||
| 394 | + char clean[WH_URL_MAX + 32]; | ||
| 395 | + clean[0] = '\0'; | ||
| 396 | + if (wh_url_parse(h->url, &u, err, sizeof err) == 0) | ||
| 397 | + wh_url_redact(&u, clean, sizeof clean); | ||
| 398 | + wh_buf_key(&b, "url", &f); | ||
| 399 | + wh_buf_json_str(&b, clean); | ||
| 400 | + } else { | ||
| 401 | + wh_buf_key(&b, "url", &f); | ||
| 402 | + wh_buf_json_str(&b, h->url); | ||
| 403 | + } | ||
| 404 | + wh_buf_key(&b, "headers", &f); | ||
| 405 | + wh_buf_str(&b, "["); | ||
| 406 | + for (k = 0; k < h->nheaders; k++) { | ||
| 407 | + int f2 = 1; | ||
| 408 | + if (k) wh_buf_str(&b, ","); | ||
| 409 | + wh_buf_str(&b, "{"); | ||
| 410 | + wh_buf_key(&b, "name", &f2); | ||
| 411 | + wh_buf_json_str(&b, h->headers[k].name); | ||
| 412 | + if (redacted) { | ||
| 413 | + wh_buf_key(&b, "has_secret", &f2); | ||
| 414 | + wh_buf_str(&b, h->headers[k].value[0] ? "true" : "false"); | ||
| 415 | + } | ||
| 416 | + wh_buf_str(&b, "}"); | ||
| 417 | + } | ||
| 418 | + wh_buf_str(&b, "]}"); | ||
| 419 | + snprintf(out, outsz, "%s", wh_buf_cstr(&b)); | ||
| 420 | + wh_buf_free(&b); | ||
| 421 | +} | ||
| 422 | + | ||
| 423 | +void wh_store_json(const wh_store *s, int redacted, char *out, size_t outsz) | ||
| 424 | +{ | ||
| 425 | + wh_buf b; | ||
| 426 | + int i; | ||
| 427 | + | ||
| 428 | + if (!out || outsz == 0) return; | ||
| 429 | + out[0] = '\0'; | ||
| 430 | + wh_buf_init(&b); | ||
| 431 | + wh_buf_str(&b, "{\"ok\":true,\"count\":"); | ||
| 432 | + wh_buf_printf(&b, "%d", s->nhooks); | ||
| 433 | + wh_buf_str(&b, ",\"hooks\":["); | ||
| 434 | + for (i = 0; i < s->nhooks; i++) { | ||
| 435 | + char one[WH_URL_MAX * 2 + 4096]; | ||
| 436 | + if (i) wh_buf_str(&b, ","); | ||
| 437 | + wh_hook_json(&s->hooks[i], redacted, one, sizeof one); | ||
| 438 | + wh_buf_str(&b, one); | ||
| 439 | + } | ||
| 440 | + wh_buf_str(&b, "]}"); | ||
| 441 | + snprintf(out, outsz, "%s", wh_buf_cstr(&b)); | ||
| 442 | + wh_buf_free(&b); | ||
| 443 | +} | ||
| 444 | + | ||
| 445 | +void wh_store_list_json(const wh_store *s, char *out, size_t outsz) | ||
| 446 | +{ | ||
| 447 | + wh_buf b; | ||
| 448 | + int i, f = 0; /* "ok" and "count" were written literally, so the next | ||
| 449 | + * key needs its separator */ | ||
| 450 | + | ||
| 451 | + if (!out || outsz == 0) return; | ||
| 452 | + out[0] = '\0'; | ||
| 453 | + wh_buf_init(&b); | ||
| 454 | + wh_buf_str(&b, "{\"ok\":true,\"count\":"); | ||
| 455 | + wh_buf_printf(&b, "%d", s->nhooks); | ||
| 456 | + wh_buf_key(&b, "hooks", &f); | ||
| 457 | + wh_buf_str(&b, "["); | ||
| 458 | + for (i = 0; i < s->nhooks; i++) { | ||
| 459 | + char one[WH_URL_MAX * 2 + 4096]; | ||
| 460 | + if (i) wh_buf_str(&b, ","); | ||
| 461 | + wh_hook_json(&s->hooks[i], 1, one, sizeof one); | ||
| 462 | + wh_buf_str(&b, one); | ||
| 463 | + } | ||
| 464 | + wh_buf_str(&b, "]"); | ||
| 465 | + /* Every key after "hooks" must go through wh_buf_key so the object stays | ||
| 466 | + * well-formed: a hand-written ",\"log\":[" here once produced | ||
| 467 | + * {"count":16"hooks":... - valid-looking, unparseable. */ | ||
| 468 | + wh_buf_key(&b, "log", &f); | ||
| 469 | + wh_buf_str(&b, "["); | ||
| 470 | + for (i = 0; i < s->nlog; i++) { | ||
| 471 | + const wh_logent *e = &s->log[i]; | ||
| 472 | + int f2 = 1; | ||
| 473 | + if (i) wh_buf_str(&b, ","); | ||
| 474 | + wh_buf_str(&b, "{"); | ||
| 475 | + wh_buf_key(&b, "at", &f2); wh_buf_json_str(&b, e->at); | ||
| 476 | + wh_buf_key(&b, "name", &f2); wh_buf_json_str(&b, e->name); | ||
| 477 | + wh_buf_key(&b, "status", &f2); wh_buf_printf(&b, "%d", e->status); | ||
| 478 | + wh_buf_key(&b, "ok", &f2); wh_buf_str(&b, e->ok ? "true" : "false"); | ||
| 479 | + wh_buf_key(&b, "bytes", &f2); wh_buf_printf(&b, "%ld", e->bytes); | ||
| 480 | + wh_buf_key(&b, "ms", &f2); wh_buf_printf(&b, "%ld", e->ms); | ||
| 481 | + wh_buf_key(&b, "error", &f2); wh_buf_json_str(&b, e->error); | ||
| 482 | + wh_buf_str(&b, "}"); | ||
| 483 | + } | ||
| 484 | + wh_buf_str(&b, "]"); | ||
| 485 | + wh_buf_key(&b, "allow_private", &f); | ||
| 486 | + wh_buf_str(&b, wh_allow_private() ? "true" : "false"); | ||
| 487 | + wh_buf_str(&b, "}"); | ||
| 488 | + snprintf(out, outsz, "%s", wh_buf_cstr(&b)); | ||
| 489 | + wh_buf_free(&b); | ||
| 490 | +} | ||
| 491 | + | ||
| 492 | +/* ----------------------------------------------------------------- validate */ | ||
| 493 | + | ||
| 494 | +static int header_name_ok(const char *s) | ||
| 495 | +{ | ||
| 496 | + if (!s || !*s) return 0; | ||
| 497 | + for (; *s; s++) { | ||
| 498 | + unsigned char c = (unsigned char)*s; | ||
| 499 | + if (c <= 0x20 || c >= 0x7F) return 0; | ||
| 500 | + if (strchr("()<>@,;:\\\"/[]?={}", c)) return 0; | ||
| 501 | + } | ||
| 502 | + return 1; | ||
| 503 | +} | ||
| 504 | + | ||
| 505 | +static int header_value_ok(const char *s) | ||
| 506 | +{ | ||
| 507 | + if (!s) return 1; | ||
| 508 | + for (; *s; s++) { | ||
| 509 | + if (*s == '\r' || *s == '\n' || *s == '\0') return 0; | ||
| 510 | + } | ||
| 511 | + return 1; | ||
| 512 | +} | ||
| 513 | + | ||
| 514 | +int wh_hook_validate(const wh_hook *h, char *err, size_t errsz) | ||
| 515 | +{ | ||
| 516 | + wh_url u; | ||
| 517 | + char uerr[160]; | ||
| 518 | + int i; | ||
| 519 | + | ||
| 520 | + if (err && errsz) err[0] = '\0'; | ||
| 521 | + if (!h->name[0]) { | ||
| 522 | + if (err) snprintf(err, errsz, "a hook needs a name"); | ||
| 523 | + return -1; | ||
| 524 | + } | ||
| 525 | + for (i = 0; h->name[i]; i++) { | ||
| 526 | + unsigned char c = (unsigned char)h->name[i]; | ||
| 527 | + if (!(isalnum(c) || c == '-' || c == '_' || c == '.')) { | ||
| 528 | + if (err) snprintf(err, errsz, | ||
| 529 | + "hook names may contain letters, digits, dash, " | ||
| 530 | + "underscore and dot only"); | ||
| 531 | + return -1; | ||
| 532 | + } | ||
| 533 | + } | ||
| 534 | + if (wh_url_parse(h->url, &u, uerr, sizeof uerr) != 0) { | ||
| 535 | + if (err) snprintf(err, errsz, "url: %s", uerr); | ||
| 536 | + return -1; | ||
| 537 | + } | ||
| 538 | + if (!wh_method_ok(h->method)) { | ||
| 539 | + if (err) snprintf(err, errsz, "method must be one of GET, POST, PUT, PATCH, DELETE, HEAD"); | ||
| 540 | + return -1; | ||
| 541 | + } | ||
| 542 | + if (h->sig[0] && strcmp(h->sig, WH_SIG_GITHUB) != 0 && | ||
| 543 | + strcmp(h->sig, WH_SIG_GITLAB) != 0 && strcmp(h->sig, WH_SIG_V2) != 0) { | ||
| 544 | + if (err) snprintf(err, errsz, "unknown signature scheme"); | ||
| 545 | + return -1; | ||
| 546 | + } | ||
| 547 | + if (h->sig[0] && !h->secret[0]) { | ||
| 548 | + if (err) snprintf(err, errsz, "a signature scheme needs a secret"); | ||
| 549 | + return -1; | ||
| 550 | + } | ||
| 551 | + if (h->nheaders < 0 || h->nheaders > WH_MAX_HEADERS) { | ||
| 552 | + if (err) snprintf(err, errsz, "too many headers (max %d)", WH_MAX_HEADERS); | ||
| 553 | + return -1; | ||
| 554 | + } | ||
| 555 | + for (i = 0; i < h->nheaders; i++) { | ||
| 556 | + if (!header_name_ok(h->headers[i].name)) { | ||
| 557 | + if (err) snprintf(err, errsz, "header %d has an invalid name", i + 1); | ||
| 558 | + return -1; | ||
| 559 | + } | ||
| 560 | + if (!header_value_ok(h->headers[i].value)) { | ||
| 561 | + if (err) snprintf(err, errsz, | ||
| 562 | + "header %s has a newline in its value", | ||
| 563 | + h->headers[i].name); | ||
| 564 | + return -1; | ||
| 565 | + } | ||
| 566 | + } | ||
| 567 | + return 0; | ||
| 568 | +} | ||
| 569 | + | ||
| 570 | +/* ------------------------------------------------------------- apply a body */ | ||
| 571 | + | ||
| 572 | +static int apply_obj(wh_hook *h, yyjson_val *root, const wh_hook *existing, | ||
| 573 | + char *err, size_t errsz) | ||
| 574 | +{ | ||
| 575 | + const char *v; | ||
| 576 | + yyjson_val *hdrs; | ||
| 577 | + | ||
| 578 | + v = jstr(root, "name"); | ||
| 579 | + if (v) copy_trunc(h->name, sizeof h->name, v); | ||
| 580 | + v = jstr(root, "url"); | ||
| 581 | + if (v) copy_trunc(h->url, sizeof h->url, v); | ||
| 582 | + v = jstr(root, "desc"); | ||
| 583 | + if (v) copy_trunc(h->desc, sizeof h->desc, v); | ||
| 584 | + v = jstr(root, "method"); | ||
| 585 | + if (v) { | ||
| 586 | + size_t i; | ||
| 587 | + char m[8]; | ||
| 588 | + copy_trunc(m, sizeof m, v); | ||
| 589 | + for (i = 0; m[i]; i++) m[i] = (char)toupper((unsigned char)m[i]); | ||
| 590 | + copy_trunc(h->method, sizeof h->method, m); | ||
| 591 | + } | ||
| 592 | + if (!h->method[0]) copy_trunc(h->method, sizeof h->method, "POST"); | ||
| 593 | + | ||
| 594 | + v = jstr(root, "sig"); | ||
| 595 | + if (v) { | ||
| 596 | + if (!*v || strcmp(v, WH_SIG_NONE) == 0) h->sig[0] = '\0'; | ||
| 597 | + else copy_trunc(h->sig, sizeof h->sig, v); | ||
| 598 | + } | ||
| 599 | + | ||
| 600 | + /* A secret is never echoed back, so an empty incoming value means "keep the | ||
| 601 | + * stored one". Rotating a secret is a save with a new value; clearing it is | ||
| 602 | + * an explicit sig=none. */ | ||
| 603 | + v = jstr(root, "secret"); | ||
| 604 | + if (v && *v) copy_trunc(h->secret, sizeof h->secret, v); | ||
| 605 | + else if (!h->sig[0]) h->secret[0] = '\0'; | ||
| 606 | + | ||
| 607 | + hdrs = yyjson_obj_get(root, "headers"); | ||
| 608 | + if (hdrs && yyjson_is_arr(hdrs)) { | ||
| 609 | + size_t i, n = yyjson_arr_size(hdrs); | ||
| 610 | + int out = 0; | ||
| 611 | + for (i = 0; i < n && out < WH_MAX_HEADERS; i++) { | ||
| 612 | + yyjson_val *e = yyjson_arr_get(hdrs, i); | ||
| 613 | + const char *nm = jstr(e, "name"); | ||
| 614 | + const char *val = jstr(e, "value"); | ||
| 615 | + int k, kept = 0; | ||
| 616 | + if (!nm || !*nm) continue; | ||
| 617 | + copy_trunc(h->headers[out].name, sizeof h->headers[out].name, nm); | ||
| 618 | + h->headers[out].value[0] = '\0'; | ||
| 619 | + if (val) { | ||
| 620 | + copy_trunc(h->headers[out].value, sizeof h->headers[out].value, val); | ||
| 621 | + } else if (existing) { | ||
| 622 | + /* no value supplied: keep the stored value for this name */ | ||
| 623 | + for (k = 0; k < existing->nheaders; k++) { | ||
| 624 | + if (strcmp(existing->headers[k].name, nm) == 0) { | ||
| 625 | + copy_trunc(h->headers[out].value, | ||
| 626 | + sizeof h->headers[out].value, | ||
| 627 | + existing->headers[k].value); | ||
| 628 | + kept = 1; | ||
| 629 | + break; | ||
| 630 | + } | ||
| 631 | + } | ||
| 632 | + } | ||
| 633 | + (void)kept; | ||
| 634 | + out++; | ||
| 635 | + } | ||
| 636 | + h->nheaders = out; | ||
| 637 | + } | ||
| 638 | + (void)err; | ||
| 639 | + (void)errsz; | ||
| 640 | + return 0; | ||
| 641 | +} | ||
| 642 | + | ||
| 643 | +int wh_hook_apply(wh_hook *h, const char *json, const wh_hook *existing, | ||
| 644 | + char *err, size_t errsz) | ||
| 645 | +{ | ||
| 646 | + yyjson_doc *doc; | ||
| 647 | + yyjson_val *root; | ||
| 648 | + | ||
| 649 | + if (err && errsz) err[0] = '\0'; | ||
| 650 | + if (!json || !*json) { | ||
| 651 | + if (err) snprintf(err, errsz, "empty request body"); | ||
| 652 | + return -1; | ||
| 653 | + } | ||
| 654 | + doc = yyjson_read(json, strlen(json), 0); | ||
| 655 | + if (!doc) { | ||
| 656 | + if (err) snprintf(err, errsz, "request body is not valid JSON"); | ||
| 657 | + return -1; | ||
| 658 | + } | ||
| 659 | + root = yyjson_doc_get_root(doc); | ||
| 660 | + if (!yyjson_is_obj(root)) { | ||
| 661 | + yyjson_doc_free(doc); | ||
| 662 | + if (err) snprintf(err, errsz, "request body must be a JSON object"); | ||
| 663 | + return -1; | ||
| 664 | + } | ||
| 665 | + apply_obj(h, root, existing, err, errsz); | ||
| 666 | + yyjson_doc_free(doc); | ||
| 667 | + return wh_hook_validate(h, err, errsz); | ||
| 668 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..7357b8f | index 0000000..7357b8f | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/wh_store.h | +++ b/src/wh_store.h | ||
| @@ -0,0 +1,108 @@ | @@ -0,0 +1,108 @@ | ||
| 1 | +/* | ||
| 2 | + * wh_store.h - the named-hook store: definitions, secrets, delivery log. | ||
| 3 | + * | ||
| 4 | + * One JSON document on disk, written atomically at mode 0600, in | ||
| 5 | + * | ||
| 6 | + * /workspace/.scorpiox/connectors/plugin_webhook/hooks.json (when /workspace exists) | ||
| 7 | + * ~/.scorpiox/connectors/plugin_webhook/hooks.json (elsewhere) | ||
| 8 | + * | ||
| 9 | + * or wherever WEBHOOK_STORE_PATH points (the offline suite uses that). | ||
| 10 | + * | ||
| 11 | + * Secrets never leave this module in a readable form. Every serializer that | ||
| 12 | + * faces the browser or an MCP client emits, for each header, only its NAME and | ||
| 13 | + * `has_secret: true`; for the HMAC it emits the scheme and `has_secret: true`. | ||
| 14 | + * A hook definition read back from disk is the only place a value exists, and | ||
| 15 | + * it is used for exactly one thing: composing the outbound request. | ||
| 16 | + * | ||
| 17 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 18 | + */ | ||
| 19 | +#ifndef SX_WH_STORE_H | ||
| 20 | +#define SX_WH_STORE_H | ||
| 21 | + | ||
| 22 | +#include <stddef.h> | ||
| 23 | + | ||
| 24 | +#include "wh_http.h" | ||
| 25 | + | ||
| 26 | +#define WH_MAX_HOOKS 64 | ||
| 27 | +#define WH_MAX_HEADERS 16 | ||
| 28 | +#define WH_LOG_MAX 50 | ||
| 29 | +#define WH_NAME_MAX 64 | ||
| 30 | +#define WH_DESC_MAX 200 | ||
| 31 | +#define WH_SECRET_MAX 256 | ||
| 32 | +#define WH_HDRVAL_MAX 1024 | ||
| 33 | + | ||
| 34 | +/* HMAC schemes. Body-only signatures are not offered: they never expire, so a | ||
| 35 | + * captured request can be replayed forever. */ | ||
| 36 | +#define WH_SIG_NONE "" | ||
| 37 | +#define WH_SIG_GITHUB "github" /* X-Hub-Signature-256: sha256=<hex(body)> */ | ||
| 38 | +#define WH_SIG_GITLAB "gitlab" /* X-Gitlab-Token: <secret> (shared token) */ | ||
| 39 | +#define WH_SIG_V2 "v2" /* X-Webhook-Signature: t=<ts>,v1=<hex(ts|.|body)> */ | ||
| 40 | + | ||
| 41 | +typedef struct { | ||
| 42 | + char name[WH_NAME_MAX]; | ||
| 43 | + char url[WH_URL_MAX]; | ||
| 44 | + char method[8]; | ||
| 45 | + char desc[WH_DESC_MAX]; | ||
| 46 | + wh_header headers[WH_MAX_HEADERS]; /* values are secrets */ | ||
| 47 | + int nheaders; | ||
| 48 | + char sig[16]; /* WH_SIG_* */ | ||
| 49 | + char secret[WH_SECRET_MAX]; /* a secret: never serialized out */ | ||
| 50 | +} wh_hook; | ||
| 51 | + | ||
| 52 | +typedef struct { | ||
| 53 | + char at[24]; /* ISO-8601 UTC */ | ||
| 54 | + char name[WH_NAME_MAX]; | ||
| 55 | + int status; | ||
| 56 | + int ok; | ||
| 57 | + long bytes; | ||
| 58 | + long ms; | ||
| 59 | + char error[192]; | ||
| 60 | +} wh_logent; | ||
| 61 | + | ||
| 62 | +typedef struct { | ||
| 63 | + wh_hook hooks[WH_MAX_HOOKS]; | ||
| 64 | + int nhooks; | ||
| 65 | + wh_logent log[WH_LOG_MAX]; | ||
| 66 | + int nlog; | ||
| 67 | +} wh_store; | ||
| 68 | + | ||
| 69 | +/* Path of the store file (created parents not included). Always writes. */ | ||
| 70 | +void wh_store_path(char *out, size_t outsz); | ||
| 71 | + | ||
| 72 | +/* Load the document. A missing file is an empty store (returns 0). A file that | ||
| 73 | + * exists but cannot be read costs a diagnostic in `err` and an empty store, so | ||
| 74 | + * the UI can say why the list is empty instead of pretending there are none. */ | ||
| 75 | +int wh_store_load(wh_store *s, char *err, size_t errsz); | ||
| 76 | + | ||
| 77 | +/* Write atomically (tmp + rename) at mode 0600. Returns 0 on success. */ | ||
| 78 | +int wh_store_save(const wh_store *s, char *err, size_t errsz); | ||
| 79 | + | ||
| 80 | +/* Find a hook by name (exact). NULL when absent. */ | ||
| 81 | +wh_hook *wh_hook_find(wh_store *s, const char *name); | ||
| 82 | + | ||
| 83 | +/* Remove hook at index, shifting the rest. */ | ||
| 84 | +void wh_hook_remove(wh_store *s, int idx); | ||
| 85 | + | ||
| 86 | +/* Append to the delivery log, newest first, dropping the oldest beyond | ||
| 87 | + * WH_LOG_MAX. */ | ||
| 88 | +void wh_store_log_add(wh_store *s, const wh_logent *e); | ||
| 89 | + | ||
| 90 | +/* ---- serializers ------------------------------------------------------- | ||
| 91 | + * `redacted` emits names + has_secret only (browser / MCP). Never pass a | ||
| 92 | + * secret-bearing document to a caller that writes it to a response. */ | ||
| 93 | +void wh_hook_json(const wh_hook *h, int redacted, char *out, size_t outsz); | ||
| 94 | +void wh_store_json(const wh_store *s, int redacted, char *out, size_t outsz); | ||
| 95 | +/* "hooks" array + "log" array + counts, the shape every read route returns. */ | ||
| 96 | +void wh_store_list_json(const wh_store *s, char *out, size_t outsz); | ||
| 97 | + | ||
| 98 | +/* Apply a JSON object (as sent by the UI or an MCP call) onto `h`, keeping the | ||
| 99 | + * stored secret for any header whose value is absent, and keeping the stored | ||
| 100 | + * HMAC secret when the incoming secret is empty. Returns 0 on success or -1 | ||
| 101 | + * with a human-readable reason. */ | ||
| 102 | +int wh_hook_apply(wh_hook *h, const char *json, const wh_hook *existing, | ||
| 103 | + char *err, size_t errsz); | ||
| 104 | + | ||
| 105 | +/* Validate a hook (URL shape, method, name, header names). Returns 0 or -1. */ | ||
| 106 | +int wh_hook_validate(const wh_hook *h, char *err, size_t errsz); | ||
| 107 | + | ||
| 108 | +#endif /* SX_WH_STORE_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..df6d23a | index 0000000..df6d23a | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/wh_tls.c | +++ b/src/wh_tls.c | ||
| @@ -0,0 +1,248 @@ | @@ -0,0 +1,248 @@ | ||
| 1 | +/* | ||
| 2 | + * wh_tls.c - mbedTLS over an already-connected socket (POSIX). | ||
| 3 | + * | ||
| 4 | + * The socket arrives pre-validated and pre-connected by wh_http.c (the SSRF | ||
| 5 | + * check ran on the numeric address before connect, and we connected to that | ||
| 6 | + * exact address), so this layer only wraps TLS around it. No DNS here and no | ||
| 7 | + * second connect, therefore no window in which a rebinding DNS answer could | ||
| 8 | + * move the connection to a private address after the check. | ||
| 9 | + * | ||
| 10 | + * _WIN32: WinHTTP does TLS itself; this file compiles to nothing there. | ||
| 11 | + * | ||
| 12 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 13 | + */ | ||
| 14 | +#include "wh_tls.h" | ||
| 15 | + | ||
| 16 | +#if !defined(_WIN32) | ||
| 17 | + | ||
| 18 | +#ifndef _POSIX_C_SOURCE | ||
| 19 | +#define _POSIX_C_S |