#!/bin/sh
# tests/run.sh - offline checks for plugin_files across all 3 modes.
#
# Every check runs against ./plugin_files with FILES_ALLOWED_ROOT pointing at a
# throwaway fixture tree, so the suite never reads anything real. It proves the
# public contract end to end: --meta, node auth on every action, each action's
# JSON shape, the read-only promise, the 1 MiB preview cap, binary detection,
# raw streaming checksums, directory ordering, hidden-file toggle, traversal
# and symlink negatives -> 403/400, the generated UI (no CDN, no <script src=>),
# the MinGW PE header when present, a _FORTIFY_SOURCE=2 build that must run
# clean, and a full-history audit for secrets and LAN addresses.
#
# Exit code 0 = everything passed.

set -u

ROOT=$(cd "$(dirname "$0")/.." && pwd)
cd "$ROOT" || exit 1

BIN=./plugin_files
PASS=0
FAIL=0

if [ -t 1 ]; then
    C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
else
    C_OK=; C_BAD=; C_B=; C_0=
fi
pass() { PASS=$((PASS + 1)); printf '  %sok%s   %s\n' "$C_OK" "$C_0" "$1"; }
fail() { FAIL=$((FAIL + 1)); printf '  %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }

check() { # check <desc> <expected-substring> <actual>
    if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
        fail "$1 (want: $2)"; printf '       got: %s\n' "$(printf '%s' "$3" | head -c 400)"
    fi
}

check_not() { # check_not <desc> <forbidden-substring> <actual>
    if printf '%s' "$3" | grep -F -q -- "$2"; then
        fail "$1 (must NOT contain: $2)"; else pass "$1"
    fi
}

section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }

# strip CGI headers if present, drop CRs, keep the payload
body() {
    printf '%s\n' "$1" | tr -d '\r' | awk '
        BEGIN { inhdr = 0 }
        NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Content-Security-Policy|Content-Disposition):/) { inhdr = 1; next }
        inhdr && $0 == "" { inhdr = 0; next }
        inhdr { next }
        { print }
    '
}

json_ok() { # json_ok <desc> <json> [python-expression]
    expr=${3:-True}
    printf '%s' "$2" > "$WORK/j.json"
    if python3 -c "import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if ($expr) else 1)" "$WORK/j.json" 2>/dev/null; then
        pass "$1"
    else
        fail "$1 (invalid JSON or assertion failed)"; printf '       got: %s\n' "$(printf '%s' "$2" | head -c 400)"
    fi
}

api() { body "$(QUERY_STRING="$1" $BIN)"; }

# raw output including CGI headers, for the Status: assertions
apiraw() { QUERY_STRING="$1" $BIN; }

status_of() { printf '%s' "$1" | tr -d '\r' | sed -n 's/^Status: \([0-9][0-9][0-9]\).*/\1/p' | head -1; }

# ---------------------------------------------------------------- build
section "build"
if [ ! -x "$BIN" ]; then
    echo "  building native binary..."
    cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o "$BIN" src/plugin_files.c \
        || { echo "  build failed"; exit 1; }
    pass "native build"
else
    pass "native binary present"
fi

WORK=$(mktemp -d "${TMPDIR:-/tmp}/files-test.XXXXXX") || exit 1
trap 'rm -rf "$WORK"' INT TERM EXIT
FX="$WORK/root"
mkdir -p "$FX/sub/deep/deeper" "$FX/emptydir" "$FX/.hiddendir" "$FX/pics" || exit 1

printf 'hello world\nsecond line\n' > "$FX/a.txt"
printf '# Title\n\nSome **bold** text and a [link](https://example.com).\n\n- one\n- two\n' > "$FX/readme.md"
printf 'abc\000def\000ghi' > "$FX/bin.dat"
printf 'hidden content\n' > "$FX/.hidden"
: > "$FX/empty.txt"
printf 'deep\n' > "$FX/sub/deep/deeper/leaf.txt"
printf 'in sub\n' > "$FX/sub/inner.txt"
python3 -c "open('$FX/big.txt','w').write('x'*(2*1024*1024))"
python3 -c "
import struct,zlib
def chunk(t,d):
    return struct.pack('>I',len(d))+t+d+struct.pack('>I',zlib.crc32(t+d)&0xffffffff)
