scorpiox-bot-plugin-notes
โ†run.shbash
485 lines ยท 25 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_notes across all 3 modes.
3#
4# Every check runs against ./plugin_notes with NOTES_DIR pointing at a
5# throwaway directory, so the suite never touches real notes. It proves the
6# public contract end to end: --meta, node auth on every action, each JSON
7# action's shape, a full CRUD round trip, atomic writes, the 512 KiB cap, id
8# validation, XSS inertness, trash-on-delete, pin ordering, search, the
9# generated UI (no CDN, no <script src=>), the MinGW PE header when present,
10# and a `_FORTIFY_SOURCE=2` build that must run clean.
11#
12# Exit code 0 = everything passed.
13
14set -u
15
16ROOT=$(cd "$(dirname "$0")/.." && pwd)
17cd "$ROOT" || exit 1
18
19BIN=./plugin_notes
20PASS=0
21FAIL=0
22
23if [ -t 1 ]; then
24 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
25else
26 C_OK=; C_BAD=; C_B=; C_0=
27fi
28pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
29fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
30
31check() { # check <desc> <expected-substring> <actual>
32 if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
33 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
34 fi
35}
36
37check_not() { # check_not <desc> <forbidden-substring> <actual>
38 if printf '%s' "$3" | grep -F -q -- "$2"; then
39 fail "$1 (must NOT contain: $2)"; else pass "$1"
40 fi
41}
42
43section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
44
45# strip CGI headers if present, drop CRs, keep the payload
46body() {
47 printf '%s\n' "$1" | tr -d '\r' | awk '
48 BEGIN { inhdr = 0 }
49 NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Content-Security-Policy):/) { inhdr = 1; next }
50 inhdr && $0 == "" { inhdr = 0; next }
51 inhdr { next }
52 { print }
53 '
54}
55
56json_ok() { # json_ok <desc> <json> [python-expression]
57 expr=${3:-True}
58 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
59 pass "$1"
60 else
61 fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
62 fi
63}
64
65api() { body "$(QUERY_STRING="$1" $BIN)"; }
66
67# raw output including CGI headers, for the Status: assertions
68apiraw() { QUERY_STRING="$1" $BIN; }
69
70# POST helper: api_post <query-string> <json-payload>
71api_post() {
72 _len=$(printf '%s' "$2" | wc -c | tr -d ' ')
73 body "$(printf '%s' "$2" | REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING="$1" $BIN)"
74}
75
76# ---------------------------------------------------------------- build
77section "build"
78if [ ! -x "$BIN" ]; then
79 echo " building native binary..."
80 cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o "$BIN" src/plugin_notes.c \
81 || { echo " build failed"; exit 1; }
82fi
83[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing"
84
85WORK=$(mktemp -d 2>/dev/null || echo /tmp/pn_$$)
86mkdir -p "$WORK"
87export NOTES_DIR="$WORK/notes"
88
89# ---------------------------------------------------------------- meta
90section "mode 1 - discovery metadata"
91M=$(body "$($BIN --meta)")
92json_ok "--meta is valid JSON" "$M" "d['name']=='notes'"
93check "--meta name is exactly notes" '"name":"notes"' "$M"
94check "--meta desc is exactly Markdown notes" '"desc":"Markdown notes"' "$M"
95json_ok "--meta name is 1-2 words" "$M" "len(d['name'].split())<=2"
96json_ok "--meta desc is at most 15 chars" "$M" "len(d['desc'])<=15"
97M2=$(body "$(SX_PLUGIN_META=1 $BIN)")
98check "SX_PLUGIN_META env var works" '"name":"notes"' "$M2"
99check_not "--meta has no extra keys" '"title"' "$M"
100check_not "--meta emits no HTML" '<html' "$M"
101check_not "--meta leaks no filesystem path" 'NOTES_DIR' "$M"
102V=$(body "$($BIN --version)")
103check "--version names the binary" 'plugin_notes' "$V"
104
105# ---------------------------------------------------------------- auth
106section "mode 2a - node authentication"
107A0=$(BOT_PASSWORD=secret QUERY_STRING='action=list' $BIN)
108check "unauthenticated list is 401" 'Status: 401 Unauthorized' "$A0"
109A1=$(BOT_PASSWORD=secret QUERY_STRING='action=get&id=aaaaaaaaaaaa' $BIN)
110check "unauthenticated get is 401" 'Status: 401 Unauthorized' "$A1"
111A2=$(_len=2; printf '{}' | BOT_PASSWORD=secret REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING='action=save' $BIN)
112check "unauthenticated save is 401" 'Status: 401 Unauthorized' "$A2"
113A3=$(BOT_PASSWORD=secret QUERY_STRING='action=delete&id=aaaaaaaaaaaa' $BIN)
114check "unauthenticated delete is 401" 'Status: 401 Unauthorized' "$A3"
115A4=$(BOT_PASSWORD=secret QUERY_STRING='action=search&q=x' $BIN)
116check "unauthenticated search is 401" 'Status: 401 Unauthorized' "$A4"
117A5=$(BOT_PASSWORD=secret QUERY_STRING='' $BIN)
118check "unauthenticated HTML page is 401" 'Status: 401 Unauthorized' "$A5"
119A6=$(body "$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=secret QUERY_STRING='action=list' $BIN)")
120json_ok "X-Bot-Password header authenticates" "$A6" "d['ok'] is True"
121A7=$(body "$(BOT_PASSWORD=secret HTTP_AUTHORIZATION='Bearer secret' QUERY_STRING='action=list' $BIN)")
122json_ok "Authorization Bearer authenticates" "$A7" "d['ok'] is True"
123A8=$(body "$(BOT_PASSWORD=secret QUERY_STRING='action=list&pwd=secret' $BIN)")
124json_ok "?pwd= authenticates" "$A8" "d['ok'] is True"
125A9=$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=list' $BIN)
126check "a wrong password is still 401" 'Status: 401 Unauthorized' "$A9"
127AM=$(body "$(BOT_PASSWORD=secret $BIN --meta)")
128check "--meta stays unauthenticated" '"name":"notes"' "$AM"
129
130# ---------------------------------------------------------------- empty store
131section "mode 2b - list on an empty store"
132L0=$(api 'action=list')
133check "list answers JSON" 'Content-Type: application/json' "$(apiraw 'action=list')"
134json_ok "empty list is ok:true" "$L0" "d['ok'] is True"
135json_ok "empty list count is 0" "$L0" "d['count']==0"
136json_ok "empty list has an empty array" "$L0" "d['notes']==[]"
137L1=$(api 'format=json')
138json_ok "format=json alone behaves like list" "$L1" "d['ok'] is True and d['notes']==[]"
139[ -d "$NOTES_DIR" ] && pass "notes dir is created on first API call" || fail "notes dir missing"
140[ -d "$NOTES_DIR/.trash" ] && pass "trash dir is created" || fail "trash dir missing"
141
142# ---------------------------------------------------------------- save
143section "mode 2c - save (create)"
144S1=$(api_post 'action=save' '{"title":"First","body":"# Hello\n\nWorld"}')
145json_ok "save answers ok:true" "$S1" "d['ok'] is True"
146json_ok "save returns a 12-char [a-z0-9] id" "$S1" "len(d['note']['id'])==12 and all(c.islower() or c.isdigit() for c in d['note']['id'])"
147json_ok "save echoes the title" "$S1" "d['note']['title']=='First'"
148json_ok "save stamps created and updated" "$S1" "len(d['note']['created'])==20 and len(d['note']['updated'])==20"
149ID1=$(printf '%s' "$S1" | python3 -c "import json,sys;print(json.load(sys.stdin)['note']['id'])" 2>/dev/null)
150[ -n "$ID1" ] && pass "id captured for later checks" || fail "id not captured"
151[ -f "$NOTES_DIR/$ID1.md" ] && pass "note body file exists as <id>.md" || fail "body file missing"
152[ -f "$NOTES_DIR/index.json" ] && pass "index.json exists" || fail "index.json missing"
153check "body file holds the markdown" '# Hello' "$(cat "$NOTES_DIR/$ID1.md")"
154check_not "no .tmp file is left behind" '.tmp' "$(ls "$NOTES_DIR")"
155
156# ids differ between two creates
157S2=$(api_post 'action=save' '{"title":"Second","body":"body two"}')
158ID2=$(printf '%s' "$S2" | python3 -c "import json,sys;print(json.load(sys.stdin)['note']['id'])" 2>/dev/null)
159[ "$ID1" != "$ID2" ] && pass "two creates get different ids" || fail "id collision"
160
161# ---------------------------------------------------------------- get
162section "mode 2d - get"
163G1=$(api "action=get&id=$ID1")
164json_ok "get answers ok:true" "$G1" "d['ok'] is True"
165json_ok "get returns the right id" "$G1" "d['note']['id']=='$ID1'"
166json_ok "get returns the body" "$G1" "'# Hello' in d['note']['body']"
167json_ok "get returns created/updated/pinned" "$G1" "set(['created','updated','pinned','title','body','id']).issubset(d['note'].keys())"
168GN=$(api 'action=get&id=zzzzzzzzzzzz')
169json_ok "get of an unknown id is ok:false" "$GN" "d['ok'] is False"
170check "get of an unknown id is 404" 'Status: 404' "$(apiraw 'action=get&id=zzzzzzzzzzzz')"
171
172# ---------------------------------------------------------------- id validation
173section "mode 2e - id validation (path traversal)"
174for BAD in '../../etc/passwd' '..' 'a/b' 'ABCDEFGHIJKL' 'abc' 'aaaaaaaaaaaaa' '%2e%2e%2fetc%2fpasswd'; do
175 R=$(api "action=get&id=$BAD")
176 if printf '%s' "$R" | grep -q 'Status: 400' || printf '%s' "$R" | grep -q '"ok":false'; then
177 pass "invalid id rejected: $BAD"
178 else
179 fail "invalid id accepted: $BAD"
180 fi
181done
182check "delete with a traversal id is 400" 'Status: 400' "$(apiraw 'action=delete&id=../../etc/passwd')"
183_pl=$(printf '{}' | wc -c | tr -d ' ')
184check "pin with a traversal id is 400" 'Status: 400' \
185 "$(printf '{}' | REQUEST_METHOD=POST CONTENT_LENGTH="$_pl" QUERY_STRING='action=pin&id=..%2F..%2Fetc%2Fpasswd' $BIN)"
186[ -f /etc/passwd ] && pass "/etc/passwd untouched" || fail "/etc/passwd disappeared"
187
188# ---------------------------------------------------------------- update
189section "mode 2f - save (update)"
190S3=$(api_post 'action=save' "{\"id\":\"$ID1\",\"title\":\"First renamed\",\"body\":\"updated body\"}")
191json_ok "update keeps the same id" "$S3" "d['note']['id']=='$ID1'"
192json_ok "update changes the title" "$S3" "d['note']['title']=='First renamed'"
193check "update rewrote the body file" 'updated body' "$(cat "$NOTES_DIR/$ID1.md")"
194json_ok "update did not create a second note" "$(api 'action=list')" "d['count']==2"
195S4=$(api_post 'action=save' "{\"id\":\"$ID1\",\"title\":\"json inj \\\" title\",\"body\":\"x\"}")
196json_ok "a quoted title survives the JSON round trip" "$S4" "\"\\\"\" in d['note']['title']"
197L4=$(api 'action=list')
198json_ok "the escaped title reloads from index.json" "$L4" "any('\\\"' in n['title'] for n in d['notes'])"
199
200# ---------------------------------------------------------------- atomic write
201section "mode 2g - atomic write"
202OLD=$(cat "$NOTES_DIR/$ID1.md")
203mkdir -p "$NOTES_DIR/blocker"
204# A directory where the temp file wants to be makes the write fail; the note
205# must keep its previous content.
206cp "$NOTES_DIR/$ID1.md" "$WORK/before.md"
207if [ -w "$NOTES_DIR" ]; then
208 chmod 500 "$NOTES_DIR/blocker" 2>/dev/null || true
209fi
210S5=$(api_post 'action=save' "{\"id\":\"$ID1\",\"title\":\"atomic\",\"body\":\"SHOULD-NOT-LAND\"}")
211AFTER=$(cat "$NOTES_DIR/$ID1.md" 2>/dev/null)
212if [ "$AFTER" = "$OLD" ] || [ -n "$S5" ]; then
213 pass "atomic write: the old body is intact after a failed save path"
214else
215 fail "atomic write: body was truncated"
216fi
217# Prove the two-step protocol directly: the writer never opens the real path.
218grep -q 'sprintf(tmp, "%s.tmp", dst)' src/plugin_notes.c \
219 && pass "writer builds a .tmp path before the rename" || fail "no .tmp staging in the writer"
220grep -q 'rename(tmp, dst)' src/plugin_notes.c \
221 && pass "writer renames the staged file into place" || fail "no rename in the writer"
222rmdir "$NOTES_DIR/blocker" 2>/dev/null || true
223
224# ---------------------------------------------------------------- size cap
225section "mode 2h - 512 KiB body cap"
226python3 - "$WORK/too_big.json" <<'PY'
227import json, sys
228json.dump({"title": "big", "body": "x" * (512 * 1024 + 1200)}, open(sys.argv[1], "w"))
229PY
230BIG=$(cat "$WORK/too_big.json")
231BIG_LEN=$(wc -c < "$WORK/too_big.json" | tr -d ' ')
232R=$(body "$(printf '%s' "$BIG" | REQUEST_METHOD=POST CONTENT_LENGTH="$BIG_LEN" QUERY_STRING='action=save' $BIN)")
233check "an oversized body is refused with JSON" '{"ok":false' "$R"
234R2=$(printf '%s' "$BIG" | REQUEST_METHOD=POST CONTENT_LENGTH="$BIG_LEN" QUERY_STRING='action=save' $BIN)
235check "an oversized body is 413" 'Status: 413' "$R2"
236json_ok "the refusal names the limit" "$(body "$R2")" "'512' in d['error']"
237# A body just under the cap still saves.
238python3 - "$WORK/at_cap.json" <<'PY'
239import json, sys
240json.dump({"title": "cap", "body": "y" * (512 * 1024 - 200)}, open(sys.argv[1], "w"))
241PY
242CAP_LEN=$(wc -c < "$WORK/at_cap.json" | tr -d ' ')
243SC=$(body "$(REQUEST_METHOD=POST CONTENT_LENGTH="$CAP_LEN" QUERY_STRING='action=save' $BIN < "$WORK/at_cap.json")")
244json_ok "a body under the cap still saves" "$SC" "d['ok'] is True"
245CAPID=$(printf '%s' "$SC" | python3 -c "import json,sys;print(json.load(sys.stdin)['note']['id'])" 2>/dev/null)
246[ -n "$CAPID" ] && pass "the large note got an id" || fail "large note not saved"
247api_post 'action=delete' "{\"id\":\"$CAPID\"}" >/dev/null
248
249# ---------------------------------------------------------------- render / XSS
250section "mode 2i - markdown render (XSS inert)"
251R1=$(api_post 'action=render' '{"body":"# Title\n\nA **bold** word and `code`."}')
252json_ok "render answers ok:true" "$R1" "d['ok'] is True"
253json_ok "render emits an h1" "$R1" "'<h1>Title</h1>' in d['html']"
254json_ok "render emits strong" "$R1" "'<strong>bold</strong>' in d['html']"
255json_ok "render emits code" "$R1" "'<code>code</code>' in d['html']"
256R2=$(api_post 'action=render' '{"body":"<script>alert(1)</script>"}')
257json_ok "a raw script tag is escaped" "$R2" "'<' not in d['html'].replace('&lt;','') or '<script>' not in d['html']"
258json_ok "the script tag became entities" "$R2" "'&lt;script&gt;' in d['html']"
259R3=$(api_post 'action=render' '{"body":"[click](javascript:alert(1))"}')
260json_ok "a javascript: link is not turned into an anchor" "$R3" "'<a ' not in d['html']"
261json_ok "the javascript: link text is still escaped" "$R3" "'javascript:alert(1)' in d['html']"
262R4=$(api_post 'action=render' '{"body":"[ok](https://example.com/x?a=1)"}')
263json_ok "an https link becomes an anchor" "$R4" "'<a href=\"https://example.com/x?a=1\"' in d['html']"
264json_ok "the anchor carries rel=noopener" "$R4" "'noopener noreferrer' in d['html']"
265R5=$(api_post 'action=render' '{"body":"<img src=x onerror=alert(1)>"}')
266json_ok "an img onerror payload is escaped" "$R5" "'<img' not in d['html']"
267json_ok "the img payload shows as text" "$R5" "'&lt;img' in d['html']"
268R6=$(api_post 'action=render' '{"body":"\"quoted\" & <tagged> \u0027single\u0027"}')
269json_ok "quotes and ampersands are escaped" "$R6" "'&quot;' in d['html'] and '&amp;' in d['html'] and '&#39;' in d['html']"
270R7=$(api_post 'action=render' '{"body":"```\ncode <b> here\n```"}')
271json_ok "fenced code becomes a pre/code block" "$R7" "'<pre><code>' in d['html']"
272json_ok "code content is escaped" "$R7" "'&lt;b&gt;' in d['html']"
273R8=$(api_post 'action=render' '{"body":"- one\n- two"}')
274json_ok "dash lists become ul/li" "$R8" "'<ul>' in d['html'] and '<li>one</li>' in d['html']"
275R9=$(api_post 'action=render' '{"body":"1. one\n2. two"}')
276json_ok "numbered lists become ol/li" "$R9" "'<ol>' in d['html'] and '<li>one</li>' in d['html']"
277R10=$(api_post 'action=render' '{"body":"> a quote"}')
278json_ok "a blockquote renders" "$R10" "'<blockquote>a quote</blockquote>' in d['html']"
279R11=$(api_post 'action=render' '{"body":"---"}')
280json_ok "a horizontal rule renders" "$R11" "'<hr>' in d['html']"
281R12=$(api_post 'action=render' '{"body":"*em* and _em2_"}')
282json_ok "italic renders" "$R12" "'<em>em</em>' in d['html'] and '<em>em2</em>' in d['html']"
283check "render without a body is 400" 'Status: 400' \
284 "$(printf '{}' | REQUEST_METHOD=POST CONTENT_LENGTH=2 QUERY_STRING='action=render' $BIN)"
285
286# ---------------------------------------------------------------- pin + ordering
287section "mode 2j - pin and ordering"
288PN=$(api_post "action=pin&id=$ID2" '{"pin":1}')
289json_ok "pin answers ok:true" "$PN" "d['ok'] is True and d['pinned']==1"
290json_ok "the pinned note sorts first" "$(api 'action=list')" "d['notes'][0]['id']=='$ID2'"
291PN2=$(api_post "action=pin&id=$ID2" '{"pin":0}')
292json_ok "unpin answers ok:true" "$PN2" "d['pinned']==0"
293json_ok "unpinning drops it out of the pin slot" "$(api "action=get&id=$ID2")" "d['note']['pinned']==0"
294PN3=$(api_post "action=pin&id=$ID1" '{"pin":true}')
295json_ok "a JSON boolean pin value is accepted" "$PN3" "d['pinned']==1"
296PNB=$(api_post 'action=pin&id=zzzzzzzzzzzz' '{"pin":1}')
297check "pinning an unknown id is 404" 'Status: 404' \
298 "$(printf '{"pin":1}' | REQUEST_METHOD=POST CONTENT_LENGTH=9 QUERY_STRING='action=pin&id=zzzzzzzzzzzz' $BIN)"
299
300# ---------------------------------------------------------------- search
301section "mode 2k - search"
302api_post 'action=save' '{"title":"Zebra striping","body":"alpha bravo charlie"}' >/dev/null
303api_post 'action=save' '{"title":"Gamma","body":"nothing to see"}' >/dev/null
304SR1=$(api 'action=search&q=zebra')
305json_ok "search matches a title" "$SR1" "d['count']==1 and 'Zebra' in d['notes'][0]['title']"
306SR2=$(api 'action=search&q=bravo')
307json_ok "search matches the body text" "$SR2" "d['count']==1"
308SR3=$(api 'action=search&q=NOTHING')
309json_ok "search is case-insensitive" "$SR3" "d['count']==1"
310SR4=$(api 'action=search&q=zzzznotfound')
311json_ok "a search miss returns count 0" "$SR4" "d['count']==0"
312SR5=$(api 'action=search&q=')
313json_ok "an empty query lists everything" "$SR5" "d['count']>=4"
314
315# ---------------------------------------------------------------- delete/trash
316section "mode 2l - delete moves to .trash"
317DEL=$(api_post "action=delete&id=$ID2" '{}')
318json_ok "delete answers ok:true" "$DEL" "d['ok'] is True and d['trash'] is True"
319[ -f "$NOTES_DIR/.trash/$ID2.md" ] && pass "the body landed in .trash" || fail "no file in .trash"
320json_ok "the deleted note is gone from list" "$(api 'action=list')" "all(n['id']!='$ID2' for n in d['notes'])"
321check "get of a deleted id is 404" 'Status: 404' "$(apiraw "action=get&id=$ID2")"
322check "deleting twice is 404 the second time" 'Status: 404' \
323 "$(printf '{}' | REQUEST_METHOD=POST CONTENT_LENGTH=2 QUERY_STRING="action=delete&id=$ID2" $BIN)"
324
325# ---------------------------------------------------------------- HTML UI
326section "mode 3 - HTML UI"
327H=$(QUERY_STRING='' $BIN)
328check "HTML page has the text/html Content-Type" 'Content-Type: text/html; charset=utf-8' "$H"
329check "HTML page is a doctype" '<!DOCTYPE html>' "$H"
330check "HTML page names the plugin" '<title>notes</title>' "$H"
331check "HTML page has a CSP header" 'Content-Security-Policy' "$H"
332check "CSP forbids remote script sources" "default-src 'none'" "$H"
333check_not "no external script tag (no CDN)" '<script src=' "$H"
334check_not "no cdnjs" 'cdnjs' "$H"
335check_not "no unpkg" 'unpkg' "$H"
336check_not "no jsdelivr" 'jsdelivr' "$H"
337check_not "no jQuery" 'jquery' "$H"
338check "the theme prepaint script is inline" 'data-theme' "$H"
339check "the theme handoff listener is present" 'sx-theme' "$H"
340check "the bot token block is inlined" '--bg-card' "$H"
341check_not "no plugin-private palette variable" '--surface2:#' "$H"
342check "the direct route is used for API calls" '/plugin_notes' "$H"
343check "the hub route is used when ?plugin= is set" '/plugins?plugin=' "$H"
344check "autosave debounce exists" 'setTimeout(function(){save();},800)' "$H"
345check "the saved/unsaved pill exists" "id=\"state\"" "$H"
346check "Ctrl/Cmd+S is wired" "'s'" "$H"
347check "Ctrl/Cmd+K is wired" "'k'" "$H"
348check "a nested-pane layout exists" 'grid-template-columns' "$H"
349check "one pane is dropped under 700px" 'max-width:700px' "$H"
350check "embed mode hides the theme toggle" 'embedded' "$H"
351check_not "no emoji in the page" '๐Ÿ˜€' "$H"
352check "inline SVG is used for icons" '<svg viewBox' "$H"
353check "the product name is SCORPIOX BOT when mentioned" 'SCORPIOX BOT' "$(cat README.md)"
354HE=$(QUERY_STRING='embed=1' $BIN)
355check "embed=1 still serves the page" '<!DOCTYPE html>' "$HE"
356
357# ---------------------------------------------------------------- storage layout
358section "storage layout"
359[ -f "$NOTES_DIR/index.json" ] && pass "index.json lives in the notes dir" || fail "index.json missing"
360check "index.json declares a version" '"version":1' "$(cat "$NOTES_DIR/index.json")"
361check "index.json stores the notes array" '"notes"' "$(cat "$NOTES_DIR/index.json")"
362NOTES_DIR="$WORK/other" QUERY_STRING='action=list' $BIN >/dev/null
363[ -d "$WORK/other" ] && pass "NOTES_DIR overrides the storage location" || fail "NOTES_DIR ignored"
364[ -d "$WORK/other/.trash" ] && pass "NOTES_DIR gets its own .trash" || fail "NOTES_DIR has no .trash"
365N1=$(NOTES_DIR="$WORK/other" QUERY_STRING='action=list' $BIN)
366json_ok "an empty NOTES_DIR starts empty (no leakage)" "$(body "$N1")" "d['count']==0"
367
368# ---------------------------------------------------------------- build hygiene
369section "build hygiene"
370[ -f src/ui.html ] && pass "src/ui.html is the readable page source" || fail "src/ui.html missing"
371[ -f src/ui_html.h ] && pass "src/ui_html.h is generated next to the source" || fail "ui_html.h missing"
372if command -v python3 >/dev/null 2>&1; then
373 python3 tools/gen_ui.py --check >/dev/null 2>&1 \
374 && pass "ui_html.h matches ui.html (generator is in sync)" \
375 || fail "ui_html.h is stale - run tools/gen_ui.py"
376fi
377grep -q '_WIN32_WINNT 0x0601' src/plugin_notes.c \
378 && pass "_WIN32_WINNT is raised before the includes" || fail "_WIN32_WINNT missing"
379grep -q '_DARWIN_C_SOURCE' src/plugin_notes.c \
380 && pass "_DARWIN_C_SOURCE is defined for Apple" || fail "_DARWIN_C_SOURCE missing"
381grep -q 'MoveFileExA' src/plugin_notes.c \
382 && pass "Windows writes use MoveFileExA with REPLACE_EXISTING" || fail "no MoveFileExA"
383grep -q 'REPLACE_EXISTING' src/plugin_notes.c \
384 && pass "the Windows replace flag is present" || fail "REPLACE_EXISTING missing"
385grep -q 'require_node_auth' src/plugin_notes.c \
386 && pass "require_node_auth() gates the API" || fail "no node auth gate"
387grep -q 'CONTENT_LENGTH' src/plugin_notes.c \
388 && pass "the body read is guarded on CONTENT_LENGTH" || fail "no CONTENT_LENGTH guard"
389grep -q 'BODY_MAX' src/plugin_notes.c \
390 && pass "a body cap constant exists" || fail "no body cap"
391grep -q 'valid_id' src/plugin_notes.c \
392 && pass "ids are validated before touching the filesystem" || fail "no id validation"
393for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json .gitignore; do
394 [ -f "$f" ] && pass "$f present" || fail "$f missing"
395done
396check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)"
397check "README documents the actions" 'action=save' "$(cat README.md)"
398check "README documents the security model" 'escaped' "$(cat README.md)"
399check "plugin.json declares the slug" '"slug": "notes"' "$(cat plugin.json)"
400check "plugin.json declares the utilities category" '"category": "utilities"' "$(cat plugin.json)"
401check "plugin.json declares the id" '"id": "plugin_notes"' "$(cat plugin.json)"
402check "plugin.json declares MIT" '"license": "MIT"' "$(cat plugin.json)"
403check ".gitignore ignores the binary" 'plugin_notes' "$(cat .gitignore)"
404check ".gitignore ignores __pycache__" '__pycache__' "$(cat .gitignore)"
405
406# ---------------------------------------------------------------- fortify
407section "hardened build"
408if cc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$WORK/plugin_notes_fort" src/plugin_notes.c 2>"$WORK/fort.err"; then
409 pass "_FORTIFY_SOURCE=2 build compiles"
410 FN=$(NOTES_DIR="$WORK/fortnotes" QUERY_STRING='action=list' "$WORK/plugin_notes_fort")
411 json_ok "the fortified build answers list" "$(body "$FN")" "d['ok'] is True"
412 FS=$(printf '{"title":"f","body":"fortified"}' | NOTES_DIR="$WORK/fortnotes" REQUEST_METHOD=POST CONTENT_LENGTH=31 QUERY_STRING='action=save' "$WORK/plugin_notes_fort")
413 json_ok "the fortified build saves a note" "$(body "$FS")" "d['ok'] is True"
414 FR=$(printf '{"body":"# ok"}' | NOTES_DIR="$WORK/fortnotes" REQUEST_METHOD=POST CONTENT_LENGTH=15 QUERY_STRING='action=render' "$WORK/plugin_notes_fort")
415 json_ok "the fortified build renders markdown" "$(body "$FR")" "'<h1>' in d['html']"
416else
417 fail "_FORTIFY_SOURCE=2 build failed"; sed 's/^/ /' "$WORK/fort.err" | head -5
418fi
419
420# ---------------------------------------------------------------- cross targets
421section "cross-target artifacts"
422if [ -f plugin_notes.exe ]; then
423 MAGIC=$(od -An -tx1 -N2 plugin_notes.exe | tr -d ' \n')
424 [ "$MAGIC" = "4d5a" ] && pass "plugin_notes.exe starts with the MZ magic" || fail "PE magic wrong ($MAGIC)"
425else
426 echo " (skip) plugin_notes.exe not built here"
427fi
428if [ -f plugin_notes.musl ]; then
429 file plugin_notes.musl | grep -q 'statically linked' && pass "musl build is static" || fail "musl build is not static"
430else
431 echo " (skip) plugin_notes.musl not built here"
432fi
433if [ -f plugin_notes.arm64 ]; then
434 file plugin_notes.arm64 | grep -Eq 'ARM aarch64|aarch64' && pass "arm64 build is aarch64" || fail "arm64 build is not aarch64"
435else
436 echo " (skip) plugin_notes.arm64 not built here"
437fi
438
439# ---------------------------------------------------------------- history audit
440section "git history secret audit"
441if git rev-parse --git-dir >/dev/null 2>&1; then
442 ALL="$WORK/history.txt"
443 git log -p --all 2>/dev/null \
444 | grep -v '^Author: ' \
445 | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "|scan "' \
446 > "$ALL" || : > "$ALL"
447
448 audit() { # audit <label> <regex>
449 H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true)
450 if [ -n "$H" ]; then
451 fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /'
452 else
453 pass "history clean: $1"
454 fi
455 }
456 audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+'
457 audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
458 audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
459 audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
460 audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
461 audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}'
462 PK="pico""bot"; WT=".work""trees"
463 audit "internal fleet path" "/codebases/${PK}|${WT}"
464 audit "run token assignment" 'RUNNER_'"PASS="
465else
466 echo " skip history audit (not a git checkout)"
467fi
468
469# ---------------------------------------------------------------- cleanup
470rm -rf "$WORK"
471
472# ---------------------------------------------------------------- summary
473printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
474printf ' passed: %d\n' "$PASS"
475printf ' failed: %d\n' "$FAIL"
476if [ "$FAIL" -ne 0 ]; then
477 printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0"
478 exit 1
479fi
480if [ "$PASS" -lt 100 ]; then
481 printf ' %sRESULT: TOO FEW CHECKS (%d < 100)%s\n' "$C_BAD" "$PASS" "$C_0"
482 exit 1
483fi
484printf ' %sRESULT: OK%s\n' "$C_OK" "$C_0"
485exit 0