scorpiox-bot-plugin-time
←run.shbash
603 lines · 34 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_time across all its modes.
3#
4# Everything runs against ./plugin_time with SX_TIME_NOW pinned, so every
5# assertion names an exact instant and the suite gives the same verdict on
6# Linux, macOS and Windows. It proves the public contract end to end:
7#
8# --meta the connector metadata /plugins and the router read
9# --mcp a full JSON-RPC 2.0 session: handshake, notifications,
10# all three tools, DST edges, every documented error,
11# unknown tool, bad JSON, protocol errors
12# CGI JSON API the same three operations behind ?action= and POST, with
13# the node password on every one of them
14# HTML the page, with no CDN, no <script src=> and the bot theme
15# tz data the embedded table answers like a real tz database,
16# including the 2038 boundary where most zones stop
17# generating transitions
18# safety no popen/system/socket/write, the ASan+fortify build clean
19# history no LAN IP, no token, no internal hostname in git history
20#
21# Exit code 0 = everything passed.
22
23set -u
24
25ROOT=$(cd "$(dirname "$0")/.." && pwd)
26cd "$ROOT" || exit 1
27
28BIN=./plugin_time
29PASS=0
30FAIL=0
31
32if [ -t 1 ]; then
33 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
34else
35 C_OK=; C_BAD=; C_B=; C_0=
36fi
37pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
38fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
39
40check() { # check <desc> <expected-substring> <actual>
41 if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
42 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 500)"
43 fi
44}
45
46check_not() { # check_not <desc> <forbidden-substring> <actual>
47 if printf '%s' "$3" | grep -F -q -- "$2"; then
48 fail "$1 (must NOT contain: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
49 else pass "$1"; fi
50}
51
52section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
53
54# strip CGI headers if present, drop CRs, keep the payload
55body() {
56 printf '%s\n' "$1" | tr -d '\r' | awk '
57 BEGIN { inhdr = 0 }
58 NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Content-Security-Policy|Content-Disposition):/) { inhdr = 1; next }
59 inhdr && $0 == "" { inhdr = 0; next }
60 inhdr { next }
61 { print }
62 '
63}
64
65json_ok() { # json_ok <desc> <json> [python-expression]
66 expr=${3:-True}
67 if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then
68 pass "$1"
69 else
70 fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 500)"
71 fi
72}
73
74api() { body "$(QUERY_STRING="$1" $BIN)"; }
75apiraw() { QUERY_STRING="$1" $BIN; }
76
77# api_post <query-string> <json-payload>
78api_post() {
79 _len=$(printf '%s' "$2" | wc -c | tr -d ' ')
80 body "$(printf '%s' "$2" | REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING="$1" $BIN)"
81}
82
83# mcp <lines...> - run a JSON-RPC session and print one response per line.
84mcp() {
85 printf '%s\n' "$@" | $BIN --mcp
86}
87
88# tool_struct <tool> <arguments-json> - the structuredContent of one call
89tool_struct() {
90 mcp "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"$1\",\"arguments\":$2}}" \
91 | python3 -c "import json,sys
92for l in sys.stdin:
93 l=l.strip()
94 if not l: continue
95 d=json.loads(l)
96 r=d.get('result',{})
97 if r.get('isError'):
98 print('ERROR', r.get('content',[{}])[0].get('text',''))
99 else:
100 print(json.dumps(r.get('structuredContent')))
101 break"
102}
103
104# tool_text <tool> <arguments-json> - the isError text (empty when it succeeded)
105tool_err() {
106 mcp "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"$1\",\"arguments\":$2}}" \
107 | python3 -c "import json,sys
108for l in sys.stdin:
109 l=l.strip()
110 if not l: continue
111 d=json.loads(l)
112 r=d.get('result',{})
113 print(r.get('content',[{}])[0].get('text','') if r.get('isError') else '')
114 break"
115}
116
117# ---------------------------------------------------------------- build
118section "build"
119if [ ! -x "$BIN" ]; then
120 echo " building native binary..."
121 make >/dev/null 2>&1 || { echo " build failed"; exit 1; }
122fi
123[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing"
124
125# Every deterministic assertion pins "now" so a DST verdict never depends on
126# the day the suite runs.
127export SX_TIME_NOW=2026-11-14T00:00:00Z
128NOW_EPOCH=1763078400
129
130# ---------------------------------------------------------------- meta
131section "mode 1 - discovery metadata"
132M=$(body "$($BIN --meta)")
133json_ok "--meta is valid JSON" "$M" "d['name']=='time'"
134check "--meta name is exactly time" '"name":"time"' "$M"
135check "--meta desc is exactly World time MCP" '"desc":"World time MCP"' "$M"
136json_ok "--meta kind is mcp" "$M" "d['kind']=='mcp'"
137json_ok "--meta mcp is true" "$M" "d['mcp'] is True"
138json_ok "--meta daemon is false" "$M" "d['daemon'] is False"
139json_ok "--meta menus is false (connectors must not flood the dropdowns)" "$M" "d['menus'] is False"
140json_ok "--meta verified is live" "$M" "d['verified']=='live'"
141json_ok "--meta category is utilities" "$M" "d['category']=='utilities'"
142json_ok "--meta version is 1.0.2" "$M" "d['version']=='1.0.2'"
143json_ok "--meta name is 1-2 words" "$M" "len(d['name'].split())<=2"
144json_ok "--meta desc is at most 15 chars" "$M" "len(d['desc'])<=15"
145M2=$(body "$(SX_PLUGIN_META=1 $BIN)")
146check "SX_PLUGIN_META env var works" '"name":"time"' "$M2"
147check_not "--meta emits no HTML" '<html' "$M"
148V=$(body "$($BIN --version)")
149check "--version names the binary" 'plugin_time' "$V"
150check "--version names the version" '1.0.2' "$V"
151check "--version matches plugin.json" "\"version\": \"$($BIN --version | awk '{print $2}')\"" "$(cat plugin.json)"
152H=$(body "$($BIN --help)")
153check "--help lists --mcp" '--mcp' "$H"
154check "--help lists convert_time" 'convert_time' "$H"
155check "--help names the local zone" 'local is' "$H"
156
157# ---------------------------------------------------------------- auth
158section "mode 2a - node authentication"
159A0=$(BOT_PASSWORD=secret QUERY_STRING='action=current&timezone=UTC' $BIN)
160check "unauthenticated current is 401" 'Status: 401 Unauthorized' "$A0"
161A1=$(BOT_PASSWORD=secret QUERY_STRING='action=zones' $BIN)
162check "unauthenticated zones is 401" 'Status: 401 Unauthorized' "$A1"
163A2=$(BOT_PASSWORD=secret QUERY_STRING='' $BIN)
164check "unauthenticated HTML page is 401" 'Status: 401 Unauthorized' "$A2"
165A3=$(printf '{"action":"convert","time":"09:00"}' | BOT_PASSWORD=secret REQUEST_METHOD=POST CONTENT_LENGTH=43 QUERY_STRING='' $BIN)
166check "unauthenticated POST is 401" 'Status: 401 Unauthorized' "$A3"
167A4=$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=secret QUERY_STRING='action=current&timezone=UTC' $BIN)
168json_ok "X-Bot-Password header authenticates" "$(body "$A4")" "d['ok'] is True"
169A5=$(BOT_PASSWORD=secret HTTP_AUTHORIZATION='Bearer secret' QUERY_STRING='action=current&timezone=UTC' $BIN)
170json_ok "Authorization Bearer authenticates" "$(body "$A5")" "d['ok'] is True"
171A6=$(BOT_PASSWORD=secret QUERY_STRING='action=current&timezone=UTC&pwd=secret' $BIN)
172json_ok "?pwd= authenticates" "$(body "$A6")" "d['ok'] is True"
173A7=$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=current&timezone=UTC' $BIN)
174check "a wrong password is still 401" 'Status: 401 Unauthorized' "$A7"
175AM=$(body "$(BOT_PASSWORD=secret $BIN --meta)")
176check "--meta stays unauthenticated" '"name":"time"' "$AM"
177AMC=$(printf '{"jsonrpc":"2.0","id":1,"method":"ping"}' | BOT_PASSWORD=secret $BIN --mcp)
178check "--mcp runs even with BOT_PASSWORD set" '"id":1' "$AMC"
179
180# ---------------------------------------------------------------- MCP
181section "mode 2b - MCP JSON-RPC handshake"
182INIT=$(mcp '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"t","version":"1"}}}' | head -1)
183check "initialize answers with a protocolVersion" '"protocolVersion":"2025-06-18"' "$INIT"
184check "initialize names the server" '"name":"time-server"' "$INIT"
185check "initialize carries the version" '"version":"1.0.2"' "$INIT"
186check "initialize advertises tools" '"tools"' "$INIT"
187check "initialize names the node's local zone in instructions" 'Etc/UTC' "$INIT"
188NR=$(mcp '{"jsonrpc":"2.0","method":"notifications/initialized"}')
189[ -z "$NR" ] && pass "a notification gets no reply" || fail "a notification got a reply: $NR"
190PN=$(mcp '{"jsonrpc":"2.0","id":9,"method":"ping"}' | head -1)
191check "ping answers with an empty result" '"result":{}' "$PN"
192TL=$(mcp '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | head -1)
193check "tools/list has get_current_time" 'get_current_time' "$TL"
194check "tools/list has convert_time" 'convert_time' "$TL"
195check "tools/list has get_time_ago" 'get_time_ago' "$TL"
196check "the timezone argument documents the local default" 'defaults to the server' "$TL"
197check "convert_time requires time" '"required":["time"]' "$TL"
198json_ok "tools/list is valid JSON with exactly three tools" "$TL" "len(d['result']['tools'])==3"
199json_ok "no tool is destructive" "$TL" "all(t.get('readOnlyHint') for t in d['result']['tools'])"
200UM=$(mcp '{"jsonrpc":"2.0","id":3,"method":"nope"}' | head -1)
201check "an unknown method is -32601" '"code":-32601' "$UM"
202BJ=$(mcp 'not json at all' | head -1)
203check "unparseable input is -32700" '"code":-32700' "$BJ"
204check "the parse error answers with id null" '"id":null' "$BJ"
205UT=$(mcp '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"get_weather","arguments":{}}}' | head -1)
206check "an unknown tool is -32602" '"code":-32602' "$UT"
207check "the unknown tool is named" 'Unknown tool: get_weather' "$UT"
208NT=$(mcp '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"arguments":{}}}' | head -1)
209check "tools/call without a name is -32602" '"code":-32602' "$NT"
210SC=$(body "$($BIN --schema)")
211json_ok "--schema prints the tool array" "$SC" "len(d)==3 and d[0]['name']=='get_current_time'"
212check_not "--schema prints no NUL byte" 'u0000' "$SC"
213
214# ---------------------------------------------------------------- get_current_time
215section "get_current_time"
216C1=$(tool_struct get_current_time '{"timezone":"Pacific/Auckland"}')
217json_ok "Auckland at the pinned instant" "$C1" "d['datetime']=='2026-11-14T13:00:00+13:00'"
218json_ok "Auckland is DST in November" "$C1" "d['is_dst'] is True"
219json_ok "Auckland reports Saturday" "$C1" "d['day_of_week']=='Saturday'"
220json_ok "Auckland offset is +13:00" "$C1" "d['utc_offset']=='+13:00'"
221json_ok "Auckland abbreviation is NZDT" "$C1" "d['abbreviation']=='NZDT'"
222json_ok "the timezone echoes the request" "$C1" "d['timezone']=='Pacific/Auckland'"
223C2=$(tool_struct get_current_time '{"timezone":"UTC"}')
224json_ok "UTC is 00:00:00Z" "$C2" "d['datetime']=='2026-11-14T00:00:00+00:00'"
225json_ok "UTC is never DST" "$C2" "d['is_dst'] is False"
226C3=$(tool_struct get_current_time '{"timezone":"America/New_York"}')
227json_ok "New York is 19:00 the previous day" "$C3" "d['datetime']=='2026-11-13T19:00:00-05:00'"
228json_ok "New York reports Friday" "$C3" "d['day_of_week']=='Friday'"
229C4=$(tool_struct get_current_time '{"timezone":"Asia/Kathmandu"}')
230json_ok "Kathmandu keeps its +05:45 offset" "$C4" "d['utc_offset']=='+05:45'"
231json_ok "Kathmandu is 05:45" "$C4" "d['datetime']=='2026-11-14T05:45:00+05:45'"
232C5=$(tool_struct get_current_time '{}')
233json_ok "an omitted timezone defaults to the node's own" "$C5" "d['timezone']=='Etc/UTC'"
234C6=$(tool_struct get_current_time '{"timezone":""}')
235check "an empty timezone is an error" 'ERROR Invalid timezone' "$C6"
236C7=$(tool_struct get_current_time '{"timezone":"Mars/Olympus_Mons"}')
237check "an unknown timezone names the key" 'No time zone found with key Mars/Olympus_Mons' "$C7"
238C8=$(tool_struct get_current_time '{"timezone":"europe/warsaw"}')
239check "a lower-case key is refused (exact match on every platform)" 'Invalid timezone' "$C8"
240C9=$(tool_struct get_current_time '{"timezone":"Europe/Warsaw"}')
241json_ok "the canonical key is accepted" "$C9" "d['timezone']=='Europe/Warsaw'"
242C10=$(tool_struct get_current_time '{"timezone":"../../etc/passwd"}')
243check "a traversal is refused" 'Invalid timezone' "$C10"
244C11=$(tool_struct get_current_time '{"timezone":42}')
245check "a non-string timezone is an error" 'must be a string' "$C11"
246C12=$(tool_struct get_current_time '{"timezone":"Pacific\/Auckland"}')
247json_ok "a JSON-escaped slash still resolves" "$C12" "d['datetime']=='2026-11-14T13:00:00+13:00'"
248
249# ---------------------------------------------------------------- DST edges
250section "DST edges (the reason the table is embedded)"
251# 2026-03-29 01:30 UTC is 2026-03-29 in Europe; London springs forward at 01:00 UTC.
252export SX_TIME_NOW=2026-03-29T00:30:00Z
253E1=$(tool_struct get_current_time '{"timezone":"Europe/London"}')
254json_ok "London is still GMT just before the spring change" "$E1" "d['utc_offset']=='+00:00' and d['is_dst'] is False"
255export SX_TIME_NOW=2026-03-29T01:30:00Z
256E2=$(tool_struct get_current_time '{"timezone":"Europe/London"}')
257json_ok "London is BST just after the spring change" "$E2" "d['utc_offset']=='+01:00' and d['is_dst'] is True"
258json_ok "the wall clock jumped 00:59 -> 02:00" "$E2" "d['datetime']=='2026-03-29T02:30:00+01:00'"
259export SX_TIME_NOW=2026-10-25T00:30:00Z
260E3=$(tool_struct get_current_time '{"timezone":"Europe/London"}')
261json_ok "London is BST just before the autumn change" "$E3" "d['utc_offset']=='+01:00'"
262export SX_TIME_NOW=2026-10-25T01:30:00Z
263E4=$(tool_struct get_current_time '{"timezone":"Europe/London"}')
264json_ok "London is GMT just after the autumn change" "$E4" "d['utc_offset']=='+00:00' and d['is_dst'] is False"
265# Southern-hemisphere change (Auckland, April)
266export SX_TIME_NOW=2026-04-04T13:30:00Z
267E5=$(tool_struct get_current_time '{"timezone":"Pacific/Auckland"}')
268json_ok "Auckland is NZDT before its autumn change" "$E5" "d['utc_offset']=='+13:00'"
269export SX_TIME_NOW=2026-04-04T14:30:00Z
270E6=$(tool_struct get_current_time '{"timezone":"Pacific/Auckland"}')
271json_ok "Auckland is NZST after its autumn change" "$E6" "d['utc_offset']=='+12:00' and d['is_dst'] is False"
272# The 2038 boundary: the tz database stops generating transitions there, so the
273# zone's own POSIX rule has to take over. A plugin that just kept the last row
274# would answer "standard time" for every northern zone from 2038 on.
275export SX_TIME_NOW=2038-07-01T12:00:00Z
276E7=$(tool_struct get_current_time '{"timezone":"America/New_York"}')
277json_ok "New York is still on EDT in July 2038" "$E7" "d['utc_offset']=='-04:00' and d['is_dst'] is True"
278json_ok "the 2038 wall clock is 08:00" "$E7" "d['datetime']=='2038-07-01T08:00:00-04:00'"
279export SX_TIME_NOW=2087-07-01T12:00:00Z
280E8=$(tool_struct get_current_time '{"timezone":"America/New_York"}')
281json_ok "New York still follows its rule in 2087" "$E8" "d['utc_offset']=='-04:00'"
282export SX_TIME_NOW=2026-11-14T00:00:00Z
283
284# ---------------------------------------------------------------- convert_time
285section "convert_time"
286K1=$(tool_struct convert_time '{"source_timezone":"Pacific/Auckland","time":"09:00","target_timezone":"America/New_York"}')
287json_ok "Auckland 09:00 is New York 15:00 the day before" "$K1" "d['target']['datetime']=='2026-11-13T15:00:00-05:00'"
288json_ok "the source side echoes the requested wall time" "$K1" "d['source']['datetime']=='2026-11-14T09:00:00+13:00'"
289json_ok "the difference is -18.0h" "$K1" "d['time_difference']=='-18.0h'"
290json_ok "no later occurrence for an unambiguous time" "$K1" "d['later_occurrence'] is None"
291K2=$(tool_struct convert_time '{"source_timezone":"America/New_York","time":"09:00","target_timezone":"Asia/Kathmandu"}')
292json_ok "a +05:45 zone prints a two-decimal difference" "$K2" "d['time_difference']=='+10.75h'"
293json_ok "Nepal is 19:45" "$K2" "d['target']['datetime']=='2026-11-13T19:45:00+05:45'"
294K3=$(tool_struct convert_time '{"source_timezone":"UTC","time":"00:00","target_timezone":"Pacific/Chatham"}')
295json_ok "Chatham's +13:45 is honoured" "$K3" "d['target']['utc_offset']=='+13:45'"
296json_ok "Chatham is 13:45 ahead" "$K3" "d['time_difference']=='+13.75h'"
297K4=$(tool_struct convert_time '{"source_timezone":"UTC","time":"12:00","target_timezone":"UTC"}')
298json_ok "identical zones differ by zero" "$K4" "d['time_difference']=='+0.0h'"
299K5=$(tool_struct convert_time '{"time":"09:00"}')
300json_ok "both zones default to the node's own" "$K5" "d['source']['timezone']=='Etc/UTC' and d['target']['timezone']=='Etc/UTC'"
301K6=$(tool_struct convert_time '{"source_timezone":"UTC"}')
302check "a missing time is the reference's error text" 'Missing required argument: time' "$K6"
303K7=$(tool_struct convert_time '{"source_timezone":"UTC","time":"9:00","target_timezone":"UTC"}')
304check "a one-digit hour is refused" 'Invalid time format. Expected HH:MM [24-hour format]' "$K7"
305K8=$(tool_struct convert_time '{"source_timezone":"UTC","time":"24:00","target_timezone":"UTC"}')
306check "24:00 is refused" 'Invalid time format' "$K8"
307K9=$(tool_struct convert_time '{"source_timezone":"UTC","time":"12:60","target_timezone":"UTC"}')
308check "a 60th minute is refused" 'Invalid time format' "$K9"
309K10=$(tool_struct convert_time '{"source_timezone":"UTC","time":"12:30:00","target_timezone":"UTC"}')
310check "seconds in the time are refused" 'Invalid time format' "$K10"
311K11=$(tool_struct convert_time '{"source_timezone":"UTC","time":"","target_timezone":"UTC"}')
312check "an empty time is refused" 'Invalid time format' "$K11"
313K12=$(tool_struct convert_time '{"source_timezone":"Nope/Nope","time":"09:00","target_timezone":"UTC"}')
314check "an unknown source zone is an error" 'Invalid timezone' "$K12"
315K13=$(tool_struct convert_time '{"source_timezone":"UTC","time":"09:00","target_timezone":"Nope/Nope"}')
316check "an unknown target zone is an error" 'Invalid timezone' "$K13"
317
318section "convert_time - a wall time a clock change skips or repeats"
319export SX_TIME_NOW=2026-03-29T00:00:00Z
320S1=$(tool_struct convert_time '{"source_timezone":"Europe/London","time":"01:30","target_timezone":"UTC"}')
321check "01:30 on a spring-forward day is an error, not a shifted answer" \
322 'Invalid time: 01:30 does not exist in Europe/London on 2026-03-29 (skipped by a clock change)' "$S1"
323export SX_TIME_NOW=2026-10-25T00:00:00Z
324S2=$(tool_struct convert_time '{"source_timezone":"Europe/London","time":"01:30","target_timezone":"UTC"}')
325json_ok "01:30 on a fall-back day answers the FIRST occurrence" "$S2" "d['source']['datetime']=='2026-10-25T01:30:00+01:00'"
326json_ok "it also reports the second occurrence" "$S2" "d['later_occurrence'] is not None"
327json_ok "the second occurrence is at +00:00" "$S2" "d['later_occurrence']['source']['datetime']=='2026-10-25T01:30:00+00:00'"
328json_ok "the note explains the repetition" "$S2" "'occurs twice' in d['later_occurrence']['note']"
329json_ok "the second occurrence's difference is recalculated" "$S2" "d['later_occurrence']['time_difference']=='+0.0h'"
330export SX_TIME_NOW=2026-09-26T13:00:00Z
331S3=$(tool_struct convert_time '{"source_timezone":"Pacific/Auckland","time":"02:30","target_timezone":"UTC"}')
332check "the southern spring change skips 02:30 too" 'does not exist in Pacific/Auckland' "$S3"
333export SX_TIME_NOW=2026-04-04T13:00:00Z
334S4=$(tool_struct convert_time '{"source_timezone":"Pacific/Auckland","time":"02:30","target_timezone":"UTC"}')
335json_ok "the southern fall-back repeats 02:30" "$S4" "d['source']['datetime']=='2026-04-05T02:30:00+13:00'"
336json_ok "and reports the second reading an hour later" "$S4" "d['later_occurrence']['source']['datetime']=='2026-04-05T02:30:00+12:00'"
337export SX_TIME_NOW=2026-11-14T00:00:00Z
338
339# ---------------------------------------------------------------- get_time_ago
340section "get_time_ago"
341G1=$(tool_struct get_time_ago '{"timezone":"Pacific/Auckland","days_ago":1,"hours_ago":2}')
342json_ok "26 real hours back is 11:00 the previous day" "$G1" "d['datetime']=='2026-11-13T11:00:00+13:00'"
343json_ok "the day rolls back with the span" "$G1" "d['day_of_week']=='Friday'"
344G2=$(tool_struct get_time_ago '{"timezone":"UTC"}')
345json_ok "an empty span is now" "$G2" "d['datetime']=='2026-11-14T00:00:00+00:00'"
346G3=$(tool_struct get_time_ago '{"timezone":"UTC","minutes_ago":90}')
347json_ok "90 minutes back is 22:30 the previous day" "$G3" "d['datetime']=='2026-11-13T22:30:00+00:00'"
348G4=$(tool_struct get_time_ago '{"timezone":"UTC","seconds_ago":30}')
349json_ok "a 30s span is exact" "$G4" "d['datetime']=='2026-11-13T23:59:30+00:00'"
350# 5 hours across a clock change is five real hours, not five wall-clock hours.
351export SX_TIME_NOW=2026-03-29T06:00:00Z
352G5=$(tool_struct get_time_ago '{"timezone":"Europe/London","hours_ago":5}')
353json_ok "5 hours before 06:00Z is 01:00Z, which is 02:00 BST" "$G5" "d['datetime']=='2026-03-29T02:00:00+01:00'"
354export SX_TIME_NOW=2026-11-14T00:00:00Z
355G6=$(tool_struct get_time_ago '{"timezone":"UTC","days_ago":-1}')
356check "a negative span is refused" 'must be between 0 and' "$G6"
357G7=$(tool_struct get_time_ago '{"timezone":"UTC","hours_ago":"2"}')
358json_ok "a numeric string is accepted (a query string always sends text)" "$G7" "d['datetime']=='2026-11-13T22:00:00+00:00'"
359G8=$(tool_struct get_time_ago '{"timezone":"UTC","hours_ago":"x"}')
360check "a non-numeric span is refused by name" 'hours_ago must be an integer' "$G8"
361
362# ---------------------------------------------------------------- JSON API
363section "mode 3 - the JSON API"
364J1=$(api 'action=current&timezone=Asia/Tokyo')
365json_ok "action=current answers ok" "$J1" "d['ok'] is True"
366json_ok "action=current returns the same shape as the tool" "$J1" "d['datetime']=='2026-11-14T09:00:00+09:00' and d['is_dst'] is False"
367J2=$(api 'action=convert&source_timezone=Asia/Tokyo&time=09:30&target_timezone=Europe/London')
368json_ok "action=convert matches the tool" "$J2" "d['target']['datetime']=='2026-11-14T00:30:00+00:00'"
369json_ok "action=convert carries the difference" "$J2" "d['time_difference']=='-9.0h'"
370J3=$(api 'action=ago&timezone=UTC&days_ago=1')
371json_ok "action=ago matches the tool" "$J3" "d['datetime']=='2026-11-13T00:00:00+00:00'"
372J4=$(api 'action=zones')
373json_ok "action=zones returns 598 keys" "$J4" "d['count']==598 and len(d['zones'])==598"
374json_ok "the zone list is sorted" "$J4" "d['zones']==sorted(d['zones'])"
375json_ok "the zone list names the local zone" "$J4" "d['local']=='Etc/UTC'"
376J5=$(api 'action=info')
377json_ok "action=info reports the connector identity" "$J5" "d['id']=='plugin_time' and d['kind']=='mcp' and d['zones']==598"
378J6=$(api 'action=tools')
379json_ok "action=tools mirrors --schema" "$J6" "len(d['tools'])==3"
380J7=$(api 'action=nonsense')
381check "an unknown action is 400" 'Status: 400 Bad Request' "$(apiraw 'action=nonsense')"
382check "the unknown action says so" 'unknown action' "$J7"
383J8=$(api 'format=json')
384json_ok "format=json without an action answers the current time" "$J8" "d['ok'] is True and 'datetime' in d"
385J9=$(api 'action=current&timezone=Bad/Zone')
386json_ok "an API error is ok:false, not a 500" "$J9" "d['ok'] is False and 'Invalid timezone' in d['error']"
387JP=$(api_post 'action=convert' '{"source_timezone":"America/New_York","time":"01:30","target_timezone":"Asia/Tokyo"}')
388json_ok "a POST body drives the same action" "$JP" "d['target']['datetime']=='2026-11-13T15:30:00+09:00'"
389JP2=$(api_post '' '{"action":"current","timezone":"Europe/Paris"}')
390json_ok "the action can arrive in the JSON body" "$JP2" "d['timezone']=='Europe/Paris'"
391JP3=$(api_post 'action=ago' '{"timezone":"UTC","days_ago":2}')
392json_ok "integer arguments survive a JSON body" "$JP3" "d['datetime']=='2026-11-12T00:00:00+00:00'"
393# Parity: the API and the tool must agree to the byte, or the page lies.
394T_API=$(api 'action=convert&source_timezone=Pacific/Auckland&time=09:00&target_timezone=America/New_York' \
395 | python3 -c "import json,sys;d=json.load(sys.stdin);d.pop('ok',None);print(json.dumps(d,sort_keys=True))")
396T_MCP=$(tool_struct convert_time '{"source_timezone":"Pacific/Auckland","time":"09:00","target_timezone":"America/New_York"}' \
397 | python3 -c "import json,sys;print(json.dumps(json.load(sys.stdin),sort_keys=True))")
398[ "$T_API" = "$T_MCP" ] && pass "the API and the MCP tool return byte-identical objects" \
399 || { fail "API and MCP disagree"; printf ' api: %s\n mcp: %s\n' "$T_API" "$T_MCP"; }
400
401# ---------------------------------------------------------------- HTML
402section "mode 4 - the HTML page"
403P=$(apiraw '')
404check "the page is content-type text/html" 'Content-Type: text/html; charset=utf-8' "$P"
405check_not "the page has no CDN script" '<script src=' "$P"
406check_not "the page has no cdnjs reference" 'cdnjs' "$P"
407check_not "the page has no external stylesheet" '<link rel="stylesheet"' "$P"
408check "the page carries the bot theme prepaint" "localStorage.getItem('bot_theme')" "$P"
409check "the page carries the theme handoff" "sx-theme" "$P"
410check "the page carries the bot tokens" '--bg-card' "$P"
411check "the page is responsive" 'width=device-width' "$P"
412check "the page implements embed mode" 'embed=' "$P"
413check "the page has a CSP that forbids remote loads" "default-src 'none'" "$P"
414check "the page calls the direct node route" "/plugin_time?action=" "$P"
415check "the page knows the hub proxy route" "/plugins?plugin=" "$P"
416check "the page renders a clock" 'id="clock"' "$P"
417check "the page renders the converter" 'id="convBtn"' "$P"
418check "the page renders the world clock" 'id="grid"' "$P"
419check "the page renders the time-ago panel" 'id="agoBtn"' "$P"
420check_not "the page never hard-codes a host" 'http://' "$P"
421PE=$(QUERY_STRING='embed=1' $BIN)
422check "embed mode still serves the page" 'id="clock"' "$PE"
423
424# ---------------------------------------------------------------- data guards
425section "the embedded table"
426D1=$(api 'action=info')
427json_ok "598 zones are embedded (links included)" "$D1" "d['zones']==598"
428if grep -q 'TZ_TRANS_COUNT 1[0-9][0-9][0-9][0-9]' src/tzdata.h; then
429 pass "the transition table carries more than ten thousand entries"
430else
431 fail "the transition table looks truncated"
432fi
433grep -q 'TZif\|zic' src/tzdata.h && fail "the generated header must not embed the TZif reader" \
434 || pass "the generated header is a table, not a parser"
435if python3 tools/gen_tzdata.py --out /tmp/tz_check.h 2>/dev/null; then
436 if cmp -s /tmp/tz_check.h src/tzdata.h; then
437 pass "tools/gen_tzdata.py reproduces src/tzdata.h exactly"
438 else
439 fail "src/tzdata.h is stale - run tools/gen_tzdata.py"
440 fi
441 rm -f /tmp/tz_check.h
442else
443 echo " skip tzdata regeneration check (no tz database here)"
444fi
445if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
446 pass "src/ui_html.h is in sync with src/ui.html"
447else
448 fail "src/ui_html.h is stale - run tools/gen_ui.py"
449fi
450
451# ---------------------------------------------------------------- windows ids
452section "the Windows timezone map (CLDR)"
453check "--win-tz resolves the New Zealand registry id" 'Pacific/Auckland' "$($BIN --win-tz 'New Zealand Standard Time')"
454check "--win-tz resolves Eastern Standard Time" 'America/New_York' "$($BIN --win-tz 'Eastern Standard Time')"
455check "--win-tz resolves Tokyo Standard Time" 'Asia/Tokyo' "$($BIN --win-tz 'Tokyo Standard Time')"
456check "--win-tz resolves W. Europe Standard Time" 'Europe/Berlin' "$($BIN --win-tz 'W. Europe Standard Time')"
457check "--win-tz resolves AUS Eastern Standard Time" 'Australia/Sydney' "$($BIN --win-tz 'AUS Eastern Standard Time')"
458$BIN --win-tz 'Nonsense Standard Time' >/dev/null 2>&1 && fail "an unknown Windows id must exit non-zero" \
459 || pass "an unknown Windows id exits non-zero"
460json_ok "--win-tz answers with a key tz_find accepts" \
461 "$(printf '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_current_time","arguments":{"timezone":"%s"}}}' "$($BIN --win-tz 'New Zealand Standard Time')" | $BIN --mcp | head -1)" \
462 "d['result']['structuredContent']['utc_offset']=='+13:00'"
463grep -q 'TZ_WIN_COUNT 1' src/tzdata.h && pass "the generator embedded the Windows map" \
464 || fail "the Windows map is missing from src/tzdata.h"
465
466# ---------------------------------------------------------------- differential
467#
468# The suite pins the epochs it was written from, which catches a regression but
469# cannot catch a shared wrong belief. tests/tz_diff.py asks an independent
470# implementation (Python's zoneinfo over the host's own tz database) instead;
471# it is what found the post-2037 POSIX handover and the southern-rule bugs, and
472# nothing else in this file could have. It skips cleanly when zoneinfo or a tz
473# database is absent, so it never blocks a node without them.
474section "differential run against the host tz database"
475if python3 -c "import zoneinfo; zoneinfo.ZoneInfo('UTC')" >/dev/null 2>&1; then
476 DOUT=$(python3 tests/tz_diff.py --quick 2>&1)
477 if printf '%s' "$DOUT" | grep -q 'every comparison matches zoneinfo'; then
478 pass "zoneinfo and plugin_time agree on every embedded zone"
479 else
480 fail "the differential run reported a mismatch"
481 printf '%s\n' "$DOUT" | grep -E 'FAIL|error' | head -5 | sed 's/^/ /'
482 fi
483 echo " (full sweep: python3 tests/tz_diff.py - every zone x 112 instants, 2026-2040)"
484else
485 echo " skip differential run (no zoneinfo or no tz database here)"
486fi
487
488# ---------------------------------------------------------------- source guards
489section "source guards"
490SRC="src/plugin_time.c src/timeutil.c src/tz.c src/plugintime.h src/tz.h"
491hits() { grep -n -- "$1" $SRC 2>/dev/null | head -3 || true; }
492for bad in 'popen(' 'system(' 'socket(' 'connect(' 'fork(' 'execv' 'fopen(.*"w' 'fopen(.*"a' \
493 'remove(' 'unlink(' 'rmdir(' 'mkdir(' 'rename(' 'chmod(' 'curl ' 'wget '; do
494 H=$(hits "$bad")
495 if [ -n "$H" ]; then fail "source must not call $bad"; printf '%s\n' "$H" | sed 's/^/ /'
496 else pass "no $bad in the connector sources"; fi
497done
498H=$(grep -nE '(^|[^_a-z])(strcpy|strcat|sprintf)\(' src/timeutil.c src/tz.c src/plugin_time.c 2>/dev/null | head -3 || true)
499[ -z "$H" ] && pass "no unbounded strcpy/strcat/sprintf" || { fail "unbounded string op"; printf '%s\n' "$H"; }
500H=$(grep -n 'yyjson_mut_obj_add_str(' src/timeutil.c src/plugin_time.c 2>/dev/null | head -3 || true)
501[ -z "$H" ] && pass "every yyjson string is copied (no borrowed stack pointers)" \
502 || { fail "yyjson_mut_obj_add_str stores a borrowed pointer - use strcpy"; printf '%s\n' "$H"; }
503
504# ---------------------------------------------------------------- sanitizers
505section "sanitizers (ASan + UBSan + _FORTIFY_SOURCE=2)"
506if make asan >/dev/null 2>&1 && [ -x ./plugin_time.asan ]; then
507 ASAN=./plugin_time.asan
508 AOUT=$(printf '%s\n' \
509 '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \
510 '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \
511 '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"get_current_time","arguments":{"timezone":"Pacific/Auckland"}}}' \
512 '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"convert_time","arguments":{"source_timezone":"Europe/London","time":"01:30","target_timezone":"UTC"}}}' \
513 '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"get_time_ago","arguments":{"timezone":"UTC","days_ago":3}}}' \
514 '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"nope","arguments":{}}}' \
515 'garbage' \
516 | SX_TIME_NOW=2026-10-25T00:00:00Z "$ASAN" --mcp 2>&1)
517 check_not "the sanitizer run reports no memory error" 'ERROR: AddressSanitizer' "$AOUT"
518 check_not "the sanitizer run reports no undefined behaviour" 'runtime error:' "$AOUT"
519 check_not "the sanitizer run reports no leak" 'LeakSanitizer' "$AOUT"
520 # A fall-back conversion allocates the most (a note, two nested results);
521 # run it with the pointer checks on.
522 AOUT2=$(SX_TIME_NOW=2026-10-25T00:00:00Z QUERY_STRING='action=convert&source_timezone=Europe/London&time=01:30&target_timezone=Asia/Kathmandu' "$ASAN" 2>&1)
523 check_not "the repeated-hour path is clean under ASan" 'ERROR: AddressSanitizer' "$AOUT2"
524 AOUT3=$(QUERY_STRING='' "$ASAN" 2>&1)
525 check_not "the page path is clean under ASan" 'ERROR: AddressSanitizer' "$AOUT3"
526 AOUT4=$(QUERY_STRING='action=zones' "$ASAN" 2>&1 | head -c 200)
527 check "the zone list path survives the sanitizer" 'Africa/Abidjan' "$AOUT4"
528else
529 fail "the sanitizer build did not produce ./plugin_time.asan"
530fi
531
532# ---------------------------------------------------------------- cross targets
533section "cross-target builds (when the toolchain is here)"
534if command -v musl-gcc >/dev/null 2>&1; then
535 make musl >/dev/null 2>&1 && pass "musl static build" || fail "musl build"
536 if [ -x ./plugin_time.musl ]; then
537 MOUT=$(./plugin_time.musl --meta)
538 check "the musl binary runs --meta" '"kind":"mcp"' "$MOUT"
539 file ./plugin_time.musl 2>/dev/null | grep -q 'statically linked' \
540 && pass "the musl artifact is static" || fail "the musl artifact is not static"
541 MCT=$(SX_TIME_NOW=2026-11-14T00:00:00Z QUERY_STRING='action=current&timezone=Pacific/Auckland' ./plugin_time.musl | tail -1)
542 check "the musl binary resolves a zone the same way" '2026-11-14T13:00:00+13:00' "$MCT"
543 fi
544else
545 echo " skip musl (no musl-gcc here)"
546fi
547if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
548 make win64 >/dev/null 2>&1 && pass "MinGW win64 build" || fail "win64 build"
549 if [ -f ./plugin_time.exe ]; then
550 head -c 2 ./plugin_time.exe | grep -q 'MZ' \
551 && pass "the PE artifact starts with MZ" || fail "the PE header is wrong"
552 fi
553else
554 echo " skip win64 (no MinGW here)"
555fi
556if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
557 make arm64 >/dev/null 2>&1 && pass "aarch64 cross build" || fail "arm64 build"
558else
559 echo " skip arm64 (no aarch64-linux-gnu-gcc here)"
560fi
561
562# ---------------------------------------------------------------- history audit
563section "git history secret and IP audit"
564if [ -d .git ]; then
565 ALL=$(mktemp)
566 git log -p --all > "$ALL" 2>/dev/null || : > "$ALL"
567 audit() { # audit <label> <regex>
568 H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true)
569 if [ -n "$H" ]; then
570 fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /'
571 else
572 pass "history clean: $1"
573 fi
574 }
575 audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+'
576 audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
577 audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
578 audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
579 audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
580 audit "plugingit token" 'plugingit_[A-Za-z0-9]{20,}'
581 audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}'
582 audit "sshpass default" 'Xbox''one09''09'
583 audit "run token assignment" 'RUNNER_'"PASS="
584 INTERNAL="int""el-ultra""2|macmi""ni2018""i5|laza""rus"
585 audit "internal hostname" "$INTERNAL"
586 rm -f "$ALL"
587else
588 echo " skip history audit (not a git checkout)"
589fi
590
591section "brand casing"
592BRAND=$(cat README.md docs/usage.md plugin.json src/ui.html 2>/dev/null || true)
593BADCASE=$(printf '%s' "$BRAND" | grep -Eo 'Scorpio''x Bot|Scorpio''X Bot|SCORPIO BOT' | sort -u | head -3 || true)
594[ -z "$BADCASE" ] && pass "the product is only ever SCORPIOX BOT" || fail "bad casing: $BADCASE"
595
596# ---------------------------------------------------------------- summary
597printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
598printf ' passed: %d\n' "$PASS"
599printf ' failed: %d\n' "$FAIL"
600if [ "$FAIL" -ne 0 ]; then
601 exit 1
602fi
603exit 0