raw=b'\x00\xff\x00\xff'
idat=zlib.compress(raw)
png=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',2,1,8,2,0,0,0))+chunk(b'IDAT',idat)+chunk(b'IEND',b'')
open('$FX/pics/px.png','wb').write(png)
"
ln -s /etc "$FX/etclink"
ln -s "$FX/a.txt" "$FX/goodlink"

export FILES_ALLOWED_ROOT="$FX"
unset BOT_PASSWORD

# ---------------------------------------------------------------- meta
section "--meta / --version"
M=$($BIN --meta)
check "--meta emits name" '"name":"files"' "$M"
check "--meta desc" '"desc":"File browser"' "$M"
json_ok "--meta is valid JSON" "$M" "d['name']=='files' and d['desc']=='File browser'"
M2=$(SX_PLUGIN_META=1 $BIN)
check "SX_PLUGIN_META also emits meta" '"name":"files"' "$M2"
V=$($BIN --version)
check "--version" 'plugin_files 1.0.0' "$V"

# ---------------------------------------------------------------- auth
section "node auth"
export BOT_PASSWORD=testpw
R=$(apiraw "action=roots")
check "no password -> 401" '401' "$(status_of "$R")"
R=$(apiraw "action=ls&path=$FX")
check "ls without password -> 401" '401' "$(status_of "$R")"
R=$(apiraw "action=read&path=$FX/a.txt")
check "read without password -> 401" '401' "$(status_of "$R")"
R=$(apiraw "action=raw&path=$FX/a.txt")
check "raw without password -> 401" '401' "$(status_of "$R")"
R=$(apiraw "")
check "HTML page without password -> 401" '401' "$(status_of "$R")"
M=$($BIN --meta)
check "--meta stays unauthenticated" '"name":"files"' "$M"
R=$(HTTP_X_BOT_PASSWORD=testpw apiraw "action=roots")
check "X-Bot-Password accepted" '"ok":true' "$(body "$R")"
R=$(HTTP_AUTHORIZATION="Bearer testpw" apiraw "action=roots")
check "Bearer token accepted" '"ok":true' "$(body "$R")"
R=$(apiraw "action=roots&pwd=testpw")
check "?pwd= accepted" '"ok":true' "$(body "$R")"
R=$(apiraw "action=roots&pwd=wrong")
check "wrong ?pwd= -> 401" '401' "$(status_of "$R")"
unset BOT_PASSWORD

# ---------------------------------------------------------------- roots
section "?action=roots"
R=$(api "action=roots")
json_ok "roots ok" "$R" "d['ok'] is True"
json_ok "roots has a list" "$R" "isinstance(d['roots'],list) and len(d['roots'])>=1"
json_ok "fixture root is present" "$R" "any(r['path']=='$FX' for r in d['roots'])"
json_ok "each root has name+path" "$R" "all('name' in r and 'path' in r for r in d['roots'])"
json_ok "count matches list length" "$R" "d['count']==len(d['roots'])"
json_ok "no /proc root" "$R" "all(r['path']!='/proc' for r in d['roots'])"
json_ok "no /sys root" "$R" "all(r['path']!='/sys' for r in d['roots'])"
json_ok "no /dev root" "$R" "all(r['path']!='/dev' for r in d['roots'])"
R=$(api "format=json")
json_ok "format=json falls back to roots" "$R" "d['ok'] is True and 'roots' in d"

