scorpiox-bot-plugin-websearch
←run.shbash
447 lines · 22 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - the offline proof for plugin_websearch.
3#
4# Everything runs against ./plugin_websearch with the connector state directory
5# pointed at a scratch dir and every provider pointed at tests/mockapi.py on
6# loopback, so the suite never touches a real search service, never needs a real
7# credential, and never depends on the internet.
8#
9# Sections:
10# --meta the node's chip contract (1-2 word name, <= 15 char desc,
11# kind/mcp/daemon/menus) and SX_PLUGIN_META=1 agreeing
12# --schema the tool array is valid JSON, both tools carry an inputSchema
13# --mcp initialize / notifications/initialized / ping / tools/list /
14# tools/call and the JSON-RPC error shapes
15# requests every provider is compared against what the mock actually
16# RECEIVED: method, path, query, credential and JSON body
17# errors a wrong key is the provider's own 401 text, an unreachable host
18# is a clean error, an unknown provider is a tool error
19# config config.json round-trips at 0600, the environment overrides it,
20# and no response ever contains a key
21# CGI a missing node password is 401, ?theme=/?embed= are honoured,
22# and the page has no <script src= and no CDN reference
23# source no popen/system, no credential literal, no LAN address
24#
25# Exit code 0 = everything passed.
26
27set -u
28
29ROOT=$(cd "$(dirname "$0")/.." && pwd)
30cd "$ROOT" || exit 1
31
32BIN=${BIN:-./plugin_websearch}
33WORK=$(mktemp -d "${TMPDIR:-/tmp}/ws-suite.XXXXXX")
34PORTFILE="$WORK/port"
35LOG="$WORK/req.jsonl"
36CFGDIR="$WORK/cfg"
37MOCK_PID=""
38
39cleanup() {
40 [ -n "$MOCK_PID" ] && kill "$MOCK_PID" 2>/dev/null
41 rm -rf "$WORK"
42}
43trap cleanup EXIT INT TERM
44
45PASS=0
46FAIL=0
47SKIP=0
48
49if [ -t 1 ]; then
50 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m')
51 C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
52else
53 C_OK=; C_BAD=; C_B=; C_0=
54fi
55pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
56fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
57skip() { SKIP=$((SKIP + 1)); printf ' -- %s (skipped: %s)\n' "$1" "$2"; }
58section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
59
60check() { # check <label> <expected-substring> <text|file>
61 if [ -f "$3" ]; then set -- "$1" "$2" "$(cat "$3")"; fi
62 if printf '%s' "${3:-}" | grep -F -q -- "$2"; then pass "$1"; else
63 fail "$1 (want: $2)"
64 printf ' got: %s\n' "$(printf '%s' "${3:-}" | head -c 300)"
65 fi
66}
67check_not() { # check_not <label> <forbidden-substring> <text|file>
68 if [ -f "$3" ]; then set -- "$1" "$2" "$(cat "$3")"; fi
69 if printf '%s' "${3:-}" | grep -F -q -- "$2"; then
70 fail "$1 (must NOT contain: $2)"
71 printf ' got: %s\n' "$(printf '%s' "${3:-}" | head -c 300)"
72 else pass "$1"; fi
73}
74json_ok() { # json_ok <label> <json> [python expr over `d`]
75 expr=${3:-True}
76 printf '%s' "${2:-}" > "$WORK/j.json"
77 if python3 -c "import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if ($expr) else 1)" \
78 "$WORK/j.json" 2>/dev/null; then
79 pass "$1"
80 else
81 fail "$1 (invalid JSON or failed assertion)"
82 printf ' got: %s\n' "$(printf '%s' "${2:-}" | head -c 300)"
83 fi
84}
85body() { # strip the CGI header block, keep the payload
86 printf '%s\n' "${1:-}" | tr -d '\r' | awk 'p{print} /^$/{p=1}'
87}
88mcp() { # mcp <json-lines-file> -> stdout
89 ( cd "$ROOT" && "$BIN" --mcp < "$1" )
90}
91call() { # call <id> <tool> <args-json> -> the structuredContent / error line
92 printf '{"jsonrpc":"2.0","id":%s,"method":"tools/call","params":{"name":"%s","arguments":%s}}\n' \
93 "$1" "$2" "$3" > "$WORK/one.jsonl"
94 mcp "$WORK/one.jsonl" | python3 -c '
95import json,sys
96d=json.loads(sys.stdin.readline())
97r=d.get("result") or {}
98if r.get("isError"):
99 print("ERROR " + json.dumps(r.get("structuredContent") or {}))
100else:
101 print(json.dumps(r.get("structuredContent") or {}))
102'
103}
104cgi() { # cgi <query> [method] [body] -> full stdout
105 qs="$1"; m="${2:-GET}"; data="${3:-}"
106 printf '%s' "$data" > "$WORK/in.bin"
107 QUERY_STRING="$qs" REQUEST_METHOD="$m" CONTENT_LENGTH="${#data}" \
108 BOT_PASSWORD="" SWEBSEARCH_CONFIG_DIR="$CFGDIR" \
109 WEBSEARCH_MOCK_BASE="$MOCK" "$BIN" < "$WORK/in.bin"
110}
111
112export SWEBSEARCH_CONFIG_DIR="$CFGDIR"
113export BRAVE_API_KEY=BRV-TEST-KEY-1
114export TAVILY_API_KEY=TVL-TEST-KEY-1
115export EXA_API_KEY=EXA-TEST-KEY-1
116export PERPLEXITY_API_KEY=PPX-TEST-KEY-1
117
118mkdir -p "$CFGDIR"
119rm -f "$LOG"
120
121if [ ! -x "$BIN" ]; then
122 echo "plugin_websearch is not built - run make first" >&2
123 exit 1
124fi
125
126# ------------------------------------------------------------------ mock
127python3 tests/mockapi.py --portfile "$PORTFILE" --log "$LOG" 2>"$WORK/mock.err" &
128MOCK_PID=$!
129i=0
130while [ ! -s "$PORTFILE" ] && [ $i -lt 100 ]; do
131 i=$((i + 1)); sleep 0.05
132done
133if [ ! -s "$PORTFILE" ]; then
134 echo "the mock server did not start: $(cat "$WORK/mock.err")" >&2
135 exit 1
136fi
137MOCK="http://127.0.0.1:$(cat "$PORTFILE")"
138export WEBSEARCH_MOCK_BASE="$MOCK"
139export WEBSEARCH_SEARXNG_BASE="$MOCK/searxng"
140
141# ---------------------------------------------------------------- --meta
142section "--meta / discovery"
143META=$("$BIN" --meta)
144json_ok "--meta is one line of valid JSON" "$META"
145json_ok "name is websearch" "$META" 'd["name"]=="websearch"'
146json_ok "desc is <= 15 chars" "$META" 'len(d["desc"])<=15'
147json_ok "kind is mcp, mcp true, menus false" \
148 "$META" 'd["kind"]=="mcp" and d["mcp"] is True and d["menus"] is False'
149json_ok "daemon is false" "$META" 'd["daemon"] is False'
150json_ok "category is network" "$META" 'd["category"]=="network"'
151json_ok "verified is mock (an honest tier: the suite drives a mock, not a paid key)" \
152 "$META" 'd["verified"]=="mock"'
153check "SX_PLUGIN_META=1 agrees" '"name":"websearch"' "$(SX_PLUGIN_META=1 "$BIN")"
154json_ok "--meta version agrees with plugin.json" "$META" \
155 'd["version"]==__import__("json").load(open("plugin.json"))["version"]'
156VER=$(python3 -c 'import json;print(json.load(open("plugin.json"))["version"])')
157check "--version agrees with plugin.json" "$VER" "$("$BIN" --version)"
158check "--help mentions the tool names" 'web_search' "$("$BIN" --help)"
159
160# -------------------------------------------------------------- --schema
161section "--schema / --mcp tool list"
162SCHEMA=$("$BIN" --schema)
163json_ok "--schema is valid JSON" "$SCHEMA"
164json_ok "two tools are declared" "$SCHEMA" 'len(d["tools"])==2'
165json_ok "every tool has an inputSchema" \
166 "$SCHEMA" 'all("inputSchema" in t and t["inputSchema"].get("type")=="object" for t in d["tools"])'
167json_ok "web_search requires query" \
168 "$SCHEMA" 'any(t["name"]=="web_search" and t["inputSchema"]["required"]==["query"] for t in d["tools"])'
169json_ok "the provider enum lists all six backends" \
170 "$SCHEMA" 'len([e for t in d["tools"] if t["name"]=="web_search" for e in t["inputSchema"]["properties"]["provider"]["enum"]])==6'
171
172cat > "$WORK/mcp.jsonl" <<'EOF'
173{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","clientInfo":{"name":"t","version":"0"}}}
174{"jsonrpc":"2.0","method":"notifications/initialized"}
175{"jsonrpc":"2.0","id":2,"method":"ping"}
176{"jsonrpc":"2.0","id":3,"method":"tools/list"}
177{"jsonrpc":"2.0","id":4,"method":"resources/list"}
178{"jsonrpc":"2.0","id":5,"method":"prompts/list"}
179{"jsonrpc":"2.0","id":6,"method":"no/such/method"}
180not json at all
181{"jsonrpc":"2.0","id":7}
182EOF
183MCPOUT=$(mcp "$WORK/mcp.jsonl")
184check "initialize answers the protocol version" '"protocolVersion":"2025-06-18"' "$MCPOUT"
185check "initialize names the server" '"name":"websearch-server"' "$MCPOUT"
186check "ping answers an empty result" '"id":2,"result":{}' "$MCPOUT"
187check "resources/list is empty, not an error" '"resources":[]' "$MCPOUT"
188check "prompts/list is empty, not an error" '"prompts":[]' "$MCPOUT"
189check "an unknown method is -32601" '"code":-32601' "$MCPOUT"
190check "unparseable input is -32700 with id null" '"id":null,"error":{"code":-32700' "$MCPOUT"
191check "a request without a method is -32600" '"code":-32600' "$MCPOUT"
192N_RESP=$(printf '%s\n' "$MCPOUT" | grep -c '^{')
193if [ "$N_RESP" = 8 ]; then
194 pass "one response per request (7 requests + 1 parse error), none for the notification"
195else
196 fail "expected 8 responses (1 notification silent), got $N_RESP"
197fi
198json_ok "every response line is valid JSON" \
199 "$(printf '%s\n' "$MCPOUT" | python3 -c 'import sys,json; print(json.dumps([json.loads(l) for l in sys.stdin if l.strip()]))')"
200
201# --------------------------------------------------------------- requests
202section "each provider sends what its API requires"
203: > "$LOG"
204R=$(call 1 web_search '{"query":"rust lang","provider":"duckduckgo","count":3}')
205json_ok "duckduckgo: ok, 3 results, parsed title/url/snippet" "$R" \
206 'd["ok"] and d["count"]==3 and d["results"][0]["url"].startswith("https://example0.test")'
207json_ok "duckduckgo: entities decoded and tags stripped" "$R" \
208 'd["results"][0]["title"].startswith("Result & 0") and "b>rust" not in d["results"][0]["title"]'
209json_ok "duckduckgo: the /l/?uddg= redirect was unwrapped" "$R" \
210 'd["results"][1]["url"]=="https://example1.test/page1"'
211json_ok "duckduckgo: site is the host" "$R" 'd["results"][0]["site"]=="example0.test"'
212
213R=$(call 2 web_search '{"query":"rust lang","provider":"brave","count":2,"country":"NZ","freshness":"week"}')
214json_ok "brave: ok with 2 results" "$R" 'd["ok"] and d["count"]==2'
215R=$(call 3 web_search '{"query":"a b","provider":"tavily","count":2}')
216json_ok "tavily: ok with 2 results" "$R" 'd["ok"] and d["count"]==2'
217R=$(call 4 web_search '{"query":"a b","provider":"exa","count":2}')
218json_ok "exa: ok with 2 results" "$R" 'd["ok"] and d["count"]==2'
219json_ok "exa: the highlight became the snippet" "$R" 'd["results"][0]["snippet"].startswith("exa highlight")'
220R=$(call 5 web_search '{"query":"a b","provider":"perplexity","count":2}')
221json_ok "perplexity: ok with 2 results" "$R" 'd["ok"] and d["count"]==2'
222R=$(call 6 web_search '{"query":"a b","provider":"searxng","count":2}')
223json_ok "searxng: ok with 2 results" "$R" 'd["ok"] and d["count"]==2'
224
225python3 - "$LOG" <<'PY'
226import json, sys
227reqs = [json.loads(l) for l in open(sys.argv[1]) if l.strip()]
228def one(path):
229 for r in reqs:
230 if r["path"] == path:
231 return r
232 return None
233fails = []
234def want(desc, cond, detail=""):
235 if cond:
236 print(" ok %s" % desc)
237 else:
238 fails.append(desc)
239 print(" FAIL %s%s" % (desc, (" (" + str(detail)[:200] + ")") if detail else ""))
240
241d = one("/duckduckgo/html/")
242want("duckduckgo is a POST to /html/ (a GET gets a challenge page)",
243 d and d["method"] == "POST", d)
244want("duckduckgo sends the query urlencoded in the form body",
245 d and "q=rust%20lang" in (d["body"] or ""), d)
246want("duckduckgo sends the safe-search parameter", d and "kp=-1" in (d["body"] or ""), d)
247
248b = one("/brave/res/v1/web/search")
249want("brave is a GET to /res/v1/web/search", b and b["method"] == "GET", b)
250want("brave sends X-Subscription-Token", b and b["cred"] == "BRV-TEST-KEY-1", b)
251want("brave sends count, country and freshness",
252 b and b["query"].get("count") == "2" and b["query"].get("country") == "NZ"
253 and b["query"].get("freshness") == "week", b)
254
255t = one("/tavily/search")
256want("tavily is a POST with a JSON body", t and t["method"] == "POST", t)
257want("tavily sends the key as a bearer", t and t["cred"] == "Bearer TVL-TEST-KEY-1", t)
258want("tavily sends query and max_results",
259 t and t["body"].get("query") == "a b" and t["body"].get("max_results") == 2, t)
260
261e = one("/exa/search")
262want("exa is a POST with x-api-key", e and e["method"] == "POST" and e["cred"] == "EXA-TEST-KEY-1", e)
263want("exa sends numResults and a contents block",
264 e and e["body"].get("numResults") == 2 and e["body"].get("contents", {}).get("highlights") is True, e)
265
266p = one("/perplexity/search")
267want("perplexity is a POST with a bearer", p and p["method"] == "POST"
268 and p["cred"] == "Bearer PPX-TEST-KEY-1", p)
269want("perplexity sends query and max_results",
270 p and p["body"].get("query") == "a b" and p["body"].get("max_results") == 2, p)
271
272s = one("/searxng/search")
273want("searxng is a GET with format=json", s and s["method"] == "GET"
274 and s["query"].get("format") == "json", s)
275want("searxng sends the query and categories",
276 s and s["query"].get("q") == "a b" and s["query"].get("categories") == "general", s)
277
278sys.exit(1 if fails else 0)
279PY
280if [ $? -eq 0 ]; then PASS=$((PASS + 1)); else FAIL=$((FAIL + 1)); fi
281
282# ----------------------------------------------------------------- errors
283section "failures are reported, never swallowed"
284R=$(BRAVE_API_KEY=WRONG call 7 web_search '{"query":"q","provider":"brave"}')
285check "a wrong brave key is the provider's own 401" 'HTTP 401' "$R"
286check "the 401 text is the provider's message, not ours" 'invalid subscription token' "$R"
287R=$(TAVILY_API_KEY=WRONG call 8 web_search '{"query":"q","provider":"tavily"}')
288check "a wrong tavily key is a 401 tool error" 'HTTP 401' "$R"
289R=$(call 9 web_search '{"query":"q","provider":"nope"}')
290check "an unknown provider explains the choices" 'unknown provider' "$R"
291R=$(call 10 web_search '{}')
292check "a missing query is a tool error" 'query is required' "$R"
293R=$(call 11 web_search '{"query":"q","provider":"perplexity"}' )
294json_ok "a provider with no key still answers ok when one is set" "$R" 'd["ok"] or "Perplexity" in d.get("error","")'
295R=$(PERPLEXITY_API_KEY= WEBSEARCH_PPLX_KEY= call 12 web_search '{"query":"q","provider":"perplexity"}')
296check "a provider with no key says so, by name" 'Perplexity needs an API key' "$R"
297# WEBSEARCH_MOCK_BASE also fills searxng_base, so it has to be cleared too for
298# the "not configured" branch to be reachable at all.
299R=$(WEBSEARCH_MOCK_BASE= WEBSEARCH_SEARXNG_BASE= SEARXNG_URL= \
300 call 13 web_search '{"query":"q","provider":"searxng"}')
301check "searxng with no base URL says so, by name" 'SearXNG needs a base URL' "$R"
302R=$(WEBSEARCH_MOCK_BASE= WEBSEARCH_DDG_BASE=http://127.0.0.1:1 call 14 web_search '{"query":"q","provider":"duckduckgo"}')
303check "an unreachable host is a clean error, not a hang" 'connect' "$R"
304R=$(call 15 web_search '{"query":"q","provider":"ddg"}')
305check "the provider id is matched exactly" 'unknown provider' "$R"
306
307# --------------------------------------------------------------- config
308section "config.json round-trip and secret hygiene"
309rm -rf "$CFGDIR"; mkdir -p "$CFGDIR"
310SAVE=$(cgi "action=save&format=json" POST \
311 '{"action":"save","brave_key":"BRV-SAVED-1","tavily_key":"","exa_key":"EXA-SAVED-1","provider":"exa","count":"7","safe":"strict"}')
312json_ok "save answers the provider map" "$(body "$SAVE")" '"providers" in d'
313body "$SAVE" > "$WORK/save.json"
314json_ok "the saved provider became the active one" "$(cat "$WORK/save.json")" 'd["active"]=="exa"'
315json_ok "the saved count round-trips" "$(cat "$WORK/save.json")" 'd["default_count"]==7'
316json_ok "the saved safe-search round-trips" "$(cat "$WORK/save.json")" 'd["safe"]=="strict"'
317check_not "the save response never echoes the key" 'BRV-SAVED-1' "$SAVE"
318check_not "the save response never echoes the other key" 'EXA-SAVED-1' "$SAVE"
319if [ -f "$CFGDIR/config.json" ]; then
320 pass "config.json was written in the connector dir"
321 MODE=$(stat -c '%a' "$CFGDIR/config.json" 2>/dev/null || stat -f '%Lp' "$CFGDIR/config.json")
322 if [ "$MODE" = "600" ]; then pass "config.json is mode 0600"; else fail "config.json mode is $MODE, want 600"; fi
323 check "the key really is in the file" 'BRV-SAVED-1' "$CFGDIR/config.json"
324else
325 fail "config.json was not created"
326fi
327# The environment outranks the file: a saved "" for tavily must still lose to
328# TAVILY_API_KEY, and a saved value must lose to a different env value.
329PROV=$(SWEBSEARCH_CONFIG_DIR="$CFGDIR" BRAVE_API_KEY=ENV-WINS cgi "action=providers&format=json" GET)
330body "$PROV" > "$WORK/prov.json"
331json_ok "the env key outranks the saved one (brave has_key still true)" "$(cat "$WORK/prov.json")" \
332 'any(p["id"]=="brave" and p["has_key"] for p in d["providers"])'
333check_not "the providers response never carries a key" 'ENV-WINS' "$PROV"
334check_not "the providers response never carries the saved key" 'BRV-SAVED-1' "$PROV"
335CLEAR=$(SWEBSEARCH_CONFIG_DIR="$CFGDIR" BRAVE_API_KEY= cgi "action=save&format=json" POST \
336 '{"action":"save","clear_brave_key":1}')
337check_not "clearing a key removes it from the file" 'BRV-SAVED-1' "$CFGDIR/config.json"
338BAD=$(cgi "action=save&format=json" POST '{"action":"save","brave_base":"ftp://x"}')
339check "a non-http base URL is refused" 'must start with http' "$BAD"
340UNK=$(cgi "action=nope&format=json" GET)
341check "an unknown action is a 404" 'unknown action' "$UNK"
342
343# ------------------------------------------------------------------- CGI
344section "the page and its auth gate"
345UNAUTH=$(QUERY_STRING="" REQUEST_METHOD=GET BOT_PASSWORD=pw SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN")
346check "GET with no credential is 401 when a node password is set" '401 Unauthorized' "$UNAUTH"
347AUTHED=$(QUERY_STRING="pwd=pw" REQUEST_METHOD=GET BOT_PASSWORD=pw SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN")
348check "GET with ?pwd= is 200" 'Content-Type: text/html' "$AUTHED"
349HDR=$(QUERY_STRING="" REQUEST_METHOD=GET BOT_PASSWORD=pw HTTP_X_BOT_PASSWORD=pw \
350 SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN")
351check "GET with X-Bot-Password is 200" 'Content-Type: text/html' "$HDR"
352BEARER=$(QUERY_STRING="" REQUEST_METHOD=GET BOT_PASSWORD=pw HTTP_AUTHORIZATION="Bearer pw" \
353 SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN")
354check "GET with a bearer token is 200" 'Content-Type: text/html' "$BEARER"
355PAGE=$(QUERY_STRING="theme=light&embed=1" REQUEST_METHOD=GET BOT_PASSWORD="" \
356 SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN")
357check_not "the page has no external script tag" '<script src=' "$PAGE"
358check_not "the page references no CDN" 'cdnjs' "$PAGE"
359check_not "the page references no unpkg" 'unpkg' "$PAGE"
360check "the page carries the bot theme tokens" '--bg:' "$PAGE"
361check "the page carries the theme prepaint/handoff script" 'sxApplyTheme' "$PAGE"
362check "the page has the provider list container" 'id="providers"' "$PAGE"
363check "the page has a search box" 'id="q"' "$PAGE"
364check "the page has the key fields" 'id="k_brave"' "$PAGE"
365check "the page asks for an sx-theme from its host" 'sx-theme-request' "$PAGE"
366json_ok "embed=1 does not break the page (still valid HTML head)" \
367 "$(printf '%s' "$PAGE" | grep -c 'DOCTYPE html' >/dev/null && echo '{"ok":1}')"
368EMBED=$(printf '%s' "$PAGE" | grep -c 'class="embedded"\|embed-hide')
369if [ "$EMBED" -ge 1 ]; then pass "the embed-mode rules are present"; else fail "no embed-mode markup"; fi
370INFO=$(cgi "action=info&format=json" GET)
371body "$INFO" > "$WORK/info.json"
372json_ok "action=info reports the id, kind and providers" "$(cat "$WORK/info.json")" \
373 'd["id"]=="plugin_websearch" and d["kind"]=="mcp" and len(d["providers"])==6'
374SEARCHAPI=$(cgi "action=search&format=json&q=rust+lang&provider=duckduckgo&count=2" GET)
375body "$SEARCHAPI" > "$WORK/api.json"
376json_ok "action=search answers real results" "$(cat "$WORK/api.json")" \
377 'd["ok"] and d["count"]==2 and d["provider"]=="duckduckgo"'
378NOPWD=$(QUERY_STRING="action=providers&format=json" REQUEST_METHOD=GET BOT_PASSWORD=pw \
379 SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN")
380check "the JSON API is behind the same auth gate" '401 Unauthorized' "$NOPWD"
381
382# ---------------------------------------------------------------- build cmd
383section "the advertised build command actually builds the plugin"
384# `build_cmd_posix` is what the marketplace's "copy the agent build command"
385# button hands to a user's agent, so a wrong string is a broken promise - and
386# the CLI's pre-1.4.0 default was a single-source `cc` line that cannot build a
387# repo with six sources and two vendored libraries. The author declares it here
388# (rule 1 of the CLI's own precedence) and this asserts the declaration is the
389# one that works, not merely that it exists.
390json_ok "plugin.json declares build_cmd_posix" "$(cat plugin.json)" \
391 'd.get("build_cmd_posix")=="make"'
392json_ok "plugin.json declares build_cmd_win64" "$(cat plugin.json)" \
393 'd.get("build_cmd_win64")=="make win64"'
394json_ok "the declared win64 build is a real Makefile target" "$(cat plugin.json)" \
395 'open("Makefile").read().find("\nwin64:") >= 0'
396# the legacy single-source line is provably wrong here: it neither passes -I nor
397# names the vendored translation units. Prove that rather than assert it.
398if [ "$(ls src/*.c | wc -l)" -gt 1 ]; then
399 pass "repo has more than one translation unit (a one-line cc cannot build it)"
400else
401 fail "expected more than one source file"
402fi
403if grep -q -- '-I vendor' Makefile; then
404 pass "the Makefile passes -I vendor (the one-line cc does not)"
405else
406 fail "Makefile does not pass -I vendor"
407fi
408
409# ---------------------------------------------------------------- source
410section "source guards"
411if grep -rn --include='*.c' --include='*.h' -E '\b(popen|system|execv|fork)\s*\(' src/ >/dev/null 2>&1; then
412 fail "src/ must not spawn a process"
413else pass "src/ spawns no process (no popen/system/exec/fork)"; fi
414if grep -rn --include='*.c' --include='*.h' -E 'ghp_[A-Za-z0-9]{10}|hf_[A-Za-z0-9]{10}' src/ >/dev/null 2>&1; then
415 fail "src/ carries a credential literal"
416else pass "src/ carries no credential literal"; fi
417if grep -rn --include='*.c' --include='*.h' -E '192[.]168[.]|10[.][0-9]+[.][0-9]+[.]' src/*.c src/*.h >/dev/null 2>&1; then
418 fail "src/ carries a private address"
419else pass "src/ carries no private address literal"; fi
420if grep -rn --include='*.c' 'yyjson_mut_obj_add_str(' src/ >/dev/null 2>&1; then
421 fail "yyjson_mut_obj_add_str stores the caller's pointer - use the strcpy form"
422else pass "no non-copying yyjson string constructor is used"; fi
423if grep -n 'require_node_auth' src/plugin_websearch.c | grep -q .; then
424 pass "the CGI path calls require_node_auth()"
425else fail "require_node_auth() is not called"; fi
426if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
427 pass "src/ui_html.h matches src/ui.html"
428else fail "src/ui_html.h is stale (run make ui)"; fi
429# A one-line header edit must force a rebuild. `make` used to treat only
430# src/*.c and the generated UI header as prerequisites, so a version bump in
431# src/ws.h left "Nothing to be done" and the previous binary in place - the
432# build reported success with a stale artefact (the failure this project
433# keeps paying for). Pin the rule, not the belief.
434if grep -q '^HDR ' Makefile && grep -q '\$(HDR)' Makefile; then
435 pass "Makefile makes every header a rebuild prerequisite"
436else
437 fail "Makefile does not depend on src/*.h - a header edit would not rebuild"
438fi
439
440# --------------------------------------------------------------- summary
441printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
442printf 'PASS=%d FAIL=%d SKIP=%d\n' "$PASS" "$FAIL" "$SKIP"
443if [ "$FAIL" -ne 0 ]; then
444 echo "SUITE-FAIL"
445 exit 1
446fi
447echo "SUITE-OK"