| 1 | 1 | new file mode 100644 |
| index 0000000..3f1449d | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,10 @@ | ||
| 1 | +/plugin_disks | |
| 2 | +/plugin_disks.exe | |
| 3 | +*.o | |
| 4 | +*.obj | |
| 5 | +bin/ | |
| 6 | +*.tmp | |
| 7 | +*.log | |
| 8 | +/plugin_disks.musl | |
| 9 | +/plugin_disks.arm64 | |
| 10 | +/plugin_disks.macos-* |
| 1 | 1 | new file mode 100644 |
| index 0000000..ef80120 | ||
| --- /dev/null | ||
| +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | |
| 2 | + | |
| 3 | +Copyright (c) 2026 SCORPIOX INC | |
| 4 | + | |
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 6 | +of this software and associated documentation files (the "Software"), to deal | |
| 7 | +in the Software without restriction, including without limitation the rights | |
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 9 | +copies of the Software, and to permit persons to whom the Software is | |
| 10 | +furnished to do so, subject to the following conditions: | |
| 11 | + | |
| 12 | +The above copyright notice and this permission notice shall be included in all | |
| 13 | +copies or substantial portions of the Software. | |
| 14 | + | |
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 21 | +SOFTWARE. |
| 1 | 1 | new file mode 100644 |
| index 0000000..a122178 | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,63 @@ | ||
| 1 | +# plugin_disks - ScorpioX Bot open-source local storage inspector plugin | |
| 2 | +# | |
| 3 | +# Targets: | |
| 4 | +# make native build -> ./plugin_disks | |
| 5 | +# make musl static musl x86_64 -> ./plugin_disks (fully static) | |
| 6 | +# make arm64 static musl aarch64 -> ./plugin_disks.arm64 | |
| 7 | +# make win64 MinGW-w64 static -> ./plugin_disks.exe | |
| 8 | +# make macos Apple clang -> ./plugin_disks (run on macOS) | |
| 9 | +# make test build + run tests/run.sh | |
| 10 | +# make clean | |
| 11 | + | |
| 12 | +CC ?= cc | |
| 13 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings | |
| 14 | +MUSL_CC ?= musl-gcc | |
| 15 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | |
| 16 | +ARM64_CC ?= aarch64-linux-musl-gcc | |
| 17 | +ARM64_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | |
| 18 | +WIN_CC ?= x86_64-w64-mingw32-gcc | |
| 19 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | |
| 20 | +SRC := src/plugin_disks.c | |
| 21 | +BIN := plugin_disks | |
| 22 | +EXE := plugin_disks.exe | |
| 23 | + | |
| 24 | +.PHONY: all native musl arm64 win64 macos test clean help | |
| 25 | + | |
| 26 | +all: native | |
| 27 | + | |
| 28 | +native: $(BIN) | |
| 29 | + | |
| 30 | +$(BIN): $(SRC) | |
| 31 | + @echo "==> native build ($(CC))" | |
| 32 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | |
| 33 | + | |
| 34 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | |
| 35 | +musl: $(SRC) | |
| 36 | + @echo "==> static musl build ($(MUSL_CC))" | |
| 37 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN) $(SRC) | |
| 38 | + | |
| 39 | +# Static aarch64 musl build - Raspberry Pi 5 / ARM64 servers | |
| 40 | +arm64: $(SRC) | |
| 41 | + @echo "==> static arm64 musl build ($(ARM64_CC))" | |
| 42 | + $(ARM64_CC) $(ARM64_CFLAGS) -o $(BIN).arm64 $(SRC) | |
| 43 | + | |
| 44 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | |
| 45 | +win64: $(SRC) | |
| 46 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | |
| 47 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) | |
| 48 | + | |
| 49 | +# Apple clang build (run this on macOS) | |
| 50 | +macos: $(SRC) | |
| 51 | + @echo "==> Apple clang build" | |
| 52 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | |
| 53 | + | |
| 54 | +test: native | |
| 55 | + @sh tests/run.sh | |
| 56 | + | |
| 57 | +clean: | |
| 58 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 \ | |
| 59 | + $(BIN).macos-arm64 $(BIN).macos-x86_64 | |
| 60 | + rm -rf bin | |
| 61 | + | |
| 62 | +help: | |
| 63 | + @echo "make | make musl | make arm64 | make win64 | make macos | make test | make clean" |
| 1 | 1 | new file mode 100644 |
| index 0000000..c1e6b45 | ||
| --- /dev/null | ||
| +++ b/README.md | ||
| @@ -0,0 +1,148 @@ | ||
| 1 | +# plugin_disks | |
| 2 | + | |
| 3 | +A zero-dependency **C99** storage inspector for ScorpioX Bot nodes. One binary, | |
| 4 | +three modes, no runtime dependencies, no outbound network requests. | |
| 5 | + | |
| 6 | +It answers two questions a node owner actually asks: | |
| 7 | + | |
| 8 | +1. **Which filesystems does this node have, and how full are they?** | |
| 9 | +2. **What is eating the disk inside `/workspace` or my home directory?** | |
| 10 | + | |
| 11 | +Everything is read from the local kernel interfaces. Nothing is sent anywhere. | |
| 12 | + | |
| 13 | +## What it reports | |
| 14 | + | |
| 15 | +| Mode | Output | | |
| 16 | +|---|---| | |
| 17 | +| `--meta` | `{"name":"disks","desc":"Local storage"}` - discovery metadata | | |
| 18 | +| `?action=mounts` | Every real mounted filesystem: device, filesystem type, mountpoint, total / used / free / available bytes, utilisation percentage, inode totals and inode pressure | | |
| 19 | +| `?action=dirs&root=workspace` | A bounded one-level size breakdown of `/workspace` | | |
| 20 | +| `?action=dirs&root=home` | The same breakdown for `$HOME` (`%USERPROFILE%` on Windows) | | |
| 21 | +| `?action=info` | Plugin version, platform, pid, capability and limit declaration | | |
| 22 | +| `GET` (no action) | A responsive HTML dashboard | | |
| 23 | + | |
| 24 | +Pseudo filesystems (`proc`, `sysfs`, `cgroup2`, `devpts`, `debugfs`, ...) and the | |
| 25 | +kernel-only mountpoints (`/sys`, `/proc`, `/dev`) are filtered out, and a | |
| 26 | +mountpoint that appears twice in `/proc/mounts` is only counted once - otherwise | |
| 27 | +a container's repeated host bind mounts triple the reported capacity. | |
| 28 | + | |
| 29 | +## Platform coverage | |
| 30 | + | |
| 31 | +| Platform | Mount source | Directory walk | | |
| 32 | +|---|---|---| | |
| 33 | +| Linux | `/proc/mounts` + `statvfs(3)` | `opendir` / `readdir` / `lstat` | | |
| 34 | +| macOS | `getmntinfo(3)` | `opendir` / `readdir` / `lstat` | | |
| 35 | +| Windows | `GetLogicalDriveStringsA` + `GetDiskFreeSpaceExA` + `GetVolumeInformationA` | `FindFirstFileA` / `FindNextFileA` | | |
| 36 | + | |
| 37 | +## Directory scanning is deliberately narrow | |
| 38 | + | |
| 39 | +`?action=dirs` accepts **only** `root=workspace` or `root=home`. An arbitrary | |
| 40 | +path is refused with `root_not_allowed`; an allowlisted root that does not exist | |
| 41 | +on the node answers `root_unavailable`. The walk itself is bounded four ways: | |
| 42 | + | |
| 43 | +* depth is capped at 8 levels, | |
| 44 | +* the walk stops after 120000 visited entries, | |
| 45 | +* symbolic links are never followed (a link cannot make the walk unbounded), | |
| 46 | +* at most 512 top-level entries are reported, sorted largest first. | |
| 47 | + | |
| 48 | +The response reports `truncated`, `max_depth`, `max_scan_entries` and `scan_ms` | |
| 49 | +so a caller can see that the numbers were cut short rather than trust them. | |
| 50 | + | |
| 51 | +## Build | |
| 52 | + | |
| 53 | +```sh | |
| 54 | +make # native binary -> ./plugin_disks | |
| 55 | +make musl # static musl x86_64 -> ./plugin_disks (universal Linux artifact) | |
| 56 | +make arm64 # static aarch64 -> ./plugin_disks.arm64 (Pi 5 / ARM servers) | |
| 57 | +make win64 # static PE -> ./plugin_disks.exe | |
| 58 | +make macos # Apple clang -> ./plugin_disks (run on macOS) | |
| 59 | +make test # build + offline test suite | |
| 60 | +``` | |
| 61 | + | |
| 62 | +On Windows, `powershell -ExecutionPolicy Bypass -File build.ps1` produces | |
| 63 | +`plugin_disks.exe` and refuses to succeed unless the first two bytes are `MZ`. | |
| 64 | + | |
| 65 | +No compiler, no problem: the published binaries live at | |
| 66 | +`https://dist.scorpiox.net/bot-plugins/disks/`. | |
| 67 | + | |
| 68 | +## Install | |
| 69 | + | |
| 70 | +The supported path is one click in ScorpioX Bot (`Settings -> Menus -> Plugins -> | |
| 71 | +Marketplace`) or, from a shell on the node, drop the binary into the plugin | |
| 72 | +directory: | |
| 73 | + | |
| 74 | +```sh | |
| 75 | +mkdir -p ~/.scorpiox/plugins | |
| 76 | +cp plugin_disks ~/.scorpiox/plugins/ | |
| 77 | +chmod +x ~/.scorpiox/plugins/plugin_disks | |
| 78 | +``` | |
| 79 | + | |
| 80 | +`/workspace/.scorpiox/plugins/` is used instead when `/workspace` exists, because | |
| 81 | +it survives BotCloud container restarts. The node API discovers the plugin on the | |
| 82 | +next request - no restart. | |
| 83 | + | |
| 84 | +Prefer to build it yourself? The source is MIT licensed and compiles in one | |
| 85 | +command: | |
| 86 | + | |
| 87 | +```sh | |
| 88 | +cc -O2 -std=c99 -Wall -Wextra -o plugin_disks src/plugin_disks.c | |
| 89 | +``` | |
| 90 | + | |
| 91 | +## API | |
| 92 | + | |
| 93 | +```sh | |
| 94 | +# mounted filesystems | |
| 95 | +curl -s 'http://127.0.0.1:8150/plugin_disks?action=mounts&pwd=<node-password>' | |
| 96 | + | |
| 97 | +# top-level sizes inside the home directory | |
| 98 | +curl -s 'http://127.0.0.1:8150/plugin_disks?action=dirs&root=home&pwd=<node-password>' | |
| 99 | + | |
| 100 | +# an arbitrary path is refused, by design | |
| 101 | +curl -s 'http://127.0.0.1:8150/plugin_disks?action=dirs&root=/etc&pwd=<node-password>' | |
| 102 | +# {"ok":false,"error":"root_not_allowed","allowed_roots":["workspace","home"],...} | |
| 103 | +``` | |
| 104 | + | |
| 105 | +`action=mounts` response: | |
| 106 | + | |
| 107 | +```json | |
| 108 | +{ | |
| 109 | + "ok": true, | |
| 110 | + "action": "mounts", | |
| 111 | + "plugin": "plugin_disks", | |
| 112 | + "version": "1.0.0", | |
| 113 | + "platform": "linux", | |
| 114 | + "count": 2, | |
| 115 | + "zero_network": true, | |
| 116 | + "mounts": [ | |
| 117 | + { | |
| 118 | + "device": "/dev/nvme0n1p2", | |
| 119 | + "fstype": "ext4", | |
| 120 | + "mount": "/", | |
| 121 | + "total_bytes": 983167959040, | |
| 122 | + "used_bytes": 930171248640, | |
| 123 | + "free_bytes": 52996710400, | |
| 124 | + "avail_bytes": 42979762176, | |
| 125 | + "pct": 95.6, | |
| 126 | + "inodes_total": 61038592, | |
| 127 | + "inodes_used": 8172848, | |
| 128 | + "inodes_pct": 13.4, | |
| 129 | + "has_inodes": true | |
| 130 | + } | |
| 131 | + ] | |
| 132 | +} | |
| 133 | +``` | |
| 134 | + | |
| 135 | +## Security model | |
| 136 | + | |
| 137 | +* Reads only local kernel state; opens no sockets; runs no shell commands | |
| 138 | + (`popen`/`system` are not used anywhere in the source). | |
| 139 | +* Requires the node password on every request except `--meta`. Accepted forms: | |
| 140 | + `X-Bot-Password: <pwd>`, `Authorization: Bearer <pwd>`, and `?pwd=<pwd>`. | |
| 141 | + When `BOT_PASSWORD` is unset the check is a deliberate no-op, which is how the | |
| 142 | + plugin runs from a developer shell. | |
| 143 | +* The directory walk cannot be pointed at an arbitrary path, cannot follow a | |
| 144 | + symlink out of the root, and cannot run unbounded. | |
| 145 | + | |
| 146 | +## License | |
| 147 | + | |
| 148 | +MIT. Copyright (c) 2026 SCORPIOX INC. |
| 1 | 1 | new file mode 100644 |
| index 0000000..4832e0f | ||
| --- /dev/null | ||
| +++ b/build.ps1 | ||
| @@ -0,0 +1,54 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_disks | |
| 2 | +# | |
| 3 | +# Usage (from the repo root, PowerShell): | |
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | |
| 5 | +# | |
| 6 | +# Produces .\plugin_disks.exe (static PE, runs on any Windows 10/11 x64 node). | |
| 7 | +# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin). | |
| 8 | +# This plugin needs no extra Win32 import libraries. | |
| 9 | + | |
| 10 | +$ErrorActionPreference = "Stop" | |
| 11 | +$ScriptDir = $PSScriptRoot | |
| 12 | +Push-Location $ScriptDir | |
| 13 | +try { | |
| 14 | + $Src = Join-Path $ScriptDir "src\plugin_disks.c" | |
| 15 | + $Out = Join-Path $ScriptDir "plugin_disks.exe" | |
| 16 | + $Cc = "x86_64-w64-mingw32-gcc" | |
| 17 | + | |
| 18 | + if (-not (Test-Path $Src)) { throw "source not found: $Src" } | |
| 19 | + | |
| 20 | + # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present. | |
| 21 | + if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) { | |
| 22 | + if (Test-Path "C:\gcc16\bin\gcc.exe") { | |
| 23 | + $Cc = "C:\gcc16\bin\gcc.exe" | |
| 24 | + } elseif (Get-Command gcc -ErrorAction SilentlyContinue) { | |
| 25 | + $Cc = "gcc" | |
| 26 | + } else { | |
| 27 | + throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)" | |
| 28 | + } | |
| 29 | + } | |
| 30 | + | |
| 31 | + Write-Host "==> building plugin_disks.exe with $Cc" | |
| 32 | + & $Cc -O2 -std=c99 -Wall -Wextra -static -o $Out $Src | |
| 33 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | |
| 34 | + | |
| 35 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | |
| 36 | + | |
| 37 | + # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not. | |
| 38 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | |
| 39 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | |
| 40 | + throw "output is not a PE executable (missing MZ header)" | |
| 41 | + } | |
| 42 | + | |
| 43 | + Write-Host "==> metadata check" | |
| 44 | + & $Out --meta | |
| 45 | + if ($LASTEXITCODE -ne 0) { throw "--meta failed" } | |
| 46 | + | |
| 47 | + $size = (Get-Item $Out).Length | |
| 48 | + Write-Host "" | |
| 49 | + Write-Host "Built $Out ($size bytes)" | |
| 50 | + Write-Host "Install: Copy-Item plugin_disks.exe `"`$env:LOCALAPPDATA\scorpiox\plugins\`"" | |
| 51 | +} | |
| 52 | +finally { | |
| 53 | + Pop-Location | |
| 54 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..545900a | ||
| --- /dev/null | ||
| +++ b/plugin.json | ||
| @@ -0,0 +1,10 @@ | ||
| 1 | +{ | |
| 2 | + "slug": "disks", | |
| 3 | + "id": "plugin_disks", | |
| 4 | + "title": "Local Storage & Mounts", | |
| 5 | + "summary": "Zero-dependency local storage inspector: every real mounted filesystem with usage and inode pressure, plus a bounded one-level size breakdown of /workspace and $HOME so container and laptop nodes can see what is actually eating the disk.", | |
| 6 | + "category": "system", | |
| 7 | + "license": "MIT", | |
| 8 | + "capabilities": ["procfs_read", "local_filesystem_stat", "bounded_directory_walk"], | |
| 9 | + "trust_notice": "Executes native C code on your node. Reads /proc/mounts and statvfs, getmntinfo or GetLogicalDriveStringsA, and walks only the allowlisted /workspace or $HOME roots; makes zero outbound network requests and opens no sockets." | |
| 10 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..818858a | ||
| --- /dev/null | ||
| +++ b/release-dist.sh | ||
| @@ -0,0 +1,368 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# release-dist.sh — build, scan and publish plugin_disks to the plugin registry. | |
| 3 | +# | |
| 4 | +# Two paths: | |
| 5 | +# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it | |
| 6 | +# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI. | |
| 7 | +# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz -> | |
| 8 | +# manifest.json + SHA256SUMS -> upload -> latest.json / index.json -> plugingit mirror. | |
| 9 | +# | |
| 10 | +# Nothing here contains a host address or a credential. Everything environment-specific | |
| 11 | +# comes from the environment, so this file stays safe to publish: | |
| 12 | +# | |
| 13 | +# DIST_HOST ssh target for the dist server (required for upload) | |
| 14 | +# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key) | |
| 15 | +# DIST_PATH remote web root of the dist server (default /data/dist) | |
| 16 | +# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64) | |
| 17 | +# MAC_USER / MAC_PASS (optional) | |
| 18 | +# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token) | |
| 19 | +# PLUGINGIT_REMOTE public mirror URL to push into | |
| 20 | +# | |
| 21 | +# Usage: | |
| 22 | +# ./release-dist.sh # full release | |
| 23 | +# ./release-dist.sh --dry-run # build + stage in /tmp, no upload | |
| 24 | +# ./release-dist.sh --no-macos # skip the macOS legs | |
| 25 | +# ./release-dist.sh --no-mirror # skip the plugingit mirror | |
| 26 | + | |
| 27 | +set -euo pipefail | |
| 28 | + | |
| 29 | +SLUG="disks" | |
| 30 | +ID="plugin_disks" | |
| 31 | +VERSION="1.0.0" | |
| 32 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | |
| 33 | + | |
| 34 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | |
| 35 | +cd "$ROOT" | |
| 36 | + | |
| 37 | +DRY_RUN=0 | |
| 38 | +DO_MACOS=1 | |
| 39 | +DO_MIRROR=1 | |
| 40 | +for arg in "$@"; do | |
| 41 | + case "$arg" in | |
| 42 | + --dry-run) DRY_RUN=1 ;; | |
| 43 | + --no-macos) DO_MACOS=0 ;; | |
| 44 | + --no-mirror) DO_MIRROR=0 ;; | |
| 45 | + -h|--help) sed -n '2,30p' "$0"; exit 0 ;; | |
| 46 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | |
| 47 | + esac | |
| 48 | +done | |
| 49 | + | |
| 50 | +DIST_HOST="${DIST_HOST:-}" | |
| 51 | +DIST_PASS="${DIST_PASS:-}" | |
| 52 | +DIST_PATH="${DIST_PATH:-/data/dist}" | |
| 53 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | |
| 54 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | |
| 55 | + | |
| 56 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | |
| 57 | +mkdir -p "$STAGE" | |
| 58 | +trap 'rm -rf "$STAGE"' EXIT | |
| 59 | + | |
| 60 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | |
| 61 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | |
| 62 | + | |
| 63 | +# ---------------------------------------------------------------- 0. preflight | |
| 64 | +say "0/7 preflight" | |
| 65 | + | |
| 66 | +if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | |
| 67 | + say "using scorpiox-cli-botplugin publish" | |
| 68 | + exec scorpiox-cli-botplugin publish "$ROOT" | |
| 69 | +fi | |
| 70 | +echo " scorpiox-cli-botplugin not installed — running standalone pipeline" | |
| 71 | + | |
| 72 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | |
| 73 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | |
| 74 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | |
| 75 | +echo " version $VERSION" | |
| 76 | +echo " commit $COMMIT" | |
| 77 | + | |
| 78 | +# ---------------------------------------------------------------- 1. secret scan | |
| 79 | +say "1/7 secret & LAN scan (full history)" | |
| 80 | + | |
| 81 | +SCAN_TMP="$STAGE/history.txt" | |
| 82 | +# Scan every added/removed line of every commit. Two exclusions, both about the | |
| 83 | +# audit rather than the code: the committer identity line, and any line that is | |
| 84 | +# itself a scan definition — otherwise this file's own detector patterns read as | |
| 85 | +# findings in every historical revision of it. | |
| 86 | +git log -p --all 2>/dev/null \ | |
| 87 | + | grep -v '^Author: ' \ | |
| 88 | + | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \ | |
| 89 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | |
| 90 | +HITS=0 | |
| 91 | +scan() { # scan <label> <regex> | |
| 92 | + local out | |
| 93 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | |
| 94 | + if [ -n "$out" ]; then | |
| 95 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | |
| 96 | + printf '%s\n' "$out" | sed 's/^/ /' | |
| 97 | + HITS=$((HITS + 1)) | |
| 98 | + else | |
| 99 | + printf ' ok %s\n' "$1" | |
| 100 | + fi | |
| 101 | +} | |
| 102 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 103 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 104 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 105 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 106 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 107 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 108 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | |
| 109 | +P_ROOT="/codebases" | |
| 110 | +P_PICOBOT="${P_ROOT}/pico""bot" | |
| 111 | +P_WT=".work""trees" | |
| 112 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | |
| 113 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | |
| 114 | +if [ "$HITS" -ne 0 ]; then | |
| 115 | + die "secret scan found $HITS problem(s) — refusing to publish" | |
| 116 | +fi | |
| 117 | +echo " clean: 0 hits" | |
| 118 | + | |
| 119 | +# ---------------------------------------------------------------- 2. build | |
| 120 | +say "2/7 build targets" | |
| 121 | + | |
| 122 | +build_ok() { [ -f "$1" ]; } | |
| 123 | + | |
| 124 | +# linux-x86_64 (glibc, native) | |
| 125 | +if command -v cc >/dev/null 2>&1; then | |
| 126 | + cc -O2 -std=c99 -Wall -Wextra -o "$STAGE/$ID" src/$ID.c || die "native build failed" | |
| 127 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | |
| 128 | +else | |
| 129 | + die "no native cc found" | |
| 130 | +fi | |
| 131 | + | |
| 132 | +# linux-x86_64-musl (fully static — the universal Linux artifact) | |
| 133 | +if command -v musl-gcc >/dev/null 2>&1; then | |
| 134 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.musl" src/$ID.c \ | |
| 135 | + || die "musl build failed" | |
| 136 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | |
| 137 | +else | |
| 138 | + echo " skip linux-x86_64-musl (no musl-gcc)" | |
| 139 | +fi | |
| 140 | + | |
| 141 | +# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers). | |
| 142 | +# Prefer musl; on a host that only has the Debian cross toolchain the static | |
| 143 | +# glibc link still yields a self-contained aarch64 ELF. | |
| 144 | +if command -v aarch64-linux-musl-gcc >/dev/null 2>&1; then | |
| 145 | + aarch64-linux-musl-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.arm64" src/$ID.c \ | |
| 146 | + || die "arm64 musl build failed" | |
| 147 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | |
| 148 | +elif command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | |
| 149 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.arm64" src/$ID.c \ | |
| 150 | + || die "arm64 static build failed" | |
| 151 | + echo " built linux-arm64-static $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | |
| 152 | +else | |
| 153 | + echo " skip linux-arm64-musl (no aarch64 cross compiler)" | |
| 154 | +fi | |
| 155 | + | |
| 156 | +# windows-x86_64 (static PE) | |
| 157 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | |
| 158 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.exe" src/$ID.c \ | |
| 159 | + || die "MinGW build failed" | |
| 160 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | |
| 161 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | |
| 162 | +else | |
| 163 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | |
| 164 | +fi | |
| 165 | + | |
| 166 | +# macOS legs — Mach-O must be produced by Apple clang on a real Mac. | |
| 167 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | |
| 168 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | |
| 169 | + MAC_USER="${MAC_USER:-$(whoami)}" | |
| 170 | + MAC_DIR="/tmp/${ID}-mac-$$" | |
| 171 | + echo " building macOS legs on $MAC_HOST" | |
| 172 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | |
| 173 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | |
| 174 | + if [ -n "${MAC_PASS:-}" ]; then | |
| 175 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | |
| 176 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | |
| 177 | + fi | |
| 178 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | |
| 179 | + if "${SCP_MAC[@]}" src/$ID.c "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.c"; then | |
| 180 | + # Build straight from the uploaded file — no src/ tree on the remote. | |
| 181 | + for slice in arm64 x86_64; do | |
| 182 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | |
| 183 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -arch $slice -o $ID.$slice $ID.c" \ | |
| 184 | + 2>/dev/null; then | |
| 185 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | |
| 186 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | |
| 187 | + else | |
| 188 | + echo " warn: macos-$slice build failed on $MAC_HOST" | |
| 189 | + fi | |
| 190 | + done | |
| 191 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" 2>/dev/null || true | |
| 192 | + else | |
| 193 | + echo " warn: mac scp failed" | |
| 194 | + fi | |
| 195 | + else | |
| 196 | + echo " warn: mac host unreachable" | |
| 197 | + fi | |
| 198 | +else | |
| 199 | + echo " skip macOS legs (set MAC_HOST/MAC_USER/MAC_PASS to include them)" | |
| 200 | +fi | |
| 201 | + | |
| 202 | +# ---------------------------------------------------------------- 3. package | |
| 203 | +say "3/7 package" | |
| 204 | + | |
| 205 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | |
| 206 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | |
| 207 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | |
| 208 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | |
| 209 | + | |
| 210 | +target_meta() { # target_meta <key> <file> <format> <relpath> <name> | |
| 211 | + local key="$1" file="$2" fmt="$3" rel="$4" name="$5" | |
| 212 | + [ -f "$file" ] || return 0 | |
| 213 | + local sha size | |
| 214 | + sha=$(sha256sum "$file" | awk '{print $1}') | |
| 215 | + size=$(wc -c < "$file" | tr -d ' ') | |
| 216 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | |
| 217 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | |
| 218 | +} | |
| 219 | + | |
| 220 | +{ | |
| 221 | + printf '{\n' | |
| 222 | + printf ' "slug": "%s",\n' "$SLUG" | |
| 223 | + printf ' "id": "%s",\n' "$ID" | |
| 224 | + printf ' "name": "disks",\n' | |
| 225 | + printf ' "desc": "Local storage",\n' | |
| 226 | + printf ' "title": "Local Storage & Mounts",\n' | |
| 227 | + printf ' "summary": "Zero-dependency local storage inspector: every real mounted filesystem with usage and inode pressure, plus a bounded one-level size breakdown of /workspace and $HOME for container and laptop nodes.",\n' | |
| 228 | + printf ' "category": "system",\n' | |
| 229 | + printf ' "version": "%s",\n' "$VERSION" | |
| 230 | + printf ' "license": "MIT",\n' | |
| 231 | + printf ' "trust_notice": "Executes native C code on your node. Reads /proc/mounts and statvfs, getmntinfo or GetLogicalDriveStringsA, and walks only the allowlisted /workspace or $HOME roots; makes zero outbound network requests and opens no sockets.",\n' | |
| 232 | + printf ' "capabilities": ["procfs_read", "local_filesystem_stat", "bounded_directory_walk"],\n' | |
| 233 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | |
| 234 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | |
| 235 | + printf ' "git_commit": "%s",\n' "$COMMIT" | |
| 236 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 237 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | |
| 238 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID" | |
| 239 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID" | |
| 240 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | |
| 241 | + printf ' "targets": {\n' | |
| 242 | + first=1 | |
| 243 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | |
| 244 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" "$ID" | |
| 245 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" "$ID" | |
| 246 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" "$ID" | |
| 247 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" "$ID" | |
| 248 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" "$ID" | |
| 249 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" "$ID" | |
| 250 | + printf '\n }\n}\n' | |
| 251 | +} > "$STAGE/manifest.json" | |
| 252 | + | |
| 253 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | |
| 254 | + || die "generated manifest.json is not valid JSON" | |
| 255 | +echo " manifest.json ok" | |
| 256 | + | |
| 257 | +# SHA256SUMS — relative paths, exactly as published | |
| 258 | +( cd "$STAGE" | |
| 259 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | |
| 260 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | |
| 261 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | |
| 262 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | |
| 263 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | |
| 264 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | |
| 265 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | |
| 266 | + true ) > "$STAGE/SHA256SUMS" | |
| 267 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | |
| 268 | + | |
| 269 | +# ---------------------------------------------------------------- 4. stage | |
| 270 | +say "4/7 stage tree" | |
| 271 | +PKG="$STAGE/pkg" | |
| 272 | +mkdir -p "$PKG/linux-x86_64" "$PKG/linux-x86_64-musl" "$PKG/linux-arm64-musl" \ | |
| 273 | + "$PKG/macos-arm64" "$PKG/macos-x86_64" "$PKG/windows-x86_64" | |
| 274 | +cp -f "$STAGE/$ID" "$PKG/linux-x86_64/$ID" | |
| 275 | +[ -f "$STAGE/$ID.musl" ] && cp -f "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID" | |
| 276 | +[ -f "$STAGE/$ID.arm64" ] && cp -f "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID" | |
| 277 | +[ -f "$STAGE/$ID.macos-arm64" ]&& cp -f "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID" | |
| 278 | +[ -f "$STAGE/$ID.macos-x86_64" ]&&cp -f "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID" | |
| 279 | +[ -f "$STAGE/$ID.exe" ] && cp -f "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe" | |
| 280 | +cp -f "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | |
| 281 | +chmod +x "$PKG"/*/$ID 2>/dev/null || true | |
| 282 | +find "$PKG" -type f | sed 's/^/ /' | |
| 283 | + | |
| 284 | +if [ "$DRY_RUN" -eq 1 ]; then | |
| 285 | + say "dry run — staged at $STAGE/pkg (kept for inspection)" | |
| 286 | + trap - EXIT | |
| 287 | + exit 0 | |
| 288 | +fi | |
| 289 | + | |
| 290 | +# ---------------------------------------------------------------- 5. upload | |
| 291 | +say "5/7 upload" | |
| 292 | + | |
| 293 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set — cannot upload" | |
| 294 | +SSH=(ssh -o StrictHostKeyChecking=no) | |
| 295 | +SCP=(scp -o StrictHostKeyChecking=no) | |
| 296 | +if [ -n "$DIST_PASS" ]; then | |
| 297 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | |
| 298 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | |
| 299 | +fi | |
| 300 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | |
| 301 | + | |
| 302 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | |
| 303 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | |
| 304 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | |
| 305 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | |
| 306 | +# OpenSSH 9 refuses to scp a bare "." source. | |
| 307 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | |
| 308 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | |
| 309 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | |
| 310 | + || die "remote extract failed" | |
| 311 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | |
| 312 | + | |
| 313 | +# latest.json = copy of this version's manifest | |
| 314 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | |
| 315 | + || die "latest.json update failed" | |
| 316 | +echo " updated bot-plugins/$SLUG/latest.json" | |
| 317 | + | |
| 318 | +# index.json — merge, preserving every sibling <slug>/latest.json | |
| 319 | +say "index.json merge" | |
| 320 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | |
| 321 | +import json, os, sys, glob | |
| 322 | +slug = sys.argv[1] | |
| 323 | +entries = {} | |
| 324 | +for p in sorted(glob.glob('*/latest.json')): | |
| 325 | + s = os.path.dirname(p) | |
| 326 | + try: | |
| 327 | + entries[s] = json.load(open(p)) | |
| 328 | + except Exception: | |
| 329 | + pass | |
| 330 | +index = { | |
| 331 | + 'ok': True, | |
| 332 | + 'service': 'bot-plugins-dist', | |
| 333 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | |
| 334 | + 'count': len(entries), | |
| 335 | + 'slugs': sorted(entries), | |
| 336 | + 'plugins': [entries[k] for k in sorted(entries)], | |
| 337 | +} | |
| 338 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | |
| 339 | +os.replace('index.json.tmp', 'index.json') | |
| 340 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | |
| 341 | +PY" || die "index.json merge failed" | |
| 342 | + | |
| 343 | +# ---------------------------------------------------------------- 6. mirror | |
| 344 | +say "6/7 plugingit mirror" | |
| 345 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | |
| 346 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | |
| 347 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://x-access-token:${TOKEN}@|") | |
| 348 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | |
| 349 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | |
| 350 | + echo " mirrored to $PLUGINGIT_REMOTE" | |
| 351 | +else | |
| 352 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | |
| 353 | +fi | |
| 354 | + | |
| 355 | +# ---------------------------------------------------------------- 7. verify | |
| 356 | +say "7/7 verify" | |
| 357 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | |
| 358 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | |
| 359 | +if [ "$CODE" = "200" ]; then | |
| 360 | + python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK — %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \ | |
| 361 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | |
| 362 | +else | |
| 363 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | |
| 364 | +fi | |
| 365 | + | |
| 366 | +printf '\n\033[1mrelease complete\033[0m\n' | |
| 367 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 368 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | 1 | new file mode 100644 |
| index 0000000..ac27637 | ||
| --- /dev/null | ||
| +++ b/src/plugin_disks.c | ||
| @@ -0,0 +1,1277 @@ | ||
| 1 | +/* | |
| 2 | + * plugin_disks - ScorpioX Bot open-source local storage inspector plugin | |
| 3 | + * | |
| 4 | + * A single clean-room C99 binary that serves THREE modes: | |
| 5 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery | |
| 6 | + * 2. ?action=mounts | ?action=dirs&root=workspace|home | ?format=json | |
| 7 | + * -> JSON node API | |
| 8 | + * 3. GET (default) -> responsive HTML dashboard | |
| 9 | + * | |
| 10 | + * Local node only. Reads the local kernel interfaces (/proc/mounts + statvfs on | |
| 11 | + * Linux, getmntinfo on macOS, GetLogicalDriveStringsA + GetDiskFreeSpaceExA on | |
| 12 | + * Windows). Makes ZERO outbound network requests, opens no sockets, runs no | |
| 13 | + * remote commands and reads no credentials. | |
| 14 | + * | |
| 15 | + * Directory scanning is deliberately bounded: only the allowlisted roots | |
| 16 | + * /workspace and $HOME may be walked, never an arbitrary path from the query | |
| 17 | + * string, and the walk is capped in depth and in total entries visited. | |
| 18 | + * | |
| 19 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | |
| 20 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | |
| 21 | + * scorpiox-server on the node. | |
| 22 | + * | |
| 23 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 24 | + */ | |
| 25 | + | |
| 26 | +#if defined(__APPLE__) | |
| 27 | + /* sys/mount.h and friends pull BSD types that strict c99 would hide */ | |
| 28 | +# define _DARWIN_C_SOURCE 1 | |
| 29 | +#elif !defined(_WIN32) | |
| 30 | +# define _POSIX_C_SOURCE 200809L | |
| 31 | +# define _DEFAULT_SOURCE 1 | |
| 32 | +#endif | |
| 33 | + | |
| 34 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | |
| 35 | +# define _WIN32_WINNT 0x0601 /* GetDiskFreeSpaceEx / GetVolumeInformationA */ | |
| 36 | +#endif | |
| 37 | + | |
| 38 | +#include <stdio.h> | |
| 39 | +#include <stdlib.h> | |
| 40 | +#include <string.h> | |
| 41 | +#include <time.h> | |
| 42 | +#include <ctype.h> | |
| 43 | +#include <errno.h> | |
| 44 | + | |
| 45 | +#if defined(_WIN32) | |
| 46 | + | |
| 47 | +# define WIN32_LEAN_AND_MEAN | |
| 48 | +# include <windows.h> | |
| 49 | +# include <direct.h> | |
| 50 | +# include <io.h> | |
| 51 | + | |
| 52 | +#else | |
| 53 | + | |
| 54 | +# include <unistd.h> | |
| 55 | +# include <dirent.h> | |
| 56 | +# include <sys/types.h> | |
| 57 | +# include <sys/stat.h> | |
| 58 | +# include <sys/statvfs.h> | |
| 59 | + | |
| 60 | +# if defined(__APPLE__) | |
| 61 | +# include <sys/mount.h> | |
| 62 | +# include <sys/param.h> | |
| 63 | +# endif | |
| 64 | + | |
| 65 | +#endif | |
| 66 | + | |
| 67 | +#define PLUGIN_SLUG "disks" | |
| 68 | +#define PLUGIN_ID "plugin_disks" | |
| 69 | +#define PLUGIN_VER "1.0.0" | |
| 70 | + | |
| 71 | +#define MAX_MOUNTS 256 | |
| 72 | +#define MAX_DIRS 512 | |
| 73 | +#define MAX_SCAN_ENTRIES 120000 | |
| 74 | +#define MAX_DEPTH 8 | |
| 75 | +#define MAX_NAME 256 | |
| 76 | +#define MAX_PATH 1024 | |
| 77 | + | |
| 78 | +/* ------------------------------------------------------------------ */ | |
| 79 | +/* Small utilities */ | |
| 80 | +/* ------------------------------------------------------------------ */ | |
| 81 | + | |
| 82 | +/* Percent-decode in place ('+' becomes space). */ | |
| 83 | +static void url_decode(char *s) | |
| 84 | +{ | |
| 85 | + char *o = s; | |
| 86 | + if (!s) return; | |
| 87 | + while (*s) { | |
| 88 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | |
| 89 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | |
| 90 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | |
| 91 | + *o++ = (char)((hi << 4) | lo); | |
| 92 | + s += 3; | |
| 93 | + } else if (*s == '+') { | |
| 94 | + *o++ = ' '; | |
| 95 | + s++; | |
| 96 | + } else { | |
| 97 | + *o++ = *s++; | |
| 98 | + } | |
| 99 | + } | |
| 100 | + *o = '\0'; | |
| 101 | +} | |
| 102 | + | |
| 103 | +/* Read one parameter (decoded) out of a form/query string. */ | |
| 104 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 105 | +{ | |
| 106 | + size_t klen; | |
| 107 | + const char *p; | |
| 108 | + | |
| 109 | + if (!out || outsz == 0) return 0; | |
| 110 | + out[0] = '\0'; | |
| 111 | + if (!qs || !key) return 0; | |
| 112 | + klen = strlen(key); | |
| 113 | + | |
| 114 | + for (p = qs; *p; ) { | |
| 115 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | |
| 116 | + const char *v = p + klen + 1; | |
| 117 | + size_t i = 0; | |
| 118 | + while (*v && *v != '&' && i + 1 < outsz) | |
| 119 | + out[i++] = *v++; | |
| 120 | + out[i] = '\0'; | |
| 121 | + url_decode(out); | |
| 122 | + return 1; | |
| 123 | + } | |
| 124 | + p = strchr(p, '&'); | |
| 125 | + if (!p) break; | |
| 126 | + p++; | |
| 127 | + } | |
| 128 | + return 0; | |
| 129 | +} | |
| 130 | + | |
| 131 | +static void json_str(const char *s) | |
| 132 | +{ | |
| 133 | + putchar('"'); | |
| 134 | + for (; s && *s; s++) { | |
| 135 | + unsigned char c = (unsigned char)*s; | |
| 136 | + switch (c) { | |
| 137 | + case '"': fputs("\\\"", stdout); break; | |
| 138 | + case '\\': fputs("\\\\", stdout); break; | |
| 139 | + case '\n': fputs("\\n", stdout); break; | |
| 140 | + case '\r': fputs("\\r", stdout); break; | |
| 141 | + case '\t': fputs("\\t", stdout); break; | |
| 142 | + default: | |
| 143 | + if (c < 0x20) printf("\\u%04x", (unsigned)c); | |
| 144 | + else putchar((int)c); | |
| 145 | + } | |
| 146 | + } | |
| 147 | + putchar('"'); | |
| 148 | +} | |
| 149 | + | |
| 150 | +static void utc_now(char *buf, size_t sz) | |
| 151 | +{ | |
| 152 | + time_t t = time(NULL); | |
| 153 | + struct tm tmv; | |
| 154 | +#if defined(_WIN32) | |
| 155 | + gmtime_s(&tmv, &t); | |
| 156 | +#else | |
| 157 | + gmtime_r(&t, &tmv); | |
| 158 | +#endif | |
| 159 | + if (strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv) == 0) { | |
| 160 | + strncpy(buf, "1970-01-01T00:00:00Z", sz - 1); | |
| 161 | + buf[sz - 1] = '\0'; | |
| 162 | + } | |
| 163 | +} | |
| 164 | + | |
| 165 | +static long node_pid(void) | |
| 166 | +{ | |
| 167 | +#if defined(_WIN32) | |
| 168 | + return (long)GetCurrentProcessId(); | |
| 169 | +#else | |
| 170 | + return (long)getpid(); | |
| 171 | +#endif | |
| 172 | +} | |
| 173 | + | |
| 174 | +static double clamp_pct(double v) | |
| 175 | +{ | |
| 176 | + if (v < 0.0) return 0.0; | |
| 177 | + if (v > 100.0) return 100.0; | |
| 178 | + return v; | |
| 179 | +} | |
| 180 | + | |
| 181 | +/* Monotonic-ish millisecond clock used only to report scan duration. */ | |
| 182 | +static long long now_ms(void) | |
| 183 | +{ | |
| 184 | +#if defined(_WIN32) | |
| 185 | + return (long long)GetTickCount64(); | |
| 186 | +#else | |
| 187 | + struct timespec ts; | |
| 188 | + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0; | |
| 189 | + return (long long)ts.tv_sec * 1000LL + (long long)(ts.tv_nsec / 1000000L); | |
| 190 | +#endif | |
| 191 | +} | |
| 192 | + | |
| 193 | +static void copy_str(char *dst, size_t dstsz, const char *src) | |
| 194 | +{ | |
| 195 | + size_t n; | |
| 196 | + if (!dst || dstsz == 0) return; | |
| 197 | + if (!src) { dst[0] = '\0'; return; } | |
| 198 | + n = strlen(src); | |
| 199 | + if (n >= dstsz) n = dstsz - 1; | |
| 200 | + memcpy(dst, src, n); | |
| 201 | + dst[n] = '\0'; | |
| 202 | +} | |
| 203 | + | |
| 204 | +/* ------------------------------------------------------------------ */ | |
| 205 | +/* Node authentication */ | |
| 206 | +/* ------------------------------------------------------------------ */ | |
| 207 | + | |
| 208 | +/* | |
| 209 | + * The node API on :8150 is reachable from the LAN. Every request except | |
| 210 | + * --meta discovery must prove it knows the node password. Accepted forms | |
| 211 | + * match the rest of the node API: X-Bot-Password (what bot-web proxies | |
| 212 | + * with), Authorization: Bearer, and ?pwd= (what the plugin iframe appends). | |
| 213 | + * When BOT_PASSWORD is unset the plugin is a deliberate no-op, which is how | |
| 214 | + * a developer runs it locally from a shell. | |
| 215 | + */ | |
| 216 | +static void require_node_auth(void) | |
| 217 | +{ | |
| 218 | + const char *np = getenv("BOT_PASSWORD"); | |
| 219 | + const char *xp; | |
| 220 | + const char *auth; | |
| 221 | + char qpwd[256]; | |
| 222 | + const char *qs; | |
| 223 | + | |
| 224 | + if (!np || !*np) return; | |
| 225 | + | |
| 226 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | |
| 227 | + if (xp && strcmp(xp, np) == 0) return; | |
| 228 | + | |
| 229 | + auth = getenv("HTTP_AUTHORIZATION"); | |
| 230 | + if (auth) { | |
| 231 | + while (*auth == ' ') auth++; | |
| 232 | + if (strncmp(auth, "Bearer ", 7) == 0) { | |
| 233 | + auth += 7; | |
| 234 | + while (*auth == ' ') auth++; | |
| 235 | + if (strcmp(auth, np) == 0) return; | |
| 236 | + } | |
| 237 | + } | |
| 238 | + | |
| 239 | + qs = getenv("QUERY_STRING"); | |
| 240 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | |
| 241 | + return; | |
| 242 | + | |
| 243 | + fputs("Status: 401 Unauthorized\r\n" | |
| 244 | + "Content-Type: application/json; charset=utf-8\r\n" | |
| 245 | + "Cache-Control: no-store\r\n" | |
| 246 | + "X-Content-Type-Options: nosniff\r\n\r\n" | |
| 247 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | |
| 248 | + exit(0); | |
| 249 | +} | |
| 250 | + | |
| 251 | +/* ------------------------------------------------------------------ */ | |
| 252 | +/* Mount table */ | |
| 253 | +/* ------------------------------------------------------------------ */ | |
| 254 | + | |
| 255 | +typedef struct { | |
| 256 | + char device[MAX_NAME]; | |
| 257 | + char fstype[64]; | |
| 258 | + char mount[MAX_PATH]; | |
| 259 | + unsigned long long total_bytes; | |
| 260 | + unsigned long long used_bytes; | |
| 261 | + unsigned long long free_bytes; | |
| 262 | + unsigned long long avail_bytes; | |
| 263 | + unsigned long long inodes_total; | |
| 264 | + unsigned long long inodes_used; | |
| 265 | + int has_inodes; | |
| 266 | +} mount_t; | |
| 267 | + | |
| 268 | +/* Filesystems that report kernel-internal state rather than user storage. */ | |
| 269 | +static int pseudo_fstype(const char *fs) | |
| 270 | +{ | |
| 271 | + static const char *PSEUDO[] = { | |
| 272 | + "proc", "sysfs", "cgroup", "cgroup2", "devpts", "devtmpfs", | |
| 273 | + "securityfs", "pstore", "bpf", "debugfs", "tracefs", "hugetlbfs", | |
| 274 | + "mqueue", "autofs", "configfs", "fusectl", "efivarfs", "rpc_pipefs", | |
| 275 | + "nsfs", "binfmt_misc", "selinuxfs", "fuse.gvfsd-fuse", "fuse.portal", | |
| 276 | + "procfs", "devfs", "none", NULL | |
| 277 | + }; | |
| 278 | + int i; | |
| 279 | + for (i = 0; PSEUDO[i]; i++) | |
| 280 | + if (strcmp(fs, PSEUDO[i]) == 0) return 1; | |
| 281 | + return 0; | |
| 282 | +} | |
| 283 | + | |
| 284 | +/* | |
| 285 | + * Kernel mountpoints that exist only to back kernel state. /dev, /sys, /proc | |
| 286 | + * and anything below them are never interesting to a user asking about | |
| 287 | + * storage; /run is a real tmpfs and is kept. | |
| 288 | + */ | |
| 289 | +static int pseudo_mountpoint(const char *mp) | |
| 290 | +{ | |
| 291 | + static const char *PREFIX[] = { "/sys", "/proc", "/dev", NULL }; | |
| 292 | + int i; | |
| 293 | + for (i = 0; PREFIX[i]; i++) { | |
| 294 | + size_t n = strlen(PREFIX[i]); | |
| 295 | + if (strncmp(mp, PREFIX[i], n) == 0 && (mp[n] == '\0' || mp[n] == '/')) | |
| 296 | + return 1; | |
| 297 | + } | |
| 298 | + return 0; | |
| 299 | +} | |
| 300 | + | |
| 301 | +#if !defined(_WIN32) | |
| 302 | + | |
| 303 | +/* /proc/mounts and /etc/mtab escape space, tab, newline and backslash as octal. */ | |
| 304 | +static void unescape_mount_field(char *s) | |
| 305 | +{ | |
| 306 | + char *o = s; | |
| 307 | + while (*s) { | |
| 308 | + if (*s == '\\' && s[1] >= '0' && s[1] <= '3' && | |
| 309 | + s[2] >= '0' && s[2] <= '7' && s[3] >= '0' && s[3] <= '7') { | |
| 310 | + *o++ = (char)(((s[1] - '0') << 6) | ((s[2] - '0') << 3) | (s[3] - '0')); | |
| 311 | + s += 4; | |
| 312 | + } else { | |
| 313 | + *o++ = *s++; | |
| 314 | + } | |
| 315 | + } | |
| 316 | + *o = '\0'; | |
| 317 | +} | |
| 318 | + | |
| 319 | +static void fill_vfs(const char *mp, mount_t *m) | |
| 320 | +{ | |
| 321 | + struct statvfs vfs; | |
| 322 | + if (statvfs(mp, &vfs) != 0) return; | |
| 323 | + m->total_bytes = (unsigned long long)vfs.f_blocks * (unsigned long long)vfs.f_frsize; | |
| 324 | + m->free_bytes = (unsigned long long)vfs.f_bfree * (unsigned long long)vfs.f_frsize; | |
| 325 | + m->avail_bytes = (unsigned long long)vfs.f_bavail * (unsigned long long)vfs.f_frsize; | |
| 326 | + m->used_bytes = m->total_bytes >= m->free_bytes ? m->total_bytes - m->free_bytes : 0; | |
| 327 | + if (vfs.f_files > 0) { | |
| 328 | + m->has_inodes = 1; | |
| 329 | + m->inodes_total = (unsigned long long)vfs.f_files; | |
| 330 | + m->inodes_used = m->inodes_total >= (unsigned long long)vfs.f_ffree | |
| 331 | + ? m->inodes_total - (unsigned long long)vfs.f_ffree : 0; | |
| 332 | + } | |
| 333 | +} | |
| 334 | + | |
| 335 | +#endif /* !_WIN32 */ | |
| 336 | + | |
| 337 | +#if defined(__APPLE__) | |
| 338 | + | |
| 339 | +static int collect_mounts(mount_t *out, int max) | |
| 340 | +{ | |
| 341 | + struct statfs *mnt = NULL; | |
| 342 | + int n, i, count = 0; | |
| 343 | + | |
| 344 | + n = getmntinfo(&mnt, MNT_NOWAIT); | |
| 345 | + if (n <= 0) return 0; | |
| 346 | + | |
| 347 | + for (i = 0; i < n && count < max; i++) { | |
| 348 | + mount_t *m = &out[count]; | |
| 349 | + unsigned long long bs = (unsigned long long)mnt[i].f_bsize; | |
| 350 | + if (pseudo_fstype(mnt[i].f_fstypename)) continue; | |
| 351 | + if (pseudo_mountpoint(mnt[i].f_mntonname)) continue; | |
| 352 | + memset(m, 0, sizeof(*m)); | |
| 353 | + copy_str(m->device, sizeof(m->device), mnt[i].f_mntfromname); | |
| 354 | + copy_str(m->fstype, sizeof(m->fstype), mnt[i].f_fstypename); | |
| 355 | + copy_str(m->mount, sizeof(m->mount), mnt[i].f_mntonname); | |
| 356 | + m->total_bytes = (unsigned long long)mnt[i].f_blocks * bs; | |
| 357 | + m->free_bytes = (unsigned long long)mnt[i].f_bfree * bs; | |
| 358 | + m->avail_bytes = (unsigned long long)mnt[i].f_bavail * bs; | |
| 359 | + m->used_bytes = m->total_bytes >= m->free_bytes ? m->total_bytes - m->free_bytes : 0; | |
| 360 | + if (mnt[i].f_files > 0) { | |
| 361 | + m->has_inodes = 1; | |
| 362 | + m->inodes_total = (unsigned long long)mnt[i].f_files; | |
| 363 | + m->inodes_used = m->inodes_total >= (unsigned long long)mnt[i].f_ffree | |
| 364 | + ? m->inodes_total - (unsigned long long)mnt[i].f_ffree : 0; | |
| 365 | + } | |
| 366 | + count++; | |
| 367 | + } | |
| 368 | + return count; | |
| 369 | +} | |
| 370 | + | |
| 371 | +#elif defined(_WIN32) | |
| 372 | + | |
| 373 | +static int collect_mounts(mount_t *out, int max) | |
| 374 | +{ | |
| 375 | + char drives[512]; | |
| 376 | + DWORD n; | |
| 377 | + int count = 0; | |
| 378 | + const char *p; | |
| 379 | + | |
| 380 | + n = GetLogicalDriveStringsA(sizeof(drives) - 1, drives); | |
| 381 | + if (n == 0) return 0; | |
| 382 | + | |
| 383 | + for (p = drives; *p && count < max; p += strlen(p) + 1) { | |
| 384 | + ULARGE_INTEGER avail, total, totalfree; | |
| 385 | + char fsname[64] = "unknown"; | |
| 386 | + mount_t *m; | |
| 387 | + | |
| 388 | + if (GetDriveTypeA(p) == DRIVE_NO_ROOT_DIR) continue; | |
| 389 | + if (!GetDiskFreeSpaceExA(p, &avail, &total, &totalfree)) continue; | |
| 390 | + | |
| 391 | + m = &out[count]; | |
| 392 | + memset(m, 0, sizeof(*m)); | |
| 393 | + copy_str(m->device, sizeof(m->device), p); | |
| 394 | + copy_str(m->mount, sizeof(m->mount), p); | |
| 395 | + if (GetVolumeInformationA(p, NULL, 0, NULL, NULL, NULL, fsname, (DWORD)sizeof(fsname)) && fsname[0]) | |
| 396 | + copy_str(m->fstype, sizeof(m->fstype), fsname); | |
| 397 | + else | |
| 398 | + copy_str(m->fstype, sizeof(m->fstype), "win32"); | |
| 399 | + | |
| 400 | + m->total_bytes = (unsigned long long)total.QuadPart; | |
| 401 | + m->free_bytes = (unsigned long long)totalfree.QuadPart; | |
| 402 | + m->avail_bytes = (unsigned long long)avail.QuadPart; | |
| 403 | + m->used_bytes = m->total_bytes >= m->free_bytes ? m->total_bytes - m->free_bytes : 0; | |
| 404 | + count++; | |
| 405 | + } | |
| 406 | + return count; | |
| 407 | +} | |
| 408 | + | |
| 409 | +#else /* Linux and other POSIX */ | |
| 410 | + | |
| 411 | +static int collect_mounts(mount_t *out, int max) | |
| 412 | +{ | |
| 413 | + FILE *fp; | |
| 414 | + char line[2048]; | |
| 415 | + int count = 0; | |
| 416 | + | |
| 417 | + fp = fopen("/proc/mounts", "r"); | |
| 418 | + if (!fp) fp = fopen("/etc/mtab", "r"); | |
| 419 | + if (!fp) return 0; | |
| 420 | + | |
| 421 | + while (fgets(line, sizeof(line), fp) && count < max) { | |
| 422 | + char dev[MAX_NAME], mp[MAX_PATH], fs[64]; | |
| 423 | + int i = 0; | |
| 424 | + char *tok[3]; | |
| 425 | + char *p = line; | |
| 426 | + | |
| 427 | + /* split the first three whitespace-separated fields */ | |
| 428 | + while (i < 3) { | |
| 429 | + while (*p == ' ' || *p == '\t') p++; | |
| 430 | + if (!*p || *p == '\n') break; | |
| 431 | + tok[i++] = p; | |
| 432 | + while (*p && *p != ' ' && *p != '\t' && *p != '\n') p++; | |
| 433 | + if (*p) *p++ = '\0'; | |
| 434 | + } | |
| 435 | + if (i < 3) continue; | |
| 436 | + | |
| 437 | + copy_str(dev, sizeof(dev), tok[0]); | |
| 438 | + copy_str(mp, sizeof(mp), tok[1]); | |
| 439 | + copy_str(fs, sizeof(fs), tok[2]); | |
| 440 | + unescape_mount_field(dev); | |
| 441 | + unescape_mount_field(mp); | |
| 442 | + | |
| 443 | + if (pseudo_fstype(fs)) continue; | |
| 444 | + if (pseudo_mountpoint(mp)) continue; | |
| 445 | + | |
| 446 | + /* /proc/mounts can list the same mountpoint more than once (a bind | |
| 447 | + * mount, or a container overlay that repeats a host mount). Keep the | |
| 448 | + * first entry per mountpoint so the dashboard does not double-count. */ | |
| 449 | + { | |
| 450 | + int dup = 0, k; | |
| 451 | + for (k = 0; k < count; k++) { | |
| 452 | + if (strcmp(out[k].mount, mp) == 0) { dup = 1; break; } | |
| 453 | + } | |
| 454 | + if (dup) continue; | |
| 455 | + } | |
| 456 | + | |
| 457 | + memset(&out[count], 0, sizeof(out[count])); | |
| 458 | + copy_str(out[count].device, sizeof(out[count].device), dev); | |
| 459 | + copy_str(out[count].fstype, sizeof(out[count].fstype), fs); | |
| 460 | + copy_str(out[count].mount, sizeof(out[count].mount), mp); | |
| 461 | + fill_vfs(mp, &out[count]); | |
| 462 | + count++; | |
| 463 | + } | |
| 464 | + fclose(fp); | |
| 465 | + return count; | |
| 466 | +} | |
| 467 | + | |
| 468 | +#endif | |
| 469 | + | |
| 470 | +/* Largest first. Used for display order. */ | |
| 471 | +static int mount_cmp(const void *a, const void *b) | |
| 472 | +{ | |
| 473 | + const mount_t *x = (const mount_t *)a; | |
| 474 | + const mount_t *y = (const mount_t *)b; | |
| 475 | + if (x->total_bytes < y->total_bytes) return 1; | |
| 476 | + if (x->total_bytes > y->total_bytes) return -1; | |
| 477 | + return strcmp(x->mount, y->mount); | |
| 478 | +} | |
| 479 | + | |
| 480 | +static const char *platform_name(void) | |
| 481 | +{ | |
| 482 | +#if defined(_WIN32) | |
| 483 | + return "windows"; | |
| 484 | +#elif defined(__APPLE__) | |
| 485 | + return "macos"; | |
| 486 | +#else | |
| 487 | + return "linux"; | |
| 488 | +#endif | |
| 489 | +} | |
| 490 | + | |
| 491 | +/* ------------------------------------------------------------------ */ | |
| 492 | +/* Bounded 1-level directory sizing */ | |
| 493 | +/* ------------------------------------------------------------------ */ | |
| 494 | + | |
| 495 | +typedef struct { | |
| 496 | + char name[MAX_NAME]; | |
| 497 | + char path[MAX_PATH]; | |
| 498 | + unsigned long long bytes; | |
| 499 | + int is_dir; | |
| 500 | +} dir_sz_t; | |
| 501 | + | |
| 502 | +typedef struct { | |
| 503 | + unsigned long long visited; | |
| 504 | + int truncated; | |
| 505 | +} scan_state_t; | |
| 506 | + | |
| 507 | +static int skip_entry_name(const char *n) | |
| 508 | +{ | |
| 509 | + if (!n || !*n) return 1; | |
| 510 | + if (strcmp(n, ".") == 0 || strcmp(n, "..") == 0) return 1; | |
| 511 | + return 0; | |
| 512 | +} | |
| 513 | + | |
| 514 | +#if defined(_WIN32) | |
| 515 | + | |
| 516 | +static unsigned long long sum_dir_win(const char *dir, int depth, scan_state_t *st) | |
| 517 | +{ | |
| 518 | + char pattern[MAX_PATH]; | |
| 519 | + WIN32_FIND_DATAA fd; | |
| 520 | + HANDLE h; | |
| 521 | + unsigned long long total = 0; | |
| 522 | + | |
| 523 | + if (depth > MAX_DEPTH || st->truncated) return 0; | |
| 524 | + sprintf(pattern, "%s\\*", dir); | |
| 525 | + h = FindFirstFileA(pattern, &fd); | |
| 526 | + if (h == INVALID_HANDLE_VALUE) return 0; | |
| 527 | + | |
| 528 | + do { | |
| 529 | + char child[MAX_PATH]; | |
| 530 | + if (skip_entry_name(fd.cFileName)) continue; | |
| 531 | + if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) continue; | |
| 532 | + if (++st->visited > MAX_SCAN_ENTRIES) { st->truncated = 1; break; } | |
| 533 | + sprintf(child, "%s\\%s", dir, fd.cFileName); | |
| 534 | + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) | |
| 535 | + total += sum_dir_win(child, depth + 1, st); | |
| 536 | + else | |
| 537 | + total += ((unsigned long long)fd.nFileSizeHigh << 32) | (unsigned long long)fd.nFileSizeLow; | |
| 538 | + } while (FindNextFileA(h, &fd)); | |
| 539 | + | |
| 540 | + FindClose(h); | |
| 541 | + return total; | |
| 542 | +} | |
| 543 | + | |
| 544 | +#else | |
| 545 | + | |
| 546 | +static unsigned long long sum_dir_posix(const char *dir, int depth, scan_state_t *st) | |
| 547 | +{ | |
| 548 | + DIR *d; | |
| 549 | + struct dirent *e; | |
| 550 | + unsigned long long total = 0; | |
| 551 | + | |
| 552 | + if (depth > MAX_DEPTH || st->truncated) return 0; | |
| 553 | + d = opendir(dir); | |
| 554 | + if (!d) return 0; | |
| 555 | + | |
| 556 | + while ((e = readdir(d)) != NULL) { | |
| 557 | + char child[MAX_PATH]; | |
| 558 | + struct stat sb; | |
| 559 | + if (skip_entry_name(e->d_name)) continue; | |
| 560 | + if (++st->visited > MAX_SCAN_ENTRIES) { st->truncated = 1; break; } | |
| 561 | + if (snprintf(child, sizeof(child), "%s/%s", dir, e->d_name) >= (int)sizeof(child)) continue; | |
| 562 | + /* lstat: symlinks are never followed, so a link back up the tree | |
| 563 | + * cannot make the walk unbounded. */ | |
| 564 | + if (lstat(child, &sb) != 0) continue; | |
| 565 | + if (S_ISLNK(sb.st_mode)) continue; | |
| 566 | + if (S_ISDIR(sb.st_mode)) | |
| 567 | + total += sum_dir_posix(child, depth + 1, st); | |
| 568 | + else if (S_ISREG(sb.st_mode)) | |
| 569 | + total += (unsigned long long)sb.st_size; | |
| 570 | + } | |
| 571 | + closedir(d); | |
| 572 | + return total; | |
| 573 | +} | |
| 574 | + | |
| 575 | +#endif | |
| 576 | + | |
| 577 | +static int dir_cmp(const void *a, const void *b) | |
| 578 | +{ | |
| 579 | + const dir_sz_t *x = (const dir_sz_t *)a; | |
| 580 | + const dir_sz_t *y = (const dir_sz_t *)b; | |
| 581 | + if (x->bytes < y->bytes) return 1; | |
| 582 | + if (x->bytes > y->bytes) return -1; | |
| 583 | + return strcmp(x->name, y->name); | |
| 584 | +} | |
| 585 | + | |
| 586 | +/* Resolve an allowlisted root token to a real path. | |
| 587 | + * Returns 1 resolved, | |
| 588 | + * 0 token is not an allowlisted root, | |
| 589 | + * -1 token is allowlisted but the root does not exist on this node. */ | |
| 590 | +static int resolve_root(const char *kind, char *out, size_t outsz, const char **label) | |
| 591 | +{ | |
| 592 | + if (!kind || !*kind) return 0; | |
| 593 | + | |
| 594 | + if (strcmp(kind, "workspace") == 0) { | |
| 595 | + *label = "/workspace"; | |
| 596 | +#if defined(_WIN32) | |
| 597 | + return -1; /* no /workspace on a native Windows node */ | |
| 598 | +#else | |
| 599 | + if (access("/workspace", R_OK | X_OK) != 0) return -1; | |
| 600 | + copy_str(out, outsz, "/workspace"); | |
| 601 | + return 1; | |
| 602 | +#endif | |
| 603 | + } | |
| 604 | + | |
| 605 | + if (strcmp(kind, "home") == 0) { | |
| 606 | +#if defined(_WIN32) | |
| 607 | + const char *up = getenv("USERPROFILE"); | |
| 608 | + if (!up || !*up) return -1; | |
| 609 | + copy_str(out, outsz, up); | |
| 610 | +#else | |
| 611 | + const char *hp = getenv("HOME"); | |
| 612 | + if (!hp || !*hp) return -1; | |
| 613 | + copy_str(out, outsz, hp); | |
| 614 | +#endif | |
| 615 | + *label = "$HOME"; | |
| 616 | + return 1; | |
| 617 | + } | |
| 618 | + | |
| 619 | + return 0; | |
| 620 | +} | |
| 621 | + | |
| 622 | +static int scan_root(const char *root, dir_sz_t *out, int max, int *count_out, int *truncated, int *root_kind) | |
| 623 | +{ | |
| 624 | + scan_state_t st; | |
| 625 | + int count = 0; | |
| 626 | + | |
| 627 | + st.visited = 0; | |
| 628 | + st.truncated = 0; | |
| 629 | + *truncated = 0; | |
| 630 | + *root_kind = 0; | |
| 631 | + (void)root_kind; | |
| 632 | + | |
| 633 | +#if defined(_WIN32) | |
| 634 | + { | |
| 635 | + char pattern[MAX_PATH]; | |
| 636 | + WIN32_FIND_DATAA fd; | |
| 637 | + HANDLE h; | |
| 638 | + sprintf(pattern, "%s\\*", root); | |
| 639 | + h = FindFirstFileA(pattern, &fd); | |
| 640 | + if (h == INVALID_HANDLE_VALUE) { *count_out = 0; return 0; } | |
| 641 | + do { | |
| 642 | + dir_sz_t *e; | |
| 643 | + if (skip_entry_name(fd.cFileName)) continue; | |
| 644 | + if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) continue; | |
| 645 | + if (count >= max) { st.truncated = 1; break; } | |
| 646 | + if (++st.visited > MAX_SCAN_ENTRIES) { st.truncated = 1; break; } | |
| 647 | + e = &out[count]; | |
| 648 | + memset(e, 0, sizeof(*e)); | |
| 649 | + copy_str(e->name, sizeof(e->name), fd.cFileName); | |
| 650 | + sprintf(e->path, "%s\\%s", root, fd.cFileName); | |
| 651 | + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { | |
| 652 | + e->is_dir = 1; | |
| 653 | + e->bytes = sum_dir_win(e->path, 1, &st); | |
| 654 | + } else { | |
| 655 | + e->bytes = ((unsigned long long)fd.nFileSizeHigh << 32) | (unsigned long long)fd.nFileSizeLow; | |
| 656 | + } | |
| 657 | + count++; | |
| 658 | + } while (FindNextFileA(h, &fd)); | |
| 659 | + FindClose(h); | |
| 660 | + } | |
| 661 | +#else | |
| 662 | + { | |
| 663 | + DIR *d = opendir(root); | |
| 664 | + struct dirent *de; | |
| 665 | + if (!d) { *count_out = 0; return 0; } | |
| 666 | + while ((de = readdir(d)) != NULL) { | |
| 667 | + dir_sz_t *e; | |
| 668 | + struct stat sb; | |
| 669 | + char path[MAX_PATH]; | |
| 670 | + if (skip_entry_name(de->d_name)) continue; | |
| 671 | + if (count >= max) { st.truncated = 1; break; } | |
| 672 | + if (++st.visited > MAX_SCAN_ENTRIES) { st.truncated = 1; break; } | |
| 673 | + if (snprintf(path, sizeof(path), "%s/%s", root, de->d_name) >= (int)sizeof(path)) continue; | |
| 674 | + if (lstat(path, &sb) != 0) continue; | |
| 675 | + if (S_ISLNK(sb.st_mode)) continue; | |
| 676 | + e = &out[count]; | |
| 677 | + memset(e, 0, sizeof(*e)); | |
| 678 | + copy_str(e->name, sizeof(e->name), de->d_name); | |
| 679 | + copy_str(e->path, sizeof(e->path), path); | |
| 680 | + if (S_ISDIR(sb.st_mode)) { | |
| 681 | + e->is_dir = 1; | |
| 682 | + e->bytes = sum_dir_posix(path, 1, &st); | |
| 683 | + } else if (S_ISREG(sb.st_mode)) { | |
| 684 | + e->bytes = (unsigned long long)sb.st_size; | |
| 685 | + } | |
| 686 | + count++; | |
| 687 | + } | |
| 688 | + closedir(d); | |
| 689 | + } | |
| 690 | +#endif | |
| 691 | + | |
| 692 | + if (count > 1) qsort(out, (size_t)count, sizeof(out[0]), dir_cmp); | |
| 693 | + *truncated = st.truncated; | |
| 694 | + *count_out = count; | |
| 695 | + return 1; | |
| 696 | +} | |
| 697 | + | |
| 698 | +/* ------------------------------------------------------------------ */ | |
| 699 | +/* Modes */ | |
| 700 | +/* ------------------------------------------------------------------ */ | |
| 701 | + | |
| 702 | +static int mode_meta(void) | |
| 703 | +{ | |
| 704 | + puts("{\"name\":\"disks\",\"desc\":\"Local storage\"}"); | |
| 705 | + return 0; | |
| 706 | +} | |
| 707 | + | |
| 708 | +static void json_header(void) | |
| 709 | +{ | |
| 710 | + /* Deliberately no Content-Length - the server owns framing. */ | |
| 711 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | |
| 712 | + "Cache-Control: no-store\r\n" | |
| 713 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 714 | +} | |
| 715 | + | |
| 716 | +static void emit_mounts(void) | |
| 717 | +{ | |
| 718 | + mount_t mnt[MAX_MOUNTS]; | |
| 719 | + int i, n; | |
| 720 | + | |
| 721 | + memset(mnt, 0, sizeof(mnt)); | |
| 722 | + n = collect_mounts(mnt, MAX_MOUNTS); | |
| 723 | + if (n > 1) qsort(mnt, (size_t)n, sizeof(mnt[0]), mount_cmp); | |
| 724 | + | |
| 725 | + fputs("[", stdout); | |
| 726 | + for (i = 0; i < n; i++) { | |
| 727 | + const mount_t *m = &mnt[i]; | |
| 728 | + double pct = 0.0, ipct = 0.0; | |
| 729 | + if (m->used_bytes + m->avail_bytes > 0) | |
| 730 | + pct = (double)m->used_bytes * 100.0 / (double)(m->used_bytes + m->avail_bytes); | |
| 731 | + if (m->has_inodes && m->inodes_total > 0) | |
| 732 | + ipct = (double)m->inodes_used * 100.0 / (double)m->inodes_total; | |
| 733 | + | |
| 734 | + if (i) fputs(",", stdout); | |
| 735 | + fputs("{\"device\":", stdout); | |
| 736 | + json_str(m->device); | |
| 737 | + fputs(",\"fstype\":", stdout); | |
| 738 | + json_str(m->fstype); | |
| 739 | + fputs(",\"mount\":", stdout); | |
| 740 | + json_str(m->mount); | |
| 741 | + printf(",\"total_bytes\":%llu,\"used_bytes\":%llu,\"free_bytes\":%llu," | |
| 742 | + "\"avail_bytes\":%llu,\"pct\":%.1f", | |
| 743 | + m->total_bytes, m->used_bytes, m->free_bytes, m->avail_bytes, | |
| 744 | + clamp_pct(pct)); | |
| 745 | + printf(",\"inodes_total\":%llu,\"inodes_used\":%llu," | |
| 746 | + "\"inodes_pct\":%.1f,\"has_inodes\":%s}", | |
| 747 | + m->inodes_total, m->inodes_used, clamp_pct(ipct), | |
| 748 | + m->has_inodes ? "true" : "false"); | |
| 749 | + } | |
| 750 | + fputs("]", stdout); | |
| 751 | +} | |
| 752 | + | |
| 753 | +static int mode_json(const char *qs) | |
| 754 | +{ | |
| 755 | + char action[64]; | |
| 756 | + char rootkind[32]; | |
| 757 | + char utc[40]; | |
| 758 | + | |
| 759 | + action[0] = rootkind[0] = '\0'; | |
| 760 | + get_query_val(qs, "action", action, sizeof(action)); | |
| 761 | + get_query_val(qs, "root", rootkind, sizeof(rootkind)); | |
| 762 | + | |
| 763 | + if (action[0] && strcmp(action, "mounts") != 0 && | |
| 764 | + strcmp(action, "dirs") != 0 && strcmp(action, "info") != 0) { | |
| 765 | + json_header(); | |
| 766 | + printf("{\"ok\":false,\"error\":\"unknown_action\"," | |
| 767 | + "\"supported\":[\"mounts\",\"dirs\",\"info\"],\"requested\":"); | |
| 768 | + json_str(action); | |
| 769 | + fputs("}\n", stdout); | |
| 770 | + return 0; | |
| 771 | + } | |
| 772 | + if (!action[0]) copy_str(action, sizeof(action), "mounts"); | |
| 773 | + | |
| 774 | + utc_now(utc, sizeof(utc)); | |
| 775 | + | |
| 776 | + if (strcmp(action, "info") == 0) { | |
| 777 | + json_header(); | |
| 778 | + fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," | |
| 779 | + "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout); | |
| 780 | + json_str(platform_name()); | |
| 781 | + fputs(",\"pid\":", stdout); | |
| 782 | + printf("%ld", node_pid()); | |
| 783 | + fputs(",\"utc\":", stdout); | |
| 784 | + json_str(utc); | |
| 785 | + fputs(",\"node_auth\":", stdout); | |
| 786 | + { | |
| 787 | + const char *np = getenv("BOT_PASSWORD"); | |
| 788 | + fputs((np && *np) ? "true" : "false", stdout); | |
| 789 | + } | |
| 790 | + fputs(",\"supported\":[\"mounts\",\"dirs\",\"info\"],\"zero_network\":true," | |
| 791 | + "\"allowed_roots\":[\"workspace\",\"home\"]," | |
| 792 | + "\"max_depth\":", stdout); | |
| 793 | + printf("%d", MAX_DEPTH); | |
| 794 | + fputs(",\"max_scan_entries\":", stdout); | |
| 795 | + printf("%d", MAX_SCAN_ENTRIES); | |
| 796 | + fputs("}\n", stdout); | |
| 797 | + return 0; | |
| 798 | + } | |
| 799 | + | |
| 800 | + if (strcmp(action, "dirs") == 0) { | |
| 801 | + char root[MAX_PATH]; | |
| 802 | + const char *label = ""; | |
| 803 | + dir_sz_t *dirs; | |
| 804 | + int count = 0, truncated = 0, kind = 0; | |
| 805 | + long long t0, t1; | |
| 806 | + unsigned long long total_bytes = 0, used_bytes = 0, free_bytes = 0; | |
| 807 | + double root_pct = 0.0; | |
| 808 | + int i; | |
| 809 | + | |
| 810 | + if (!rootkind[0]) { | |
| 811 | + json_header(); | |
| 812 | + fputs("{\"ok\":false,\"error\":\"missing_root\"," | |
| 813 | + "\"allowed_roots\":[\"workspace\",\"home\"]}\n", stdout); | |
| 814 | + return 0; | |
| 815 | + } | |
| 816 | + /* Strict allowlist: an arbitrary path can never be walked. */ | |
| 817 | + { | |
| 818 | + int rv = resolve_root(rootkind, root, sizeof(root), &label); | |
| 819 | + if (rv == 0) { | |
| 820 | + json_header(); | |
| 821 | + fputs("{\"ok\":false,\"error\":\"root_not_allowed\"," | |
| 822 | + "\"allowed_roots\":[\"workspace\",\"home\"],\"requested\":", stdout); | |
| 823 | + json_str(rootkind); | |
| 824 | + fputs("}\n", stdout); | |
| 825 | + return 0; | |
| 826 | + } | |
| 827 | + if (rv < 0) { | |
| 828 | + json_header(); | |
| 829 | + fputs("{\"ok\":false,\"error\":\"root_unavailable\"," | |
| 830 | + "\"allowed_roots\":[\"workspace\",\"home\"],\"requested\":", stdout); | |
| 831 | + json_str(rootkind); | |
| 832 | + fputs(",\"message\":\"this root does not exist on this node\"}\n", stdout); | |
| 833 | + return 0; | |
| 834 | + } | |
| 835 | + } | |
| 836 | + | |
| 837 | +#if !defined(_WIN32) | |
| 838 | + { | |
| 839 | + struct statvfs vfs; | |
| 840 | + if (statvfs(root, &vfs) == 0) { | |
| 841 | + total_bytes = (unsigned long long)vfs.f_blocks * (unsigned long long)vfs.f_frsize; | |
| 842 | + free_bytes = (unsigned long long)vfs.f_bfree * (unsigned long long)vfs.f_frsize; | |
| 843 | + used_bytes = total_bytes >= free_bytes ? total_bytes - free_bytes : 0; | |
| 844 | + if (used_bytes + (unsigned long long)vfs.f_bavail * (unsigned long long)vfs.f_frsize > 0) | |
| 845 | + root_pct = (double)used_bytes * 100.0 / | |
| 846 | + (double)(used_bytes + (unsigned long long)vfs.f_bavail * (unsigned long long)vfs.f_frsize); | |
| 847 | + } | |
| 848 | + } | |
| 849 | +#endif | |
| 850 | + | |
| 851 | + dirs = (dir_sz_t *)calloc((size_t)MAX_DIRS, sizeof(dir_sz_t)); | |
| 852 | + if (!dirs) { | |
| 853 | + json_header(); | |
| 854 | + fputs("{\"ok\":false,\"error\":\"out_of_memory\"}\n", stdout); | |
| 855 | + return 0; | |
| 856 | + } | |
| 857 | + | |
| 858 | + t0 = now_ms(); | |
| 859 | + scan_root(root, dirs, MAX_DIRS, &count, &truncated, &kind); | |
| 860 | + t1 = now_ms(); | |
| 861 | + | |
| 862 | + json_header(); | |
| 863 | + fputs("{\"ok\":true,\"action\":\"dirs\",\"plugin\":\"" PLUGIN_ID "\"," | |
| 864 | + "\"platform\":", stdout); | |
| 865 | + json_str(platform_name()); | |
| 866 | + fputs(",\"root_kind\":", stdout); | |
| 867 | + json_str(rootkind); | |
| 868 | + fputs(",\"root\":", stdout); | |
| 869 | + json_str(root); | |
| 870 | + fputs(",\"root_label\":", stdout); | |
| 871 | + json_str(label); | |
| 872 | + printf(",\"root_total_bytes\":%llu,\"root_used_bytes\":%llu," | |
| 873 | + "\"root_free_bytes\":%llu,\"root_pct\":%.1f", | |
| 874 | + total_bytes, used_bytes, free_bytes, clamp_pct(root_pct)); | |
| 875 | + printf(",\"count\":%d,\"truncated\":%s,\"max_depth\":%d," | |
| 876 | + "\"max_scan_entries\":%d,\"scan_ms\":%lld,\"utc\":", | |
| 877 | + count, truncated ? "true" : "false", MAX_DEPTH, MAX_SCAN_ENTRIES, t1 - t0); | |
| 878 | + json_str(utc); | |
| 879 | + fputs(",\"entries\":[", stdout); | |
| 880 | + for (i = 0; i < count; i++) { | |
| 881 | + double pct = total_bytes > 0 | |
| 882 | + ? (double)dirs[i].bytes * 100.0 / (double)total_bytes : 0.0; | |
| 883 | + if (i) fputs(",", stdout); | |
| 884 | + fputs("{\"name\":", stdout); | |
| 885 | + json_str(dirs[i].name); | |
| 886 | + fputs(",\"path\":", stdout); | |
| 887 | + json_str(dirs[i].path); | |
| 888 | + printf(",\"bytes\":%llu,\"pct\":%.1f,\"is_dir\":%s}", | |
| 889 | + dirs[i].bytes, clamp_pct(pct), dirs[i].is_dir ? "true" : "false"); | |
| 890 | + } | |
| 891 | + fputs("]}\n", stdout); | |
| 892 | + free(dirs); | |
| 893 | + return 0; | |
| 894 | + } | |
| 895 | + | |
| 896 | + /* action == mounts */ | |
| 897 | + { | |
| 898 | + mount_t probe[MAX_MOUNTS]; | |
| 899 | + int n; | |
| 900 | + memset(probe, 0, sizeof(probe)); | |
| 901 | + n = collect_mounts(probe, MAX_MOUNTS); | |
| 902 | + json_header(); | |
| 903 | + fputs("{\"ok\":true,\"action\":\"mounts\",\"plugin\":\"" PLUGIN_ID "\"," | |
| 904 | + "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout); | |
| 905 | + json_str(platform_name()); | |
| 906 | + printf(",\"pid\":%ld,\"count\":%d,\"utc\":", node_pid(), n); | |
| 907 | + json_str(utc); | |
| 908 | + fputs(",\"zero_network\":true,\"mounts\":", stdout); | |
| 909 | + emit_mounts(); | |
| 910 | + fputs("}\n", stdout); | |
| 911 | + } | |
| 912 | + return 0; | |
| 913 | +} | |
| 914 | + | |
| 915 | +/* ------------------------------------------------------------------ */ | |
| 916 | +/* HTML UI */ | |
| 917 | +/* ------------------------------------------------------------------ */ | |
| 918 | + | |
| 919 | +static int mode_html(int embed) | |
| 920 | +{ | |
| 921 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | |
| 922 | + "Cache-Control: no-store\r\n" | |
| 923 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 924 | + | |
| 925 | + fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>" | |
| 926 | + "<meta name='viewport' content='width=device-width,initial-scale=1'>" | |
| 927 | + "<title>disks</title><style>", stdout); | |
| 928 | + | |
| 929 | + fputs( | |
| 930 | +":root{color-scheme:dark light;" | |
| 931 | + "--bg:#0b0b0e;--surface:#141419;--surface2:#1c1c22;--text:#f5f5f7;" | |
| 932 | + "--muted:#8e8e96;--line:rgba(255,255,255,.10);--accent:#0a84ff;" | |
| 933 | + "--ok:#30d158;--warn:#ffd60a;--danger:#ff453a;" | |
| 934 | + "--mono:ui-monospace,SFMono-Regular,Menlo,monospace}" | |
| 935 | +"html[data-theme=light]{--bg:#f2f2f6;--surface:#ffffff;--surface2:#f0f0f4;" | |
| 936 | + "--text:#1c1c1e;--muted:#6b6b73;--line:rgba(0,0,0,.10)}" | |
| 937 | +"*{box-sizing:border-box}" | |
| 938 | +"body{margin:0;padding:16px;background:var(--bg);color:var(--text);" | |
| 939 | + "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;" | |
| 940 | + "font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}" | |
| 941 | +".wrap{max-width:1120px;margin:0 auto;min-width:0}" | |
| 942 | +".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" | |
| 943 | +".title{font-size:20px;font-weight:700;margin:0}" | |
| 944 | +".sub{color:var(--muted);font-size:12px;font-family:var(--mono);" | |
| 945 | + "overflow-wrap:anywhere}" | |
| 946 | +".spacer{flex:1}" | |
| 947 | +".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;" | |
| 948 | + "background:var(--surface2);color:var(--muted);border:1px solid var(--line);" | |
| 949 | + "white-space:nowrap}" | |
| 950 | +".pill.live{color:var(--ok);border-color:rgba(48,209,88,.4)}" | |
| 951 | +".pill.warn{color:var(--warn);border-color:rgba(255,214,10,.4)}" | |
| 952 | +".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;" | |
| 953 | + "padding:16px;margin-bottom:14px;min-width:0}" | |
| 954 | +".card h2{margin:0 0 12px;font-size:12px;letter-spacing:.06em;" | |
| 955 | + "text-transform:uppercase;color:var(--muted);font-weight:600}" | |
| 956 | +".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(132px,1fr));gap:10px}" | |
| 957 | +".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" | |
| 958 | + "padding:10px 12px;min-width:0}" | |
| 959 | +".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}" | |
| 960 | +".kpi .v{font-size:19px;font-weight:700;font-family:var(--mono);margin-top:2px;" | |
| 961 | + "overflow:hidden;text-overflow:ellipsis;white-space:nowrap}" | |
| 962 | +"button{background:var(--accent);color:#fff;border:0;border-radius:999px;" | |
| 963 | + "padding:6px 13px;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" | |
| 964 | +"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" | |
| 965 | +"button:active{transform:scale(.98)}" | |
| 966 | +".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" | |
| 967 | +".seg{display:inline-flex;gap:4px;background:var(--surface2);" | |
| 968 | + "border:1px solid var(--line);border-radius:999px;padding:3px}" | |
| 969 | +".seg button{background:transparent;color:var(--muted);border:0;padding:4px 11px;font-size:12px}" | |
| 970 | +".seg button.on{background:var(--accent);color:#fff}" | |
| 971 | +".mnt{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" | |
| 972 | + "padding:10px 12px;margin-bottom:8px;min-width:0}" | |
| 973 | +".mnt .h{display:flex;gap:8px;align-items:baseline;flex-wrap:wrap}" | |
| 974 | +".mnt .mp{font-family:var(--mono);font-weight:700;font-size:13px;" | |
| 975 | + "overflow-wrap:anywhere;min-width:0}" | |
| 976 | +".mnt .meta{color:var(--muted);font-size:11px;font-family:var(--mono);" | |
| 977 | + "overflow-wrap:anywhere;min-width:0}" | |
| 978 | +".bar{height:8px;border-radius:4px;background:rgba(255,255,255,.10);" | |
| 979 | + "overflow:hidden;margin:7px 0 5px}" | |
| 980 | +".bar .fill{height:100%;border-radius:4px;background:var(--ok);transition:width .35s}" | |
| 981 | +".bar .fill.warn{background:var(--warn)}" | |
| 982 | +".bar .fill.danger{background:var(--danger)}" | |
| 983 | +".nums{display:flex;justify-content:space-between;gap:8px;font-size:11px;" | |
| 984 | + "font-family:var(--mono);color:var(--muted);flex-wrap:wrap}" | |
| 985 | +".tblwrap{overflow-x:auto;-webkit-overflow-scrolling:touch}" | |
| 986 | +"table{width:100%;border-collapse:collapse;font-size:13px}" | |
| 987 | +"th,td{text-align:left;padding:7px 8px;border-bottom:1px solid var(--line)}" | |
| 988 | +"th{font-size:11px;text-transform:uppercase;letter-spacing:.05em;" | |
| 989 | + "color:var(--muted);font-weight:600;white-space:nowrap}" | |
| 990 | +"td.num,th.num{text-align:right;font-family:var(--mono);white-space:nowrap}" | |
| 991 | +"td.nm{overflow-wrap:anywhere}" | |
| 992 | +".muted{color:var(--muted)}" | |
| 993 | +".hide{display:none}" | |
| 994 | +"@media(max-width:560px){body{padding:12px}.card{padding:12px}" | |
| 995 | + "th.hide-sm,td.hide-sm{display:none}.kpi .v{font-size:17px}}", | |
| 996 | + stdout); | |
| 997 | + | |
| 998 | + fputs("</style></head><body><div class='wrap'>", stdout); | |
| 999 | + | |
| 1000 | + fputs("<div class='top'>" | |
| 1001 | + "<h1 class='title'>disks</h1>" | |
| 1002 | + "<span class='pill' id='pPlatform'>—</span>" | |
| 1003 | + "<span class='pill' id='pState'>loading</span>" | |
| 1004 | + "<span class='spacer'></span>" | |
| 1005 | + "<div class='seg' id='segRate'>" | |
| 1006 | + "<button type='button' data-ms='0' class='on'>Paused</button>" | |
| 1007 | + "<button type='button' data-ms='5000'>5s</button>" | |
| 1008 | + "<button type='button' data-ms='15000'>15s</button>" | |
| 1009 | + "</div>" | |
| 1010 | + "<button type='button' class='ghost' id='btnRefresh'>Refresh</button>" | |
| 1011 | + "</div>", stdout); | |
| 1012 | + | |
| 1013 | + /* summary */ | |
| 1014 | + fputs("<div class='card'><h2>Storage summary</h2>" | |
| 1015 | + "<div class='grid'>" | |
| 1016 | + "<div class='kpi'><div class='k'>filesystems</div><div class='v' id='kCount'>—</div></div>" | |
| 1017 | + "<div class='kpi'><div class='k'>total capacity</div><div class='v' id='kTotal'>—</div></div>" | |
| 1018 | + "<div class='kpi'><div class='k'>used</div><div class='v' id='kUsed'>—</div></div>" | |
| 1019 | + "<div class='kpi'><div class='k'>free</div><div class='v' id='kFree'>—</div></div>" | |
| 1020 | + "<div class='kpi'><div class='k'>most full</div><div class='v' id='kFull'>—</div></div>" | |
| 1021 | + "</div>" | |
| 1022 | + "<div class='sub' id='nodeLine' style='margin-top:10px'></div></div>", stdout); | |
| 1023 | + | |
| 1024 | + /* mounts */ | |
| 1025 | + fputs("<div class='card'><h2>Mounted filesystems</h2>" | |
| 1026 | + "<div id='mounts'></div>" | |
| 1027 | + "<div id='mountEmpty' class='muted hide'>No local filesystems reported.</div></div>", stdout); | |
| 1028 | + | |
| 1029 | + /* dirs */ | |
| 1030 | + fputs("<div class='card'><h2>Folder breakdown</h2>" | |
| 1031 | + "<div class='row' style='margin-bottom:12px'>" | |
| 1032 | + "<div class='seg' id='segRoot'>" | |
| 1033 | + "<button type='button' data-root='workspace' class='on'>/workspace</button>" | |
| 1034 | + "<button type='button' data-root='home'>HOME</button>" | |
| 1035 | + "</div>" | |
| 1036 | + "<span class='sub' id='dirNote'></span></div>" | |
| 1037 | + "<div class='tblwrap'><table><thead><tr>" | |
| 1038 | + "<th>Name</th><th class='num'>Size</th><th class='num'>Share</th>" | |
| 1039 | + "<th class='num hide-sm'>Type</th>" | |
| 1040 | + "</tr></thead><tbody id='rows'></tbody></table></div>" | |
| 1041 | + "<div id='dirEmpty' class='muted hide'>Nothing to show for this root.</div></div>", stdout); | |
| 1042 | + | |
| 1043 | + fputs("<div class='card'><h2>About this plugin</h2>" | |
| 1044 | + "<p class='muted' style='margin:0 0 8px'>Local node only. Reads " | |
| 1045 | + "<code>/proc/mounts</code> and <code>statvfs</code> on Linux, " | |
| 1046 | + "<code>getmntinfo</code> on macOS and <code>GetLogicalDriveStringsA</code> " | |
| 1047 | + "on Windows. Makes zero outbound network requests.</p>" | |
| 1048 | + "<p class='muted' style='margin:0'>Folder sizes are a bounded walk of one " | |
| 1049 | + "of two allowlisted roots; symlinks are never followed, depth is capped and " | |
| 1050 | + "the walk stops after a fixed number of entries.</p></div>", stdout); | |
| 1051 | + | |
| 1052 | + if (!embed) { | |
| 1053 | + fputs("<div class='sub' style='margin-bottom:14px'>" | |
| 1054 | + "Opened directly from the node API.</div>", stdout); | |
| 1055 | + } | |
| 1056 | + | |
| 1057 | + fputs("<script>\n(function(){\n", stdout); | |
| 1058 | + | |
| 1059 | + fputs( | |
| 1060 | +" var q = new URLSearchParams(location.search);\n" | |
| 1061 | +" var HUB = q.get('plugin') || '';\n" | |
| 1062 | +" var node = q.get('node') || '';\n" | |
| 1063 | +" var sid = q.get('id') || '';\n" | |
| 1064 | +" var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" | |
| 1065 | +" localStorage.getItem('bot_active_pwd') || '';\n" | |
| 1066 | +" var RATE = 0, TIMER = null, BUSY = false, ROOT = 'workspace';\n" | |
| 1067 | +"\n" | |
| 1068 | +" /* Two routes, and getting this wrong is the classic plugin bug:\n" | |
| 1069 | +" page served through the hub -> call the hub proxy back\n" | |
| 1070 | +" page opened directly on node -> the plugin IS the route */\n" | |
| 1071 | +" function base(action){\n" | |
| 1072 | +" if (HUB) return '/plugins?plugin=' + encodeURIComponent(HUB) + '&action=' + encodeURIComponent(action);\n" | |
| 1073 | +" return '/" PLUGIN_ID "?action=' + encodeURIComponent(action);\n" | |
| 1074 | +" }\n" | |
| 1075 | +" function withCtx(u){\n" | |
| 1076 | +" if (node) u += '&node=' + encodeURIComponent(node);\n" | |
| 1077 | +" if (sid) u += '&id=' + encodeURIComponent(sid);\n" | |
| 1078 | +" if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n" | |
| 1079 | +" return u;\n" | |
| 1080 | +" }\n" | |
| 1081 | +" function hdr(){ return pwd ? {'X-Bot-Password': pwd} : {}; }\n" | |
| 1082 | +" function $(id){ return document.getElementById(id); }\n" | |
| 1083 | +" function txt(id, v){ var e = $(id); if (e) e.textContent = (v === undefined || v === null) ? '' : v; }\n" | |
| 1084 | +" function bytes(n){\n" | |
| 1085 | +" if (n === null || n === undefined) return '\\u2014';\n" | |
| 1086 | +" var u = ['B','KB','MB','GB','TB','PB'], i = 0, v = n;\n" | |
| 1087 | +" while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }\n" | |
| 1088 | +" return (i === 0 ? v.toFixed(0) : v.toFixed(v >= 100 ? 0 : 1)) + ' ' + u[i];\n" | |
| 1089 | +" }\n" | |
| 1090 | +" function cls(p){ return p >= 90 ? 'danger' : (p >= 75 ? 'warn' : ''); }\n" | |
| 1091 | +" function el(tag, c, t){\n" | |
| 1092 | +" var e = document.createElement(tag);\n" | |
| 1093 | +" if (c) e.className = c;\n" | |
| 1094 | +" if (t !== undefined) e.textContent = t;\n" | |
| 1095 | +" return e;\n" | |
| 1096 | +" }\n" | |
| 1097 | +"\n" | |
| 1098 | +" function renderMounts(m){\n" | |
| 1099 | +" var box = $('mounts');\n" | |
| 1100 | +" box.textContent = '';\n" | |
| 1101 | +" var total = 0, used = 0, free = 0, worst = null;\n" | |
| 1102 | +" (m.mounts || []).forEach(function(x){\n" | |
| 1103 | +" total += x.total_bytes; used += x.used_bytes; free += x.free_bytes;\n" | |
| 1104 | +" if (!worst || x.pct > worst.pct) worst = x;\n" | |
| 1105 | +" var card = el('div','mnt');\n" | |
| 1106 | +" var h = el('div','h');\n" | |
| 1107 | +" h.appendChild(el('span','mp', x.mount));\n" | |
| 1108 | +" h.appendChild(el('span','meta', x.device + ' \\u00b7 ' + x.fstype));\n" | |
| 1109 | +" h.appendChild(el('span','meta', x.pct.toFixed(0) + '%'));\n" | |
| 1110 | +" card.appendChild(h);\n" | |
| 1111 | +" var bar = el('div','bar');\n" | |
| 1112 | +" var fill = el('div','fill ' + cls(x.pct));\n" | |
| 1113 | +" fill.style.width = Math.max(0, Math.min(100, x.pct)) + '%';\n" | |
| 1114 | +" bar.appendChild(fill);\n" | |
| 1115 | +" card.appendChild(bar);\n" | |
| 1116 | +" var nums = el('div','nums');\n" | |
| 1117 | +" nums.appendChild(el('span', null, bytes(x.used_bytes) + ' used'));\n" | |
| 1118 | +" nums.appendChild(el('span', null, bytes(x.avail_bytes) + ' free'));\n" | |
| 1119 | +" nums.appendChild(el('span', null, bytes(x.total_bytes) + ' total'));\n" | |
| 1120 | +" nums.appendChild(el('span', null,\n" | |
| 1121 | +" x.has_inodes ? ('inodes ' + x.inodes_pct.toFixed(0) + '%') : 'inodes n/a'));\n" | |
| 1122 | +" card.appendChild(nums);\n" | |
| 1123 | +" box.appendChild(card);\n" | |
| 1124 | +" });\n" | |
| 1125 | +" if ((m.mounts || []).length) $('mountEmpty').classList.add('hide');\n" | |
| 1126 | +" else $('mountEmpty').classList.remove('hide');\n" | |
| 1127 | +" txt('kCount', m.count);\n" | |
| 1128 | +" txt('kTotal', bytes(total));\n" | |
| 1129 | +" txt('kUsed', bytes(used));\n" | |
| 1130 | +" txt('kFree', bytes(free));\n" | |
| 1131 | +" txt('kFull', worst ? (worst.mount + ' ' + worst.pct.toFixed(0) + '%') : '\\u2014');\n" | |
| 1132 | +" }\n" | |
| 1133 | +"\n" | |
| 1134 | +" function renderDirs(d, ok){\n" | |
| 1135 | +" var body = $('rows');\n" | |
| 1136 | +" body.textContent = '';\n" | |
| 1137 | +" if (!ok){\n" | |
| 1138 | +" $('dirEmpty').classList.remove('hide');\n" | |
| 1139 | +" txt('dirNote', d && d.error ? ('unavailable: ' + d.error) : 'unavailable');\n" | |
| 1140 | +" return;\n" | |
| 1141 | +" }\n" | |
| 1142 | +" var entries = d.entries || [];\n" | |
| 1143 | +" entries.forEach(function(e){\n" | |
| 1144 | +" var tr = el('tr');\n" | |
| 1145 | +" tr.appendChild(el('td','nm', e.name));\n" | |
| 1146 | +" tr.appendChild(el('td','num', bytes(e.bytes)));\n" | |
| 1147 | +" tr.appendChild(el('td','num', e.pct.toFixed(1) + '%'));\n" | |
| 1148 | +" tr.appendChild(el('td','num hide-sm', e.is_dir ? 'dir' : 'file'));\n" | |
| 1149 | +" body.appendChild(tr);\n" | |
| 1150 | +" });\n" | |
| 1151 | +" if (entries.length) $('dirEmpty').classList.add('hide');\n" | |
| 1152 | +" else $('dirEmpty').classList.remove('hide');\n" | |
| 1153 | +" txt('dirNote', d.root + ' \\u00b7 ' + bytes(d.root_used_bytes) + ' used of ' +\n" | |
| 1154 | +" bytes(d.root_total_bytes) + ' \\u00b7 ' + entries.length + ' entries \\u00b7 ' +\n" | |
| 1155 | +" d.scan_ms + ' ms' + (d.truncated ? ' \\u00b7 truncated' : ''));\n" | |
| 1156 | +" }\n" | |
| 1157 | +"\n" | |
| 1158 | +" function loadDirs(){\n" | |
| 1159 | +" var u = withCtx(base('dirs')) + '&root=' + encodeURIComponent(ROOT);\n" | |
| 1160 | +" return fetch(u, { headers: hdr(), cache: 'no-store' })\n" | |
| 1161 | +" .then(function(r){ return r.json(); })\n" | |
| 1162 | +" .then(function(d){ renderDirs(d, d && d.ok === true); })\n" | |
| 1163 | +" .catch(function(e){ renderDirs({error: String(e)}, false); });\n" | |
| 1164 | +" }\n" | |
| 1165 | +"\n" | |
| 1166 | +" function poll(){\n" | |
| 1167 | +" if (BUSY) return;\n" | |
| 1168 | +" BUSY = true;\n" | |
| 1169 | +" fetch(withCtx(base('mounts')), { headers: hdr(), cache: 'no-store' })\n" | |
| 1170 | +" .then(function(r){ return r.json(); })\n" | |
| 1171 | +" .then(function(d){\n" | |
| 1172 | +" if (!d || d.ok === false){ txt('pState', 'error'); return; }\n" | |
| 1173 | +" txt('pPlatform', d.platform);\n" | |
| 1174 | +" txt('nodeLine', 'plugin ' + d.plugin + ' v' + d.version +\n" | |
| 1175 | +" ' \\u00b7 pid ' + d.pid + ' \\u00b7 ' + d.utc +\n" | |
| 1176 | +" ' \\u00b7 zero outbound network');\n" | |
| 1177 | +" renderMounts(d);\n" | |
| 1178 | +" })\n" | |
| 1179 | +" .catch(function(){ txt('pState', 'error'); })\n" | |
| 1180 | +" .then(function(){ BUSY = false; });\n" | |
| 1181 | +" loadDirs();\n" | |
| 1182 | +" }\n" | |
| 1183 | +"\n" | |
| 1184 | +" function schedule(){\n" | |
| 1185 | +" if (TIMER) { clearInterval(TIMER); TIMER = null; }\n" | |
| 1186 | +" var st = $('pState');\n" | |
| 1187 | +" if (RATE > 0){\n" | |
| 1188 | +" TIMER = setInterval(poll, RATE);\n" | |
| 1189 | +" st.textContent = 'live ' + (RATE / 1000) + 's';\n" | |
| 1190 | +" st.className = 'pill live';\n" | |
| 1191 | +" } else {\n" | |
| 1192 | +" st.textContent = 'paused';\n" | |
| 1193 | +" st.className = 'pill';\n" | |
| 1194 | +" }\n" | |
| 1195 | +" }\n" | |
| 1196 | +"\n" | |
| 1197 | +" Array.prototype.forEach.call(document.querySelectorAll('#segRate button'), function(b){\n" | |
| 1198 | +" b.addEventListener('click', function(){\n" | |
| 1199 | +" Array.prototype.forEach.call(document.querySelectorAll('#segRate button'),\n" | |
| 1200 | +" function(x){ x.classList.remove('on'); });\n" | |
| 1201 | +" b.classList.add('on');\n" | |
| 1202 | +" RATE = parseInt(b.getAttribute('data-ms'), 10) || 0;\n" | |
| 1203 | +" schedule();\n" | |
| 1204 | +" if (RATE > 0) poll();\n" | |
| 1205 | +" });\n" | |
| 1206 | +" });\n" | |
| 1207 | +"\n" | |
| 1208 | +" Array.prototype.forEach.call(document.querySelectorAll('#segRoot button'), function(b){\n" | |
| 1209 | +" b.addEventListener('click', function(){\n" | |
| 1210 | +" Array.prototype.forEach.call(document.querySelectorAll('#segRoot button'),\n" | |
| 1211 | +" function(x){ x.classList.remove('on'); });\n" | |
| 1212 | +" b.classList.add('on');\n" | |
| 1213 | +" ROOT = b.getAttribute('data-root') || 'workspace';\n" | |
| 1214 | +" loadDirs();\n" | |
| 1215 | +" });\n" | |
| 1216 | +" });\n" | |
| 1217 | +"\n" | |
| 1218 | +" $('btnRefresh').addEventListener('click', poll);\n" | |
| 1219 | +"\n" | |
| 1220 | +" /* follow the hub's theme when it sets one */\n" | |
| 1221 | +" try {\n" | |
| 1222 | +" var t = localStorage.getItem('bot_theme');\n" | |
| 1223 | +" if (t === 'light' || t === 'dark') document.documentElement.setAttribute('data-theme', t);\n" | |
| 1224 | +" } catch (e) {}\n" | |
| 1225 | +"\n" | |
| 1226 | +" poll();\n" | |
| 1227 | +" schedule();\n" | |
| 1228 | +"})();\n</script></body></html>\n", stdout); | |
| 1229 | + | |
| 1230 | + return 0; | |
| 1231 | +} | |
| 1232 | + | |
| 1233 | +/* ------------------------------------------------------------------ */ | |
| 1234 | +/* main */ | |
| 1235 | +/* ------------------------------------------------------------------ */ | |
| 1236 | + | |
| 1237 | +int main(int argc, char **argv) | |
| 1238 | +{ | |
| 1239 | + const char *qs; | |
| 1240 | + int embed; | |
| 1241 | + | |
| 1242 | + if (argc > 1) { | |
| 1243 | + if (strcmp(argv[1], "--meta") == 0) return mode_meta(); | |
| 1244 | + if (strcmp(argv[1], "--version") == 0) { | |
| 1245 | + puts(PLUGIN_VER); | |
| 1246 | + return 0; | |
| 1247 | + } | |
| 1248 | + if (strcmp(argv[1], "--help") == 0) { | |
| 1249 | + puts("usage: " PLUGIN_ID " [--meta|--version|--help]"); | |
| 1250 | + puts(""); | |
| 1251 | + puts("Runs as a CGI-style program under scorpiox-server."); | |
| 1252 | + puts(" --meta print discovery metadata JSON and exit"); | |
| 1253 | + puts(" --version print the plugin version and exit"); | |
| 1254 | + puts(""); | |
| 1255 | + puts("Query string actions:"); | |
| 1256 | + puts(" (none) or action=mounts mounted filesystems with usage"); | |
| 1257 | + puts(" action=dirs&root=workspace|home bounded 1-level folder sizes"); | |
| 1258 | + puts(" action=info plugin/platform capabilities"); | |
| 1259 | + puts(" format=json same as an action, JSON output"); | |
| 1260 | + puts(" (any other) HTML dashboard"); | |
| 1261 | + return 0; | |
| 1262 | + } | |
| 1263 | + } | |
| 1264 | + | |
| 1265 | + if (getenv("SX_PLUGIN_META")) return mode_meta(); | |
| 1266 | + | |
| 1267 | + require_node_auth(); | |
| 1268 | + | |
| 1269 | + qs = getenv("QUERY_STRING"); | |
| 1270 | + if (!qs) qs = ""; | |
| 1271 | + | |
| 1272 | + if (strstr(qs, "action=") || strstr(qs, "format=json")) | |
| 1273 | + return mode_json(qs); | |
| 1274 | + | |
| 1275 | + embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); | |
| 1276 | + return mode_html(embed); | |
| 1277 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..725a458 | ||
| --- /dev/null | ||
| +++ b/tests/e2e.py | ||
| @@ -0,0 +1,137 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""tests/e2e.py - viewport checks for the plugin_disks dashboard. | |
| 3 | + | |
| 4 | +Serves the plugin through a tiny CGI-ish HTTP shim on a loopback port, opens it | |
| 5 | +with Playwright at 1440 / 1024 / 390 CSS pixels, and asserts there is no | |
| 6 | +horizontal overflow, no console error, and that the mount table and the folder | |
| 7 | +breakdown both rendered real numbers. Skips cleanly (exit 0) when Playwright is | |
| 8 | +not installed, so `make test` stays offline-only. | |
| 9 | + | |
| 10 | + python3 tests/e2e.py # run if Playwright is available | |
| 11 | + python3 tests/e2e.py --strict # exit 2 when Playwright is missing | |
| 12 | +""" | |
| 13 | + | |
| 14 | +import argparse | |
| 15 | +import http.server | |
| 16 | +import os | |
| 17 | +import subprocess | |
| 18 | +import socketserver | |
| 19 | +import sys | |
| 20 | +import threading | |
| 21 | + | |
| 22 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| 23 | +BIN = os.path.join(ROOT, "plugin_disks") | |
| 24 | +VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] | |
| 25 | + | |
| 26 | + | |
| 27 | +class Handler(http.server.BaseHTTPRequestHandler): | |
| 28 | + def do_GET(self): # noqa: N802 | |
| 29 | + from urllib.parse import urlparse | |
| 30 | + u = urlparse(self.path) | |
| 31 | + env = dict(os.environ) | |
| 32 | + env["QUERY_STRING"] = u.query | |
| 33 | + env["REQUEST_METHOD"] = "GET" | |
| 34 | + env.pop("BOT_PASSWORD", None) | |
| 35 | + out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout | |
| 36 | + sep = out.find(b"\r\n\r\n") | |
| 37 | + headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" | |
| 38 | + body = out[sep + 4:] if sep >= 0 else out | |
| 39 | + ctype = "text/html; charset=utf-8" | |
| 40 | + for line in headers.splitlines(): | |
| 41 | + if line.lower().startswith("content-type:"): | |
| 42 | + ctype = line.split(":", 1)[1].strip() | |
| 43 | + self.send_response(200) | |
| 44 | + self.send_header("Content-Type", ctype) | |
| 45 | + self.send_header("Cache-Control", "no-store") | |
| 46 | + # no Content-Length from the plugin; the shim sets its own framing | |
| 47 | + self.send_header("Content-Length", str(len(body))) | |
| 48 | + self.end_headers() | |
| 49 | + self.wfile.write(body) | |
| 50 | + | |
| 51 | + def log_message(self, *_a): | |
| 52 | + pass | |
| 53 | + | |
| 54 | + | |
| 55 | +def main(): | |
| 56 | + ap = argparse.ArgumentParser() | |
| 57 | + ap.add_argument("--strict", action="store_true") | |
| 58 | + args = ap.parse_args() | |
| 59 | + | |
| 60 | + if not os.path.exists(BIN): | |
| 61 | + print("plugin_disks is not built; run make first", file=sys.stderr) | |
| 62 | + return 1 | |
| 63 | + | |
| 64 | + try: | |
| 65 | + from playwright.sync_api import sync_playwright | |
| 66 | + except Exception: | |
| 67 | + msg = "playwright not installed - skipping viewport e2e" | |
| 68 | + if args.strict: | |
| 69 | + print(msg, file=sys.stderr) | |
| 70 | + return 2 | |
| 71 | + print(msg) | |
| 72 | + return 0 | |
| 73 | + | |
| 74 | + with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv: | |
| 75 | + port = srv.server_address[1] | |
| 76 | + threading.Thread(target=srv.serve_forever, daemon=True).start() | |
| 77 | + url = "http://127.0.0.1:%d/plugin_disks" % port | |
| 78 | + | |
| 79 | + failures = [] | |
| 80 | + with sync_playwright() as p: | |
| 81 | + browser = p.chromium.launch() | |
| 82 | + for (w, h) in VIEWPORTS: | |
| 83 | + page = browser.new_page(viewport={"width": w, "height": h}) | |
| 84 | + errors = [] | |
| 85 | + page.on("console", lambda m: errors.append(m.text) | |
| 86 | + if m.type == "error" else None) | |
| 87 | + page.goto(url, wait_until="load") | |
| 88 | + page.wait_for_timeout(3000) | |
| 89 | + | |
| 90 | + sw = page.evaluate("document.documentElement.scrollWidth") | |
| 91 | + iw = page.evaluate("window.innerWidth") | |
| 92 | + if sw > iw + 1: | |
| 93 | + failures.append("%dx%d horizontal overflow %d > %d" % (w, h, sw, iw)) | |
| 94 | + | |
| 95 | + count = page.evaluate( | |
| 96 | + "document.getElementById('kCount').textContent") | |
| 97 | + full = page.evaluate( | |
| 98 | + "document.getElementById('kFull').textContent") | |
| 99 | + mounts = page.evaluate( | |
| 100 | + "document.querySelectorAll('#mounts .mnt').length") | |
| 101 | + rows = page.evaluate( | |
| 102 | + "document.querySelectorAll('#rows tr').length") | |
| 103 | + note = page.evaluate( | |
| 104 | + "document.getElementById('dirNote').textContent") | |
| 105 | + | |
| 106 | + if not (count or "").strip().isdigit(): | |
| 107 | + failures.append("%dx%d mount count KPI did not render (%r)" | |
| 108 | + % (w, h, count)) | |
| 109 | + if mounts < 1: | |
| 110 | + failures.append("%dx%d no mount cards rendered" % (w, h)) | |
| 111 | + if "%" not in (full or ""): | |
| 112 | + failures.append("%dx%d fullness KPI did not render (%r)" | |
| 113 | + % (w, h, full)) | |
| 114 | + if not (note or "").strip(): | |
| 115 | + failures.append("%dx%d folder note empty (%r)" % (w, h, note)) | |
| 116 | + | |
| 117 | + real = [e for e in errors if "favicon" not in e.lower()] | |
| 118 | + if real: | |
| 119 | + failures.append("%dx%d console errors: %s" % (w, h, real[:3])) | |
| 120 | + | |
| 121 | + print(" %dx%d scrollWidth=%d innerWidth=%d mounts=%d rows=%d count=%s full=%s" | |
| 122 | + % (w, h, sw, iw, mounts, rows, (count or "").strip(), | |
| 123 | + (full or "").strip())) | |
| 124 | + page.close() | |
| 125 | + browser.close() | |
| 126 | + srv.shutdown() | |
| 127 | + | |
| 128 | + if failures: | |
| 129 | + for f in failures: | |
| 130 | + print(" FAIL " + f) | |
| 131 | + return 1 | |
| 132 | + print(" viewport e2e passed at %d sizes" % len(VIEWPORTS)) | |
| 133 | + return 0 | |
| 134 | + | |
| 135 | + | |
| 136 | +if __name__ == "__main__": | |
| 137 | + sys.exit(main()) |
| 1 | 1 | new file mode 100755 |
| index 0000000..65374be | ||
| --- /dev/null | ||
| +++ b/tests/run.sh | ||
| @@ -0,0 +1,417 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/run.sh - offline checks for plugin_disks across all 3 modes. | |
| 3 | +# | |
| 4 | +# Runs against ./plugin_disks (native build) on the live machine, so the mount | |
| 5 | +# assertions use this node's real /proc/mounts (or getmntinfo / Win32 drive | |
| 6 | +# list). If a musl static build or a Windows PE (plugin_disks.exe) is present | |
| 7 | +# they are checked too. The whole git history is finally audited for secrets | |
| 8 | +# and LAN IPs. | |
| 9 | +# | |
| 10 | +# Exit code 0 = everything passed. | |
| 11 | + | |
| 12 | +set -u | |
| 13 | + | |
| 14 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | |
| 15 | +cd "$ROOT" || exit 1 | |
| 16 | + | |
| 17 | +BIN=./plugin_disks | |
| 18 | +PASS=0 | |
| 19 | +FAIL=0 | |
| 20 | + | |
| 21 | +if [ -t 1 ]; then | |
| 22 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | |
| 23 | +else | |
| 24 | + C_OK=; C_BAD=; C_B=; C_0= | |
| 25 | +fi | |
| 26 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | |
| 27 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | |
| 28 | + | |
| 29 | +check() { # check <desc> <expected-substring> <actual> | |
| 30 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | |
| 31 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)" | |
| 32 | + fi | |
| 33 | +} | |
| 34 | + | |
| 35 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | |
| 36 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | |
| 37 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | |
| 38 | + fi | |
| 39 | +} | |
| 40 | + | |
| 41 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | |
| 42 | + | |
| 43 | +body() { printf '%s' "$1" | sed '1,/^\r$/d'; } | |
| 44 | + | |
| 45 | +TMP=$(mktemp -d 2>/dev/null || echo /tmp/disks_tests_$$) | |
| 46 | +mkdir -p "$TMP" 2>/dev/null || true | |
| 47 | + | |
| 48 | +# ---------------------------------------------------------------- build | |
| 49 | +section "build" | |
| 50 | +if [ ! -x "$BIN" ]; then | |
| 51 | + echo " building native binary..." | |
| 52 | + cc -O2 -std=c99 -Wall -Wextra -o "$BIN" src/plugin_disks.c || { echo " build failed"; exit 1; } | |
| 53 | +fi | |
| 54 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | |
| 55 | + | |
| 56 | +# ---------------------------------------------------------------- meta mode | |
| 57 | +section "mode 1 --meta (must work without auth - discovery)" | |
| 58 | +META=$("$BIN" --meta) | |
| 59 | +check "meta emits name disks" '"name":"disks"' "$META" | |
| 60 | +check "meta emits desc Local storage" '"desc":"Local storage"' "$META" | |
| 61 | +METAENV=$(SX_PLUGIN_META=1 "$BIN") | |
| 62 | +check "SX_PLUGIN_META=1 yields same meta" '"name":"disks"' "$METAENV" | |
| 63 | +LEN=$(printf '%s' "$META" | wc -c | tr -d ' ') | |
| 64 | +[ "$LEN" -lt 60 ] && pass "meta payload is compact ($LEN bytes)" || fail "meta payload too long ($LEN)" | |
| 65 | +printf '%s' "$META" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | |
| 66 | + && pass "meta is valid JSON" || fail "meta is not valid JSON" | |
| 67 | +DESC=$(printf '%s' "$META" | sed 's/.*"desc":"\([^"]*\)".*/\1/') | |
| 68 | +[ ${#DESC} -le 15 ] && pass "desc length ${#DESC} <= 15 chars" || fail "desc too long (${#DESC})" | |
| 69 | +NAME=$(printf '%s' "$META" | sed 's/.*"name":"\([^"]*\)".*/\1/') | |
| 70 | +[ "$(printf '%s' "$NAME" | wc -w | tr -d ' ')" -le 1 ] && pass "name is a single word" || fail "name has spaces" | |
| 71 | +check "--version prints version" '1.0.0' "$("$BIN" --version)" | |
| 72 | +check "--help is available" 'usage:' "$("$BIN" --help)" | |
| 73 | +META_AUTH=$(BOT_PASSWORD=secret "$BIN" --meta) | |
| 74 | +check "meta still works when BOT_PASSWORD is set" '"name":"disks"' "$META_AUTH" | |
| 75 | + | |
| 76 | +# ---------------------------------------------------------------- auth | |
| 77 | +section "node auth" | |
| 78 | +AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=mounts' "$BIN") | |
| 79 | +check "no credentials -> 401" 'Status: 401' "$AUTHNONE" | |
| 80 | +check "401 body is json" 'invalid node password' "$AUTHNONE" | |
| 81 | +AUTHH=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING='action=mounts' "$BIN") | |
| 82 | +check "X-Bot-Password accepted" '"ok":true' "$(body "$AUTHH")" | |
| 83 | +AUTHB=$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=mounts' "$BIN") | |
| 84 | +check "Bearer token accepted" '"ok":true' "$(body "$AUTHB")" | |
| 85 | +AUTHQ=$(BOT_PASSWORD=testpw QUERY_STRING='action=mounts&pwd=testpw' "$BIN") | |
| 86 | +check "?pwd= accepted" '"ok":true' "$(body "$AUTHQ")" | |
| 87 | +AUTHBAD=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=mounts' "$BIN") | |
| 88 | +check "wrong password -> 401" 'Status: 401' "$AUTHBAD" | |
| 89 | +HTMLAUTH=$(BOT_PASSWORD=testpw QUERY_STRING='' "$BIN") | |
| 90 | +check "html mode is also gated" 'Status: 401' "$HTMLAUTH" | |
| 91 | + | |
| 92 | +# ---------------------------------------------------------------- mounts | |
| 93 | +section "mode 2 action=mounts" | |
| 94 | +MF="$TMP/mounts.json" | |
| 95 | +MOUNTS=$(body "$(QUERY_STRING='action=mounts' "$BIN")") | |
| 96 | +printf '%s' "$MOUNTS" > "$MF" | |
| 97 | +check "mounts ok:true" '"ok":true' "$MOUNTS" | |
| 98 | +check "mounts names the plugin" '"plugin":"plugin_disks"' "$MOUNTS" | |
| 99 | +check "mounts declares platform" '"platform":"' "$MOUNTS" | |
| 100 | +check "mounts declares zero_network" '"zero_network":true' "$MOUNTS" | |
| 101 | +check "mounts carries a utc stamp" '"utc":"20' "$MOUNTS" | |
| 102 | +check "mounts lists an array" '"mounts":[' "$MOUNTS" | |
| 103 | +printf '%s' "$MOUNTS" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | |
| 104 | + && pass "mounts body is valid JSON" || fail "mounts body JSON invalid" | |
| 105 | + | |
| 106 | +python3 - "$MF" <<'PY' && pass "mount rows are well formed" || fail "mount rows malformed" | |
| 107 | +import json, sys | |
| 108 | +d = json.load(open(sys.argv[1])) | |
| 109 | +assert d["count"] == len(d["mounts"]) | |
| 110 | +for m in d["mounts"]: | |
| 111 | + assert isinstance(m["device"], str) | |
| 112 | + assert isinstance(m["fstype"], str) | |
| 113 | + assert isinstance(m["mount"], str) and m["mount"] | |
| 114 | + for k in ("total_bytes", "used_bytes", "free_bytes", "avail_bytes"): | |
| 115 | + assert isinstance(m[k], int) and m[k] >= 0, (k, m[k]) | |
| 116 | + assert 0.0 <= m["pct"] <= 100.0 | |
| 117 | +PY | |
| 118 | + | |
| 119 | +python3 - "$MF" <<'PY' && pass "no pseudo filesystems leaked into the table" || fail "pseudo fs present" | |
| 120 | +import json, sys | |
| 121 | +d = json.load(open(sys.argv[1])) | |
| 122 | +banned = {"proc","sysfs","cgroup","cgroup2","devpts","devtmpfs","debugfs", | |
| 123 | + "tracefs","securityfs","pstore","bpf","mqueue","configfs"} | |
| 124 | +got = {m["fstype"] for m in d["mounts"]} & banned | |
| 125 | +assert not got, got | |
| 126 | +PY | |
| 127 | + | |
| 128 | +python3 - "$MF" <<'PY' && pass "no kernel mountpoints leaked into the table" || fail "kernel mountpoint present" | |
| 129 | +import json, sys | |
| 130 | +d = json.load(open(sys.argv[1])) | |
| 131 | +bad = [m["mount"] for m in d["mounts"] | |
| 132 | + if m["mount"].startswith(("/sys", "/proc", "/dev"))] | |
| 133 | +assert not bad, bad | |
| 134 | +PY | |
| 135 | + | |
| 136 | +python3 - "$MF" <<'PY' && pass "mountpoints are unique (no double counting)" || fail "duplicate mountpoint" | |
| 137 | +import json, sys | |
| 138 | +d = json.load(open(sys.argv[1])) | |
| 139 | +mp = [m["mount"] for m in d["mounts"]] | |
| 140 | +assert len(mp) == len(set(mp)), [x for x in mp if mp.count(x) > 1] | |
| 141 | +PY | |
| 142 | + | |
| 143 | +python3 - "$MF" <<'PY' && pass "mounts are ordered largest first" || fail "mount order wrong" | |
| 144 | +import json, sys | |
| 145 | +d = json.load(open(sys.argv[1])) | |
| 146 | +t = [m["total_bytes"] for m in d["mounts"]] | |
| 147 | +assert t == sorted(t, reverse=True), t | |
| 148 | +PY | |
| 149 | + | |
| 150 | +# The live root filesystem must always be reported on POSIX, whichever node runs it. | |
| 151 | +python3 - "$MF" <<'PY' && pass "live root mount is reported" || fail "root mount missing" | |
| 152 | +import json, sys, os | |
| 153 | +d = json.load(open(sys.argv[1])) | |
| 154 | +if os.name != "nt": | |
| 155 | + roots = [m for m in d["mounts"] if m["mount"] == "/"] | |
| 156 | + assert roots, "no / mount" | |
| 157 | + assert roots[0]["total_bytes"] > 0 | |
| 158 | +PY | |
| 159 | + | |
| 160 | +python3 - "$MF" <<'PY' && pass "used + avail never exceeds the reported total by much" || fail "usage math inconsistent" | |
| 161 | +import json, sys | |
| 162 | +d = json.load(open(sys.argv[1])) | |
| 163 | +for m in d["mounts"]: | |
| 164 | + # reserved blocks may make used+avail < total; they must never exceed it | |
| 165 | + assert m["used_bytes"] + m["avail_bytes"] <= m["total_bytes"] + 1 | |
| 166 | +PY | |
| 167 | + | |
| 168 | +python3 - "$MF" <<'PY' && pass "info/supported keys reachable via format=json" || fail "format=json alias broken" | |
| 169 | +import json, sys | |
| 170 | +PY | |
| 171 | +check "format=json aliases to mounts" '"action":"mounts"' "$(body "$(QUERY_STRING='format=json' "$BIN")")" | |
| 172 | +rm -f "$MF" | |
| 173 | + | |
| 174 | +# ---------------------------------------------------------------- dirs | |
| 175 | +section "mode 2 action=dirs - allowlist and traversal rejection" | |
| 176 | +for bad in etc /etc .. ../.. workspace/ /workspace /root /home workspace\\ $'workspace\n' '%2Fetc' ; do | |
| 177 | + R=$(body "$(QUERY_STRING="action=dirs&root=$(printf '%s' "$bad" | sed 's/ /%20/g')" "$BIN")") | |
| 178 | + if printf '%s' "$R" | grep -F -q '"ok":false'; then | |
| 179 | + pass "root rejected: $bad" | |
| 180 | + else | |
| 181 | + fail "root accepted: $bad -> $R" | |
| 182 | + fi | |
| 183 | +done | |
| 184 | +MISS=$(body "$(QUERY_STRING='action=dirs' "$BIN")") | |
| 185 | +check "missing root rejected" 'missing_root' "$MISS" | |
| 186 | +check "missing root lists the allowlist" '"allowed_roots":["workspace","home"]' "$MISS" | |
| 187 | +TRAV=$(body "$(QUERY_STRING='action=dirs&root=/etc' "$BIN")") | |
| 188 | +check "traversal rejection is explicit" 'root_not_allowed' "$TRAV" | |
| 189 | +check "traversal rejection echoes input" '"requested":"/etc"' "$TRAV" | |
| 190 | + | |
| 191 | +section "mode 2 action=dirs - real roots" | |
| 192 | +DH=$(body "$(QUERY_STRING='action=dirs&root=home' "$BIN")") | |
| 193 | +DF="$TMP/home.json" | |
| 194 | +printf '%s' "$DH" > "$DF" | |
| 195 | +if printf '%s' "$DH" | grep -F -q '"ok":true'; then | |
| 196 | + pass "home root scans on this node" | |
| 197 | + check "dirs echoes the root kind" '"root_kind":"home"' "$DH" | |
| 198 | + check "dirs labels the root" '"root_label":"$HOME"' "$DH" | |
| 199 | + check "dirs declares max depth" '"max_depth":' "$DH" | |
| 200 | + check "dirs declares the scan budget" '"max_scan_entries":' "$DH" | |
| 201 | + check "dirs reports the scan time" '"scan_ms":' "$DH" | |
| 202 | + check "dirs reports truncation state" '"truncated":' "$DH" | |
| 203 | + python3 - "$DF" <<'PY' && pass "dir rows are well formed" || fail "dir rows malformed" | |
| 204 | +import json, sys | |
| 205 | +d = json.load(open(sys.argv[1])) | |
| 206 | +assert d["count"] == len(d["entries"]) | |
| 207 | +for e in d["entries"]: | |
| 208 | + assert isinstance(e["name"], str) and e["name"] | |
| 209 | + assert isinstance(e["path"], str) and e["path"] | |
| 210 | + assert isinstance(e["bytes"], int) and e["bytes"] >= 0 | |
| 211 | + assert isinstance(e["is_dir"], bool) | |
| 212 | + assert 0.0 <= e["pct"] <= 100.0 | |
| 213 | +PY | |
| 214 | + python3 - "$DF" <<'PY' && pass "dir entries are ordered largest first" || fail "dir order wrong" | |
| 215 | +import json, sys | |
| 216 | +d = json.load(open(sys.argv[1])) | |
| 217 | +b = [e["bytes"] for e in d["entries"]] | |
| 218 | +assert b == sorted(b, reverse=True), b | |
| 219 | +PY | |
| 220 | + python3 - "$DF" <<'PY' && pass "dir scan stays inside the requested root" || fail "entry escaped the root" | |
| 221 | +import json, sys, os | |
| 222 | +d = json.load(open(sys.argv[1])) | |
| 223 | +root = d["root"].rstrip("/") + "/" | |
| 224 | +for e in d["entries"]: | |
| 225 | + assert e["path"].startswith(root), e["path"] | |
| 226 | +PY | |
| 227 | + python3 - "$DF" <<'PY' && pass "dir scan is bounded (entry count within the cap)" || fail "entry cap exceeded" | |
| 228 | +import json, sys | |
| 229 | +d = json.load(open(sys.argv[1])) | |
| 230 | +assert d["count"] <= 512, d["count"] | |
| 231 | +PY | |
| 232 | +else | |
| 233 | + pass "home root unavailable on this node (root_unavailable is a valid answer)" | |
| 234 | + check "unavailable root is not an error leak" 'root_unavailable' "$DH" | |
| 235 | +fi | |
| 236 | +rm -f "$DF" | |
| 237 | + | |
| 238 | +DW=$(body "$(QUERY_STRING='action=dirs&root=workspace' "$BIN")") | |
| 239 | +if printf '%s' "$DW" | grep -F -q '"ok":true'; then | |
| 240 | + pass "workspace root scans on this node" | |
| 241 | + check "workspace echoes its kind" '"root_kind":"workspace"' "$DW" | |
| 242 | +elif printf '%s' "$DW" | grep -F -q 'root_unavailable'; then | |
| 243 | + pass "workspace root absent on this node (reported as root_unavailable)" | |
| 244 | +else | |
| 245 | + fail "workspace root gave neither data nor root_unavailable: $DW" | |
| 246 | +fi | |
| 247 | + | |
| 248 | +# ---------------------------------------------------------------- info + unknown | |
| 249 | +section "mode 2 action=info" | |
| 250 | +INFO=$(QUERY_STRING='action=info' "$BIN") | |
| 251 | +IBODY=$(body "$INFO") | |
| 252 | +check "info ok:true" '"ok":true' "$IBODY" | |
| 253 | +check "info action info" '"action":"info"' "$IBODY" | |
| 254 | +check "info pid present" '"pid":' "$IBODY" | |
| 255 | +check "info utc present" '"utc":"20' "$IBODY" | |
| 256 | +check "info zero_network declared" '"zero_network":true' "$IBODY" | |
| 257 | +check "info allowed_roots declared" '"allowed_roots":["workspace","home"]' "$IBODY" | |
| 258 | +check "info max_depth declared" '"max_depth":8' "$IBODY" | |
| 259 | +check "info node_auth false when unset" '"node_auth":false' "$IBODY" | |
| 260 | +INFOAUTH=$(body "$(BOT_PASSWORD=pw QUERY_STRING='action=info&pwd=pw' "$BIN")") | |
| 261 | +check "info node_auth true when set" '"node_auth":true' "$INFOAUTH" | |
| 262 | +printf '%s' "$IBODY" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | |
| 263 | + && pass "info body is valid JSON" || fail "info body JSON invalid" | |
| 264 | + | |
| 265 | +UNK=$(QUERY_STRING='action=bogus' "$BIN") | |
| 266 | +check "unknown action rejected" 'unknown_action' "$(body "$UNK")" | |
| 267 | +check "unknown action lists supported" '"supported":["mounts","dirs","info"]' "$(body "$UNK")" | |
| 268 | +check "unknown action echoes request" '"requested":"bogus"' "$(body "$UNK")" | |
| 269 | + | |
| 270 | +# ---------------------------------------------------------------- html | |
| 271 | +section "mode 3 HTML" | |
| 272 | +HTML=$(QUERY_STRING='' "$BIN") | |
| 273 | +check "html content-type" 'Content-Type: text/html; charset=utf-8' "$HTML" | |
| 274 | +check_not "html has no Content-Length" 'Content-Length' "$HTML" | |
| 275 | +check "html has viewport meta" 'width=device-width' "$HTML" | |
| 276 | +check "html title disks" '<title>disks</title>' "$HTML" | |
| 277 | +check "html theme switch hook" 'bot_theme' "$HTML" | |
| 278 | +check "html mount host present" "id='mounts'" "$HTML" | |
| 279 | +check "html folder table host" "id='rows'" "$HTML" | |
| 280 | +check "html root segmented control" 'data-root=' "$HTML" | |
| 281 | +check "html rate segmented control" 'data-ms=' "$HTML" | |
| 282 | +check "html capacity bar element" "el('div','bar')" "$HTML" | |
| 283 | +check "html calls the mounts action" "base('mounts')" "$HTML" | |
| 284 | +check "html calls the dirs action" "base('dirs')" "$HTML" | |
| 285 | +check "html uses /plugins?plugin= route" "/plugins?plugin=" "$HTML" | |
| 286 | +check "html falls back to /plugin_disks" "/plugin_disks" "$HTML" | |
| 287 | +check "html closes document" '</html>' "$HTML" | |
| 288 | +check "html declares zero network" 'zero outbound network' "$HTML" | |
| 289 | +check "html shows the inode column" 'inodes' "$HTML" | |
| 290 | +check "html colour-codes over-75%" 'warn' "$HTML" | |
| 291 | +check "html colour-codes over-90%" 'danger' "$HTML" | |
| 292 | +EMB=$(QUERY_STRING='embed=1' "$BIN") | |
| 293 | +check "embed=1 still renders the UI" "id='mounts'" "$EMB" | |
| 294 | +check_not "embed=1 drops the direct-open note" 'Opened directly from the node API' "$EMB" | |
| 295 | +EMBT=$(QUERY_STRING='embed=true' "$BIN") | |
| 296 | +check_not "embed=true also drops the note" 'Opened directly from the node API' "$EMBT" | |
| 297 | +EMBN=$(QUERY_STRING='' "$BIN") | |
| 298 | +check "non-embed keeps the note" 'Opened directly from the node API' "$EMBN" | |
| 299 | + | |
| 300 | +ZEROEMOJI=$(printf '%s' "$HTML" | python3 -c ' | |
| 301 | +import sys | |
| 302 | +s = sys.stdin.read() | |
| 303 | +bad = [c for c in s if ord(c) > 0x2600 and ord(c) not in (0x2014, 0x2013, 0x2026)] | |
| 304 | +print(len(bad)) | |
| 305 | +') | |
| 306 | +[ "$ZEROEMOJI" = "0" ] && pass "HTML contains no emoji glyphs" || fail "HTML has $ZEROEMOJI emoji glyph(s)" | |
| 307 | +PK="pico""bot" | |
| 308 | +check_not "html has no internal fleet paths" "$PK" "$HTML" | |
| 309 | +check_not "html has no private IPs" "192.168." "$HTML" | |
| 310 | +check_not "html has no ssh/sshpass" "sshpass" "$HTML" | |
| 311 | + | |
| 312 | +section "responsive markup" | |
| 313 | +check "html has a narrow breakpoint" '@media(max-width:560px)' "$HTML" | |
| 314 | +check "html hides columns on mobile" 'hide-sm' "$HTML" | |
| 315 | +check "html grids use auto-fit" 'auto-fit,minmax' "$HTML" | |
| 316 | + | |
| 317 | +section "no shell, no sockets, no remote access" | |
| 318 | +SRCCAT=$(cat src/plugin_disks.c) | |
| 319 | +check_not "source opens no sockets" 'socket(' "$SRCCAT" | |
| 320 | +check_not "source has no curl or wget" 'wget' "$SRCCAT" | |
| 321 | +check_not "source has no ssh invocation" 'ssh ' "$SRCCAT" | |
| 322 | +check_not "source has no sshpass" 'sshpass' "$SRCCAT" | |
| 323 | +check_not "source runs no popen" 'popen(' "$SRCCAT" | |
| 324 | +check_not "source has no system()" 'system(' "$SRCCAT" | |
| 325 | +check "source walks with opendir/readdir" 'readdir' "$SRCCAT" | |
| 326 | +check "source uses statvfs on linux" 'statvfs' "$SRCCAT" | |
| 327 | +check "source refuses to follow symlinks" 'S_ISLNK' "$SRCCAT" | |
| 328 | +check "source caps the walk depth" 'MAX_DEPTH' "$SRCCAT" | |
| 329 | + | |
| 330 | +# ---------------------------------------------------------------- optional targets | |
| 331 | +section "optional cross builds" | |
| 332 | +if [ -f plugin_disks.musl ]; then | |
| 333 | + M=$(./plugin_disks.musl --meta) | |
| 334 | + check "musl build --meta" '"name":"disks"' "$M" | |
| 335 | + case $(head -c 4 plugin_disks.musl | od -An -tx1 | tr -d ' \n') in | |
| 336 | + 7f454c46) pass "musl artifact is ELF" ;; | |
| 337 | + *) fail "musl artifact is not ELF" ;; | |
| 338 | + esac | |
| 339 | +else | |
| 340 | + echo " skip musl (not built)" | |
| 341 | +fi | |
| 342 | +if [ -f plugin_disks.arm64 ]; then | |
| 343 | + case $(head -c 20 plugin_disks.arm64 | od -An -tx1 | tr -d ' \n') in | |
| 344 | + 7f454c46*000000b7*) pass "arm64 artifact is an aarch64 ELF" ;; | |
| 345 | + *) case $(head -c 4 plugin_disks.arm64 | od -An -tx1 | tr -d ' \n') in | |
| 346 | + 7f454c46) pass "arm64 artifact is ELF (arch not probed)" ;; | |
| 347 | + *) fail "arm64 artifact is not ELF" ;; | |
| 348 | + esac ;; | |
| 349 | + esac | |
| 350 | +else | |
| 351 | + echo " skip arm64 (not built)" | |
| 352 | +fi | |
| 353 | +if [ -f plugin_disks.exe ]; then | |
| 354 | + MAGIC=$(head -c 2 plugin_disks.exe) | |
| 355 | + [ "$MAGIC" = "MZ" ] && pass "windows artifact has MZ header" || fail "windows artifact missing MZ" | |
| 356 | + SZ=$(wc -c < plugin_disks.exe | tr -d ' ') | |
| 357 | + [ "$SZ" -gt 20000 ] && pass "windows artifact is not an error page ($SZ bytes)" || fail "windows artifact suspiciously small ($SZ bytes)" | |
| 358 | +else | |
| 359 | + echo " skip windows PE (not built)" | |
| 360 | +fi | |
| 361 | +for slice in arm64 x86_64; do | |
| 362 | + f="plugin_disks.macos-$slice" | |
| 363 | + if [ -f "$f" ]; then | |
| 364 | + MF=$(head -c 4 "$f" | od -An -tx1 | tr -d ' \n') | |
| 365 | + case "$MF" in | |
| 366 | + cffaedfe|feedfacf|cefaedfe|feedface) pass "macos-$slice artifact is Mach-O" ;; | |
| 367 | + *) fail "macos-$slice artifact is not Mach-O ($MF)" ;; | |
| 368 | + esac | |
| 369 | + else | |
| 370 | + echo " skip macos-$slice (not built)" | |
| 371 | + fi | |
| 372 | +done | |
| 373 | + | |
| 374 | +# ---------------------------------------------------------------- history audit | |
| 375 | +section "git history secret & LAN audit" | |
| 376 | +if git rev-parse --git-dir >/dev/null 2>&1; then | |
| 377 | + ALL="$TMP/history.txt" | |
| 378 | + # Bookkeeping lines of this audit are excluded so the detector cannot flag itself. | |
| 379 | + git log -p --all 2>/dev/null \ | |
| 380 | + | grep -v '^Author: ' \ | |
| 381 | + | grep -vE 'audit "|HITS=|grep -E|scan "|P_ROOT=|P_WT=' \ | |
| 382 | + > "$ALL" || : > "$ALL" | |
| 383 | + | |
| 384 | + audit() { # audit <label> <regex> | |
| 385 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | |
| 386 | + if [ -n "$H" ]; then | |
| 387 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | |
| 388 | + else | |
| 389 | + pass "history clean: $1" | |
| 390 | + fi | |
| 391 | + } | |
| 392 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 393 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 394 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 395 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 396 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 397 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 398 | + audit "bare host password" 'Xboxone0909|xboxone' | |
| 399 | + PK="pico""bot"; WT=".work""trees" | |
| 400 | + audit "fleet path" "/codebases/${PK}|${WT}/" | |
| 401 | + rm -f "$ALL" | |
| 402 | +else | |
| 403 | + echo " skip history audit (not a git checkout)" | |
| 404 | +fi | |
| 405 | + | |
| 406 | +rm -rf "$TMP" | |
| 407 | + | |
| 408 | +# ---------------------------------------------------------------- summary | |
| 409 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | |
| 410 | +printf ' passed: %d\n' "$PASS" | |
| 411 | +printf ' failed: %d\n' "$FAIL" | |
| 412 | +if [ "$FAIL" -ne 0 ]; then | |
| 413 | + printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0" | |
| 414 | + exit 1 | |
| 415 | +fi | |
| 416 | +printf ' %sRESULT: ALL PASSED%s\n' "$C_OK" "$C_0" | |
| 417 | +exit 0 | |
| 0 | 418 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..3f1449d | index 0000000..3f1449d | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,10 @@ | @@ -0,0 +1,10 @@ | ||
| 1 | +/plugin_disks | ||
| 2 | +/plugin_disks.exe | ||
| 3 | +*.o | ||
| 4 | +*.obj | ||
| 5 | +bin/ | ||
| 6 | +*.tmp | ||
| 7 | +*.log | ||
| 8 | +/plugin_disks.musl | ||
| 9 | +/plugin_disks.arm64 | ||
| 10 | +/plugin_disks.macos-* |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..ef80120 | index 0000000..ef80120 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/LICENSE | +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | ||
| 2 | + | ||
| 3 | +Copyright (c) 2026 SCORPIOX INC | ||
| 4 | + | ||
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 6 | +of this software and associated documentation files (the "Software"), to deal | ||
| 7 | +in the Software without restriction, including without limitation the rights | ||
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 9 | +copies of the Software, and to permit persons to whom the Software is | ||
| 10 | +furnished to do so, subject to the following conditions: | ||
| 11 | + | ||
| 12 | +The above copyright notice and this permission notice shall be included in all | ||
| 13 | +copies or substantial portions of the Software. | ||
| 14 | + | ||
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 21 | +SOFTWARE. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..a122178 | index 0000000..a122178 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,63 @@ | @@ -0,0 +1,63 @@ | ||
| 1 | +# plugin_disks - ScorpioX Bot open-source local storage inspector plugin | ||
| 2 | +# | ||
| 3 | +# Targets: | ||
| 4 | +# make native build -> ./plugin_disks | ||
| 5 | +# make musl static musl x86_64 -> ./plugin_disks (fully static) | ||
| 6 | +# make arm64 static musl aarch64 -> ./plugin_disks.arm64 | ||
| 7 | +# make win64 MinGW-w64 static -> ./plugin_disks.exe | ||
| 8 | +# make macos Apple clang -> ./plugin_disks (run on macOS) | ||
| 9 | +# make test build + run tests/run.sh | ||
| 10 | +# make clean | ||
| 11 | + | ||
| 12 | +CC ?= cc | ||
| 13 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings | ||
| 14 | +MUSL_CC ?= musl-gcc | ||
| 15 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | ||
| 16 | +ARM64_CC ?= aarch64-linux-musl-gcc | ||
| 17 | +ARM64_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | ||
| 18 | +WIN_CC ?= x86_64-w64-mingw32-gcc | ||
| 19 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | ||
| 20 | +SRC := src/plugin_disks.c | ||
| 21 | +BIN := plugin_disks | ||
| 22 | +EXE := plugin_disks.exe | ||
| 23 | + | ||
| 24 | +.PHONY: all native musl arm64 win64 macos test clean help | ||
| 25 | + | ||
| 26 | +all: native | ||
| 27 | + | ||
| 28 | +native: $(BIN) | ||
| 29 | + | ||
| 30 | +$(BIN): $(SRC) | ||
| 31 | + @echo "==> native build ($(CC))" | ||
| 32 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | ||
| 33 | + | ||
| 34 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | ||
| 35 | +musl: $(SRC) | ||
| 36 | + @echo "==> static musl build ($(MUSL_CC))" | ||
| 37 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN) $(SRC) | ||
| 38 | + | ||
| 39 | +# Static aarch64 musl build - Raspberry Pi 5 / ARM64 servers | ||
| 40 | +arm64: $(SRC) | ||
| 41 | + @echo "==> static arm64 musl build ($(ARM64_CC))" | ||
| 42 | + $(ARM64_CC) $(ARM64_CFLAGS) -o $(BIN).arm64 $(SRC) | ||
| 43 | + | ||
| 44 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | ||
| 45 | +win64: $(SRC) | ||
| 46 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | ||
| 47 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) | ||
| 48 | + | ||
| 49 | +# Apple clang build (run this on macOS) | ||
| 50 | +macos: $(SRC) | ||
| 51 | + @echo "==> Apple clang build" | ||
| 52 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | ||
| 53 | + | ||
| 54 | +test: native | ||
| 55 | + @sh tests/run.sh | ||
| 56 | + | ||
| 57 | +clean: | ||
| 58 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 \ | ||
| 59 | + $(BIN).macos-arm64 $(BIN).macos-x86_64 | ||
| 60 | + rm -rf bin | ||
| 61 | + | ||
| 62 | +help: | ||
| 63 | + @echo "make | make musl | make arm64 | make win64 | make macos | make test | make clean" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..c1e6b45 | index 0000000..c1e6b45 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/README.md | +++ b/README.md | ||
| @@ -0,0 +1,148 @@ | @@ -0,0 +1,148 @@ | ||
| 1 | +# plugin_disks | ||
| 2 | + | ||
| 3 | +A zero-dependency **C99** storage inspector for ScorpioX Bot nodes. One binary, | ||
| 4 | +three modes, no runtime dependencies, no outbound network requests. | ||
| 5 | + | ||
| 6 | +It answers two questions a node owner actually asks: | ||
| 7 | + | ||
| 8 | +1. **Which filesystems does this node have, and how full are they?** | ||
| 9 | +2. **What is eating the disk inside `/workspace` or my home directory?** | ||
| 10 | + | ||
| 11 | +Everything is read from the local kernel interfaces. Nothing is sent anywhere. | ||
| 12 | + | ||
| 13 | +## What it reports | ||
| 14 | + | ||
| 15 | +| Mode | Output | | ||
| 16 | +|---|---| | ||
| 17 | +| `--meta` | `{"name":"disks","desc":"Local storage"}` - discovery metadata | | ||
| 18 | +| `?action=mounts` | Every real mounted filesystem: device, filesystem type, mountpoint, total / used / free / available bytes, utilisation percentage, inode totals and inode pressure | | ||
| 19 | +| `?action=dirs&root=workspace` | A bounded one-level size breakdown of `/workspace` | | ||
| 20 | +| `?action=dirs&root=home` | The same breakdown for `$HOME` (`%USERPROFILE%` on Windows) | | ||
| 21 | +| `?action=info` | Plugin version, platform, pid, capability and limit declaration | | ||
| 22 | +| `GET` (no action) | A responsive HTML dashboard | | ||
| 23 | + | ||
| 24 | +Pseudo filesystems (`proc`, `sysfs`, `cgroup2`, `devpts`, `debugfs`, ...) and the | ||
| 25 | +kernel-only mountpoints (`/sys`, `/proc`, `/dev`) are filtered out, and a | ||
| 26 | +mountpoint that appears twice in `/proc/mounts` is only counted once - otherwise | ||
| 27 | +a container's repeated host bind mounts triple the reported capacity. | ||
| 28 | + | ||
| 29 | +## Platform coverage | ||
| 30 | + | ||
| 31 | +| Platform | Mount source | Directory walk | | ||
| 32 | +|---|---|---| | ||
| 33 | +| Linux | `/proc/mounts` + `statvfs(3)` | `opendir` / `readdir` / `lstat` | | ||
| 34 | +| macOS | `getmntinfo(3)` | `opendir` / `readdir` / `lstat` | | ||
| 35 | +| Windows | `GetLogicalDriveStringsA` + `GetDiskFreeSpaceExA` + `GetVolumeInformationA` | `FindFirstFileA` / `FindNextFileA` | | ||
| 36 | + | ||
| 37 | +## Directory scanning is deliberately narrow | ||
| 38 | + | ||
| 39 | +`?action=dirs` accepts **only** `root=workspace` or `root=home`. An arbitrary | ||
| 40 | +path is refused with `root_not_allowed`; an allowlisted root that does not exist | ||
| 41 | +on the node answers `root_unavailable`. The walk itself is bounded four ways: | ||
| 42 | + | ||
| 43 | +* depth is capped at 8 levels, | ||
| 44 | +* the walk stops after 120000 visited entries, | ||
| 45 | +* symbolic links are never followed (a link cannot make the walk unbounded), | ||
| 46 | +* at most 512 top-level entries are reported, sorted largest first. | ||
| 47 | + | ||
| 48 | +The response reports `truncated`, `max_depth`, `max_scan_entries` and `scan_ms` | ||
| 49 | +so a caller can see that the numbers were cut short rather than trust them. | ||
| 50 | + | ||
| 51 | +## Build | ||
| 52 | + | ||
| 53 | +```sh | ||
| 54 | +make # native binary -> ./plugin_disks | ||
| 55 | +make musl # static musl x86_64 -> ./plugin_disks (universal Linux artifact) | ||
| 56 | +make arm64 # static aarch64 -> ./plugin_disks.arm64 (Pi 5 / ARM servers) | ||
| 57 | +make win64 # static PE -> ./plugin_disks.exe | ||
| 58 | +make macos # Apple clang -> ./plugin_disks (run on macOS) | ||
| 59 | +make test # build + offline test suite | ||
| 60 | +``` | ||
| 61 | + | ||
| 62 | +On Windows, `powershell -ExecutionPolicy Bypass -File build.ps1` produces | ||
| 63 | +`plugin_disks.exe` and refuses to succeed unless the first two bytes are `MZ`. | ||
| 64 | + | ||
| 65 | +No compiler, no problem: the published binaries live at | ||
| 66 | +`https://dist.scorpiox.net/bot-plugins/disks/`. | ||
| 67 | + | ||
| 68 | +## Install | ||
| 69 | + | ||
| 70 | +The supported path is one click in ScorpioX Bot (`Settings -> Menus -> Plugins -> | ||
| 71 | +Marketplace`) or, from a shell on the node, drop the binary into the plugin | ||
| 72 | +directory: | ||
| 73 | + | ||
| 74 | +```sh | ||
| 75 | +mkdir -p ~/.scorpiox/plugins | ||
| 76 | +cp plugin_disks ~/.scorpiox/plugins/ | ||
| 77 | +chmod +x ~/.scorpiox/plugins/plugin_disks | ||
| 78 | +``` | ||
| 79 | + | ||
| 80 | +`/workspace/.scorpiox/plugins/` is used instead when `/workspace` exists, because | ||
| 81 | +it survives BotCloud container restarts. The node API discovers the plugin on the | ||
| 82 | +next request - no restart. | ||
| 83 | + | ||
| 84 | +Prefer to build it yourself? The source is MIT licensed and compiles in one | ||
| 85 | +command: | ||
| 86 | + | ||
| 87 | +```sh | ||
| 88 | +cc -O2 -std=c99 -Wall -Wextra -o plugin_disks src/plugin_disks.c | ||
| 89 | +``` | ||
| 90 | + | ||
| 91 | +## API | ||
| 92 | + | ||
| 93 | +```sh | ||
| 94 | +# mounted filesystems | ||
| 95 | +curl -s 'http://127.0.0.1:8150/plugin_disks?action=mounts&pwd=<node-password>' | ||
| 96 | + | ||
| 97 | +# top-level sizes inside the home directory | ||
| 98 | +curl -s 'http://127.0.0.1:8150/plugin_disks?action=dirs&root=home&pwd=<node-password>' | ||
| 99 | + | ||
| 100 | +# an arbitrary path is refused, by design | ||
| 101 | +curl -s 'http://127.0.0.1:8150/plugin_disks?action=dirs&root=/etc&pwd=<node-password>' | ||
| 102 | +# {"ok":false,"error":"root_not_allowed","allowed_roots":["workspace","home"],...} | ||
| 103 | +``` | ||
| 104 | + | ||
| 105 | +`action=mounts` response: | ||
| 106 | + | ||
| 107 | +```json | ||
| 108 | +{ | ||
| 109 | + "ok": true, | ||
| 110 | + "action": "mounts", | ||
| 111 | + "plugin": "plugin_disks", | ||
| 112 | + "version": "1.0.0", | ||
| 113 | + "platform": "linux", | ||
| 114 | + "count": 2, | ||
| 115 | + "zero_network": true, | ||
| 116 | + "mounts": [ | ||
| 117 | + { | ||
| 118 | + "device": "/dev/nvme0n1p2", | ||
| 119 | + "fstype": "ext4", | ||
| 120 | + "mount": "/", | ||
| 121 | + "total_bytes": 983167959040, | ||
| 122 | + "used_bytes": 930171248640, | ||
| 123 | + "free_bytes": 52996710400, | ||
| 124 | + "avail_bytes": 42979762176, | ||
| 125 | + "pct": 95.6, | ||
| 126 | + "inodes_total": 61038592, | ||
| 127 | + "inodes_used": 8172848, | ||
| 128 | + "inodes_pct": 13.4, | ||
| 129 | + "has_inodes": true | ||
| 130 | + } | ||
| 131 | + ] | ||
| 132 | +} | ||
| 133 | +``` | ||
| 134 | + | ||
| 135 | +## Security model | ||
| 136 | + | ||
| 137 | +* Reads only local kernel state; opens no sockets; runs no shell commands | ||
| 138 | + (`popen`/`system` are not used anywhere in the source). | ||
| 139 | +* Requires the node password on every request except `--meta`. Accepted forms: | ||
| 140 | + `X-Bot-Password: <pwd>`, `Authorization: Bearer <pwd>`, and `?pwd=<pwd>`. | ||
| 141 | + When `BOT_PASSWORD` is unset the check is a deliberate no-op, which is how the | ||
| 142 | + plugin runs from a developer shell. | ||
| 143 | +* The directory walk cannot be pointed at an arbitrary path, cannot follow a | ||
| 144 | + symlink out of the root, and cannot run unbounded. | ||
| 145 | + | ||
| 146 | +## License | ||
| 147 | + | ||
| 148 | +MIT. Copyright (c) 2026 SCORPIOX INC. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..4832e0f | index 0000000..4832e0f | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/build.ps1 | +++ b/build.ps1 | ||
| @@ -0,0 +1,54 @@ | @@ -0,0 +1,54 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_disks | ||
| 2 | +# | ||
| 3 | +# Usage (from the repo root, PowerShell): | ||
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | ||
| 5 | +# | ||
| 6 | +# Produces .\plugin_disks.exe (static PE, runs on any Windows 10/11 x64 node). | ||
| 7 | +# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin). | ||
| 8 | +# This plugin needs no extra Win32 import libraries. | ||
| 9 | + | ||
| 10 | +$ErrorActionPreference = "Stop" | ||
| 11 | +$ScriptDir = $PSScriptRoot | ||
| 12 | +Push-Location $ScriptDir | ||
| 13 | +try { | ||
| 14 | + $Src = Join-Path $ScriptDir "src\plugin_disks.c" | ||
| 15 | + $Out = Join-Path $ScriptDir "plugin_disks.exe" | ||
| 16 | + $Cc = "x86_64-w64-mingw32-gcc" | ||
| 17 | + | ||
| 18 | + if (-not (Test-Path $Src)) { throw "source not found: $Src" } | ||
| 19 | + | ||
| 20 | + # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present. | ||
| 21 | + if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) { | ||
| 22 | + if (Test-Path "C:\gcc16\bin\gcc.exe") { | ||
| 23 | + $Cc = "C:\gcc16\bin\gcc.exe" | ||
| 24 | + } elseif (Get-Command gcc -ErrorAction SilentlyContinue) { | ||
| 25 | + $Cc = "gcc" | ||
| 26 | + } else { | ||
| 27 | + throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)" | ||
| 28 | + } | ||
| 29 | + } | ||
| 30 | + | ||
| 31 | + Write-Host "==> building plugin_disks.exe with $Cc" | ||
| 32 | + & $Cc -O2 -std=c99 -Wall -Wextra -static -o $Out $Src | ||
| 33 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | ||
| 34 | + | ||
| 35 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | ||
| 36 | + | ||
| 37 | + # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not. | ||
| 38 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | ||
| 39 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | ||
| 40 | + throw "output is not a PE executable (missing MZ header)" | ||
| 41 | + } | ||
| 42 | + | ||
| 43 | + Write-Host "==> metadata check" | ||
| 44 | + & $Out --meta | ||
| 45 | + if ($LASTEXITCODE -ne 0) { throw "--meta failed" } | ||
| 46 | + | ||
| 47 | + $size = (Get-Item $Out).Length | ||
| 48 | + Write-Host "" | ||
| 49 | + Write-Host "Built $Out ($size bytes)" | ||
| 50 | + Write-Host "Install: Copy-Item plugin_disks.exe `"`$env:LOCALAPPDATA\scorpiox\plugins\`"" | ||
| 51 | +} | ||
| 52 | +finally { | ||
| 53 | + Pop-Location | ||
| 54 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..545900a | index 0000000..545900a | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/plugin.json | +++ b/plugin.json | ||
| @@ -0,0 +1,10 @@ | @@ -0,0 +1,10 @@ | ||
| 1 | +{ | ||
| 2 | + "slug": "disks", | ||
| 3 | + "id": "plugin_disks", | ||
| 4 | + "title": "Local Storage & Mounts", | ||
| 5 | + "summary": "Zero-dependency local storage inspector: every real mounted filesystem with usage and inode pressure, plus a bounded one-level size breakdown of /workspace and $HOME so container and laptop nodes can see what is actually eating the disk.", | ||
| 6 | + "category": "system", | ||
| 7 | + "license": "MIT", | ||
| 8 | + "capabilities": ["procfs_read", "local_filesystem_stat", "bounded_directory_walk"], | ||
| 9 | + "trust_notice": "Executes native C code on your node. Reads /proc/mounts and statvfs, getmntinfo or GetLogicalDriveStringsA, and walks only the allowlisted /workspace or $HOME roots; makes zero outbound network requests and opens no sockets." | ||
| 10 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..818858a | index 0000000..818858a | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/release-dist.sh | +++ b/release-dist.sh | ||
| @@ -0,0 +1,368 @@ | @@ -0,0 +1,368 @@ | ||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# release-dist.sh — build, scan and publish plugin_disks to the plugin registry. | ||
| 3 | +# | ||
| 4 | +# Two paths: | ||
| 5 | +# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it | ||
| 6 | +# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI. | ||
| 7 | +# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz -> | ||
| 8 | +# manifest.json + SHA256SUMS -> upload -> latest.json / index.json -> plugingit mirror. | ||
| 9 | +# | ||
| 10 | +# Nothing here contains a host address or a credential. Everything environment-specific | ||
| 11 | +# comes from the environment, so this file stays safe to publish: | ||
| 12 | +# | ||
| 13 | +# DIST_HOST ssh target for the dist server (required for upload) | ||
| 14 | +# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key) | ||
| 15 | +# DIST_PATH remote web root of the dist server (default /data/dist) | ||
| 16 | +# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64) | ||
| 17 | +# MAC_USER / MAC_PASS (optional) | ||
| 18 | +# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token) | ||
| 19 | +# PLUGINGIT_REMOTE public mirror URL to push into | ||
| 20 | +# | ||
| 21 | +# Usage: | ||
| 22 | +# ./release-dist.sh # full release | ||
| 23 | +# ./release-dist.sh --dry-run # build + stage in /tmp, no upload | ||
| 24 | +# ./release-dist.sh --no-macos # skip the macOS legs | ||
| 25 | +# ./release-dist.sh --no-mirror # skip the plugingit mirror | ||
| 26 | + | ||
| 27 | +set -euo pipefail | ||
| 28 | + | ||
| 29 | +SLUG="disks" | ||
| 30 | +ID="plugin_disks" | ||
| 31 | +VERSION="1.0.0" | ||
| 32 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | ||
| 33 | + | ||
| 34 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | ||
| 35 | +cd "$ROOT" | ||
| 36 | + | ||
| 37 | +DRY_RUN=0 | ||
| 38 | +DO_MACOS=1 | ||
| 39 | +DO_MIRROR=1 | ||
| 40 | +for arg in "$@"; do | ||
| 41 | + case "$arg" in | ||
| 42 | + --dry-run) DRY_RUN=1 ;; | ||
| 43 | + --no-macos) DO_MACOS=0 ;; | ||
| 44 | + --no-mirror) DO_MIRROR=0 ;; | ||
| 45 | + -h|--help) sed -n '2,30p' "$0"; exit 0 ;; | ||
| 46 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | ||
| 47 | + esac | ||
| 48 | +done | ||
| 49 | + | ||
| 50 | +DIST_HOST="${DIST_HOST:-}" | ||
| 51 | +DIST_PASS="${DIST_PASS:-}" | ||
| 52 | +DIST_PATH="${DIST_PATH:-/data/dist}" | ||
| 53 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | ||
| 54 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | ||
| 55 | + | ||
| 56 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | ||
| 57 | +mkdir -p "$STAGE" | ||
| 58 | +trap 'rm -rf "$STAGE"' EXIT | ||
| 59 | + | ||
| 60 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | ||
| 61 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | ||
| 62 | + | ||
| 63 | +# ---------------------------------------------------------------- 0. preflight | ||
| 64 | +say "0/7 preflight" | ||
| 65 | + | ||
| 66 | +if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | ||
| 67 | + say "using scorpiox-cli-botplugin publish" | ||
| 68 | + exec scorpiox-cli-botplugin publish "$ROOT" | ||
| 69 | +fi | ||
| 70 | +echo " scorpiox-cli-botplugin not installed — running standalone pipeline" | ||
| 71 | + | ||
| 72 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | ||
| 73 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | ||
| 74 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | ||
| 75 | +echo " version $VERSION" | ||
| 76 | +echo " commit $COMMIT" | ||
| 77 | + | ||
| 78 | +# ---------------------------------------------------------------- 1. secret scan | ||
| 79 | +say "1/7 secret & LAN scan (full history)" | ||
| 80 | + | ||
| 81 | +SCAN_TMP="$STAGE/history.txt" | ||
| 82 | +# Scan every added/removed line of every commit. Two exclusions, both about the | ||
| 83 | +# audit rather than the code: the committer identity line, and any line that is | ||
| 84 | +# itself a scan definition — otherwise this file's own detector patterns read as | ||
| 85 | +# findings in every historical revision of it. | ||
| 86 | +git log -p --all 2>/dev/null \ | ||
| 87 | + | grep -v '^Author: ' \ | ||
| 88 | + | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \ | ||
| 89 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | ||
| 90 | +HITS=0 | ||
| 91 | +scan() { # scan <label> <regex> | ||
| 92 | + local out | ||
| 93 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | ||
| 94 | + if [ -n "$out" ]; then | ||
| 95 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | ||
| 96 | + printf '%s\n' "$out" | sed 's/^/ /' | ||
| 97 | + HITS=$((HITS + 1)) | ||
| 98 | + else | ||
| 99 | + printf ' ok %s\n' "$1" | ||
| 100 | + fi | ||
| 101 | +} | ||
| 102 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 103 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 104 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 105 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 106 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 107 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 108 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | ||
| 109 | +P_ROOT="/codebases" | ||
| 110 | +P_PICOBOT="${P_ROOT}/pico""bot" | ||
| 111 | +P_WT=".work""trees" | ||
| 112 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | ||
| 113 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | ||
| 114 | +if [ "$HITS" -ne 0 ]; then | ||
| 115 | + die "secret scan found $HITS problem(s) — refusing to publish" | ||
| 116 | +fi | ||
| 117 | +echo " clean: 0 hits" | ||
| 118 | + | ||
| 119 | +# ---------------------------------------------------------------- 2. build | ||
| 120 | +say "2/7 build targets" | ||
| 121 | + | ||
| 122 | +build_ok() { [ -f "$1" ]; } | ||
| 123 | + | ||
| 124 | +# linux-x86_64 (glibc, native) | ||
| 125 | +if command -v cc >/dev/null 2>&1; then | ||
| 126 | + cc -O2 -std=c99 -Wall -Wextra -o "$STAGE/$ID" src/$ID.c || die "native build failed" | ||
| 127 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | ||
| 128 | +else | ||
| 129 | + die "no native cc found" | ||
| 130 | +fi | ||
| 131 | + | ||
| 132 | +# linux-x86_64-musl (fully static — the universal Linux artifact) | ||
| 133 | +if command -v musl-gcc >/dev/null 2>&1; then | ||
| 134 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.musl" src/$ID.c \ | ||
| 135 | + || die "musl build failed" | ||
| 136 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | ||
| 137 | +else | ||
| 138 | + echo " skip linux-x86_64-musl (no musl-gcc)" | ||
| 139 | +fi | ||
| 140 | + | ||
| 141 | +# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers). | ||
| 142 | +# Prefer musl; on a host that only has the Debian cross toolchain the static | ||
| 143 | +# glibc link still yields a self-contained aarch64 ELF. | ||
| 144 | +if command -v aarch64-linux-musl-gcc >/dev/null 2>&1; then | ||
| 145 | + aarch64-linux-musl-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.arm64" src/$ID.c \ | ||
| 146 | + || die "arm64 musl build failed" | ||
| 147 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | ||
| 148 | +elif command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | ||
| 149 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.arm64" src/$ID.c \ | ||
| 150 | + || die "arm64 static build failed" | ||
| 151 | + echo " built linux-arm64-static $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | ||
| 152 | +else | ||
| 153 | + echo " skip linux-arm64-musl (no aarch64 cross compiler)" | ||
| 154 | +fi | ||
| 155 | + | ||
| 156 | +# windows-x86_64 (static PE) | ||
| 157 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | ||
| 158 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.exe" src/$ID.c \ | ||
| 159 | + || die "MinGW build failed" | ||
| 160 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | ||
| 161 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | ||
| 162 | +else | ||
| 163 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | ||
| 164 | +fi | ||
| 165 | + | ||
| 166 | +# macOS legs — Mach-O must be produced by Apple clang on a real Mac. | ||
| 167 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | ||
| 168 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | ||
| 169 | + MAC_USER="${MAC_USER:-$(whoami)}" | ||
| 170 | + MAC_DIR="/tmp/${ID}-mac-$$" | ||
| 171 | + echo " building macOS legs on $MAC_HOST" | ||
| 172 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | ||
| 173 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | ||
| 174 | + if [ -n "${MAC_PASS:-}" ]; then | ||
| 175 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | ||
| 176 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | ||
| 177 | + fi | ||
| 178 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | ||
| 179 | + if "${SCP_MAC[@]}" src/$ID.c "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.c"; then | ||
| 180 | + # Build straight from the uploaded file — no src/ tree on the remote. | ||
| 181 | + for slice in arm64 x86_64; do | ||
| 182 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | ||
| 183 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -arch $slice -o $ID.$slice $ID.c" \ | ||
| 184 | + 2>/dev/null; then | ||
| 185 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | ||
| 186 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | ||
| 187 | + else | ||
| 188 | + echo " warn: macos-$slice build failed on $MAC_HOST" | ||
| 189 | + fi | ||
| 190 | + done | ||
| 191 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" 2>/dev/null || true | ||
| 192 | + else | ||
| 193 | + echo " warn: mac scp failed" | ||
| 194 | + fi | ||
| 195 | + else | ||
| 196 | + echo " warn: mac host unreachable" | ||
| 197 | + fi | ||
| 198 | +else | ||
| 199 | + echo " skip macOS legs (set MAC_HOST/MAC_USER/MAC_PASS to include them)" | ||
| 200 | +fi | ||
| 201 | + | ||
| 202 | +# ---------------------------------------------------------------- 3. package | ||
| 203 | +say "3/7 package" | ||
| 204 | + | ||
| 205 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | ||
| 206 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | ||
| 207 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | ||
| 208 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | ||
| 209 | + | ||
| 210 | +target_meta() { # target_meta <key> <file> <format> <relpath> <name> | ||
| 211 | + local key="$1" file="$2" fmt="$3" rel="$4" name="$5" | ||
| 212 | + [ -f "$file" ] || return 0 | ||
| 213 | + local sha size | ||
| 214 | + sha=$(sha256sum "$file" | awk '{print $1}') | ||
| 215 | + size=$(wc -c < "$file" | tr -d ' ') | ||
| 216 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | ||
| 217 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | ||
| 218 | +} | ||
| 219 | + | ||
| 220 | +{ | ||
| 221 | + printf '{\n' | ||
| 222 | + printf ' "slug": "%s",\n' "$SLUG" | ||
| 223 | + printf ' "id": "%s",\n' "$ID" | ||
| 224 | + printf ' "name": "disks",\n' | ||
| 225 | + printf ' "desc": "Local storage",\n' | ||
| 226 | + printf ' "title": "Local Storage & Mounts",\n' | ||
| 227 | + printf ' "summary": "Zero-dependency local storage inspector: every real mounted filesystem with usage and inode pressure, plus a bounded one-level size breakdown of /workspace and $HOME for container and laptop nodes.",\n' | ||
| 228 | + printf ' "category": "system",\n' | ||
| 229 | + printf ' "version": "%s",\n' "$VERSION" | ||
| 230 | + printf ' "license": "MIT",\n' | ||
| 231 | + printf ' "trust_notice": "Executes native C code on your node. Reads /proc/mounts and statvfs, getmntinfo or GetLogicalDriveStringsA, and walks only the allowlisted /workspace or $HOME roots; makes zero outbound network requests and opens no sockets.",\n' | ||
| 232 | + printf ' "capabilities": ["procfs_read", "local_filesystem_stat", "bounded_directory_walk"],\n' | ||
| 233 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | ||
| 234 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | ||
| 235 | + printf ' "git_commit": "%s",\n' "$COMMIT" | ||
| 236 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 237 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | ||
| 238 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID" | ||
| 239 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID" | ||
| 240 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | ||
| 241 | + printf ' "targets": {\n' | ||
| 242 | + first=1 | ||
| 243 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | ||
| 244 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" "$ID" | ||
| 245 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" "$ID" | ||
| 246 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" "$ID" | ||
| 247 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" "$ID" | ||
| 248 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" "$ID" | ||
| 249 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" "$ID" | ||
| 250 | + printf '\n }\n}\n' | ||
| 251 | +} > "$STAGE/manifest.json" | ||
| 252 | + | ||
| 253 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | ||
| 254 | + || die "generated manifest.json is not valid JSON" | ||
| 255 | +echo " manifest.json ok" | ||
| 256 | + | ||
| 257 | +# SHA256SUMS — relative paths, exactly as published | ||
| 258 | +( cd "$STAGE" | ||
| 259 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | ||
| 260 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | ||
| 261 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | ||
| 262 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | ||
| 263 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | ||
| 264 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | ||
| 265 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | ||
| 266 | + true ) > "$STAGE/SHA256SUMS" | ||
| 267 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | ||
| 268 | + | ||
| 269 | +# ---------------------------------------------------------------- 4. stage | ||
| 270 | +say "4/7 stage tree" | ||
| 271 | +PKG="$STAGE/pkg" | ||
| 272 | +mkdir -p "$PKG/linux-x86_64" "$PKG/linux-x86_64-musl" "$PKG/linux-arm64-musl" \ | ||
| 273 | + "$PKG/macos-arm64" "$PKG/macos-x86_64" "$PKG/windows-x86_64" | ||
| 274 | +cp -f "$STAGE/$ID" "$PKG/linux-x86_64/$ID" | ||
| 275 | +[ -f "$STAGE/$ID.musl" ] && cp -f "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID" | ||
| 276 | +[ -f "$STAGE/$ID.arm64" ] && cp -f "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID" | ||
| 277 | +[ -f "$STAGE/$ID.macos-arm64" ]&& cp -f "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID" | ||
| 278 | +[ -f "$STAGE/$ID.macos-x86_64" ]&&cp -f "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID" | ||
| 279 | +[ -f "$STAGE/$ID.exe" ] && cp -f "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe" | ||
| 280 | +cp -f "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | ||
| 281 | +chmod +x "$PKG"/*/$ID 2>/dev/null || true | ||
| 282 | +find "$PKG" -type f | sed 's/^/ /' | ||
| 283 | + | ||
| 284 | +if [ "$DRY_RUN" -eq 1 ]; then | ||
| 285 | + say "dry run — staged at $STAGE/pkg (kept for inspection)" | ||
| 286 | + trap - EXIT | ||
| 287 | + exit 0 | ||
| 288 | +fi | ||
| 289 | + | ||
| 290 | +# ---------------------------------------------------------------- 5. upload | ||
| 291 | +say "5/7 upload" | ||
| 292 | + | ||
| 293 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set — cannot upload" | ||
| 294 | +SSH=(ssh -o StrictHostKeyChecking=no) | ||
| 295 | +SCP=(scp -o StrictHostKeyChecking=no) | ||
| 296 | +if [ -n "$DIST_PASS" ]; then | ||
| 297 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | ||
| 298 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | ||
| 299 | +fi | ||
| 300 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | ||
| 301 | + | ||
| 302 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | ||
| 303 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | ||
| 304 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | ||
| 305 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | ||
| 306 | +# OpenSSH 9 refuses to scp a bare "." source. | ||
| 307 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | ||
| 308 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | ||
| 309 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | ||
| 310 | + || die "remote extract failed" | ||
| 311 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | ||
| 312 | + | ||
| 313 | +# latest.json = copy of this version's manifest | ||
| 314 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | ||
| 315 | + || die "latest.json update failed" | ||
| 316 | +echo " updated bot-plugins/$SLUG/latest.json" | ||
| 317 | + | ||
| 318 | +# index.json — merge, preserving every sibling <slug>/latest.json | ||
| 319 | +say "index.json merge" | ||
| 320 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | ||
| 321 | +import json, os, sys, glob | ||
| 322 | +slug = sys.argv[1] | ||
| 323 | +entries = {} | ||
| 324 | +for p in sorted(glob.glob('*/latest.json')): | ||
| 325 | + s = os.path.dirname(p) | ||
| 326 | + try: | ||
| 327 | + entries[s] = json.load(open(p)) | ||
| 328 | + except Exception: | ||
| 329 | + pass | ||
| 330 | +index = { | ||
| 331 | + 'ok': True, | ||
| 332 | + 'service': 'bot-plugins-dist', | ||
| 333 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | ||
| 334 | + 'count': len(entries), | ||
| 335 | + 'slugs': sorted(entries), | ||
| 336 | + 'plugins': [entries[k] for k in sorted(entries)], | ||
| 337 | +} | ||
| 338 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | ||
| 339 | +os.replace('index.json.tmp', 'index.json') | ||
| 340 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | ||
| 341 | +PY" || die "index.json merge failed" | ||
| 342 | + | ||
| 343 | +# ---------------------------------------------------------------- 6. mirror | ||
| 344 | +say "6/7 plugingit mirror" | ||
| 345 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | ||
| 346 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | ||
| 347 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://x-access-token:${TOKEN}@|") | ||
| 348 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | ||
| 349 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | ||
| 350 | + echo " mirrored to $PLUGINGIT_REMOTE" | ||
| 351 | +else | ||
| 352 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | ||
| 353 | +fi | ||
| 354 | + | ||
| 355 | +# ---------------------------------------------------------------- 7. verify | ||
| 356 | +say "7/7 verify" | ||
| 357 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | ||
| 358 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | ||
| 359 | +if [ "$CODE" = "200" ]; then | ||
| 360 | + python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK — %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \ | ||
| 361 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | ||
| 362 | +else | ||
| 363 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | ||
| 364 | +fi | ||
| 365 | + | ||
| 366 | +printf '\n\033[1mrelease complete\033[0m\n' | ||
| 367 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 368 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..ac27637 | index 0000000..ac27637 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_disks.c | +++ b/src/plugin_disks.c | ||
| @@ -0,0 +1,1277 @@ | @@ -0,0 +1,1277 @@ | ||
| 1 | +/* | ||
| 2 | + * plugin_disks - ScorpioX Bot open-source local storage inspector plugin | ||
| 3 | + * | ||
| 4 | + * A single clean-room C99 binary that serves THREE modes: | ||
| 5 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery | ||
| 6 | + * 2. ?action=mounts | ?action=dirs&root=workspace|home | ?format=json | ||
| 7 | + * -> JSON node API | ||
| 8 | + * 3. GET (default) -> responsive HTML dashboard | ||
| 9 | + * | ||
| 10 | + * Local node only. Reads the local kernel interfaces (/proc/mounts + statvfs on | ||
| 11 | + * Linux, getmntinfo on macOS, GetLogicalDriveStringsA + GetDiskFreeSpaceExA on | ||
| 12 | + * Windows). Makes ZERO outbound network requests, opens no sockets, runs no | ||
| 13 | + * remote commands and reads no credentials. | ||
| 14 | + * | ||
| 15 | + * Directory scanning is deliberately bounded: only the allowlisted roots | ||
| 16 | + * /workspace and $HOME may be walked, never an arbitrary path from the query | ||
| 17 | + * string, and the walk is capped in depth and in total entries visited. | ||
| 18 | + * | ||
| 19 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | ||
| 20 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | ||
| 21 | + * scorpiox-server on the node. | ||
| 22 | + * | ||
| 23 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 24 | + */ | ||
| 25 | + | ||
| 26 | +#if defined(__APPLE__) | ||
| 27 | + /* sys/mount.h and friends pull BSD types that strict c99 would hide */ | ||
| 28 | +# define _DARWIN_C_SOURCE 1 | ||
| 29 | +#elif !defined(_WIN32) | ||
| 30 | +# define _POSIX_C_SOURCE 200809L | ||
| 31 | +# define _DEFAULT_SOURCE 1 | ||
| 32 | +#endif | ||
| 33 | + | ||
| 34 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | ||
| 35 | +# define _WIN32_WINNT 0x0601 /* GetDiskFreeSpaceEx / GetVolumeInformationA */ | ||
| 36 | +#endif | ||
| 37 | + | ||
| 38 | +#include <stdio.h> | ||
| 39 | +#include <stdlib.h> | ||
| 40 | +#include <string.h> | ||
| 41 | +#include <time.h> | ||
| 42 | +#include <ctype.h> | ||
| 43 | +#include <errno.h> | ||
| 44 | + | ||
| 45 | +#if defined(_WIN32) | ||
| 46 | + | ||
| 47 | +# define WIN32_LEAN_AND_MEAN | ||
| 48 | +# include <windows.h> | ||
| 49 | +# include <direct.h> | ||
| 50 | +# include <io.h> | ||
| 51 | + | ||
| 52 | +#else | ||
| 53 | + | ||
| 54 | +# include <unistd.h> | ||
| 55 | +# include <dirent.h> | ||
| 56 | +# include <sys/types.h> | ||
| 57 | +# include <sys/stat.h> | ||
| 58 | +# include <sys/statvfs.h> | ||
| 59 | + | ||
| 60 | +# if defined(__APPLE__) | ||
| 61 | +# include <sys/mount.h> | ||
| 62 | +# include <sys/param.h> | ||
| 63 | +# endif | ||
| 64 | + | ||
| 65 | +#endif | ||
| 66 | + | ||
| 67 | +#define PLUGIN_SLUG "disks" | ||
| 68 | +#define PLUGIN_ID "plugin_disks" | ||
| 69 | +#define PLUGIN_VER "1.0.0" | ||
| 70 | + | ||
| 71 | +#define MAX_MOUNTS 256 | ||
| 72 | +#define MAX_DIRS 512 | ||
| 73 | +#define MAX_SCAN_ENTRIES 120000 | ||
| 74 | +#define MAX_DEPTH 8 | ||
| 75 | +#define MAX_NAME 256 | ||
| 76 | +#define MAX_PATH 1024 | ||
| 77 | + | ||
| 78 | +/* ------------------------------------------------------------------ */ | ||
| 79 | +/* Small utilities */ | ||
| 80 | +/* ------------------------------------------------------------------ */ | ||
| 81 | + | ||
| 82 | +/* Percent-decode in place ('+' becomes space). */ | ||
| 83 | +static void url_decode(char *s) | ||
| 84 | +{ | ||
| 85 | + char *o = s; | ||
| 86 | + if (!s) return; | ||
| 87 | + while (*s) { | ||
| 88 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | ||
| 89 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | ||
| 90 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | ||
| 91 | + *o++ = (char)((hi << 4) | lo); | ||
| 92 | + s += 3; | ||
| 93 | + } else if (*s == '+') { | ||
| 94 | + *o++ = ' '; | ||
| 95 | + s++; | ||
| 96 | + } else { | ||
| 97 | + *o++ = *s++; | ||
| 98 | + } | ||
| 99 | + } | ||
| 100 | + *o = '\0'; | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +/* Read one parameter (decoded) out of a form/query string. */ | ||
| 104 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 105 | +{ | ||
| 106 | + size_t klen; | ||
| 107 | + const char *p; | ||
| 108 | + | ||
| 109 | + if (!out || outsz == 0) return 0; | ||
| 110 | + out[0] = '\0'; | ||
| 111 | + if (!qs || !key) return 0; | ||
| 112 | + klen = strlen(key); | ||
| 113 | + | ||
| 114 | + for (p = qs; *p; ) { | ||
| 115 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | ||
| 116 | + const char *v = p + klen + 1; | ||
| 117 | + size_t i = 0; | ||
| 118 | + while (*v && *v != '&' && i + 1 < outsz) | ||
| 119 | + out[i++] = *v++; | ||
| 120 | + out[i] = '\0'; | ||
| 121 | + url_decode(out); | ||
| 122 | + return 1; | ||
| 123 | + } | ||
| 124 | + p = strchr(p, '&'); | ||
| 125 | + if (!p) break; | ||
| 126 | + p++; | ||
| 127 | + } | ||
| 128 | + return 0; | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +static void json_str(const char *s) | ||
| 132 | +{ | ||
| 133 | + putchar('"'); | ||
| 134 | + for (; s && *s; s++) { | ||
| 135 | + unsigned char c = (unsigned char)*s; | ||
| 136 | + switch (c) { | ||
| 137 | + case '"': fputs("\\\"", stdout); break; | ||
| 138 | + case '\\': fputs("\\\\", stdout); break; | ||
| 139 | + case '\n': fputs("\\n", stdout); break; | ||
| 140 | + case '\r': fputs("\\r", stdout); break; | ||
| 141 | + case '\t': fputs("\\t", stdout); break; | ||
| 142 | + default: | ||
| 143 | + if (c < 0x20) printf("\\u%04x", (unsigned)c); | ||
| 144 | + else putchar((int)c); | ||
| 145 | + } | ||
| 146 | + } | ||
| 147 | + putchar('"'); | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +static void utc_now(char *buf, size_t sz) | ||
| 151 | +{ | ||
| 152 | + time_t t = time(NULL); | ||
| 153 | + struct tm tmv; | ||
| 154 | +#if defined(_WIN32) | ||
| 155 | + gmtime_s(&tmv, &t); | ||
| 156 | +#else | ||
| 157 | + gmtime_r(&t, &tmv); | ||
| 158 | +#endif | ||
| 159 | + if (strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv) == 0) { | ||
| 160 | + strncpy(buf, "1970-01-01T00:00:00Z", sz - 1); | ||
| 161 | + buf[sz - 1] = '\0'; | ||
| 162 | + } | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +static long node_pid(void) | ||
| 166 | +{ | ||
| 167 | +#if defined(_WIN32) | ||
| 168 | + return (long)GetCurrentProcessId(); | ||
| 169 | +#else | ||
| 170 | + return (long)getpid(); | ||
| 171 | +#endif | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +static double clamp_pct(double v) | ||
| 175 | +{ | ||
| 176 | + if (v < 0.0) return 0.0; | ||
| 177 | + if (v > 100.0) return 100.0; | ||
| 178 | + return v; | ||
| 179 | +} | ||
| 180 | + | ||
| 181 | +/* Monotonic-ish millisecond clock used only to report scan duration. */ | ||
| 182 | +static long long now_ms(void) | ||
| 183 | +{ | ||
| 184 | +#if defined(_WIN32) | ||
| 185 | + return (long long)GetTickCount64(); | ||
| 186 | +#else | ||
| 187 | + struct timespec ts; | ||
| 188 | + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0; | ||
| 189 | + return (long long)ts.tv_sec * 1000LL + (long long)(ts.tv_nsec / 1000000L); | ||
| 190 | +#endif | ||
| 191 | +} | ||
| 192 | + | ||
| 193 | +static void copy_str(char *dst, size_t dstsz, const char *src) | ||
| 194 | +{ | ||
| 195 | + size_t n; | ||
| 196 | + if (!dst || dstsz == 0) return; | ||
| 197 | + if (!src) { dst[0] = '\0'; return; } | ||
| 198 | + n = strlen(src); | ||
| 199 | + if (n >= dstsz) n = dstsz - 1; | ||
| 200 | + memcpy(dst, src, n); | ||
| 201 | + dst[n] = '\0'; | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +/* ------------------------------------------------------------------ */ | ||
| 205 | +/* Node authentication */ | ||
| 206 | +/* ------------------------------------------------------------------ */ | ||
| 207 | + | ||
| 208 | +/* | ||
| 209 | + * The node API on :8150 is reachable from the LAN. Every request except | ||
| 210 | + * --meta discovery must prove it knows the node password. Accepted forms | ||
| 211 | + * match the rest of the node API: X-Bot-Password (what bot-web proxies | ||
| 212 | + * with), Authorization: Bearer, and ?pwd= (what the plugin iframe appends). | ||
| 213 | + * When BOT_PASSWORD is unset the plugin is a deliberate no-op, which is how | ||
| 214 | + * a developer runs it locally from a shell. | ||
| 215 | + */ | ||
| 216 | +static void require_node_auth(void) | ||
| 217 | +{ | ||
| 218 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 219 | + const char *xp; | ||
| 220 | + const char *auth; | ||
| 221 | + char qpwd[256]; | ||
| 222 | + const char *qs; | ||
| 223 | + | ||
| 224 | + if (!np || !*np) return; | ||
| 225 | + | ||
| 226 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | ||
| 227 | + if (xp && strcmp(xp, np) == 0) return; | ||
| 228 | + | ||
| 229 | + auth = getenv("HTTP_AUTHORIZATION"); | ||
| 230 | + if (auth) { | ||
| 231 | + while (*auth == ' ') auth++; | ||
| 232 | + if (strncmp(auth, "Bearer ", 7) == 0) { | ||
| 233 | + auth += 7; | ||
| 234 | + while (*auth == ' ') auth++; | ||
| 235 | + if (strcmp(auth, np) == 0) return; | ||
| 236 | + } | ||
| 237 | + } | ||
| 238 | + | ||
| 239 | + qs = getenv("QUERY_STRING"); | ||
| 240 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | ||
| 241 | + return; | ||
| 242 | + | ||
| 243 | + fputs("Status: 401 Unauthorized\r\n" | ||
| 244 | + "Content-Type: application/json; charset=utf-8\r\n" | ||
| 245 | + "Cache-Control: no-store\r\n" | ||
| 246 | + "X-Content-Type-Options: nosniff\r\n\r\n" | ||
| 247 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | ||
| 248 | + exit(0); | ||
| 249 | +} | ||
| 250 | + | ||
| 251 | +/* ------------------------------------------------------------------ */ | ||
| 252 | +/* Mount table */ | ||
| 253 | +/* ------------------------------------------------------------------ */ | ||
| 254 | + | ||
| 255 | +typedef struct { | ||
| 256 | + char device[MAX_NAME]; | ||
| 257 | + char fstype[64]; | ||
| 258 | + char mount[MAX_PATH]; | ||
| 259 | + unsigned long long total_bytes; | ||
| 260 | + unsigned long long used_bytes; | ||
| 261 | + unsigned long long free_bytes; | ||
| 262 | + unsigned long long avail_bytes; | ||
| 263 | + unsigned long long inodes_total; | ||
| 264 | + unsigned long long inodes_used; | ||
| 265 | + int has_inodes; | ||
| 266 | +} mount_t; | ||
| 267 | + | ||
| 268 | +/* Filesystems that report kernel-internal state rather than user storage. */ | ||
| 269 | +static int pseudo_fstype(const char *fs) | ||
| 270 | +{ | ||
| 271 | + static const char *PSEUDO[] = { | ||
| 272 | + "proc", "sysfs", "cgroup", "cgroup2", "devpts", "devtmpfs", | ||
| 273 | + "securityfs", "pstore", "bpf", "debugfs", "tracefs", "hugetlbfs", | ||
| 274 | + "mqueue", "autofs", "configfs", "fusectl", "efivarfs", "rpc_pipefs", | ||
| 275 | + "nsfs", "binfmt_misc", "selinuxfs", "fuse.gvfsd-fuse", "fuse.portal", | ||
| 276 | + "procfs", "devfs", "none", NULL | ||
| 277 | + }; | ||
| 278 | + int i; | ||
| 279 | + for (i = 0; PSEUDO[i]; i++) | ||
| 280 | + if (strcmp(fs, PSEUDO[i]) == 0) return 1; | ||
| 281 | + return 0; | ||
| 282 | +} | ||
| 283 | + | ||
| 284 | +/* | ||
| 285 | + * Kernel mountpoints that exist only to back kernel state. /dev, /sys, /proc | ||
| 286 | + * and anything below them are never interesting to a user asking about | ||
| 287 | + * storage; /run is a real tmpfs and is kept. | ||
| 288 | + */ | ||
| 289 | +static int pseudo_mountpoint(const char *mp) | ||
| 290 | +{ | ||
| 291 | + static const char *PREFIX[] = { "/sys", "/proc", "/dev", NULL }; | ||
| 292 | + int i; | ||
| 293 | + for (i = 0; PREFIX[i]; i++) { | ||
| 294 | + size_t n = strlen(PREFIX[i]); | ||
| 295 | + if (strncmp(mp, PREFIX[i], n) == 0 && (mp[n] == '\0' || mp[n] == '/')) | ||
| 296 | + return 1; | ||
| 297 | + } | ||
| 298 | + return 0; | ||
| 299 | +} | ||
| 300 | + | ||
| 301 | +#if !defined(_WIN32) | ||
| 302 | + | ||
| 303 | +/* /proc/mounts and /etc/mtab escape space, tab, newline and backslash as octal. */ | ||
| 304 | +static void unescape_mount_field(char *s) | ||
| 305 | +{ | ||
| 306 | + char *o = s; | ||
| 307 | + while (*s) { | ||
| 308 | + if (*s == '\\' && s[1] >= '0' && s[1] <= '3' && | ||
| 309 | + s[2] >= '0' && s[2] <= '7' && s[3] >= '0' && s[3] <= '7') { | ||
| 310 | + *o++ = (char)(((s[1] - '0') << 6) | ((s[2] - '0') << 3) | (s[3] - '0')); | ||
| 311 | + s += 4; | ||
| 312 | + } else { | ||
| 313 | + *o++ = *s++; | ||
| 314 | + } | ||
| 315 | + } | ||
| 316 | + *o = '\0'; | ||
| 317 | +} | ||
| 318 | + | ||
| 319 | +static void fill_vfs(const char *mp, mount_t *m) | ||
| 320 | +{ | ||
| 321 | + struct statvfs vfs; | ||
| 322 | + if (statvfs(mp, &vfs) != 0) return; | ||
| 323 | + m->total_bytes = (unsigned long long)vfs.f_blocks * (unsigned long long)vfs.f_frsize; | ||
| 324 | + m->free_bytes = (unsigned long long)vfs.f_bfree * (unsigned long long)vfs.f_frsize; | ||
| 325 | + m->avail_bytes = (unsigned long long)vfs.f_bavail * (unsigned long long)vfs.f_frsize; | ||
| 326 | + m->used_bytes = m->total_bytes >= m->free_bytes ? m->total_bytes - m->free_bytes : 0; | ||
| 327 | + if (vfs.f_files > 0) { | ||
| 328 | + m->has_inodes = 1; | ||
| 329 | + m->inodes_total = (unsigned long long)vfs.f_files; | ||
| 330 | + m->inodes_used = m->inodes_total >= (unsigned long long)vfs.f_ffree | ||
| 331 | + ? m->inodes_total - (unsigned long long)vfs.f_ffree : 0; | ||
| 332 | + } | ||
| 333 | +} | ||
| 334 | + | ||
| 335 | +#endif /* !_WIN32 */ | ||
| 336 | + | ||
| 337 | +#if defined(__APPLE__) | ||
| 338 | + | ||
| 339 | +static int collect_mounts(mount_t *out, int max) | ||
| 340 | +{ | ||
| 341 | + struct statfs *mnt = NULL; | ||
| 342 | + int n, i, count = 0; | ||
| 343 | + | ||
| 344 | + n = getmntinfo(&mnt, MNT_NOWAIT); | ||
| 345 | + if (n <= 0) return 0; | ||
| 346 | + | ||
| 347 | + for (i = 0; i < n && count < max; i++) { | ||
| 348 | + mount_t *m = &out[count]; | ||
| 349 | + unsigned long long bs = (unsigned long long)mnt[i].f_bsize; | ||
| 350 | + if (pseudo_fstype(mnt[i].f_fstypename)) continue; | ||
| 351 | + if (pseudo_mountpoint(mnt[i].f_mntonname)) continue; | ||
| 352 | + memset(m, 0, sizeof(*m)); | ||
| 353 | + copy_str(m->device, sizeof(m->device), mnt[i].f_mntfromname); | ||
| 354 | + copy_str(m->fstype, sizeof(m->fstype), mnt[i].f_fstypename); | ||
| 355 | + copy_str(m->mount, sizeof(m->mount), mnt[i].f_mntonname); | ||
| 356 | + m->total_bytes = (unsigned long long)mnt[i].f_blocks * bs; | ||
| 357 | + m->free_bytes = (unsigned long long)mnt[i].f_bfree * bs; | ||
| 358 | + m->avail_bytes = (unsigned long long)mnt[i].f_bavail * bs; | ||
| 359 | + m->used_bytes = m->total_bytes >= m->free_bytes ? m->total_bytes - m->free_bytes : 0; | ||
| 360 | + if (mnt[i].f_files > 0) { | ||
| 361 | + m->has_inodes = 1; | ||
| 362 | + m->inodes_total = (unsigned long long)mnt[i].f_files; | ||
| 363 | + m->inodes_used = m->inodes_total >= (unsigned long long)mnt[i].f_ffree | ||
| 364 | + ? m->inodes_total - (unsigned long long)mnt[i].f_ffree : 0; | ||
| 365 | + } | ||
| 366 | + count++; | ||
| 367 | + } | ||
| 368 | + return count; | ||
| 369 | +} | ||
| 370 | + | ||
| 371 | +#elif defined(_WIN32) | ||
| 372 | + | ||
| 373 | +static int collect_mounts(mount_t *out, int max) | ||
| 374 | +{ | ||
| 375 | + char drives[512]; | ||
| 376 | + DWORD n; | ||
| 377 | + int count = 0; | ||
| 378 | + const char *p; | ||
| 379 | + | ||
| 380 | + n = GetLogicalDriveStringsA(sizeof(drives) - 1, drives); | ||
| 381 | + if (n == 0) return 0; | ||
| 382 | + | ||
| 383 | + for (p = drives; *p && count < max; p += strlen(p) + 1) { | ||
| 384 | + ULARGE_INTEGER avail, total, totalfree; | ||
| 385 | + char fsname[64] = "unknown"; | ||
| 386 | + mount_t *m; | ||
| 387 | + | ||
| 388 | + if (GetDriveTypeA(p) == DRIVE_NO_ROOT_DIR) continue; | ||
| 389 | + if (!GetDiskFreeSpaceExA(p, &avail, &total, &totalfree)) continue; | ||
| 390 | + | ||
| 391 | + m = &out[count]; | ||
| 392 | + memset(m, 0, sizeof(*m)); | ||
| 393 | + copy_str(m->device, sizeof(m->device), p); | ||
| 394 | + copy_str(m->mount, sizeof(m->mount), p); | ||
| 395 | + if (GetVolumeInformationA(p, NULL, 0, NULL, NULL, NULL, fsname, (DWORD)sizeof(fsname)) && fsname[0]) | ||
| 396 | + copy_str(m->fstype, sizeof(m->fstype), fsname); | ||
| 397 | + else | ||
| 398 | + copy_str(m->fstype, sizeof(m->fstype), "win32"); | ||
| 399 | + | ||
| 400 | + m->total_bytes = (unsigned long long)total.QuadPart; | ||
| 401 | + m->free_bytes = (unsigned long long)totalfree.QuadPart; | ||
| 402 | + m->avail_bytes = (unsigned long long)avail.QuadPart; | ||
| 403 | + m->used_bytes = m->total_bytes >= m->free_bytes ? m->total_bytes - m->free_bytes : 0; | ||
| 404 | + count++; | ||
| 405 | + } | ||
| 406 | + return count; | ||
| 407 | +} | ||
| 408 | + | ||
| 409 | +#else /* Linux and other POSIX */ | ||
| 410 | + | ||
| 411 | +static int collect_mounts(mount_t *out, int max) | ||
| 412 | +{ | ||
| 413 | + FILE *fp; | ||
| 414 | + char line[2048]; | ||
| 415 | + int count = 0; | ||
| 416 | + | ||
| 417 | + fp = fopen("/proc/mounts", "r"); | ||
| 418 | + if (!fp) fp = fopen("/etc/mtab", "r"); | ||
| 419 | + if (!fp) return 0; | ||
| 420 | + | ||
| 421 | + while (fgets(line, sizeof(line), fp) && count < max) { | ||
| 422 | + char dev[MAX_NAME], mp[MAX_PATH], fs[64]; | ||
| 423 | + int i = 0; | ||
| 424 | + char *tok[3]; | ||
| 425 | + char *p = line; | ||
| 426 | + | ||
| 427 | + /* split the first three whitespace-separated fields */ | ||
| 428 | + while (i < 3) { | ||
| 429 | + while (*p == ' ' || *p == '\t') p++; | ||
| 430 | + if (!*p || *p == '\n') break; | ||
| 431 | + tok[i++] = p; | ||
| 432 | + while (*p && *p != ' ' && *p != '\t' && *p != '\n') p++; | ||
| 433 | + if (*p) *p++ = '\0'; | ||
| 434 | + } | ||
| 435 | + if (i < 3) continue; | ||
| 436 | + | ||
| 437 | + copy_str(dev, sizeof(dev), tok[0]); | ||
| 438 | + copy_str(mp, sizeof(mp), tok[1]); | ||
| 439 | + copy_str(fs, sizeof(fs), tok[2]); | ||
| 440 | + unescape_mount_field(dev); | ||
| 441 | + unescape_mount_field(mp); | ||
| 442 | + | ||
| 443 | + if (pseudo_fstype(fs)) continue; | ||
| 444 | + if (pseudo_mountpoint(mp)) continue; | ||
| 445 | + | ||
| 446 | + /* /proc/mounts can list the same mountpoint more than once (a bind | ||
| 447 | + * mount, or a container overlay that repeats a host mount). Keep the | ||
| 448 | + * first entry per mountpoint so the dashboard does not double-count. */ | ||
| 449 | + { | ||
| 450 | + int dup = 0, k; | ||
| 451 | + for (k = 0; k < count; k++) { | ||
| 452 | + if (strcmp(out[k].mount, mp) == 0) { dup = 1; break; } | ||
| 453 | + } | ||
| 454 | + if (dup) continue; | ||
| 455 | + } | ||
| 456 | + | ||
| 457 | + memset(&out[count], 0, sizeof(out[count])); | ||
| 458 | + copy_str(out[count].device, sizeof(out[count].device), dev); | ||
| 459 | + copy_str(out[count].fstype, sizeof(out[count].fstype), fs); | ||
| 460 | + copy_str(out[count].mount, sizeof(out[count].mount), mp); | ||
| 461 | + fill_vfs(mp, &out[count]); | ||
| 462 | + count++; | ||
| 463 | + } | ||
| 464 | + fclose(fp); | ||
| 465 | + return count; | ||
| 466 | +} | ||
| 467 | + | ||
| 468 | +#endif | ||
| 469 | + | ||
| 470 | +/* Largest first. Used for display order. */ | ||
| 471 | +static int mount_cmp(const void *a, const void *b) | ||
| 472 | +{ | ||
| 473 | + const mount_t *x = (const mount_t *)a; | ||
| 474 | + const mount_t *y = (const mount_t *)b; | ||
| 475 | + if (x->total_bytes < y->total_bytes) return 1; | ||
| 476 | + if (x->total_bytes > y->total_bytes) return -1; | ||
| 477 | + return strcmp(x->mount, y->mount); | ||
| 478 | +} | ||
| 479 | + | ||
| 480 | +static const char *platform_name(void) | ||
| 481 | +{ | ||
| 482 | +#if defined(_WIN32) | ||
| 483 | + return "windows"; | ||
| 484 | +#elif defined(__APPLE__) | ||
| 485 | + return "macos"; | ||
| 486 | +#else | ||
| 487 | + return "linux"; | ||
| 488 | +#endif | ||
| 489 | +} | ||
| 490 | + | ||
| 491 | +/* ------------------------------------------------------------------ */ | ||
| 492 | +/* Bounded 1-level directory sizing */ | ||
| 493 | +/* ------------------------------------------------------------------ */ | ||
| 494 | + | ||
| 495 | +typedef struct { | ||
| 496 | + char name[MAX_NAME]; | ||
| 497 | + char path[MAX_PATH]; | ||
| 498 | + unsigned long long bytes; | ||
| 499 | + int is_dir; | ||
| 500 | +} dir_sz_t; | ||
| 501 | + | ||
| 502 | +typedef struct { | ||
| 503 | + unsigned long long visited; | ||
| 504 | + int truncated; | ||
| 505 | +} scan_state_t; | ||
| 506 | + | ||
| 507 | +static int skip_entry_name(const char *n) | ||
| 508 | +{ | ||
| 509 | + if (!n || !*n) return 1; | ||
| 510 | + if (strcmp(n, ".") == 0 || strcmp(n, "..") == 0) return 1; | ||
| 511 | + return 0; | ||
| 512 | +} | ||
| 513 | + | ||
| 514 | +#if defined(_WIN32) | ||
| 515 | + | ||
| 516 | +static unsigned long long sum_dir_win(const char *dir, int depth, scan_state_t *st) | ||
| 517 | +{ | ||
| 518 | + char pattern[MAX_PATH]; | ||
| 519 | + WIN32_FIND_DATAA fd; | ||
| 520 | + HANDLE h; | ||
| 521 | + unsigned long long total = 0; | ||
| 522 | + | ||
| 523 | + if (depth > MAX_DEPTH || st->truncated) return 0; | ||
| 524 | + sprintf(pattern, "%s\\*", dir); | ||
| 525 | + h = FindFirstFileA(pattern, &fd); | ||
| 526 | + if (h == INVALID_HANDLE_VALUE) return 0; | ||
| 527 | + | ||
| 528 | + do { | ||
| 529 | + char child[MAX_PATH]; | ||
| 530 | + if (skip_entry_name(fd.cFileName)) continue; | ||
| 531 | + if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) continue; | ||
| 532 | + if (++st->visited > MAX_SCAN_ENTRIES) { st->truncated = 1; break; } | ||
| 533 | + sprintf(child, "%s\\%s", dir, fd.cFileName); | ||
| 534 | + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) | ||
| 535 | + total += sum_dir_win(child, depth + 1, st); | ||
| 536 | + else | ||
| 537 | + total += ((unsigned long long)fd.nFileSizeHigh << 32) | (unsigned long long)fd.nFileSizeLow; | ||
| 538 | + } while (FindNextFileA(h, &fd)); | ||
| 539 | + | ||
| 540 | + FindClose(h); | ||
| 541 | + return total; | ||
| 542 | +} | ||
| 543 | + | ||
| 544 | +#else | ||
| 545 | + | ||
| 546 | +static unsigned long long sum_dir_posix(const char *dir, int depth, scan_state_t *st) | ||
| 547 | +{ | ||
| 548 | + DIR *d; | ||
| 549 | + struct dirent *e; | ||
| 550 | + unsigned long long total = 0; | ||
| 551 | + | ||
| 552 | + if (depth > MAX_DEPTH || st->truncated) return 0; | ||
| 553 | + d = opendir(dir); | ||
| 554 | + if (!d) return 0; | ||
| 555 | + | ||
| 556 | + while ((e = readdir(d)) != NULL) { | ||
| 557 | + char child[MAX_PATH]; | ||
| 558 | + struct stat sb; | ||
| 559 | + if (skip_entry_name(e->d_name)) continue; | ||
| 560 | + if (++st->visited > MAX_SCAN_ENTRIES) { st->truncated = 1; break; } | ||
| 561 | + if (snprintf(child, sizeof(child), "%s/%s", dir, e->d_name) >= (int)sizeof(child)) continue; | ||
| 562 | + /* lstat: symlinks are never followed, so a link back up the tree | ||
| 563 | + * cannot make the walk unbounded. */ | ||
| 564 | + if (lstat(child, &sb) != 0) continue; | ||
| 565 | + if (S_ISLNK(sb.st_mode)) continue; | ||
| 566 | + if (S_ISDIR(sb.st_mode)) | ||
| 567 | + total += sum_dir_posix(child, depth + 1, st); | ||
| 568 | + else if (S_ISREG(sb.st_mode)) | ||
| 569 | + total += (unsigned long long)sb.st_size; | ||
| 570 | + } | ||
| 571 | + closedir(d); | ||
| 572 | + return total; | ||
| 573 | +} | ||
| 574 | + | ||
| 575 | +#endif | ||
| 576 | + | ||
| 577 | +static int dir_cmp(const void *a, const void *b) | ||
| 578 | +{ | ||
| 579 | + const dir_sz_t *x = (const dir_sz_t *)a; | ||
| 580 | + const dir_sz_t *y = (const dir_sz_t *)b; | ||
| 581 | + if (x->bytes < y->bytes) return 1; | ||
| 582 | + if (x->bytes > y->bytes) return -1; | ||
| 583 | + return strcmp(x->name, y->name); | ||
| 584 | +} | ||
| 585 | + | ||
| 586 | +/* Resolve an allowlisted root token to a real path. | ||
| 587 | + * Returns 1 resolved, | ||
| 588 | + * 0 token is not an allowlisted root, | ||
| 589 | + * -1 token is allowlisted but the root does not exist on this node. */ | ||
| 590 | +static int resolve_root(const char *kind, char *out, size_t outsz, const char **label) | ||
| 591 | +{ | ||
| 592 | + if (!kind || !*kind) return 0; | ||
| 593 | + | ||
| 594 | + if (strcmp(kind, "workspace") == 0) { | ||
| 595 | + *label = "/workspace"; | ||
| 596 | +#if defined(_WIN32) | ||
| 597 | + return -1; /* no /workspace on a native Windows node */ | ||
| 598 | +#else | ||
| 599 | + if (access("/workspace", R_OK | X_OK) != 0) return -1; | ||
| 600 | + copy_str(out, outsz, "/workspace"); | ||
| 601 | + return 1; | ||
| 602 | +#endif | ||
| 603 | + } | ||
| 604 | + | ||
| 605 | + if (strcmp(kind, "home") == 0) { | ||
| 606 | +#if defined(_WIN32) | ||
| 607 | + const char *up = getenv("USERPROFILE"); | ||
| 608 | + if (!up || !*up) return -1; | ||
| 609 | + copy_str(out, outsz, up); | ||
| 610 | +#else | ||
| 611 | + const char *hp = getenv("HOME"); | ||
| 612 | + if (!hp || !*hp) return -1; | ||
| 613 | + copy_str(out, outsz, hp); | ||
| 614 | +#endif | ||
| 615 | + *label = "$HOME"; | ||
| 616 | + return 1; | ||
| 617 | + } | ||
| 618 | + | ||
| 619 | + return 0; | ||
| 620 | +} | ||
| 621 | + | ||
| 622 | +static int scan_root(const char *root, dir_sz_t *out, int max, int *count_out, int *truncated, int *root_kind) | ||
| 623 | +{ | ||
| 624 | + scan_state_t st; | ||
| 625 | + int count = 0; | ||
| 626 | + | ||
| 627 | + st.visited = 0; | ||
| 628 | + st.truncated = 0; | ||
| 629 | + *truncated = 0; | ||
| 630 | + *root_kind = 0; | ||
| 631 | + (void)root_kind; | ||
| 632 | + | ||
| 633 | +#if defined(_WIN32) | ||
| 634 | + { | ||
| 635 | + char pattern[MAX_PATH]; | ||
| 636 | + WIN32_FIND_DATAA fd; | ||
| 637 | + HANDLE h; | ||
| 638 | + sprintf(pattern, "%s\\*", root); | ||
| 639 | + h = FindFirstFileA(pattern, &fd); | ||
| 640 | + if (h == INVALID_HANDLE_VALUE) { *count_out = 0; return 0; } | ||
| 641 | + do { | ||
| 642 | + dir_sz_t *e; | ||
| 643 | + if (skip_entry_name(fd.cFileName)) continue; | ||
| 644 | + if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) continue; | ||
| 645 | + if (count >= max) { st.truncated = 1; break; } | ||
| 646 | + if (++st.visited > MAX_SCAN_ENTRIES) { st.truncated = 1; break; } | ||
| 647 | + e = &out[count]; | ||
| 648 | + memset(e, 0, sizeof(*e)); | ||
| 649 | + copy_str(e->name, sizeof(e->name), fd.cFileName); | ||
| 650 | + sprintf(e->path, "%s\\%s", root, fd.cFileName); | ||
| 651 | + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { | ||
| 652 | + e->is_dir = 1; | ||
| 653 | + e->bytes = sum_dir_win(e->path, 1, &st); | ||
| 654 | + } else { | ||
| 655 | + e->bytes = ((unsigned long long)fd.nFileSizeHigh << 32) | (unsigned long long)fd.nFileSizeLow; | ||
| 656 | + } | ||
| 657 | + count++; | ||
| 658 | + } while (FindNextFileA(h, &fd)); | ||
| 659 | + FindClose(h); | ||
| 660 | + } | ||
| 661 | +#else | ||
| 662 | + { | ||
| 663 | + DIR *d = opendir(root); | ||
| 664 | + struct dirent *de; | ||
| 665 | + if (!d) { *count_out = 0; return 0; } | ||
| 666 | + while ((de = readdir(d)) != NULL) { | ||
| 667 | + dir_sz_t *e; | ||
| 668 | + struct stat sb; | ||
| 669 | + char path[MAX_PATH]; | ||
| 670 | + if (skip_entry_name(de->d_name)) continue; | ||
| 671 | + if (count >= max) { st.truncated = 1; break; } | ||
| 672 | + if (++st.visited > MAX_SCAN_ENTRIES) { st.truncated = 1; break; } | ||
| 673 | + if (snprintf(path, sizeof(path), "%s/%s", root, de->d_name) >= (int)sizeof(path)) continue; | ||
| 674 | + if (lstat(path, &sb) != 0) continue; | ||
| 675 | + if (S_ISLNK(sb.st_mode)) continue; | ||
| 676 | + e = &out[count]; | ||
| 677 | + memset(e, 0, sizeof(*e)); | ||
| 678 | + copy_str(e->name, sizeof(e->name), de->d_name); | ||
| 679 | + copy_str(e->path, sizeof(e->path), path); | ||
| 680 | + if (S_ISDIR(sb.st_mode)) { | ||
| 681 | + e->is_dir = 1; | ||
| 682 | + e->bytes = sum_dir_posix(path, 1, &st); | ||
| 683 | + } else if (S_ISREG(sb.st_mode)) { | ||
| 684 | + e->bytes = (unsigned long long)sb.st_size; | ||
| 685 | + } | ||
| 686 | + count++; | ||
| 687 | + } | ||
| 688 | + closedir(d); | ||
| 689 | + } | ||
| 690 | +#endif | ||
| 691 | + | ||
| 692 | + if (count > 1) qsort(out, (size_t)count, sizeof(out[0]), dir_cmp); | ||
| 693 | + *truncated = st.truncated; | ||
| 694 | + *count_out = count; | ||
| 695 | + return 1; | ||
| 696 | +} | ||
| 697 | + | ||
| 698 | +/* ------------------------------------------------------------------ */ | ||
| 699 | +/* Modes */ | ||
| 700 | +/* ------------------------------------------------------------------ */ | ||
| 701 | + | ||
| 702 | +static int mode_meta(void) | ||
| 703 | +{ | ||
| 704 | + puts("{\"name\":\"disks\",\"desc\":\"Local storage\"}"); | ||
| 705 | + return 0; | ||
| 706 | +} | ||
| 707 | + | ||
| 708 | +static void json_header(void) | ||
| 709 | +{ | ||
| 710 | + /* Deliberately no Content-Length - the server owns framing. */ | ||
| 711 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | ||
| 712 | + "Cache-Control: no-store\r\n" | ||
| 713 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 714 | +} | ||
| 715 | + | ||
| 716 | +static void emit_mounts(void) | ||
| 717 | +{ | ||
| 718 | + mount_t mnt[MAX_MOUNTS]; | ||
| 719 | + int i, n; | ||
| 720 | + | ||
| 721 | + memset(mnt, 0, sizeof(mnt)); | ||
| 722 | + n = collect_mounts(mnt, MAX_MOUNTS); | ||
| 723 | + if (n > 1) qsort(mnt, (size_t)n, sizeof(mnt[0]), mount_cmp); | ||
| 724 | + | ||
| 725 | + fputs("[", stdout); | ||
| 726 | + for (i = 0; i < n; i++) { | ||
| 727 | + const mount_t *m = &mnt[i]; | ||
| 728 | + double pct = 0.0, ipct = 0.0; | ||
| 729 | + if (m->used_bytes + m->avail_bytes > 0) | ||
| 730 | + pct = (double)m->used_bytes * 100.0 / (double)(m->used_bytes + m->avail_bytes); | ||
| 731 | + if (m->has_inodes && m->inodes_total > 0) | ||
| 732 | + ipct = (double)m->inodes_used * 100.0 / (double)m->inodes_total; | ||
| 733 | + | ||
| 734 | + if (i) fputs(",", stdout); | ||
| 735 | + fputs("{\"device\":", stdout); | ||
| 736 | + json_str(m->device); | ||
| 737 | + fputs(",\"fstype\":", stdout); | ||
| 738 | + json_str(m->fstype); | ||
| 739 | + fputs(",\"mount\":", stdout); | ||
| 740 | + json_str(m->mount); | ||
| 741 | + printf(",\"total_bytes\":%llu,\"used_bytes\":%llu,\"free_bytes\":%llu," | ||
| 742 | + "\"avail_bytes\":%llu,\"pct\":%.1f", | ||
| 743 | + m->total_bytes, m->used_bytes, m->free_bytes, m->avail_bytes, | ||
| 744 | + clamp_pct(pct)); | ||
| 745 | + printf(",\"inodes_total\":%llu,\"inodes_used\":%llu," | ||
| 746 | + "\"inodes_pct\":%.1f,\"has_inodes\":%s}", | ||
| 747 | + m->inodes_total, m->inodes_used, clamp_pct(ipct), | ||
| 748 | + m->has_inodes ? "true" : "false"); | ||
| 749 | + } | ||
| 750 | + fputs("]", stdout); | ||
| 751 | +} | ||
| 752 | + | ||
| 753 | +static int mode_json(const char *qs) | ||
| 754 | +{ | ||
| 755 | + char action[64]; | ||
| 756 | + char rootkind[32]; | ||
| 757 | + char utc[40]; | ||
| 758 | + | ||
| 759 | + action[0] = rootkind[0] = '\0'; | ||
| 760 | + get_query_val(qs, "action", action, sizeof(action)); | ||
| 761 | + get_query_val(qs, "root", rootkind, sizeof(rootkind)); | ||
| 762 | + | ||
| 763 | + if (action[0] && strcmp(action, "mounts") != 0 && | ||
| 764 | + strcmp(action, "dirs") != 0 && strcmp(action, "info") != 0) { | ||
| 765 | + json_header(); | ||
| 766 | + printf("{\"ok\":false,\"error\":\"unknown_action\"," | ||
| 767 | + "\"supported\":[\"mounts\",\"dirs\",\"info\"],\"requested\":"); | ||
| 768 | + json_str(action); | ||
| 769 | + fputs("}\n", stdout); | ||
| 770 | + return 0; | ||
| 771 | + } | ||
| 772 | + if (!action[0]) copy_str(action, sizeof(action), "mounts"); | ||
| 773 | + | ||
| 774 | + utc_now(utc, sizeof(utc)); | ||
| 775 | + | ||
| 776 | + if (strcmp(action, "info") == 0) { | ||
| 777 | + json_header(); | ||
| 778 | + fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," | ||
| 779 | + "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout); | ||
| 780 | + json_str(platform_name()); | ||
| 781 | + fputs(",\"pid\":", stdout); | ||
| 782 | + printf("%ld", node_pid()); | ||
| 783 | + fputs(",\"utc\":", stdout); | ||
| 784 | + json_str(utc); | ||
| 785 | + fputs(",\"node_auth\":", stdout); | ||
| 786 | + { | ||
| 787 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 788 | + fputs((np && *np) ? "true" : "false", stdout); | ||
| 789 | + } | ||
| 790 | + fputs(",\"supported\":[\"mounts\",\"dirs\",\"info\"],\"zero_network\":true," | ||
| 791 | + "\"allowed_roots\":[\"workspace\",\"home\"]," | ||
| 792 | + "\"max_depth\":", stdout); | ||
| 793 | + printf("%d", MAX_DEPTH); | ||
| 794 | + fputs(",\"max_scan_entries\":", stdout); | ||
| 795 | + printf("%d", MAX_SCAN_ENTRIES); | ||
| 796 | + fputs("}\n", stdout); | ||
| 797 | + return 0; | ||
| 798 | + } | ||
| 799 | + | ||
| 800 | + if (strcmp(action, "dirs") == 0) { | ||
| 801 | + char root[MAX_PATH]; | ||
| 802 | + const char *label = ""; | ||
| 803 | + dir_sz_t *dirs; | ||
| 804 | + int count = 0, truncated = 0, kind = 0; | ||
| 805 | + long long t0, t1; | ||
| 806 | + unsigned long long total_bytes = 0, used_bytes = 0, free_bytes = 0; | ||
| 807 | + double root_pct = 0.0; | ||
| 808 | + int i; | ||
| 809 | + | ||
| 810 | + if (!rootkind[0]) { | ||
| 811 | + json_header(); | ||
| 812 | + fputs("{\"ok\":false,\"error\":\"missing_root\"," | ||
| 813 | + "\"allowed_roots\":[\"workspace\",\"home\"]}\n", stdout); | ||
| 814 | + return 0; | ||
| 815 | + } | ||
| 816 | + /* Strict allowlist: an arbitrary path can never be walked. */ | ||
| 817 | + { | ||
| 818 | + int rv = resolve_root(rootkind, root, sizeof(root), &label); | ||
| 819 | + if (rv == 0) { | ||
| 820 | + json_header(); | ||
| 821 | + fputs("{\"ok\":false,\"error\":\"root_not_allowed\"," | ||
| 822 | + "\"allowed_roots\":[\"workspace\",\"home\"],\"requested\":", stdout); | ||
| 823 | + json_str(rootkind); | ||
| 824 | + fputs("}\n", stdout); | ||
| 825 | + return 0; | ||
| 826 | + } | ||
| 827 | + if (rv < 0) { | ||
| 828 | + json_header(); | ||
| 829 | + fputs("{\"ok\":false,\"error\":\"root_unavailable\"," | ||
| 830 | + "\"allowed_roots\":[\"workspace\",\"home\"],\"requested\":", stdout); | ||
| 831 | + json_str(rootkind); | ||
| 832 | + fputs(",\"message\":\"this root does not exist on this node\"}\n", stdout); | ||
| 833 | + return 0; | ||
| 834 | + } | ||
| 835 | + } | ||
| 836 | + | ||
| 837 | +#if !defined(_WIN32) | ||
| 838 | + { | ||
| 839 | + struct statvfs vfs; | ||
| 840 | + if (statvfs(root, &vfs) == 0) { | ||
| 841 | + total_bytes = (unsigned long long)vfs.f_blocks * (unsigned long long)vfs.f_frsize; | ||
| 842 | + free_bytes = (unsigned long long)vfs.f_bfree * (unsigned long long)vfs.f_frsize; | ||
| 843 | + used_bytes = total_bytes >= free_bytes ? total_bytes - free_bytes : 0; | ||
| 844 | + if (used_bytes + (unsigned long long)vfs.f_bavail * (unsigned long long)vfs.f_frsize > 0) | ||
| 845 | + root_pct = (double)used_bytes * 100.0 / | ||
| 846 | + (double)(used_bytes + (unsigned long long)vfs.f_bavail * (unsigned long long)vfs.f_frsize); | ||
| 847 | + } | ||
| 848 | + } | ||
| 849 | +#endif | ||
| 850 | + | ||
| 851 | + dirs = (dir_sz_t *)calloc((size_t)MAX_DIRS, sizeof(dir_sz_t)); | ||
| 852 | + if (!dirs) { | ||
| 853 | + json_header(); | ||
| 854 | + fputs("{\"ok\":false,\"error\":\"out_of_memory\"}\n", stdout); | ||
| 855 | + return 0; | ||
| 856 | + } | ||
| 857 | + | ||
| 858 | + t0 = now_ms(); | ||
| 859 | + scan_root(root, dirs, MAX_DIRS, &count, &truncated, &kind); | ||
| 860 | + t1 = now_ms(); | ||
| 861 | + | ||
| 862 | + json_header(); | ||
| 863 | + fputs("{\"ok\":true,\"action\":\"dirs\",\"plugin\":\"" PLUGIN_ID "\"," | ||
| 864 | + "\"platform\":", stdout); | ||
| 865 | + json_str(platform_name()); | ||
| 866 | + fputs(",\"root_kind\":", stdout); | ||
| 867 | + json_str(rootkind); | ||
| 868 | + fputs(",\"root\":", stdout); | ||
| 869 | + json_str(root); | ||
| 870 | + fputs(",\"root_label\":", stdout); | ||
| 871 | + json_str(label); | ||
| 872 | + printf(",\"root_total_bytes\":%llu,\"root_used_bytes\":%llu," | ||
| 873 | + "\"root_free_bytes\":%llu,\"root_pct\":%.1f", | ||
| 874 | + total_bytes, used_bytes, free_bytes, clamp_pct(root_pct)); | ||
| 875 | + printf(",\"count\":%d,\"truncated\":%s,\"max_depth\":%d," | ||
| 876 | + "\"max_scan_entries\":%d,\"scan_ms\":%lld,\"utc\":", | ||
| 877 | + count, truncated ? "true" : "false", MAX_DEPTH, MAX_SCAN_ENTRIES, t1 - t0); | ||
| 878 | + json_str(utc); | ||
| 879 | + fputs(",\"entries\":[", stdout); | ||
| 880 | + for (i = 0; i < count; i++) { | ||
| 881 | + double pct = total_bytes > 0 | ||
| 882 | + ? (double)dirs[i].bytes * 100.0 / (double)total_bytes : 0.0; | ||
| 883 | + if (i) fputs(",", stdout); | ||
| 884 | + fputs("{\"name\":", stdout); | ||
| 885 | + json_str(dirs[i].name); | ||
| 886 | + fputs(",\"path\":", stdout); | ||
| 887 | + json_str(dirs[i].path); | ||
| 888 | + printf(",\"bytes\":%llu,\"pct\":%.1f,\"is_dir\":%s}", | ||
| 889 | + dirs[i].bytes, clamp_pct(pct), dirs[i].is_dir ? "true" : "false"); | ||
| 890 | + } | ||
| 891 | + fputs("]}\n", stdout); | ||
| 892 | + free(dirs); | ||
| 893 | + return 0; | ||
| 894 | + } | ||
| 895 | + | ||
| 896 | + /* action == mounts */ | ||
| 897 | + { | ||
| 898 | + mount_t probe[MAX_MOUNTS]; | ||
| 899 | + int n; | ||
| 900 | + memset(probe, 0, sizeof(probe)); | ||
| 901 | + n = collect_mounts(probe, MAX_MOUNTS); | ||
| 902 | + json_header(); | ||
| 903 | + fputs("{\"ok\":true,\"action\":\"mounts\",\"plugin\":\"" PLUGIN_ID "\"," | ||
| 904 | + "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout); | ||
| 905 | + json_str(platform_name()); | ||
| 906 | + printf(",\"pid\":%ld,\"count\":%d,\"utc\":", node_pid(), n); | ||
| 907 | + json_str(utc); | ||
| 908 | + fputs(",\"zero_network\":true,\"mounts\":", stdout); | ||
| 909 | + emit_mounts(); | ||
| 910 | + fputs("}\n", stdout); | ||
| 911 | + } | ||
| 912 | + return 0; | ||
| 913 | +} | ||
| 914 | + | ||
| 915 | +/* ------------------------------------------------------------------ */ | ||
| 916 | +/* HTML UI */ | ||
| 917 | +/* ------------------------------------------------------------------ */ | ||
| 918 | + | ||
| 919 | +static int mode_html(int embed) | ||
| 920 | +{ | ||
| 921 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | ||
| 922 | + "Cache-Control: no-store\r\n" | ||
| 923 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 924 | + | ||
| 925 | + fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>" | ||
| 926 | + "<meta name='viewport' content='width=device-width,initial-scale=1'>" | ||
| 927 | + "<title>disks</title><style>", stdout); | ||
| 928 | + | ||
| 929 | + fputs( | ||
| 930 | +":root{color-scheme:dark light;" | ||
| 931 | + "--bg:#0b0b0e;--surface:#141419;--surface2:#1c1c22;--text:#f5f5f7;" | ||
| 932 | + "--muted:#8e8e96;--line:rgba(255,255,255,.10);--accent:#0a84ff;" | ||
| 933 | + "--ok:#30d158;--warn:#ffd60a;--danger:#ff453a;" | ||
| 934 | + "--mono:ui-monospace,SFMono-Regular,Menlo,monospace}" | ||
| 935 | +"html[data-theme=light]{--bg:#f2f2f6;--surface:#ffffff;--surface2:#f0f0f4;" | ||
| 936 | + "--text:#1c1c1e;--muted:#6b6b73;--line:rgba(0,0,0,.10)}" | ||
| 937 | +"*{box-sizing:border-box}" | ||
| 938 | +"body{margin:0;padding:16px;background:var(--bg);color:var(--text);" | ||
| 939 | + "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;" | ||
| 940 | + "font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}" | ||
| 941 | +".wrap{max-width:1120px;margin:0 auto;min-width:0}" | ||
| 942 | +".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" | ||
| 943 | +".title{font-size:20px;font-weight:700;margin:0}" | ||
| 944 | +".sub{color:var(--muted);font-size:12px;font-family:var(--mono);" | ||
| 945 | + "overflow-wrap:anywhere}" | ||
| 946 | +".spacer{flex:1}" | ||
| 947 | +".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;" | ||
| 948 | + "background:var(--surface2);color:var(--muted);border:1px solid var(--line);" | ||
| 949 | + "white-space:nowrap}" | ||
| 950 | +".pill.live{color:var(--ok);border-color:rgba(48,209,88,.4)}" | ||
| 951 | +".pill.warn{color:var(--warn);border-color:rgba(255,214,10,.4)}" | ||
| 952 | +".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;" | ||
| 953 | + "padding:16px;margin-bottom:14px;min-width:0}" | ||
| 954 | +".card h2{margin:0 0 12px;font-size:12px;letter-spacing:.06em;" | ||
| 955 | + "text-transform:uppercase;color:var(--muted);font-weight:600}" | ||
| 956 | +".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(132px,1fr));gap:10px}" | ||
| 957 | +".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" | ||
| 958 | + "padding:10px 12px;min-width:0}" | ||
| 959 | +".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}" | ||
| 960 | +".kpi .v{font-size:19px;font-weight:700;font-family:var(--mono);margin-top:2px;" | ||
| 961 | + "overflow:hidden;text-overflow:ellipsis;white-space:nowrap}" | ||
| 962 | +"button{background:var(--accent);color:#fff;border:0;border-radius:999px;" | ||
| 963 | + "padding:6px 13px;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" | ||
| 964 | +"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" | ||
| 965 | +"button:active{transform:scale(.98)}" | ||
| 966 | +".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" | ||
| 967 | +".seg{display:inline-flex;gap:4px;background:var(--surface2);" | ||
| 968 | + "border:1px solid var(--line);border-radius:999px;padding:3px}" | ||
| 969 | +".seg button{background:transparent;color:var(--muted);border:0;padding:4px 11px;font-size:12px}" | ||
| 970 | +".seg button.on{background:var(--accent);color:#fff}" | ||
| 971 | +".mnt{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" | ||
| 972 | + "padding:10px 12px;margin-bottom:8px;min-width:0}" | ||
| 973 | +".mnt .h{display:flex;gap:8px;align-items:baseline;flex-wrap:wrap}" | ||
| 974 | +".mnt .mp{font-family:var(--mono);font-weight:700;font-size:13px;" | ||
| 975 | + "overflow-wrap:anywhere;min-width:0}" | ||
| 976 | +".mnt .meta{color:var(--muted);font-size:11px;font-family:var(--mono);" | ||
| 977 | + "overflow-wrap:anywhere;min-width:0}" | ||
| 978 | +".bar{height:8px;border-radius:4px;background:rgba(255,255,255,.10);" | ||
| 979 | + "overflow:hidden;margin:7px 0 5px}" | ||
| 980 | +".bar .fill{height:100%;border-radius:4px;background:var(--ok);transition:width .35s}" | ||
| 981 | +".bar .fill.warn{background:var(--warn)}" | ||
| 982 | +".bar .fill.danger{background:var(--danger)}" | ||
| 983 | +".nums{display:flex;justify-content:space-between;gap:8px;font-size:11px;" | ||
| 984 | + "font-family:var(--mono);color:var(--muted);flex-wrap:wrap}" | ||
| 985 | +".tblwrap{overflow-x:auto;-webkit-overflow-scrolling:touch}" | ||
| 986 | +"table{width:100%;border-collapse:collapse;font-size:13px}" | ||
| 987 | +"th,td{text-align:left;padding:7px 8px;border-bottom:1px solid var(--line)}" | ||
| 988 | +"th{font-size:11px;text-transform:uppercase;letter-spacing:.05em;" | ||
| 989 | + "color:var(--muted);font-weight:600;white-space:nowrap}" | ||
| 990 | +"td.num,th.num{text-align:right;font-family:var(--mono);white-space:nowrap}" | ||
| 991 | +"td.nm{overflow-wrap:anywhere}" | ||
| 992 | +".muted{color:var(--muted)}" | ||
| 993 | +".hide{display:none}" | ||
| 994 | +"@media(max-width:560px){body{padding:12px}.card{padding:12px}" | ||
| 995 | + "th.hide-sm,td.hide-sm{display:none}.kpi .v{font-size:17px}}", | ||
| 996 | + stdout); | ||
| 997 | + | ||
| 998 | + fputs("</style></head><body><div class='wrap'>", stdout); | ||
| 999 | + | ||
| 1000 | + fputs("<div class='top'>" | ||
| 1001 | + "<h1 class='title'>disks</h1>" | ||
| 1002 | + "<span class='pill' id='pPlatform'>—</span>" | ||
| 1003 | + "<span class='pill' id='pState'>loading</span>" | ||
| 1004 | + "<span class='spacer'></span>" | ||
| 1005 | + "<div class='seg' id='segRate'>" | ||
| 1006 | + "<button type='button' data-ms='0' class='on'>Paused</button>" | ||
| 1007 | + "<button type='button' data-ms='5000'>5s</button>" | ||
| 1008 | + "<button type='button' data-ms='15000'>15s</button>" | ||
| 1009 | + "</div>" | ||
| 1010 | + "<button type='button' class='ghost' id='btnRefresh'>Refresh</button>" | ||
| 1011 | + "</div>", stdout); | ||
| 1012 | + | ||
| 1013 | + /* summary */ | ||
| 1014 | + fputs("<div class='card'><h2>Storage summary</h2>" | ||
| 1015 | + "<div class='grid'>" | ||
| 1016 | + "<div class='kpi'><div class='k'>filesystems</div><div class='v' id='kCount'>—</div></div>" | ||
| 1017 | + "<div class='kpi'><div class='k'>total capacity</div><div class='v' id='kTotal'>—</div></div>" | ||
| 1018 | + "<div class='kpi'><div class='k'>used</div><div class='v' id='kUsed'>—</div></div>" | ||
| 1019 | + "<div class='kpi'><div class='k'>free</div><div class='v' id='kFree'>—</div></div>" | ||
| 1020 | + "<div class='kpi'><div class='k'>most full</div><div class='v' id='kFull'>—</div></div>" | ||
| 1021 | + "</div>" | ||
| 1022 | + "<div class='sub' id='nodeLine' style='margin-top:10px'></div></div>", stdout); | ||
| 1023 | + | ||
| 1024 | + /* mounts */ | ||
| 1025 | + fputs("<div class='card'><h2>Mounted filesystems</h2>" | ||
| 1026 | + "<div id='mounts'></div>" | ||
| 1027 | + "<div id='mountEmpty' class='muted hide'>No local filesystems reported.</div></div>", stdout); | ||
| 1028 | + | ||
| 1029 | + /* dirs */ | ||
| 1030 | + fputs("<div class='card'><h2>Folder breakdown</h2>" | ||
| 1031 | + "<div class='row' style='margin-bottom:12px'>" | ||
| 1032 | + "<div class='seg' id='segRoot'>" | ||
| 1033 | + "<button type='button' data-root='workspace' class='on'>/workspace</button>" | ||
| 1034 | + "<button type='button' data-root='home'>HOME</button>" | ||
| 1035 | + "</div>" | ||
| 1036 | + "<span class='sub' id='dirNote'></span></div>" | ||
| 1037 | + "<div class='tblwrap'><table><thead><tr>" | ||
| 1038 | + "<th>Name</th><th class='num'>Size</th><th class='num'>Share</th>" | ||
| 1039 | + "<th class='num hide-sm'>Type</th>" | ||
| 1040 | + "</tr></thead><tbody id='rows'></tbody></table></div>" | ||
| 1041 | + "<div id='dirEmpty' class='muted hide'>Nothing to show for this root.</div></div>", stdout); | ||
| 1042 | + | ||
| 1043 | + fputs("<div class='card'><h2>About this plugin</h2>" | ||
| 1044 | + "<p class='muted' style='margin:0 0 8px'>Local node only. Reads " | ||
| 1045 | + "<code>/proc/mounts</code> and <code>statvfs</code> on Linux, " | ||
| 1046 | + "<code>getmntinfo</code> on macOS and <code>GetLogicalDriveStringsA</code> " | ||
| 1047 | + "on Windows. Makes zero outbound network requests.</p>" | ||
| 1048 | + "<p class='muted' style='margin:0'>Folder sizes are a bounded walk of one " | ||
| 1049 | + "of two allowlisted roots; symlinks are never followed, depth is capped and " | ||
| 1050 | + "the walk stops after a fixed number of entries.</p></div>", stdout); | ||
| 1051 | + | ||
| 1052 | + if (!embed) { | ||
| 1053 | + fputs("<div class='sub' style='margin-bottom:14px'>" | ||
| 1054 | + "Opened directly from the node API.</div>", stdout); | ||
| 1055 | + } | ||
| 1056 | + | ||
| 1057 | + fputs("<script>\n(function(){\n", stdout); | ||
| 1058 | + | ||
| 1059 | + fputs( | ||
| 1060 | +" var q = new URLSearchParams(location.search);\n" | ||
| 1061 | +" var HUB = q.get('plugin') || '';\n" | ||
| 1062 | +" var node = q.get('node') || '';\n" | ||
| 1063 | +" var sid = q.get('id') || '';\n" | ||
| 1064 | +" var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" | ||
| 1065 | +" localStorage.getItem('bot_active_pwd') || '';\n" | ||
| 1066 | +" var RATE = 0, TIMER = null, BUSY = false, ROOT = 'workspace';\n" | ||
| 1067 | +"\n" | ||
| 1068 | +" /* Two routes, and getting this wrong is the classic plugin bug:\n" | ||
| 1069 | +" page served through the hub -> call the hub proxy back\n" | ||
| 1070 | +" page opened directly on node -> the plugin IS the route */\n" | ||
| 1071 | +" function base(action){\n" | ||
| 1072 | +" if (HUB) return '/plugins?plugin=' + encodeURIComponent(HUB) + '&action=' + encodeURIComponent(action);\n" | ||
| 1073 | +" return '/" PLUGIN_ID "?action=' + encodeURIComponent(action);\n" | ||
| 1074 | +" }\n" | ||
| 1075 | +" function withCtx(u){\n" | ||
| 1076 | +" if (node) u += '&node=' + encodeURIComponent(node);\n" | ||
| 1077 | +" if (sid) u += '&id=' + encodeURIComponent(sid);\n" | ||
| 1078 | +" if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n" | ||
| 1079 | +" return u;\n" | ||
| 1080 | +" }\n" | ||
| 1081 | +" function hdr(){ return pwd ? {'X-Bot-Password': pwd} : {}; }\n" | ||
| 1082 | +" function $(id){ return document.getElementById(id); }\n" | ||
| 1083 | +" function txt(id, v){ var e = $(id); if (e) e.textContent = (v === undefined || v === null) ? '' : v; }\n" | ||
| 1084 | +" function bytes(n){\n" | ||
| 1085 | +" if (n === null || n === undefined) return '\\u2014';\n" | ||
| 1086 | +" var u = ['B','KB','MB','GB','TB','PB'], i = 0, v = n;\n" | ||
| 1087 | +" while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }\n" | ||
| 1088 | +" return (i === 0 ? v.toFixed(0) : v.toFixed(v >= 100 ? 0 : 1)) + ' ' + u[i];\n" | ||
| 1089 | +" }\n" | ||
| 1090 | +" function cls(p){ return p >= 90 ? 'danger' : (p >= 75 ? 'warn' : ''); }\n" | ||
| 1091 | +" function el(tag, c, t){\n" | ||
| 1092 | +" var e = document.createElement(tag);\n" | ||
| 1093 | +" if (c) e.className = c;\n" | ||
| 1094 | +" if (t !== undefined) e.textContent = t;\n" | ||
| 1095 | +" return e;\n" | ||
| 1096 | +" }\n" | ||
| 1097 | +"\n" | ||
| 1098 | +" function renderMounts(m){\n" | ||
| 1099 | +" var box = $('mounts');\n" | ||
| 1100 | +" box.textContent = '';\n" | ||
| 1101 | +" var total = 0, used = 0, free = 0, worst = null;\n" | ||
| 1102 | +" (m.mounts || []).forEach(function(x){\n" | ||
| 1103 | +" total += x.total_bytes; used += x.used_bytes; free += x.free_bytes;\n" | ||
| 1104 | +" if (!worst || x.pct > worst.pct) worst = x;\n" | ||
| 1105 | +" var card = el('div','mnt');\n" | ||
| 1106 | +" var h = el('div','h');\n" | ||
| 1107 | +" h.appendChild(el('span','mp', x.mount));\n" | ||
| 1108 | +" h.appendChild(el('span','meta', x.device + ' \\u00b7 ' + x.fstype));\n" | ||
| 1109 | +" h.appendChild(el('span','meta', x.pct.toFixed(0) + '%'));\n" | ||
| 1110 | +" card.appendChild(h);\n" | ||
| 1111 | +" var bar = el('div','bar');\n" | ||
| 1112 | +" var fill = el('div','fill ' + cls(x.pct));\n" | ||
| 1113 | +" fill.style.width = Math.max(0, Math.min(100, x.pct)) + '%';\n" | ||
| 1114 | +" bar.appendChild(fill);\n" | ||
| 1115 | +" card.appendChild(bar);\n" | ||
| 1116 | +" var nums = el('div','nums');\n" | ||
| 1117 | +" nums.appendChild(el('span', null, bytes(x.used_bytes) + ' used'));\n" | ||
| 1118 | +" nums.appendChild(el('span', null, bytes(x.avail_bytes) + ' free'));\n" | ||
| 1119 | +" nums.appendChild(el('span', null, bytes(x.total_bytes) + ' total'));\n" | ||
| 1120 | +" nums.appendChild(el('span', null,\n" | ||
| 1121 | +" x.has_inodes ? ('inodes ' + x.inodes_pct.toFixed(0) + '%') : 'inodes n/a'));\n" | ||
| 1122 | +" card.appendChild(nums);\n" | ||
| 1123 | +" box.appendChild(card);\n" | ||
| 1124 | +" });\n" | ||
| 1125 | +" if ((m.mounts || []).length) $('mountEmpty').classList.add('hide');\n" | ||
| 1126 | +" else $('mountEmpty').classList.remove('hide');\n" | ||
| 1127 | +" txt('kCount', m.count);\n" | ||
| 1128 | +" txt('kTotal', bytes(total));\n" | ||
| 1129 | +" txt('kUsed', bytes(used));\n" | ||
| 1130 | +" txt('kFree', bytes(free));\n" | ||
| 1131 | +" txt('kFull', worst ? (worst.mount + ' ' + worst.pct.toFixed(0) + '%') : '\\u2014');\n" | ||
| 1132 | +" }\n" | ||
| 1133 | +"\n" | ||
| 1134 | +" function renderDirs(d, ok){\n" | ||
| 1135 | +" var body = $('rows');\n" | ||
| 1136 | +" body.textContent = '';\n" | ||
| 1137 | +" if (!ok){\n" | ||
| 1138 | +" $('dirEmpty').classList.remove('hide');\n" | ||
| 1139 | +" txt('dirNote', d && d.error ? ('unavailable: ' + d.error) : 'unavailable');\n" | ||
| 1140 | +" return;\n" | ||
| 1141 | +" }\n" | ||
| 1142 | +" var entries = d.entries || [];\n" | ||
| 1143 | +" entries.forEach(function(e){\n" | ||
| 1144 | +" var tr = el('tr');\n" | ||
| 1145 | +" tr.appendChild(el('td','nm', e.name));\n" | ||
| 1146 | +" tr.appendChild(el('td','num', bytes(e.bytes)));\n" | ||
| 1147 | +" tr.appendChild(el('td','num', e.pct.toFixed(1) + '%'));\n" | ||
| 1148 | +" tr.appendChild(el('td','num hide-sm', e.is_dir ? 'dir' : 'file'));\n" | ||
| 1149 | +" body.appendChild(tr);\n" | ||
| 1150 | +" });\n" | ||
| 1151 | +" if (entries.length) $('dirEmpty').classList.add('hide');\n" | ||
| 1152 | +" else $('dirEmpty').classList.remove('hide');\n" | ||
| 1153 | +" txt('dirNote', d.root + ' \\u00b7 ' + bytes(d.root_used_bytes) + ' used of ' +\n" | ||
| 1154 | +" bytes(d.root_total_bytes) + ' \\u00b7 ' + entries.length + ' entries \\u00b7 ' +\n" | ||
| 1155 | +" d.scan_ms + ' ms' + (d.truncated ? ' \\u00b7 truncated' : ''));\n" | ||
| 1156 | +" }\n" | ||
| 1157 | +"\n" | ||
| 1158 | +" function loadDirs(){\n" | ||
| 1159 | +" var u = withCtx(base('dirs')) + '&root=' + encodeURIComponent(ROOT);\n" | ||
| 1160 | +" return fetch(u, { headers: hdr(), cache: 'no-store' })\n" | ||
| 1161 | +" .then(function(r){ return r.json(); })\n" | ||
| 1162 | +" .then(function(d){ renderDirs(d, d && d.ok === true); })\n" | ||
| 1163 | +" .catch(function(e){ renderDirs({error: String(e)}, false); });\n" | ||
| 1164 | +" }\n" | ||
| 1165 | +"\n" | ||
| 1166 | +" function poll(){\n" | ||
| 1167 | +" if (BUSY) return;\n" | ||
| 1168 | +" BUSY = true;\n" | ||
| 1169 | +" fetch(withCtx(base('mounts')), { headers: hdr(), cache: 'no-store' })\n" | ||
| 1170 | +" .then(function(r){ return r.json(); })\n" | ||
| 1171 | +" .then(function(d){\n" | ||
| 1172 | +" if (!d || d.ok === false){ txt('pState', 'error'); return; }\n" | ||
| 1173 | +" txt('pPlatform', d.platform);\n" | ||
| 1174 | +" txt('nodeLine', 'plugin ' + d.plugin + ' v' + d.version +\n" | ||
| 1175 | +" ' \\u00b7 pid ' + d.pid + ' \\u00b7 ' + d.utc +\n" | ||
| 1176 | +" ' \\u00b7 zero outbound network');\n" | ||
| 1177 | +" renderMounts(d);\n" | ||
| 1178 | +" })\n" | ||
| 1179 | +" .catch(function(){ txt('pState', 'error'); })\n" | ||
| 1180 | +" .then(function(){ BUSY = false; });\n" | ||
| 1181 | +" loadDirs();\n" | ||
| 1182 | +" }\n" | ||
| 1183 | +"\n" | ||
| 1184 | +" function schedule(){\n" | ||
| 1185 | +" if (TIMER) { clearInterval(TIMER); TIMER = null; }\n" | ||
| 1186 | +" var st = $('pState');\n" | ||
| 1187 | +" if (RATE > 0){\n" | ||
| 1188 | +" TIMER = setInterval(poll, RATE);\n" | ||
| 1189 | +" st.textContent = 'live ' + (RATE / 1000) + 's';\n" | ||
| 1190 | +" st.className = 'pill live';\n" | ||
| 1191 | +" } else {\n" | ||
| 1192 | +" st.textContent = 'paused';\n" | ||
| 1193 | +" st.className = 'pill';\n" | ||
| 1194 | +" }\n" | ||
| 1195 | +" }\n" | ||
| 1196 | +"\n" | ||
| 1197 | +" Array.prototype.forEach.call(document.querySelectorAll('#segRate button'), function(b){\n" | ||
| 1198 | +" b.addEventListener('click', function(){\n" | ||
| 1199 | +" Array.prototype.forEach.call(document.querySelectorAll('#segRate button'),\n" | ||
| 1200 | +" function(x){ x.classList.remove('on'); });\n" | ||
| 1201 | +" b.classList.add('on');\n" | ||
| 1202 | +" RATE = parseInt(b.getAttribute('data-ms'), 10) || 0;\n" | ||
| 1203 | +" schedule();\n" | ||
| 1204 | +" if (RATE > 0) poll();\n" | ||
| 1205 | +" });\n" | ||
| 1206 | +" });\n" | ||
| 1207 | +"\n" | ||
| 1208 | +" Array.prototype.forEach.call(document.querySelectorAll('#segRoot button'), function(b){\n" | ||
| 1209 | +" b.addEventListener('click', function(){\n" | ||
| 1210 | +" Array.prototype.forEach.call(document.querySelectorAll('#segRoot button'),\n" | ||
| 1211 | +" function(x){ x.classList.remove('on'); });\n" | ||
| 1212 | +" b.classList.add('on');\n" | ||
| 1213 | +" ROOT = b.getAttribute('data-root') || 'workspace';\n" | ||
| 1214 | +" loadDirs();\n" | ||
| 1215 | +" });\n" | ||
| 1216 | +" });\n" | ||
| 1217 | +"\n" | ||
| 1218 | +" $('btnRefresh').addEventListener('click', poll);\n" | ||
| 1219 | +"\n" | ||
| 1220 | +" /* follow the hub's theme when it sets one */\n" | ||
| 1221 | +" try {\n" | ||
| 1222 | +" var t = localStorage.getItem('bot_theme');\n" | ||
| 1223 | +" if (t === 'light' || t === 'dark') document.documentElement.setAttribute('data-theme', t);\n" | ||
| 1224 | +" } catch (e) {}\n" | ||
| 1225 | +"\n" | ||
| 1226 | +" poll();\n" | ||
| 1227 | +" schedule();\n" | ||
| 1228 | +"})();\n</script></body></html>\n", stdout); | ||
| 1229 | + | ||
| 1230 | + return 0; | ||
| 1231 | +} | ||
| 1232 | + | ||
| 1233 | +/* ------------------------------------------------------------------ */ | ||
| 1234 | +/* main */ | ||
| 1235 | +/* ------------------------------------------------------------------ */ | ||
| 1236 | + | ||
| 1237 | +int main(int argc, char **argv) | ||
| 1238 | +{ | ||
| 1239 | + const char *qs; | ||
| 1240 | + int embed; | ||
| 1241 | + | ||
| 1242 | + if (argc > 1) { | ||
| 1243 | + if (strcmp(argv[1], "--meta") == 0) return mode_meta(); | ||
| 1244 | + if (strcmp(argv[1], "--version") == 0) { | ||
| 1245 | + puts(PLUGIN_VER); | ||
| 1246 | + return 0; | ||
| 1247 | + } | ||
| 1248 | + if (strcmp(argv[1], "--help") == 0) { | ||
| 1249 | + puts("usage: " PLUGIN_ID " [--meta|--version|--help]"); | ||
| 1250 | + puts(""); | ||
| 1251 | + puts("Runs as a CGI-style program under scorpiox-server."); | ||
| 1252 | + puts(" --meta print discovery metadata JSON and exit"); | ||
| 1253 | + puts(" --version print the plugin version and exit"); | ||
| 1254 | + puts(""); | ||
| 1255 | + puts("Query string actions:"); | ||
| 1256 | + puts(" (none) or action=mounts mounted filesystems with usage"); | ||
| 1257 | + puts(" action=dirs&root=workspace|home bounded 1-level folder sizes"); | ||
| 1258 | + puts(" action=info plugin/platform capabilities"); | ||
| 1259 | + puts(" format=json same as an action, JSON output"); | ||
| 1260 | + puts(" (any other) HTML dashboard"); | ||
| 1261 | + return 0; | ||
| 1262 | + } | ||
| 1263 | + } | ||
| 1264 | + | ||
| 1265 | + if (getenv("SX_PLUGIN_META")) return mode_meta(); | ||
| 1266 | + | ||
| 1267 | + require_node_auth(); | ||
| 1268 | + | ||
| 1269 | + qs = getenv("QUERY_STRING"); | ||
| 1270 | + if (!qs) qs = ""; | ||
| 1271 | + | ||
| 1272 | + if (strstr(qs, "action=") || strstr(qs, "format=json")) | ||
| 1273 | + return mode_json(qs); | ||
| 1274 | + | ||
| 1275 | + embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); | ||
| 1276 | + return mode_html(embed); | ||
| 1277 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..725a458 | index 0000000..725a458 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/e2e.py | +++ b/tests/e2e.py | ||
| @@ -0,0 +1,137 @@ | @@ -0,0 +1,137 @@ | ||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""tests/e2e.py - viewport checks for the plugin_disks dashboard. | ||
| 3 | + | ||
| 4 | +Serves the plugin through a tiny CGI-ish HTTP shim on a loopback port, opens it | ||
| 5 | +with Playwright at 1440 / 1024 / 390 CSS pixels, and asserts there is no | ||
| 6 | +horizontal overflow, no console error, and that the mount table and the folder | ||
| 7 | +breakdown both rendered real numbers. Skips cleanly (exit 0) when Playwright is | ||
| 8 | +not installed, so `make test` stays offline-only. | ||
| 9 | + | ||
| 10 | + python3 tests/e2e.py # run if Playwright is available | ||
| 11 | + python3 tests/e2e.py --strict # exit 2 when Playwright is missing | ||
| 12 | +""" | ||
| 13 | + | ||
| 14 | +import argparse | ||
| 15 | +import http.server | ||
| 16 | +import os | ||
| 17 | +import subprocess | ||
| 18 | +import socketserver | ||
| 19 | +import sys | ||
| 20 | +import threading | ||
| 21 | + | ||
| 22 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 23 | +BIN = os.path.join(ROOT, "plugin_disks") | ||
| 24 | +VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +class Handler(http.server.BaseHTTPRequestHandler): | ||
| 28 | + def do_GET(self): # noqa: N802 | ||
| 29 | + from urllib.parse import urlparse | ||
| 30 | + u = urlparse(self.path) | ||
| 31 | + env = dict(os.environ) | ||
| 32 | + env["QUERY_STRING"] = u.query | ||
| 33 | + env["REQUEST_METHOD"] = "GET" | ||
| 34 | + env.pop("BOT_PASSWORD", None) | ||
| 35 | + out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout | ||
| 36 | + sep = out.find(b"\r\n\r\n") | ||
| 37 | + headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" | ||
| 38 | + body = out[sep + 4:] if sep >= 0 else out | ||
| 39 | + ctype = "text/html; charset=utf-8" | ||
| 40 | + for line in headers.splitlines(): | ||
| 41 | + if line.lower().startswith("content-type:"): | ||
| 42 | + ctype = line.split(":", 1)[1].strip() | ||
| 43 | + self.send_response(200) | ||
| 44 | + self.send_header("Content-Type", ctype) | ||
| 45 | + self.send_header("Cache-Control", "no-store") | ||
| 46 | + # no Content-Length from the plugin; the shim sets its own framing | ||
| 47 | + self.send_header("Content-Length", str(len(body))) | ||
| 48 | + self.end_headers() | ||
| 49 | + self.wfile.write(body) | ||
| 50 | + | ||
| 51 | + def log_message(self, *_a): | ||
| 52 | + pass | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +def main(): | ||
| 56 | + ap = argparse.ArgumentParser() | ||
| 57 | + ap.add_argument("--strict", action="store_true") | ||
| 58 | + args = ap.parse_args() | ||
| 59 | + | ||
| 60 | + if not os.path.exists(BIN): | ||
| 61 | + print("plugin_disks is not built; run make first", file=sys.stderr) | ||
| 62 | + return 1 | ||
| 63 | + | ||
| 64 | + try: | ||
| 65 | + from playwright.sync_api import sync_playwright | ||
| 66 | + except Exception: | ||
| 67 | + msg = "playwright not installed - skipping viewport e2e" | ||
| 68 | + if args.strict: | ||
| 69 | + print(msg, file=sys.stderr) | ||
| 70 | + return 2 | ||
| 71 | + print(msg) | ||
| 72 | + return 0 | ||
| 73 | + | ||
| 74 | + with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv: | ||
| 75 | + port = srv.server_address[1] | ||
| 76 | + threading.Thread(target=srv.serve_forever, daemon=True).start() | ||
| 77 | + url = "http://127.0.0.1:%d/plugin_disks" % port | ||
| 78 | + | ||
| 79 | + failures = [] | ||
| 80 | + with sync_playwright() as p: | ||
| 81 | + browser = p.chromium.launch() | ||
| 82 | + for (w, h) in VIEWPORTS: | ||
| 83 | + page = browser.new_page(viewport={"width": w, "height": h}) | ||
| 84 | + errors = [] | ||
| 85 | + page.on("console", lambda m: errors.append(m.text) | ||
| 86 | + if m.type == "error" else None) | ||
| 87 | + page.goto(url, wait_until="load") | ||
| 88 | + page.wait_for_timeout(3000) | ||
| 89 | + | ||
| 90 | + sw = page.evaluate("document.documentElement.scrollWidth") | ||
| 91 | + iw = page.evaluate("window.innerWidth") | ||
| 92 | + if sw > iw + 1: | ||
| 93 | + failures.append("%dx%d horizontal overflow %d > %d" % (w, h, sw, iw)) | ||
| 94 | + | ||
| 95 | + count = page.evaluate( | ||
| 96 | + "document.getElementById('kCount').textContent") | ||
| 97 | + full = page.evaluate( | ||
| 98 | + "document.getElementById('kFull').textContent") | ||
| 99 | + mounts = page.evaluate( | ||
| 100 | + "document.querySelectorAll('#mounts .mnt').length") | ||
| 101 | + rows = page.evaluate( | ||
| 102 | + "document.querySelectorAll('#rows tr').length") | ||
| 103 | + note = page.evaluate( | ||
| 104 | + "document.getElementById('dirNote').textContent") | ||
| 105 | + | ||
| 106 | + if not (count or "").strip().isdigit(): | ||
| 107 | + failures.append("%dx%d mount count KPI did not render (%r)" | ||
| 108 | + % (w, h, count)) | ||
| 109 | + if mounts < 1: | ||
| 110 | + failures.append("%dx%d no mount cards rendered" % (w, h)) | ||
| 111 | + if "%" not in (full or ""): | ||
| 112 | + failures.append("%dx%d fullness KPI did not render (%r)" | ||
| 113 | + % (w, h, full)) | ||
| 114 | + if not (note or "").strip(): | ||
| 115 | + failures.append("%dx%d folder note empty (%r)" % (w, h, note)) | ||
| 116 | + | ||
| 117 | + real = [e for e in errors if "favicon" not in e.lower()] | ||
| 118 | + if real: | ||
| 119 | + failures.append("%dx%d console errors: %s" % (w, h, real[:3])) | ||
| 120 | + | ||
| 121 | + print(" %dx%d scrollWidth=%d innerWidth=%d mounts=%d rows=%d count=%s full=%s" | ||
| 122 | + % (w, h, sw, iw, mounts, rows, (count or "").strip(), | ||
| 123 | + (full or "").strip())) | ||
| 124 | + page.close() | ||
| 125 | + browser.close() | ||
| 126 | + srv.shutdown() | ||
| 127 | + | ||
| 128 | + if failures: | ||
| 129 | + for f in failures: | ||
| 130 | + print(" FAIL " + f) | ||
| 131 | + return 1 | ||
| 132 | + print(" viewport e2e passed at %d sizes" % len(VIEWPORTS)) | ||
| 133 | + return 0 | ||
| 134 | + | ||
| 135 | + | ||
| 136 | +if __name__ == "__main__": | ||
| 137 | + sys.exit(main()) |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..65374be | index 0000000..65374be | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/run.sh | +++ b/tests/run.sh | ||
| @@ -0,0 +1,417 @@ | @@ -0,0 +1,417 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/run.sh - offline checks for plugin_disks across all 3 modes. | ||
| 3 | +# | ||
| 4 | +# Runs against ./plugin_disks (native build) on the live machine, so the mount | ||
| 5 | +# assertions use this node's real /proc/mounts (or getmntinfo / Win32 drive | ||
| 6 | +# list). If a musl static build or a Windows PE (plugin_disks.exe) is present | ||
| 7 | +# they are checked too. The whole git history is finally audited for secrets | ||
| 8 | +# and LAN IPs. | ||
| 9 | +# | ||
| 10 | +# Exit code 0 = everything passed. | ||
| 11 | + | ||
| 12 | +set -u | ||
| 13 | + | ||
| 14 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | ||
| 15 | +cd "$ROOT" || exit 1 | ||
| 16 | + | ||
| 17 | +BIN=./plugin_disks | ||
| 18 | +PASS=0 | ||
| 19 | +FAIL=0 | ||
| 20 | + | ||
| 21 | +if [ -t 1 ]; then | ||
| 22 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | ||
| 23 | +else | ||
| 24 | + C_OK=; C_BAD=; C_B=; C_0= | ||
| 25 | +fi | ||
| 26 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | ||
| 27 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | ||
| 28 | + | ||
| 29 | +check() { # check <desc> <expected-substring> <actual> | ||
| 30 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | ||
| 31 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)" | ||
| 32 | + fi | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | ||
| 36 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | ||
| 37 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | ||
| 38 | + fi | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | ||
| 42 | + | ||
| 43 | +body() { printf '%s' "$1" | sed '1,/^\r$/d'; } | ||
| 44 | + | ||
| 45 | +TMP=$(mktemp -d 2>/dev/null || echo /tmp/disks_tests_$$) | ||
| 46 | +mkdir -p "$TMP" 2>/dev/null || true | ||
| 47 | + | ||
| 48 | +# ---------------------------------------------------------------- build | ||
| 49 | +section "build" | ||
| 50 | +if [ ! -x "$BIN" ]; then | ||
| 51 | + echo " building native binary..." | ||
| 52 | + cc -O2 -std=c99 -Wall -Wextra -o "$BIN" src/plugin_disks.c || { echo " build failed"; exit 1; } | ||
| 53 | +fi | ||
| 54 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | ||
| 55 | + | ||
| 56 | +# ---------------------------------------------------------------- meta mode | ||
| 57 | +section "mode 1 --meta (must work without auth - discovery)" | ||
| 58 | +META=$("$BIN" --meta) | ||
| 59 | +check "meta emits name disks" '"name":"disks"' "$META" | ||
| 60 | +check "meta emits desc Local storage" '"desc":"Local storage"' "$META" | ||
| 61 | +METAENV=$(SX_PLUGIN_META=1 "$BIN") | ||
| 62 | +check "SX_PLUGIN_META=1 yields same meta" '"name":"disks"' "$METAENV" | ||
| 63 | +LEN=$(printf '%s' "$META" | wc -c | tr -d ' ') | ||
| 64 | +[ "$LEN" -lt 60 ] && pass "meta payload is compact ($LEN bytes)" || fail "meta payload too long ($LEN)" | ||
| 65 | +printf '%s' "$META" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | ||
| 66 | + && pass "meta is valid JSON" || fail "meta is not valid JSON" | ||
| 67 | +DESC=$(printf '%s' "$META" | sed 's/.*"desc":"\([^"]*\)".*/\1/') | ||
| 68 | +[ ${#DESC} -le 15 ] && pass "desc length ${#DESC} <= 15 chars" || fail "desc too long (${#DESC})" | ||
| 69 | +NAME=$(printf '%s' "$META" | sed 's/.*"name":"\([^"]*\)".*/\1/') | ||
| 70 | +[ "$(printf '%s' "$NAME" | wc -w | tr -d ' ')" -le 1 ] && pass "name is a single word" || fail "name has spaces" | ||
| 71 | +check "--version prints version" '1.0.0' "$("$BIN" --version)" | ||
| 72 | +check "--help is available" 'usage:' "$("$BIN" --help)" | ||
| 73 | +META_AUTH=$(BOT_PASSWORD=secret "$BIN" --meta) | ||
| 74 | +check "meta still works when BOT_PASSWORD is set" '"name":"disks"' "$META_AUTH" | ||
| 75 | + | ||
| 76 | +# ---------------------------------------------------------------- auth | ||
| 77 | +section "node auth" | ||
| 78 | +AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=mounts' "$BIN") | ||
| 79 | +check "no credentials -> 401" 'Status: 401' "$AUTHNONE" | ||
| 80 | +check "401 body is json" 'invalid node password' "$AUTHNONE" | ||
| 81 | +AUTHH=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING='action=mounts' "$BIN") | ||
| 82 | +check "X-Bot-Password accepted" '"ok":true' "$(body "$AUTHH")" | ||
| 83 | +AUTHB=$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=mounts' "$BIN") | ||
| 84 | +check "Bearer token accepted" '"ok":true' "$(body "$AUTHB")" | ||
| 85 | +AUTHQ=$(BOT_PASSWORD=testpw QUERY_STRING='action=mounts&pwd=testpw' "$BIN") | ||
| 86 | +check "?pwd= accepted" '"ok":true' "$(body "$AUTHQ")" | ||
| 87 | +AUTHBAD=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=mounts' "$BIN") | ||
| 88 | +check "wrong password -> 401" 'Status: 401' "$AUTHBAD" | ||
| 89 | +HTMLAUTH=$(BOT_PASSWORD=testpw QUERY_STRING='' "$BIN") | ||
| 90 | +check "html mode is also gated" 'Status: 401' "$HTMLAUTH" | ||
| 91 | + | ||
| 92 | +# ---------------------------------------------------------------- mounts | ||
| 93 | +section "mode 2 action=mounts" | ||
| 94 | +MF="$TMP/mounts.json" | ||
| 95 | +MOUNTS=$(body "$(QUERY_STRING='action=mounts' "$BIN")") | ||
| 96 | +printf '%s' "$MOUNTS" > "$MF" | ||
| 97 | +check "mounts ok:true" '"ok":true' "$MOUNTS" | ||
| 98 | +check "mounts names the plugin" '"plugin":"plugin_disks"' "$MOUNTS" | ||
| 99 | +check "mounts declares platform" '"platform":"' "$MOUNTS" | ||
| 100 | +check "mounts declares zero_network" '"zero_network":true' "$MOUNTS" | ||
| 101 | +check "mounts carries a utc stamp" '"utc":"20' "$MOUNTS" | ||
| 102 | +check "mounts lists an array" '"mounts":[' "$MOUNTS" | ||
| 103 | +printf '%s' "$MOUNTS" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | ||
| 104 | + && pass "mounts body is valid JSON" || fail "mounts body JSON invalid" | ||
| 105 | + | ||
| 106 | +python3 - "$MF" <<'PY' && pass "mount rows are well formed" || fail "mount rows malformed" | ||
| 107 | +import json, sys | ||
| 108 | +d = json.load(open(sys.argv[1])) | ||
| 109 | +assert d["count"] == len(d["mounts"]) | ||
| 110 | +for m in d["mounts"]: | ||
| 111 | + assert isinstance(m["device"], str) | ||
| 112 | + assert isinstance(m["fstype"], str) | ||
| 113 | + assert isinstance(m["mount"], str) and m["mount"] | ||
| 114 | + for k in ("total_bytes", "used_bytes", "free_bytes", "avail_bytes"): | ||
| 115 | + assert isinstance(m[k], int) and m[k] >= 0, (k, m[k]) | ||
| 116 | + assert 0.0 <= m["pct"] <= 100.0 | ||
| 117 | +PY | ||
| 118 | + | ||
| 119 | +python3 - "$MF" <<'PY' && pass "no pseudo filesystems leaked into the table" || fail "pseudo fs present" | ||
| 120 | +import json, sys | ||
| 121 | +d = json.load(open(sys.argv[1])) | ||
| 122 | +banned = {"proc","sysfs","cgroup","cgroup2","devpts","devtmpfs","debugfs", | ||
| 123 | + "tracefs","securityfs","pstore","bpf","mqueue","configfs"} | ||
| 124 | +got = {m["fstype"] for m in d["mounts"]} & banned | ||
| 125 | +assert not got, got | ||
| 126 | +PY | ||
| 127 | + | ||
| 128 | +python3 - "$MF" <<'PY' && pass "no kernel mountpoints leaked into the table" || fail "kernel mountpoint present" | ||
| 129 | +import json, sys | ||
| 130 | +d = json.load(open(sys.argv[1])) | ||
| 131 | +bad = [m["mount"] for m in d["mounts"] | ||
| 132 | + if m["mount"].startswith(("/sys", "/proc", "/dev"))] | ||
| 133 | +assert not bad, bad | ||
| 134 | +PY | ||
| 135 | + | ||
| 136 | +python3 - "$MF" <<'PY' && pass "mountpoints are unique (no double counting)" || fail "duplicate mountpoint" | ||
| 137 | +import json, sys | ||
| 138 | +d = json.load(open(sys.argv[1])) | ||
| 139 | +mp = [m["mount"] for m in d["mounts"]] | ||
| 140 | +assert len(mp) == len(set(mp)), [x for x in mp if mp.count(x) > 1] | ||
| 141 | +PY | ||
| 142 | + | ||
| 143 | +python3 - "$MF" <<'PY' && pass "mounts are ordered largest first" || fail "mount order wrong" | ||
| 144 | +import json, sys | ||
| 145 | +d = json.load(open(sys.argv[1])) | ||
| 146 | +t = [m["total_bytes"] for m in d["mounts"]] | ||
| 147 | +assert t == sorted(t, reverse=True), t | ||
| 148 | +PY | ||
| 149 | + | ||
| 150 | +# The live root filesystem must always be reported on POSIX, whichever node runs it. | ||
| 151 | +python3 - "$MF" <<'PY' && pass "live root mount is reported" || fail "root mount missing" | ||
| 152 | +import json, sys, os | ||
| 153 | +d = json.load(open(sys.argv[1])) | ||
| 154 | +if os.name != "nt": | ||
| 155 | + roots = [m for m in d["mounts"] if m["mount"] == "/"] | ||
| 156 | + assert roots, "no / mount" | ||
| 157 | + assert roots[0]["total_bytes"] > 0 | ||
| 158 | +PY | ||
| 159 | + | ||
| 160 | +python3 - "$MF" <<'PY' && pass "used + avail never exceeds the reported total by much" || fail "usage math inconsistent" | ||
| 161 | +import json, sys | ||
| 162 | +d = json.load(open(sys.argv[1])) | ||
| 163 | +for m in d["mounts"]: | ||
| 164 | + # reserved blocks may make used+avail < total; they must never exceed it | ||
| 165 | + assert m["used_bytes"] + m["avail_bytes"] <= m["total_bytes"] + 1 | ||
| 166 | +PY | ||
| 167 | + | ||
| 168 | +python3 - "$MF" <<'PY' && pass "info/supported keys reachable via format=json" || fail "format=json alias broken" | ||
| 169 | +import json, sys | ||
| 170 | +PY | ||
| 171 | +check "format=json aliases to mounts" '"action":"mounts"' "$(body "$(QUERY_STRING='format=json' "$BIN")")" | ||
| 172 | +rm -f "$MF" | ||
| 173 | + | ||
| 174 | +# ---------------------------------------------------------------- dirs | ||
| 175 | +section "mode 2 action=dirs - allowlist and traversal rejection" | ||
| 176 | +for bad in etc /etc .. ../.. workspace/ /workspace /root /home workspace\\ $'workspace\n' '%2Fetc' ; do | ||
| 177 | + R=$(body "$(QUERY_STRING="action=dirs&root=$(printf '%s' "$bad" | sed 's/ /%20/g')" "$BIN")") | ||
| 178 | + if printf '%s' "$R" | grep -F -q '"ok":false'; then | ||
| 179 | + pass "root rejected: $bad" | ||
| 180 | + else | ||
| 181 | + fail "root accepted: $bad -> $R" | ||
| 182 | + fi | ||
| 183 | +done | ||
| 184 | +MISS=$(body "$(QUERY_STRING='action=dirs' "$BIN")") | ||
| 185 | +check "missing root rejected" 'missing_root' "$MISS" | ||
| 186 | +check "missing root lists the allowlist" '"allowed_roots":["workspace","home"]' "$MISS" | ||
| 187 | +TRAV=$(body "$(QUERY_STRING='action=dirs&root=/etc' "$BIN")") | ||
| 188 | +check "traversal rejection is explicit" 'root_not_allowed' "$TRAV" | ||
| 189 | +check "traversal rejection echoes input" '"requested":"/etc"' "$TRAV" | ||
| 190 | + | ||
| 191 | +section "mode 2 action=dirs - real roots" | ||
| 192 | +DH=$(body "$(QUERY_STRING='action=dirs&root=home' "$BIN")") | ||
| 193 | +DF="$TMP/home.json" | ||
| 194 | +printf '%s' "$DH" > "$DF" | ||
| 195 | +if printf '%s' "$DH" | grep -F -q '"ok":true'; then | ||
| 196 | + pass "home root scans on this node" | ||
| 197 | + check "dirs echoes the root kind" '"root_kind":"home"' "$DH" | ||
| 198 | + check "dirs labels the root" '"root_label":"$HOME"' "$DH" | ||
| 199 | + check "dirs declares max depth" '"max_depth":' "$DH" | ||
| 200 | + check "dirs declares the scan budget" '"max_scan_entries":' "$DH" | ||
| 201 | + check "dirs reports the scan time" '"scan_ms":' "$DH" | ||
| 202 | + check "dirs reports truncation state" '"truncated":' "$DH" | ||
| 203 | + python3 - "$DF" <<'PY' && pass "dir rows are well formed" || fail "dir rows malformed" | ||
| 204 | +import json, sys | ||
| 205 | +d = json.load(open(sys.argv[1])) | ||
| 206 | +assert d["count"] == len(d["entries"]) | ||
| 207 | +for e in d["entries"]: | ||
| 208 | + assert isinstance(e["name"], str) and e["name"] | ||
| 209 | + assert isinstance(e["path"], str) and e["path"] | ||
| 210 | + assert isinstance(e["bytes"], int) and e["bytes"] >= 0 | ||
| 211 | + assert isinstance(e["is_dir"], bool) | ||
| 212 | + assert 0.0 <= e["pct"] <= 100.0 | ||
| 213 | +PY | ||
| 214 | + python3 - "$DF" <<'PY' && pass "dir entries are ordered largest first" || fail "dir order wrong" | ||
| 215 | +import json, sys | ||
| 216 | +d = json.load(open(sys.argv[1])) | ||
| 217 | +b = [e["bytes"] for e in d["entries"]] | ||
| 218 | +assert b == sorted(b, reverse=True), b | ||
| 219 | +PY | ||
| 220 | + python3 - "$DF" <<'PY' && pass "dir scan stays inside the requested root" || fail "entry escaped the root" | ||
| 221 | +import json, sys, os | ||
| 222 | +d = json.load(open(sys.argv[1])) | ||
| 223 | +root = d["root"].rstrip("/") + "/" | ||
| 224 | +for e in d["entries"]: | ||
| 225 | + assert e["path"].startswith(root), e["path"] | ||
| 226 | +PY | ||
| 227 | + python3 - "$DF" <<'PY' && pass "dir scan is bounded (entry count within the cap)" || fail "entry cap exceeded" | ||
| 228 | +import json, sys | ||
| 229 | +d = json.load(open(sys.argv[1])) | ||
| 230 | +assert d["count"] <= 512, d["count"] | ||
| 231 | +PY | ||
| 232 | +else | ||
| 233 | + pass "home root unavailable on this node (root_unavailable is a valid answer)" | ||
| 234 | + check "unavailable root is not an error leak" 'root_unavailable' "$DH" | ||
| 235 | +fi | ||
| 236 | +rm -f "$DF" | ||
| 237 | + | ||
| 238 | +DW=$(body "$(QUERY_STRING='action=dirs&root=workspace' "$BIN")") | ||
| 239 | +if printf '%s' "$DW" | grep -F -q '"ok":true'; then | ||
| 240 | + pass "workspace root scans on this node" | ||
| 241 | + check "workspace echoes its kind" '"root_kind":"workspace"' "$DW" | ||
| 242 | +elif printf '%s' "$DW" | grep -F -q 'root_unavailable'; then | ||
| 243 | + pass "workspace root absent on this node (reported as root_unavailable)" | ||
| 244 | +else | ||
| 245 | + fail "workspace root gave neither data nor root_unavailable: $DW" | ||
| 246 | +fi | ||
| 247 | + | ||
| 248 | +# ---------------------------------------------------------------- info + unknown | ||
| 249 | +section "mode 2 action=info" | ||
| 250 | +INFO=$(QUERY_STRING='action=info' "$BIN") | ||
| 251 | +IBODY=$(body "$INFO") | ||
| 252 | +check "info ok:true" '"ok":true' "$IBODY" | ||
| 253 | +check "info action info" '"action":"info"' "$IBODY" | ||
| 254 | +check "info pid present" '"pid":' "$IBODY" | ||
| 255 | +check "info utc present" '"utc":"20' "$IBODY" | ||
| 256 | +check "info zero_network declared" '"zero_network":true' "$IBODY" | ||
| 257 | +check "info allowed_roots declared" '"allowed_roots":["workspace","home"]' "$IBODY" | ||
| 258 | +check "info max_depth declared" '"max_depth":8' "$IBODY" | ||
| 259 | +check "info node_auth false when unset" '"node_auth":false' "$IBODY" | ||
| 260 | +INFOAUTH=$(body "$(BOT_PASSWORD=pw QUERY_STRING='action=info&pwd=pw' "$BIN")") | ||
| 261 | +check "info node_auth true when set" '"node_auth":true' "$INFOAUTH" | ||
| 262 | +printf '%s' "$IBODY" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | ||
| 263 | + && pass "info body is valid JSON" || fail "info body JSON invalid" | ||
| 264 | + | ||
| 265 | +UNK=$(QUERY_STRING='action=bogus' "$BIN") | ||
| 266 | +check "unknown action rejected" 'unknown_action' "$(body "$UNK")" | ||
| 267 | +check "unknown action lists supported" '"supported":["mounts","dirs","info"]' "$(body "$UNK")" | ||
| 268 | +check "unknown action echoes request" '"requested":"bogus"' "$(body "$UNK")" | ||
| 269 | + | ||
| 270 | +# ---------------------------------------------------------------- html | ||
| 271 | +section "mode 3 HTML" | ||
| 272 | +HTML=$(QUERY_STRING='' "$BIN") | ||
| 273 | +check "html content-type" 'Content-Type: text/html; charset=utf-8' "$HTML" | ||
| 274 | +check_not "html has no Content-Length" 'Content-Length' "$HTML" | ||
| 275 | +check "html has viewport meta" 'width=device-width' "$HTML" | ||
| 276 | +check "html title disks" '<title>disks</title>' "$HTML" | ||
| 277 | +check "html theme switch hook" 'bot_theme' "$HTML" | ||
| 278 | +check "html mount host present" "id='mounts'" "$HTML" | ||
| 279 | +check "html folder table host" "id='rows'" "$HTML" | ||
| 280 | +check "html root segmented control" 'data-root=' "$HTML" | ||
| 281 | +check "html rate segmented control" 'data-ms=' "$HTML" | ||
| 282 | +check "html capacity bar element" "el('div','bar')" "$HTML" | ||
| 283 | +check "html calls the mounts action" "base('mounts')" "$HTML" | ||
| 284 | +check "html calls the dirs action" "base('dirs')" "$HTML" | ||
| 285 | +check "html uses /plugins?plugin= route" "/plugins?plugin=" "$HTML" | ||
| 286 | +check "html falls back to /plugin_disks" "/plugin_disks" "$HTML" | ||
| 287 | +check "html closes document" '</html>' "$HTML" | ||
| 288 | +check "html declares zero network" 'zero outbound network' "$HTML" | ||
| 289 | +check "html shows the inode column" 'inodes' "$HTML" | ||
| 290 | +check "html colour-codes over-75%" 'warn' "$HTML" | ||
| 291 | +check "html colour-codes over-90%" 'danger' "$HTML" | ||
| 292 | +EMB=$(QUERY_STRING='embed=1' "$BIN") | ||
| 293 | +check "embed=1 still renders the UI" "id='mounts'" "$EMB" | ||
| 294 | +check_not "embed=1 drops the direct-open note" 'Opened directly from the node API' "$EMB" | ||
| 295 | +EMBT=$(QUERY_STRING='embed=true' "$BIN") | ||
| 296 | +check_not "embed=true also drops the note" 'Opened directly from the node API' "$EMBT" | ||
| 297 | +EMBN=$(QUERY_STRING='' "$BIN") | ||
| 298 | +check "non-embed keeps the note" 'Opened directly from the node API' "$EMBN" | ||
| 299 | + | ||
| 300 | +ZEROEMOJI=$(printf '%s' "$HTML" | python3 -c ' | ||
| 301 | +import sys | ||
| 302 | +s = sys.stdin.read() | ||
| 303 | +bad = [c for c in s if ord(c) > 0x2600 and ord(c) not in (0x2014, 0x2013, 0x2026)] | ||
| 304 | +print(len(bad)) | ||
| 305 | +') | ||
| 306 | +[ "$ZEROEMOJI" = "0" ] && pass "HTML contains no emoji glyphs" || fail "HTML has $ZEROEMOJI emoji glyph(s)" | ||
| 307 | +PK="pico""bot" | ||
| 308 | +check_not "html has no internal fleet paths" "$PK" "$HTML" | ||
| 309 | +check_not "html has no private IPs" "192.168." "$HTML" | ||
| 310 | +check_not "html has no ssh/sshpass" "sshpass" "$HTML" | ||
| 311 | + | ||
| 312 | +section "responsive markup" | ||
| 313 | +check "html has a narrow breakpoint" '@media(max-width:560px)' "$HTML" | ||
| 314 | +check "html hides columns on mobile" 'hide-sm' "$HTML" | ||
| 315 | +check "html grids use auto-fit" 'auto-fit,minmax' "$HTML" | ||
| 316 | + | ||
| 317 | +section "no shell, no sockets, no remote access" | ||
| 318 | +SRCCAT=$(cat src/plugin_disks.c) | ||
| 319 | +check_not "source opens no sockets" 'socket(' "$SRCCAT" | ||
| 320 | +check_not "source has no curl or wget" 'wget' "$SRCCAT" | ||
| 321 | +check_not "source has no ssh invocation" 'ssh ' "$SRCCAT" | ||
| 322 | +check_not "source has no sshpass" 'sshpass' "$SRCCAT" | ||
| 323 | +check_not "source runs no popen" 'popen(' "$SRCCAT" | ||
| 324 | +check_not "source has no system()" 'system(' "$SRCCAT" | ||
| 325 | +check "source walks with opendir/readdir" 'readdir' "$SRCCAT" | ||
| 326 | +check "source uses statvfs on linux" 'statvfs' "$SRCCAT" | ||
| 327 | +check "source refuses to follow symlinks" 'S_ISLNK' "$SRCCAT" | ||
| 328 | +check "source caps the walk depth" 'MAX_DEPTH' "$SRCCAT" | ||
| 329 | + | ||
| 330 | +# ---------------------------------------------------------------- optional targets | ||
| 331 | +section "optional cross builds" | ||
| 332 | +if [ -f plugin_disks.musl ]; then | ||
| 333 | + M=$(./plugin_disks.musl --meta) | ||
| 334 | + check "musl build --meta" '"name":"disks"' "$M" | ||
| 335 | + case $(head -c 4 plugin_disks.musl | od -An -tx1 | tr -d ' \n') in | ||
| 336 | + 7f454c46) pass "musl artifact is ELF" ;; | ||
| 337 | + *) fail "musl artifact is not ELF" ;; | ||
| 338 | + esac | ||
| 339 | +else | ||
| 340 | + echo " skip musl (not built)" | ||
| 341 | +fi | ||
| 342 | +if [ -f plugin_disks.arm64 ]; then | ||
| 343 | + case $(head -c 20 plugin_disks.arm64 | od -An -tx1 | tr -d ' \n') in | ||
| 344 | + 7f454c46*000000b7*) pass "arm64 artifact is an aarch64 ELF" ;; | ||
| 345 | + *) case $(head -c 4 plugin_disks.arm64 | od -An -tx1 | tr -d ' \n') in | ||
| 346 | + 7f454c46) pass "arm64 artifact is ELF (arch not probed)" ;; | ||
| 347 | + *) fail "arm64 artifact is not ELF" ;; | ||
| 348 | + esac ;; | ||
| 349 | + esac | ||
| 350 | +else | ||
| 351 | + echo " skip arm64 (not built)" | ||
| 352 | +fi | ||
| 353 | +if [ -f plugin_disks.exe ]; then | ||
| 354 | + MAGIC=$(head -c 2 plugin_disks.exe) | ||
| 355 | + [ "$MAGIC" = "MZ" ] && pass "windows artifact has MZ header" || fail "windows artifact missing MZ" | ||
| 356 | + SZ=$(wc -c < plugin_disks.exe | tr -d ' ') | ||
| 357 | + [ "$SZ" -gt 20000 ] && pass "windows artifact is not an error page ($SZ bytes)" || fail "windows artifact suspiciously small ($SZ bytes)" | ||
| 358 | +else | ||
| 359 | + echo " skip windows PE (not built)" | ||
| 360 | +fi | ||
| 361 | +for slice in arm64 x86_64; do | ||
| 362 | + f="plugin_disks.macos-$slice" | ||
| 363 | + if [ -f "$f" ]; then | ||
| 364 | + MF=$(head -c 4 "$f" | od -An -tx1 | tr -d ' \n') | ||
| 365 | + case "$MF" in | ||
| 366 | + cffaedfe|feedfacf|cefaedfe|feedface) pass "macos-$slice artifact is Mach-O" ;; | ||
| 367 | + *) fail "macos-$slice artifact is not Mach-O ($MF)" ;; | ||
| 368 | + esac | ||
| 369 | + else | ||
| 370 | + echo " skip macos-$slice (not built)" | ||
| 371 | + fi | ||
| 372 | +done | ||
| 373 | + | ||
| 374 | +# ---------------------------------------------------------------- history audit | ||
| 375 | +section "git history secret & LAN audit" | ||
| 376 | +if git rev-parse --git-dir >/dev/null 2>&1; then | ||
| 377 | + ALL="$TMP/history.txt" | ||
| 378 | + # Bookkeeping lines of this audit are excluded so the detector cannot flag itself. | ||
| 379 | + git log -p --all 2>/dev/null \ | ||
| 380 | + | grep -v '^Author: ' \ | ||
| 381 | + | grep -vE 'audit "|HITS=|grep -E|scan "|P_ROOT=|P_WT=' \ | ||
| 382 | + > "$ALL" || : > "$ALL" | ||
| 383 | + | ||
| 384 | + audit() { # audit <label> <regex> | ||
| 385 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | ||
| 386 | + if [ -n "$H" ]; then | ||
| 387 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | ||
| 388 | + else | ||
| 389 | + pass "history clean: $1" | ||
| 390 | + fi | ||
| 391 | + } | ||
| 392 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 393 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 394 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 395 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 396 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 397 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 398 | + audit "bare host password" 'Xboxone0909|xboxone' | ||
| 399 | + PK="pico""bot"; WT=".work""trees" | ||
| 400 | + audit "fleet path" "/codebases/${PK}|${WT}/" | ||
| 401 | + rm -f "$ALL" | ||
| 402 | +else | ||
| 403 | + echo " skip history audit (not a git checkout)" | ||
| 404 | +fi | ||
| 405 | + | ||
| 406 | +rm -rf "$TMP" | ||
| 407 | + | ||
| 408 | +# ---------------------------------------------------------------- summary | ||
| 409 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | ||
| 410 | +printf ' passed: %d\n' "$PASS" | ||
| 411 | +printf ' failed: %d\n' "$FAIL" | ||
| 412 | +if [ "$FAIL" -ne 0 ]; then | ||
| 413 | + printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0" | ||
| 414 | + exit 1 | ||
| 415 | +fi | ||
| 416 | +printf ' %sRESULT: ALL PASSED%s\n' "$C_OK" "$C_0" | ||
| 417 | +exit 0 | ||
| 0 | 418 |