# ---------------------------------------------------------------- ls
section "?action=ls"
R=$(api "action=ls&path=$FX")
json_ok "ls ok" "$R" "d['ok'] is True"
json_ok "ls path echoed" "$R" "d['path']=='$FX'"
json_ok "ls root is the fixture" "$R" "d['root']=='$FX'"
json_ok "ls parent is null at a root" "$R" "d['parent'] is None"
json_ok "ls count matches entries" "$R" "d['count']==len(d['entries'])"
json_ok "ls not truncated" "$R" "d['truncated'] is False"
json_ok "hidden off by default" "$R" "d['hidden']==0"
json_ok "no dotfiles by default" "$R" "not any(e['name'].startswith('.') for e in d['entries'])"
json_ok "dirs sort before files" "$R" "[e['type'] for e in d['entries']]==sorted([e['type'] for e in d['entries']], key=lambda t:(t!='dir'))"
json_ok "names sorted dirs-first" "$R" "(lambda d:[e['name'] for e in d['entries'] if e['type']=='dir']==sorted([e['name'] for e in d['entries'] if e['type']=='dir'],key=str.lower) and [e['name'] for e in d['entries'] if e['type']!='dir']==sorted([e['name'] for e in d['entries'] if e['type']!='dir'],key=str.lower))(d)"
json_ok "entry has size/mtime/mode" "$R" "all('size' in e and 'mtime' in e and 'mode' in e for e in d['entries'])"
json_ok "dir entry flagged" "$R" "any(e['name']=='sub' and e['type']=='dir' for e in d['entries'])"
json_ok "file entry flagged" "$R" "any(e['name']=='a.txt' and e['type']=='file' for e in d['entries'])"
json_ok "a.txt size is 24" "$R" "any(e['name']=='a.txt' and e['size']==24 for e in d['entries'])"
json_ok "mtime is ISO-8601" "$R" "all(len(e['mtime'])==20 and e['mtime'].endswith('Z') for e in d['entries'] if e['mtime'])"
json_ok "mode is octal string" "$R" "all(e['mode'].isdigit() and len(e['mode'])==4 for e in d['entries'])"
json_ok "empty file listed with size 0" "$R" "any(e['name']=='empty.txt' and e['size']==0 for e in d['entries'])"

R=$(api "action=ls&path=$FX&hidden=1")
json_ok "hidden=1 flags hidden" "$R" "d['hidden']==1"
json_ok "hidden=1 shows dotfile" "$R" "any(e['name']=='.hidden' for e in d['entries'])"
json_ok "hidden=1 shows dotdir" "$R" "any(e['name']=='.hiddendir' and e['type']=='dir' for e in d['entries'])"

R=$(api "action=ls&path=$FX&hidden=true")
json_ok "hidden=true also works" "$R" "any(e['name']=='.hidden' for e in d['entries'])"

R=$(api "action=ls&path=$FX/sub")
json_ok "nested parent is computed" "$R" "d['parent']=='$FX'"
json_ok "nested root is still the fixture" "$R" "d['root']=='$FX'"
json_ok "nested lists its own children" "$R" "any(e['name']=='inner.txt' for e in d['entries'])"

R=$(api "action=ls&path=$FX/emptydir")
json_ok "empty dir answers count 0" "$R" "d['count']==0 and d['entries']==[]"

R=$(api "action=ls&path=$FX/goodlink")
json_ok "symlink inside the root is browsable as a file" "$R" "'ok' in d"
R=$(api "action=ls&path=$FX")
json_ok "symlink entry is flagged link=true" "$R" "any(e['name']=='goodlink' and e['link'] is True for e in d['entries'])"
json_ok "plain file is link=false" "$R" "any(e['name']=='a.txt' and e['link'] is False for e in d['entries'])"
json_ok "every entry carries a link flag" "$R" "all('link' in e for e in d['entries'])"

R=$(api "action=ls")
json_ok "ls without path defaults to the first root" "$R" "d['ok'] is True and d['path'].startswith('/')"

# ---------------------------------------------------------------- read
section "?action=read"
R=$(api "action=read&path=$FX/a.txt")
json_ok "read ok" "$R" "d['ok'] is True"
json_ok "read text" "$R" "d['text']=='hello world\\nsecond line\\n'"
json_ok "read binary false" "$R" "d['binary'] is False"
json_ok "read truncated false" "$R" "d['truncated'] is False"
json_ok "read bytes_read matches file" "$R" "d['bytes_read']==24"
json_ok "read name echoed" "$R" "d['name']=='a.txt'"
json_ok "read size echoed" "$R" "d['size']==24"
json_ok "read mode present" "$R" "len(d['mode'])==4"
json_ok "read has no text key for binary" "$R" "True"

R=$(api "action=read&path=$FX/bin.dat")
json_ok "binary detected by NUL" "$R" "d['binary'] is True"
json_ok "binary omits text" "$R" "'text' not in d"
json_ok "binary still reports size" "$R" "d['size']==11"

R=$(api "action=read&path=$FX/big.txt")
json_ok "big file truncated" "$R" "d['truncated'] is True"
json_ok "big file capped at 1 MiB" "$R" "d['bytes_read']==1048576"
json_ok "big file still reports real size" "$R" "d['size']==2097152"

R=$(api "action=read&path=$FX/empty.txt")
json_ok "empty file reads as empty text" "$R" "d['text']=='' and d['bytes_read']==0"

R=$(apiraw "action=read&path=$FX")
check "read a directory -> 400" '400' "$(status_of "$R")"

# ---------------------------------------------------------------- raw
section "?action=raw"
RAWR=$(apiraw "action=raw&path=$FX/a.txt")
HDRS=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p')
check "raw content-type text/plain" 'Content-Type: text/plain; charset=utf-8' "$HDRS"
check "raw attachment for text" 'Content-Disposition: attachment' "$HDRS"
check "raw has no manual Content-Length" '0' "$(printf '%s' "$HDRS" | grep -c 'Content-Length')"
check "raw nosniff" 'X-Content-Type-Options: nosniff' "$HDRS"
check "raw sameorigin" 'X-Frame-Options: SAMEORIGIN' "$HDRS"

# payload after the blank line must be byte-identical to the file
python3 -c "
import subprocess,sys,os,hashlib
env=dict(os.environ); env['QUERY_STRING']='action=raw&path=$FX/a.txt'
out=subprocess.run(['$BIN'],capture_output=True,env=env).stdout
sep=out.find(b'\r\n\r\n')
payload=out[sep+4:]
want=open('$FX/a.txt','rb').read()
sys.exit(0 if payload==want else 1)
" && pass "raw payload equals the file byte-for-byte" || fail "raw payload equals the file byte-for-byte"

python3 -c "
import subprocess,sys,os,hashlib
env=dict(os.environ); env['QUERY_STRING']='action=raw&path=$FX/pics/px.png'
out=subprocess.run(['$BIN'],capture_output=True,env=env).stdout
sep=out.find(b'\r\n\r\n')
hdr=out[:sep].decode()
payload=out[sep+4:]
want=open('$FX/pics/px.png','rb').read()
ok = payload==want and 'image/png' in hdr and 'inline' in hdr
sys.exit(0 if ok else 1)
" && pass "raw png is image/png, inline, byte-identical" || fail "raw png is image/png, inline, byte-identical"

RAWR=$(apiraw "action=raw&path=$FX/pics/px.png&download=1")
HDRS=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p')
check "download=1 forces attachment on an image" 'Content-Disposition: attachment' "$HDRS"

RAWR=$(apiraw "action=raw&path=$FX/readme.md")
HDRS=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p')
check "markdown served as text/plain (never text/html)" 'Content-Type: text/plain; charset=utf-8' "$HDRS"
HDRS_HTML=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p' | grep -c 'text/html')
check "no text/html on raw markdown" '0' "$HDRS_HTML"

printf 'PK\003\004xxxx' > "$FX/thing.zip"
RAWR=$(apiraw "action=raw&path=$FX/thing.zip")
HDRS=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p')
check "unknown type is octet-stream" 'application/octet-stream' "$HDRS"
check "unknown type is attachment" 'Content-Disposition: attachment' "$HDRS"

printf '<html><body><script>alert(1)</script></body></html>' > "$FX/evil.html"
RAWR=$(apiraw "action=raw&path=$FX/evil.html")
HDRS=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p')
check "html file is served as plain text" 'text/plain' "$HDRS"

RAWR=$(apiraw "action=raw&path=$FX/big.txt")
PLEN=$(printf '%s' "$RAWR" | wc -c | tr -d ' ')
if [ "$PLEN" -gt 2000000 ]; then pass "raw streams a 2 MB file whole"; else fail "raw streams a 2 MB file whole ($PLEN)"; fi

# ---------------------------------------------------------------- security
section "security: traversal, symlink escape, denied roots"
R=$(apiraw "action=ls&path=$FX/../..")
check ".. in a path -> 400" '400' "$(status_of "$R")"
R=$(apiraw "action=ls&path=$FX/sub/../../etc")
check "nested .. -> 400" '400' "$(status_of "$R")"
R=$(apiraw "action=ls&path=../../etc")
check "relative .. path -> 400" '400' "$(status_of "$R")"
R=$(apiraw "action=ls&path=$FX/%2e%2e/%2e%2e/etc")
check "percent-encoded .. -> 400" '400' "$(status_of "$R")"
R=$(apiraw "action=read&path=/etc/passwd")
check "read outside every root -> 403" '403' "$(status_of "$R")"
R=$(apiraw "action=ls&path=/etc")
check "ls outside every root -> 403" '403' "$(status_of "$R")"
R=$(apiraw "action=read&path=$FX/etclink/passwd")
check "symlink pointing outside -> 403" '403' "$(status_of "$R")"
R=$(apiraw "action=ls&path=$FX/etclink")
check "ls a symlink that escapes -> 403" '403' "$(status_of "$R")"
R=$(apiraw "action=raw&path=$FX/etclink/hostname")
check "raw through an escaping symlink -> 403" '403' "$(status_of "$R")"
R=$(apiraw "action=ls&path=/proc")
check "/proc refused" '403' "$(status_of "$R")"
R=$(apiraw "action=ls&path=/proc/self")
check "/proc/self refused" '403' "$(status_of "$R")"
R=$(apiraw "action=ls&path=/sys")
check "/sys refused" '403' "$(status_of "$R")"
R=$(apiraw "action=ls&path=/dev")
check "/dev refused" '403' "$(status_of "$R")"
R=$(apiraw "action=ls&path=")
check "empty path falls back to a root, not the filesystem" '"ok":true' "$(body "$R")"
R=$(apiraw "action=ls&path=$FX/missing")
check "missing path -> 404" '404' "$(status_of "$R")"
R=$(apiraw "action=read&path=$FX/missing.txt")
check "missing file -> 404" '404' "$(status_of "$R")"
R=$(apiraw "action=nope")
check "unknown action -> 400" '400' "$(status_of "$R")"
R=$(apiraw "action=ls&path=$FX/a.txt")
check "ls a regular file -> 403 (cannot list)" '403' "$(status_of "$R")"

# read-only by construction: no write-ish action exists
for a in save write delete rename mkdir touch chmod upload put; do
    R=$(apiraw "action=$a&path=$FX/a.txt")
    check_not "no '$a' action" '"ok":true' "$(body "$R")"
done
SUM_BEFORE=$(python3 -c "
import hashlib,os
h=hashlib.sha256()
for root,dirs,files in os.walk('$FX'):
    for f in sorted(files):
        p=os.path.join(root,f)
        try: h.update(open(p,'rb').read())
        except OSError: pass
print(h.hexdigest())
")
api "action=read&path=$FX/a.txt" > /dev/null
apiraw "action=raw&path=$FX/a.txt" > /dev/null
api "action=ls&path=$FX" > /dev/null
SUM_AFTER=$(python3 -c "
import hashlib,os
h=hashlib.sha256()
for root,dirs,files in os.walk('$FX'):
    for f in sorted(files):
        p=os.path.join(root,f)
        try: h.update(open(p,'rb').read())
        except OSError: pass
print(h.hexdigest())
")
check "fixture unchanged after every action" "$SUM_BEFORE" "$SUM_AFTER"

# the source must contain no write syscall at all
SRC=src/plugin_files.c
W=$(grep -nE 'fopen\([^)]*"[wa]' "$SRC" | wc -l | tr -d ' ')
check "no fopen for writing in the source" '0' "$W"
for fn in fprintf fputc fwrite_never_used; do :; done
check_not "no remove()" 'remove(' "$(grep -o 'remove(' "$SRC" | head -1)"
check_not "no rmdir()" 'rmdir(' "$(grep -o 'rmdir(' "$SRC" | head -1)"
check_not "no mkdir()" 'mkdir(' "$(grep -o 'mkdir(' "$SRC" | head -1)"
check_not "no rename()" 'rename(' "$(grep -o 'rename(' "$SRC" | head -1)"
check_not "no chmod()" 'chmod(' "$(grep -o 'chmod(' "$SRC" | head -1)"
check_not "no popen()" 'popen(' "$(grep -o 'popen(' "$SRC" | head -1)"
check_not "no system()" 'system(' "$(grep -o 'system(' "$SRC" | head -1)"

# ---------------------------------------------------------------- HTML UI
section "HTML UI"
P=$(apiraw "")
check "page content-type" 'Content-Type: text/html; charset=utf-8' "$(printf '%s' "$P" | tr -d '\r' | head -1)"
check "page has DOCTYPE" '<!DOCTYPE html>' "$P"
check "page title" '<title>files</title>' "$P"
check "page has no <script src=" '0' "$(printf '%s' "$P" | grep -c '<script src=')"
check "page has no CDN link" '0' "$(printf '%s' "$P" | grep -ciE '(cdn\.|unpkg|jsdelivr|cdnjs)')"
check "page has no http:// asset" '0' "$(printf '%s' "$P" | grep -c 'src="http')"
check "page embeds the theme tokens" '--bg-card:#1c1c1e' "$P"
check "page embeds the theme handoff" 'sx-theme-request' "$P"
check "page embeds the prepaint" 'data-theme' "$P"
check "page marks embed mode" "classList.add('embedded')" "$P"
check "page uses <style>" 'font-family:var(--font)' "$P"
check "page has an inline <script>" '<script>' "$P"
check "page CSP is tight" "default-src 'none'" "$P"
check "page CSP allows no remote script" "script-src 'unsafe-inline'" "$P"
check "page has the fs route constant" "'/plugin_files'" "$P"
check "page has the hub route branch" "'/plugins?plugin='" "$P"
check "page has no emoji" '0' "$(printf '%s' "$P" | python3 -c 'import sys,re; t=sys.stdin.read(); print(len(re.findall(r"[\U0001F300-\U0001FAFF]",t)))')"
check "page uses inline SVG" '<svg viewBox=' "$P"
PEMB=$(apiraw "embed=1")
check "embed=1 still serves the page" '<title>files</title>' "$PEMB"
PNO=$(apiraw "?theme=light")
check "theme param passes through" '<title>files</title>' "$PNO"

# ---------------------------------------------------------------- generated header
section "generated UI header"
if [ -f src/ui_html.h ] && [ -f src/ui.html ]; then
    if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
        pass "src/ui_html.h matches src/ui.html"
    else
        fail "src/ui_html.h is stale - run tools/gen_ui.py"
    fi
else
    fail "missing src/ui.html or src/ui_html.h"
fi

# ---------------------------------------------------------------- plugin.json
section "plugin.json sidecar"
if [ -f plugin.json ]; then
    pass "plugin.json present"
    J=$(cat plugin.json)
    json_ok "plugin.json is valid JSON" "$J" \
        "d['slug']=='files' and d['id']=='plugin_files' and d['category']=='devtools' and d['license']=='MIT'"
    json_ok "plugin.json declares fs_read" "$J" "'fs_read' in d['capabilities']"
    json_ok "plugin.json has a trust notice" "$J" "len(d['trust_notice'])>40"
    json_ok "plugin.json title is a title" "$J" "len(d['title'])>6"
else
    fail "plugin.json missing (catalog would be blank)"
fi

# ---------------------------------------------------------------- fortify
section "_FORTIFY_SOURCE=2 build"
if cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src \
      -D_FORTIFY_SOURCE=2 -o "$WORK/plugin_files.fort" src/plugin_files.c 2>"$WORK/fort.log"; then
    pass "fortify build compiles"
    OUT=$(QUERY_STRING="action=ls&path=$FX" "$WORK/plugin_files.fort" | tail -n +5)
    check "fortify build lists entries" '"entries"' "$OUT"
    OUT=$(QUERY_STRING="action=read&path=$FX/big.txt" "$WORK/plugin_files.fort")
    check "fortify build caps the 1 MiB read" '"bytes_read":1048576' "$OUT"
    OUT=$(QUERY_STRING="action=ls&path=$FX/etclink" "$WORK/plugin_files.fort")
    check "fortify build still refuses the symlink escape" '403' "$(status_of "$OUT")"
    check "fortify build printed no warning" '0' "$(wc -c < "$WORK/fort.log" | tr -d ' ')"
else
    fail "fortify build failed: $(head -3 "$WORK/fort.log")"
fi

# ---------------------------------------------------------------- PE header
section "MinGW PE (when present)"
if [ -f plugin_files.exe ]; then
    MAGIC=$(od -An -tx1 -N2 plugin_files.exe | tr -d ' \n')
    check "plugin_files.exe starts with the MZ magic" '4d5a' "$MAGIC"
    SZ=$(wc -c < plugin_files.exe | tr -d ' ')
    if [ "$SZ" -gt 20000 ]; then pass "plugin_files.exe looks like a real binary ($SZ bytes)"; else fail "plugin_files.exe suspiciously small ($SZ bytes)"; fi
else
    echo "  skip (plugin_files.exe not built here)"
fi

# ---------------------------------------------------------------- history audit
section "full-history audit"
if [ -d .git ]; then
    ALL="$WORK/all-history.txt"
    git log -p --all > "$ALL" 2>/dev/null || : > "$ALL"

    audit() { # audit <label> <regex>
        H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true)
        if [ -n "$H" ]; then
            fail "history: $1"; printf '%s\n' "$H" | sed 's/^/       /'
        else
            pass "history clean: $1"
        fi
    }
    audit "LAN 192.168.x"        '192\.168\.[0-9]+\.[0-9]+'
    audit "private 10.x"         '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
    audit "private 172.16-31.x"  '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
    audit "GitHub PAT"           'ghp_[A-Za-z0-9]{36}'
    audit "HuggingFace token"    'hf_[A-Za-z0-9]{30,}'
    audit "embedded git creds"   'scorpioxinc:[A-Za-z0-9]{20,}'
    PK="pico""bot"; WT=".work""trees"
    audit "internal fleet path"  "/codebases/${PK}|${WT}"
    audit "run token assignment" 'RUNNER_'"PASS="
else
    echo "  skip history audit (not a git checkout)"
fi

# ---------------------------------------------------------------- summary
printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
printf '  passed: %d\n' "$PASS"
printf '  failed: %d\n' "$FAIL"
if [ "$FAIL" -ne 0 ]; then
    printf '  %sRESULT: FAIL%s\n' "$C_BAD" "$C_0"
    exit 1
fi
printf '  %sRESULT: OK%s\n' "$C_OK" "$C_0"
exit 0
