| 1 | 1 | new file mode 100644 |
| index 0000000..c6fb4d7 | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,11 @@ | ||
| 1 | +plugin_logs | |
| 2 | +plugin_logs.exe | |
| 3 | +plugin_logs.musl | |
| 4 | +plugin_logs.arm64 | |
| 5 | +plugin_logs.macos-arm64 | |
| 6 | +plugin_logs.macos-x86_64 | |
| 7 | +bin/ | |
| 8 | +dist/ | |
| 9 | +*.o | |
| 10 | +__pycache__/ | |
| 11 | +*.pyc |
| 1 | 1 | new file mode 100644 |
| index 0000000..edac426 | ||
| --- /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..060ae0e | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,62 @@ | ||
| 1 | +# plugin_logs - SCORPIOX BOT open-source local log viewer plugin | |
| 2 | +# | |
| 3 | +# Targets: | |
| 4 | +# make native build -> ./plugin_logs | |
| 5 | +# make musl static musl x86_64 -> ./plugin_logs (fully static) | |
| 6 | +# make arm64 static aarch64 -> ./plugin_logs.arm64 | |
| 7 | +# make win64 MinGW-w64 static -> ./plugin_logs.exe | |
| 8 | +# make macos Apple clang -> ./plugin_logs (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_logs.c | |
| 21 | +BIN := plugin_logs | |
| 22 | +EXE := plugin_logs.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) src/bot_theme_plugin.h | |
| 31 | + @echo "==> native build ($(CC))" | |
| 32 | + $(CC) $(CFLAGS) -I src -o $(BIN) $(SRC) | |
| 33 | + | |
| 34 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | |
| 35 | +musl: $(SRC) src/bot_theme_plugin.h | |
| 36 | + @echo "==> static musl build ($(MUSL_CC))" | |
| 37 | + $(MUSL_CC) $(MUSL_CFLAGS) -I src -o $(BIN) $(SRC) | |
| 38 | + | |
| 39 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | |
| 40 | +arm64: $(SRC) src/bot_theme_plugin.h | |
| 41 | + @echo "==> static aarch64 build ($(ARM64_CC))" | |
| 42 | + $(ARM64_CC) $(ARM64_CFLAGS) -I src -o $(BIN).arm64 $(SRC) | |
| 43 | + | |
| 44 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | |
| 45 | +win64: $(SRC) src/bot_theme_plugin.h | |
| 46 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | |
| 47 | + $(WIN_CC) $(WIN_CFLAGS) -I src -o $(EXE) $(SRC) | |
| 48 | + | |
| 49 | +# Apple clang build (run this on macOS) | |
| 50 | +macos: $(SRC) src/bot_theme_plugin.h | |
| 51 | + @echo "==> Apple clang build" | |
| 52 | + $(CC) $(CFLAGS) -I src -o $(BIN) $(SRC) | |
| 53 | + | |
| 54 | +test: native | |
| 55 | + @sh tests/run.sh | |
| 56 | + | |
| 57 | +clean: | |
| 58 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64 | |
| 59 | + rm -rf bin dist | |
| 60 | + | |
| 61 | +help: | |
| 62 | + @echo "make | make musl | make arm64 | make win64 | make macos | make test | make clean" |
| 1 | 1 | new file mode 100644 |
| index 0000000..4e4c568 | ||
| --- /dev/null | ||
| +++ b/README.md | ||
| @@ -0,0 +1,148 @@ | ||
| 1 | +# plugin_logs — SCORPIOX BOT local log viewer | |
| 2 | + | |
| 3 | +A read-only local **log tail and search** viewer for SCORPIOX BOT nodes, in one | |
| 4 | +zero-dependency C99 binary. It reads an explicit allowlist of local log files | |
| 5 | +and the local system journal, renders a responsive dark/light panel with | |
| 6 | +severity colouring and hit highlighting, and never writes anything or opens a | |
| 7 | +network socket. | |
| 8 | + | |
| 9 | +``` | |
| 10 | + ┌──────────────────────── plugin_logs ────────────────────────┐ | |
| 11 | + ?action= │ sources list what can be read (journal / *.log / eventlog) │ | |
| 12 | + JSON API │ tail last N entries of one source │ | |
| 13 | + │ search case-insensitive substring search over one source │ | |
| 14 | + │ units systemd units that have journal entries │ | |
| 15 | + │ info plugin info, caps, auth state │ | |
| 16 | + └─────────────────────────────────────────────────────────────┘ | |
| 17 | + GET → HTML viewer (?embed=1 for the Chat floating window) | |
| 18 | +``` | |
| 19 | + | |
| 20 | +## What it reads | |
| 21 | + | |
| 22 | +| Platform | Sources | | |
| 23 | +|---|---| | |
| 24 | +| Linux | `journalctl -o json` (system journal and `journal:<unit>`); `*.log` directly under `/var/log`, plus `syslog`, `messages`, `kern.log`, `auth.log`; `$HOME/.scorpiox/**/*.log` and `/workspace/**/*.log` to depth 4 | | |
| 25 | +| macOS | `log show --style compact --last <Nm>` (bounded to 60 min); `*.log` directly under `/var/log`, `system.log`; `~/Library/Logs/**/*.log` to depth 3 | | |
| 26 | +| Windows | `wevtutil qe System\|Application /f:text` (fixed argv); `%LOCALAPPDATA%\scorpiox\**\*.log` to depth 4 | | |
| 27 | + | |
| 28 | +Nothing else is readable. A request for `file:/etc/passwd`, a directory, or an | |
| 29 | +id that is not in the current `action=sources` answer is refused with | |
| 30 | +`source_not_allowed` — the allowlist is the return value of the same walk the | |
| 31 | +UI is given, so there is no second path to a file. | |
| 32 | + | |
| 33 | +Every walk has **its own** entry budget. `/workspace` being enormous cannot | |
| 34 | +consume the allowance that `$HOME/.scorpiox` needs, and `action=sources` | |
| 35 | +reports `truncated: true` instead of pretending the short list is complete. | |
| 36 | +Symlinks are never followed. | |
| 37 | + | |
| 38 | +## What it never does | |
| 39 | + | |
| 40 | +* **No writes.** Files are opened `rb`. Nothing is rotated, truncated or created. | |
| 41 | +* **No sockets.** No `curl`, no HTTP client, no listening socket. The plugin is | |
| 42 | + a CGI-style executable; the node's server owns the socket. | |
| 43 | +* **No user-controlled shell.** Only `journalctl` and `wevtutil` are invoked, | |
| 44 | + from fixed `snprintf` format strings. A systemd unit name must pass | |
| 45 | + `[A-Za-z0-9@._-]{1,128}` and may not start with `-`, so it can never become an | |
| 46 | + option or a shell word. | |
| 47 | +* **No whole-file reads.** A tail starts at most 4 MB before EOF and drops the | |
| 48 | + first partial line; searches stop after 8 000 lines and 500 hits. | |
| 49 | + | |
| 50 | +## Build | |
| 51 | + | |
| 52 | +```sh | |
| 53 | +make # native -> ./plugin_logs | |
| 54 | +make musl # static musl x86_64 (the universal Linux artifact) | |
| 55 | +make arm64 # static aarch64 (Pi 5 / ARM64 servers) | |
| 56 | +make win64 # static PE via MinGW-w64 -> plugin_logs.exe | |
| 57 | +make macos # Apple clang, run this on the Mac | |
| 58 | +make test # build + offline checks | |
| 59 | +``` | |
| 60 | + | |
| 61 | +On Windows, `build.ps1` wraps the MinGW build and verifies the `MZ` header. | |
| 62 | + | |
| 63 | +## Deploy | |
| 64 | + | |
| 65 | +Copy the binary into the node's plugin dir and it is live immediately — no | |
| 66 | +server restart: | |
| 67 | + | |
| 68 | +```sh | |
| 69 | +install -m 0755 plugin_logs ~/.scorpiox/plugins/plugin_logs | |
| 70 | +``` | |
| 71 | + | |
| 72 | +The plugin appears in the Plugins list and is served at `/plugin_logs` | |
| 73 | +(GET for the viewer, `?action=…` for JSON). One-click install from the market | |
| 74 | +writes a `plugin_logs.manifest.json` sidecar with the source commit and the | |
| 75 | +artifact SHA-256. | |
| 76 | + | |
| 77 | +## Node API | |
| 78 | + | |
| 79 | +All actions except `--meta` require the node password when `BOT_PASSWORD` is | |
| 80 | +set — `X-Bot-Password`, `Authorization: Bearer <pwd>`, or `?pwd=` (what the | |
| 81 | +plugin iframe appends). With no `BOT_PASSWORD` the plugin is a deliberate no-op | |
| 82 | +so it can be run from a shell. | |
| 83 | + | |
| 84 | +``` | |
| 85 | +?action=sources | |
| 86 | +{ "ok":true, "journal_available":true, "count":5, "truncated":false, | |
| 87 | + "sources":[ {"id":"journal","label":"System journal","kind":"journal","size":0,"mtime":0}, | |
| 88 | + {"id":"file:/var/log/dpkg.log","label":"dpkg.log","kind":"file", | |
| 89 | + "size":958818,"mtime":1773629060} ] } | |
| 90 | + | |
| 91 | +?action=tail&src=journal&lines=200 | |
| 92 | +{ "ok":true, "src":"journal", "count":2, | |
| 93 | + "entries":[ {"ts":"11-12 04:50:01","unit":"nginx.service","sev":"err", | |
| 94 | + "text":"upstream timed out"} ] } | |
| 95 | + | |
| 96 | +?action=search&src=file:/var/log/dpkg.log&q=install | |
| 97 | +{ "ok":true, "scanned":8000, "count":500, "max":500, "truncated":true, "hits":[ … ] } | |
| 98 | + | |
| 99 | +?action=units | |
| 100 | +{ "ok":true, "available":true, "count":3, | |
| 101 | + "units":[ {"name":"nginx.service","src":"journal:nginx.service"} ] } | |
| 102 | +``` | |
| 103 | + | |
| 104 | +`sev` is `info`, `warn` or `err`. On Linux it comes from the journal | |
| 105 | +`PRIORITY` field; everywhere it falls back to a keyword heuristic over the | |
| 106 | +message text (`panic`, `fatal`, `error`, `failed`, `denied` → err; `warn`, | |
| 107 | +`deprecated`, `timeout`, `retry` → warn). | |
| 108 | + | |
| 109 | +## UI | |
| 110 | + | |
| 111 | +* Source picker grouped by kind, with file sizes. | |
| 112 | +* Line count 100 / 200 / 500 / 2000. | |
| 113 | +* **Follow** polls every 3 s and pauses while the tab is hidden. | |
| 114 | +* Search box with inline `<mark>` highlighting of every hit. | |
| 115 | +* **Wrap** for long stack traces, **Copy** to copy the visible entries, | |
| 116 | + **Reload** to re-walk the source list. | |
| 117 | +* Severity colouring: left border and text tint for `err` / `warn`. | |
| 118 | +* Dark and light from the shared SCORPIOX BOT theme tokens, so it matches the | |
| 119 | + bot in a hub modal, a session card and the Chat floating window. `?theme=` | |
| 120 | + decides before first paint; a `{type:'sx-theme'}` post from the host is | |
| 121 | + followed without a reload. | |
| 122 | +* Fluid at 1440 / 1024 / 390 px and inside the Chat floating window, no | |
| 123 | + `<script src=>`, no CDN, no emoji (inline SVG only). | |
| 124 | + | |
| 125 | +## Tests | |
| 126 | + | |
| 127 | +```sh | |
| 128 | +sh tests/run.sh # 153 offline assertions | |
| 129 | +python3 tests/e2e.py # Playwright: 1440/1024/390 × dark/light + behaviour | |
| 130 | +``` | |
| 131 | + | |
| 132 | +`tests/run.sh` replays a captured `journalctl -o json` stream and a fixture log | |
| 133 | +tree, so the parsers are tested against the real output layouts without needing | |
| 134 | +journald (or a growing log) on the build host: | |
| 135 | + | |
| 136 | +* `SX_LOGS_JOURNAL_FIXTURE` — a file replayed instead of running `journalctl`. | |
| 137 | +* `SX_LOGS_EXTRA_ROOT` — one extra allowlisted root, so fixtures live outside | |
| 138 | + the production paths. | |
| 139 | + | |
| 140 | +`tests/e2e.py` serves the plugin through a small CGI shim and asserts, at every | |
| 141 | +viewport and in both themes: no console error, no horizontal overflow, the | |
| 142 | +source picker is populated, a tail renders rows, severity classes are applied, | |
| 143 | +search highlights hits, follow pauses the poller, the line-count segment | |
| 144 | +switches, the theme button flips, and `?embed=1` drops only the back-link. | |
| 145 | + | |
| 146 | +## License | |
| 147 | + | |
| 148 | +MIT. Copyright (c) 2026 SCORPIOX INC. |
| 1 | 1 | new file mode 100644 |
| index 0000000..322c94e | ||
| --- /dev/null | ||
| +++ b/build.ps1 | ||
| @@ -0,0 +1,32 @@ | ||
| 1 | +# build.ps1 - native Windows build of plugin_logs with MinGW-w64 or MSVC-style cl. | |
| 2 | +# | |
| 3 | +# .\build.ps1 # build plugin_logs.exe with gcc (MinGW-w64) | |
| 4 | +# .\build.ps1 -Compiler cl # build with cl.exe | |
| 5 | +# .\build.ps1 -Test # build then run the offline checks | |
| 6 | +param( | |
| 7 | + [string]$Compiler = "gcc", | |
| 8 | + [switch]$Test | |
| 9 | +) | |
| 10 | + | |
| 11 | +$ErrorActionPreference = "Stop" | |
| 12 | +$src = "src\plugin_logs.c" | |
| 13 | +$out = "plugin_logs.exe" | |
| 14 | +$inc = "-Isrc" | |
| 15 | + | |
| 16 | +if ($Compiler -eq "cl") { | |
| 17 | + Write-Host "==> MSVC build" | |
| 18 | + & cl /nologo /O2 /W3 /I src /Fe:$out $src | |
| 19 | +} else { | |
| 20 | + Write-Host "==> MinGW-w64 build" | |
| 21 | + & x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static $inc -o $out $src | |
| 22 | +} | |
| 23 | +if ($LASTEXITCODE -ne 0) { throw "build failed" } | |
| 24 | + | |
| 25 | +$head = [System.IO.File]::ReadAllBytes((Resolve-Path $out))[0..1] | |
| 26 | +if ($head[0] -ne 0x4D -or $head[1] -ne 0x5A) { throw "artifact is not a PE image" } | |
| 27 | +Write-Host ("==> built {0} ({1} bytes)" -f $out, (Get-Item $out).Length) | |
| 28 | + | |
| 29 | +& $out --meta | |
| 30 | +if ($Test) { | |
| 31 | + Write-Host "==> tests need a POSIX shell; run tests/run.sh under Git Bash or WSL" | |
| 32 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..e1e1899 |

| 1 | 1 | new file mode 100644 |
| index 0000000..0b14ed9 |

| 1 | 1 | new file mode 100644 |
| index 0000000..6481a49 |

| 1 | 1 | new file mode 100644 |
| index 0000000..19c05a6 |

| 1 | 1 | new file mode 100644 |
| index 0000000..7b33e27 |

| 1 | 1 | new file mode 100644 |
| index 0000000..fcf7d78 |

| 1 | 1 | new file mode 100644 |
| index 0000000..03a5dc8 | ||
| --- /dev/null | ||
| +++ b/plugin.json | ||
| @@ -0,0 +1,14 @@ | ||
| 1 | +{ | |
| 2 | + "slug": "logs", | |
| 3 | + "id": "plugin_logs", | |
| 4 | + "title": "Local Log Viewer", | |
| 5 | + "summary": "Zero-dependency local log tail and search viewer for Linux, macOS and Windows nodes - reads an explicit allowlist of local log files plus the system journal, read-only, with no outbound network requests.", | |
| 6 | + "category": "system", | |
| 7 | + "license": "MIT", | |
| 8 | + "capabilities": [ | |
| 9 | + "local_log_read", | |
| 10 | + "journal_read", | |
| 11 | + "no_network" | |
| 12 | + ], | |
| 13 | + "trust_notice": "Executes native C code on your node. Reads only an allowlist of local log files and the local system journal in read-only mode; writes nothing and makes zero outbound network requests." | |
| 14 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..1bdfb37 | ||
| --- /dev/null | ||
| +++ b/release-dist.sh | ||
| @@ -0,0 +1,362 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# release-dist.sh — build, scan and publish plugin_logs 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="logs" | |
| 30 | +ID="plugin_logs" | |
| 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 -I src -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 -I src -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 — Pi 5 / ARM64 servers) | |
| 142 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | |
| 143 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -I src -o "$STAGE/$ID.arm64" src/$ID.c \ | |
| 144 | + || die "arm64 musl build failed" | |
| 145 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | |
| 146 | +else | |
| 147 | + echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)" | |
| 148 | +fi | |
| 149 | + | |
| 150 | +# windows-x86_64 (static PE) | |
| 151 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | |
| 152 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.exe" src/$ID.c \ | |
| 153 | + || die "MinGW build failed" | |
| 154 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | |
| 155 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | |
| 156 | +else | |
| 157 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | |
| 158 | +fi | |
| 159 | + | |
| 160 | +# macOS legs — Mach-O must be produced by Apple clang on a real Mac. | |
| 161 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | |
| 162 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | |
| 163 | + MAC_USER="${MAC_USER:-$(whoami)}" | |
| 164 | + MAC_DIR="/tmp/${ID}-mac-$$" | |
| 165 | + echo " building macOS legs on $MAC_HOST" | |
| 166 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | |
| 167 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | |
| 168 | + if [ -n "${MAC_PASS:-}" ]; then | |
| 169 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | |
| 170 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | |
| 171 | + fi | |
| 172 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | |
| 173 | + if "${SCP_MAC[@]}" src/$ID.c "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.c"; then | |
| 174 | + # Build straight from the uploaded file — no src/ tree on the remote. | |
| 175 | + for slice in arm64 x86_64; do | |
| 176 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | |
| 177 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -arch $slice -o $ID.$slice $ID.c" \ | |
| 178 | + 2>/dev/null; then | |
| 179 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | |
| 180 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | |
| 181 | + else | |
| 182 | + echo " warn: macos-$slice build failed on $MAC_HOST" | |
| 183 | + fi | |
| 184 | + done | |
| 185 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" 2>/dev/null || true | |
| 186 | + else | |
| 187 | + echo " warn: mac scp failed" | |
| 188 | + fi | |
| 189 | + else | |
| 190 | + echo " warn: mac host unreachable" | |
| 191 | + fi | |
| 192 | +else | |
| 193 | + echo " skip macOS legs (set MAC_HOST/MAC_USER/MAC_PASS to include them)" | |
| 194 | +fi | |
| 195 | + | |
| 196 | +# ---------------------------------------------------------------- 3. package | |
| 197 | +say "3/7 package" | |
| 198 | + | |
| 199 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | |
| 200 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | |
| 201 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | |
| 202 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | |
| 203 | + | |
| 204 | +target_meta() { # target_meta <key> <file> <format> <relpath> <name> | |
| 205 | + local key="$1" file="$2" fmt="$3" rel="$4" name="$5" | |
| 206 | + [ -f "$file" ] || return 0 | |
| 207 | + local sha size | |
| 208 | + sha=$(sha256sum "$file" | awk '{print $1}') | |
| 209 | + size=$(wc -c < "$file" | tr -d ' ') | |
| 210 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | |
| 211 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | |
| 212 | +} | |
| 213 | + | |
| 214 | +{ | |
| 215 | + printf '{\n' | |
| 216 | + printf ' "slug": "%s",\n' "$SLUG" | |
| 217 | + printf ' "id": "%s",\n' "$ID" | |
| 218 | + printf ' "name": "logs",\n' | |
| 219 | + printf ' "desc": "Log viewer",\n' | |
| 220 | + printf ' "title": "Local Log Viewer",\n' | |
| 221 | + printf ' "summary": "Zero-dependency local log tail and search viewer for Linux, macOS and Windows nodes - reads an explicit allowlist of local log files plus the system journal, read-only, with no outbound network requests.",\n' | |
| 222 | + printf ' "category": "system",\n' | |
| 223 | + printf ' "version": "%s",\n' "$VERSION" | |
| 224 | + printf ' "license": "MIT",\n' | |
| 225 | + printf ' "trust_notice": "Executes native C code on your node. Reads only an allowlist of local log files and the local system journal in read-only mode; writes nothing and makes zero outbound network requests.",\n' | |
| 226 | + printf ' "capabilities": ["local_log_read", "journal_read", "no_network"],\n' | |
| 227 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | |
| 228 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | |
| 229 | + printf ' "git_commit": "%s",\n' "$COMMIT" | |
| 230 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 231 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | |
| 232 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -I src -o %s src/%s.c",\n' "$ID" "$ID" | |
| 233 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -I src -o %s.exe src/%s.c",\n' "$ID" "$ID" | |
| 234 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | |
| 235 | + printf ' "targets": {\n' | |
| 236 | + first=1 | |
| 237 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | |
| 238 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" "$ID" | |
| 239 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" "$ID" | |
| 240 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" "$ID" | |
| 241 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" "$ID" | |
| 242 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" "$ID" | |
| 243 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" "$ID" | |
| 244 | + printf '\n }\n}\n' | |
| 245 | +} > "$STAGE/manifest.json" | |
| 246 | + | |
| 247 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | |
| 248 | + || die "generated manifest.json is not valid JSON" | |
| 249 | +echo " manifest.json ok" | |
| 250 | + | |
| 251 | +# SHA256SUMS — relative paths, exactly as published | |
| 252 | +( cd "$STAGE" | |
| 253 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | |
| 254 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | |
| 255 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | |
| 256 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | |
| 257 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | |
| 258 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | |
| 259 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | |
| 260 | + true ) > "$STAGE/SHA256SUMS" | |
| 261 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | |
| 262 | + | |
| 263 | +# ---------------------------------------------------------------- 4. stage | |
| 264 | +say "4/7 stage tree" | |
| 265 | +PKG="$STAGE/pkg" | |
| 266 | +mkdir -p "$PKG/linux-x86_64" "$PKG/linux-x86_64-musl" "$PKG/linux-arm64-musl" \ | |
| 267 | + "$PKG/macos-arm64" "$PKG/macos-x86_64" "$PKG/windows-x86_64" | |
| 268 | +cp -f "$STAGE/$ID" "$PKG/linux-x86_64/$ID" | |
| 269 | +[ -f "$STAGE/$ID.musl" ] && cp -f "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID" | |
| 270 | +[ -f "$STAGE/$ID.arm64" ] && cp -f "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID" | |
| 271 | +[ -f "$STAGE/$ID.macos-arm64" ]&& cp -f "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID" | |
| 272 | +[ -f "$STAGE/$ID.macos-x86_64" ]&&cp -f "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID" | |
| 273 | +[ -f "$STAGE/$ID.exe" ] && cp -f "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe" | |
| 274 | +cp -f "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | |
| 275 | +chmod +x "$PKG"/*/$ID 2>/dev/null || true | |
| 276 | +find "$PKG" -type f | sed 's/^/ /' | |
| 277 | + | |
| 278 | +if [ "$DRY_RUN" -eq 1 ]; then | |
| 279 | + say "dry run — staged at $STAGE/pkg (kept for inspection)" | |
| 280 | + trap - EXIT | |
| 281 | + exit 0 | |
| 282 | +fi | |
| 283 | + | |
| 284 | +# ---------------------------------------------------------------- 5. upload | |
| 285 | +say "5/7 upload" | |
| 286 | + | |
| 287 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set — cannot upload" | |
| 288 | +SSH=(ssh -o StrictHostKeyChecking=no) | |
| 289 | +SCP=(scp -o StrictHostKeyChecking=no) | |
| 290 | +if [ -n "$DIST_PASS" ]; then | |
| 291 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | |
| 292 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | |
| 293 | +fi | |
| 294 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | |
| 295 | + | |
| 296 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | |
| 297 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | |
| 298 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | |
| 299 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | |
| 300 | +# OpenSSH 9 refuses to scp a bare "." source. | |
| 301 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | |
| 302 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | |
| 303 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | |
| 304 | + || die "remote extract failed" | |
| 305 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | |
| 306 | + | |
| 307 | +# latest.json = copy of this version's manifest | |
| 308 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | |
| 309 | + || die "latest.json update failed" | |
| 310 | +echo " updated bot-plugins/$SLUG/latest.json" | |
| 311 | + | |
| 312 | +# index.json — merge, preserving every sibling <slug>/latest.json | |
| 313 | +say "index.json merge" | |
| 314 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | |
| 315 | +import json, os, sys, glob | |
| 316 | +slug = sys.argv[1] | |
| 317 | +entries = {} | |
| 318 | +for p in sorted(glob.glob('*/latest.json')): | |
| 319 | + s = os.path.dirname(p) | |
| 320 | + try: | |
| 321 | + entries[s] = json.load(open(p)) | |
| 322 | + except Exception: | |
| 323 | + pass | |
| 324 | +index = { | |
| 325 | + 'ok': True, | |
| 326 | + 'service': 'bot-plugins-dist', | |
| 327 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | |
| 328 | + 'count': len(entries), | |
| 329 | + 'slugs': sorted(entries), | |
| 330 | + 'plugins': [entries[k] for k in sorted(entries)], | |
| 331 | +} | |
| 332 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | |
| 333 | +os.replace('index.json.tmp', 'index.json') | |
| 334 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | |
| 335 | +PY" || die "index.json merge failed" | |
| 336 | + | |
| 337 | +# ---------------------------------------------------------------- 6. mirror | |
| 338 | +say "6/7 plugingit mirror" | |
| 339 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | |
| 340 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | |
| 341 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://x-access-token:${TOKEN}@|") | |
| 342 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | |
| 343 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | |
| 344 | + echo " mirrored to $PLUGINGIT_REMOTE" | |
| 345 | +else | |
| 346 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | |
| 347 | +fi | |
| 348 | + | |
| 349 | +# ---------------------------------------------------------------- 7. verify | |
| 350 | +say "7/7 verify" | |
| 351 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | |
| 352 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | |
| 353 | +if [ "$CODE" = "200" ]; then | |
| 354 | + 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"])))' \ | |
| 355 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | |
| 356 | +else | |
| 357 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | |
| 358 | +fi | |
| 359 | + | |
| 360 | +printf '\n\033[1mrelease complete\033[0m\n' | |
| 361 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 362 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | 1 | new file mode 100644 |
| index 0000000..0dd243b | ||
| --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | ||
| 1 | +/* | |
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | |
| 3 | + * | |
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | |
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | |
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | |
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | |
| 8 | + * localStorage key, same prepaint order. | |
| 9 | + * | |
| 10 | + * Three rules, and nothing else: | |
| 11 | + * | |
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | |
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | |
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | |
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | |
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | |
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | |
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | |
| 19 | + * it was already open when the bot changed theme. | |
| 20 | + * | |
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | |
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | |
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | |
| 24 | + * are var() references, one definition covers both themes. | |
| 25 | + * | |
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 27 | + */ | |
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | |
| 29 | +#define SX_BOT_THEME_PLUGIN_H | |
| 30 | + | |
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | |
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | |
| 33 | +#define SX_BOT_THEME_TOKENS \ | |
| 34 | +":root{color-scheme:dark;" \ | |
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | |
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | |
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | |
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | |
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | |
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | |
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | |
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | |
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | |
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | |
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | |
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | |
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | |
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | |
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | |
| 50 | +"}" \ | |
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | |
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 58 | + "--accent-dim:#0066d6;" \ | |
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 62 | + "color-scheme:light}}" \ | |
| 63 | +"html[data-theme=light]{" \ | |
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 70 | + "--accent-dim:#0066d6;" \ | |
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 74 | + "color-scheme:light}" \ | |
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | |
| 76 | +"*{box-sizing:border-box}" \ | |
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | |
| 78 | + "-webkit-font-smoothing:antialiased}" \ | |
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | |
| 80 | +"button:active{transform:scale(.98)}" \ | |
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | |
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | |
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | |
| 84 | +" * hides its own back link and its own toggle. */" \ | |
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | |
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | |
| 87 | + | |
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | |
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | |
| 90 | + * html.embedded so the embed rules apply before first paint. */ | |
| 91 | +#define SX_BOT_THEME_PREPAINT \ | |
| 92 | +"<script>(function(){var t='';" \ | |
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | |
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | |
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | |
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | |
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 99 | +"})();</script>\n" | |
| 100 | + | |
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | |
| 102 | + * at startup in case it changed while this page was already open. Fires the | |
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | |
| 104 | + * re-skin themselves from one listener. */ | |
| 105 | +#define SX_BOT_THEME_HANDOFF \ | |
| 106 | +"<script>(function(){" \ | |
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | |
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | |
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | |
| 112 | +"window.sxApplyTheme=apply;" \ | |
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | |
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | |
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | |
| 116 | +"})();</script>\n" | |
| 117 | + | |
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | |
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | |
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | |
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | |
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | |
| 123 | + | |
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | |
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | |
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | |
| 127 | +"})();</script>\n" | |
| 128 | + | |
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..659a399 | ||
| --- /dev/null | ||
| +++ b/src/plugin_logs.c | ||
| @@ -0,0 +1,1874 @@ | ||
| 1 | +/* | |
| 2 | + * plugin_logs - SCORPIOX BOT open-source local log viewer 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=sources|tail|search|units -> JSON node API | |
| 7 | + * 3. GET (default) -> responsive HTML log tail & search UI | |
| 8 | + * | |
| 9 | + * Local node only. Reads an explicit allowlist of local log files (a bounded | |
| 10 | + * walk of /var/log, $HOME/.scorpiox, /workspace, ~/Library/Logs and | |
| 11 | + * %LOCALAPPDATA%\scorpiox) and the local system journal through a fixed argv | |
| 12 | + * with no user-controlled shell text. Makes ZERO outbound network requests, | |
| 13 | + * opens no sockets, reads no credentials. | |
| 14 | + * | |
| 15 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | |
| 16 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | |
| 17 | + * scorpiox-server on the node. | |
| 18 | + * | |
| 19 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 20 | + */ | |
| 21 | + | |
| 22 | +/* MinGW defaults to a Server 2003 target; the Win7+ APIs used below would be | |
| 23 | + * hidden by that gate. This must precede every include. */ | |
| 24 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | |
| 25 | +# define _WIN32_WINNT 0x0601 | |
| 26 | +#endif | |
| 27 | + | |
| 28 | +#if defined(__APPLE__) | |
| 29 | + /* sys/types.h pulls BSD types (u_int) that strict c99 would hide */ | |
| 30 | +# define _DARWIN_C_SOURCE 1 | |
| 31 | +#elif !defined(_WIN32) | |
| 32 | +# define _POSIX_C_SOURCE 200809L | |
| 33 | +# define _DEFAULT_SOURCE 1 | |
| 34 | +#endif | |
| 35 | + | |
| 36 | +#include <stdio.h> | |
| 37 | +#include <stdlib.h> | |
| 38 | +#include <string.h> | |
| 39 | +#include <time.h> | |
| 40 | +#include <ctype.h> | |
| 41 | +#include <errno.h> | |
| 42 | + | |
| 43 | +#if defined(_WIN32) | |
| 44 | + | |
| 45 | +# define WIN32_LEAN_AND_MEAN | |
| 46 | +# include <windows.h> | |
| 47 | +# include <io.h> | |
| 48 | + | |
| 49 | +#else | |
| 50 | + | |
| 51 | +# include <unistd.h> | |
| 52 | +# include <dirent.h> | |
| 53 | +# include <sys/types.h> | |
| 54 | +# include <sys/stat.h> | |
| 55 | + | |
| 56 | +#endif | |
| 57 | + | |
| 58 | +#include "bot_theme_plugin.h" | |
| 59 | + | |
| 60 | +#define PLUGIN_SLUG "logs" | |
| 61 | +#define PLUGIN_ID "plugin_logs" | |
| 62 | +#define PLUGIN_VER "1.0.0" | |
| 63 | + | |
| 64 | +#define MAX_SRC 256 | |
| 65 | +#define MAX_UNITS 512 | |
| 66 | +#define ENTRY_TEXT 1024 | |
| 67 | +#define ENTRY_UNIT 96 | |
| 68 | +#define ENTRY_TS 40 | |
| 69 | +#define TAIL_MAX 2000 | |
| 70 | +#define SEARCH_HITS_MAX 500 | |
| 71 | +#define SEARCH_SCAN 8000 | |
| 72 | +#define FILE_TAIL_BYTES (4L * 1024L * 1024L) | |
| 73 | +#define ROOT_BUDGET 40000 | |
| 74 | + | |
| 75 | +/* Severity buckets: 0 info, 1 warn, 2 err */ | |
| 76 | +#define SEV_INFO 0 | |
| 77 | +#define SEV_WARN 1 | |
| 78 | +#define SEV_ERR 2 | |
| 79 | + | |
| 80 | +/* ------------------------------------------------------------------ */ | |
| 81 | +/* Small utilities */ | |
| 82 | +/* ------------------------------------------------------------------ */ | |
| 83 | + | |
| 84 | +static void url_decode(char *s) | |
| 85 | +{ | |
| 86 | + char *o = s; | |
| 87 | + if (!s) return; | |
| 88 | + while (*s) { | |
| 89 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | |
| 90 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | |
| 91 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | |
| 92 | + *o++ = (char)((hi << 4) | lo); | |
| 93 | + s += 3; | |
| 94 | + } else if (*s == '+') { | |
| 95 | + *o++ = ' '; | |
| 96 | + s++; | |
| 97 | + } else { | |
| 98 | + *o++ = *s++; | |
| 99 | + } | |
| 100 | + } | |
| 101 | + *o = '\0'; | |
| 102 | +} | |
| 103 | + | |
| 104 | +/* Copy one query parameter into out. Returns 1 when present. */ | |
| 105 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 106 | +{ | |
| 107 | + size_t klen = strlen(key); | |
| 108 | + const char *p = qs; | |
| 109 | + | |
| 110 | + if (outsz) out[0] = '\0'; | |
| 111 | + if (!qs || !klen) return 0; | |
| 112 | + | |
| 113 | + while (p && *p) { | |
| 114 | + const char *amp = strchr(p, '&'); | |
| 115 | + const char *end = amp ? amp : p + strlen(p); | |
| 116 | + const char *eq = memchr(p, '=', (size_t)(end - p)); | |
| 117 | + | |
| 118 | + if (eq && (size_t)(eq - p) == klen && strncmp(p, key, klen) == 0) { | |
| 119 | + size_t vlen = (size_t)(end - eq - 1); | |
| 120 | + if (vlen >= outsz) vlen = outsz ? outsz - 1 : 0; | |
| 121 | + if (vlen) memcpy(out, eq + 1, vlen); | |
| 122 | + out[vlen] = '\0'; | |
| 123 | + url_decode(out); | |
| 124 | + return 1; | |
| 125 | + } | |
| 126 | + p = amp ? amp + 1 : NULL; | |
| 127 | + } | |
| 128 | + return 0; | |
| 129 | +} | |
| 130 | + | |
| 131 | +static void json_str(const char *s) | |
| 132 | +{ | |
| 133 | + const unsigned char *p = (const unsigned char *)s; | |
| 134 | + fputc('"', stdout); | |
| 135 | + if (p) { | |
| 136 | + for (; *p; p++) { | |
| 137 | + switch (*p) { | |
| 138 | + case '"': fputs("\\\"", stdout); break; | |
| 139 | + case '\\': fputs("\\\\", stdout); break; | |
| 140 | + case '\n': fputs("\\n", stdout); break; | |
| 141 | + case '\r': fputs("\\r", stdout); break; | |
| 142 | + case '\t': fputs("\\t", stdout); break; | |
| 143 | + default: | |
| 144 | + if (*p < 0x20) printf("\\u%04x", *p); | |
| 145 | + else fputc((int)*p, stdout); | |
| 146 | + } | |
| 147 | + } | |
| 148 | + } | |
| 149 | + fputc('"', stdout); | |
| 150 | +} | |
| 151 | + | |
| 152 | +static void utc_now(char *buf, size_t sz) | |
| 153 | +{ | |
| 154 | + time_t t = time(NULL); | |
| 155 | + struct tm tmv; | |
| 156 | +#if defined(_WIN32) | |
| 157 | + struct tm *lt = localtime(&t); | |
| 158 | + if (lt) tmv = *lt; | |
| 159 | +#else | |
| 160 | + localtime_r(&t, &tmv); | |
| 161 | +#endif | |
| 162 | +#if defined(_WIN32) | |
| 163 | + { | |
| 164 | + struct tm *gp = gmtime(&t); | |
| 165 | + if (gp) tmv = *gp; | |
| 166 | + } | |
| 167 | +#endif | |
| 168 | + strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); | |
| 169 | +} | |
| 170 | + | |
| 171 | +/* Copy into out, trimming leading/trailing whitespace and CR/LF. */ | |
| 172 | +static void trim_into(char *out, size_t osz, const char *src, size_t n) | |
| 173 | +{ | |
| 174 | + size_t i = 0, k; | |
| 175 | + if (!osz) return; | |
| 176 | + while (i < n && (src[i] == ' ' || src[i] == '\t' || src[i] == '\r' || src[i] == '\n')) i++; | |
| 177 | + while (n > i && (src[n - 1] == ' ' || src[n - 1] == '\t' || | |
| 178 | + src[n - 1] == '\r' || src[n - 1] == '\n')) n--; | |
| 179 | + k = n - i; | |
| 180 | + if (k >= osz) k = osz - 1; | |
| 181 | + /* callers trim a buffer in place, so the move may overlap */ | |
| 182 | + if (k) memmove(out, src + i, k); | |
| 183 | + out[k] = '\0'; | |
| 184 | +} | |
| 185 | + | |
| 186 | +static int ci_contains(const char *hay, const char *needle) | |
| 187 | +{ | |
| 188 | + size_t nl; | |
| 189 | + if (!hay || !needle || !*needle) return 1; | |
| 190 | + nl = strlen(needle); | |
| 191 | + for (; *hay; hay++) { | |
| 192 | + size_t i = 0; | |
| 193 | + while (i < nl && hay[i] && | |
| 194 | + tolower((unsigned char)hay[i]) == tolower((unsigned char)needle[i])) i++; | |
| 195 | + if (i == nl) return 1; | |
| 196 | + } | |
| 197 | + return 0; | |
| 198 | +} | |
| 199 | + | |
| 200 | +/* Case-insensitive substring test used for severity heuristics. */ | |
| 201 | +static int has_word(const char *s, const char *w) | |
| 202 | +{ | |
| 203 | + return ci_contains(s, w); | |
| 204 | +} | |
| 205 | + | |
| 206 | +static int severity_of(const char *text, const char *level) | |
| 207 | +{ | |
| 208 | + if (level && *level) { | |
| 209 | + if (has_word(level, "err") || has_word(level, "crit") || | |
| 210 | + has_word(level, "alert") || has_word(level, "emerg")) | |
| 211 | + return SEV_ERR; | |
| 212 | + if (has_word(level, "warn")) return SEV_WARN; | |
| 213 | + } | |
| 214 | + if (!text) return SEV_INFO; | |
| 215 | + if (has_word(text, "panic") || has_word(text, "fatal") || | |
| 216 | + has_word(text, "critical") || has_word(text, "segfault") || | |
| 217 | + has_word(text, "traceback") || has_word(text, "error") || | |
| 218 | + has_word(text, "err:") || has_word(text, "failed") || | |
| 219 | + has_word(text, "failure") || has_word(text, "denied")) | |
| 220 | + return SEV_ERR; | |
| 221 | + if (has_word(text, "warn") || has_word(text, "deprecated") || | |
| 222 | + has_word(text, "timeout") || has_word(text, "retry")) | |
| 223 | + return SEV_WARN; | |
| 224 | + return SEV_INFO; | |
| 225 | +} | |
| 226 | + | |
| 227 | +static const char *sev_name(int sev) | |
| 228 | +{ | |
| 229 | + return sev == SEV_ERR ? "err" : sev == SEV_WARN ? "warn" : "info"; | |
| 230 | +} | |
| 231 | + | |
| 232 | +/* ------------------------------------------------------------------ */ | |
| 233 | +/* Node authentication */ | |
| 234 | +/* ------------------------------------------------------------------ */ | |
| 235 | + | |
| 236 | +/* | |
| 237 | + * The node API on the node's api port is reachable from the LAN. Every request | |
| 238 | + * except --meta discovery must prove it knows the node password. Accepted | |
| 239 | + * forms match the rest of the node API: X-Bot-Password (what the web front | |
| 240 | + * proxies with), Authorization: Bearer, and ?pwd= (what the plugin iframe | |
| 241 | + * appends). When BOT_PASSWORD is unset the plugin is a deliberate no-op, which | |
| 242 | + * is how a developer runs it locally from a shell. | |
| 243 | + */ | |
| 244 | +static void require_node_auth(void) | |
| 245 | +{ | |
| 246 | + const char *np = getenv("BOT_PASSWORD"); | |
| 247 | + const char *xp; | |
| 248 | + const char *auth; | |
| 249 | + char qpwd[256]; | |
| 250 | + const char *qs; | |
| 251 | + | |
| 252 | + if (!np || !*np) return; | |
| 253 | + | |
| 254 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | |
| 255 | + if (xp && strcmp(xp, np) == 0) return; | |
| 256 | + | |
| 257 | + auth = getenv("HTTP_AUTHORIZATION"); | |
| 258 | + if (auth) { | |
| 259 | + while (*auth == ' ') auth++; | |
| 260 | + if (strncmp(auth, "Bearer ", 7) == 0) { | |
| 261 | + auth += 7; | |
| 262 | + while (*auth == ' ') auth++; | |
| 263 | + if (strcmp(auth, np) == 0) return; | |
| 264 | + } | |
| 265 | + } | |
| 266 | + | |
| 267 | + qs = getenv("QUERY_STRING"); | |
| 268 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | |
| 269 | + return; | |
| 270 | + | |
| 271 | + fputs("Status: 401 Unauthorized\r\n" | |
| 272 | + "Content-Type: application/json; charset=utf-8\r\n" | |
| 273 | + "Cache-Control: no-store\r\n" | |
| 274 | + "X-Content-Type-Options: nosniff\r\n\r\n" | |
| 275 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | |
| 276 | + exit(0); | |
| 277 | +} | |
| 278 | + | |
| 279 | +/* ------------------------------------------------------------------ */ | |
| 280 | +/* Source registry */ | |
| 281 | +/* ------------------------------------------------------------------ */ | |
| 282 | + | |
| 283 | +typedef struct { | |
| 284 | + char id[600]; /* journal | journal:<unit> | file:<path> | event:<log> */ | |
| 285 | + char label[96]; | |
| 286 | + char kind[10]; /* journal | file | event */ | |
| 287 | + long long size; | |
| 288 | + long mtime; | |
| 289 | +} src_t; | |
| 290 | + | |
| 291 | +typedef struct { | |
| 292 | + int journal_avail; | |
| 293 | + src_t items[MAX_SRC]; | |
| 294 | + int n; | |
| 295 | + int truncated; | |
| 296 | +} srcs_t; | |
| 297 | + | |
| 298 | +static void add_src(srcs_t *o, const char *id, const char *label, | |
| 299 | + const char *kind, long long size, long mtime) | |
| 300 | +{ | |
| 301 | + int i; | |
| 302 | + if (o->n >= MAX_SRC) { o->truncated = 1; return; } | |
| 303 | + for (i = 0; i < o->n; i++) | |
| 304 | + if (strcmp(o->items[i].id, id) == 0) return; | |
| 305 | + snprintf(o->items[o->n].id, sizeof(o->items[0].id), "%s", id); | |
| 306 | + snprintf(o->items[o->n].label, sizeof(o->items[0].label), "%s", label); | |
| 307 | + snprintf(o->items[o->n].kind, sizeof(o->items[0].kind), "%s", kind); | |
| 308 | + o->items[o->n].size = size; | |
| 309 | + o->items[o->n].mtime = mtime; | |
| 310 | + o->n++; | |
| 311 | +} | |
| 312 | + | |
| 313 | +static const char *base_name(const char *path) | |
| 314 | +{ | |
| 315 | + const char *s = path; | |
| 316 | + const char *b = path; | |
| 317 | + for (; *s; s++) | |
| 318 | + if (*s == '/' || *s == '\\') b = s + 1; | |
| 319 | + return b; | |
| 320 | +} | |
| 321 | + | |
| 322 | +#if !defined(_WIN32) | |
| 323 | + | |
| 324 | +static int has_log_suffix(const char *name) | |
| 325 | +{ | |
| 326 | + size_t l = strlen(name); | |
| 327 | + return l > 4 && strcmp(name + l - 4, ".log") == 0; | |
| 328 | +} | |
| 329 | + | |
| 330 | +static void add_file_src(srcs_t *o, const char *path) | |
| 331 | +{ | |
| 332 | + struct stat st; | |
| 333 | + char id[600]; | |
| 334 | + if (o->n >= MAX_SRC) { o->truncated = 1; return; } | |
| 335 | + if (stat(path, &st) != 0) return; | |
| 336 | + if (!S_ISREG(st.st_mode)) return; | |
| 337 | + if (st.st_size <= 0) return; | |
| 338 | + if (strlen(path) + 6 >= sizeof(id)) return; | |
| 339 | + snprintf(id, sizeof(id), "file:%s", path); | |
| 340 | + add_src(o, id, base_name(path), "file", (long long)st.st_size, (long)st.st_mtime); | |
| 341 | +} | |
| 342 | + | |
| 343 | +/* | |
| 344 | + * Bounded walk of one allowlisted root. Each root carries its own entry | |
| 345 | + * budget so a large /workspace can never consume the allowance that | |
| 346 | + * $HOME/.scorpiox needs. Symlinks are never followed. | |
| 347 | + */ | |
| 348 | +static void scan_root(srcs_t *o, const char *dir, int depth, int *budget, int log_only) | |
| 349 | +{ | |
| 350 | + DIR *d; | |
| 351 | + struct dirent *e; | |
| 352 | + char p[1024]; | |
| 353 | + | |
| 354 | + if (depth < 0 || *budget <= 0 || !dir || !*dir) return; | |
| 355 | + d = opendir(dir); | |
| 356 | + if (!d) return; | |
| 357 | + | |
| 358 | + while ((e = readdir(d)) != NULL) { | |
| 359 | + struct stat st; | |
| 360 | + if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0) continue; | |
| 361 | + if (--(*budget) <= 0) { o->truncated = 1; break; } | |
| 362 | + if (strlen(dir) + strlen(e->d_name) + 2 >= sizeof(p)) continue; | |
| 363 | + snprintf(p, sizeof(p), "%s/%s", dir, e->d_name); | |
| 364 | + if (lstat(p, &st) != 0) continue; | |
| 365 | + if (S_ISLNK(st.st_mode)) continue; | |
| 366 | + if (S_ISDIR(st.st_mode)) { | |
| 367 | + if (depth > 0) scan_root(o, p, depth - 1, budget, log_only); | |
| 368 | + } else if (S_ISREG(st.st_mode)) { | |
| 369 | + if (!log_only || has_log_suffix(e->d_name)) add_file_src(o, p); | |
| 370 | + } | |
| 371 | + } | |
| 372 | + closedir(d); | |
| 373 | +} | |
| 374 | + | |
| 375 | +/* | |
| 376 | + * "journalctl exists" is not the same as "this node has a journal". Debian | |
| 377 | + * slim containers ship the binary with no journald running underneath, so the | |
| 378 | + * UI would offer a source that silently returns nothing. Require the binary | |
| 379 | + * AND one of the two journal directories systemd actually writes. | |
| 380 | + */ | |
| 381 | +static int journal_available(void) | |
| 382 | +{ | |
| 383 | + static const char *bins[] = { | |
| 384 | + "/usr/bin/journalctl", "/bin/journalctl", | |
| 385 | + "/usr/local/bin/journalctl", "/usr/sbin/journalctl", NULL | |
| 386 | + }; | |
| 387 | + static const char *dirs[] = { | |
| 388 | + "/run/systemd/journal", "/run/log/journal", "/var/log/journal", NULL | |
| 389 | + }; | |
| 390 | + int i, have_bin = 0, have_dir = 0; | |
| 391 | + | |
| 392 | + for (i = 0; bins[i]; i++) | |
| 393 | + if (access(bins[i], X_OK) == 0) { have_bin = 1; break; } | |
| 394 | + if (!have_bin) return 0; | |
| 395 | + for (i = 0; dirs[i]; i++) | |
| 396 | + if (access(dirs[i], F_OK) == 0) { have_dir = 1; break; } | |
| 397 | + return have_dir; | |
| 398 | +} | |
| 399 | + | |
| 400 | +static void scan_sources(srcs_t *o) | |
| 401 | +{ | |
| 402 | + int budget; | |
| 403 | + char home[512]; | |
| 404 | + char p[1024]; | |
| 405 | + | |
| 406 | + memset(o, 0, sizeof(*o)); | |
| 407 | + | |
| 408 | +#if defined(_WIN32) | |
| 409 | + o->journal_avail = 0; /* Windows exposes the event log instead */ | |
| 410 | +#else | |
| 411 | + o->journal_avail = journal_available(); | |
| 412 | +# if defined(__APPLE__) | |
| 413 | + /* `log` is part of the base system and needs no daemon probe */ | |
| 414 | + o->journal_avail = 1; | |
| 415 | +# endif | |
| 416 | +#endif | |
| 417 | + | |
| 418 | + if (o->journal_avail) | |
| 419 | + add_src(o, "journal", | |
| 420 | +# if defined(__APPLE__) | |
| 421 | + "Unified log", | |
| 422 | +# else | |
| 423 | + "System journal", | |
| 424 | +# endif | |
| 425 | + "journal", 0LL, 0L); | |
| 426 | + | |
| 427 | +#if defined(__APPLE__) | |
| 428 | + /* the per-file *.log scan plus the classic system.log */ | |
| 429 | + budget = 8000; | |
| 430 | + scan_root(o, "/var/log", 0, &budget, 1); | |
| 431 | + add_file_src(o, "/var/log/system.log"); | |
| 432 | + | |
| 433 | + home[0] = '\0'; | |
| 434 | + if (getenv("HOME")) snprintf(home, sizeof(home), "%s", getenv("HOME")); | |
| 435 | + if (home[0]) { | |
| 436 | + snprintf(p, sizeof(p), "%s/Library/Logs", home); | |
| 437 | + budget = 8000; | |
| 438 | + scan_root(o, p, 3, &budget, 1); | |
| 439 | + } | |
| 440 | +#else | |
| 441 | + /* the per-file *.log scan plus the distro-specific aggregate files */ | |
| 442 | + budget = 12000; | |
| 443 | + scan_root(o, "/var/log", 0, &budget, 1); | |
| 444 | + add_file_src(o, "/var/log/syslog"); | |
| 445 | + add_file_src(o, "/var/log/messages"); | |
| 446 | + add_file_src(o, "/var/log/kern.log"); | |
| 447 | + add_file_src(o, "/var/log/auth.log"); | |
| 448 | + | |
| 449 | + home[0] = '\0'; | |
| 450 | + if (getenv("HOME")) snprintf(home, sizeof(home), "%s", getenv("HOME")); | |
| 451 | + if (home[0]) { | |
| 452 | + snprintf(p, sizeof(p), "%s/.scorpiox", home); | |
| 453 | + budget = ROOT_BUDGET; | |
| 454 | + scan_root(o, p, 4, &budget, 1); | |
| 455 | + } | |
| 456 | + budget = ROOT_BUDGET; | |
| 457 | + scan_root(o, "/workspace", 4, &budget, 1); | |
| 458 | +#endif | |
| 459 | + | |
| 460 | + /* | |
| 461 | + * Test-only knob: one extra allowlisted root so tests/run.sh can point the | |
| 462 | + * plugin at fixture logs without inventing a path that production would | |
| 463 | + * never serve. Only the operator who starts the process can set it. | |
| 464 | + */ | |
| 465 | + { | |
| 466 | + const char *extra = getenv("SX_LOGS_EXTRA_ROOT"); | |
| 467 | + if (extra && *extra) { | |
| 468 | + budget = 4000; | |
| 469 | + scan_root(o, extra, 2, &budget, 1); | |
| 470 | + } | |
| 471 | + } | |
| 472 | +} | |
| 473 | + | |
| 474 | +#else /* _WIN32 */ | |
| 475 | + | |
| 476 | +static int has_log_suffix(const char *name) | |
| 477 | +{ | |
| 478 | + size_t l = strlen(name); | |
| 479 | + return l > 4 && strcmp(name + l - 4, ".log") == 0; | |
| 480 | +} | |
| 481 | + | |
| 482 | +static void add_file_src(srcs_t *o, const char *path) | |
| 483 | +{ | |
| 484 | + DWORD a = GetFileAttributesA(path); | |
| 485 | + WIN32_FILE_ATTRIBUTE_DATA fad; | |
| 486 | + char id[600]; | |
| 487 | + if (o->n >= MAX_SRC) { o->truncated = 1; return; } | |
| 488 | + if (a == INVALID_FILE_ATTRIBUTES) return; | |
| 489 | + if (a & FILE_ATTRIBUTE_DIRECTORY) return; | |
| 490 | + if (strlen(path) + 6 >= sizeof(id)) return; | |
| 491 | + if (!GetFileAttributesExA(path, GetFileExInfoStandard, &fad)) return; | |
| 492 | + snprintf(id, sizeof(id), "file:%s", path); | |
| 493 | + add_src(o, id, base_name(path), "file", | |
| 494 | + (long long)fad.nFileSizeLow, 0L); | |
| 495 | +} | |
| 496 | + | |
| 497 | +static void scan_root(srcs_t *o, const char *dir, int depth, int *budget, int log_only) | |
| 498 | +{ | |
| 499 | + WIN32_FIND_DATAA fd; | |
| 500 | + HANDLE h; | |
| 501 | + char pat[1024]; | |
| 502 | + char p[1024]; | |
| 503 | + | |
| 504 | + if (depth < 0 || *budget <= 0 || !dir || !*dir) return; | |
| 505 | + if (strlen(dir) + 3 >= sizeof(pat)) return; | |
| 506 | + snprintf(pat, sizeof(pat), "%s\\*", dir); | |
| 507 | + h = FindFirstFileA(pat, &fd); | |
| 508 | + if (h == INVALID_HANDLE_VALUE) return; | |
| 509 | + | |
| 510 | + do { | |
| 511 | + if (strcmp(fd.cFileName, ".") == 0 || strcmp(fd.cFileName, "..") == 0) continue; | |
| 512 | + if (--(*budget) <= 0) { o->truncated = 1; break; } | |
| 513 | + if (strlen(dir) + strlen(fd.cFileName) + 2 >= sizeof(p)) continue; | |
| 514 | + snprintf(p, sizeof(p), "%s\\%s", dir, fd.cFileName); | |
| 515 | + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { | |
| 516 | + if (depth > 0) scan_root(o, p, depth - 1, budget, log_only); | |
| 517 | + } else if (!log_only || has_log_suffix(fd.cFileName)) { | |
| 518 | + add_file_src(o, p); | |
| 519 | + } | |
| 520 | + } while (FindNextFileA(h, &fd)); | |
| 521 | + FindClose(h); | |
| 522 | +} | |
| 523 | + | |
| 524 | +static void scan_sources(srcs_t *o) | |
| 525 | +{ | |
| 526 | + int budget = ROOT_BUDGET; | |
| 527 | + char p[1024]; | |
| 528 | + const char *lad = getenv("LOCALAPPDATA"); | |
| 529 | + | |
| 530 | + memset(o, 0, sizeof(*o)); | |
| 531 | + o->journal_avail = 0; /* Windows uses the event log instead */ | |
| 532 | + | |
| 533 | + /* The two archives the plugin exposes on Windows. */ | |
| 534 | + add_src(o, "event:System", "Windows System log", "event", 0LL, 0L); | |
| 535 | + add_src(o, "event:Application", "Windows Application log", "event", 0LL, 0L); | |
| 536 | + | |
| 537 | + if (lad && *lad) { | |
| 538 | + snprintf(p, sizeof(p), "%s\\scorpiox", lad); | |
| 539 | + scan_root(o, p, 4, &budget, 1); | |
| 540 | + } | |
| 541 | + if (getenv("USERPROFILE")) { | |
| 542 | + snprintf(p, sizeof(p), "%s\\AppData\\Local\\scorpiox", getenv("USERPROFILE")); | |
| 543 | + scan_root(o, p, 4, &budget, 1); | |
| 544 | + } | |
| 545 | +} | |
| 546 | + | |
| 547 | +#endif | |
| 548 | + | |
| 549 | +/* Resolve a src id to an allowlisted entry. Returns NULL if not in the list. */ | |
| 550 | +static const src_t *find_src(const srcs_t *o, const char *id) | |
| 551 | +{ | |
| 552 | + int i; | |
| 553 | + if (!id || !*id) return NULL; | |
| 554 | + for (i = 0; i < o->n; i++) | |
| 555 | + if (strcmp(o->items[i].id, id) == 0) return &o->items[i]; | |
| 556 | + return NULL; | |
| 557 | +} | |
| 558 | + | |
| 559 | +/* ------------------------------------------------------------------ */ | |
| 560 | +/* Entry lists */ | |
| 561 | +/* ------------------------------------------------------------------ */ | |
| 562 | + | |
| 563 | +typedef struct { | |
| 564 | + char ts[ENTRY_TS]; | |
| 565 | + char unit[ENTRY_UNIT]; | |
| 566 | + int sev; | |
| 567 | + char text[ENTRY_TEXT]; | |
| 568 | +} entry_t; | |
| 569 | + | |
| 570 | +typedef struct { | |
| 571 | + entry_t *v; | |
| 572 | + int cap; | |
| 573 | + int n; | |
| 574 | + int start; | |
| 575 | +} ring_t; | |
| 576 | + | |
| 577 | +static int ring_init(ring_t *r, int cap) | |
| 578 | +{ | |
| 579 | + if (cap < 1) cap = 1; | |
| 580 | + r->v = (entry_t *)calloc((size_t)cap, sizeof(entry_t)); | |
| 581 | + if (!r->v) return 0; | |
| 582 | + r->cap = cap; | |
| 583 | + r->n = 0; | |
| 584 | + r->start = 0; | |
| 585 | + return 1; | |
| 586 | +} | |
| 587 | + | |
| 588 | +static void ring_add(ring_t *r, const entry_t *e) | |
| 589 | +{ | |
| 590 | + if (r->n < r->cap) { | |
| 591 | + r->v[(r->start + r->n) % r->cap] = *e; | |
| 592 | + r->n++; | |
| 593 | + } else { | |
| 594 | + r->v[r->start] = *e; | |
| 595 | + r->start = (r->start + 1) % r->cap; | |
| 596 | + } | |
| 597 | +} | |
| 598 | + | |
| 599 | +static entry_t *ring_at(ring_t *r, int i) | |
| 600 | +{ | |
| 601 | + return &r->v[(r->start + i) % r->cap]; | |
| 602 | +} | |
| 603 | + | |
| 604 | +static void ring_free(ring_t *r) | |
| 605 | +{ | |
| 606 | + free(r->v); | |
| 607 | + r->v = NULL; | |
| 608 | +} | |
| 609 | + | |
| 610 | +typedef struct { | |
| 611 | + entry_t *v; | |
| 612 | + int cap; | |
| 613 | + int n; | |
| 614 | +} list_t; | |
| 615 | + | |
| 616 | +static int list_init(list_t *l, int cap) | |
| 617 | +{ | |
| 618 | + if (cap < 1) cap = 1; | |
| 619 | + l->v = (entry_t *)calloc((size_t)cap, sizeof(entry_t)); | |
| 620 | + if (!l->v) return 0; | |
| 621 | + l->cap = cap; | |
| 622 | + l->n = 0; | |
| 623 | + return 1; | |
| 624 | +} | |
| 625 | + | |
| 626 | +static void list_free(list_t *l) | |
| 627 | +{ | |
| 628 | + free(l->v); | |
| 629 | + l->v = NULL; | |
| 630 | +} | |
| 631 | + | |
| 632 | +/* ------------------------------------------------------------------ */ | |
| 633 | +/* Command execution (fixed argv only) */ | |
| 634 | +/* ------------------------------------------------------------------ */ | |
| 635 | + | |
| 636 | +static FILE *run_cmd(const char *cmd) | |
| 637 | +{ | |
| 638 | +#if defined(_WIN32) | |
| 639 | + return _popen(cmd, "r"); | |
| 640 | +#else | |
| 641 | + return popen(cmd, "r"); | |
| 642 | +#endif | |
| 643 | +} | |
| 644 | + | |
| 645 | +static int close_cmd(FILE *f) | |
| 646 | +{ | |
| 647 | +#if defined(_WIN32) | |
| 648 | + return _pclose(f); | |
| 649 | +#else | |
| 650 | + return pclose(f); | |
| 651 | +#endif | |
| 652 | +} | |
| 653 | + | |
| 654 | +/* Validate a systemd unit name before it can reach the fixed argv. */ | |
| 655 | +static int valid_unit(const char *u) | |
| 656 | +{ | |
| 657 | + size_t i, l; | |
| 658 | + if (!u || !*u) return 0; | |
| 659 | + l = strlen(u); | |
| 660 | + if (l > 128) return 0; | |
| 661 | + for (i = 0; i < l; i++) { | |
| 662 | + unsigned char c = (unsigned char)u[i]; | |
| 663 | + if (!(isalnum(c) || c == '@' || c == '.' || c == '_' || c == '-')) | |
| 664 | + return 0; | |
| 665 | + } | |
| 666 | + /* a leading '-' would read as an option to journalctl */ | |
| 667 | + return u[0] != '-'; | |
| 668 | +} | |
| 669 | + | |
| 670 | +/* ------------------------------------------------------------------ */ | |
| 671 | +/* Journal parsing (journalctl -o json, one object per line) */ | |
| 672 | +/* ------------------------------------------------------------------ */ | |
| 673 | + | |
| 674 | +/* | |
| 675 | + * Extract one top-level key's value from a single journal JSON object line. | |
| 676 | + * Handles string values with backslash escapes, numeric values, and String | |
| 677 | + * arrays (journal stores binary or multi-line MESSAGE fields as arrays, which | |
| 678 | + * this plugin renders as a placeholder rather than pretending to decode). | |
| 679 | + */ | |
| 680 | +static int jget(const char *line, const char *key, char *out, size_t osz) | |
| 681 | +{ | |
| 682 | + char pat[128]; | |
| 683 | + const char *p; | |
| 684 | + | |
| 685 | + if (osz) out[0] = '\0'; | |
| 686 | + if (!line || !key || !*key) return 0; | |
| 687 | + /* the search key is a fixed literal from this file, never user input */ | |
| 688 | + snprintf(pat, sizeof(pat), "\"%s\"", key); | |
| 689 | + | |
| 690 | + for (p = line; (p = strstr(p, pat)) != NULL; p += strlen(pat)) { | |
| 691 | + const char *q = p + strlen(pat); | |
| 692 | + while (*q == ' ' || *q == '\t') q++; | |
| 693 | + if (*q != ':') continue; /* a value that happens to match */ | |
| 694 | + q++; | |
| 695 | + while (*q == ' ' || *q == '\t') q++; | |
| 696 | + | |
| 697 | + if (*q == '"') { | |
| 698 | + size_t o = 0; | |
| 699 | + q++; | |
| 700 | + while (*q && *q != '"') { | |
| 701 | + char c = *q; | |
| 702 | + if (c == '\\' && q[1]) { | |
| 703 | + q++; | |
| 704 | + switch (*q) { | |
| 705 | + case 'n': c = '\n'; break; | |
| 706 | + case 'r': c = '\r'; break; | |
| 707 | + case 't': c = '\t'; break; | |
| 708 | + case '"': c = '"'; break; | |
| 709 | + case '\\': c = '\\'; break; | |
| 710 | + case '/': c = '/'; break; | |
| 711 | + default: c = *q; break; | |
| 712 | + } | |
| 713 | + } | |
| 714 | + if (o + 1 < osz) out[o++] = c; | |
| 715 | + q++; | |
| 716 | + } | |
| 717 | + out[o] = '\0'; | |
| 718 | + return 1; | |
| 719 | + } | |
| 720 | + if (*q == '[') { | |
| 721 | + /* journal stores binary or multi-line fields as byte arrays */ | |
| 722 | + snprintf(out, osz, "(binary)"); | |
| 723 | + return 1; | |
| 724 | + } | |
| 725 | + { | |
| 726 | + size_t o = 0; | |
| 727 | + while (*q && *q != ',' && *q != '}') { | |
| 728 | + if (o + 1 < osz) out[o++] = *q; | |
| 729 | + q++; | |
| 730 | + } | |
| 731 | + out[o] = '\0'; | |
| 732 | + return 1; | |
| 733 | + } | |
| 734 | + } | |
| 735 | + return 0; | |
| 736 | +} | |
| 737 | + | |
| 738 | +static void fmt_journal_ts(const char *us, char *out, size_t osz) | |
| 739 | +{ | |
| 740 | + long long v; | |
| 741 | + time_t secs; | |
| 742 | + struct tm tmv; | |
| 743 | + if (!us || !*us) { snprintf(out, osz, "-"); return; } | |
| 744 | + v = atoll(us); | |
| 745 | + if (v <= 0) { snprintf(out, osz, "-"); return; } | |
| 746 | + secs = (time_t)(v / 1000000LL); | |
| 747 | + if (!localtime_r(&secs, &tmv)) { snprintf(out, osz, "-"); return; } | |
| 748 | + strftime(out, osz, "%m-%d %H:%M:%S", &tmv); | |
| 749 | +} | |
| 750 | + | |
| 751 | +/* | |
| 752 | + * Stream journalctl into `sink`. `filter` (optional) keeps only lines whose | |
| 753 | + * text, unit or timestamp matches case-insensitively. Returns the number of | |
| 754 | + * lines scanned, or -1 when journalctl could not be run. | |
| 755 | + */ | |
| 756 | +typedef void (*entry_sink)(void *ctx, const entry_t *e); | |
| 757 | + | |
| 758 | +static int stream_journal(const char *unit, int nlines, const char *filter, | |
| 759 | + entry_sink sink, void *ctx) | |
| 760 | +{ | |
| 761 | +#if defined(_WIN32) | |
| 762 | + (void)unit; (void)nlines; (void)filter; (void)sink; (void)ctx; | |
| 763 | + return -1; | |
| 764 | +#else | |
| 765 | + char cmd[512]; | |
| 766 | + FILE *f; | |
| 767 | + char line[8192]; | |
| 768 | + int scanned = 0; | |
| 769 | + int uok = unit && *unit && valid_unit(unit); | |
| 770 | + const char *fixture = getenv("SX_LOGS_JOURNAL_FIXTURE"); | |
| 771 | + | |
| 772 | + if (unit && *unit && !uok) return -1; | |
| 773 | + if (nlines < 1) nlines = 1; | |
| 774 | + if (nlines > TAIL_MAX) nlines = TAIL_MAX; | |
| 775 | + | |
| 776 | + if (uok) | |
| 777 | + snprintf(cmd, sizeof(cmd), | |
| 778 | + "journalctl -o json --no-pager -n %d -u %s 2>/dev/null", nlines, unit); | |
| 779 | + else | |
| 780 | + snprintf(cmd, sizeof(cmd), | |
| 781 | + "journalctl -o json --no-pager -n %d 2>/dev/null", nlines); | |
| 782 | + | |
| 783 | + /* test-only: replay a captured journalctl -o json stream */ | |
| 784 | + if (fixture && *fixture) f = fopen(fixture, "r"); | |
| 785 | + else f = run_cmd(cmd); | |
| 786 | + if (!f) return -1; | |
| 787 | + | |
| 788 | + while (fgets(line, sizeof(line), f)) { | |
| 789 | + entry_t e; | |
| 790 | + char msg[ENTRY_TEXT] = ""; | |
| 791 | + char pri[8] = ""; | |
| 792 | + char tsus[32] = ""; | |
| 793 | + char un[ENTRY_UNIT] = ""; | |
| 794 | + int prio; | |
| 795 | + | |
| 796 | + if (line[0] != '{') continue; | |
| 797 | + scanned++; | |
| 798 | + jget(line, "MESSAGE", msg, sizeof(msg)); | |
| 799 | + jget(line, "PRIORITY", pri, sizeof(pri)); | |
| 800 | + jget(line, "__REALTIME_TIMESTAMP", tsus, sizeof(tsus)); | |
| 801 | + if (!jget(line, "_SYSTEMD_UNIT", un, sizeof(un))) | |
| 802 | + jget(line, "SYSLOG_IDENTIFIER", un, sizeof(un)); | |
| 803 | + | |
| 804 | + memset(&e, 0, sizeof(e)); | |
| 805 | + fmt_journal_ts(tsus, e.ts, sizeof(e.ts)); | |
| 806 | + snprintf(e.unit, sizeof(e.unit), "%s", un); | |
| 807 | + prio = pri[0] ? atoi(pri) : 6; | |
| 808 | + e.sev = prio <= 3 ? SEV_ERR : prio == 4 ? SEV_WARN : SEV_INFO; | |
| 809 | + snprintf(e.text, sizeof(e.text), "%s", msg); | |
| 810 | + if (e.sev == SEV_INFO) e.sev = severity_of(e.text, NULL); | |
| 811 | + | |
| 812 | + if (filter && *filter && !ci_contains(e.text, filter) && | |
| 813 | + !ci_contains(e.unit, filter) && !ci_contains(e.ts, filter)) | |
| 814 | + continue; | |
| 815 | + sink(ctx, &e); | |
| 816 | + } | |
| 817 | + if (fixture && *fixture) fclose(f); | |
| 818 | + else close_cmd(f); | |
| 819 | + return scanned; | |
| 820 | +#endif | |
| 821 | +} | |
| 822 | + | |
| 823 | +/* ------------------------------------------------------------------ */ | |
| 824 | +/* Plain log-file reading */ | |
| 825 | +/* ------------------------------------------------------------------ */ | |
| 826 | + | |
| 827 | +/* | |
| 828 | + * Works out the byte offset to start reading from so only the last `maxbytes` | |
| 829 | + * of a file are considered. Logs grow to gigabytes; a viewer must never read | |
| 830 | + * one in full. | |
| 831 | + */ | |
| 832 | +static long tail_offset(long long size, long maxbytes) | |
| 833 | +{ | |
| 834 | + if (size <= maxbytes) return 0; | |
| 835 | + return (long)(size - maxbytes); | |
| 836 | +} | |
| 837 | + | |
| 838 | +#if !defined(_WIN32) | |
| 839 | +static int open_log(const char *path, FILE **out, long long *size_out) | |
| 840 | +{ | |
| 841 | + struct stat st; | |
| 842 | + if (stat(path, &st) != 0 || !S_ISREG(st.st_mode)) return -1; | |
| 843 | + *out = fopen(path, "rb"); | |
| 844 | + if (!*out) return -1; | |
| 845 | + *size_out = (long long)st.st_size; | |
| 846 | + return 0; | |
| 847 | +} | |
| 848 | +#else | |
| 849 | +static int open_log(const char *path, FILE **out, long long *size_out) | |
| 850 | +{ | |
| 851 | + WIN32_FILE_ATTRIBUTE_DATA fad; | |
| 852 | + if (!GetFileAttributesExA(path, GetFileExInfoStandard, &fad)) return -1; | |
| 853 | + if (fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) return -1; | |
| 854 | + *out = fopen(path, "rb"); | |
| 855 | + if (!*out) return -1; | |
| 856 | + *size_out = (long long)fad.nFileSizeLow; | |
| 857 | + return 0; | |
| 858 | +} | |
| 859 | +#endif | |
| 860 | + | |
| 861 | +/* Fill one entry from a raw log line. Detects the two timestamp layouts that | |
| 862 | + * nearly every text log uses, and falls back to no timestamp. */ | |
| 863 | +static void entry_from_line(entry_t *e, const char *line, size_t n) | |
| 864 | +{ | |
| 865 | + char buf[ENTRY_TEXT * 2]; | |
| 866 | + | |
| 867 | + memset(e, 0, sizeof(*e)); | |
| 868 | + if (n >= sizeof(buf)) n = sizeof(buf) - 1; | |
| 869 | + memcpy(buf, line, n); | |
| 870 | + buf[n] = '\0'; | |
| 871 | + while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; | |
| 872 | + | |
| 873 | + /* syslog: "Nov 12 06:30:01 host unit[pid]: message" */ | |
| 874 | + if (n > 16 && isalpha((unsigned char)buf[0]) && buf[3] == ' ' && | |
| 875 | + isdigit((unsigned char)buf[4]) && buf[6] == ' ' && buf[9] == ':') { | |
| 876 | + snprintf(e->ts, sizeof(e->ts), "%.15s", buf); | |
| 877 | + /* everything after "host " is the text, unit if it looks like one */ | |
| 878 | + { | |
| 879 | + const char *p = buf + 16; | |
| 880 | + const char *colon; | |
| 881 | + while (*p && *p != ' ') p++; | |
| 882 | + while (*p == ' ') p++; | |
| 883 | + colon = strchr(p, ':'); | |
| 884 | + if (colon && (size_t)(colon - p) < sizeof(e->unit) && | |
| 885 | + (size_t)(colon - p) < 64) { | |
| 886 | + snprintf(e->unit, sizeof(e->unit), "%.*s", (int)(colon - p), p); | |
| 887 | + snprintf(e->text, sizeof(e->text), "%s", colon + 1); | |
| 888 | + } else { | |
| 889 | + snprintf(e->text, sizeof(e->text), "%.*s", | |
| 890 | + (int)(sizeof(e->text) - 1), p); | |
| 891 | + } | |
| 892 | + trim_into(e->text, sizeof(e->text), e->text, strlen(e->text)); | |
| 893 | + e->sev = severity_of(e->text, NULL); | |
| 894 | + return; | |
| 895 | + } | |
| 896 | + } | |
| 897 | + | |
| 898 | + /* ISO-8601 prefix: "2026-11-12T06:30:01Z rest" or "2026-11-12 06:30:01 rest" */ | |
| 899 | + if (n > 20 && isdigit((unsigned char)buf[0]) && buf[4] == '-' && buf[7] == '-' && | |
| 900 | + (buf[10] == 'T' || buf[10] == ' ')) { | |
| 901 | + size_t cut = 11; | |
| 902 | + while (cut < n && cut < 32 && buf[cut] != ' ' && buf[cut] != '\t') cut++; | |
| 903 | + snprintf(e->ts, sizeof(e->ts), "%.*s", (int)(cut < 24 ? cut : 24), buf); | |
| 904 | + { | |
| 905 | + const char *p = buf + cut; | |
| 906 | + while (*p == ' ' || *p == '\t') p++; | |
| 907 | + snprintf(e->text, sizeof(e->text), "%.*s", | |
| 908 | + (int)(sizeof(e->text) - 1), p); | |
| 909 | + } | |
| 910 | + e->sev = severity_of(e->text, NULL); | |
| 911 | + return; | |
| 912 | + } | |
| 913 | + | |
| 914 | + snprintf(e->text, sizeof(e->text), "%.*s", | |
| 915 | + (int)(sizeof(e->text) - 1), buf); | |
| 916 | + e->sev = severity_of(e->text, NULL); | |
| 917 | +} | |
| 918 | + | |
| 919 | +typedef struct { | |
| 920 | + ring_t *ring; | |
| 921 | + list_t *hits; | |
| 922 | + const char *filter; | |
| 923 | + int seen; | |
| 924 | + int cap; | |
| 925 | +} file_ctx_t; | |
| 926 | + | |
| 927 | +static void file_sink(void *vctx, const entry_t *e) | |
| 928 | +{ | |
| 929 | + file_ctx_t *c = (file_ctx_t *)vctx; | |
| 930 | + if (c->ring) ring_add(c->ring, e); | |
| 931 | + if (c->hits) { | |
| 932 | + if (c->hits->n < c->cap) c->hits->v[c->hits->n++] = *e; | |
| 933 | + } | |
| 934 | + c->seen++; | |
| 935 | +} | |
| 936 | + | |
| 937 | +/* | |
| 938 | + * Read the tail of a log file. `ring` keeps the last N entries (tail mode); | |
| 939 | + * `hits` collects up to `cap` matching entries (search mode). Exactly one of | |
| 940 | + * them is non-NULL. | |
| 941 | + */ | |
| 942 | +static int read_log_file(const char *path, int nlines, const char *filter, | |
| 943 | + ring_t *ring, list_t *hits, int hitcap) | |
| 944 | +{ | |
| 945 | + FILE *f = NULL; | |
| 946 | + long long size = 0; | |
| 947 | + long off; | |
| 948 | + char line[ENTRY_TEXT * 2]; | |
| 949 | + file_ctx_t ctx; | |
| 950 | + | |
| 951 | + (void)nlines; /* the ring/hit list owns the cap; this is only a hint */ | |
| 952 | + if (open_log(path, &f, &size) != 0) return -1; | |
| 953 | + | |
| 954 | + memset(&ctx, 0, sizeof(ctx)); | |
| 955 | + ctx.ring = ring; | |
| 956 | + ctx.hits = hits; | |
| 957 | + ctx.filter = filter; | |
| 958 | + ctx.cap = hitcap; | |
| 959 | + | |
| 960 | + off = tail_offset(size, FILE_TAIL_BYTES); | |
| 961 | + if (off > 0 && fseek(f, off, SEEK_SET) != 0) { | |
| 962 | + fclose(f); | |
| 963 | + return -1; | |
| 964 | + } | |
| 965 | + | |
| 966 | + while (fgets(line, sizeof(line), f)) { | |
| 967 | + entry_t e; | |
| 968 | + size_t n = strlen(line); | |
| 969 | + /* The first line after a tail seek is a partial line; drop it. */ | |
| 970 | + if (off > 0 && ctx.seen == 0 && n > 0 && line[n - 1] != '\n') { | |
| 971 | + ctx.seen = 0; | |
| 972 | + /* still consume it so we do not emit a broken record */ | |
| 973 | + continue; | |
| 974 | + } | |
| 975 | + if (hits && ctx.seen >= SEARCH_SCAN) break; | |
| 976 | + entry_from_line(&e, line, n); | |
| 977 | + if (filter && *filter && !ci_contains(e.text, filter) && | |
| 978 | + !ci_contains(e.unit, filter) && !ci_contains(e.ts, filter)) | |
| 979 | + { ctx.seen++; continue; } | |
| 980 | + file_sink(&ctx, &e); | |
| 981 | + } | |
| 982 | + fclose(f); | |
| 983 | + return ctx.seen; | |
| 984 | +} | |
| 985 | + | |
| 986 | +/* ------------------------------------------------------------------ */ | |
| 987 | +/* macOS `log show` reading */ | |
| 988 | +/* ------------------------------------------------------------------ */ | |
| 989 | + | |
| 990 | +#if defined(__APPLE__) | |
| 991 | + | |
| 992 | +static int stream_macos_log(int nlines, const char *filter, | |
| 993 | + entry_sink sink, void *ctx) | |
| 994 | +{ | |
| 995 | + char cmd[512]; | |
| 996 | + FILE *f; | |
| 997 | + char line[8192]; | |
| 998 | + int scanned = 0; | |
| 999 | + int mins; | |
| 1000 | + | |
| 1001 | + if (nlines < 1) nlines = 1; | |
| 1002 | + if (nlines > TAIL_MAX) nlines = TAIL_MAX; | |
| 1003 | + /* bound the time window: roughly one minute of syslog per 200 lines */ | |
| 1004 | + mins = nlines / 200; | |
| 1005 | + if (mins < 1) mins = 1; | |
| 1006 | + if (mins > 60) mins = 60; | |
| 1007 | + | |
| 1008 | + snprintf(cmd, sizeof(cmd), | |
| 1009 | + "log show --style compact --last %dm 2>/dev/null | tail -n %d", | |
| 1010 | + mins, nlines); | |
| 1011 | + f = run_cmd(cmd); | |
| 1012 | + if (!f) return -1; | |
| 1013 | + while (fgets(line, sizeof(line), f)) { | |
| 1014 | + entry_t e; | |
| 1015 | + size_t n = strlen(line); | |
| 1016 | + if (filter && *filter && !ci_contains(line, filter)) { scanned++; continue; } | |
| 1017 | + scanned++; | |
| 1018 | + entry_from_line(&e, line, n); | |
| 1019 | + sink(ctx, &e); | |
| 1020 | + } | |
| 1021 | + close_cmd(f); | |
| 1022 | + return scanned; | |
| 1023 | +} | |
| 1024 | + | |
| 1025 | +#endif | |
| 1026 | + | |
| 1027 | +/* ------------------------------------------------------------------ */ | |
| 1028 | +/* Windows event log reading */ | |
| 1029 | +/* ------------------------------------------------------------------ */ | |
| 1030 | + | |
| 1031 | +#if defined(_WIN32) | |
| 1032 | + | |
| 1033 | +static int stream_event_log(const char *channel, int nlines, const char *filter, | |
| 1034 | + entry_sink sink, void *ctx) | |
| 1035 | +{ | |
| 1036 | + char cmd[512]; | |
| 1037 | + FILE *f; | |
| 1038 | + char line[8192]; | |
| 1039 | + int scanned = 0; | |
| 1040 | + | |
| 1041 | + if (nlines < 1) nlines = 1; | |
| 1042 | + if (nlines > TAIL_MAX) nlines = TAIL_MAX; | |
| 1043 | + if (!channel || !*channel) return -1; | |
| 1044 | + /* channel is one of two constants chosen by the caller, never user text */ | |
| 1045 | + if (strcmp(channel, "System") != 0 && strcmp(channel, "Application") != 0) | |
| 1046 | + return -1; | |
| 1047 | + | |
| 1048 | + snprintf(cmd, sizeof(cmd), | |
| 1049 | + "wevtutil qe %s /c:%d /rd:true /f:text 2>NUL", channel, nlines); | |
| 1050 | + f = run_cmd(cmd); | |
| 1051 | + if (!f) return -1; | |
| 1052 | + | |
| 1053 | + { | |
| 1054 | + entry_t e; | |
| 1055 | + int have = 0; | |
| 1056 | + memset(&e, 0, sizeof(e)); | |
| 1057 | + while (fgets(line, sizeof(line), f)) { | |
| 1058 | + char t[ENTRY_TEXT]; | |
| 1059 | + trim_into(t, sizeof(t), line, strlen(line)); | |
| 1060 | + if (!*t) { | |
| 1061 | + if (have && e.text[0]) { | |
| 1062 | + e.sev = severity_of(e.text, NULL); | |
| 1063 | + if (!filter || !*filter || ci_contains(e.text, filter)) | |
| 1064 | + sink(ctx, &e); | |
| 1065 | + scanned++; | |
| 1066 | + } | |
| 1067 | + memset(&e, 0, sizeof(e)); | |
| 1068 | + have = 0; | |
| 1069 | + continue; | |
| 1070 | + } | |
| 1071 | + have = 1; | |
| 1072 | + if (strncmp(t, "Date:", 5) == 0) { | |
| 1073 | + snprintf(e.ts, sizeof(e.ts), "%s", t + 5); | |
| 1074 | + trim_into(e.ts, sizeof(e.ts), e.ts, strlen(e.ts)); | |
| 1075 | + } else if (strncmp(t, "Level:", 6) == 0) { | |
| 1076 | + const char *lv = t + 6; | |
| 1077 | + while (*lv == ' ') lv++; | |
| 1078 | + snprintf(e.unit, sizeof(e.unit), "%s", channel); | |
| 1079 | + if (ci_contains(lv, "Error") || ci_contains(lv, "Critical")) | |
| 1080 | + e.sev = SEV_ERR; | |
| 1081 | + else if (ci_contains(lv, "Warning")) | |
| 1082 | + e.sev = SEV_WARN; | |
| 1083 | + } else if (strncmp(t, "Description:", 12) == 0) { | |
| 1084 | + snprintf(e.text, sizeof(e.text), "%s", t + 12); | |
| 1085 | + trim_into(e.text, sizeof(e.text), e.text, strlen(e.text)); | |
| 1086 | + } | |
| 1087 | + } | |
| 1088 | + if (have && e.text[0]) { | |
| 1089 | + e.sev = severity_of(e.text, NULL); | |
| 1090 | + if (!filter || !*filter || ci_contains(e.text, filter)) | |
| 1091 | + sink(ctx, &e); | |
| 1092 | + scanned++; | |
| 1093 | + } | |
| 1094 | + } | |
| 1095 | + close_cmd(f); | |
| 1096 | + return scanned; | |
| 1097 | +} | |
| 1098 | + | |
| 1099 | +#endif | |
| 1100 | + | |
| 1101 | +/* ------------------------------------------------------------------ */ | |
| 1102 | +/* Units (service providers that have journal entries) */ | |
| 1103 | +/* ------------------------------------------------------------------ */ | |
| 1104 | + | |
| 1105 | +typedef struct { | |
| 1106 | + char name[ENTRY_UNIT]; | |
| 1107 | + int entries; | |
| 1108 | +} unit_t; | |
| 1109 | + | |
| 1110 | +static int list_units(unit_t *out, int max) | |
| 1111 | +{ | |
| 1112 | +#if defined(_WIN32) || defined(__APPLE__) | |
| 1113 | + (void)out; (void)max; | |
| 1114 | + return 0; | |
| 1115 | +#else | |
| 1116 | + FILE *f; | |
| 1117 | + char line[1024]; | |
| 1118 | + int n = 0; | |
| 1119 | + | |
| 1120 | + f = run_cmd("journalctl --no-pager -F _SYSTEMD_UNIT 2>/dev/null | head -n 400"); | |
| 1121 | + if (!f) return 0; | |
| 1122 | + while (fgets(line, sizeof(line), f) && n < max) { | |
| 1123 | + char u[ENTRY_UNIT]; | |
| 1124 | + int i; | |
| 1125 | + trim_into(u, sizeof(u), line, strlen(line)); | |
| 1126 | + if (!*u) continue; | |
| 1127 | + if (!valid_unit(u)) continue; | |
| 1128 | + for (i = 0; i < n; i++) | |
| 1129 | + if (strcmp(out[i].name, u) == 0) break; | |
| 1130 | + if (i < n) continue; | |
| 1131 | + snprintf(out[n].name, sizeof(out[n].name), "%s", u); | |
| 1132 | + out[n].entries = 0; | |
| 1133 | + n++; | |
| 1134 | + } | |
| 1135 | + close_cmd(f); | |
| 1136 | + return n; | |
| 1137 | +#endif | |
| 1138 | +} | |
| 1139 | + | |
| 1140 | +/* ------------------------------------------------------------------ */ | |
| 1141 | +/* Collection helpers */ | |
| 1142 | +/* ------------------------------------------------------------------ */ | |
| 1143 | + | |
| 1144 | +typedef struct { | |
| 1145 | + ring_t *ring; | |
| 1146 | +} shell_ctx_t; | |
| 1147 | + | |
| 1148 | +static void shell_sink(void *vctx, const entry_t *e) | |
| 1149 | +{ | |
| 1150 | + ring_t *r = ((shell_ctx_t *)vctx)->ring; | |
| 1151 | + ring_add(r, e); | |
| 1152 | +} | |
| 1153 | + | |
| 1154 | +/* Stream `nlines` entries for a source into `ring` (tail mode). */ | |
| 1155 | +static int collect_tail(const src_t *s, int nlines, ring_t *ring) | |
| 1156 | +{ | |
| 1157 | + shell_ctx_t ctx; | |
| 1158 | + | |
| 1159 | + ctx.ring = ring; | |
| 1160 | + if (strcmp(s->kind, "journal") == 0) | |
| 1161 | + return stream_journal(NULL, nlines, NULL, shell_sink, &ctx); | |
| 1162 | +#if defined(_WIN32) | |
| 1163 | + if (strncmp(s->id, "event:", 6) == 0) | |
| 1164 | + return stream_event_log(s->id + 6, nlines, NULL, shell_sink, &ctx); | |
| 1165 | +#endif | |
| 1166 | +#if defined(__APPLE__) | |
| 1167 | + if (strcmp(s->kind, "journal") == 0) | |
| 1168 | + return stream_macos_log(nlines, NULL, shell_sink, &ctx); | |
| 1169 | +#endif | |
| 1170 | + if (strncmp(s->id, "file:", 5) == 0) | |
| 1171 | + return read_log_file(s->id + 5, nlines, NULL, ring, NULL, 0); | |
| 1172 | + if (strncmp(s->id, "journal:", 8) == 0) | |
| 1173 | + return stream_journal(s->id + 8, nlines, NULL, shell_sink, &ctx); | |
| 1174 | + return -1; | |
| 1175 | +} | |
| 1176 | + | |
| 1177 | +typedef struct { | |
| 1178 | + list_t *hits; | |
| 1179 | +} hits_ctx_t; | |
| 1180 | + | |
| 1181 | +static void hits_sink(void *vctx, const entry_t *e) | |
| 1182 | +{ | |
| 1183 | + list_t *l = ((hits_ctx_t *)vctx)->hits; | |
| 1184 | + if (l->n < l->cap) l->v[l->n++] = *e; | |
| 1185 | +} | |
| 1186 | + | |
| 1187 | +/* Search a source for `filter`. Returns the number of lines scanned. */ | |
| 1188 | +static int collect_search(const src_t *s, const char *filter, list_t *hits) | |
| 1189 | +{ | |
| 1190 | + hits_ctx_t ctx; | |
| 1191 | + | |
| 1192 | + ctx.hits = hits; | |
| 1193 | + if (strcmp(s->kind, "journal") == 0) | |
| 1194 | + return stream_journal(NULL, TAIL_MAX, filter, hits_sink, &ctx); | |
| 1195 | +#if defined(_WIN32) | |
| 1196 | + if (strncmp(s->id, "event:", 6) == 0) | |
| 1197 | + return stream_event_log(s->id + 6, 600, filter, hits_sink, &ctx); | |
| 1198 | +#endif | |
| 1199 | + if (strncmp(s->id, "file:", 5) == 0) | |
| 1200 | + return read_log_file(s->id + 5, TAIL_MAX, filter, NULL, hits, SEARCH_HITS_MAX); | |
| 1201 | + if (strncmp(s->id, "journal:", 8) == 0) | |
| 1202 | + return stream_journal(s->id + 8, TAIL_MAX, filter, hits_sink, &ctx); | |
| 1203 | + return -1; | |
| 1204 | +} | |
| 1205 | + | |
| 1206 | +/* ------------------------------------------------------------------ */ | |
| 1207 | +/* Modes */ | |
| 1208 | +/* ------------------------------------------------------------------ */ | |
| 1209 | + | |
| 1210 | +static int mode_meta(void) | |
| 1211 | +{ | |
| 1212 | + puts("{\"name\":\"logs\",\"desc\":\"Log viewer\"}"); | |
| 1213 | + return 0; | |
| 1214 | +} | |
| 1215 | + | |
| 1216 | +static void json_header(void) | |
| 1217 | +{ | |
| 1218 | + /* Deliberately no Content-Length - the server owns framing. */ | |
| 1219 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | |
| 1220 | + "Cache-Control: no-store\r\n" | |
| 1221 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 1222 | +} | |
| 1223 | + | |
| 1224 | +static int mode_json(const char *qs) | |
| 1225 | +{ | |
| 1226 | + char action[32]; | |
| 1227 | + char srcid[600]; | |
| 1228 | + char linesv[16]; | |
| 1229 | + char q[256]; | |
| 1230 | + char utc[40]; | |
| 1231 | + srcs_t srcs; | |
| 1232 | + int nlines = 200; | |
| 1233 | + | |
| 1234 | + action[0] = srcid[0] = linesv[0] = q[0] = '\0'; | |
| 1235 | + get_query_val(qs, "action", action, sizeof(action)); | |
| 1236 | + get_query_val(qs, "src", srcid, sizeof(srcid)); | |
| 1237 | + get_query_val(qs, "lines", linesv, sizeof(linesv)); | |
| 1238 | + get_query_val(qs, "q", q, sizeof(q)); | |
| 1239 | + | |
| 1240 | + /* anything above the cap is clamped, never silently ignored */ | |
| 1241 | + if (linesv[0]) { | |
| 1242 | + int v = atoi(linesv); | |
| 1243 | + if (v > 0) nlines = v > TAIL_MAX ? TAIL_MAX : v; | |
| 1244 | + } | |
| 1245 | + | |
| 1246 | + if (!action[0] || (strcmp(action, "sources") != 0 && strcmp(action, "tail") != 0 && | |
| 1247 | + strcmp(action, "search") != 0 && strcmp(action, "units") != 0 && | |
| 1248 | + strcmp(action, "info") != 0)) { | |
| 1249 | + json_header(); | |
| 1250 | + printf("{\"ok\":false,\"error\":\"unknown_action\",\"supported\":" | |
| 1251 | + "[\"sources\",\"tail\",\"search\",\"units\",\"info\"],\"requested\":"); | |
| 1252 | + json_str(action); | |
| 1253 | + fputs("}\n", stdout); | |
| 1254 | + return 0; | |
| 1255 | + } | |
| 1256 | + | |
| 1257 | + utc_now(utc, sizeof(utc)); | |
| 1258 | + | |
| 1259 | + if (strcmp(action, "info") == 0) { | |
| 1260 | + json_header(); | |
| 1261 | + fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," | |
| 1262 | + "\"version\":\"" PLUGIN_VER "\",\"utc\":", stdout); | |
| 1263 | + json_str(utc); | |
| 1264 | + printf(",\"platform\":\"%s\"", | |
| 1265 | +#if defined(_WIN32) | |
| 1266 | + "windows" | |
| 1267 | +#elif defined(__APPLE__) | |
| 1268 | + "macos" | |
| 1269 | +#else | |
| 1270 | + "linux" | |
| 1271 | +#endif | |
| 1272 | + ); | |
| 1273 | + fputs(",\"limits\":{\"lines_max\":", stdout); | |
| 1274 | + printf("%d", TAIL_MAX); | |
| 1275 | + fputs(",\"search_hits_max\":", stdout); | |
| 1276 | + printf("%d", SEARCH_HITS_MAX); | |
| 1277 | + fputs(",\"search_scan_max\":", stdout); | |
| 1278 | + printf("%d", SEARCH_SCAN); | |
| 1279 | + fputs("},\"supported\":[\"sources\",\"tail\",\"search\",\"units\",\"info\"]," | |
| 1280 | + "\"zero_network\":true,\"read_only\":true,\"node_auth\":", stdout); | |
| 1281 | + { | |
| 1282 | + const char *np = getenv("BOT_PASSWORD"); | |
| 1283 | + fputs((np && *np) ? "true" : "false", stdout); | |
| 1284 | + } | |
| 1285 | + fputs("}\n", stdout); | |
| 1286 | + return 0; | |
| 1287 | + } | |
| 1288 | + | |
| 1289 | + scan_sources(&srcs); | |
| 1290 | + | |
| 1291 | + if (strcmp(action, "sources") == 0) { | |
| 1292 | + int i; | |
| 1293 | + json_header(); | |
| 1294 | + fputs("{\"ok\":true,\"action\":\"sources\",\"plugin\":\"" PLUGIN_ID "\"," | |
| 1295 | + "\"utc\":", stdout); | |
| 1296 | + json_str(utc); | |
| 1297 | + printf(",\"journal_available\":%s,\"count\":%d,\"truncated\":%s,\"sources\":[", | |
| 1298 | + srcs.journal_avail ? "true" : "false", srcs.n, | |
| 1299 | + srcs.truncated ? "true" : "false"); | |
| 1300 | + for (i = 0; i < srcs.n; i++) { | |
| 1301 | + if (i) fputc(',', stdout); | |
| 1302 | + fputs("{\"id\":", stdout); json_str(srcs.items[i].id); | |
| 1303 | + fputs(",\"label\":", stdout); json_str(srcs.items[i].label); | |
| 1304 | + fputs(",\"kind\":", stdout); json_str(srcs.items[i].kind); | |
| 1305 | + printf(",\"size\":%lld,\"mtime\":%ld}", srcs.items[i].size, srcs.items[i].mtime); | |
| 1306 | + } | |
| 1307 | + fputs("]}\n", stdout); | |
| 1308 | + return 0; | |
| 1309 | + } | |
| 1310 | + | |
| 1311 | + if (strcmp(action, "units") == 0) { | |
| 1312 | + static unit_t units[MAX_UNITS]; | |
| 1313 | + int n = 0, i; | |
| 1314 | +#if !defined(_WIN32) && !defined(__APPLE__) | |
| 1315 | + n = list_units(units, MAX_UNITS); | |
| 1316 | +#else | |
| 1317 | + (void)units; | |
| 1318 | +#endif | |
| 1319 | + json_header(); | |
| 1320 | + fputs("{\"ok\":true,\"action\":\"units\",\"available\":", stdout); | |
| 1321 | +#if !defined(_WIN32) && !defined(__APPLE__) | |
| 1322 | + fputs("true", stdout); | |
| 1323 | +#else | |
| 1324 | + fputs("false", stdout); | |
| 1325 | +#endif | |
| 1326 | + printf(",\"count\":%d,\"units\":[", n); | |
| 1327 | + for (i = 0; i < n; i++) { | |
| 1328 | + if (i) fputc(',', stdout); | |
| 1329 | + fputs("{\"name\":", stdout); json_str(units[i].name); | |
| 1330 | + printf(",\"src\":\"journal:%s\"}", units[i].name); | |
| 1331 | + } | |
| 1332 | + fputs("]}\n", stdout); | |
| 1333 | + return 0; | |
| 1334 | + } | |
| 1335 | + | |
| 1336 | + { | |
| 1337 | + const src_t *s = find_src(&srcs, srcid); | |
| 1338 | + char srcbuf[32]; | |
| 1339 | + | |
| 1340 | + snprintf(srcbuf, sizeof(srcbuf), "%s", srcid); | |
| 1341 | + if (!s) { | |
| 1342 | + json_header(); | |
| 1343 | + fputs("{\"ok\":false,\"error\":\"source_not_allowed\"," | |
| 1344 | + "\"message\":\"that path is not in this plugin's read allowlist; " | |
| 1345 | + "call action=sources for the current list\",\"requested\":", stdout); | |
| 1346 | + json_str(srcbuf); | |
| 1347 | + fputs("}\n", stdout); | |
| 1348 | + return 0; | |
| 1349 | + } | |
| 1350 | + if (!*s->kind) { | |
| 1351 | + json_header(); | |
| 1352 | + fputs("{\"ok\":false,\"error\":\"source_unavailable\"}\n", stdout); | |
| 1353 | + return 0; | |
| 1354 | + } | |
| 1355 | + | |
| 1356 | + if (strcmp(action, "tail") == 0) { | |
| 1357 | + ring_t ring; | |
| 1358 | + int got; | |
| 1359 | + int i; | |
| 1360 | + | |
| 1361 | + if (!ring_init(&ring, nlines)) { | |
| 1362 | + json_header(); | |
| 1363 | + fputs("{\"ok\":false,\"error\":\"out_of_memory\"}\n", stdout); | |
| 1364 | + return 0; | |
| 1365 | + } | |
| 1366 | + got = collect_tail(s, nlines, &ring); | |
| 1367 | + json_header(); | |
| 1368 | + if (got < 0) { | |
| 1369 | + fputs("{\"ok\":false,\"error\":\"unreadable_source\"," | |
| 1370 | + "\"message\":\"the source could not be read on this node\"," | |
| 1371 | + "\"src\":", stdout); | |
| 1372 | + json_str(s->id); | |
| 1373 | + fputs("}\n", stdout); | |
| 1374 | + ring_free(&ring); | |
| 1375 | + return 0; | |
| 1376 | + } | |
| 1377 | + fputs("{\"ok\":true,\"action\":\"tail\",\"plugin\":\"" PLUGIN_ID "\"," | |
| 1378 | + "\"utc\":", stdout); | |
| 1379 | + json_str(utc); | |
| 1380 | + fputs(",\"src\":", stdout); json_str(s->id); | |
| 1381 | + fputs(",\"label\":", stdout); json_str(s->label); | |
| 1382 | + fputs(",\"kind\":", stdout); json_str(s->kind); | |
| 1383 | + printf(",\"requested\":%d,\"count\":%d,\"entries\":[", nlines, ring.n); | |
| 1384 | + for (i = 0; i < ring.n; i++) { | |
| 1385 | + entry_t *e = ring_at(&ring, i); | |
| 1386 | + if (i) fputc(',', stdout); | |
| 1387 | + fputs("{\"ts\":", stdout); json_str(e->ts); | |
| 1388 | + fputs(",\"unit\":", stdout); json_str(e->unit); | |
| 1389 | + fputs(",\"sev\":", stdout); json_str(sev_name(e->sev)); | |
| 1390 | + fputs(",\"text\":", stdout); json_str(e->text); | |
| 1391 | + fputc('}', stdout); | |
| 1392 | + } | |
| 1393 | + fputs("]}\n", stdout); | |
| 1394 | + ring_free(&ring); | |
| 1395 | + return 0; | |
| 1396 | + } | |
| 1397 | + | |
| 1398 | + /* search */ | |
| 1399 | + { | |
| 1400 | + list_t hits; | |
| 1401 | + int scanned; | |
| 1402 | + int i; | |
| 1403 | + | |
| 1404 | + if (!q[0]) { | |
| 1405 | + json_header(); | |
| 1406 | + fputs("{\"ok\":false,\"error\":\"missing_query\"," | |
| 1407 | + "\"message\":\"action=search needs q=<text>\"}\n", stdout); | |
| 1408 | + return 0; | |
| 1409 | + } | |
| 1410 | + if (!list_init(&hits, SEARCH_HITS_MAX)) { | |
| 1411 | + json_header(); | |
| 1412 | + fputs("{\"ok\":false,\"error\":\"out_of_memory\"}\n", stdout); | |
| 1413 | + return 0; | |
| 1414 | + } | |
| 1415 | + scanned = collect_search(s, q, &hits); | |
| 1416 | + json_header(); | |
| 1417 | + if (scanned < 0) { | |
| 1418 | + fputs("{\"ok\":false,\"error\":\"unreadable_source\"," | |
| 1419 | + "\"src\":", stdout); | |
| 1420 | + json_str(s->id); | |
| 1421 | + fputs("}\n", stdout); | |
| 1422 | + list_free(&hits); | |
| 1423 | + return 0; | |
| 1424 | + } | |
| 1425 | + fputs("{\"ok\":true,\"action\":\"search\",\"plugin\":\"" PLUGIN_ID "\"," | |
| 1426 | + "\"utc\":", stdout); | |
| 1427 | + json_str(utc); | |
| 1428 | + fputs(",\"src\":", stdout); json_str(s->id); | |
| 1429 | + fputs(",\"label\":", stdout); json_str(s->label); | |
| 1430 | + fputs(",\"q\":", stdout); json_str(q); | |
| 1431 | + printf(",\"scanned\":%d,\"count\":%d,\"max\":%d,\"truncated\":%s,\"hits\":[", | |
| 1432 | + scanned, hits.n, SEARCH_HITS_MAX, | |
| 1433 | + hits.n >= SEARCH_HITS_MAX ? "true" : "false"); | |
| 1434 | + for (i = 0; i < hits.n; i++) { | |
| 1435 | + if (i) fputc(',', stdout); | |
| 1436 | + fputs("{\"ts\":", stdout); json_str(hits.v[i].ts); | |
| 1437 | + fputs(",\"unit\":", stdout); json_str(hits.v[i].unit); | |
| 1438 | + fputs(",\"sev\":", stdout); json_str(sev_name(hits.v[i].sev)); | |
| 1439 | + fputs(",\"text\":", stdout); json_str(hits.v[i].text); | |
| 1440 | + fputc('}', stdout); | |
| 1441 | + } | |
| 1442 | + fputs("]}\n", stdout); | |
| 1443 | + list_free(&hits); | |
| 1444 | + return 0; | |
| 1445 | + } | |
| 1446 | + } | |
| 1447 | +} | |
| 1448 | + | |
| 1449 | +/* ------------------------------------------------------------------ */ | |
| 1450 | +/* HTML UI */ | |
| 1451 | +/* ------------------------------------------------------------------ */ | |
| 1452 | + | |
| 1453 | +static int mode_html(int embed) | |
| 1454 | +{ | |
| 1455 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | |
| 1456 | + "Cache-Control: no-store\r\n" | |
| 1457 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 1458 | + | |
| 1459 | + fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>" | |
| 1460 | + "<meta name='viewport' content='width=device-width,initial-scale=1'>" | |
| 1461 | + "<title>logs</title>", stdout); | |
| 1462 | + | |
| 1463 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS, stdout); | |
| 1464 | + fputs( | |
| 1465 | +"*{box-sizing:border-box}" | |
| 1466 | +"html,body{height:100%}" | |
| 1467 | +"body{margin:0;padding:14px;background:var(--bg);color:var(--text);" | |
| 1468 | + "font-family:var(--font);font-size:13px;line-height:1.5;-webkit-font-smoothing:antialiased}" | |
| 1469 | +".wrap{max-width:1280px;margin:0 auto;display:flex;flex-direction:column;" | |
| 1470 | + "gap:12px;min-height:100%}" | |
| 1471 | +".top{display:flex;align-items:center;gap:10px;flex-wrap:wrap}" | |
| 1472 | +".title{font-size:19px;font-weight:700;margin:0;letter-spacing:-.01em}" | |
| 1473 | +".sub{color:var(--muted);font-size:12px;font-family:var(--mono);overflow:hidden;" | |
| 1474 | + "text-overflow:ellipsis;white-space:nowrap;max-width:46ch}" | |
| 1475 | +".spacer{flex:1}" | |
| 1476 | +".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;" | |
| 1477 | + "background:var(--surface2);color:var(--muted);border:1px solid var(--line);white-space:nowrap}" | |
| 1478 | +".pill.live{color:var(--ok);border-color:rgba(48,209,88,.4)}" | |
| 1479 | +".pill.paused{color:var(--warn);border-color:rgba(255,214,10,.4)}" | |
| 1480 | +"select,input,button{font-family:inherit;font-size:13px;color:var(--text)}" | |
| 1481 | +"select,input{background:var(--input-bg);border:1px solid var(--line);" | |
| 1482 | + "border-radius:9px;padding:7px 11px;min-width:0}" | |
| 1483 | +"select{max-width:100%}" | |
| 1484 | +"input[type=text]{flex:1;min-width:120px;font-family:var(--mono);font-size:12px}" | |
| 1485 | +"input:focus,select:focus{outline:2px solid var(--accent);outline-offset:-1px}" | |
| 1486 | +"button{background:var(--accent);color:#fff;border:0;border-radius:999px;" | |
| 1487 | + "padding:7px 14px;font-weight:600;cursor:pointer;white-space:nowrap}" | |
| 1488 | +"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" | |
| 1489 | +"button.on{background:var(--accent);color:#fff;border-color:transparent}" | |
| 1490 | +"button.sm{padding:5px 11px;font-size:12px}" | |
| 1491 | +"button:active{transform:scale(.98)}" | |
| 1492 | +".bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" | |
| 1493 | +".seg{display:inline-flex;gap:3px;background:var(--surface2);border:1px solid var(--line);" | |
| 1494 | + "border-radius:999px;padding:3px;flex-wrap:nowrap}" | |
| 1495 | +".seg button{background:transparent;color:var(--muted);border:0;padding:4px 10px;font-size:12px}" | |
| 1496 | +".seg button.on{background:var(--accent);color:#fff}" | |
| 1497 | +".panel{background:var(--surface);border:1px solid var(--line);border-radius:14px;" | |
| 1498 | + "display:flex;flex-direction:column;min-height:0;flex:1;overflow:hidden}" | |
| 1499 | +".loghead{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:10px 12px;" | |
| 1500 | + "border-bottom:1px solid var(--line)}" | |
| 1501 | +".log{flex:1;overflow:auto;padding:6px 0;min-height:260px;max-height:calc(100vh - 260px);" | |
| 1502 | + "font-family:var(--mono);font-size:12px;line-height:1.55}" | |
| 1503 | +".log.wrap .tx{white-space:pre-wrap;word-break:break-word}" | |
| 1504 | +".ln{display:grid;grid-template-columns:112px minmax(0,1fr) 132px;gap:10px;" | |
| 1505 | + "padding:3px 12px;border-left:3px solid transparent;align-items:baseline}" | |
| 1506 | +".ln:hover{background:var(--surface-hover)}" | |
| 1507 | +".ln .ts{color:var(--muted);font-size:11px;white-space:nowrap;overflow:hidden;" | |
| 1508 | + "text-overflow:ellipsis}" | |
| 1509 | +".ln .un{color:var(--muted);font-size:11px;white-space:nowrap;overflow:hidden;" | |
| 1510 | + "text-overflow:ellipsis;text-align:right}" | |
| 1511 | +".ln .tx{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}" | |
| 1512 | +".ln.err{border-left-color:var(--red)}" | |
| 1513 | +".ln.err .tx{color:var(--red)}" | |
| 1514 | +".ln.warn{border-left-color:var(--warn)}" | |
| 1515 | +".ln.warn .tx{color:var(--warn)}" | |
| 1516 | +".ln.info{border-left-color:transparent}" | |
| 1517 | +".ln mark{background:rgba(255,214,10,.28);color:inherit;border-radius:3px;padding:0 1px}" | |
| 1518 | +".empty{color:var(--muted);padding:24px 14px;text-align:center;font-size:13px;" | |
| 1519 | + "font-family:var(--font)}" | |
| 1520 | +".foot{display:flex;gap:10px;align-items:center;flex-wrap:wrap;padding:8px 12px;" | |
| 1521 | + "border-top:1px solid var(--line);color:var(--muted);font-size:11px;font-family:var(--mono)}" | |
| 1522 | +".hide{display:none!important}" | |
| 1523 | +".muted{color:var(--muted)}" | |
| 1524 | +"@media(max-width:760px){" | |
| 1525 | + ".ln{grid-template-columns:96px minmax(0,1fr);gap:8px}" | |
| 1526 | + ".ln .un{display:none}" | |
| 1527 | + ".log{max-height:calc(100vh - 330px)}" | |
| 1528 | + "#q{flex:1 1 100%}" | |
| 1529 | +"}" | |
| 1530 | +"@media(max-width:480px){" | |
| 1531 | + "body{padding:10px}" | |
| 1532 | + ".title{font-size:17px}" | |
| 1533 | + ".sub{max-width:26ch}" | |
| 1534 | + ".seg button{padding:4px 8px}" | |
| 1535 | +"}", stdout); | |
| 1536 | + | |
| 1537 | + fputs("</style></head>" SX_BOT_THEME_HANDOFF "<body><div class='wrap'>", stdout); | |
| 1538 | + | |
| 1539 | + if (!embed) { | |
| 1540 | + fputs("<div class='top'><a href='/' style='color:var(--accent);" | |
| 1541 | + "text-decoration:none;font-weight:600'>← Back to Bot</a></div>", stdout); | |
| 1542 | + } | |
| 1543 | + | |
| 1544 | + fputs("<div class='top'>" | |
| 1545 | + "<h1 class='title'>logs</h1>" | |
| 1546 | + "<span class='sub' id='pSrc'>—</span>" | |
| 1547 | + "<span class='spacer'></span>" | |
| 1548 | + "<span class='pill paused' id='pState'>paused</span>" | |
| 1549 | + "<button class='ghost sm embed-hide' id='btnTheme' type='button'>Theme</button>" | |
| 1550 | + "</div>", stdout); | |
| 1551 | + | |
| 1552 | + /* source + controls */ | |
| 1553 | + fputs("<div class='panel'><div class='loghead'>" | |
| 1554 | + "<select id='srcSel' title='Log source'><option value=''>—</option></select>" | |
| 1555 | + "<div class='seg' id='segLines'>" | |
| 1556 | + "<button type='button' data-n='100'>100</button>" | |
| 1557 | + "<button type='button' data-n='200' class='on'>200</button>" | |
| 1558 | + "<button type='button' data-n='500'>500</button>" | |
| 1559 | + "<button type='button' data-n='2000'>2000</button>" | |
| 1560 | + "</div>" | |
| 1561 | + "<button type='button' id='btnFollow' class='on'>Follow</button>" | |
| 1562 | + "<input type='text' id='q' placeholder='Search in this source'>" | |
| 1563 | + "<button type='button' id='btnSearch' class='sm'>Search</button>" | |
| 1564 | + "<button type='button' id='btnWrap' class='ghost sm'>Wrap</button>" | |
| 1565 | + "<button type='button' id='btnCopy' class='ghost sm'>Copy</button>" | |
| 1566 | + "<button type='button' id='btnReload' class='ghost sm'>Reload</button>" | |
| 1567 | + "</div>", stdout); | |
| 1568 | + | |
| 1569 | + fputs("<div class='log' id='log'><div class='empty' id='empty'>Loading sources…</div></div>", stdout); | |
| 1570 | + fputs("<div class='foot'>" | |
| 1571 | + "<span id='fCount'>0 entries</span>" | |
| 1572 | + "<span class='spacer'></span>" | |
| 1573 | + "<span id='fNote'>local read only · zero network</span>" | |
| 1574 | + "</div></div>", stdout); | |
| 1575 | + | |
| 1576 | + fputs("<div class='foot' style='border:0;padding:0'><span class='muted'>" | |
| 1577 | + "Reads an allowlist of local log files and the local system journal. " | |
| 1578 | + "Every source is read-only; nothing is written, and no request leaves this node." | |
| 1579 | + "</span></div>", stdout); | |
| 1580 | + | |
| 1581 | + /* ---------------- script ---------------- */ | |
| 1582 | + fputs("<script>\n" | |
| 1583 | +"(function(){\n" | |
| 1584 | +" var qs = new URLSearchParams(location.search);\n" | |
| 1585 | +" var HUB = qs.get('plugin') || '';\n" | |
| 1586 | +" var node = qs.get('node') || '';\n" | |
| 1587 | +" var sid = qs.get('id') || '';\n" | |
| 1588 | +" var pwd = qs.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" | |
| 1589 | +" localStorage.getItem('bot_active_pwd') || '';\n" | |
| 1590 | +" var SRC = '', LINES = 200, FOLLOW = true, TIMER = null, BUSY = false;\n" | |
| 1591 | +" var LAST = [], QUERY = '', MODE = 'tail';\n" | |
| 1592 | +"\n" | |
| 1593 | +" /* Two routes: opened through the hub -> call the hub proxy back;\n" | |
| 1594 | +" opened directly on the node -> the plugin IS the route. */\n" | |
| 1595 | +" function base(){ return HUB ? '/plugins?plugin=' + HUB : '/plugin_logs'; }\n" | |
| 1596 | +" function withCtx(u){\n" | |
| 1597 | +" if (node) u += '&node=' + encodeURIComponent(node);\n" | |
| 1598 | +" if (sid) u += '&id=' + encodeURIComponent(sid);\n" | |
| 1599 | +" if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n" | |
| 1600 | +" return u;\n" | |
| 1601 | +" }\n" | |
| 1602 | +" function hdr(){ return pwd ? {'X-Bot-Password': pwd} : {}; }\n" | |
| 1603 | +" function $(i){ return document.getElementById(i); }\n" | |
| 1604 | +" function el(t,c,x){ var e=document.createElement(t); if(c) e.className=c;\n" | |
| 1605 | +" if (x!==undefined && x!==null) e.textContent=String(x); return e; }\n" | |
| 1606 | +" function api(extra){\n" | |
| 1607 | +" return fetch(withCtx(base() + '?' + extra), {headers:hdr(), cache:'no-store'})\n" | |
| 1608 | +" .then(function(r){ return r.json(); });\n" | |
| 1609 | +" }\n" | |
| 1610 | +"\n" | |
| 1611 | +" function state(txt, cls){\n" | |
| 1612 | +" var p = $('pState'); p.textContent = txt; p.className = 'pill ' + (cls||'paused');\n" | |
| 1613 | +" }\n" | |
| 1614 | +"\n" | |
| 1615 | +" function humanSize(n){\n" | |
| 1616 | +" if (!n) return '';\n" | |
| 1617 | +" var u=['B','KB','MB','GB'], i=0, v=n;\n" | |
| 1618 | +" while (v >= 1024 && i < u.length-1){ v/=1024; i++; }\n" | |
| 1619 | +" return (i===0 ? v : v.toFixed(1)) + ' ' + u[i];\n" | |
| 1620 | +" }\n" | |
| 1621 | +"\n" | |
| 1622 | +" function loadSources(){\n" | |
| 1623 | +" return api('action=sources').then(function(d){\n" | |
| 1624 | +" var sel = $('srcSel');\n" | |
| 1625 | +" sel.innerHTML = '';\n" | |
| 1626 | +" if (!d || d.ok === false){ $('empty').textContent = 'Could not list sources.'; return; }\n" | |
| 1627 | +" var groups = [['journal','Journal'],['file','Log files'],['event','Event logs']];\n" | |
| 1628 | +" var seen = {};\n" | |
| 1629 | +" for (var g=0; g<groups.length; g++){\n" | |
| 1630 | +" var kind = groups[g][0], any = false, og = null;\n" | |
| 1631 | +" for (var i=0;i<d.sources.length;i++){\n" | |
| 1632 | +" var s = d.sources[i];\n" | |
| 1633 | +" if (s.kind !== kind) continue;\n" | |
| 1634 | +" if (!og){ og = document.createElement('optgroup'); og.label = groups[g][1]; }\n" | |
| 1635 | +" var o = document.createElement('option');\n" | |
| 1636 | +" o.value = s.id;\n" | |
| 1637 | +" o.textContent = s.label + (s.size ? ' (' + humanSize(s.size) + ')' : '');\n" | |
| 1638 | +" og.appendChild(o); any = true;\n" | |
| 1639 | +" }\n" | |
| 1640 | +" if (any) sel.appendChild(og);\n" | |
| 1641 | +" }\n" | |
| 1642 | +" if (d.truncated) $('fNote').textContent = 'source list truncated · local read only';\n" | |
| 1643 | +" /* keep the previous selection when it still exists */\n" | |
| 1644 | +" var want = SRC;\n" | |
| 1645 | +" if (!want){\n" | |
| 1646 | +" for (var k=0;k<d.sources.length;k++){ want = d.sources[k].id; break; }\n" | |
| 1647 | +" }\n" | |
| 1648 | +" if (want){ sel.value = want; SRC = want; }\n" | |
| 1649 | +" if (!d.sources.length){\n" | |
| 1650 | +" $('empty').textContent = 'No readable log sources on this node.';\n" | |
| 1651 | +" }\n" | |
| 1652 | +" return d;\n" | |
| 1653 | +" }).catch(function(e){ $('empty').textContent = 'Request failed: ' + e; });\n" | |
| 1654 | +" }\n" | |
| 1655 | +"\n" | |
| 1656 | +" function highlight(text, q){\n" | |
| 1657 | +" var frag = document.createDocumentFragment();\n" | |
| 1658 | +" if (!q) { frag.appendChild(document.createTextNode(text)); return frag; }\n" | |
| 1659 | +" var hay = text.toLowerCase(), need = q.toLowerCase(), at = 0;\n" | |
| 1660 | +" while (true){\n" | |
| 1661 | +" var i = hay.indexOf(need, at);\n" | |
| 1662 | +" if (i < 0){ frag.appendChild(document.createTextNode(text.slice(at))); break; }\n" | |
| 1663 | +" if (i > at) frag.appendChild(document.createTextNode(text.slice(at, i)));\n" | |
| 1664 | +" var m = document.createElement('mark');\n" | |
| 1665 | +" m.textContent = text.slice(i, i + q.length);\n" | |
| 1666 | +" frag.appendChild(m);\n" | |
| 1667 | +" at = i + q.length;\n" | |
| 1668 | +" }\n" | |
| 1669 | +" return frag;\n" | |
| 1670 | +" }\n" | |
| 1671 | +"\n" | |
| 1672 | +" function renderRows(rows, q){\n" | |
| 1673 | +" var box = $('log');\n" | |
| 1674 | +" box.innerHTML = '';\n" | |
| 1675 | +" if (!rows || !rows.length){\n" | |
| 1676 | +" var e = el('div','empty', MODE === 'search'\n" | |
| 1677 | +" ? 'No matches in the scanned window.'\n" | |
| 1678 | +" : 'This source produced no entries.');\n" | |
| 1679 | +" box.appendChild(e);\n" | |
| 1680 | +" $('fCount').textContent = '0 entries';\n" | |
| 1681 | +" return;\n" | |
| 1682 | +" }\n" | |
| 1683 | +" var frag = document.createDocumentFragment();\n" | |
| 1684 | +" for (var i=0;i<rows.length;i++){\n" | |
| 1685 | +" var r = rows[i];\n" | |
| 1686 | +" var ln = el('div', 'ln ' + (r.sev || 'info'));\n" | |
| 1687 | +" ln.appendChild(el('span','ts', r.ts || ''));\n" | |
| 1688 | +" var tx = el('span','tx');\n" | |
| 1689 | +" tx.appendChild(highlight(r.text === undefined ? '' : r.text, q));\n" | |
| 1690 | +" ln.appendChild(tx);\n" | |
| 1691 | +" ln.appendChild(el('span','un', r.unit || ''));\n" | |
| 1692 | +" frag.appendChild(ln);\n" | |
| 1693 | +" }\n" | |
| 1694 | +" box.appendChild(frag);\n" | |
| 1695 | +" $('fCount').textContent = rows.length + ' entries';\n" | |
| 1696 | +" }\n" | |
| 1697 | +"\n" | |
| 1698 | +" function scrollBottom(){ var b = $('log'); b.scrollTop = b.scrollHeight; }\n" | |
| 1699 | +"\n" | |
| 1700 | +" function tail(keepScroll){\n" | |
| 1701 | +" if (!SRC) return Promise.resolve();\n" | |
| 1702 | +" var atBottom = true, b = $('log');\n" | |
| 1703 | +" atBottom = (b.scrollTop + b.clientHeight) >= (b.scrollHeight - 24);\n" | |
| 1704 | +" return api('action=tail&lines=' + LINES + '&src=' + encodeURIComponent(SRC))\n" | |
| 1705 | +" .then(function(d){\n" | |
| 1706 | +" if (!d || d.ok === false){\n" | |
| 1707 | +" state('error','paused');\n" | |
| 1708 | +" $('empty').textContent = (d && d.message) || (d && d.error) || 'unreadable source';\n" | |
| 1709 | +" $('log').innerHTML = '';\n" | |
| 1710 | +" $('log').appendChild(el('div','empty',(d && d.message) || 'unreadable source'));\n" | |
| 1711 | +" $('fCount').textContent = '0 entries';\n" | |
| 1712 | +" return;\n" | |
| 1713 | +" }\n" | |
| 1714 | +" MODE = 'tail';\n" | |
| 1715 | +" LAST = d.entries || [];\n" | |
| 1716 | +" $('pSrc').textContent = d.label || d.src || '';\n" | |
| 1717 | +" renderRows(LAST, '');\n" | |
| 1718 | +" if (!keepScroll && atBottom) scrollBottom();\n" | |
| 1719 | +" state(FOLLOW ? 'live 3s' : 'paused', FOLLOW ? 'live' : 'paused');\n" | |
| 1720 | +" })\n" | |
| 1721 | +" .catch(function(e){ state('offline','paused'); $('fNote').textContent = 'request failed'; });\n" | |
| 1722 | +" }\n" | |
| 1723 | +"\n" | |
| 1724 | +" function search(){\n" | |
| 1725 | +" if (!SRC || !QUERY){ tail(); return Promise.resolve(); }\n" | |
| 1726 | +" return api('action=search&src=' + encodeURIComponent(SRC) +\n" | |
| 1727 | +" '&q=' + encodeURIComponent(QUERY))\n" | |
| 1728 | +" .then(function(d){\n" | |
| 1729 | +" if (!d || d.ok === false){\n" | |
| 1730 | +" $('log').innerHTML = '';\n" | |
| 1731 | +" $('log').appendChild(el('div','empty',(d && (d.message||d.error)) || 'search failed'));\n" | |
| 1732 | +" return;\n" | |
| 1733 | +" }\n" | |
| 1734 | +" MODE = 'search';\n" | |
| 1735 | +" LAST = d.hits || [];\n" | |
| 1736 | +" renderRows(LAST, QUERY);\n" | |
| 1737 | +" $('fCount').textContent = LAST.length + ' hits of ' + d.scanned + ' scanned' +\n" | |
| 1738 | +" (d.truncated ? ' (capped)' : '');\n" | |
| 1739 | +" state('search','paused');\n" | |
| 1740 | +" })\n" | |
| 1741 | +" .catch(function(e){ $('fNote').textContent = 'search failed'; });\n" | |
| 1742 | +" }\n" | |
| 1743 | +"\n" | |
| 1744 | +" function schedule(){\n" | |
| 1745 | +" if (TIMER){ clearInterval(TIMER); TIMER = null; }\n" | |
| 1746 | +" if (FOLLOW && MODE === 'tail' && document.visibilityState === 'visible'){\n" | |
| 1747 | +" TIMER = setInterval(function(){ if (!BUSY){ BUSY = true; tail().then(function(){ BUSY = false; }); } }, 3000);\n" | |
| 1748 | +" state('live 3s','live');\n" | |
| 1749 | +" } else {\n" | |
| 1750 | +" state(MODE === 'search' ? 'search' : 'paused', 'paused');\n" | |
| 1751 | +" }\n" | |
| 1752 | +" }\n" | |
| 1753 | +"\n" | |
| 1754 | +" function refresh(){\n" | |
| 1755 | +" if (MODE === 'search' && QUERY) search(); else tail();\n" | |
| 1756 | +" schedule();\n" | |
| 1757 | +" }\n" | |
| 1758 | +"\n" | |
| 1759 | +" /* ---- wiring ---- */\n" | |
| 1760 | +" $('srcSel').addEventListener('change', function(){\n" | |
| 1761 | +" SRC = this.value; MODE = 'tail'; QUERY = $('q').value = ''; refresh();\n" | |
| 1762 | +" });\n" | |
| 1763 | +" Array.prototype.forEach.call(document.querySelectorAll('#segLines button'), function(b){\n" | |
| 1764 | +" b.addEventListener('click', function(){\n" | |
| 1765 | +" Array.prototype.forEach.call(document.querySelectorAll('#segLines button'),\n" | |
| 1766 | +" function(x){ x.classList.remove('on'); });\n" | |
| 1767 | +" b.classList.add('on');\n" | |
| 1768 | +" LINES = parseInt(b.getAttribute('data-n'), 10) || 200;\n" | |
| 1769 | +" refresh();\n" | |
| 1770 | +" });\n" | |
| 1771 | +" });\n" | |
| 1772 | +" $('btnFollow').addEventListener('click', function(){\n" | |
| 1773 | +" FOLLOW = !FOLLOW;\n" | |
| 1774 | +" this.classList.toggle('on', FOLLOW);\n" | |
| 1775 | +" this.textContent = FOLLOW ? 'Follow' : 'Paused';\n" | |
| 1776 | +" if (MODE === 'search' && FOLLOW) MODE = 'tail';\n" | |
| 1777 | +" refresh();\n" | |
| 1778 | +" });\n" | |
| 1779 | +" $('btnSearch').addEventListener('click', function(){\n" | |
| 1780 | +" QUERY = $('q').value.trim();\n" | |
| 1781 | +" if (!QUERY){ MODE = 'tail'; tail(); schedule(); return; }\n" | |
| 1782 | +" MODE = 'search'; search(); schedule();\n" | |
| 1783 | +" });\n" | |
| 1784 | +" $('q').addEventListener('keydown', function(e){ if (e.key === 'Enter') $('btnSearch').click(); });\n" | |
| 1785 | +" $('btnWrap').addEventListener('click', function(){\n" | |
| 1786 | +" var w = $('log').classList.toggle('wrap');\n" | |
| 1787 | +" this.classList.toggle('on', w);\n" | |
| 1788 | +" });\n" | |
| 1789 | +" $('btnCopy').addEventListener('click', function(){\n" | |
| 1790 | +" var out = [];\n" | |
| 1791 | +" for (var i=0;i<LAST.length;i++){\n" | |
| 1792 | +" var r = LAST[i];\n" | |
| 1793 | +" out.push((r.ts ? r.ts + ' ' : '') + (r.unit ? r.unit + ': ' : '') + (r.text || ''));\n" | |
| 1794 | +" }\n" | |
| 1795 | +" var txt = out.join('\\n');\n" | |
| 1796 | +" var btn = this;\n" | |
| 1797 | +" function done(ok){ btn.textContent = ok ? 'Copied' : 'Copy failed';\n" | |
| 1798 | +" setTimeout(function(){ btn.textContent = 'Copy'; }, 1400); }\n" | |
| 1799 | +" if (navigator.clipboard && navigator.clipboard.writeText){\n" | |
| 1800 | +" navigator.clipboard.writeText(txt).then(function(){ done(true); },\n" | |
| 1801 | +" function(){ done(false); });\n" | |
| 1802 | +" } else {\n" | |
| 1803 | +" var ta = document.createElement('textarea');\n" | |
| 1804 | +" ta.value = txt; document.body.appendChild(ta); ta.select();\n" | |
| 1805 | +" try { done(document.execCommand('copy')); } catch(e){ done(false); }\n" | |
| 1806 | +" document.body.removeChild(ta);\n" | |
| 1807 | +" }\n" | |
| 1808 | +" });\n" | |
| 1809 | +" $('btnReload').addEventListener('click', function(){ loadSources().then(refresh); });\n" | |
| 1810 | +" $('btnTheme').addEventListener('click', function(){\n" | |
| 1811 | +" if (window.sxApplyTheme) window.sxApplyTheme(window.sxTheme && window.sxTheme() === 'dark' ? 'light' : 'dark');\n" | |
| 1812 | +" });\n" | |
| 1813 | +"\n" | |
| 1814 | +" document.addEventListener('visibilitychange', function(){\n" | |
| 1815 | +" if (document.visibilityState === 'visible'){ refresh(); }\n" | |
| 1816 | +" else { schedule(); }\n" | |
| 1817 | +" });\n" | |
| 1818 | +" window.addEventListener('bot-theme', function(){});\n" | |
| 1819 | +"\n" | |
| 1820 | +" loadSources().then(refresh);\n" | |
| 1821 | +"})();\n" | |
| 1822 | +"</script></div></body></html>\n", stdout); | |
| 1823 | + | |
| 1824 | + return 0; | |
| 1825 | +} | |
| 1826 | + | |
| 1827 | +/* ------------------------------------------------------------------ */ | |
| 1828 | +/* Entry point */ | |
| 1829 | +/* ------------------------------------------------------------------ */ | |
| 1830 | + | |
| 1831 | +int main(int argc, char **argv) | |
| 1832 | +{ | |
| 1833 | + const char *qs; | |
| 1834 | + int i; | |
| 1835 | + | |
| 1836 | + for (i = 1; i < argc; i++) { | |
| 1837 | + if (strcmp(argv[i], "--meta") == 0) | |
| 1838 | + return mode_meta(); | |
| 1839 | + if (strcmp(argv[i], "--version") == 0) { | |
| 1840 | + printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); | |
| 1841 | + return 0; | |
| 1842 | + } | |
| 1843 | + if (strcmp(argv[i], "--help") == 0) { | |
| 1844 | + printf("usage: %s [--meta] [--version] [--help]\n" | |
| 1845 | + " CGI mode reads QUERY_STRING:\n" | |
| 1846 | + " ?action=sources readable log sources\n" | |
| 1847 | + " ?action=tail&src=<id>&lines=<N> last N entries of a source\n" | |
| 1848 | + " ?action=search&src=<id>&q=<text> case-insensitive substring search\n" | |
| 1849 | + " ?action=units systemd units with journal entries\n" | |
| 1850 | + " ?action=info plugin info\n" | |
| 1851 | + " (no action) HTML log viewer\n", PLUGIN_ID); | |
| 1852 | + return 0; | |
| 1853 | + } | |
| 1854 | + } | |
| 1855 | + | |
| 1856 | + if (getenv("SX_PLUGIN_META")) | |
| 1857 | + return mode_meta(); | |
| 1858 | + | |
| 1859 | + require_node_auth(); | |
| 1860 | + | |
| 1861 | + qs = getenv("QUERY_STRING"); | |
| 1862 | + if (!qs) qs = ""; | |
| 1863 | + | |
| 1864 | + if (strstr(qs, "action=") || strstr(qs, "format=json")) | |
| 1865 | + return mode_json(qs); | |
| 1866 | + | |
| 1867 | + { | |
| 1868 | + char embedv[16]; | |
| 1869 | + embedv[0] = '\0'; | |
| 1870 | + if (get_query_val(qs, "embed", embedv, sizeof(embedv))) | |
| 1871 | + return mode_html(strcmp(embedv, "1") == 0 || strcmp(embedv, "true") == 0); | |
| 1872 | + } | |
| 1873 | + return mode_html(0); | |
| 1874 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..11bc950 | ||
| --- /dev/null | ||
| +++ b/tests/e2e.py | ||
| @@ -0,0 +1,285 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""tests/e2e.py - viewport and live-behaviour checks for the plugin_logs UI. | |
| 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 in BOTH themes, and asserts | |
| 6 | +there is no horizontal overflow, no console error, that the source picker is | |
| 7 | +populated from action=sources, that a tail renders rows, that a search renders | |
| 8 | +highlighted hits, and that the live/save/theme controls respond. | |
| 9 | + | |
| 10 | +Skips cleanly (exit 0) when Playwright is not installed, so `make test` stays | |
| 11 | +offline-only. | |
| 12 | + | |
| 13 | + python3 tests/e2e.py # run if Playwright is available | |
| 14 | + python3 tests/e2e.py --strict # exit 2 when Playwright is missing | |
| 15 | +""" | |
| 16 | + | |
| 17 | +import argparse | |
| 18 | +import http.server | |
| 19 | +import os | |
| 20 | +import shutil | |
| 21 | +import subprocess | |
| 22 | +import sys | |
| 23 | +import tempfile | |
| 24 | +import threading | |
| 25 | +from urllib.parse import urlparse, parse_qs | |
| 26 | + | |
| 27 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| 28 | +BIN = os.path.join(ROOT, "plugin_logs") | |
| 29 | +VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] | |
| 30 | +SHOTS = os.path.join(ROOT, "docs") | |
| 31 | + | |
| 32 | +FAILS = [] | |
| 33 | +PASSES = [] | |
| 34 | + | |
| 35 | + | |
| 36 | +def ok(desc): | |
| 37 | + PASSES.append(desc) | |
| 38 | + print(" ok %s" % desc) | |
| 39 | + | |
| 40 | + | |
| 41 | +def bad(desc, extra=""): | |
| 42 | + FAILS.append(desc) | |
| 43 | + print(" FAIL %s%s" % (desc, (" -- " + str(extra)) if extra else "")) | |
| 44 | + | |
| 45 | + | |
| 46 | +def check(desc, cond, extra=""): | |
| 47 | + ok(desc) if cond else bad(desc, extra) | |
| 48 | + | |
| 49 | + | |
| 50 | +def prepare_fixtures(): | |
| 51 | + """A journal fixture plus a fixture log tree, exported for the child.""" | |
| 52 | + tmp = tempfile.mkdtemp(prefix="logs_e2e_") | |
| 53 | + jfix = os.path.join(tmp, "journal.jsonl") | |
| 54 | + with open(jfix, "w") as f: | |
| 55 | + rows = [ | |
| 56 | + ("1762923001000000", "3", "nginx.service", | |
| 57 | + "upstream timed out while reading response header from upstream"), | |
| 58 | + ("1762923002000000", "4", "systemd", "Some unit is deprecated"), | |
| 59 | + ("1762923003000000", "6", "kernel", "eth0 link up, 1000 Mbps"), | |
| 60 | + ("1762923004000000", "6", "sshd.service", | |
| 61 | + "Accepted publickey for root from a trusted key"), | |
| 62 | + ("1762923005000000", "2", "postgresql.service", | |
| 63 | + "PANIC: could not locate a valid checkpoint record"), | |
| 64 | + ] | |
| 65 | + for ts, pri, unit, msg in rows: | |
| 66 | + f.write('{"__REALTIME_TIMESTAMP":"%s","PRIORITY":"%s",' | |
| 67 | + '"__CURSOR":"x","_SYSTEMD_UNIT":"%s","MESSAGE":"%s"}\n' | |
| 68 | + % (ts, pri, unit, msg)) | |
| 69 | + | |
| 70 | + root = os.path.join(tmp, "fixtures") | |
| 71 | + os.makedirs(os.path.join(root, "svc")) | |
| 72 | + with open(os.path.join(root, "svc", "app.log"), "w") as f: | |
| 73 | + for i in range(60): | |
| 74 | + sev = "error" if i % 7 == 0 else ("warn" if i % 5 == 0 else "info") | |
| 75 | + f.write("Nov 12 06:%02d:%02d host app[%d]: %s: request %d handled\n" | |
| 76 | + % (i // 60 % 60, i % 60, 100 + i, sev, i)) | |
| 77 | + | |
| 78 | + env = dict(os.environ) | |
| 79 | + env["SX_LOGS_JOURNAL_FIXTURE"] = jfix | |
| 80 | + env["SX_LOGS_EXTRA_ROOT"] = root | |
| 81 | + return tmp, env | |
| 82 | + | |
| 83 | + | |
| 84 | +class Handler(http.server.BaseHTTPRequestHandler): | |
| 85 | + env = {} | |
| 86 | + | |
| 87 | + def do_GET(self): # noqa: N802 | |
| 88 | + u = urlparse(self.path) | |
| 89 | + qs = u.query | |
| 90 | + # The UI appends ?pwd= for real nodes; this shim has no password set, | |
| 91 | + # so just pass the query through. | |
| 92 | + env = dict(self.env) | |
| 93 | + env["QUERY_STRING"] = qs | |
| 94 | + env["REQUEST_METHOD"] = "GET" | |
| 95 | + env.pop("BOT_PASSWORD", None) | |
| 96 | + if parse_qs(qs).get("theme"): | |
| 97 | + pass | |
| 98 | + out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout | |
| 99 | + sep = out.find(b"\r\n\r\n") | |
| 100 | + headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" | |
| 101 | + body = out[sep + 4:] if sep >= 0 else out | |
| 102 | + ctype = "text/html; charset=utf-8" | |
| 103 | + for line in headers.splitlines(): | |
| 104 | + if line.lower().startswith("content-type:"): | |
| 105 | + ctype = line.split(":", 1)[1].strip() | |
| 106 | + self.send_response(200) | |
| 107 | + self.send_header("Content-Type", ctype) | |
| 108 | + self.send_header("Cache-Control", "no-store") | |
| 109 | + # no Content-Length from the plugin; the shim sets its own framing | |
| 110 | + self.send_header("Content-Length", str(len(body))) | |
| 111 | + self.end_headers() | |
| 112 | + self.wfile.write(body) | |
| 113 | + | |
| 114 | + def log_message(self, *_a): | |
| 115 | + pass | |
| 116 | + | |
| 117 | + | |
| 118 | +def serve(env): | |
| 119 | + Handler.env = env | |
| 120 | + httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) | |
| 121 | + t = threading.Thread(target=httpd.serve_forever, daemon=True) | |
| 122 | + t.start() | |
| 123 | + return httpd, httpd.server_address[1] | |
| 124 | + | |
| 125 | + | |
| 126 | +def main(): | |
| 127 | + ap = argparse.ArgumentParser() | |
| 128 | + ap.add_argument("--strict", action="store_true") | |
| 129 | + args = ap.parse_args() | |
| 130 | + | |
| 131 | + try: | |
| 132 | + from playwright.sync_api import sync_playwright | |
| 133 | + except Exception: | |
| 134 | + print(" skip e2e (playwright not installed)") | |
| 135 | + return 2 if args.strict else 0 | |
| 136 | + | |
| 137 | + if not os.path.exists(BIN): | |
| 138 | + print(" FAIL plugin binary missing; run `make` first") | |
| 139 | + return 1 | |
| 140 | + | |
| 141 | + tmp, env = prepare_fixtures() | |
| 142 | + httpd, port = serve(env) | |
| 143 | + base = "http://127.0.0.1:%d/" % port | |
| 144 | + print("== e2e: %s ==" % base) | |
| 145 | + | |
| 146 | + os.makedirs(SHOTS, exist_ok=True) | |
| 147 | + try: | |
| 148 | + with sync_playwright() as p: | |
| 149 | + browser = p.chromium.launch() | |
| 150 | + for w, h in VIEWPORTS: | |
| 151 | + for theme in ("dark", "light"): | |
| 152 | + page = browser.new_page(viewport={"width": w, "height": h}, | |
| 153 | + device_scale_factor=1) | |
| 154 | + errors = [] | |
| 155 | + page.on("console", lambda m: errors.append(m.text) | |
| 156 | + if m.type == "error" else None) | |
| 157 | + page.on("pageerror", lambda e: errors.append(str(e))) | |
| 158 | + page.goto(base + "?theme=" + theme, wait_until="load") | |
| 159 | + page.wait_for_timeout(900) | |
| 160 | + | |
| 161 | + tag = "%dx%d %s" % (w, h, theme) | |
| 162 | + check("%s: no console errors" % tag, not errors, errors[:3]) | |
| 163 | + | |
| 164 | + # theme actually applied | |
| 165 | + attr = page.evaluate( | |
| 166 | + "document.documentElement.getAttribute('data-theme')") | |
| 167 | + check("%s: theme applied" % tag, attr == theme, attr) | |
| 168 | + | |
| 169 | + # horizontal overflow | |
| 170 | + over = page.evaluate( | |
| 171 | + "() => Math.max(document.documentElement.scrollWidth," | |
| 172 | + " document.body.scrollWidth) - window.innerWidth") | |
| 173 | + check("%s: no horizontal overflow" % tag, over <= 1, over) | |
| 174 | + | |
| 175 | + # source picker populated from action=sources | |
| 176 | + n = page.evaluate("document.querySelectorAll('#srcSel option').length") | |
| 177 | + check("%s: source picker populated" % tag, n >= 2, n) | |
| 178 | + | |
| 179 | + # tail rendered rows | |
| 180 | + rows = page.evaluate("document.querySelectorAll('#log .ln').length") | |
| 181 | + check("%s: tail rendered entries" % tag, rows >= 5, rows) | |
| 182 | + | |
| 183 | + # severity colouring present at least once | |
| 184 | + sev = page.evaluate( | |
| 185 | + "document.querySelectorAll('#log .ln.err, #log .ln.warn').length") | |
| 186 | + check("%s: severity classes applied" % tag, sev >= 1, sev) | |
| 187 | + | |
| 188 | + # no stray grid overflow inside the log | |
| 189 | + clip = page.evaluate( | |
| 190 | + "() => { var l=document.getElementById('log');" | |
| 191 | + " return l.scrollWidth - l.clientWidth; }") | |
| 192 | + check("%s: log body fits its own width" % tag, clip <= 2, clip) | |
| 193 | + | |
| 194 | + shot = os.path.join(SHOTS, "ui-%dx%d-%s.png" % (w, h, theme)) | |
| 195 | + page.screenshot(path=shot, full_page=False) | |
| 196 | + size = os.path.getsize(shot) | |
| 197 | + check("%s: screenshot < 900 KB" % tag, size < 900 * 1024, size) | |
| 198 | + | |
| 199 | + page.close() | |
| 200 | + | |
| 201 | + # one deep behavioural run at the primary viewport | |
| 202 | + page = browser.new_page(viewport={"width": 1440, "height": 900}) | |
| 203 | + page.goto(base + "?theme=dark", wait_until="load") | |
| 204 | + page.wait_for_timeout(800) | |
| 205 | + | |
| 206 | + # switch to the fixture app.log, which carries "error" lines | |
| 207 | + page.evaluate( | |
| 208 | + "() => { var sel = document.getElementById('srcSel');" | |
| 209 | + " for (var i = 0; i < sel.options.length; i++) {" | |
| 210 | + " if (sel.options[i].value.indexOf('app.log') >= 0) {" | |
| 211 | + " sel.value = sel.options[i].value;" | |
| 212 | + " sel.dispatchEvent(new Event('change')); return; } } }") | |
| 213 | + page.wait_for_timeout(800) | |
| 214 | + | |
| 215 | + # search renders highlighted hits | |
| 216 | + page.fill("#q", "error") | |
| 217 | + page.click("#btnSearch") | |
| 218 | + page.wait_for_timeout(900) | |
| 219 | + marks = page.evaluate("document.querySelectorAll('#log mark').length") | |
| 220 | + check("search renders highlighted hits", marks >= 1, marks) | |
| 221 | + fcount = page.inner_text("#fCount") | |
| 222 | + check("search reports hits and scanned count", | |
| 223 | + "hits" in fcount and "scanned" in fcount, fcount) | |
| 224 | + | |
| 225 | + # wrap toggle widens the layout class | |
| 226 | + page.click("#btnWrap") | |
| 227 | + page.wait_for_timeout(150) | |
| 228 | + wrap = page.evaluate("document.getElementById('log').classList.contains('wrap')") | |
| 229 | + check("wrap toggle applies", wrap is True, wrap) | |
| 230 | + page.click("#btnWrap") | |
| 231 | + | |
| 232 | + # clearing the query returns to tail | |
| 233 | + page.fill("#q", "") | |
| 234 | + page.click("#btnSearch") | |
| 235 | + page.wait_for_timeout(700) | |
| 236 | + rows = page.evaluate("document.querySelectorAll('#log .ln').length") | |
| 237 | + check("empty query returns to tail", rows >= 5, rows) | |
| 238 | + | |
| 239 | + # follow toggle pauses the poller | |
| 240 | + page.click("#btnFollow") | |
| 241 | + page.wait_for_timeout(200) | |
| 242 | + st = page.inner_text("#pState") | |
| 243 | + check("follow toggle pauses", "paused" in st.lower(), st) | |
| 244 | + page.click("#btnFollow") | |
| 245 | + | |
| 246 | + # line-count segment changes the request | |
| 247 | + page.click("#segLines button[data-n='500']") | |
| 248 | + page.wait_for_timeout(700) | |
| 249 | + on = page.evaluate( | |
| 250 | + "document.querySelector('#segLines button.on').getAttribute('data-n')") | |
| 251 | + check("line-count segment switches", on == "500", on) | |
| 252 | + | |
| 253 | + # theme button flips the document | |
| 254 | + before = page.evaluate("document.documentElement.getAttribute('data-theme')") | |
| 255 | + page.click("#btnTheme") | |
| 256 | + page.wait_for_timeout(200) | |
| 257 | + after = page.evaluate("document.documentElement.getAttribute('data-theme')") | |
| 258 | + check("theme button flips appearance", before != after, (before, after)) | |
| 259 | + | |
| 260 | + # embed mode hides the back-link only | |
| 261 | + page.goto(base + "?embed=1&theme=dark", wait_until="load") | |
| 262 | + page.wait_for_timeout(600) | |
| 263 | + body = page.inner_text("body") | |
| 264 | + check("embed=1 hides the back-link", "Back to Bot" not in body) | |
| 265 | + rows = page.evaluate("document.querySelectorAll('#log .ln').length") | |
| 266 | + check("embed=1 still renders entries", rows >= 5, rows) | |
| 267 | + | |
| 268 | + page.close() | |
| 269 | + browser.close() | |
| 270 | + finally: | |
| 271 | + httpd.shutdown() | |
| 272 | + shutil.rmtree(tmp, ignore_errors=True) | |
| 273 | + | |
| 274 | + print("\n== summary ==") | |
| 275 | + print(" passed: %d" % len(PASSES)) | |
| 276 | + print(" failed: %d" % len(FAILS)) | |
| 277 | + if FAILS: | |
| 278 | + print(" RESULT: FAILED") | |
| 279 | + return 1 | |
| 280 | + print(" RESULT: ALL PASSED") | |
| 281 | + return 0 | |
| 282 | + | |
| 283 | + | |
| 284 | +if __name__ == "__main__": | |
| 285 | + sys.exit(main()) |
| 1 | 1 | new file mode 100755 |
| index 0000000..6281a98 | ||
| --- /dev/null | ||
| +++ b/tests/run.sh | ||
| @@ -0,0 +1,432 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/run.sh - offline checks for plugin_logs across all 3 modes. | |
| 3 | +# | |
| 4 | +# Runs against ./plugin_logs (native build) on the live machine. Journal output | |
| 5 | +# is replayed from a captured fixture so the parser is tested on the real | |
| 6 | +# `journalctl -o json` layout without needing a running journald, and the file | |
| 7 | +# reader is pointed at fixture logs through the SX_LOGS_EXTRA_ROOT knob. The | |
| 8 | +# last section audits the whole git history for secrets and internal addresses. | |
| 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_logs | |
| 18 | +PASS=0 | |
| 19 | +FAIL=0 | |
| 20 | +TMP=$(mktemp -d 2>/dev/null || echo /tmp/logs_test_$$) | |
| 21 | +mkdir -p "$TMP" | |
| 22 | +trap 'rm -rf "$TMP"' EXIT | |
| 23 | + | |
| 24 | +if [ -t 1 ]; then | |
| 25 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | |
| 26 | +else | |
| 27 | + C_OK=; C_BAD=; C_B=; C_0= | |
| 28 | +fi | |
| 29 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | |
| 30 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | |
| 31 | + | |
| 32 | +check() { # check <desc> <expected-substring> <actual> | |
| 33 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | |
| 34 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)" | |
| 35 | + fi | |
| 36 | +} | |
| 37 | + | |
| 38 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | |
| 39 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | |
| 40 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | |
| 41 | + fi | |
| 42 | +} | |
| 43 | + | |
| 44 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | |
| 45 | +body() { printf '%s' "$1" | sed '1,/^\r$/d'; } | |
| 46 | + | |
| 47 | +# ---------------------------------------------------------------- fixtures | |
| 48 | +# A journal stream in the exact shape journalctl -o json emits (one object per | |
| 49 | +# line, microsecond epoch timestamps, string PRIORITY, arrays for binary fields). | |
| 50 | +JFIX="$TMP/journal.jsonl" | |
| 51 | +cat > "$JFIX" <<'JSONL' | |
| 52 | +{"__REALTIME_TIMESTAMP":"1762923001000000","PRIORITY":"3","_SYSTEMD_UNIT":"nginx.service","MESSAGE":"upstream timed out while reading response header"} | |
| 53 | +{"__REALTIME_TIMESTAMP":"1762923002000000","PRIORITY":"4","_SYSTEMD_UNIT":"systemd","MESSAGE":"Some unit is deprecated"} | |
| 54 | +{"__REALTIME_TIMESTAMP":"1762923003000000","PRIORITY":"6","SYSLOG_IDENTIFIER":"kernel","MESSAGE":"eth0 link up"} | |
| 55 | +{"__REALTIME_TIMESTAMP":"1762923004000000","PRIORITY":"6","_SYSTEMD_UNIT":"cron.service","MESSAGE":["multi","line"]} | |
| 56 | +{"__REALTIME_TIMESTAMP":"1762923005000000","PRIORITY":"6","_SYSTEMD_UNIT":"sshd.service","MESSAGE":"Accepted publickey for root"} | |
| 57 | +JSONL | |
| 58 | + | |
| 59 | +FROOT="$TMP/fixtures" | |
| 60 | +mkdir -p "$FROOT/sub/deeper" | |
| 61 | +printf 'Nov 12 06:30:01 host sshd[123]: error: failed login\nNov 12 06:30:02 host cron[9]: (root) CMD ok\n' > "$FROOT/sub/app.log" | |
| 62 | +cat > "$FROOT/sub/deeper/iso.log" <<'LOG' | |
| 63 | +2026-11-12T06:31:00Z warn: something is deprecated | |
| 64 | +2026-11-12T06:31:05Z FATAL: disk controller panic | |
| 65 | +plain line with no timestamp at all | |
| 66 | +LOG | |
| 67 | +printf 'not a log file\n' > "$FROOT/sub/notes.txt" | |
| 68 | +ZEROS="$FROOT/sub/deeper/empty.log" | |
| 69 | +: > "$ZEROS" | |
| 70 | + | |
| 71 | +export SX_LOGS_JOURNAL_FIXTURE="$JFIX" | |
| 72 | +export SX_LOGS_EXTRA_ROOT="$FROOT" | |
| 73 | + | |
| 74 | +jq_() { # jq_ <desc> <python-expression using d> <json> | |
| 75 | + printf '%s' "$3" > "$TMP/_j.json" | |
| 76 | + if python3 - "$TMP/_j.json" "$2" <<'PY' 2>/dev/null | |
| 77 | +import json, sys | |
| 78 | +d = json.load(open(sys.argv[1])) | |
| 79 | +assert eval(sys.argv[2], {"d": d}), sys.argv[2] | |
| 80 | +PY | |
| 81 | + then pass "$1"; else fail "$1"; fi | |
| 82 | +} | |
| 83 | + | |
| 84 | +# ---------------------------------------------------------------- build | |
| 85 | +section "build" | |
| 86 | +if [ ! -x "$BIN" ]; then | |
| 87 | + echo " building native binary..." | |
| 88 | + cc -O2 -std=c99 -Wall -Wextra -I src -o "$BIN" src/plugin_logs.c || { echo " build failed"; exit 1; } | |
| 89 | +fi | |
| 90 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | |
| 91 | + | |
| 92 | +# ---------------------------------------------------------------- meta mode | |
| 93 | +section "mode 1 --meta (must work without auth - discovery)" | |
| 94 | +META=$("$BIN" --meta) | |
| 95 | +check "meta emits name logs" '"name":"logs"' "$META" | |
| 96 | +check "meta emits desc Log viewer" '"desc":"Log viewer"' "$META" | |
| 97 | +METAENV=$(SX_PLUGIN_META=1 "$BIN") | |
| 98 | +check "SX_PLUGIN_META=1 yields same meta" '"name":"logs"' "$METAENV" | |
| 99 | +LEN=$(printf '%s' "$META" | wc -c | tr -d ' ') | |
| 100 | +[ "$LEN" -lt 60 ] && pass "meta payload is compact ($LEN bytes)" || fail "meta payload too long ($LEN)" | |
| 101 | +printf '%s' "$META" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | |
| 102 | + && pass "meta is valid JSON" || fail "meta is not valid JSON" | |
| 103 | +DESC=$(printf '%s' "$META" | sed 's/.*"desc":"\([^"]*\)".*/\1/') | |
| 104 | +[ ${#DESC} -le 15 ] && pass "desc length ${#DESC} <= 15 chars" || fail "desc too long (${#DESC})" | |
| 105 | +NAME=$(printf '%s' "$META" | sed 's/.*"name":"\([^"]*\)".*/\1/') | |
| 106 | +[ "$(printf '%s' "$NAME" | wc -w | tr -d ' ')" -le 2 ] && pass "name is at most two words" || fail "name has too many words" | |
| 107 | +check "--version prints version" '1.0.0' "$("$BIN" --version)" | |
| 108 | +check "--help is available" 'usage:' "$("$BIN" --help)" | |
| 109 | +META_AUTH=$(BOT_PASSWORD=secret "$BIN" --meta) | |
| 110 | +check "meta still works when BOT_PASSWORD is set" '"name":"logs"' "$META_AUTH" | |
| 111 | + | |
| 112 | +# ---------------------------------------------------------------- auth | |
| 113 | +section "node auth" | |
| 114 | +AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=sources' "$BIN") | |
| 115 | +check "no credentials -> 401" 'Status: 401' "$AUTHNONE" | |
| 116 | +check "401 body is json" 'invalid node password' "$AUTHNONE" | |
| 117 | +AUTHH=$(body "$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING='action=sources' "$BIN")") | |
| 118 | +check "X-Bot-Password accepted" '"ok":true' "$AUTHH" | |
| 119 | +AUTHB=$(body "$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=sources' "$BIN")") | |
| 120 | +check "Authorization Bearer accepted" '"ok":true' "$AUTHB" | |
| 121 | +AUTHQ=$(body "$(BOT_PASSWORD=testpw QUERY_STRING='action=sources&pwd=testpw' "$BIN")") | |
| 122 | +check "?pwd= accepted (plugin iframe)" '"ok":true' "$AUTHQ" | |
| 123 | +AUTHBAD=$(BOT_PASSWORD=testpw QUERY_STRING='action=sources&pwd=wrong' "$BIN") | |
| 124 | +check "wrong ?pwd= -> 401" 'Status: 401' "$AUTHBAD" | |
| 125 | +META_NOAUTH=$(BOT_PASSWORD=testpw "$BIN" --meta) | |
| 126 | +check "--meta is never gated by auth" '"name":"logs"' "$META_NOAUTH" | |
| 127 | + | |
| 128 | +# ---------------------------------------------------------------- sources | |
| 129 | +section "mode 2 action=sources" | |
| 130 | +SRCJSON=$(body "$(QUERY_STRING='action=sources' "$BIN")") | |
| 131 | +check "sources ok:true" '"ok":true' "$SRCJSON" | |
| 132 | +check "sources echoes the action" '"action":"sources"' "$SRCJSON" | |
| 133 | +check "sources reports journal availability" '"journal_available":' "$SRCJSON" | |
| 134 | +check "sources carries the plugin id" '"plugin":"plugin_logs"' "$SRCJSON" | |
| 135 | +check "sources reports truncation flag" '"truncated":' "$SRCJSON" | |
| 136 | +check "fixture log listed" "file:$FROOT/sub/app.log" "$SRCJSON" | |
| 137 | +check "nested fixture log listed" "deeper/iso.log" "$SRCJSON" | |
| 138 | +check_not "non-.log fixture is not listed" "notes.txt" "$SRCJSON" | |
| 139 | +jq_ 'sources has one entry per listed item' 'd["count"] == len(d["sources"])' "$SRCJSON" | |
| 140 | +jq_ 'every source has id/label/kind' 'all(s.get("id") and s.get("label") and s.get("kind") for s in d["sources"])' "$SRCJSON" | |
| 141 | +jq_ 'file sources carry a positive size' 'all(s["size"] > 0 for s in d["sources"] if s["kind"] == "file")' "$SRCJSON" | |
| 142 | +jq_ 'every source path is inside an allowlisted root' 'all((s["id"].startswith("file:/var/log/") or s["id"].startswith("file:/workspace/") or s["id"].startswith("file:" + __import__("os").environ["HOME"] + "/.scorpiox/") or s["id"].startswith("file:'"$FROOT"'/") or s["id"] in ("journal",) or s["id"].startswith("event:")) for s in d["sources"])' "$SRCJSON" | |
| 143 | + | |
| 144 | +# ---------------------------------------------------------------- tail (journal) | |
| 145 | +section "mode 2 action=tail (journal fixture)" | |
| 146 | +JT=$(body "$(QUERY_STRING='action=tail&src=journal&lines=10' "$BIN")") | |
| 147 | +check "journal tail ok:true" '"ok":true' "$JT" | |
| 148 | +check "journal tail echoes src" '"src":"journal"' "$JT" | |
| 149 | +check "journal tail kind journal" '"kind":"journal"' "$JT" | |
| 150 | +check "journal severity err from PRIORITY=3" '"sev":"err"' "$JT" | |
| 151 | +check "journal severity warn from PRIORITY=4" '"sev":"warn"' "$JT" | |
| 152 | +check "journal unit extracted" '"unit":"nginx.service"' "$JT" | |
| 153 | +check "journal message extracted" 'upstream timed out' "$JT" | |
| 154 | +check "binary MESSAGE rendered as a placeholder" '"(binary)"' "$JT" | |
| 155 | +check "SYSLOG_IDENTIFIER used when no unit" '"unit":"kernel"' "$JT" | |
| 156 | +jq_ 'journal tail returns exactly the fixture entries' 'd["count"] == 5 and len(d["entries"]) == 5' "$JT" | |
| 157 | +jq_ 'journal timestamps are formatted' 'all(len(e["ts"]) >= 8 for e in d["entries"])' "$JT" | |
| 158 | +jq_ 'journal severities are one of info/warn/err' 'all(e["sev"] in ("info","warn","err") for e in d["entries"])' "$JT" | |
| 159 | +jq_ 'journal text is never empty' 'all(e["text"] != "" for e in d["entries"])' "$JT" | |
| 160 | + | |
| 161 | +J1=$(body "$(QUERY_STRING='action=tail&src=journal&lines=1' "$BIN")") | |
| 162 | +jq_ 'lines=1 limits the fixture window to one entry' 'd["count"] >= 1 and d["requested"] == 1' "$J1" | |
| 163 | +JBIG=$(body "$(QUERY_STRING='action=tail&src=journal&lines=999999' "$BIN")") | |
| 164 | +check "absurd lines still answers ok" '"ok":true' "$JBIG" | |
| 165 | +check "absurd lines is capped" '"requested":2000' "$JBIG" | |
| 166 | +JZERO=$(body "$(QUERY_STRING='action=tail&src=journal&lines=0' "$BIN")") | |
| 167 | +check "lines=0 falls back to the default" '"requested":200' "$JZERO" | |
| 168 | + | |
| 169 | +# ---------------------------------------------------------------- tail (file) | |
| 170 | +section "mode 2 action=tail (log file)" | |
| 171 | +FSRC="file:$FROOT/sub/app.log" | |
| 172 | +FT=$(body "$(QUERY_STRING="action=tail&src=$FSRC&lines=10" "$BIN")") | |
| 173 | +check "file tail ok:true" '"ok":true' "$FT" | |
| 174 | +check "file tail kind file" '"kind":"file"' "$FT" | |
| 175 | +check "syslog timestamp parsed" '"ts":"Nov 12 06:30:01"' "$FT" | |
| 176 | +check "syslog unit parsed" '"unit":"sshd[123]"' "$FT" | |
| 177 | +check "syslog message parsed" 'error: failed login' "$FT" | |
| 178 | +check "error line is severity err" '"sev":"err"' "$FT" | |
| 179 | +jq_ 'file tail returns every fixture line' 'd["count"] == 2' "$FT" | |
| 180 | + | |
| 181 | +ISRC="file:$FROOT/sub/deeper/iso.log" | |
| 182 | +IT=$(body "$(QUERY_STRING="action=tail&src=$ISRC&lines=10" "$BIN")") | |
| 183 | +check "ISO-8601 timestamp parsed" '"ts":"2026-11-12T06:31:00Z"' "$IT" | |
| 184 | +check "FATAL line is severity err" 'disk controller panic' "$IT" | |
| 185 | +check "plain line still has text" 'plain line with no timestamp' "$IT" | |
| 186 | +jq_ 'plain line carries no timestamp' 'any(e["ts"] == "" for e in d["entries"])' "$IT" | |
| 187 | + | |
| 188 | +ESRC="file:$FROOT/sub/deeper/empty.log" | |
| 189 | +ET=$(body "$(QUERY_STRING="action=tail&src=$ESRC&lines=5" "$BIN")") | |
| 190 | +check "empty file answers ok (or is simply not listed)" '"ok":' "$ET" | |
| 191 | + | |
| 192 | +# ---------------------------------------------------------------- search | |
| 193 | +section "mode 2 action=search" | |
| 194 | +ST=$(body "$(QUERY_STRING="action=search&src=$FSRC&q=FAILED" "$BIN")") | |
| 195 | +check "search is case-insensitive" 'error: failed login' "$ST" | |
| 196 | +check "search echoes the query" '"q":"FAILED"' "$ST" | |
| 197 | +check "search reports scanned count" '"scanned":' "$ST" | |
| 198 | +jq_ 'case-insensitive search finds exactly the failing line' 'd["count"] == 1' "$ST" | |
| 199 | +jq_ 'search response carries hit objects' 'all("ts" in h and "sev" in h and "text" in h for h in d["hits"])' "$ST" | |
| 200 | + | |
| 201 | +SMISS=$(body "$(QUERY_STRING="action=search&src=$FSRC&q=zzzznotthere" "$BIN")") | |
| 202 | +jq_ 'a query with no match returns zero hits' 'd["ok"] is True and d["count"] == 0' "$SMISS" | |
| 203 | +check "no-match is not an error" '"ok":true' "$SMISS" | |
| 204 | + | |
| 205 | +JS=$(body "$(QUERY_STRING='action=search&src=journal&q=deprecated' "$BIN")") | |
| 206 | +jq_ 'journal search filters the fixture' 'd["count"] == 1 and d["scanned"] == 5' "$JS" | |
| 207 | +check "journal search keeps severity" '"sev":"warn"' "$JS" | |
| 208 | + | |
| 209 | +NOQ=$(body "$(QUERY_STRING="action=search&src=$FSRC" "$BIN")") | |
| 210 | +check "search without q is rejected" 'missing_query' "$NOQ" | |
| 211 | + | |
| 212 | +# ---------------------------------------------------------------- refusals | |
| 213 | +section "mode 2 refusals (read allowlist)" | |
| 214 | +for bad in 'file:/etc/passwd' 'file:/etc/shadow' 'file:/proc/self/environ' \ | |
| 215 | + '../../../../etc/passwd' 'journal:../../etc' 'file:' ''; do | |
| 216 | + R=$(body "$(QUERY_STRING="action=tail&src=$bad&lines=5" "$BIN")") | |
| 217 | + if printf '%s' "$R" | grep -F -q 'source_not_allowed' || printf '%s' "$R" | grep -F -q 'source_unavailable'; then | |
| 218 | + pass "refused: ${bad:-<empty>}" | |
| 219 | + else | |
| 220 | + fail "should have refused: ${bad:-<empty>}" | |
| 221 | + printf ' got: %s\n' "$(printf '%s' "$R" | head -c 200)" | |
| 222 | + fi | |
| 223 | +done | |
| 224 | +R=$(body "$(QUERY_STRING='action=tail&src=file:/workspace' "$BIN")") | |
| 225 | +check_not "a directory is never opened as a log" '"ok":true' "$R" | |
| 226 | +RU=$(body "$(QUERY_STRING='action=tail&src=journal:--help' "$BIN")") | |
| 227 | +check_not "a unit name starting with '-' is refused" '"ok":true' "$RU" | |
| 228 | +RU2=$(body "$(QUERY_STRING='action=tail&src=journal:nginx.service;rm -rf /' "$BIN")") | |
| 229 | +check_not "a unit name with shell text is refused" '"ok":true' "$RU2" | |
| 230 | + | |
| 231 | +UNK=$(body "$(QUERY_STRING='action=bogus' "$BIN")") | |
| 232 | +check "unknown action rejected" 'unknown_action' "$UNK" | |
| 233 | +check "unknown action lists supported" '"supported":["sources","tail","search","units","info"]' "$UNK" | |
| 234 | +check "unknown action echoes request" '"requested":"bogus"' "$UNK" | |
| 235 | + | |
| 236 | +# ---------------------------------------------------------------- units / info | |
| 237 | +section "mode 2 action=units and action=info" | |
| 238 | +UNITS=$(body "$(QUERY_STRING='action=units' "$BIN")") | |
| 239 | +check "units ok:true" '"ok":true' "$UNITS" | |
| 240 | +check "units reports availability" '"available":' "$UNITS" | |
| 241 | +jq_ 'units count matches the array' 'd["count"] == len(d["units"])' "$UNITS" | |
| 242 | +jq_ 'every unit offers a journal:<name> src' 'all(u["src"].startswith("journal:") for u in d["units"])' "$UNITS" | |
| 243 | + | |
| 244 | +INFO=$(body "$(QUERY_STRING='action=info' "$BIN")") | |
| 245 | +check "info ok:true" '"ok":true' "$INFO" | |
| 246 | +check "info action info" '"action":"info"' "$INFO" | |
| 247 | +check "info declares zero network" '"zero_network":true' "$INFO" | |
| 248 | +check "info declares read-only" '"read_only":true' "$INFO" | |
| 249 | +check "info node_auth false when unset" '"node_auth":false' "$INFO" | |
| 250 | +check "info publishes the line cap" '"lines_max":2000' "$INFO" | |
| 251 | +check "info publishes the hit cap" '"search_hits_max":500' "$INFO" | |
| 252 | +INFOAUTH=$(body "$(BOT_PASSWORD=pw QUERY_STRING='action=info&pwd=pw' "$BIN")") | |
| 253 | +check "info node_auth true when set" '"node_auth":true' "$INFOAUTH" | |
| 254 | +printf '%s' "$INFO" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | |
| 255 | + && pass "info body is valid JSON" || fail "info body JSON invalid" | |
| 256 | +check "format=json works as an alias" '"ok":true' "$(body "$(QUERY_STRING='format=json&action=info' "$BIN")")" | |
| 257 | + | |
| 258 | +# ---------------------------------------------------------------- html | |
| 259 | +section "mode 3 HTML" | |
| 260 | +HTML=$(QUERY_STRING='' "$BIN") | |
| 261 | +check "html content-type" 'Content-Type: text/html; charset=utf-8' "$HTML" | |
| 262 | +check_not "html has no Content-Length" 'Content-Length' "$HTML" | |
| 263 | +check "html has viewport meta" 'width=device-width' "$HTML" | |
| 264 | +check "html title logs" '<title>logs</title>' "$HTML" | |
| 265 | +check "html back-link present" 'Back to Bot' "$HTML" | |
| 266 | +check "html theme switch hook" 'bot_theme' "$HTML" | |
| 267 | +check "html source picker present" "id='srcSel'" "$HTML" | |
| 268 | +check "html log viewport present" "id='log'" "$HTML" | |
| 269 | +check "html search input present" "id='q'" "$HTML" | |
| 270 | +check "html follow toggle present" "id='btnFollow'" "$HTML" | |
| 271 | +check "html wrap toggle present" "id='btnWrap'" "$HTML" | |
| 272 | +check "html copy button present" "id='btnCopy'" "$HTML" | |
| 273 | +check "html line-count segmented control" 'data-n=' "$HTML" | |
| 274 | +check "html calls action=sources" 'action=sources' "$HTML" | |
| 275 | +check "html calls action=tail" 'action=tail' "$HTML" | |
| 276 | +check "html calls action=search" 'action=search' "$HTML" | |
| 277 | +check "html uses /plugins?plugin= route" "/plugins?plugin=" "$HTML" | |
| 278 | +check "html falls back to /plugin_logs" "/plugin_logs" "$HTML" | |
| 279 | +check "html highlights matches with mark" "'mark'" "$HTML" | |
| 280 | +check "html polls every 3s when following" '3000' "$HTML" | |
| 281 | +check "html pauses when the tab is hidden" 'visibilitychange' "$HTML" | |
| 282 | +check "html closes document" '</html>' "$HTML" | |
| 283 | +check "html declares read-only local read" 'read-only' "$HTML" | |
| 284 | + | |
| 285 | +# ---- theme handoff (bot_theme_plugin.h) ---- | |
| 286 | +check "html reads ?theme= before paint" 'theme=(light|dark)' "$HTML" | |
| 287 | +check "html has the sx-theme listener" "type==='sx-theme'" "$HTML" | |
| 288 | +check "html asks the host for its theme" 'sx-theme-request' "$HTML" | |
| 289 | +check "html uses the shared bot_theme key" "localStorage.getItem('bot_theme')" "$HTML" | |
| 290 | +check "html carries bot theme tokens" '--bg-card' "$HTML" | |
| 291 | +check_not "html no private palette 0b0b0e" '0b0b0e' "$HTML" | |
| 292 | +check_not "html no private palette 141419" '141419' "$HTML" | |
| 293 | +check_not "html no private palette f2f2f6" 'f2f2f6' "$HTML" | |
| 294 | +THEMEQ=$(QUERY_STRING='theme=light' "$BIN") | |
| 295 | +check "?theme=light still renders the UI" 'prefers-color-scheme' "$THEMEQ" | |
| 296 | + | |
| 297 | +EMB=$(QUERY_STRING='embed=1' "$BIN") | |
| 298 | +check_not "embed=1 strips the back-link" 'Back to Bot' "$EMB" | |
| 299 | +check "embed=1 still renders the UI" "id='log'" "$EMB" | |
| 300 | +EMBT=$(QUERY_STRING='embed=true' "$BIN") | |
| 301 | +check_not "embed=true also strips back-link" 'Back to Bot' "$EMBT" | |
| 302 | + | |
| 303 | +ZEROEMOJI=$(printf '%s' "$HTML" | python3 -c ' | |
| 304 | +import sys | |
| 305 | +s = sys.stdin.read() | |
| 306 | +bad = [c for c in s if ord(c) > 0x2600 and ord(c) not in (0x2014, 0x2013, 0x2026)] | |
| 307 | +print(len(bad)) | |
| 308 | +') | |
| 309 | +[ "$ZEROEMOJI" = "0" ] && pass "HTML contains no emoji glyphs" || fail "HTML has $ZEROEMOJI emoji glyph(s)" | |
| 310 | + | |
| 311 | +check_not "html has no <script src=>" '<script src=' "$HTML" | |
| 312 | +check_not "html has no CDN reference" 'cdnjs' "$HTML" | |
| 313 | +check_not "html has no external font" 'fonts.googleapis' "$HTML" | |
| 314 | +PK="pico""bot" | |
| 315 | +check_not "html has no internal fleet paths" "$PK" "$HTML" | |
| 316 | +check_not "html has no private IPs" "192.168." "$HTML" | |
| 317 | +check_not "html has no ssh/sshpass" "sshpass" "$HTML" | |
| 318 | + | |
| 319 | +section "responsive markup" | |
| 320 | +check "html has a 760px breakpoint" '@media(max-width:760px)' "$HTML" | |
| 321 | +check "html has a 480px breakpoint" '@media(max-width:480px)' "$HTML" | |
| 322 | +check "html hides the unit column on mobile" 'ln .un{display:none}' "$HTML" | |
| 323 | +check "html scrolls the log viewport" 'overflow:auto' "$HTML" | |
| 324 | + | |
| 325 | +# ---------------------------------------------------------------- source audit | |
| 326 | +section "no sockets, no user-controlled shell" | |
| 327 | +SRCCAT=$(cat src/plugin_logs.c) | |
| 328 | +check_not "source opens no sockets" 'socket(' "$SRCCAT" | |
| 329 | +check_not "source has no curl or wget" 'wget' "$SRCCAT" | |
| 330 | +check_not "source has no ssh invocation" 'ssh ' "$SRCCAT" | |
| 331 | +check_not "source has no sshpass" 'sshpass' "$SRCCAT" | |
| 332 | +check_not "source never calls system()" 'system(' "$SRCCAT" | |
| 333 | +check "journal argv is built with snprintf" 'journalctl -o json --no-pager' "$SRCCAT" | |
| 334 | +check "unit names are validated" 'valid_unit' "$SRCCAT" | |
| 335 | +check "files are opened read-only" '"rb"' "$SRCCAT" | |
| 336 | +check "tail reads are bounded" 'FILE_TAIL_BYTES' "$SRCCAT" | |
| 337 | +check "walks have a per-root budget" 'ROOT_BUDGET' "$SRCCAT" | |
| 338 | +check "symlinks are never followed" 'S_ISLNK' "$SRCCAT" | |
| 339 | + | |
| 340 | +# ---------------------------------------------------------------- optional targets | |
| 341 | +section "optional cross builds" | |
| 342 | +if [ -f plugin_logs.musl ]; then | |
| 343 | + M=$(./plugin_logs.musl --meta) | |
| 344 | + check "musl build --meta" '"name":"logs"' "$M" | |
| 345 | + case $(head -c 4 plugin_logs.musl | od -An -tx1 | tr -d ' \n') in | |
| 346 | + 7f454c46) pass "musl artifact is ELF" ;; | |
| 347 | + *) fail "musl artifact is not ELF" ;; | |
| 348 | + esac | |
| 349 | +else | |
| 350 | + echo " skip musl (not built)" | |
| 351 | +fi | |
| 352 | +if [ -f plugin_logs.arm64 ]; then | |
| 353 | + case $(head -c 20 plugin_logs.arm64 | od -An -tx1 | tr -d ' \n') in | |
| 354 | + 7f454c46*e500b700*|7f454c46*b700*) pass "arm64 artifact is an aarch64 ELF" ;; | |
| 355 | + 7f454c46*) | |
| 356 | + if od -An -tx1 -j18 -N2 plugin_logs.arm64 | tr -d ' \n' | grep -q 'b7'; then | |
| 357 | + pass "arm64 artifact is an aarch64 ELF" | |
| 358 | + else | |
| 359 | + fail "arm64 artifact is not aarch64" | |
| 360 | + fi ;; | |
| 361 | + *) fail "arm64 artifact is not ELF" ;; | |
| 362 | + esac | |
| 363 | +else | |
| 364 | + echo " skip arm64 (not built)" | |
| 365 | +fi | |
| 366 | +if [ -f plugin_logs.exe ]; then | |
| 367 | + MAGIC=$(head -c 2 plugin_logs.exe) | |
| 368 | + [ "$MAGIC" = "MZ" ] && pass "windows artifact has MZ header" || fail "windows artifact missing MZ" | |
| 369 | + SZ=$(wc -c < plugin_logs.exe | tr -d ' ') | |
| 370 | + [ "$SZ" -gt 20000 ] && pass "windows artifact is not an error page ($SZ bytes)" || fail "windows artifact suspiciously small ($SZ bytes)" | |
| 371 | +else | |
| 372 | + echo " skip windows PE (not built)" | |
| 373 | +fi | |
| 374 | +if [ -f plugin_logs.macos-arm64 ]; then | |
| 375 | + case $(head -c 4 plugin_logs.macos-arm64 | od -An -tx1 | tr -d ' \n') in | |
| 376 | + cffaedfe|cefaedfe) pass "macos-arm64 artifact is Mach-O" ;; | |
| 377 | + *) fail "macos-arm64 artifact is not Mach-O" ;; | |
| 378 | + esac | |
| 379 | +else | |
| 380 | + echo " skip macos-arm64 (not built)" | |
| 381 | +fi | |
| 382 | +if [ -f plugin_logs.macos-x86_64 ]; then | |
| 383 | + case $(head -c 4 plugin_logs.macos-x86_64 | od -An -tx1 | tr -d ' \n') in | |
| 384 | + cffaedfe|cefaedfe) pass "macos-x86_64 artifact is Mach-O" ;; | |
| 385 | + *) fail "macos-x86_64 artifact is not Mach-O" ;; | |
| 386 | + esac | |
| 387 | +else | |
| 388 | + echo " skip macos-x86_64 (not built)" | |
| 389 | +fi | |
| 390 | + | |
| 391 | +# ---------------------------------------------------------------- history audit | |
| 392 | +section "git history secret & LAN audit" | |
| 393 | +if git rev-parse --git-dir >/dev/null 2>&1; then | |
| 394 | + ALL="$TMP/history.txt" | |
| 395 | + # Bookkeeping lines of this audit are excluded so the detector cannot flag | |
| 396 | + # itself. Detector literals are also assembled from fragments below. | |
| 397 | + git log -p --all 2>/dev/null \ | |
| 398 | + | grep -v '^Author: ' \ | |
| 399 | + | grep -vE 'audit "|HITS=|grep -E|scan "' \ | |
| 400 | + > "$ALL" || : > "$ALL" | |
| 401 | + | |
| 402 | + audit() { # audit <label> <regex> | |
| 403 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | |
| 404 | + if [ -n "$H" ]; then | |
| 405 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | |
| 406 | + else | |
| 407 | + pass "history clean: $1" | |
| 408 | + fi | |
| 409 | + } | |
| 410 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 411 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 412 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 413 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 414 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 415 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 416 | + PK2="pico""bot"; WT=".work""trees" | |
| 417 | + audit "fleet path" "/codebases/${PK2}|${WT}/" | |
| 418 | + audit "internal hostname" 'intel-ultra2|macmini2018i5|lazarus' | |
| 419 | +else | |
| 420 | + echo " skip history audit (not a git checkout)" | |
| 421 | +fi | |
| 422 | + | |
| 423 | +# ---------------------------------------------------------------- summary | |
| 424 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | |
| 425 | +printf ' passed: %d\n' "$PASS" | |
| 426 | +printf ' failed: %d\n' "$FAIL" | |
| 427 | +if [ "$FAIL" -ne 0 ]; then | |
| 428 | + printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0" | |
| 429 | + exit 1 | |
| 430 | +fi | |
| 431 | +printf ' %sRESULT: ALL PASSED%s\n' "$C_OK" "$C_0" | |
| 432 | +exit 0 | |
| 0 | 433 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..c6fb4d7 | index 0000000..c6fb4d7 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,11 @@ | @@ -0,0 +1,11 @@ | ||
| 1 | +plugin_logs | ||
| 2 | +plugin_logs.exe | ||
| 3 | +plugin_logs.musl | ||
| 4 | +plugin_logs.arm64 | ||
| 5 | +plugin_logs.macos-arm64 | ||
| 6 | +plugin_logs.macos-x86_64 | ||
| 7 | +bin/ | ||
| 8 | +dist/ | ||
| 9 | +*.o | ||
| 10 | +__pycache__/ | ||
| 11 | +*.pyc |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..edac426 | index 0000000..edac426 | ||
| --- /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..060ae0e | index 0000000..060ae0e | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,62 @@ | @@ -0,0 +1,62 @@ | ||
| 1 | +# plugin_logs - SCORPIOX BOT open-source local log viewer plugin | ||
| 2 | +# | ||
| 3 | +# Targets: | ||
| 4 | +# make native build -> ./plugin_logs | ||
| 5 | +# make musl static musl x86_64 -> ./plugin_logs (fully static) | ||
| 6 | +# make arm64 static aarch64 -> ./plugin_logs.arm64 | ||
| 7 | +# make win64 MinGW-w64 static -> ./plugin_logs.exe | ||
| 8 | +# make macos Apple clang -> ./plugin_logs (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_logs.c | ||
| 21 | +BIN := plugin_logs | ||
| 22 | +EXE := plugin_logs.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) src/bot_theme_plugin.h | ||
| 31 | + @echo "==> native build ($(CC))" | ||
| 32 | + $(CC) $(CFLAGS) -I src -o $(BIN) $(SRC) | ||
| 33 | + | ||
| 34 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | ||
| 35 | +musl: $(SRC) src/bot_theme_plugin.h | ||
| 36 | + @echo "==> static musl build ($(MUSL_CC))" | ||
| 37 | + $(MUSL_CC) $(MUSL_CFLAGS) -I src -o $(BIN) $(SRC) | ||
| 38 | + | ||
| 39 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | ||
| 40 | +arm64: $(SRC) src/bot_theme_plugin.h | ||
| 41 | + @echo "==> static aarch64 build ($(ARM64_CC))" | ||
| 42 | + $(ARM64_CC) $(ARM64_CFLAGS) -I src -o $(BIN).arm64 $(SRC) | ||
| 43 | + | ||
| 44 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | ||
| 45 | +win64: $(SRC) src/bot_theme_plugin.h | ||
| 46 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | ||
| 47 | + $(WIN_CC) $(WIN_CFLAGS) -I src -o $(EXE) $(SRC) | ||
| 48 | + | ||
| 49 | +# Apple clang build (run this on macOS) | ||
| 50 | +macos: $(SRC) src/bot_theme_plugin.h | ||
| 51 | + @echo "==> Apple clang build" | ||
| 52 | + $(CC) $(CFLAGS) -I src -o $(BIN) $(SRC) | ||
| 53 | + | ||
| 54 | +test: native | ||
| 55 | + @sh tests/run.sh | ||
| 56 | + | ||
| 57 | +clean: | ||
| 58 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64 | ||
| 59 | + rm -rf bin dist | ||
| 60 | + | ||
| 61 | +help: | ||
| 62 | + @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..4e4c568 | index 0000000..4e4c568 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/README.md | +++ b/README.md | ||
| @@ -0,0 +1,148 @@ | @@ -0,0 +1,148 @@ | ||
| 1 | +# plugin_logs — SCORPIOX BOT local log viewer | ||
| 2 | + | ||
| 3 | +A read-only local **log tail and search** viewer for SCORPIOX BOT nodes, in one | ||
| 4 | +zero-dependency C99 binary. It reads an explicit allowlist of local log files | ||
| 5 | +and the local system journal, renders a responsive dark/light panel with | ||
| 6 | +severity colouring and hit highlighting, and never writes anything or opens a | ||
| 7 | +network socket. | ||
| 8 | + | ||
| 9 | +``` | ||
| 10 | + ┌──────────────────────── plugin_logs ────────────────────────┐ | ||
| 11 | + ?action= │ sources list what can be read (journal / *.log / eventlog) │ | ||
| 12 | + JSON API │ tail last N entries of one source │ | ||
| 13 | + │ search case-insensitive substring search over one source │ | ||
| 14 | + │ units systemd units that have journal entries │ | ||
| 15 | + │ info plugin info, caps, auth state │ | ||
| 16 | + └─────────────────────────────────────────────────────────────┘ | ||
| 17 | + GET → HTML viewer (?embed=1 for the Chat floating window) | ||
| 18 | +``` | ||
| 19 | + | ||
| 20 | +## What it reads | ||
| 21 | + | ||
| 22 | +| Platform | Sources | | ||
| 23 | +|---|---| | ||
| 24 | +| Linux | `journalctl -o json` (system journal and `journal:<unit>`); `*.log` directly under `/var/log`, plus `syslog`, `messages`, `kern.log`, `auth.log`; `$HOME/.scorpiox/**/*.log` and `/workspace/**/*.log` to depth 4 | | ||
| 25 | +| macOS | `log show --style compact --last <Nm>` (bounded to 60 min); `*.log` directly under `/var/log`, `system.log`; `~/Library/Logs/**/*.log` to depth 3 | | ||
| 26 | +| Windows | `wevtutil qe System\|Application /f:text` (fixed argv); `%LOCALAPPDATA%\scorpiox\**\*.log` to depth 4 | | ||
| 27 | + | ||
| 28 | +Nothing else is readable. A request for `file:/etc/passwd`, a directory, or an | ||
| 29 | +id that is not in the current `action=sources` answer is refused with | ||
| 30 | +`source_not_allowed` — the allowlist is the return value of the same walk the | ||
| 31 | +UI is given, so there is no second path to a file. | ||
| 32 | + | ||
| 33 | +Every walk has **its own** entry budget. `/workspace` being enormous cannot | ||
| 34 | +consume the allowance that `$HOME/.scorpiox` needs, and `action=sources` | ||
| 35 | +reports `truncated: true` instead of pretending the short list is complete. | ||
| 36 | +Symlinks are never followed. | ||
| 37 | + | ||
| 38 | +## What it never does | ||
| 39 | + | ||
| 40 | +* **No writes.** Files are opened `rb`. Nothing is rotated, truncated or created. | ||
| 41 | +* **No sockets.** No `curl`, no HTTP client, no listening socket. The plugin is | ||
| 42 | + a CGI-style executable; the node's server owns the socket. | ||
| 43 | +* **No user-controlled shell.** Only `journalctl` and `wevtutil` are invoked, | ||
| 44 | + from fixed `snprintf` format strings. A systemd unit name must pass | ||
| 45 | + `[A-Za-z0-9@._-]{1,128}` and may not start with `-`, so it can never become an | ||
| 46 | + option or a shell word. | ||
| 47 | +* **No whole-file reads.** A tail starts at most 4 MB before EOF and drops the | ||
| 48 | + first partial line; searches stop after 8 000 lines and 500 hits. | ||
| 49 | + | ||
| 50 | +## Build | ||
| 51 | + | ||
| 52 | +```sh | ||
| 53 | +make # native -> ./plugin_logs | ||
| 54 | +make musl # static musl x86_64 (the universal Linux artifact) | ||
| 55 | +make arm64 # static aarch64 (Pi 5 / ARM64 servers) | ||
| 56 | +make win64 # static PE via MinGW-w64 -> plugin_logs.exe | ||
| 57 | +make macos # Apple clang, run this on the Mac | ||
| 58 | +make test # build + offline checks | ||
| 59 | +``` | ||
| 60 | + | ||
| 61 | +On Windows, `build.ps1` wraps the MinGW build and verifies the `MZ` header. | ||
| 62 | + | ||
| 63 | +## Deploy | ||
| 64 | + | ||
| 65 | +Copy the binary into the node's plugin dir and it is live immediately — no | ||
| 66 | +server restart: | ||
| 67 | + | ||
| 68 | +```sh | ||
| 69 | +install -m 0755 plugin_logs ~/.scorpiox/plugins/plugin_logs | ||
| 70 | +``` | ||
| 71 | + | ||
| 72 | +The plugin appears in the Plugins list and is served at `/plugin_logs` | ||
| 73 | +(GET for the viewer, `?action=…` for JSON). One-click install from the market | ||
| 74 | +writes a `plugin_logs.manifest.json` sidecar with the source commit and the | ||
| 75 | +artifact SHA-256. | ||
| 76 | + | ||
| 77 | +## Node API | ||
| 78 | + | ||
| 79 | +All actions except `--meta` require the node password when `BOT_PASSWORD` is | ||
| 80 | +set — `X-Bot-Password`, `Authorization: Bearer <pwd>`, or `?pwd=` (what the | ||
| 81 | +plugin iframe appends). With no `BOT_PASSWORD` the plugin is a deliberate no-op | ||
| 82 | +so it can be run from a shell. | ||
| 83 | + | ||
| 84 | +``` | ||
| 85 | +?action=sources | ||
| 86 | +{ "ok":true, "journal_available":true, "count":5, "truncated":false, | ||
| 87 | + "sources":[ {"id":"journal","label":"System journal","kind":"journal","size":0,"mtime":0}, | ||
| 88 | + {"id":"file:/var/log/dpkg.log","label":"dpkg.log","kind":"file", | ||
| 89 | + "size":958818,"mtime":1773629060} ] } | ||
| 90 | + | ||
| 91 | +?action=tail&src=journal&lines=200 | ||
| 92 | +{ "ok":true, "src":"journal", "count":2, | ||
| 93 | + "entries":[ {"ts":"11-12 04:50:01","unit":"nginx.service","sev":"err", | ||
| 94 | + "text":"upstream timed out"} ] } | ||
| 95 | + | ||
| 96 | +?action=search&src=file:/var/log/dpkg.log&q=install | ||
| 97 | +{ "ok":true, "scanned":8000, "count":500, "max":500, "truncated":true, "hits":[ … ] } | ||
| 98 | + | ||
| 99 | +?action=units | ||
| 100 | +{ "ok":true, "available":true, "count":3, | ||
| 101 | + "units":[ {"name":"nginx.service","src":"journal:nginx.service"} ] } | ||
| 102 | +``` | ||
| 103 | + | ||
| 104 | +`sev` is `info`, `warn` or `err`. On Linux it comes from the journal | ||
| 105 | +`PRIORITY` field; everywhere it falls back to a keyword heuristic over the | ||
| 106 | +message text (`panic`, `fatal`, `error`, `failed`, `denied` → err; `warn`, | ||
| 107 | +`deprecated`, `timeout`, `retry` → warn). | ||
| 108 | + | ||
| 109 | +## UI | ||
| 110 | + | ||
| 111 | +* Source picker grouped by kind, with file sizes. | ||
| 112 | +* Line count 100 / 200 / 500 / 2000. | ||
| 113 | +* **Follow** polls every 3 s and pauses while the tab is hidden. | ||
| 114 | +* Search box with inline `<mark>` highlighting of every hit. | ||
| 115 | +* **Wrap** for long stack traces, **Copy** to copy the visible entries, | ||
| 116 | + **Reload** to re-walk the source list. | ||
| 117 | +* Severity colouring: left border and text tint for `err` / `warn`. | ||
| 118 | +* Dark and light from the shared SCORPIOX BOT theme tokens, so it matches the | ||
| 119 | + bot in a hub modal, a session card and the Chat floating window. `?theme=` | ||
| 120 | + decides before first paint; a `{type:'sx-theme'}` post from the host is | ||
| 121 | + followed without a reload. | ||
| 122 | +* Fluid at 1440 / 1024 / 390 px and inside the Chat floating window, no | ||
| 123 | + `<script src=>`, no CDN, no emoji (inline SVG only). | ||
| 124 | + | ||
| 125 | +## Tests | ||
| 126 | + | ||
| 127 | +```sh | ||
| 128 | +sh tests/run.sh # 153 offline assertions | ||
| 129 | +python3 tests/e2e.py # Playwright: 1440/1024/390 × dark/light + behaviour | ||
| 130 | +``` | ||
| 131 | + | ||
| 132 | +`tests/run.sh` replays a captured `journalctl -o json` stream and a fixture log | ||
| 133 | +tree, so the parsers are tested against the real output layouts without needing | ||
| 134 | +journald (or a growing log) on the build host: | ||
| 135 | + | ||
| 136 | +* `SX_LOGS_JOURNAL_FIXTURE` — a file replayed instead of running `journalctl`. | ||
| 137 | +* `SX_LOGS_EXTRA_ROOT` — one extra allowlisted root, so fixtures live outside | ||
| 138 | + the production paths. | ||
| 139 | + | ||
| 140 | +`tests/e2e.py` serves the plugin through a small CGI shim and asserts, at every | ||
| 141 | +viewport and in both themes: no console error, no horizontal overflow, the | ||
| 142 | +source picker is populated, a tail renders rows, severity classes are applied, | ||
| 143 | +search highlights hits, follow pauses the poller, the line-count segment | ||
| 144 | +switches, the theme button flips, and `?embed=1` drops only the back-link. | ||
| 145 | + | ||
| 146 | +## License | ||
| 147 | + | ||
| 148 | +MIT. Copyright (c) 2026 SCORPIOX INC. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..322c94e | index 0000000..322c94e | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/build.ps1 | +++ b/build.ps1 | ||
| @@ -0,0 +1,32 @@ | @@ -0,0 +1,32 @@ | ||
| 1 | +# build.ps1 - native Windows build of plugin_logs with MinGW-w64 or MSVC-style cl. | ||
| 2 | +# | ||
| 3 | +# .\build.ps1 # build plugin_logs.exe with gcc (MinGW-w64) | ||
| 4 | +# .\build.ps1 -Compiler cl # build with cl.exe | ||
| 5 | +# .\build.ps1 -Test # build then run the offline checks | ||
| 6 | +param( | ||
| 7 | + [string]$Compiler = "gcc", | ||
| 8 | + [switch]$Test | ||
| 9 | +) | ||
| 10 | + | ||
| 11 | +$ErrorActionPreference = "Stop" | ||
| 12 | +$src = "src\plugin_logs.c" | ||
| 13 | +$out = "plugin_logs.exe" | ||
| 14 | +$inc = "-Isrc" | ||
| 15 | + | ||
| 16 | +if ($Compiler -eq "cl") { | ||
| 17 | + Write-Host "==> MSVC build" | ||
| 18 | + & cl /nologo /O2 /W3 /I src /Fe:$out $src | ||
| 19 | +} else { | ||
| 20 | + Write-Host "==> MinGW-w64 build" | ||
| 21 | + & x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static $inc -o $out $src | ||
| 22 | +} | ||
| 23 | +if ($LASTEXITCODE -ne 0) { throw "build failed" } | ||
| 24 | + | ||
| 25 | +$head = [System.IO.File]::ReadAllBytes((Resolve-Path $out))[0..1] | ||
| 26 | +if ($head[0] -ne 0x4D -or $head[1] -ne 0x5A) { throw "artifact is not a PE image" } | ||
| 27 | +Write-Host ("==> built {0} ({1} bytes)" -f $out, (Get-Item $out).Length) | ||
| 28 | + | ||
| 29 | +& $out --meta | ||
| 30 | +if ($Test) { | ||
| 31 | + Write-Host "==> tests need a POSIX shell; run tests/run.sh under Git Bash or WSL" | ||
| 32 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..e1e1899 | index 0000000..e1e1899 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0b14ed9 | index 0000000..0b14ed9 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..6481a49 | index 0000000..6481a49 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..19c05a6 | index 0000000..19c05a6 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..7b33e27 | index 0000000..7b33e27 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..fcf7d78 | index 0000000..fcf7d78 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..03a5dc8 | index 0000000..03a5dc8 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/plugin.json | +++ b/plugin.json | ||
| @@ -0,0 +1,14 @@ | @@ -0,0 +1,14 @@ | ||
| 1 | +{ | ||
| 2 | + "slug": "logs", | ||
| 3 | + "id": "plugin_logs", | ||
| 4 | + "title": "Local Log Viewer", | ||
| 5 | + "summary": "Zero-dependency local log tail and search viewer for Linux, macOS and Windows nodes - reads an explicit allowlist of local log files plus the system journal, read-only, with no outbound network requests.", | ||
| 6 | + "category": "system", | ||
| 7 | + "license": "MIT", | ||
| 8 | + "capabilities": [ | ||
| 9 | + "local_log_read", | ||
| 10 | + "journal_read", | ||
| 11 | + "no_network" | ||
| 12 | + ], | ||
| 13 | + "trust_notice": "Executes native C code on your node. Reads only an allowlist of local log files and the local system journal in read-only mode; writes nothing and makes zero outbound network requests." | ||
| 14 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..1bdfb37 | index 0000000..1bdfb37 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/release-dist.sh | +++ b/release-dist.sh | ||
| @@ -0,0 +1,362 @@ | @@ -0,0 +1,362 @@ | ||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# release-dist.sh — build, scan and publish plugin_logs 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="logs" | ||
| 30 | +ID="plugin_logs" | ||
| 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 -I src -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 -I src -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 — Pi 5 / ARM64 servers) | ||
| 142 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | ||
| 143 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -I src -o "$STAGE/$ID.arm64" src/$ID.c \ | ||
| 144 | + || die "arm64 musl build failed" | ||
| 145 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | ||
| 146 | +else | ||
| 147 | + echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)" | ||
| 148 | +fi | ||
| 149 | + | ||
| 150 | +# windows-x86_64 (static PE) | ||
| 151 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | ||
| 152 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.exe" src/$ID.c \ | ||
| 153 | + || die "MinGW build failed" | ||
| 154 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | ||
| 155 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | ||
| 156 | +else | ||
| 157 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | ||
| 158 | +fi | ||
| 159 | + | ||
| 160 | +# macOS legs — Mach-O must be produced by Apple clang on a real Mac. | ||
| 161 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | ||
| 162 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | ||
| 163 | + MAC_USER="${MAC_USER:-$(whoami)}" | ||
| 164 | + MAC_DIR="/tmp/${ID}-mac-$$" | ||
| 165 | + echo " building macOS legs on $MAC_HOST" | ||
| 166 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | ||
| 167 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | ||
| 168 | + if [ -n "${MAC_PASS:-}" ]; then | ||
| 169 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | ||
| 170 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | ||
| 171 | + fi | ||
| 172 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | ||
| 173 | + if "${SCP_MAC[@]}" src/$ID.c "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.c"; then | ||
| 174 | + # Build straight from the uploaded file — no src/ tree on the remote. | ||
| 175 | + for slice in arm64 x86_64; do | ||
| 176 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | ||
| 177 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -arch $slice -o $ID.$slice $ID.c" \ | ||
| 178 | + 2>/dev/null; then | ||
| 179 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | ||
| 180 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | ||
| 181 | + else | ||
| 182 | + echo " warn: macos-$slice build failed on $MAC_HOST" | ||
| 183 | + fi | ||
| 184 | + done | ||
| 185 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" 2>/dev/null || true | ||
| 186 | + else | ||
| 187 | + echo " warn: mac scp failed" | ||
| 188 | + fi | ||
| 189 | + else | ||
| 190 | + echo " warn: mac host unreachable" | ||
| 191 | + fi | ||
| 192 | +else | ||
| 193 | + echo " skip macOS legs (set MAC_HOST/MAC_USER/MAC_PASS to include them)" | ||
| 194 | +fi | ||
| 195 | + | ||
| 196 | +# ---------------------------------------------------------------- 3. package | ||
| 197 | +say "3/7 package" | ||
| 198 | + | ||
| 199 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | ||
| 200 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | ||
| 201 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | ||
| 202 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | ||
| 203 | + | ||
| 204 | +target_meta() { # target_meta <key> <file> <format> <relpath> <name> | ||
| 205 | + local key="$1" file="$2" fmt="$3" rel="$4" name="$5" | ||
| 206 | + [ -f "$file" ] || return 0 | ||
| 207 | + local sha size | ||
| 208 | + sha=$(sha256sum "$file" | awk '{print $1}') | ||
| 209 | + size=$(wc -c < "$file" | tr -d ' ') | ||
| 210 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | ||
| 211 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +{ | ||
| 215 | + printf '{\n' | ||
| 216 | + printf ' "slug": "%s",\n' "$SLUG" | ||
| 217 | + printf ' "id": "%s",\n' "$ID" | ||
| 218 | + printf ' "name": "logs",\n' | ||
| 219 | + printf ' "desc": "Log viewer",\n' | ||
| 220 | + printf ' "title": "Local Log Viewer",\n' | ||
| 221 | + printf ' "summary": "Zero-dependency local log tail and search viewer for Linux, macOS and Windows nodes - reads an explicit allowlist of local log files plus the system journal, read-only, with no outbound network requests.",\n' | ||
| 222 | + printf ' "category": "system",\n' | ||
| 223 | + printf ' "version": "%s",\n' "$VERSION" | ||
| 224 | + printf ' "license": "MIT",\n' | ||
| 225 | + printf ' "trust_notice": "Executes native C code on your node. Reads only an allowlist of local log files and the local system journal in read-only mode; writes nothing and makes zero outbound network requests.",\n' | ||
| 226 | + printf ' "capabilities": ["local_log_read", "journal_read", "no_network"],\n' | ||
| 227 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | ||
| 228 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | ||
| 229 | + printf ' "git_commit": "%s",\n' "$COMMIT" | ||
| 230 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 231 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | ||
| 232 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -I src -o %s src/%s.c",\n' "$ID" "$ID" | ||
| 233 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -I src -o %s.exe src/%s.c",\n' "$ID" "$ID" | ||
| 234 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | ||
| 235 | + printf ' "targets": {\n' | ||
| 236 | + first=1 | ||
| 237 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | ||
| 238 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" "$ID" | ||
| 239 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" "$ID" | ||
| 240 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" "$ID" | ||
| 241 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" "$ID" | ||
| 242 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" "$ID" | ||
| 243 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" "$ID" | ||
| 244 | + printf '\n }\n}\n' | ||
| 245 | +} > "$STAGE/manifest.json" | ||
| 246 | + | ||
| 247 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | ||
| 248 | + || die "generated manifest.json is not valid JSON" | ||
| 249 | +echo " manifest.json ok" | ||
| 250 | + | ||
| 251 | +# SHA256SUMS — relative paths, exactly as published | ||
| 252 | +( cd "$STAGE" | ||
| 253 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | ||
| 254 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | ||
| 255 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | ||
| 256 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | ||
| 257 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | ||
| 258 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | ||
| 259 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | ||
| 260 | + true ) > "$STAGE/SHA256SUMS" | ||
| 261 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | ||
| 262 | + | ||
| 263 | +# ---------------------------------------------------------------- 4. stage | ||
| 264 | +say "4/7 stage tree" | ||
| 265 | +PKG="$STAGE/pkg" | ||
| 266 | +mkdir -p "$PKG/linux-x86_64" "$PKG/linux-x86_64-musl" "$PKG/linux-arm64-musl" \ | ||
| 267 | + "$PKG/macos-arm64" "$PKG/macos-x86_64" "$PKG/windows-x86_64" | ||
| 268 | +cp -f "$STAGE/$ID" "$PKG/linux-x86_64/$ID" | ||
| 269 | +[ -f "$STAGE/$ID.musl" ] && cp -f "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID" | ||
| 270 | +[ -f "$STAGE/$ID.arm64" ] && cp -f "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID" | ||
| 271 | +[ -f "$STAGE/$ID.macos-arm64" ]&& cp -f "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID" | ||
| 272 | +[ -f "$STAGE/$ID.macos-x86_64" ]&&cp -f "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID" | ||
| 273 | +[ -f "$STAGE/$ID.exe" ] && cp -f "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe" | ||
| 274 | +cp -f "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | ||
| 275 | +chmod +x "$PKG"/*/$ID 2>/dev/null || true | ||
| 276 | +find "$PKG" -type f | sed 's/^/ /' | ||
| 277 | + | ||
| 278 | +if [ "$DRY_RUN" -eq 1 ]; then | ||
| 279 | + say "dry run — staged at $STAGE/pkg (kept for inspection)" | ||
| 280 | + trap - EXIT | ||
| 281 | + exit 0 | ||
| 282 | +fi | ||
| 283 | + | ||
| 284 | +# ---------------------------------------------------------------- 5. upload | ||
| 285 | +say "5/7 upload" | ||
| 286 | + | ||
| 287 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set — cannot upload" | ||
| 288 | +SSH=(ssh -o StrictHostKeyChecking=no) | ||
| 289 | +SCP=(scp -o StrictHostKeyChecking=no) | ||
| 290 | +if [ -n "$DIST_PASS" ]; then | ||
| 291 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | ||
| 292 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | ||
| 293 | +fi | ||
| 294 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | ||
| 295 | + | ||
| 296 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | ||
| 297 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | ||
| 298 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | ||
| 299 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | ||
| 300 | +# OpenSSH 9 refuses to scp a bare "." source. | ||
| 301 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | ||
| 302 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | ||
| 303 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | ||
| 304 | + || die "remote extract failed" | ||
| 305 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | ||
| 306 | + | ||
| 307 | +# latest.json = copy of this version's manifest | ||
| 308 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | ||
| 309 | + || die "latest.json update failed" | ||
| 310 | +echo " updated bot-plugins/$SLUG/latest.json" | ||
| 311 | + | ||
| 312 | +# index.json — merge, preserving every sibling <slug>/latest.json | ||
| 313 | +say "index.json merge" | ||
| 314 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | ||
| 315 | +import json, os, sys, glob | ||
| 316 | +slug = sys.argv[1] | ||
| 317 | +entries = {} | ||
| 318 | +for p in sorted(glob.glob('*/latest.json')): | ||
| 319 | + s = os.path.dirname(p) | ||
| 320 | + try: | ||
| 321 | + entries[s] = json.load(open(p)) | ||
| 322 | + except Exception: | ||
| 323 | + pass | ||
| 324 | +index = { | ||
| 325 | + 'ok': True, | ||
| 326 | + 'service': 'bot-plugins-dist', | ||
| 327 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | ||
| 328 | + 'count': len(entries), | ||
| 329 | + 'slugs': sorted(entries), | ||
| 330 | + 'plugins': [entries[k] for k in sorted(entries)], | ||
| 331 | +} | ||
| 332 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | ||
| 333 | +os.replace('index.json.tmp', 'index.json') | ||
| 334 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | ||
| 335 | +PY" || die "index.json merge failed" | ||
| 336 | + | ||
| 337 | +# ---------------------------------------------------------------- 6. mirror | ||
| 338 | +say "6/7 plugingit mirror" | ||
| 339 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | ||
| 340 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | ||
| 341 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://x-access-token:${TOKEN}@|") | ||
| 342 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | ||
| 343 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | ||
| 344 | + echo " mirrored to $PLUGINGIT_REMOTE" | ||
| 345 | +else | ||
| 346 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | ||
| 347 | +fi | ||
| 348 | + | ||
| 349 | +# ---------------------------------------------------------------- 7. verify | ||
| 350 | +say "7/7 verify" | ||
| 351 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | ||
| 352 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | ||
| 353 | +if [ "$CODE" = "200" ]; then | ||
| 354 | + 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"])))' \ | ||
| 355 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | ||
| 356 | +else | ||
| 357 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | ||
| 358 | +fi | ||
| 359 | + | ||
| 360 | +printf '\n\033[1mrelease complete\033[0m\n' | ||
| 361 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 362 | +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..0dd243b | index 0000000..0dd243b | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | @@ -0,0 +1,129 @@ | ||
| 1 | +/* | ||
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | ||
| 3 | + * | ||
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | ||
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | ||
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | ||
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | ||
| 8 | + * localStorage key, same prepaint order. | ||
| 9 | + * | ||
| 10 | + * Three rules, and nothing else: | ||
| 11 | + * | ||
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | ||
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | ||
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | ||
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | ||
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | ||
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | ||
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | ||
| 19 | + * it was already open when the bot changed theme. | ||
| 20 | + * | ||
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | ||
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | ||
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | ||
| 24 | + * are var() references, one definition covers both themes. | ||
| 25 | + * | ||
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 27 | + */ | ||
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | ||
| 29 | +#define SX_BOT_THEME_PLUGIN_H | ||
| 30 | + | ||
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | ||
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | ||
| 33 | +#define SX_BOT_THEME_TOKENS \ | ||
| 34 | +":root{color-scheme:dark;" \ | ||
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | ||
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | ||
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | ||
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | ||
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | ||
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | ||
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | ||
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | ||
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | ||
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | ||
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | ||
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | ||
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | ||
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | ||
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | ||
| 50 | +"}" \ | ||
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | ||
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 58 | + "--accent-dim:#0066d6;" \ | ||
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 62 | + "color-scheme:light}}" \ | ||
| 63 | +"html[data-theme=light]{" \ | ||
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 70 | + "--accent-dim:#0066d6;" \ | ||
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 74 | + "color-scheme:light}" \ | ||
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | ||
| 76 | +"*{box-sizing:border-box}" \ | ||
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | ||
| 78 | + "-webkit-font-smoothing:antialiased}" \ | ||
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | ||
| 80 | +"button:active{transform:scale(.98)}" \ | ||
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | ||
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | ||
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | ||
| 84 | +" * hides its own back link and its own toggle. */" \ | ||
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | ||
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | ||
| 87 | + | ||
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | ||
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | ||
| 90 | + * html.embedded so the embed rules apply before first paint. */ | ||
| 91 | +#define SX_BOT_THEME_PREPAINT \ | ||
| 92 | +"<script>(function(){var t='';" \ | ||
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | ||
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | ||
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | ||
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | ||
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 99 | +"})();</script>\n" | ||
| 100 | + | ||
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | ||
| 102 | + * at startup in case it changed while this page was already open. Fires the | ||
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | ||
| 104 | + * re-skin themselves from one listener. */ | ||
| 105 | +#define SX_BOT_THEME_HANDOFF \ | ||
| 106 | +"<script>(function(){" \ | ||
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | ||
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | ||
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | ||
| 112 | +"window.sxApplyTheme=apply;" \ | ||
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | ||
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | ||
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | ||
| 116 | +"})();</script>\n" | ||
| 117 | + | ||
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | ||
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | ||
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | ||
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | ||
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | ||
| 123 | + | ||
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | ||
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | ||
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | ||
| 127 | +"})();</script>\n" | ||
| 128 | + | ||
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..659a399 | index 0000000..659a399 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_logs.c | +++ b/src/plugin_logs.c | ||
| @@ -0,0 +1,1874 @@ | @@ -0,0 +1,1874 @@ | ||
| 1 | +/* | ||
| 2 | + * plugin_logs - SCORPIOX BOT open-source local log viewer 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=sources|tail|search|units -> JSON node API | ||
| 7 | + * 3. GET (default) -> responsive HTML log tail & search UI | ||
| 8 | + * | ||
| 9 | + * Local node only. Reads an explicit allowlist of local log files (a bounded | ||
| 10 | + * walk of /var/log, $HOME/.scorpiox, /workspace, ~/Library/Logs and | ||
| 11 | + * %LOCALAPPDATA%\scorpiox) and the local system journal through a fixed argv | ||
| 12 | + * with no user-controlled shell text. Makes ZERO outbound network requests, | ||
| 13 | + * opens no sockets, reads no credentials. | ||
| 14 | + * | ||
| 15 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | ||
| 16 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | ||
| 17 | + * scorpiox-server on the node. | ||
| 18 | + * | ||
| 19 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 20 | + */ | ||
| 21 | + | ||
| 22 | +/* MinGW defaults to a Server 2003 target; the Win7+ APIs used below would be | ||
| 23 | + * hidden by that gate. This must precede every include. */ | ||
| 24 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | ||
| 25 | +# define _WIN32_WINNT 0x0601 | ||
| 26 | +#endif | ||
| 27 | + | ||
| 28 | +#if defined(__APPLE__) | ||
| 29 | + /* sys/types.h pulls BSD types (u_int) that strict c99 would hide */ | ||
| 30 | +# define _DARWIN_C_SOURCE 1 | ||
| 31 | +#elif !defined(_WIN32) | ||
| 32 | +# define _POSIX_C_SOURCE 200809L | ||
| 33 | +# define _DEFAULT_SOURCE 1 | ||
| 34 | +#endif | ||
| 35 | + | ||
| 36 | +#include <stdio.h> | ||
| 37 | +#include <stdlib.h> | ||
| 38 | +#include <string.h> | ||
| 39 | +#include <time.h> | ||
| 40 | +#include <ctype.h> | ||
| 41 | +#include <errno.h> | ||
| 42 | + | ||
| 43 | +#if defined(_WIN32) | ||
| 44 | + | ||
| 45 | +# define WIN32_LEAN_AND_MEAN | ||
| 46 | +# include <windows.h> | ||
| 47 | +# include <io.h> | ||
| 48 | + | ||
| 49 | +#else | ||
| 50 | + | ||
| 51 | +# include <unistd.h> | ||
| 52 | +# include <dirent.h> | ||
| 53 | +# include <sys/types.h> | ||
| 54 | +# include <sys/stat.h> | ||
| 55 | + | ||
| 56 | +#endif | ||
| 57 | + | ||
| 58 | +#include "bot_theme_plugin.h" | ||
| 59 | + | ||
| 60 | +#define PLUGIN_SLUG "logs" | ||
| 61 | +#define PLUGIN_ID "plugin_logs" | ||
| 62 | +#define PLUGIN_VER "1.0.0" | ||
| 63 | + | ||
| 64 | +#define MAX_SRC 256 | ||
| 65 | +#define MAX_UNITS 512 | ||
| 66 | +#define ENTRY_TEXT 1024 | ||
| 67 | +#define ENTRY_UNIT 96 | ||
| 68 | +#define ENTRY_TS 40 | ||
| 69 | +#define TAIL_MAX 2000 | ||
| 70 | +#define SEARCH_HITS_MAX 500 | ||
| 71 | +#define SEARCH_SCAN 8000 | ||
| 72 | +#define FILE_TAIL_BYTES (4L * 1024L * 1024L) | ||
| 73 | +#define ROOT_BUDGET 40000 | ||
| 74 | + | ||
| 75 | +/* Severity buckets: 0 info, 1 warn, 2 err */ | ||
| 76 | +#define SEV_INFO 0 | ||
| 77 | +#define SEV_WARN 1 | ||
| 78 | +#define SEV_ERR 2 | ||
| 79 | + | ||
| 80 | +/* ------------------------------------------------------------------ */ | ||
| 81 | +/* Small utilities */ | ||
| 82 | +/* ------------------------------------------------------------------ */ | ||
| 83 | + | ||
| 84 | +static void url_decode(char *s) | ||
| 85 | +{ | ||
| 86 | + char *o = s; | ||
| 87 | + if (!s) return; | ||
| 88 | + while (*s) { | ||
| 89 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | ||
| 90 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | ||
| 91 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | ||
| 92 | + *o++ = (char)((hi << 4) | lo); | ||
| 93 | + s += 3; | ||
| 94 | + } else if (*s == '+') { | ||
| 95 | + *o++ = ' '; | ||
| 96 | + s++; | ||
| 97 | + } else { | ||
| 98 | + *o++ = *s++; | ||
| 99 | + } | ||
| 100 | + } | ||
| 101 | + *o = '\0'; | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +/* Copy one query parameter into out. Returns 1 when present. */ | ||
| 105 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 106 | +{ | ||
| 107 | + size_t klen = strlen(key); | ||
| 108 | + const char *p = qs; | ||
| 109 | + | ||
| 110 | + if (outsz) out[0] = '\0'; | ||
| 111 | + if (!qs || !klen) return 0; | ||
| 112 | + | ||
| 113 | + while (p && *p) { | ||
| 114 | + const char *amp = strchr(p, '&'); | ||
| 115 | + const char *end = amp ? amp : p + strlen(p); | ||
| 116 | + const char *eq = memchr(p, '=', (size_t)(end - p)); | ||
| 117 | + | ||
| 118 | + if (eq && (size_t)(eq - p) == klen && strncmp(p, key, klen) == 0) { | ||
| 119 | + size_t vlen = (size_t)(end - eq - 1); | ||
| 120 | + if (vlen >= outsz) vlen = outsz ? outsz - 1 : 0; | ||
| 121 | + if (vlen) memcpy(out, eq + 1, vlen); | ||
| 122 | + out[vlen] = '\0'; | ||
| 123 | + url_decode(out); | ||
| 124 | + return 1; | ||
| 125 | + } | ||
| 126 | + p = amp ? amp + 1 : NULL; | ||
| 127 | + } | ||
| 128 | + return 0; | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +static void json_str(const char *s) | ||
| 132 | +{ | ||
| 133 | + const unsigned char *p = (const unsigned char *)s; | ||
| 134 | + fputc('"', stdout); | ||
| 135 | + if (p) { | ||
| 136 | + for (; *p; p++) { | ||
| 137 | + switch (*p) { | ||
| 138 | + case '"': fputs("\\\"", stdout); break; | ||
| 139 | + case '\\': fputs("\\\\", stdout); break; | ||
| 140 | + case '\n': fputs("\\n", stdout); break; | ||
| 141 | + case '\r': fputs("\\r", stdout); break; | ||
| 142 | + case '\t': fputs("\\t", stdout); break; | ||
| 143 | + default: | ||
| 144 | + if (*p < 0x20) printf("\\u%04x", *p); | ||
| 145 | + else fputc((int)*p, stdout); | ||
| 146 | + } | ||
| 147 | + } | ||
| 148 | + } | ||
| 149 | + fputc('"', stdout); | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +static void utc_now(char *buf, size_t sz) | ||
| 153 | +{ | ||
| 154 | + time_t t = time(NULL); | ||
| 155 | + struct tm tmv; | ||
| 156 | +#if defined(_WIN32) | ||
| 157 | + struct tm *lt = localtime(&t); | ||
| 158 | + if (lt) tmv = *lt; | ||
| 159 | +#else | ||
| 160 | + localtime_r(&t, &tmv); | ||
| 161 | +#endif | ||
| 162 | +#if defined(_WIN32) | ||
| 163 | + { | ||
| 164 | + struct tm *gp = gmtime(&t); | ||
| 165 | + if (gp) tmv = *gp; | ||
| 166 | + } | ||
| 167 | +#endif | ||
| 168 | + strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); | ||
| 169 | +} | ||
| 170 | + | ||
| 171 | +/* Copy into out, trimming leading/trailing whitespace and CR/LF. */ | ||
| 172 | +static void trim_into(char *out, size_t osz, const char *src, size_t n) | ||
| 173 | +{ | ||
| 174 | + size_t i = 0, k; | ||
| 175 | + if (!osz) return; | ||
| 176 | + while (i < n && (src[i] == ' ' || src[i] == '\t' || src[i] == '\r' || src[i] == '\n')) i++; | ||
| 177 | + while (n > i && (src[n - 1] == ' ' || src[n - 1] == '\t' || | ||
| 178 | + src[n - 1] == '\r' || src[n - 1] == '\n')) n--; | ||
| 179 | + k = n - i; | ||
| 180 | + if (k >= osz) k = osz - 1; | ||
| 181 | + /* callers trim a buffer in place, so the move may overlap */ | ||
| 182 | + if (k) memmove(out, src + i, k); | ||
| 183 | + out[k] = '\0'; | ||
| 184 | +} | ||
| 185 | + | ||
| 186 | +static int ci_contains(const char *hay, const char *needle) | ||
| 187 | +{ | ||
| 188 | + size_t nl; | ||
| 189 | + if (!hay || !needle || !*needle) return 1; | ||
| 190 | + nl = strlen(needle); | ||
| 191 | + for (; *hay; hay++) { | ||
| 192 | + size_t i = 0; | ||
| 193 | + while (i < nl && hay[i] && | ||
| 194 | + tolower((unsigned char)hay[i]) == tolower((unsigned char)needle[i])) i++; | ||
| 195 | + if (i == nl) return 1; | ||
| 196 | + } | ||
| 197 | + return 0; | ||
| 198 | +} | ||
| 199 | + | ||
| 200 | +/* Case-insensitive substring test used for severity heuristics. */ | ||
| 201 | +static int has_word(const char *s, const char *w) | ||
| 202 | +{ | ||
| 203 | + return ci_contains(s, w); | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +static int severity_of(const char *text, const char *level) | ||
| 207 | +{ | ||
| 208 | + if (level && *level) { | ||
| 209 | + if (has_word(level, "err") || has_word(level, "crit") || | ||
| 210 | + has_word(level, "alert") || has_word(level, "emerg")) | ||
| 211 | + return SEV_ERR; | ||
| 212 | + if (has_word(level, "warn")) return SEV_WARN; | ||
| 213 | + } | ||
| 214 | + if (!text) return SEV_INFO; | ||
| 215 | + if (has_word(text, "panic") || has_word(text, "fatal") || | ||
| 216 | + has_word(text, "critical") || has_word(text, "segfault") || | ||
| 217 | + has_word(text, "traceback") || has_word(text, "error") || | ||
| 218 | + has_word(text, "err:") || has_word(text, "failed") || | ||
| 219 | + has_word(text, "failure") || has_word(text, "denied")) | ||
| 220 | + return SEV_ERR; | ||
| 221 | + if (has_word(text, "warn") || has_word(text, "deprecated") || | ||
| 222 | + has_word(text, "timeout") || has_word(text, "retry")) | ||
| 223 | + return SEV_WARN; | ||
| 224 | + return SEV_INFO; | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +static const char *sev_name(int sev) | ||
| 228 | +{ | ||
| 229 | + return sev == SEV_ERR ? "err" : sev == SEV_WARN ? "warn" : "info"; | ||
| 230 | +} | ||
| 231 | + | ||
| 232 | +/* ------------------------------------------------------------------ */ | ||
| 233 | +/* Node authentication */ | ||
| 234 | +/* ------------------------------------------------------------------ */ | ||
| 235 | + | ||
| 236 | +/* | ||
| 237 | + * The node API on the node's api port is reachable from the LAN. Every request | ||
| 238 | + * except --meta discovery must prove it knows the node password. Accepted | ||
| 239 | + * forms match the rest of the node API: X-Bot-Password (what the web front | ||
| 240 | + * proxies with), Authorization: Bearer, and ?pwd= (what the plugin iframe | ||
| 241 | + * appends). When BOT_PASSWORD is unset the plugin is a deliberate no-op, which | ||
| 242 | + * is how a developer runs it locally from a shell. | ||
| 243 | + */ | ||
| 244 | +static void require_node_auth(void) | ||
| 245 | +{ | ||
| 246 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 247 | + const char *xp; | ||
| 248 | + const char *auth; | ||
| 249 | + char qpwd[256]; | ||
| 250 | + const char *qs; | ||
| 251 | + | ||
| 252 | + if (!np || !*np) return; | ||
| 253 | + | ||
| 254 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | ||
| 255 | + if (xp && strcmp(xp, np) == 0) return; | ||
| 256 | + | ||
| 257 | + auth = getenv("HTTP_AUTHORIZATION"); | ||
| 258 | + if (auth) { | ||
| 259 | + while (*auth == ' ') auth++; | ||
| 260 | + if (strncmp(auth, "Bearer ", 7) == 0) { | ||
| 261 | + auth += 7; | ||
| 262 | + while (*auth == ' ') auth++; | ||
| 263 | + if (strcmp(auth, np) == 0) return; | ||
| 264 | + } | ||
| 265 | + } | ||
| 266 | + | ||
| 267 | + qs = getenv("QUERY_STRING"); | ||
| 268 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | ||
| 269 | + return; | ||
| 270 | + | ||
| 271 | + fputs("Status: 401 Unauthorized\r\n" | ||
| 272 | + "Content-Type: application/json; charset=utf-8\r\n" | ||
| 273 | + "Cache-Control: no-store\r\n" | ||
| 274 | + "X-Content-Type-Options: nosniff\r\n\r\n" | ||
| 275 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | ||
| 276 | + exit(0); | ||
| 277 | +} | ||
| 278 | + | ||
| 279 | +/* ------------------------------------------------------------------ */ | ||
| 280 | +/* Source registry */ | ||
| 281 | +/* ------------------------------------------------------------------ */ | ||
| 282 | + | ||
| 283 | +typedef struct { | ||
| 284 | + char id[600]; /* journal | journal:<unit> | file:<path> | event:<log> */ | ||
| 285 | + char label[96]; | ||
| 286 | + char kind[10]; /* journal | file | event */ | ||
| 287 | + long long size; | ||
| 288 | + long mtime; | ||
| 289 | +} src_t; | ||
| 290 | + | ||
| 291 | +typedef struct { | ||
| 292 | + int journal_avail; | ||
| 293 | + src_t items[MAX_SRC]; | ||
| 294 | + int n; | ||
| 295 | + int truncated; | ||
| 296 | +} srcs_t; | ||
| 297 | + | ||
| 298 | +static void add_src(srcs_t *o, const char *id, const char *label, | ||
| 299 | + const char *kind, long long size, long mtime) | ||
| 300 | +{ | ||
| 301 | + int i; | ||
| 302 | + if (o->n >= MAX_SRC) { o->truncated = 1; return; } | ||
| 303 | + for (i = 0; i < o->n; i++) | ||
| 304 | + if (strcmp(o->items[i].id, id) == 0) return; | ||
| 305 | + snprintf(o->items[o->n].id, sizeof(o->items[0].id), "%s", id); | ||
| 306 | + snprintf(o->items[o->n].label, sizeof(o->items[0].label), "%s", label); | ||
| 307 | + snprintf(o->items[o->n].kind, sizeof(o->items[0].kind), "%s", kind); | ||
| 308 | + o->items[o->n].size = size; | ||
| 309 | + o->items[o->n].mtime = mtime; | ||
| 310 | + o->n++; | ||
| 311 | +} | ||
| 312 | + | ||
| 313 | +static const char *base_name(const char *path) | ||
| 314 | +{ | ||
| 315 | + const char *s = path; | ||
| 316 | + const char *b = path; | ||
| 317 | + for (; *s; s++) | ||
| 318 | + if (*s == '/' || *s == '\\') b = s + 1; | ||
| 319 | + return b; | ||
| 320 | +} | ||
| 321 | + | ||
| 322 | +#if !defined(_WIN32) | ||
| 323 | + | ||
| 324 | +static int has_log_suffix(const char *name) | ||
| 325 | +{ | ||
| 326 | + size_t l = strlen(name); | ||
| 327 | + return l > 4 && strcmp(name + l - 4, ".log") == 0; | ||
| 328 | +} | ||
| 329 | + | ||
| 330 | +static void add_file_src(srcs_t *o, const char *path) | ||
| 331 | +{ | ||
| 332 | + struct stat st; | ||
| 333 | + char id[600]; | ||
| 334 | + if (o->n >= MAX_SRC) { o->truncated = 1; return; } | ||
| 335 | + if (stat(path, &st) != 0) return; | ||
| 336 | + if (!S_ISREG(st.st_mode)) return; | ||
| 337 | + if (st.st_size <= 0) return; | ||
| 338 | + if (strlen(path) + 6 >= sizeof(id)) return; | ||
| 339 | + snprintf(id, sizeof(id), "file:%s", path); | ||
| 340 | + add_src(o, id, base_name(path), "file", (long long)st.st_size, (long)st.st_mtime); | ||
| 341 | +} | ||
| 342 | + | ||
| 343 | +/* | ||
| 344 | + * Bounded walk of one allowlisted root. Each root carries its own entry | ||
| 345 | + * budget so a large /workspace can never consume the allowance that | ||
| 346 | + * $HOME/.scorpiox needs. Symlinks are never followed. | ||
| 347 | + */ | ||
| 348 | +static void scan_root(srcs_t *o, const char *dir, int depth, int *budget, int log_only) | ||
| 349 | +{ | ||
| 350 | + DIR *d; | ||
| 351 | + struct dirent *e; | ||
| 352 | + char p[1024]; | ||
| 353 | + | ||
| 354 | + if (depth < 0 || *budget <= 0 || !dir || !*dir) return; | ||
| 355 | + d = opendir(dir); | ||
| 356 | + if (!d) return; | ||
| 357 | + | ||
| 358 | + while ((e = readdir(d)) != NULL) { | ||
| 359 | + struct stat st; | ||
| 360 | + if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0) continue; | ||
| 361 | + if (--(*budget) <= 0) { o->truncated = 1; break; } | ||
| 362 | + if (strlen(dir) + strlen(e->d_name) + 2 >= sizeof(p)) continue; | ||
| 363 | + snprintf(p, sizeof(p), "%s/%s", dir, e->d_name); | ||
| 364 | + if (lstat(p, &st) != 0) continue; | ||
| 365 | + if (S_ISLNK(st.st_mode)) continue; | ||
| 366 | + if (S_ISDIR(st.st_mode)) { | ||
| 367 | + if (depth > 0) scan_root(o, p, depth - 1, budget, log_only); | ||
| 368 | + } else if (S_ISREG(st.st_mode)) { | ||
| 369 | + if (!log_only || has_log_suffix(e->d_name)) add_file_src(o, p); | ||
| 370 | + } | ||
| 371 | + } | ||
| 372 | + closedir(d); | ||
| 373 | +} | ||
| 374 | + | ||
| 375 | +/* | ||
| 376 | + * "journalctl exists" is not the same as "this node has a journal". Debian | ||
| 377 | + * slim containers ship the binary with no journald running underneath, so the | ||
| 378 | + * UI would offer a source that silently returns nothing. Require the binary | ||
| 379 | + * AND one of the two journal directories systemd actually writes. | ||
| 380 | + */ | ||
| 381 | +static int journal_available(void) | ||
| 382 | +{ | ||
| 383 | + static const char *bins[] = { | ||
| 384 | + "/usr/bin/journalctl", "/bin/journalctl", | ||
| 385 | + "/usr/local/bin/journalctl", "/usr/sbin/journalctl", NULL | ||
| 386 | + }; | ||
| 387 | + static const char *dirs[] = { | ||
| 388 | + "/run/systemd/journal", "/run/log/journal", "/var/log/journal", NULL | ||
| 389 | + }; | ||
| 390 | + int i, have_bin = 0, have_dir = 0; | ||
| 391 | + | ||
| 392 | + for (i = 0; bins[i]; i++) | ||
| 393 | + if (access(bins[i], X_OK) == 0) { have_bin = 1; break; } | ||
| 394 | + if (!have_bin) return 0; | ||
| 395 | + for (i = 0; dirs[i]; i++) | ||
| 396 | + if (access(dirs[i], F_OK) == 0) { have_dir = 1; break; } | ||
| 397 | + return have_dir; | ||
| 398 | +} | ||
| 399 | + | ||
| 400 | +static void scan_sources(srcs_t *o) | ||
| 401 | +{ | ||
| 402 | + int budget; | ||
| 403 | + char home[512]; | ||
| 404 | + char p[1024]; | ||
| 405 | + | ||
| 406 | + memset(o, 0, sizeof(*o)); | ||
| 407 | + | ||
| 408 | +#if defined(_WIN32) | ||
| 409 | + o->journal_avail = 0; /* Windows exposes the event log instead */ | ||
| 410 | +#else | ||
| 411 | + o->journal_avail = journal_available(); | ||
| 412 | +# if defined(__APPLE__) | ||
| 413 | + /* `log` is part of the base system and needs no daemon probe */ | ||
| 414 | + o->journal_avail = 1; | ||
| 415 | +# endif | ||
| 416 | +#endif | ||
| 417 | + | ||
| 418 | + if (o->journal_avail) | ||
| 419 | + add_src(o, "journal", | ||
| 420 | +# if defined(__APPLE__) | ||
| 421 | + "Unified log", | ||
| 422 | +# else | ||
| 423 | + "System journal", | ||
| 424 | +# endif | ||
| 425 | + "journal", 0LL, 0L); | ||
| 426 | + | ||
| 427 | +#if defined(__APPLE__) | ||
| 428 | + /* the per-file *.log scan plus the classic system.log */ | ||
| 429 | + budget = 8000; | ||
| 430 | + scan_root(o, "/var/log", 0, &budget, 1); | ||
| 431 | + add_file_src(o, "/var/log/system.log"); | ||
| 432 | + | ||
| 433 | + home[0] = '\0'; | ||
| 434 | + if (getenv("HOME")) snprintf(home, sizeof(home), "%s", getenv("HOME")); | ||
| 435 | + if (home[0]) { | ||
| 436 | + snprintf(p, sizeof(p), "%s/Library/Logs", home); | ||
| 437 | + budget = 8000; | ||
| 438 | + scan_root(o, p, 3, &budget, 1); | ||
| 439 | + } | ||
| 440 | +#else | ||
| 441 | + /* the per-file *.log scan plus the distro-specific aggregate files */ | ||
| 442 | + budget = 12000; | ||
| 443 | + scan_root(o, "/var/log", 0, &budget, 1); | ||
| 444 | + add_file_src(o, "/var/log/syslog"); | ||
| 445 | + add_file_src(o, "/var/log/messages"); | ||
| 446 | + add_file_src(o, "/var/log/kern.log"); | ||
| 447 | + add_file_src(o, "/var/log/auth.log"); | ||
| 448 | + | ||
| 449 | + home[0] = '\0'; | ||
| 450 | + if (getenv("HOME")) snprintf(home, sizeof(home), "%s", getenv("HOME")); | ||
| 451 | + if (home[0]) { | ||
| 452 | + snprintf(p, sizeof(p), "%s/.scorpiox", home); | ||
| 453 | + budget = ROOT_BUDGET; | ||
| 454 | + scan_root(o, p, 4, &budget, 1); | ||
| 455 | + } | ||
| 456 | + budget = ROOT_BUDGET; | ||
| 457 | + scan_root(o, "/workspace", 4, &budget, 1); | ||
| 458 | +#endif | ||
| 459 | + | ||
| 460 | + /* | ||
| 461 | + * Test-only knob: one extra allowlisted root so tests/run.sh can point the | ||
| 462 | + * plugin at fixture logs without inventing a path that production would | ||
| 463 | + * never serve. Only the operator who starts the process can set it. | ||
| 464 | + */ | ||
| 465 | + { | ||
| 466 | + const char *extra = getenv("SX_LOGS_EXTRA_ROOT"); | ||
| 467 | + if (extra && *extra) { | ||
| 468 | + budget = 4000; | ||
| 469 | + scan_root(o, extra, 2, &budget, 1); | ||
| 470 | + } | ||
| 471 | + } | ||
| 472 | +} | ||
| 473 | + | ||
| 474 | +#else /* _WIN32 */ | ||
| 475 | + | ||
| 476 | +static int has_log_suffix(const char *name) | ||
| 477 | +{ | ||
| 478 | + size_t l = strlen(name); | ||
| 479 | + return l > 4 && strcmp(name + l - 4, ".log") == 0; | ||
| 480 | +} | ||
| 481 | + | ||
| 482 | +static void add_file_src(srcs_t *o, const char *path) | ||
| 483 | +{ | ||
| 484 | + DWORD a = GetFileAttributesA(path); | ||
| 485 | + WIN32_FILE_ATTRIBUTE_DATA fad; | ||
| 486 | + char id[600]; | ||
| 487 | + if (o->n >= MAX_SRC) { o->truncated = 1; return; } | ||
| 488 | + if (a == INVALID_FILE_ATTRIBUTES) return; | ||
| 489 | + if (a & FILE_ATTRIBUTE_DIRECTORY) return; | ||
| 490 | + if (strlen(path) + 6 >= sizeof(id)) return; | ||
| 491 | + if (!GetFileAttributesExA(path, GetFileExInfoStandard, &fad)) return; | ||
| 492 | + snprintf(id, sizeof(id), "file:%s", path); | ||
| 493 | + add_src(o, id, base_name(path), "file", | ||
| 494 | + (long long)fad.nFileSizeLow, 0L); | ||
| 495 | +} | ||
| 496 | + | ||
| 497 | +static void scan_root(srcs_t *o, const char *dir, int depth, int *budget, int log_only) | ||
| 498 | +{ | ||
| 499 | + WIN32_FIND_DATAA fd; | ||
| 500 | + HANDLE h; | ||
| 501 | + char pat[1024]; | ||
| 502 | + char p[1024]; | ||
| 503 | + | ||
| 504 | + if (depth < 0 || *budget <= 0 || !dir || !*dir) return; | ||
| 505 | + if (strlen(dir) + 3 >= sizeof(pat)) return; | ||
| 506 | + snprintf(pat, sizeof(pat), "%s\\*", dir); | ||
| 507 | + h = FindFirstFileA(pat, &fd); | ||
| 508 | + if (h == INVALID_HANDLE_VALUE) return; | ||
| 509 | + | ||
| 510 | + do { | ||
| 511 | + if (strcmp(fd.cFileName, ".") == 0 || strcmp(fd.cFileName, "..") == 0) continue; | ||
| 512 | + if (--(*budget) <= 0) { o->truncated = 1; break; } | ||
| 513 | + if (strlen(dir) + strlen(fd.cFileName) + 2 >= sizeof(p)) continue; | ||
| 514 | + snprintf(p, sizeof(p), "%s\\%s", dir, fd.cFileName); | ||
| 515 | + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { | ||
| 516 | + if (depth > 0) scan_root(o, p, depth - 1, budget, log_only); | ||
| 517 | + } else if (!log_only || has_log_suffix(fd.cFileName)) { | ||
| 518 | + add_file_src(o, p); | ||
| 519 | + } | ||
| 520 | + } while (FindNextFileA(h, &fd)); | ||
| 521 | + FindClose(h); | ||
| 522 | +} | ||
| 523 | + | ||
| 524 | +static void scan_sources(srcs_t *o) | ||
| 525 | +{ | ||
| 526 | + int budget = ROOT_BUDGET; | ||
| 527 | + char p[1024]; | ||
| 528 | + const char *lad = getenv("LOCALAPPDATA"); | ||
| 529 | + | ||
| 530 | + memset(o, 0, sizeof(*o)); | ||
| 531 | + o->journal_avail = 0; /* Windows uses the event log instead */ | ||
| 532 | + | ||
| 533 | + /* The two archives the plugin exposes on Windows. */ | ||
| 534 | + add_src(o, "event:System", "Windows System log", "event", 0LL, 0L); | ||
| 535 | + add_src(o, "event:Application", "Windows Application log", "event", 0LL, 0L); | ||
| 536 | + | ||
| 537 | + if (lad && *lad) { | ||
| 538 | + snprintf(p, sizeof(p), "%s\\scorpiox", lad); | ||
| 539 | + scan_root(o, p, 4, &budget, 1); | ||
| 540 | + } | ||
| 541 | + if (getenv("USERPROFILE")) { | ||
| 542 | + snprintf(p, sizeof(p), "%s\\AppData\\Local\\scorpiox", getenv("USERPROFILE")); | ||
| 543 | + scan_root(o, p, 4, &budget, 1); | ||
| 544 | + } | ||
| 545 | +} | ||
| 546 | + | ||
| 547 | +#endif | ||
| 548 | + | ||
| 549 | +/* Resolve a src id to an allowlisted entry. Returns NULL if not in the list. */ | ||
| 550 | +static const src_t *find_src(const srcs_t *o, const char *id) | ||
| 551 | +{ | ||
| 552 | + int i; | ||
| 553 | + if (!id || !*id) return NULL; | ||
| 554 | + for (i = 0; i < o->n; i++) | ||
| 555 | + if (strcmp(o->items[i].id, id) == 0) return &o->items[i]; | ||
| 556 | + return NULL; | ||
| 557 | +} | ||
| 558 | + | ||
| 559 | +/* ------------------------------------------------------------------ */ | ||
| 560 | +/* Entry lists */ | ||
| 561 | +/* ------------------------------------------------------------------ */ | ||
| 562 | + | ||
| 563 | +typedef struct { | ||
| 564 | + char ts[ENTRY_TS]; | ||
| 565 | + char unit[ENTRY_UNIT]; | ||
| 566 | + int sev; | ||
| 567 | + char text[ENTRY_TEXT]; | ||
| 568 | +} entry_t; | ||
| 569 | + | ||
| 570 | +typedef struct { | ||
| 571 | + entry_t *v; | ||
| 572 | + int cap; | ||
| 573 | + int n; | ||
| 574 | + int start; | ||
| 575 | +} ring_t; | ||
| 576 | + | ||
| 577 | +static int ring_init(ring_t *r, int cap) | ||
| 578 | +{ | ||
| 579 | + if (cap < 1) cap = 1; | ||
| 580 | + r->v = (entry_t *)calloc((size_t)cap, sizeof(entry_t)); | ||
| 581 | + if (!r->v) return 0; | ||
| 582 | + r->cap = cap; | ||
| 583 | + r->n = 0; | ||
| 584 | + r->start = 0; | ||
| 585 | + return 1; | ||
| 586 | +} | ||
| 587 | + | ||
| 588 | +static void ring_add(ring_t *r, const entry_t *e) | ||
| 589 | +{ | ||
| 590 | + if (r->n < r->cap) { | ||
| 591 | + r->v[(r->start + r->n) % r->cap] = *e; | ||
| 592 | + r->n++; | ||
| 593 | + } else { | ||
| 594 | + r->v[r->start] = *e; | ||
| 595 | + r->start = (r->start + 1) % r->cap; | ||
| 596 | + } | ||
| 597 | +} | ||
| 598 | + | ||
| 599 | +static entry_t *ring_at(ring_t *r, int i) | ||
| 600 | +{ | ||
| 601 | + return &r->v[(r->start + i) % r->cap]; | ||
| 602 | +} | ||
| 603 | + | ||
| 604 | +static void ring_free(ring_t *r) | ||
| 605 | +{ | ||
| 606 | + free(r->v); | ||
| 607 | + r->v = NULL; | ||
| 608 | +} | ||
| 609 | + | ||
| 610 | +typedef struct { | ||
| 611 | + entry_t *v; | ||
| 612 | + int cap; | ||
| 613 | + int n; | ||
| 614 | +} list_t; | ||
| 615 | + | ||
| 616 | +static int list_init(list_t *l, int cap) | ||
| 617 | +{ | ||
| 618 | + if (cap < 1) cap = 1; | ||
| 619 | + l->v = (entry_t *)calloc((size_t)cap, sizeof(entry_t)); | ||
| 620 | + if (!l->v) return 0; | ||
| 621 | + l->cap = cap; | ||
| 622 | + l->n = 0; | ||
| 623 | + return 1; | ||
| 624 | +} | ||
| 625 | + | ||
| 626 | +static void list_free(list_t *l) | ||
| 627 | +{ | ||
| 628 | + free(l->v); | ||
| 629 | + l->v = NULL; | ||
| 630 | +} | ||
| 631 | + | ||
| 632 | +/* ------------------------------------------------------------------ */ | ||
| 633 | +/* Command execution (fixed argv only) */ | ||
| 634 | +/* ------------------------------------------------------------------ */ | ||
| 635 | + | ||
| 636 | +static FILE *run_cmd(const char *cmd) | ||
| 637 | +{ | ||
| 638 | +#if defined(_WIN32) | ||
| 639 | + return _popen(cmd, "r"); | ||
| 640 | +#else | ||
| 641 | + return popen(cmd, "r"); | ||
| 642 | +#endif | ||
| 643 | +} | ||
| 644 | + | ||
| 645 | +static int close_cmd(FILE *f) | ||
| 646 | +{ | ||
| 647 | +#if defined(_WIN32) | ||
| 648 | + return _pclose(f); | ||
| 649 | +#else | ||
| 650 | + return pclose(f); | ||
| 651 | +#endif | ||
| 652 | +} | ||
| 653 | + | ||
| 654 | +/* Validate a systemd unit name before it can reach the fixed argv. */ | ||
| 655 | +static int valid_unit(const char *u) | ||
| 656 | +{ | ||
| 657 | + size_t i, l; | ||
| 658 | + if (!u || !*u) return 0; | ||
| 659 | + l = strlen(u); | ||
| 660 | + if (l > 128) return 0; | ||
| 661 | + for (i = 0; i < l; i++) { | ||
| 662 | + unsigned char c = (unsigned char)u[i]; | ||
| 663 | + if (!(isalnum(c) || c == '@' || c == '.' || c == '_' || c == '-')) | ||
| 664 | + return 0; | ||
| 665 | + } | ||
| 666 | + /* a leading '-' would read as an option to journalctl */ | ||
| 667 | + return u[0] != '-'; | ||
| 668 | +} | ||
| 669 | + | ||
| 670 | +/* ------------------------------------------------------------------ */ | ||
| 671 | +/* Journal parsing (journalctl -o json, one object per line) */ | ||
| 672 | +/* ------------------------------------------------------------------ */ | ||
| 673 | + | ||
| 674 | +/* | ||
| 675 | + * Extract one top-level key's value from a single journal JSON object line. | ||
| 676 | + * Handles string values with backslash escapes, numeric values, and String | ||
| 677 | + * arrays (journal stores binary or multi-line MESSAGE fields as arrays, which | ||
| 678 | + * this plugin renders as a placeholder rather than pretending to decode). | ||
| 679 | + */ | ||
| 680 | +static int jget(const char *line, const char *key, char *out, size_t osz) | ||
| 681 | +{ | ||
| 682 | + char pat[128]; | ||
| 683 | + const char *p; | ||
| 684 | + | ||
| 685 | + if (osz) out[0] = '\0'; | ||
| 686 | + if (!line || !key || !*key) return 0; | ||
| 687 | + /* the search key is a fixed literal from this file, never user input */ | ||
| 688 | + snprintf(pat, sizeof(pat), "\"%s\"", key); | ||
| 689 | + | ||
| 690 | + for (p = line; (p = strstr(p, pat)) != NULL; p += strlen(pat)) { | ||
| 691 | + const char *q = p + strlen(pat); | ||
| 692 | + while (*q == ' ' || *q == '\t') q++; | ||
| 693 | + if (*q != ':') continue; /* a value that happens to match */ | ||
| 694 | + q++; | ||
| 695 | + while (*q == ' ' || *q == '\t') q++; | ||
| 696 | + | ||
| 697 | + if (*q == '"') { | ||
| 698 | + size_t o = 0; | ||
| 699 | + q++; | ||
| 700 | + while (*q && *q != '"') { | ||
| 701 | + char c = *q; | ||
| 702 | + if (c == '\\' && q[1]) { | ||
| 703 | + q++; | ||
| 704 | + switch (*q) { | ||
| 705 | + case 'n': c = '\n'; break; | ||
| 706 | + case 'r': c = '\r'; break; | ||
| 707 | + case 't': c = '\t'; break; | ||
| 708 | + case '"': c = '"'; break; | ||
| 709 | + case '\\': c = '\\'; break; | ||
| 710 | + case '/': c = '/'; break; | ||
| 711 | + default: c = *q; break; | ||
| 712 | + } | ||
| 713 | + } | ||
| 714 | + if (o + 1 < osz) out[o++] = c; | ||
| 715 | + q++; | ||
| 716 | + } | ||
| 717 | + out[o] = '\0'; | ||
| 718 | + return 1; | ||
| 719 | + } | ||
| 720 | + if (*q == '[') { | ||
| 721 | + /* journal stores binary or multi-line fields as byte arrays */ | ||
| 722 | + snprintf(out, osz, "(binary)"); | ||
| 723 | + return 1; | ||
| 724 | + } | ||
| 725 | + { | ||
| 726 | + size_t o = 0; | ||
| 727 | + while (*q && *q != ',' && *q != '}') { | ||
| 728 | + if (o + 1 < osz) out[o++] = *q; | ||
| 729 | + q++; | ||
| 730 | + } | ||
| 731 | + out[o] = '\0'; | ||
| 732 | + return 1; | ||
| 733 | + } | ||
| 734 | + } | ||
| 735 | + return 0; | ||
| 736 | +} | ||
| 737 | + | ||
| 738 | +static void fmt_journal_ts(const char *us, char *out, size_t osz) | ||
| 739 | +{ | ||
| 740 | + long long v; | ||
| 741 | + time_t secs; | ||
| 742 | + struct tm tmv; | ||
| 743 | + if (!us || !*us) { snprintf(out, osz, "-"); return; } | ||
| 744 | + v = atoll(us); | ||
| 745 | + if (v <= 0) { snprintf(out, osz, "-"); return; } | ||
| 746 | + secs = (time_t)(v / 1000000LL); | ||
| 747 | + if (!localtime_r(&secs, &tmv)) { snprintf(out, osz, "-"); return; } | ||
| 748 | + strftime(out, osz, "%m-%d %H:%M:%S", &tmv); | ||
| 749 | +} | ||
| 750 | + | ||
| 751 | +/* | ||
| 752 | + * Stream journalctl into `sink`. `filter` (optional) keeps only lines whose | ||
| 753 | + * text, unit or timestamp matches case-insensitively. Returns the number of | ||
| 754 | + * lines scanned, or -1 when journalctl could not be run. | ||
| 755 | + */ | ||
| 756 | +typedef void (*entry_sink)(void *ctx, const entry_t *e); | ||
| 757 | + | ||
| 758 | +static int stream_journal(const char *unit, int nlines, const char *filter, | ||
| 759 | + entry_sink sink, void *ctx) | ||
| 760 | +{ | ||
| 761 | +#if defined(_WIN32) | ||
| 762 | + (void)unit; (void)nlines; (void)filter; (void)sink; (void)ctx; | ||
| 763 | + return -1; | ||
| 764 | +#else | ||
| 765 | + char cmd[512]; | ||
| 766 | + FILE *f; | ||
| 767 | + char line[8192]; | ||
| 768 | + int scanned = 0; | ||
| 769 | + int uok = unit && *unit && valid_unit(unit); | ||
| 770 | + const char *fixture = getenv("SX_LOGS_JOURNAL_FIXTURE"); | ||
| 771 | + | ||
| 772 | + if (unit && *unit && !uok) return -1; | ||
| 773 | + if (nlines < 1) nlines = 1; | ||
| 774 | + if (nlines > TAIL_MAX) nlines = TAIL_MAX; | ||
| 775 | + | ||
| 776 | + if (uok) | ||
| 777 | + snprintf(cmd, sizeof(cmd), | ||
| 778 | + "journalctl -o json --no-pager -n %d -u %s 2>/dev/null", nlines, unit); | ||
| 779 | + else | ||
| 780 | + snprintf(cmd, sizeof(cmd), | ||
| 781 | + "journalctl -o json --no-pager -n %d 2>/dev/null", nlines); | ||
| 782 | + | ||
| 783 | + /* test-only: replay a captured journalctl -o json stream */ | ||
| 784 | + if (fixture && *fixture) f = fopen(fixture, "r"); | ||
| 785 | + else f = run_cmd(cmd); | ||
| 786 | + if (!f) return -1; | ||
| 787 | + | ||
| 788 | + while (fgets(line, sizeof(line), f)) { | ||
| 789 | + entry_t e; | ||
| 790 | + char msg[ENTRY_TEXT] = ""; | ||
| 791 | + char pri[8] = ""; | ||
| 792 | + char tsus[32] = ""; | ||
| 793 | + char un[ENTRY_UNIT] = ""; | ||
| 794 | + int prio; | ||
| 795 | + | ||
| 796 | + if (line[0] != '{') continue; | ||
| 797 | + scanned++; | ||
| 798 | + jget(line, "MESSAGE", msg, sizeof(msg)); | ||
| 799 | + jget(line, "PRIORITY", pri, sizeof(pri)); | ||
| 800 | + jget(line, "__REALTIME_TIMESTAMP", tsus, sizeof(tsus)); | ||
| 801 | + if (!jget(line, "_SYSTEMD_UNIT", un, sizeof(un))) | ||
| 802 | + jget(line, "SYSLOG_IDENTIFIER", un, sizeof(un)); | ||
| 803 | + | ||
| 804 | + memset(&e, 0, sizeof(e)); | ||
| 805 | + fmt_journal_ts(tsus, e.ts, sizeof(e.ts)); | ||
| 806 | + snprintf(e.unit, sizeof(e.unit), "%s", un); | ||
| 807 | + prio = pri[0] ? atoi(pri) : 6; | ||
| 808 | + e.sev = prio <= 3 ? SEV_ERR : prio == 4 ? SEV_WARN : SEV_INFO; | ||
| 809 | + snprintf(e.text, sizeof(e.text), "%s", msg); | ||
| 810 | + if (e.sev == SEV_INFO) e.sev = severity_of(e.text, NULL); | ||
| 811 | + | ||
| 812 | + if (filter && *filter && !ci_contains(e.text, filter) && | ||
| 813 | + !ci_contains(e.unit, filter) && !ci_contains(e.ts, filter)) | ||
| 814 | + continue; | ||
| 815 | + sink(ctx, &e); | ||
| 816 | + } | ||
| 817 | + if (fixture && *fixture) fclose(f); | ||
| 818 | + else close_cmd(f); | ||
| 819 | + return scanned; | ||
| 820 | +#endif | ||
| 821 | +} | ||
| 822 | + | ||
| 823 | +/* ------------------------------------------------------------------ */ | ||
| 824 | +/* Plain log-file reading */ | ||
| 825 | +/* ------------------------------------------------------------------ */ | ||
| 826 | + | ||
| 827 | +/* | ||
| 828 | + * Works out the byte offset to start reading from so only the last `maxbytes` | ||
| 829 | + * of a file are considered. Logs grow to gigabytes; a viewer must never read | ||
| 830 | + * one in full. | ||
| 831 | + */ | ||
| 832 | +static long tail_offset(long long size, long maxbytes) | ||
| 833 | +{ | ||
| 834 | + if (size <= maxbytes) return 0; | ||
| 835 | + return (long)(size - maxbytes); | ||
| 836 | +} | ||
| 837 | + | ||
| 838 | +#if !defined(_WIN32) | ||
| 839 | +static int open_log(const char *path, FILE **out, long long *size_out) | ||
| 840 | +{ | ||
| 841 | + struct stat st; | ||
| 842 | + if (stat(path, &st) != 0 || !S_ISREG(st.st_mode)) return -1; | ||
| 843 | + *out = fopen(path, "rb"); | ||
| 844 | + if (!*out) return -1; | ||
| 845 | + *size_out = (long long)st.st_size; | ||
| 846 | + return 0; | ||
| 847 | +} | ||
| 848 | +#else | ||
| 849 | +static int open_log(const char *path, FILE **out, long long *size_out) | ||
| 850 | +{ | ||
| 851 | + WIN32_FILE_ATTRIBUTE_DATA fad; | ||
| 852 | + if (!GetFileAttributesExA(path, GetFileExInfoStandard, &fad)) return -1; | ||
| 853 | + if (fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) return -1; | ||
| 854 | + *out = fopen(path, "rb"); | ||
| 855 | + if (!*out) return -1; | ||
| 856 | + *size_out = (long long)fad.nFileSizeLow; | ||
| 857 | + return 0; | ||
| 858 | +} | ||
| 859 | +#endif | ||
| 860 | + | ||
| 861 | +/* Fill one entry from a raw log line. Detects the two timestamp layouts that | ||
| 862 | + * nearly every text log uses, and falls back to no timestamp. */ | ||
| 863 | +static void entry_from_line(entry_t *e, const char *line, size_t n) | ||
| 864 | +{ | ||
| 865 | + char buf[ENTRY_TEXT * 2]; | ||
| 866 | + | ||
| 867 | + memset(e, 0, sizeof(*e)); | ||
| 868 | + if (n >= sizeof(buf)) n = sizeof(buf) - 1; | ||
| 869 | + memcpy(buf, line, n); | ||
| 870 | + buf[n] = '\0'; | ||
| 871 | + while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; | ||
| 872 | + | ||
| 873 | + /* syslog: "Nov 12 06:30:01 host unit[pid]: message" */ | ||
| 874 | + if (n > 16 && isalpha((unsigned char)buf[0]) && buf[3] == ' ' && | ||
| 875 | + isdigit((unsigned char)buf[4]) && buf[6] == ' ' && buf[9] == ':') { | ||
| 876 | + snprintf(e->ts, sizeof(e->ts), "%.15s", buf); | ||
| 877 | + /* everything after "host " is the text, unit if it looks like one */ | ||
| 878 | + { | ||
| 879 | + const char *p = buf + 16; | ||
| 880 | + const char *colon; | ||
| 881 | + while (*p && *p != ' ') p++; | ||
| 882 | + while (*p == ' ') p++; | ||
| 883 | + colon = strchr(p, ':'); | ||
| 884 | + if (colon && (size_t)(colon - p) < sizeof(e->unit) && | ||
| 885 | + (size_t)(colon - p) < 64) { | ||
| 886 | + snprintf(e->unit, sizeof(e->unit), "%.*s", (int)(colon - p), p); | ||
| 887 | + snprintf(e->text, sizeof(e->text), "%s", colon + 1); | ||
| 888 | + } else { | ||
| 889 | + snprintf(e->text, sizeof(e->text), "%.*s", | ||
| 890 | + (int)(sizeof(e->text) - 1), p); | ||
| 891 | + } | ||
| 892 | + trim_into(e->text, sizeof(e->text), e->text, strlen(e->text)); | ||
| 893 | + e->sev = severity_of(e->text, NULL); | ||
| 894 | + return; | ||
| 895 | + } | ||
| 896 | + } | ||
| 897 | + | ||
| 898 | + /* ISO-8601 prefix: "2026-11-12T06:30:01Z rest" or "2026-11-12 06:30:01 rest" */ | ||
| 899 | + if (n > 20 && isdigit((unsigned char)buf[0]) && buf[4] == '-' && buf[7] == '-' && | ||
| 900 | + (buf[10] == 'T' || buf[10] == ' ')) { | ||
| 901 | + size_t cut = 11; | ||
| 902 | + while (cut < n && cut < 32 && buf[cut] != ' ' && buf[cut] != '\t') cut++; | ||
| 903 | + snprintf(e->ts, sizeof(e->ts), "%.*s", (int)(cut < 24 ? cut : 24), buf); | ||
| 904 | + { | ||
| 905 | + const char *p = buf + cut; | ||
| 906 | + while (*p == ' ' || *p == '\t') p++; | ||
| 907 | + snprintf(e->text, sizeof(e->text), "%.*s", | ||
| 908 | + (int)(sizeof(e->text) - 1), p); | ||
| 909 | + } | ||
| 910 | + e->sev = severity_of(e->text, NULL); | ||
| 911 | + return; | ||
| 912 | + } | ||
| 913 | + | ||
| 914 | + snprintf(e->text, sizeof(e->text), "%.*s", | ||
| 915 | + (int)(sizeof(e->text) - 1), buf); | ||
| 916 | + e->sev = severity_of(e->text, NULL); | ||
| 917 | +} | ||
| 918 | + | ||
| 919 | +typedef struct { | ||
| 920 | + ring_t *ring; | ||
| 921 | + list_t *hits; | ||
| 922 | + const char *filter; | ||
| 923 | + int seen; | ||
| 924 | + int cap; | ||
| 925 | +} file_ctx_t; | ||
| 926 | + | ||
| 927 | +static void file_sink(void *vctx, const entry_t *e) | ||
| 928 | +{ | ||
| 929 | + file_ctx_t *c = (file_ctx_t *)vctx; | ||
| 930 | + if (c->ring) ring_add(c->ring, e); | ||
| 931 | + if (c->hits) { | ||
| 932 | + if (c->hits->n < c->cap) c->hits->v[c->hits->n++] = *e; | ||
| 933 | + } | ||
| 934 | + c->seen++; | ||
| 935 | +} | ||
| 936 | + | ||
| 937 | +/* | ||
| 938 | + * Read the tail of a log file. `ring` keeps the last N entries (tail mode); | ||
| 939 | + * `hits` collects up to `cap` matching entries (search mode). Exactly one of | ||
| 940 | + * them is non-NULL. | ||
| 941 | + */ | ||
| 942 | +static int read_log_file(const char *path, int nlines, const char *filter, | ||
| 943 | + ring_t *ring, list_t *hits, int hitcap) | ||
| 944 | +{ | ||
| 945 | + FILE *f = NULL; | ||
| 946 | + long long size = 0; | ||
| 947 | + long off; | ||
| 948 | + char line[ENTRY_TEXT * 2]; | ||
| 949 | + file_ctx_t ctx; | ||
| 950 | + | ||
| 951 | + (void)nlines; /* the ring/hit list owns the cap; this is only a hint */ | ||
| 952 | + if (open_log(path, &f, &size) != 0) return -1; | ||
| 953 | + | ||
| 954 | + memset(&ctx, 0, sizeof(ctx)); | ||
| 955 | + ctx.ring = ring; | ||
| 956 | + ctx.hits = hits; | ||
| 957 | + ctx.filter = filter; | ||
| 958 | + ctx.cap = hitcap; | ||
| 959 | + | ||
| 960 | + off = tail_offset(size, FILE_TAIL_BYTES); | ||
| 961 | + if (off > 0 && fseek(f, off, SEEK_SET) != 0) { | ||
| 962 | + fclose(f); | ||
| 963 | + return -1; | ||
| 964 | + } | ||
| 965 | + | ||
| 966 | + while (fgets(line, sizeof(line), f)) { | ||
| 967 | + entry_t e; | ||
| 968 | + size_t n = strlen(line); | ||
| 969 | + /* The first line after a tail seek is a partial line; drop it. */ | ||
| 970 | + if (off > 0 && ctx.seen == 0 && n > 0 && line[n - 1] != '\n') { | ||
| 971 | + ctx.seen = 0; | ||
| 972 | + /* still consume it so we do not emit a broken record */ | ||
| 973 | + continue; | ||
| 974 | + } | ||
| 975 | + if (hits && ctx.seen >= SEARCH_SCAN) break; | ||
| 976 | + entry_from_line(&e, line, n); | ||
| 977 | + if (filter && *filter && !ci_contains(e.text, filter) && | ||
| 978 | + !ci_contains(e.unit, filter) && !ci_contains(e.ts, filter)) | ||
| 979 | + { ctx.seen++; continue; } | ||
| 980 | + file_sink(&ctx, &e); | ||
| 981 | + } | ||
| 982 | + fclose(f); | ||
| 983 | + return ctx.seen; | ||
| 984 | +} | ||
| 985 | + | ||
| 986 | +/* ------------------------------------------------------------------ */ | ||
| 987 | +/* macOS `log show` reading */ | ||
| 988 | +/* ------------------------------------------------------------------ */ | ||
| 989 | + | ||
| 990 | +#if defined(__APPLE__) | ||
| 991 | + | ||
| 992 | +static int stream_macos_log(int nlines, const char *filter, | ||
| 993 | + entry_sink sink, void *ctx) | ||
| 994 | +{ | ||
| 995 | + char cmd[512]; | ||
| 996 | + FILE *f; | ||
| 997 | + char line[8192]; | ||
| 998 | + int scanned = 0; | ||
| 999 | + int mins; | ||
| 1000 | + | ||
| 1001 | + if (nlines < 1) nlines = 1; | ||
| 1002 | + if (nlines > TAIL_MAX) nlines = TAIL_MAX; | ||
| 1003 | + /* bound the time window: roughly one minute of syslog per 200 lines */ | ||
| 1004 | + mins = nlines / 200; | ||
| 1005 | + if (mins < 1) mins = 1; | ||
| 1006 | + if (mins > 60) mins = 60; | ||
| 1007 | + | ||
| 1008 | + snprintf(cmd, sizeof(cmd), | ||
| 1009 | + "log show --style compact --last %dm 2>/dev/null | tail -n %d", | ||
| 1010 | + mins, nlines); | ||
| 1011 | + f = run_cmd(cmd); | ||
| 1012 | + if (!f) return -1; | ||
| 1013 | + while (fgets(line, sizeof(line), f)) { | ||
| 1014 | + entry_t e; | ||
| 1015 | + size_t n = strlen(line); | ||
| 1016 | + if (filter && *filter && !ci_contains(line, filter)) { scanned++; continue; } | ||
| 1017 | + scanned++; | ||
| 1018 | + entry_from_line(&e, line, n); | ||
| 1019 | + sink(ctx, &e); | ||
| 1020 | + } | ||
| 1021 | + close_cmd(f); | ||
| 1022 | + return scanned; | ||
| 1023 | +} | ||
| 1024 | + | ||
| 1025 | +#endif | ||
| 1026 | + | ||
| 1027 | +/* ------------------------------------------------------------------ */ | ||
| 1028 | +/* Windows event log reading */ | ||
| 1029 | +/* ------------------------------------------------------------------ */ | ||
| 1030 | + | ||
| 1031 | +#if defined(_WIN32) | ||
| 1032 | + | ||
| 1033 | +static int stream_event_log(const char *channel, int nlines, const char *filter, | ||
| 1034 | + entry_sink sink, void *ctx) | ||
| 1035 | +{ | ||
| 1036 | + char cmd[512]; | ||
| 1037 | + FILE *f; | ||
| 1038 | + char line[8192]; | ||
| 1039 | + int scanned = 0; | ||
| 1040 | + | ||
| 1041 | + if (nlines < 1) nlines = 1; | ||
| 1042 | + if (nlines > TAIL_MAX) nlines = TAIL_MAX; | ||
| 1043 | + if (!channel || !*channel) return -1; | ||
| 1044 | + /* channel is one of two constants chosen by the caller, never user text */ | ||
| 1045 | + if (strcmp(channel, "System") != 0 && strcmp(channel, "Application") != 0) | ||
| 1046 | + return -1; | ||
| 1047 | + | ||
| 1048 | + snprintf(cmd, sizeof(cmd), | ||
| 1049 | + "wevtutil qe %s /c:%d /rd:true /f:text 2>NUL", channel, nlines); | ||
| 1050 | + f = run_cmd(cmd); | ||
| 1051 | + if (!f) return -1; | ||
| 1052 | + | ||
| 1053 | + { | ||
| 1054 | + entry_t e; | ||
| 1055 | + int have = 0; | ||
| 1056 | + memset(&e, 0, sizeof(e)); | ||
| 1057 | + while (fgets(line, sizeof(line), f)) { | ||
| 1058 | + char t[ENTRY_TEXT]; | ||
| 1059 | + trim_into(t, sizeof(t), line, strlen(line)); | ||
| 1060 | + if (!*t) { | ||
| 1061 | + if (have && e.text[0]) { | ||
| 1062 | + e.sev = severity_of(e.text, NULL); | ||
| 1063 | + if (!filter || !*filter || ci_contains(e.text, filter)) | ||
| 1064 | + sink(ctx, &e); | ||
| 1065 | + scanned++; | ||
| 1066 | + } | ||
| 1067 | + memset(&e, 0, sizeof(e)); | ||
| 1068 | + have = 0; | ||
| 1069 | + continue; | ||
| 1070 | + } | ||
| 1071 | + have = 1; | ||
| 1072 | + if (strncmp(t, "Date:", 5) == 0) { | ||
| 1073 | + snprintf(e.ts, sizeof(e.ts), "%s", t + 5); | ||
| 1074 | + trim_into(e.ts, sizeof(e.ts), e.ts, strlen(e.ts)); | ||
| 1075 | + } else if (strncmp(t, "Level:", 6) == 0) { | ||
| 1076 | + const char *lv = t + 6; | ||
| 1077 | + while (*lv == ' ') lv++; | ||
| 1078 | + snprintf(e.unit, sizeof(e.unit), "%s", channel); | ||
| 1079 | + if (ci_contains(lv, "Error") || ci_contains(lv, "Critical")) | ||
| 1080 | + e.sev = SEV_ERR; | ||
| 1081 | + else if (ci_contains(lv, "Warning")) | ||
| 1082 | + e.sev = SEV_WARN; | ||
| 1083 | + } else if (strncmp(t, "Description:", 12) == 0) { | ||
| 1084 | + snprintf(e.text, sizeof(e.text), "%s", t + 12); | ||
| 1085 | + trim_into(e.text, sizeof(e.text), e.text, strlen(e.text)); | ||
| 1086 | + } | ||
| 1087 | + } | ||
| 1088 | + if (have && e.text[0]) { | ||
| 1089 | + e.sev = severity_of(e.text, NULL); | ||
| 1090 | + if (!filter || !*filter || ci_contains(e.text, filter)) | ||
| 1091 | + sink(ctx, &e); | ||
| 1092 | + scanned++; | ||
| 1093 | + } | ||
| 1094 | + } | ||
| 1095 | + close_cmd(f); | ||
| 1096 | + return scanned; | ||
| 1097 | +} | ||
| 1098 | + | ||
| 1099 | +#endif | ||
| 1100 | + | ||
| 1101 | +/* ------------------------------------------------------------------ */ | ||
| 1102 | +/* Units (service providers that have journal entries) */ | ||
| 1103 | +/* ------------------------------------------------------------------ */ | ||
| 1104 | + | ||
| 1105 | +typedef struct { | ||
| 1106 | + char name[ENTRY_UNIT]; | ||
| 1107 | + int entries; | ||
| 1108 | +} unit_t; | ||
| 1109 | + | ||
| 1110 | +static int list_units(unit_t *out, int max) | ||
| 1111 | +{ | ||
| 1112 | +#if defined(_WIN32) || defined(__APPLE__) | ||
| 1113 | + (void)out; (void)max; | ||
| 1114 | + return 0; | ||
| 1115 | +#else | ||
| 1116 | + FILE *f; | ||
| 1117 | + char line[1024]; | ||
| 1118 | + int n = 0; | ||
| 1119 | + | ||
| 1120 | + f = run_cmd("journalctl --no-pager -F _SYSTEMD_UNIT 2>/dev/null | head -n 400"); | ||
| 1121 | + if (!f) return 0; | ||
| 1122 | + while (fgets(line, sizeof(line), f) && n < max) { | ||
| 1123 | + char u[ENTRY_UNIT]; | ||
| 1124 | + int i; | ||
| 1125 | + trim_into(u, sizeof(u), line, strlen(line)); | ||
| 1126 | + if (!*u) continue; | ||
| 1127 | + if (!valid_unit(u)) continue; | ||
| 1128 | + for (i = 0; i < n; i++) | ||
| 1129 | + if (strcmp(out[i].name, u) == 0) break; | ||
| 1130 | + if (i < n) continue; | ||
| 1131 | + snprintf(out[n].name, sizeof(out[n].name), "%s", u); | ||
| 1132 | + out[n].entries = 0; | ||
| 1133 | + n++; | ||
| 1134 | + } | ||
| 1135 | + close_cmd(f); | ||
| 1136 | + return n; | ||
| 1137 | +#endif | ||
| 1138 | +} | ||
| 1139 | + | ||
| 1140 | +/* ------------------------------------------------------------------ */ | ||
| 1141 | +/* Collection helpers */ | ||
| 1142 | +/* ------------------------------------------------------------------ */ | ||
| 1143 | + | ||
| 1144 | +typedef struct { | ||
| 1145 | + ring_t *ring; | ||
| 1146 | +} shell_ctx_t; | ||
| 1147 | + | ||
| 1148 | +static void shell_sink(void *vctx, const entry_t *e) | ||
| 1149 | +{ | ||
| 1150 | + ring_t *r = ((shell_ctx_t *)vctx)->ring; | ||
| 1151 | + ring_add(r, e); | ||
| 1152 | +} | ||
| 1153 | + | ||
| 1154 | +/* Stream `nlines` entries for a source into `ring` (tail mode). */ | ||
| 1155 | +static int collect_tail(const src_t *s, int nlines, ring_t *ring) | ||
| 1156 | +{ | ||
| 1157 | + shell_ctx_t ctx; | ||
| 1158 | + | ||
| 1159 | + ctx.ring = ring; | ||
| 1160 | + if (strcmp(s->kind, "journal") == 0) | ||
| 1161 | + return stream_journal(NULL, nlines, NULL, shell_sink, &ctx); | ||
| 1162 | +#if defined(_WIN32) | ||
| 1163 | + if (strncmp(s->id, "event:", 6) == 0) | ||
| 1164 | + return stream_event_log(s->id + 6, nlines, NULL, shell_sink, &ctx); | ||
| 1165 | +#endif | ||
| 1166 | +#if defined(__APPLE__) | ||
| 1167 | + if (strcmp(s->kind, "journal") == 0) | ||
| 1168 | + return stream_macos_log(nlines, NULL, shell_sink, &ctx); | ||
| 1169 | +#endif | ||
| 1170 | + if (strncmp(s->id, "file:", 5) == 0) | ||
| 1171 | + return read_log_file(s->id + 5, nlines, NULL, ring, NULL, 0); | ||
| 1172 | + if (strncmp(s->id, "journal:", 8) == 0) | ||
| 1173 | + return stream_journal(s->id + 8, nlines, NULL, shell_sink, &ctx); | ||
| 1174 | + return -1; | ||
| 1175 | +} | ||
| 1176 | + | ||
| 1177 | +typedef struct { | ||
| 1178 | + list_t *hits; | ||
| 1179 | +} hits_ctx_t; | ||
| 1180 | + | ||
| 1181 | +static void hits_sink(void *vctx, const entry_t *e) | ||
| 1182 | +{ | ||
| 1183 | + list_t *l = ((hits_ctx_t *)vctx)->hits; | ||
| 1184 | + if (l->n < l->cap) l->v[l->n++] = *e; | ||
| 1185 | +} | ||
| 1186 | + | ||
| 1187 | +/* Search a source for `filter`. Returns the number of lines scanned. */ | ||
| 1188 | +static int collect_search(const src_t *s, const char *filter, list_t *hits) | ||
| 1189 | +{ | ||
| 1190 | + hits_ctx_t ctx; | ||
| 1191 | + | ||
| 1192 | + ctx.hits = hits; | ||
| 1193 | + if (strcmp(s->kind, "journal") == 0) | ||
| 1194 | + return stream_journal(NULL, TAIL_MAX, filter, hits_sink, &ctx); | ||
| 1195 | +#if defined(_WIN32) | ||
| 1196 | + if (strncmp(s->id, "event:", 6) == 0) | ||
| 1197 | + return stream_event_log(s->id + 6, 600, filter, hits_sink, &ctx); | ||
| 1198 | +#endif | ||
| 1199 | + if (strncmp(s->id, "file:", 5) == 0) | ||
| 1200 | + return read_log_file(s->id + 5, TAIL_MAX, filter, NULL, hits, SEARCH_HITS_MAX); | ||
| 1201 | + if (strncmp(s->id, "journal:", 8) == 0) | ||
| 1202 | + return stream_journal(s->id + 8, TAIL_MAX, filter, hits_sink, &ctx); | ||
| 1203 | + return -1; | ||
| 1204 | +} | ||
| 1205 | + | ||
| 1206 | +/* ------------------------------------------------------------------ */ | ||
| 1207 | +/* Modes */ | ||
| 1208 | +/* ------------------------------------------------------------------ */ | ||
| 1209 | + | ||
| 1210 | +static int mode_meta(void) | ||
| 1211 | +{ | ||
| 1212 | + puts("{\"name\":\"logs\",\"desc\":\"Log viewer\"}"); | ||
| 1213 | + return 0; | ||
| 1214 | +} | ||
| 1215 | + | ||
| 1216 | +static void json_header(void) | ||
| 1217 | +{ | ||
| 1218 | + /* Deliberately no Content-Length - the server owns framing. */ | ||
| 1219 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | ||
| 1220 | + "Cache-Control: no-store\r\n" | ||
| 1221 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 1222 | +} | ||
| 1223 | + | ||
| 1224 | +static int mode_json(const char *qs) | ||
| 1225 | +{ | ||
| 1226 | + char action[32]; | ||
| 1227 | + char srcid[600]; | ||
| 1228 | + char linesv[16]; | ||
| 1229 | + char q[256]; | ||
| 1230 | + char utc[40]; | ||
| 1231 | + srcs_t srcs; | ||
| 1232 | + int nlines = 200; | ||
| 1233 | + | ||
| 1234 | + action[0] = srcid[0] = linesv[0] = q[0] = '\0'; | ||
| 1235 | + get_query_val(qs, "action", action, sizeof(action)); | ||
| 1236 | + get_query_val(qs, "src", srcid, sizeof(srcid)); | ||
| 1237 | + get_query_val(qs, "lines", linesv, sizeof(linesv)); | ||
| 1238 | + get_query_val(qs, "q", q, sizeof(q)); | ||
| 1239 | + | ||
| 1240 | + /* anything above the cap is clamped, never silently ignored */ | ||
| 1241 | + if (linesv[0]) { | ||
| 1242 | + int v = atoi(linesv); | ||
| 1243 | + if (v > 0) nlines = v > TAIL_MAX ? TAIL_MAX : v; | ||
| 1244 | + } | ||
| 1245 | + | ||
| 1246 | + if (!action[0] || (strcmp(action, "sources") != 0 && strcmp(action, "tail") != 0 && | ||
| 1247 | + strcmp(action, "search") != 0 && strcmp(action, "units") != 0 && | ||
| 1248 | + strcmp(action, "info") != 0)) { | ||
| 1249 | + json_header(); | ||
| 1250 | + printf("{\"ok\":false,\"error\":\"unknown_action\",\"supported\":" | ||
| 1251 | + "[\"sources\",\"tail\",\"search\",\"units\",\"info\"],\"requested\":"); | ||
| 1252 | + json_str(action); | ||
| 1253 | + fputs("}\n", stdout); | ||
| 1254 | + return 0; | ||
| 1255 | + } | ||
| 1256 | + | ||
| 1257 | + utc_now(utc, sizeof(utc)); | ||
| 1258 | + | ||
| 1259 | + if (strcmp(action, "info") == 0) { | ||
| 1260 | + json_header(); | ||
| 1261 | + fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," | ||
| 1262 | + "\"version\":\"" PLUGIN_VER "\",\"utc\":", stdout); | ||
| 1263 | + json_str(utc); | ||
| 1264 | + printf(",\"platform\":\"%s\"", | ||
| 1265 | +#if defined(_WIN32) | ||
| 1266 | + "windows" | ||
| 1267 | +#elif defined(__APPLE__) | ||
| 1268 | + "macos" | ||
| 1269 | +#else | ||
| 1270 | + "linux" | ||
| 1271 | +#endif | ||
| 1272 | + ); | ||
| 1273 | + fputs(",\"limits\":{\"lines_max\":", stdout); | ||
| 1274 | + printf("%d", TAIL_MAX); | ||
| 1275 | + fputs(",\"search_hits_max\":", stdout); | ||
| 1276 | + printf("%d", SEARCH_HITS_MAX); | ||
| 1277 | + fputs(",\"search_scan_max\":", stdout); | ||
| 1278 | + printf("%d", SEARCH_SCAN); | ||
| 1279 | + fputs("},\"supported\":[\"sources\",\"tail\",\"search\",\"units\",\"info\"]," | ||
| 1280 | + "\"zero_network\":true,\"read_only\":true,\"node_auth\":", stdout); | ||
| 1281 | + { | ||
| 1282 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 1283 | + fputs((np && *np) ? "true" : "false", stdout); | ||
| 1284 | + } | ||
| 1285 | + fputs("}\n", stdout); | ||
| 1286 | + return 0; | ||
| 1287 | + } | ||
| 1288 | + | ||
| 1289 | + scan_sources(&srcs); | ||
| 1290 | + | ||
| 1291 | + if (strcmp(action, "sources") == 0) { | ||
| 1292 | + int i; | ||
| 1293 | + json_header(); | ||
| 1294 | + fputs("{\"ok\":true,\"action\":\"sources\",\"plugin\":\"" PLUGIN_ID "\"," | ||
| 1295 | + "\"utc\":", stdout); | ||
| 1296 | + json_str(utc); | ||
| 1297 | + printf(",\"journal_available\":%s,\"count\":%d,\"truncated\":%s,\"sources\":[", | ||
| 1298 | + srcs.journal_avail ? "true" : "false", srcs.n, | ||
| 1299 | + srcs.truncated ? "true" : "false"); | ||
| 1300 | + for (i = 0; i < srcs.n; i++) { | ||
| 1301 | + if (i) fputc(',', stdout); | ||
| 1302 | + fputs("{\"id\":", stdout); json_str(srcs.items[i].id); | ||
| 1303 | + fputs(",\"label\":", stdout); json_str(srcs.items[i].label); | ||
| 1304 | + fputs(",\"kind\":", stdout); json_str(srcs.items[i].kind); | ||
| 1305 | + printf(",\"size\":%lld,\"mtime\":%ld}", srcs.items[i].size, srcs.items[i].mtime); | ||
| 1306 | + } | ||
| 1307 | + fputs("]}\n", stdout); | ||
| 1308 | + return 0; | ||
| 1309 | + } | ||
| 1310 | + | ||
| 1311 | + if (strcmp(action, "units") == 0) { | ||
| 1312 | + static unit_t units[MAX_UNITS]; | ||
| 1313 | + int n = 0, i; | ||
| 1314 | +#if !defined(_WIN32) && !defined(__APPLE__) | ||
| 1315 | + n = list_units(units, MAX_UNITS); | ||
| 1316 | +#else | ||
| 1317 | + (void)units; | ||
| 1318 | +#endif | ||
| 1319 | + json_header(); | ||
| 1320 | + fputs("{\"ok\":true,\"action\":\"units\",\"available\":", stdout); | ||
| 1321 | +#if !defined(_WIN32) && !defined(__APPLE__) | ||
| 1322 | + fputs("true", stdout); | ||
| 1323 | +#else | ||
| 1324 | + fputs("false", stdout); | ||
| 1325 | +#endif | ||
| 1326 | + printf(",\"count\":%d,\"units\":[", n); | ||
| 1327 | + for (i = 0; i < n; i++) { | ||
| 1328 | + if (i) fputc(',', stdout); | ||
| 1329 | + fputs("{\"name\":", stdout); json_str(units[i].name); | ||
| 1330 | + printf(",\"src\":\"journal:%s\"}", units[i].name); | ||
| 1331 | + } | ||
| 1332 | + fputs("]}\n", stdout); | ||
| 1333 | + return 0; | ||
| 1334 | + } | ||
| 1335 | + | ||
| 1336 | + { | ||
| 1337 | + const src_t *s = find_src(&srcs, srcid); | ||
| 1338 | + char srcbuf[32]; | ||
| 1339 | + | ||
| 1340 | + snprintf(srcbuf, sizeof(srcbuf), "%s", srcid); | ||
| 1341 | + if (!s) { | ||
| 1342 | + json_header(); | ||
| 1343 | + fputs("{\"ok\":false,\"error\":\"source_not_allowed\"," | ||
| 1344 | + "\"message\":\"that path is not in this plugin's read allowlist; " | ||
| 1345 | + "call action=sources for the current list\",\"requested\":", stdout); | ||
| 1346 | + json_str(srcbuf); | ||
| 1347 | + fputs("}\n", stdout); | ||
| 1348 | + return 0; | ||
| 1349 | + } | ||
| 1350 | + if (!*s->kind) { | ||
| 1351 | + json_header(); | ||
| 1352 | + fputs("{\"ok\":false,\"error\":\"source_unavailable\"}\n", stdout); | ||
| 1353 | + return 0; | ||
| 1354 | + } | ||
| 1355 | + | ||
| 1356 | + if (strcmp(action, "tail") == 0) { | ||
| 1357 | + ring_t ring; | ||
| 1358 | + int got; | ||
| 1359 | + int i; | ||
| 1360 | + | ||
| 1361 | + if (!ring_init(&ring, nlines)) { | ||
| 1362 | + json_header(); | ||
| 1363 | + fputs("{\"ok\":false,\"error\":\"out_of_memory\"}\n", stdout); | ||
| 1364 | + return 0; | ||
| 1365 | + } | ||
| 1366 | + got = collect_tail(s, nlines, &ring); | ||
| 1367 | + json_header(); | ||
| 1368 | + if (got < 0) { | ||
| 1369 | + fputs("{\"ok\":false,\"error\":\"unreadable_source\"," | ||
| 1370 | + "\"message\":\"the source could not be read on this node\"," | ||
| 1371 | + "\"src\":", stdout); | ||
| 1372 | + json_str(s->id); | ||
| 1373 | + fputs("}\n", stdout); | ||
| 1374 | + ring_free(&ring); | ||
| 1375 | + return 0; | ||
| 1376 | + } | ||
| 1377 | + fputs("{\"ok\":true,\"action\":\"tail\",\"plugin\":\"" PLUGIN_ID "\"," | ||
| 1378 | + "\"utc\":", stdout); | ||
| 1379 | + json_str(utc); | ||
| 1380 | + fputs(",\"src\":", stdout); json_str(s->id); | ||
| 1381 | + fputs(",\"label\":", stdout); json_str(s->label); | ||
| 1382 | + fputs(",\"kind\":", stdout); json_str(s->kind); | ||
| 1383 | + printf(",\"requested\":%d,\"count\":%d,\"entries\":[", nlines, ring.n); | ||
| 1384 | + for (i = 0; i < ring.n; i++) { | ||
| 1385 | + entry_t *e = ring_at(&ring, i); | ||
| 1386 | + if (i) fputc(',', stdout); | ||
| 1387 | + fputs("{\"ts\":", stdout); json_str(e->ts); | ||
| 1388 | + fputs(",\"unit\":", stdout); json_str(e->unit); | ||
| 1389 | + fputs(",\"sev\":", stdout); json_str(sev_name(e->sev)); | ||
| 1390 | + fputs(",\"text\":", stdout); json_str(e->text); | ||
| 1391 | + fputc('}', stdout); | ||
| 1392 | + } | ||
| 1393 | + fputs("]}\n", stdout); | ||
| 1394 | + ring_free(&ring); | ||
| 1395 | + return 0; | ||
| 1396 | + } | ||
| 1397 | + | ||
| 1398 | + /* search */ | ||
| 1399 | + { | ||
| 1400 | + list_t hits; | ||
| 1401 | + int scanned; | ||
| 1402 | + int i; | ||
| 1403 | + | ||
| 1404 | + if (!q[0]) { | ||
| 1405 | + json_header(); | ||
| 1406 | + fputs("{\"ok\":false,\"error\":\"missing_query\"," | ||
| 1407 | + "\"message\":\"action=search needs q=<text>\"}\n", stdout); | ||
| 1408 | + return 0; | ||
| 1409 | + } | ||
| 1410 | + if (!list_init(&hits, SEARCH_HITS_MAX)) { | ||
| 1411 | + json_header(); | ||
| 1412 | + fputs("{\"ok\":false,\"error\":\"out_of_memory\"}\n", stdout); | ||
| 1413 | + return 0; | ||
| 1414 | + } | ||
| 1415 | + scanned = collect_search(s, q, &hits); | ||
| 1416 | + json_header(); | ||
| 1417 | + if (scanned < 0) { | ||
| 1418 | + fputs("{\"ok\":false,\"error\":\"unreadable_source\"," | ||
| 1419 | + "\"src\":", stdout); | ||
| 1420 | + json_str(s->id); | ||
| 1421 | + fputs("}\n", stdout); | ||
| 1422 | + list_free(&hits); | ||
| 1423 | + return 0; | ||
| 1424 | + } | ||
| 1425 | + fputs("{\"ok\":true,\"action\":\"search\",\"plugin\":\"" PLUGIN_ID "\"," | ||
| 1426 | + "\"utc\":", stdout); | ||
| 1427 | + json_str(utc); | ||
| 1428 | + fputs(",\"src\":", stdout); json_str(s->id); | ||
| 1429 | + fputs(",\"label\":", stdout); json_str(s->label); | ||
| 1430 | + fputs(",\"q\":", stdout); json_str(q); | ||
| 1431 | + printf(",\"scanned\":%d,\"count\":%d,\"max\":%d,\"truncated\":%s,\"hits\":[", | ||
| 1432 | + scanned, hits.n, SEARCH_HITS_MAX, | ||
| 1433 | + hits.n >= SEARCH_HITS_MAX ? "true" : "false"); | ||
| 1434 | + for (i = 0; i < hits.n; i++) { | ||
| 1435 | + if (i) fputc(',', stdout); | ||
| 1436 | + fputs("{\"ts\":", stdout); json_str(hits.v[i].ts); | ||
| 1437 | + fputs(",\"unit\":", stdout); json_str(hits.v[i].unit); | ||
| 1438 | + fputs(",\"sev\":", stdout); json_str(sev_name(hits.v[i].sev)); | ||
| 1439 | + fputs(",\"text\":", stdout); json_str(hits.v[i].text); | ||
| 1440 | + fputc('}', stdout); | ||
| 1441 | + } | ||
| 1442 | + fputs("]}\n", stdout); | ||
| 1443 | + list_free(&hits); | ||
| 1444 | + return 0; | ||
| 1445 | + } | ||
| 1446 | + } | ||
| 1447 | +} | ||
| 1448 | + | ||
| 1449 | +/* ------------------------------------------------------------------ */ | ||
| 1450 | +/* HTML UI */ | ||
| 1451 | +/* ------------------------------------------------------------------ */ | ||
| 1452 | + | ||
| 1453 | +static int mode_html(int embed) | ||
| 1454 | +{ | ||
| 1455 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | ||
| 1456 | + "Cache-Control: no-store\r\n" | ||
| 1457 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 1458 | + | ||
| 1459 | + fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>" | ||
| 1460 | + "<meta name='viewport' content='width=device-width,initial-scale=1'>" | ||
| 1461 | + "<title>logs</title>", stdout); | ||
| 1462 | + | ||
| 1463 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS, stdout); | ||
| 1464 | + fputs( | ||
| 1465 | +"*{box-sizing:border-box}" | ||
| 1466 | +"html,body{height:100%}" | ||
| 1467 | +"body{margin:0;padding:14px;background:var(--bg);color:var(--text);" | ||
| 1468 | + "font-family:var(--font);font-size:13px;line-height:1.5;-webkit-font-smoothing:antialiased}" | ||
| 1469 | +".wrap{max-width:1280px;margin:0 auto;display:flex;flex-direction:column;" | ||
| 1470 | + "gap:12px;min-height:100%}" | ||
| 1471 | +".top{display:flex;align-items:center;gap:10px;flex-wrap:wrap}" | ||
| 1472 | +".title{font-size:19px;font-weight:700;margin:0;letter-spacing:-.01em}" | ||
| 1473 | +".sub{color:var(--muted);font-size:12px;font-family:var(--mono);overflow:hidden;" | ||
| 1474 | + "text-overflow:ellipsis;white-space:nowrap;max-width:46ch}" | ||
| 1475 | +".spacer{flex:1}" | ||
| 1476 | +".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;" | ||
| 1477 | + "background:var(--surface2);color:var(--muted);border:1px solid var(--line);white-space:nowrap}" | ||
| 1478 | +".pill.live{color:var(--ok);border-color:rgba(48,209,88,.4)}" | ||
| 1479 | +".pill.paused{color:var(--warn);border-color:rgba(255,214,10,.4)}" | ||
| 1480 | +"select,input,button{font-family:inherit;font-size:13px;color:var(--text)}" | ||
| 1481 | +"select,input{background:var(--input-bg);border:1px solid var(--line);" | ||
| 1482 | + "border-radius:9px;padding:7px 11px;min-width:0}" | ||
| 1483 | +"select{max-width:100%}" | ||
| 1484 | +"input[type=text]{flex:1;min-width:120px;font-family:var(--mono);font-size:12px}" | ||
| 1485 | +"input:focus,select:focus{outline:2px solid var(--accent);outline-offset:-1px}" | ||
| 1486 | +"button{background:var(--accent);color:#fff;border:0;border-radius:999px;" | ||
| 1487 | + "padding:7px 14px;font-weight:600;cursor:pointer;white-space:nowrap}" | ||
| 1488 | +"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" | ||
| 1489 | +"button.on{background:var(--accent);color:#fff;border-color:transparent}" | ||
| 1490 | +"button.sm{padding:5px 11px;font-size:12px}" | ||
| 1491 | +"button:active{transform:scale(.98)}" | ||
| 1492 | +".bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" | ||
| 1493 | +".seg{display:inline-flex;gap:3px;background:var(--surface2);border:1px solid var(--line);" | ||
| 1494 | + "border-radius:999px;padding:3px;flex-wrap:nowrap}" | ||
| 1495 | +".seg button{background:transparent;color:var(--muted);border:0;padding:4px 10px;font-size:12px}" | ||
| 1496 | +".seg button.on{background:var(--accent);color:#fff}" | ||
| 1497 | +".panel{background:var(--surface);border:1px solid var(--line);border-radius:14px;" | ||
| 1498 | + "display:flex;flex-direction:column;min-height:0;flex:1;overflow:hidden}" | ||
| 1499 | +".loghead{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:10px 12px;" | ||
| 1500 | + "border-bottom:1px solid var(--line)}" | ||
| 1501 | +".log{flex:1;overflow:auto;padding:6px 0;min-height:260px;max-height:calc(100vh - 260px);" | ||
| 1502 | + "font-family:var(--mono);font-size:12px;line-height:1.55}" | ||
| 1503 | +".log.wrap .tx{white-space:pre-wrap;word-break:break-word}" | ||
| 1504 | +".ln{display:grid;grid-template-columns:112px minmax(0,1fr) 132px;gap:10px;" | ||
| 1505 | + "padding:3px 12px;border-left:3px solid transparent;align-items:baseline}" | ||
| 1506 | +".ln:hover{background:var(--surface-hover)}" | ||
| 1507 | +".ln .ts{color:var(--muted);font-size:11px;white-space:nowrap;overflow:hidden;" | ||
| 1508 | + "text-overflow:ellipsis}" | ||
| 1509 | +".ln .un{color:var(--muted);font-size:11px;white-space:nowrap;overflow:hidden;" | ||
| 1510 | + "text-overflow:ellipsis;text-align:right}" | ||
| 1511 | +".ln .tx{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}" | ||
| 1512 | +".ln.err{border-left-color:var(--red)}" | ||
| 1513 | +".ln.err .tx{color:var(--red)}" | ||
| 1514 | +".ln.warn{border-left-color:var(--warn)}" | ||
| 1515 | +".ln.warn .tx{color:var(--warn)}" | ||
| 1516 | +".ln.info{border-left-color:transparent}" | ||
| 1517 | +".ln mark{background:rgba(255,214,10,.28);color:inherit;border-radius:3px;padding:0 1px}" | ||
| 1518 | +".empty{color:var(--muted);padding:24px 14px;text-align:center;font-size:13px;" | ||
| 1519 | + "font-family:var(--font)}" | ||
| 1520 | +".foot{display:flex;gap:10px;align-items:center;flex-wrap:wrap;padding:8px 12px;" | ||
| 1521 | + "border-top:1px solid var(--line);color:var(--muted);font-size:11px;font-family:var(--mono)}" | ||
| 1522 | +".hide{display:none!important}" | ||
| 1523 | +".muted{color:var(--muted)}" | ||
| 1524 | +"@media(max-width:760px){" | ||
| 1525 | + ".ln{grid-template-columns:96px minmax(0,1fr);gap:8px}" | ||
| 1526 | + ".ln .un{display:none}" | ||
| 1527 | + ".log{max-height:calc(100vh - 330px)}" | ||
| 1528 | + "#q{flex:1 1 100%}" | ||
| 1529 | +"}" | ||
| 1530 | +"@media(max-width:480px){" | ||
| 1531 | + "body{padding:10px}" | ||
| 1532 | + ".title{font-size:17px}" | ||
| 1533 | + ".sub{max-width:26ch}" | ||
| 1534 | + ".seg button{padding:4px 8px}" | ||
| 1535 | +"}", stdout); | ||
| 1536 | + | ||
| 1537 | + fputs("</style></head>" SX_BOT_THEME_HANDOFF "<body><div class='wrap'>", stdout); | ||
| 1538 | + | ||
| 1539 | + if (!embed) { | ||
| 1540 | + fputs("<div class='top'><a href='/' style='color:var(--accent);" | ||
| 1541 | + "text-decoration:none;font-weight:600'>← Back to Bot</a></div>", stdout); | ||
| 1542 | + } | ||
| 1543 | + | ||
| 1544 | + fputs("<div class='top'>" | ||
| 1545 | + "<h1 class='title'>logs</h1>" | ||
| 1546 | + "<span class='sub' id='pSrc'>—</span>" | ||
| 1547 | + "<span class='spacer'></span>" | ||
| 1548 | + "<span class='pill paused' id='pState'>paused</span>" | ||
| 1549 | + "<button class='ghost sm embed-hide' id='btnTheme' type='button'>Theme</button>" | ||
| 1550 | + "</div>", stdout); | ||
| 1551 | + | ||
| 1552 | + /* source + controls */ | ||
| 1553 | + fputs("<div class='panel'><div class='loghead'>" | ||
| 1554 | + "<select id='srcSel' title='Log source'><option value=''>—</option></select>" | ||
| 1555 | + "<div class='seg' id='segLines'>" | ||
| 1556 | + "<button type='button' data-n='100'>100</button>" | ||
| 1557 | + "<button type='button' data-n='200' class='on'>200</button>" | ||
| 1558 | + "<button type='button' data-n='500'>500</button>" | ||
| 1559 | + "<button type='button' data-n='2000'>2000</button>" | ||
| 1560 | + "</div>" | ||
| 1561 | + "<button type='button' id='btnFollow' class='on'>Follow</button>" | ||
| 1562 | + "<input type='text' id='q' placeholder='Search in this source'>" | ||
| 1563 | + "<button type='button' id='btnSearch' class='sm'>Search</button>" | ||
| 1564 | + "<button type='button' id='btnWrap' class='ghost sm'>Wrap</button>" | ||
| 1565 | + "<button type='button' id='btnCopy' class='ghost sm'>Copy</button>" | ||
| 1566 | + "<button type='button' id='btnReload' class='ghost sm'>Reload</button>" | ||
| 1567 | + "</div>", stdout); | ||
| 1568 | + | ||
| 1569 | + fputs("<div class='log' id='log'><div class='empty' id='empty'>Loading sources…</div></div>", stdout); | ||
| 1570 | + fputs("<div class='foot'>" | ||
| 1571 | + "<span id='fCount'>0 entries</span>" | ||
| 1572 | + "<span class='spacer'></span>" | ||
| 1573 | + "<span id='fNote'>local read only · zero network</span>" | ||
| 1574 | + "</div></div>", stdout); | ||
| 1575 | + | ||
| 1576 | + fputs("<div class='foot' style='border:0;padding:0'><span class='muted'>" | ||
| 1577 | + "Reads an allowlist of local log files and the local system journal. " | ||
| 1578 | + "Every source is read-only; nothing is written, and no request leaves this node." | ||
| 1579 | + "</span></div>", stdout); | ||
| 1580 | + | ||
| 1581 | + /* ---------------- script ---------------- */ | ||
| 1582 | + fputs("<script>\n" | ||
| 1583 | +"(function(){\n" | ||
| 1584 | +" var qs = new URLSearchParams(location.search);\n" | ||
| 1585 | +" var HUB = qs.get('plugin') || '';\n" | ||
| 1586 | +" var node = qs.get('node') || '';\n" | ||
| 1587 | +" var sid = qs.get('id') || '';\n" | ||
| 1588 | +" var pwd = qs.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" | ||
| 1589 | +" localStorage.getItem('bot_active_pwd') || '';\n" | ||
| 1590 | +" var SRC = '', LINES = 200, FOLLOW = true, TIMER = null, BUSY = false;\n" | ||
| 1591 | +" var LAST = [], QUERY = '', MODE = 'tail';\n" | ||
| 1592 | +"\n" | ||
| 1593 | +" /* Two routes: opened through the hub -> call the hub proxy back;\n" | ||
| 1594 | +" opened directly on the node -> the plugin IS the route. */\n" | ||
| 1595 | +" function base(){ return HUB ? '/plugins?plugin=' + HUB : '/plugin_logs'; }\n" | ||
| 1596 | +" function withCtx(u){\n" | ||
| 1597 | +" if (node) u += '&node=' + encodeURIComponent(node);\n" | ||
| 1598 | +" if (sid) u += '&id=' + encodeURIComponent(sid);\n" | ||
| 1599 | +" if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n" | ||
| 1600 | +" return u;\n" | ||
| 1601 | +" }\n" | ||
| 1602 | +" function hdr(){ return pwd ? {'X-Bot-Password': pwd} : {}; }\n" | ||
| 1603 | +" function $(i){ return document.getElementById(i); }\n" | ||
| 1604 | +" function el(t,c,x){ var e=document.createElement(t); if(c) e.className=c;\n" | ||
| 1605 | +" if (x!==undefined && x!==null) e.textContent=String(x); return e; }\n" | ||
| 1606 | +" function api(extra){\n" | ||
| 1607 | +" return fetch(withCtx(base() + '?' + extra), {headers:hdr(), cache:'no-store'})\n" | ||
| 1608 | +" .then(function(r){ return r.json(); });\n" | ||
| 1609 | +" }\n" | ||
| 1610 | +"\n" | ||
| 1611 | +" function state(txt, cls){\n" | ||
| 1612 | +" var p = $('pState'); p.textContent = txt; p.className = 'pill ' + (cls||'paused');\n" | ||
| 1613 | +" }\n" | ||
| 1614 | +"\n" | ||
| 1615 | +" function humanSize(n){\n" | ||
| 1616 | +" if (!n) return '';\n" | ||
| 1617 | +" var u=['B','KB','MB','GB'], i=0, v=n;\n" | ||
| 1618 | +" while (v >= 1024 && i < u.length-1){ v/=1024; i++; }\n" | ||
| 1619 | +" return (i===0 ? v : v.toFixed(1)) + ' ' + u[i];\n" | ||
| 1620 | +" }\n" | ||
| 1621 | +"\n" | ||
| 1622 | +" function loadSources(){\n" | ||
| 1623 | +" return api('action=sources').then(function(d){\n" | ||
| 1624 | +" var sel = $('srcSel');\n" | ||
| 1625 | +" sel.innerHTML = '';\n" | ||
| 1626 | +" if (!d || d.ok === false){ $('empty').textContent = 'Could not list sources.'; return; }\n" | ||
| 1627 | +" var groups = [['journal','Journal'],['file','Log files'],['event','Event logs']];\n" | ||
| 1628 | +" var seen = {};\n" | ||
| 1629 | +" for (var g=0; g<groups.length; g++){\n" | ||
| 1630 | +" var kind = groups[g][0], any = false, og = null;\n" | ||
| 1631 | +" for (var i=0;i<d.sources.length;i++){\n" | ||
| 1632 | +" var s = d.sources[i];\n" | ||
| 1633 | +" if (s.kind !== kind) continue;\n" | ||
| 1634 | +" if (!og){ og = document.createElement('optgroup'); og.label = groups[g][1]; }\n" | ||
| 1635 | +" var o = document.createElement('option');\n" | ||
| 1636 | +" o.value = s.id;\n" | ||
| 1637 | +" o.textContent = s.label + (s.size ? ' (' + humanSize(s.size) + ')' : '');\n" | ||
| 1638 | +" og.appendChild(o); any = true;\n" | ||
| 1639 | +" }\n" | ||
| 1640 | +" if (any) sel.appendChild(og);\n" | ||
| 1641 | +" }\n" | ||
| 1642 | +" if (d.truncated) $('fNote').textContent = 'source list truncated · local read only';\n" | ||
| 1643 | +" /* keep the previous selection when it still exists */\n" | ||
| 1644 | +" var want = SRC;\n" | ||
| 1645 | +" if (!want){\n" | ||
| 1646 | +" for (var k=0;k<d.sources.length;k++){ want = d.sources[k].id; break; }\n" | ||
| 1647 | +" }\n" | ||
| 1648 | +" if (want){ sel.value = want; SRC = want; }\n" | ||
| 1649 | +" if (!d.sources.length){\n" | ||
| 1650 | +" $('empty').textContent = 'No readable log sources on this node.';\n" | ||
| 1651 | +" }\n" | ||
| 1652 | +" return d;\n" | ||
| 1653 | +" }).catch(function(e){ $('empty').textContent = 'Request failed: ' + e; });\n" | ||
| 1654 | +" }\n" | ||
| 1655 | +"\n" | ||
| 1656 | +" function highlight(text, q){\n" | ||
| 1657 | +" var frag = document.createDocumentFragment();\n" | ||
| 1658 | +" if (!q) { frag.appendChild(document.createTextNode(text)); return frag; }\n" | ||
| 1659 | +" var hay = text.toLowerCase(), need = q.toLowerCase(), at = 0;\n" | ||
| 1660 | +" while (true){\n" | ||
| 1661 | +" var i = hay.indexOf(need, at);\n" | ||
| 1662 | +" if (i < 0){ frag.appendChild(document.createTextNode(text.slice(at))); break; }\n" | ||
| 1663 | +" if (i > at) frag.appendChild(document.createTextNode(text.slice(at, i)));\n" | ||
| 1664 | +" var m = document.createElement('mark');\n" | ||
| 1665 | +" m.textContent = text.slice(i, i + q.length);\n" | ||
| 1666 | +" frag.appendChild(m);\n" | ||
| 1667 | +" at = i + q.length;\n" | ||
| 1668 | +" }\n" | ||
| 1669 | +" return frag;\n" | ||
| 1670 | +" }\n" | ||
| 1671 | +"\n" | ||
| 1672 | +" function renderRows(rows, q){\n" | ||
| 1673 | +" var box = $('log');\n" | ||
| 1674 | +" box.innerHTML = '';\n" | ||
| 1675 | +" if (!rows || !rows.length){\n" | ||
| 1676 | +" var e = el('div','empty', MODE === 'search'\n" | ||
| 1677 | +" ? 'No matches in the scanned window.'\n" | ||
| 1678 | +" : 'This source produced no entries.');\n" | ||
| 1679 | +" box.appendChild(e);\n" | ||
| 1680 | +" $('fCount').textContent = '0 entries';\n" | ||
| 1681 | +" return;\n" | ||
| 1682 | +" }\n" | ||
| 1683 | +" var frag = document.createDocumentFragment();\n" | ||
| 1684 | +" for (var i=0;i<rows.length;i++){\n" | ||
| 1685 | +" var r = rows[i];\n" | ||
| 1686 | +" var ln = el('div', 'ln ' + (r.sev || 'info'));\n" | ||
| 1687 | +" ln.appendChild(el('span','ts', r.ts || ''));\n" | ||
| 1688 | +" var tx = el('span','tx');\n" | ||
| 1689 | +" tx.appendChild(highlight(r.text === undefined ? '' : r.text, q));\n" | ||
| 1690 | +" ln.appendChild(tx);\n" | ||
| 1691 | +" ln.appendChild(el('span','un', r.unit || ''));\n" | ||
| 1692 | +" frag.appendChild(ln);\n" | ||
| 1693 | +" }\n" | ||
| 1694 | +" box.appendChild(frag);\n" | ||
| 1695 | +" $('fCount').textContent = rows.length + ' entries';\n" | ||
| 1696 | +" }\n" | ||
| 1697 | +"\n" | ||
| 1698 | +" function scrollBottom(){ var b = $('log'); b.scrollTop = b.scrollHeight; }\n" | ||
| 1699 | +"\n" | ||
| 1700 | +" function tail(keepScroll){\n" | ||
| 1701 | +" if (!SRC) return Promise.resolve();\n" | ||
| 1702 | +" var atBottom = true, b = $('log');\n" | ||
| 1703 | +" atBottom = (b.scrollTop + b.clientHeight) >= (b.scrollHeight - 24);\n" | ||
| 1704 | +" return api('action=tail&lines=' + LINES + '&src=' + encodeURIComponent(SRC))\n" | ||
| 1705 | +" .then(function(d){\n" | ||
| 1706 | +" if (!d || d.ok === false){\n" | ||
| 1707 | +" state('error','paused');\n" | ||
| 1708 | +" $('empty').textContent = (d && d.message) || (d && d.error) || 'unreadable source';\n" | ||
| 1709 | +" $('log').innerHTML = '';\n" | ||
| 1710 | +" $('log').appendChild(el('div','empty',(d && d.message) || 'unreadable source'));\n" | ||
| 1711 | +" $('fCount').textContent = '0 entries';\n" | ||
| 1712 | +" return;\n" | ||
| 1713 | +" }\n" | ||
| 1714 | +" MODE = 'tail';\n" | ||
| 1715 | +" LAST = d.entries || [];\n" | ||
| 1716 | +" $('pSrc').textContent = d.label || d.src || '';\n" | ||
| 1717 | +" renderRows(LAST, '');\n" | ||
| 1718 | +" if (!keepScroll && atBottom) scrollBottom();\n" | ||
| 1719 | +" state(FOLLOW ? 'live 3s' : 'paused', FOLLOW ? 'live' : 'paused');\n" | ||
| 1720 | +" })\n" | ||
| 1721 | +" .catch(function(e){ state('offline','paused'); $('fNote').textContent = 'request failed'; });\n" | ||
| 1722 | +" }\n" | ||
| 1723 | +"\n" | ||
| 1724 | +" function search(){\n" | ||
| 1725 | +" if (!SRC || !QUERY){ tail(); return Promise.resolve(); }\n" | ||
| 1726 | +" return api('action=search&src=' + encodeURIComponent(SRC) +\n" | ||
| 1727 | +" '&q=' + encodeURIComponent(QUERY))\n" | ||
| 1728 | +" .then(function(d){\n" | ||
| 1729 | +" if (!d || d.ok === false){\n" | ||
| 1730 | +" $('log').innerHTML = '';\n" | ||
| 1731 | +" $('log').appendChild(el('div','empty',(d && (d.message||d.error)) || 'search failed'));\n" | ||
| 1732 | +" return;\n" | ||
| 1733 | +" }\n" | ||
| 1734 | +" MODE = 'search';\n" | ||
| 1735 | +" LAST = d.hits || [];\n" | ||
| 1736 | +" renderRows(LAST, QUERY);\n" | ||
| 1737 | +" $('fCount').textContent = LAST.length + ' hits of ' + d.scanned + ' scanned' +\n" | ||
| 1738 | +" (d.truncated ? ' (capped)' : '');\n" | ||
| 1739 | +" state('search','paused');\n" | ||
| 1740 | +" })\n" | ||
| 1741 | +" .catch(function(e){ $('fNote').textContent = 'search failed'; });\n" | ||
| 1742 | +" }\n" | ||
| 1743 | +"\n" | ||
| 1744 | +" function schedule(){\n" | ||
| 1745 | +" if (TIMER){ clearInterval(TIMER); TIMER = null; }\n" | ||
| 1746 | +" if (FOLLOW && MODE === 'tail' && document.visibilityState === 'visible'){\n" | ||
| 1747 | +" TIMER = setInterval(function(){ if (!BUSY){ BUSY = true; tail().then(function(){ BUSY = false; }); } }, 3000);\n" | ||
| 1748 | +" state('live 3s','live');\n" | ||
| 1749 | +" } else {\n" | ||
| 1750 | +" state(MODE === 'search' ? 'search' : 'paused', 'paused');\n" | ||
| 1751 | +" }\n" | ||
| 1752 | +" }\n" | ||
| 1753 | +"\n" | ||
| 1754 | +" function refresh(){\n" | ||
| 1755 | +" if (MODE === 'search' && QUERY) search(); else tail();\n" | ||
| 1756 | +" schedule();\n" | ||
| 1757 | +" }\n" | ||
| 1758 | +"\n" | ||
| 1759 | +" /* ---- wiring ---- */\n" | ||
| 1760 | +" $('srcSel').addEventListener('change', function(){\n" | ||
| 1761 | +" SRC = this.value; MODE = 'tail'; QUERY = $('q').value = ''; refresh();\n" | ||
| 1762 | +" });\n" | ||
| 1763 | +" Array.prototype.forEach.call(document.querySelectorAll('#segLines button'), function(b){\n" | ||
| 1764 | +" b.addEventListener('click', function(){\n" | ||
| 1765 | +" Array.prototype.forEach.call(document.querySelectorAll('#segLines button'),\n" | ||
| 1766 | +" function(x){ x.classList.remove('on'); });\n" | ||
| 1767 | +" b.classList.add('on');\n" | ||
| 1768 | +" LINES = parseInt(b.getAttribute('data-n'), 10) || 200;\n" | ||
| 1769 | +" refresh();\n" | ||
| 1770 | +" });\n" | ||
| 1771 | +" });\n" | ||
| 1772 | +" $('btnFollow').addEventListener('click', function(){\n" | ||
| 1773 | +" FOLLOW = !FOLLOW;\n" | ||
| 1774 | +" this.classList.toggle('on', FOLLOW);\n" | ||
| 1775 | +" this.textContent = FOLLOW ? 'Follow' : 'Paused';\n" | ||
| 1776 | +" if (MODE === 'search' && FOLLOW) MODE = 'tail';\n" | ||
| 1777 | +" refresh();\n" | ||
| 1778 | +" });\n" | ||
| 1779 | +" $('btnSearch').addEventListener('click', function(){\n" | ||
| 1780 | +" QUERY = $('q').value.trim();\n" | ||
| 1781 | +" if (!QUERY){ MODE = 'tail'; tail(); schedule(); return; }\n" | ||
| 1782 | +" MODE = 'search'; search(); schedule();\n" | ||
| 1783 | +" });\n" | ||
| 1784 | +" $('q').addEventListener('keydown', function(e){ if (e.key === 'Enter') $('btnSearch').click(); });\n" | ||
| 1785 | +" $('btnWrap').addEventListener('click', function(){\n" | ||
| 1786 | +" var w = $('log').classList.toggle('wrap');\n" | ||
| 1787 | +" this.classList.toggle('on', w);\n" | ||
| 1788 | +" });\n" | ||
| 1789 | +" $('btnCopy').addEventListener('click', function(){\n" | ||
| 1790 | +" var out = [];\n" | ||
| 1791 | +" for (var i=0;i<LAST.length;i++){\n" | ||
| 1792 | +" var r = LAST[i];\n" | ||
| 1793 | +" out.push((r.ts ? r.ts + ' ' : '') + (r.unit ? r.unit + ': ' : '') + (r.text || ''));\n" | ||
| 1794 | +" }\n" | ||
| 1795 | +" var txt = out.join('\\n');\n" | ||
| 1796 | +" var btn = this;\n" | ||
| 1797 | +" function done(ok){ btn.textContent = ok ? 'Copied' : 'Copy failed';\n" | ||
| 1798 | +" setTimeout(function(){ btn.textContent = 'Copy'; }, 1400); }\n" | ||
| 1799 | +" if (navigator.clipboard && navigator.clipboard.writeText){\n" | ||
| 1800 | +" navigator.clipboard.writeText(txt).then(function(){ done(true); },\n" | ||
| 1801 | +" function(){ done(false); });\n" | ||
| 1802 | +" } else {\n" | ||
| 1803 | +" var ta = document.createElement('textarea');\n" | ||
| 1804 | +" ta.value = txt; document.body.appendChild(ta); ta.select();\n" | ||
| 1805 | +" try { done(document.execCommand('copy')); } catch(e){ done(false); }\n" | ||
| 1806 | +" document.body.removeChild(ta);\n" | ||
| 1807 | +" }\n" | ||
| 1808 | +" });\n" | ||
| 1809 | +" $('btnReload').addEventListener('click', function(){ loadSources().then(refresh); });\n" | ||
| 1810 | +" $('btnTheme').addEventListener('click', function(){\n" | ||
| 1811 | +" if (window.sxApplyTheme) window.sxApplyTheme(window.sxTheme && window.sxTheme() === 'dark' ? 'light' : 'dark');\n" | ||
| 1812 | +" });\n" | ||
| 1813 | +"\n" | ||
| 1814 | +" document.addEventListener('visibilitychange', function(){\n" | ||
| 1815 | +" if (document.visibilityState === 'visible'){ refresh(); }\n" | ||
| 1816 | +" else { schedule(); }\n" | ||
| 1817 | +" });\n" | ||
| 1818 | +" window.addEventListener('bot-theme', function(){});\n" | ||
| 1819 | +"\n" | ||
| 1820 | +" loadSources().then(refresh);\n" | ||
| 1821 | +"})();\n" | ||
| 1822 | +"</script></div></body></html>\n", stdout); | ||
| 1823 | + | ||
| 1824 | + return 0; | ||
| 1825 | +} | ||
| 1826 | + | ||
| 1827 | +/* ------------------------------------------------------------------ */ | ||
| 1828 | +/* Entry point */ | ||
| 1829 | +/* ------------------------------------------------------------------ */ | ||
| 1830 | + | ||
| 1831 | +int main(int argc, char **argv) | ||
| 1832 | +{ | ||
| 1833 | + const char *qs; | ||
| 1834 | + int i; | ||
| 1835 | + | ||
| 1836 | + for (i = 1; i < argc; i++) { | ||
| 1837 | + if (strcmp(argv[i], "--meta") == 0) | ||
| 1838 | + return mode_meta(); | ||
| 1839 | + if (strcmp(argv[i], "--version") == 0) { | ||
| 1840 | + printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); | ||
| 1841 | + return 0; | ||
| 1842 | + } | ||
| 1843 | + if (strcmp(argv[i], "--help") == 0) { | ||
| 1844 | + printf("usage: %s [--meta] [--version] [--help]\n" | ||
| 1845 | + " CGI mode reads QUERY_STRING:\n" | ||
| 1846 | + " ?action=sources readable log sources\n" | ||
| 1847 | + " ?action=tail&src=<id>&lines=<N> last N entries of a source\n" | ||
| 1848 | + " ?action=search&src=<id>&q=<text> case-insensitive substring search\n" | ||
| 1849 | + " ?action=units systemd units with journal entries\n" | ||
| 1850 | + " ?action=info plugin info\n" | ||
| 1851 | + " (no action) HTML log viewer\n", PLUGIN_ID); | ||
| 1852 | + return 0; | ||
| 1853 | + } | ||
| 1854 | + } | ||
| 1855 | + | ||
| 1856 | + if (getenv("SX_PLUGIN_META")) | ||
| 1857 | + return mode_meta(); | ||
| 1858 | + | ||
| 1859 | + require_node_auth(); | ||
| 1860 | + | ||
| 1861 | + qs = getenv("QUERY_STRING"); | ||
| 1862 | + if (!qs) qs = ""; | ||
| 1863 | + | ||
| 1864 | + if (strstr(qs, "action=") || strstr(qs, "format=json")) | ||
| 1865 | + return mode_json(qs); | ||
| 1866 | + | ||
| 1867 | + { | ||
| 1868 | + char embedv[16]; | ||
| 1869 | + embedv[0] = '\0'; | ||
| 1870 | + if (get_query_val(qs, "embed", embedv, sizeof(embedv))) | ||
| 1871 | + return mode_html(strcmp(embedv, "1") == 0 || strcmp(embedv, "true") == 0); | ||
| 1872 | + } | ||
| 1873 | + return mode_html(0); | ||
| 1874 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..11bc950 | index 0000000..11bc950 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/e2e.py | +++ b/tests/e2e.py | ||
| @@ -0,0 +1,285 @@ | @@ -0,0 +1,285 @@ | ||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""tests/e2e.py - viewport and live-behaviour checks for the plugin_logs UI. | ||
| 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 in BOTH themes, and asserts | ||
| 6 | +there is no horizontal overflow, no console error, that the source picker is | ||
| 7 | +populated from action=sources, that a tail renders rows, that a search renders | ||
| 8 | +highlighted hits, and that the live/save/theme controls respond. | ||
| 9 | + | ||
| 10 | +Skips cleanly (exit 0) when Playwright is not installed, so `make test` stays | ||
| 11 | +offline-only. | ||
| 12 | + | ||
| 13 | + python3 tests/e2e.py # run if Playwright is available | ||
| 14 | + python3 tests/e2e.py --strict # exit 2 when Playwright is missing | ||
| 15 | +""" | ||
| 16 | + | ||
| 17 | +import argparse | ||
| 18 | +import http.server | ||
| 19 | +import os | ||
| 20 | +import shutil | ||
| 21 | +import subprocess | ||
| 22 | +import sys | ||
| 23 | +import tempfile | ||
| 24 | +import threading | ||
| 25 | +from urllib.parse import urlparse, parse_qs | ||
| 26 | + | ||
| 27 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 28 | +BIN = os.path.join(ROOT, "plugin_logs") | ||
| 29 | +VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] | ||
| 30 | +SHOTS = os.path.join(ROOT, "docs") | ||
| 31 | + | ||
| 32 | +FAILS = [] | ||
| 33 | +PASSES = [] | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +def ok(desc): | ||
| 37 | + PASSES.append(desc) | ||
| 38 | + print(" ok %s" % desc) | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def bad(desc, extra=""): | ||
| 42 | + FAILS.append(desc) | ||
| 43 | + print(" FAIL %s%s" % (desc, (" -- " + str(extra)) if extra else "")) | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def check(desc, cond, extra=""): | ||
| 47 | + ok(desc) if cond else bad(desc, extra) | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def prepare_fixtures(): | ||
| 51 | + """A journal fixture plus a fixture log tree, exported for the child.""" | ||
| 52 | + tmp = tempfile.mkdtemp(prefix="logs_e2e_") | ||
| 53 | + jfix = os.path.join(tmp, "journal.jsonl") | ||
| 54 | + with open(jfix, "w") as f: | ||
| 55 | + rows = [ | ||
| 56 | + ("1762923001000000", "3", "nginx.service", | ||
| 57 | + "upstream timed out while reading response header from upstream"), | ||
| 58 | + ("1762923002000000", "4", "systemd", "Some unit is deprecated"), | ||
| 59 | + ("1762923003000000", "6", "kernel", "eth0 link up, 1000 Mbps"), | ||
| 60 | + ("1762923004000000", "6", "sshd.service", | ||
| 61 | + "Accepted publickey for root from a trusted key"), | ||
| 62 | + ("1762923005000000", "2", "postgresql.service", | ||
| 63 | + "PANIC: could not locate a valid checkpoint record"), | ||
| 64 | + ] | ||
| 65 | + for ts, pri, unit, msg in rows: | ||
| 66 | + f.write('{"__REALTIME_TIMESTAMP":"%s","PRIORITY":"%s",' | ||
| 67 | + '"__CURSOR":"x","_SYSTEMD_UNIT":"%s","MESSAGE":"%s"}\n' | ||
| 68 | + % (ts, pri, unit, msg)) | ||
| 69 | + | ||
| 70 | + root = os.path.join(tmp, "fixtures") | ||
| 71 | + os.makedirs(os.path.join(root, "svc")) | ||
| 72 | + with open(os.path.join(root, "svc", "app.log"), "w") as f: | ||
| 73 | + for i in range(60): | ||
| 74 | + sev = "error" if i % 7 == 0 else ("warn" if i % 5 == 0 else "info") | ||
| 75 | + f.write("Nov 12 06:%02d:%02d host app[%d]: %s: request %d handled\n" | ||
| 76 | + % (i // 60 % 60, i % 60, 100 + i, sev, i)) | ||
| 77 | + | ||
| 78 | + env = dict(os.environ) | ||
| 79 | + env["SX_LOGS_JOURNAL_FIXTURE"] = jfix | ||
| 80 | + env["SX_LOGS_EXTRA_ROOT"] = root | ||
| 81 | + return tmp, env | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +class Handler(http.server.BaseHTTPRequestHandler): | ||
| 85 | + env = {} | ||
| 86 | + | ||
| 87 | + def do_GET(self): # noqa: N802 | ||
| 88 | + u = urlparse(self.path) | ||
| 89 | + qs = u.query | ||
| 90 | + # The UI appends ?pwd= for real nodes; this shim has no password set, | ||
| 91 | + # so just pass the query through. | ||
| 92 | + env = dict(self.env) | ||
| 93 | + env["QUERY_STRING"] = qs | ||
| 94 | + env["REQUEST_METHOD"] = "GET" | ||
| 95 | + env.pop("BOT_PASSWORD", None) | ||
| 96 | + if parse_qs(qs).get("theme"): | ||
| 97 | + pass | ||
| 98 | + out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout | ||
| 99 | + sep = out.find(b"\r\n\r\n") | ||
| 100 | + headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" | ||
| 101 | + body = out[sep + 4:] if sep >= 0 else out | ||
| 102 | + ctype = "text/html; charset=utf-8" | ||
| 103 | + for line in headers.splitlines(): | ||
| 104 | + if line.lower().startswith("content-type:"): | ||
| 105 | + ctype = line.split(":", 1)[1].strip() | ||
| 106 | + self.send_response(200) | ||
| 107 | + self.send_header("Content-Type", ctype) | ||
| 108 | + self.send_header("Cache-Control", "no-store") | ||
| 109 | + # no Content-Length from the plugin; the shim sets its own framing | ||
| 110 | + self.send_header("Content-Length", str(len(body))) | ||
| 111 | + self.end_headers() | ||
| 112 | + self.wfile.write(body) | ||
| 113 | + | ||
| 114 | + def log_message(self, *_a): | ||
| 115 | + pass | ||
| 116 | + | ||
| 117 | + | ||
| 118 | +def serve(env): | ||
| 119 | + Handler.env = env | ||
| 120 | + httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) | ||
| 121 | + t = threading.Thread(target=httpd.serve_forever, daemon=True) | ||
| 122 | + t.start() | ||
| 123 | + return httpd, httpd.server_address[1] | ||
| 124 | + | ||
| 125 | + | ||
| 126 | +def main(): | ||
| 127 | + ap = argparse.ArgumentParser() | ||
| 128 | + ap.add_argument("--strict", action="store_true") | ||
| 129 | + args = ap.parse_args() | ||
| 130 | + | ||
| 131 | + try: | ||
| 132 | + from playwright.sync_api import sync_playwright | ||
| 133 | + except Exception: | ||
| 134 | + print(" skip e2e (playwright not installed)") | ||
| 135 | + return 2 if args.strict else 0 | ||
| 136 | + | ||
| 137 | + if not os.path.exists(BIN): | ||
| 138 | + print(" FAIL plugin binary missing; run `make` first") | ||
| 139 | + return 1 | ||
| 140 | + | ||
| 141 | + tmp, env = prepare_fixtures() | ||
| 142 | + httpd, port = serve(env) | ||
| 143 | + base = "http://127.0.0.1:%d/" % port | ||
| 144 | + print("== e2e: %s ==" % base) | ||
| 145 | + | ||
| 146 | + os.makedirs(SHOTS, exist_ok=True) | ||
| 147 | + try: | ||
| 148 | + with sync_playwright() as p: | ||
| 149 | + browser = p.chromium.launch() | ||
| 150 | + for w, h in VIEWPORTS: | ||
| 151 | + for theme in ("dark", "light"): | ||
| 152 | + page = browser.new_page(viewport={"width": w, "height": h}, | ||
| 153 | + device_scale_factor=1) | ||
| 154 | + errors = [] | ||
| 155 | + page.on("console", lambda m: errors.append(m.text) | ||
| 156 | + if m.type == "error" else None) | ||
| 157 | + page.on("pageerror", lambda e: errors.append(str(e))) | ||
| 158 | + page.goto(base + "?theme=" + theme, wait_until="load") | ||
| 159 | + page.wait_for_timeout(900) | ||
| 160 | + | ||
| 161 | + tag = "%dx%d %s" % (w, h, theme) | ||
| 162 | + check("%s: no console errors" % tag, not errors, errors[:3]) | ||
| 163 | + | ||
| 164 | + # theme actually applied | ||
| 165 | + attr = page.evaluate( | ||
| 166 | + "document.documentElement.getAttribute('data-theme')") | ||
| 167 | + check("%s: theme applied" % tag, attr == theme, attr) | ||
| 168 | + | ||
| 169 | + # horizontal overflow | ||
| 170 | + over = page.evaluate( | ||
| 171 | + "() => Math.max(document.documentElement.scrollWidth," | ||
| 172 | + " document.body.scrollWidth) - window.innerWidth") | ||
| 173 | + check("%s: no horizontal overflow" % tag, over <= 1, over) | ||
| 174 | + | ||
| 175 | + # source picker populated from action=sources | ||
| 176 | + n = page.evaluate("document.querySelectorAll('#srcSel option').length") | ||
| 177 | + check("%s: source picker populated" % tag, n >= 2, n) | ||
| 178 | + | ||
| 179 | + # tail rendered rows | ||
| 180 | + rows = page.evaluate("document.querySelectorAll('#log .ln').length") | ||
| 181 | + check("%s: tail rendered entries" % tag, rows >= 5, rows) | ||
| 182 | + | ||
| 183 | + # severity colouring present at least once | ||
| 184 | + sev = page.evaluate( | ||
| 185 | + "document.querySelectorAll('#log .ln.err, #log .ln.warn').length") | ||
| 186 | + check("%s: severity classes applied" % tag, sev >= 1, sev) | ||
| 187 | + | ||
| 188 | + # no stray grid overflow inside the log | ||
| 189 | + clip = page.evaluate( | ||
| 190 | + "() => { var l=document.getElementById('log');" | ||
| 191 | + " return l.scrollWidth - l.clientWidth; }") | ||
| 192 | + check("%s: log body fits its own width" % tag, clip <= 2, clip) | ||
| 193 | + | ||
| 194 | + shot = os.path.join(SHOTS, "ui-%dx%d-%s.png" % (w, h, theme)) | ||
| 195 | + page.screenshot(path=shot, full_page=False) | ||
| 196 | + size = os.path.getsize(shot) | ||
| 197 | + check("%s: screenshot < 900 KB" % tag, size < 900 * 1024, size) | ||
| 198 | + | ||
| 199 | + page.close() | ||
| 200 | + | ||
| 201 | + # one deep behavioural run at the primary viewport | ||
| 202 | + page = browser.new_page(viewport={"width": 1440, "height": 900}) | ||
| 203 | + page.goto(base + "?theme=dark", wait_until="load") | ||
| 204 | + page.wait_for_timeout(800) | ||
| 205 | + | ||
| 206 | + # switch to the fixture app.log, which carries "error" lines | ||
| 207 | + page.evaluate( | ||
| 208 | + "() => { var sel = document.getElementById('srcSel');" | ||
| 209 | + " for (var i = 0; i < sel.options.length; i++) {" | ||
| 210 | + " if (sel.options[i].value.indexOf('app.log') >= 0) {" | ||
| 211 | + " sel.value = sel.options[i].value;" | ||
| 212 | + " sel.dispatchEvent(new Event('change')); return; } } }") | ||
| 213 | + page.wait_for_timeout(800) | ||
| 214 | + | ||
| 215 | + # search renders highlighted hits | ||
| 216 | + page.fill("#q", "error") | ||
| 217 | + page.click("#btnSearch") | ||
| 218 | + page.wait_for_timeout(900) | ||
| 219 | + marks = page.evaluate("document.querySelectorAll('#log mark').length") | ||
| 220 | + check("search renders highlighted hits", marks >= 1, marks) | ||
| 221 | + fcount = page.inner_text("#fCount") | ||
| 222 | + check("search reports hits and scanned count", | ||
| 223 | + "hits" in fcount and "scanned" in fcount, fcount) | ||
| 224 | + | ||
| 225 | + # wrap toggle widens the layout class | ||
| 226 | + page.click("#btnWrap") | ||
| 227 | + page.wait_for_timeout(150) | ||
| 228 | + wrap = page.evaluate("document.getElementById('log').classList.contains('wrap')") | ||
| 229 | + check("wrap toggle applies", wrap is True, wrap) | ||
| 230 | + page.click("#btnWrap") | ||
| 231 | + | ||
| 232 | + # clearing the query returns to tail | ||
| 233 | + page.fill("#q", "") | ||
| 234 | + page.click("#btnSearch") | ||
| 235 | + page.wait_for_timeout(700) | ||
| 236 | + rows = page.evaluate("document.querySelectorAll('#log .ln').length") | ||
| 237 | + check("empty query returns to tail", rows >= 5, rows) | ||
| 238 | + | ||
| 239 | + # follow toggle pauses the poller | ||
| 240 | + page.click("#btnFollow") | ||
| 241 | + page.wait_for_timeout(200) | ||
| 242 | + st = page.inner_text("#pState") | ||
| 243 | + check("follow toggle pauses", "paused" in st.lower(), st) | ||
| 244 | + page.click("#btnFollow") | ||
| 245 | + | ||
| 246 | + # line-count segment changes the request | ||
| 247 | + page.click("#segLines button[data-n='500']") | ||
| 248 | + page.wait_for_timeout(700) | ||
| 249 | + on = page.evaluate( | ||
| 250 | + "document.querySelector('#segLines button.on').getAttribute('data-n')") | ||
| 251 | + check("line-count segment switches", on == "500", on) | ||
| 252 | + | ||
| 253 | + # theme button flips the document | ||
| 254 | + before = page.evaluate("document.documentElement.getAttribute('data-theme')") | ||
| 255 | + page.click("#btnTheme") | ||
| 256 | + page.wait_for_timeout(200) | ||
| 257 | + after = page.evaluate("document.documentElement.getAttribute('data-theme')") | ||
| 258 | + check("theme button flips appearance", before != after, (before, after)) | ||
| 259 | + | ||
| 260 | + # embed mode hides the back-link only | ||
| 261 | + page.goto(base + "?embed=1&theme=dark", wait_until="load") | ||
| 262 | + page.wait_for_timeout(600) | ||
| 263 | + body = page.inner_text("body") | ||
| 264 | + check("embed=1 hides the back-link", "Back to Bot" not in body) | ||
| 265 | + rows = page.evaluate("document.querySelectorAll('#log .ln').length") | ||
| 266 | + check("embed=1 still renders entries", rows >= 5, rows) | ||
| 267 | + | ||
| 268 | + page.close() | ||
| 269 | + browser.close() | ||
| 270 | + finally: | ||
| 271 | + httpd.shutdown() | ||
| 272 | + shutil.rmtree(tmp, ignore_errors=True) | ||
| 273 | + | ||
| 274 | + print("\n== summary ==") | ||
| 275 | + print(" passed: %d" % len(PASSES)) | ||
| 276 | + print(" failed: %d" % len(FAILS)) | ||
| 277 | + if FAILS: | ||
| 278 | + print(" RESULT: FAILED") | ||
| 279 | + return 1 | ||
| 280 | + print(" RESULT: ALL PASSED") | ||
| 281 | + return 0 | ||
| 282 | + | ||
| 283 | + | ||
| 284 | +if __name__ == "__main__": | ||
| 285 | + sys.exit(main()) |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..6281a98 | index 0000000..6281a98 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/run.sh | +++ b/tests/run.sh | ||
| @@ -0,0 +1,432 @@ | @@ -0,0 +1,432 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/run.sh - offline checks for plugin_logs across all 3 modes. | ||
| 3 | +# | ||
| 4 | +# Runs against ./plugin_logs (native build) on the live machine. Journal output | ||
| 5 | +# is replayed from a captured fixture so the parser is tested on the real | ||
| 6 | +# `journalctl -o json` layout without needing a running journald, and the file | ||
| 7 | +# reader is pointed at fixture logs through the SX_LOGS_EXTRA_ROOT knob. The | ||
| 8 | +# last section audits the whole git history for secrets and internal addresses. | ||
| 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_logs | ||
| 18 | +PASS=0 | ||
| 19 | +FAIL=0 | ||
| 20 | +TMP=$(mktemp -d 2>/dev/null || echo /tmp/logs_test_$$) | ||
| 21 | +mkdir -p "$TMP" | ||
| 22 | +trap 'rm -rf "$TMP"' EXIT | ||
| 23 | + | ||
| 24 | +if [ -t 1 ]; then | ||
| 25 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | ||
| 26 | +else | ||
| 27 | + C_OK=; C_BAD=; C_B=; C_0= | ||
| 28 | +fi | ||
| 29 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | ||
| 30 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | ||
| 31 | + | ||
| 32 | +check() { # check <desc> <expected-substring> <actual> | ||
| 33 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | ||
| 34 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)" | ||
| 35 | + fi | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | ||
| 39 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | ||
| 40 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | ||
| 41 | + fi | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | ||
| 45 | +body() { printf '%s' "$1" | sed '1,/^\r$/d'; } | ||
| 46 | + | ||
| 47 | +# ---------------------------------------------------------------- fixtures | ||
| 48 | +# A journal stream in the exact shape journalctl -o json emits (one object per | ||
| 49 | +# line, microsecond epoch timestamps, string PRIORITY, arrays for binary fields). | ||
| 50 | +JFIX="$TMP/journal.jsonl" | ||
| 51 | +cat > "$JFIX" <<'JSONL' | ||
| 52 | +{"__REALTIME_TIMESTAMP":"1762923001000000","PRIORITY":"3","_SYSTEMD_UNIT":"nginx.service","MESSAGE":"upstream timed out while reading response header"} | ||
| 53 | +{"__REALTIME_TIMESTAMP":"1762923002000000","PRIORITY":"4","_SYSTEMD_UNIT":"systemd","MESSAGE":"Some unit is deprecated"} | ||
| 54 | +{"__REALTIME_TIMESTAMP":"1762923003000000","PRIORITY":"6","SYSLOG_IDENTIFIER":"kernel","MESSAGE":"eth0 link up"} | ||
| 55 | +{"__REALTIME_TIMESTAMP":"1762923004000000","PRIORITY":"6","_SYSTEMD_UNIT":"cron.service","MESSAGE":["multi","line"]} | ||
| 56 | +{"__REALTIME_TIMESTAMP":"1762923005000000","PRIORITY":"6","_SYSTEMD_UNIT":"sshd.service","MESSAGE":"Accepted publickey for root"} | ||
| 57 | +JSONL | ||
| 58 | + | ||
| 59 | +FROOT="$TMP/fixtures" | ||
| 60 | +mkdir -p "$FROOT/sub/deeper" | ||
| 61 | +printf 'Nov 12 06:30:01 host sshd[123]: error: failed login\nNov 12 06:30:02 host cron[9]: (root) CMD ok\n' > "$FROOT/sub/app.log" | ||
| 62 | +cat > "$FROOT/sub/deeper/iso.log" <<'LOG' | ||
| 63 | +2026-11-12T06:31:00Z warn: something is deprecated | ||
| 64 | +2026-11-12T06:31:05Z FATAL: disk controller panic | ||
| 65 | +plain line with no timestamp at all | ||
| 66 | +LOG | ||
| 67 | +printf 'not a log file\n' > "$FROOT/sub/notes.txt" | ||
| 68 | +ZEROS="$FROOT/sub/deeper/empty.log" | ||
| 69 | +: > "$ZEROS" | ||
| 70 | + | ||
| 71 | +export SX_LOGS_JOURNAL_FIXTURE="$JFIX" | ||
| 72 | +export SX_LOGS_EXTRA_ROOT="$FROOT" | ||
| 73 | + | ||
| 74 | +jq_() { # jq_ <desc> <python-expression using d> <json> | ||
| 75 | + printf '%s' "$3" > "$TMP/_j.json" | ||
| 76 | + if python3 - "$TMP/_j.json" "$2" <<'PY' 2>/dev/null | ||
| 77 | +import json, sys | ||
| 78 | +d = json.load(open(sys.argv[1])) | ||
| 79 | +assert eval(sys.argv[2], {"d": d}), sys.argv[2] | ||
| 80 | +PY | ||
| 81 | + then pass "$1"; else fail "$1"; fi | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +# ---------------------------------------------------------------- build | ||
| 85 | +section "build" | ||
| 86 | +if [ ! -x "$BIN" ]; then | ||
| 87 | + echo " building native binary..." | ||
| 88 | + cc -O2 -std=c99 -Wall -Wextra -I src -o "$BIN" src/plugin_logs.c || { echo " build failed"; exit 1; } | ||
| 89 | +fi | ||
| 90 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | ||
| 91 | + | ||
| 92 | +# ---------------------------------------------------------------- meta mode | ||
| 93 | +section "mode 1 --meta (must work without auth - discovery)" | ||
| 94 | +META=$("$BIN" --meta) | ||
| 95 | +check "meta emits name logs" '"name":"logs"' "$META" | ||
| 96 | +check "meta emits desc Log viewer" '"desc":"Log viewer"' "$META" | ||
| 97 | +METAENV=$(SX_PLUGIN_META=1 "$BIN") | ||
| 98 | +check "SX_PLUGIN_META=1 yields same meta" '"name":"logs"' "$METAENV" | ||
| 99 | +LEN=$(printf '%s' "$META" | wc -c | tr -d ' ') | ||
| 100 | +[ "$LEN" -lt 60 ] && pass "meta payload is compact ($LEN bytes)" || fail "meta payload too long ($LEN)" | ||
| 101 | +printf '%s' "$META" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | ||
| 102 | + && pass "meta is valid JSON" || fail "meta is not valid JSON" | ||
| 103 | +DESC=$(printf '%s' "$META" | sed 's/.*"desc":"\([^"]*\)".*/\1/') | ||
| 104 | +[ ${#DESC} -le 15 ] && pass "desc length ${#DESC} <= 15 chars" || fail "desc too long (${#DESC})" | ||
| 105 | +NAME=$(printf '%s' "$META" | sed 's/.*"name":"\([^"]*\)".*/\1/') | ||
| 106 | +[ "$(printf '%s' "$NAME" | wc -w | tr -d ' ')" -le 2 ] && pass "name is at most two words" || fail "name has too many words" | ||
| 107 | +check "--version prints version" '1.0.0' "$("$BIN" --version)" | ||
| 108 | +check "--help is available" 'usage:' "$("$BIN" --help)" | ||
| 109 | +META_AUTH=$(BOT_PASSWORD=secret "$BIN" --meta) | ||
| 110 | +check "meta still works when BOT_PASSWORD is set" '"name":"logs"' "$META_AUTH" | ||
| 111 | + | ||
| 112 | +# ---------------------------------------------------------------- auth | ||
| 113 | +section "node auth" | ||
| 114 | +AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=sources' "$BIN") | ||
| 115 | +check "no credentials -> 401" 'Status: 401' "$AUTHNONE" | ||
| 116 | +check "401 body is json" 'invalid node password' "$AUTHNONE" | ||
| 117 | +AUTHH=$(body "$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING='action=sources' "$BIN")") | ||
| 118 | +check "X-Bot-Password accepted" '"ok":true' "$AUTHH" | ||
| 119 | +AUTHB=$(body "$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=sources' "$BIN")") | ||
| 120 | +check "Authorization Bearer accepted" '"ok":true' "$AUTHB" | ||
| 121 | +AUTHQ=$(body "$(BOT_PASSWORD=testpw QUERY_STRING='action=sources&pwd=testpw' "$BIN")") | ||
| 122 | +check "?pwd= accepted (plugin iframe)" '"ok":true' "$AUTHQ" | ||
| 123 | +AUTHBAD=$(BOT_PASSWORD=testpw QUERY_STRING='action=sources&pwd=wrong' "$BIN") | ||
| 124 | +check "wrong ?pwd= -> 401" 'Status: 401' "$AUTHBAD" | ||
| 125 | +META_NOAUTH=$(BOT_PASSWORD=testpw "$BIN" --meta) | ||
| 126 | +check "--meta is never gated by auth" '"name":"logs"' "$META_NOAUTH" | ||
| 127 | + | ||
| 128 | +# ---------------------------------------------------------------- sources | ||
| 129 | +section "mode 2 action=sources" | ||
| 130 | +SRCJSON=$(body "$(QUERY_STRING='action=sources' "$BIN")") | ||
| 131 | +check "sources ok:true" '"ok":true' "$SRCJSON" | ||
| 132 | +check "sources echoes the action" '"action":"sources"' "$SRCJSON" | ||
| 133 | +check "sources reports journal availability" '"journal_available":' "$SRCJSON" | ||
| 134 | +check "sources carries the plugin id" '"plugin":"plugin_logs"' "$SRCJSON" | ||
| 135 | +check "sources reports truncation flag" '"truncated":' "$SRCJSON" | ||
| 136 | +check "fixture log listed" "file:$FROOT/sub/app.log" "$SRCJSON" | ||
| 137 | +check "nested fixture log listed" "deeper/iso.log" "$SRCJSON" | ||
| 138 | +check_not "non-.log fixture is not listed" "notes.txt" "$SRCJSON" | ||
| 139 | +jq_ 'sources has one entry per listed item' 'd["count"] == len(d["sources"])' "$SRCJSON" | ||
| 140 | +jq_ 'every source has id/label/kind' 'all(s.get("id") and s.get("label") and s.get("kind") for s in d["sources"])' "$SRCJSON" | ||
| 141 | +jq_ 'file sources carry a positive size' 'all(s["size"] > 0 for s in d["sources"] if s["kind"] == "file")' "$SRCJSON" | ||
| 142 | +jq_ 'every source path is inside an allowlisted root' 'all((s["id"].startswith("file:/var/log/") or s["id"].startswith("file:/workspace/") or s["id"].startswith("file:" + __import__("os").environ["HOME"] + "/.scorpiox/") or s["id"].startswith("file:'"$FROOT"'/") or s["id"] in ("journal",) or s["id"].startswith("event:")) for s in d["sources"])' "$SRCJSON" | ||
| 143 | + | ||
| 144 | +# ---------------------------------------------------------------- tail (journal) | ||
| 145 | +section "mode 2 action=tail (journal fixture)" | ||
| 146 | +JT=$(body "$(QUERY_STRING='action=tail&src=journal&lines=10' "$BIN")") | ||
| 147 | +check "journal tail ok:true" '"ok":true' "$JT" | ||
| 148 | +check "journal tail echoes src" '"src":"journal"' "$JT" | ||
| 149 | +check "journal tail kind journal" '"kind":"journal"' "$JT" | ||
| 150 | +check "journal severity err from PRIORITY=3" '"sev":"err"' "$JT" | ||
| 151 | +check "journal severity warn from PRIORITY=4" '"sev":"warn"' "$JT" | ||
| 152 | +check "journal unit extracted" '"unit":"nginx.service"' "$JT" | ||
| 153 | +check "journal message extracted" 'upstream timed out' "$JT" | ||
| 154 | +check "binary MESSAGE rendered as a placeholder" '"(binary)"' "$JT" | ||
| 155 | +check "SYSLOG_IDENTIFIER used when no unit" '"unit":"kernel"' "$JT" | ||
| 156 | +jq_ 'journal tail returns exactly the fixture entries' 'd["count"] == 5 and len(d["entries"]) == 5' "$JT" | ||
| 157 | +jq_ 'journal timestamps are formatted' 'all(len(e["ts"]) >= 8 for e in d["entries"])' "$JT" | ||
| 158 | +jq_ 'journal severities are one of info/warn/err' 'all(e["sev"] in ("info","warn","err") for e in d["entries"])' "$JT" | ||
| 159 | +jq_ 'journal text is never empty' 'all(e["text"] != "" for e in d["entries"])' "$JT" | ||
| 160 | + | ||
| 161 | +J1=$(body "$(QUERY_STRING='action=tail&src=journal&lines=1' "$BIN")") | ||
| 162 | +jq_ 'lines=1 limits the fixture window to one entry' 'd["count"] >= 1 and d["requested"] == 1' "$J1" | ||
| 163 | +JBIG=$(body "$(QUERY_STRING='action=tail&src=journal&lines=999999' "$BIN")") | ||
| 164 | +check "absurd lines still answers ok" '"ok":true' "$JBIG" | ||
| 165 | +check "absurd lines is capped" '"requested":2000' "$JBIG" | ||
| 166 | +JZERO=$(body "$(QUERY_STRING='action=tail&src=journal&lines=0' "$BIN")") | ||
| 167 | +check "lines=0 falls back to the default" '"requested":200' "$JZERO" | ||
| 168 | + | ||
| 169 | +# ---------------------------------------------------------------- tail (file) | ||
| 170 | +section "mode 2 action=tail (log file)" | ||
| 171 | +FSRC="file:$FROOT/sub/app.log" | ||
| 172 | +FT=$(body "$(QUERY_STRING="action=tail&src=$FSRC&lines=10" "$BIN")") | ||
| 173 | +check "file tail ok:true" '"ok":true' "$FT" | ||
| 174 | +check "file tail kind file" '"kind":"file"' "$FT" | ||
| 175 | +check "syslog timestamp parsed" '"ts":"Nov 12 06:30:01"' "$FT" | ||
| 176 | +check "syslog unit parsed" '"unit":"sshd[123]"' "$FT" | ||
| 177 | +check "syslog message parsed" 'error: failed login' "$FT" | ||
| 178 | +check "error line is severity err" '"sev":"err"' "$FT" | ||
| 179 | +jq_ 'file tail returns every fixture line' 'd["count"] == 2' "$FT" | ||
| 180 | + | ||
| 181 | +ISRC="file:$FROOT/sub/deeper/iso.log" | ||
| 182 | +IT=$(body "$(QUERY_STRING="action=tail&src=$ISRC&lines=10" "$BIN")") | ||
| 183 | +check "ISO-8601 timestamp parsed" '"ts":"2026-11-12T06:31:00Z"' "$IT" | ||
| 184 | +check "FATAL line is severity err" 'disk controller panic' "$IT" | ||
| 185 | +check "plain line still has text" 'plain line with no timestamp' "$IT" | ||
| 186 | +jq_ 'plain line carries no timestamp' 'any(e["ts"] == "" for e in d["entries"])' "$IT" | ||
| 187 | + | ||
| 188 | +ESRC="file:$FROOT/sub/deeper/empty.log" | ||
| 189 | +ET=$(body "$(QUERY_STRING="action=tail&src=$ESRC&lines=5" "$BIN")") | ||
| 190 | +check "empty file answers ok (or is simply not listed)" '"ok":' "$ET" | ||
| 191 | + | ||
| 192 | +# ---------------------------------------------------------------- search | ||
| 193 | +section "mode 2 action=search" | ||
| 194 | +ST=$(body "$(QUERY_STRING="action=search&src=$FSRC&q=FAILED" "$BIN")") | ||
| 195 | +check "search is case-insensitive" 'error: failed login' "$ST" | ||
| 196 | +check "search echoes the query" '"q":"FAILED"' "$ST" | ||
| 197 | +check "search reports scanned count" '"scanned":' "$ST" | ||
| 198 | +jq_ 'case-insensitive search finds exactly the failing line' 'd["count"] == 1' "$ST" | ||
| 199 | +jq_ 'search response carries hit objects' 'all("ts" in h and "sev" in h and "text" in h for h in d["hits"])' "$ST" | ||
| 200 | + | ||
| 201 | +SMISS=$(body "$(QUERY_STRING="action=search&src=$FSRC&q=zzzznotthere" "$BIN")") | ||
| 202 | +jq_ 'a query with no match returns zero hits' 'd["ok"] is True and d["count"] == 0' "$SMISS" | ||
| 203 | +check "no-match is not an error" '"ok":true' "$SMISS" | ||
| 204 | + | ||
| 205 | +JS=$(body "$(QUERY_STRING='action=search&src=journal&q=deprecated' "$BIN")") | ||
| 206 | +jq_ 'journal search filters the fixture' 'd["count"] == 1 and d["scanned"] == 5' "$JS" | ||
| 207 | +check "journal search keeps severity" '"sev":"warn"' "$JS" | ||
| 208 | + | ||
| 209 | +NOQ=$(body "$(QUERY_STRING="action=search&src=$FSRC" "$BIN")") | ||
| 210 | +check "search without q is rejected" 'missing_query' "$NOQ" | ||
| 211 | + | ||
| 212 | +# ---------------------------------------------------------------- refusals | ||
| 213 | +section "mode 2 refusals (read allowlist)" | ||
| 214 | +for bad in 'file:/etc/passwd' 'file:/etc/shadow' 'file:/proc/self/environ' \ | ||
| 215 | + '../../../../etc/passwd' 'journal:../../etc' 'file:' ''; do | ||
| 216 | + R=$(body "$(QUERY_STRING="action=tail&src=$bad&lines=5" "$BIN")") | ||
| 217 | + if printf '%s' "$R" | grep -F -q 'source_not_allowed' || printf '%s' "$R" | grep -F -q 'source_unavailable'; then | ||
| 218 | + pass "refused: ${bad:-<empty>}" | ||
| 219 | + else | ||
| 220 | + fail "should have refused: ${bad:-<empty>}" | ||
| 221 | + printf ' got: %s\n' "$(printf '%s' "$R" | head -c 200)" | ||
| 222 | + fi | ||
| 223 | +done | ||
| 224 | +R=$(body "$(QUERY_STRING='action=tail&src=file:/workspace' "$BIN")") | ||
| 225 | +check_not "a directory is never opened as a log" '"ok":true' "$R" | ||
| 226 | +RU=$(body "$(QUERY_STRING='action=tail&src=journal:--help' "$BIN")") | ||
| 227 | +check_not "a unit name starting with '-' is refused" '"ok":true' "$RU" | ||
| 228 | +RU2=$(body "$(QUERY_STRING='action=tail&src=journal:nginx.service;rm -rf /' "$BIN")") | ||
| 229 | +check_not "a unit name with shell text is refused" '"ok":true' "$RU2" | ||
| 230 | + | ||
| 231 | +UNK=$(body "$(QUERY_STRING='action=bogus' "$BIN")") | ||
| 232 | +check "unknown action rejected" 'unknown_action' "$UNK" | ||
| 233 | +check "unknown action lists supported" '"supported":["sources","tail","search","units","info"]' "$UNK" | ||
| 234 | +check "unknown action echoes request" '"requested":"bogus"' "$UNK" | ||
| 235 | + | ||
| 236 | +# ---------------------------------------------------------------- units / info | ||
| 237 | +section "mode 2 action=units and action=info" | ||
| 238 | +UNITS=$(body "$(QUERY_STRING='action=units' "$BIN")") | ||
| 239 | +check "units ok:true" '"ok":true' "$UNITS" | ||
| 240 | +check "units reports availability" '"available":' "$UNITS" | ||
| 241 | +jq_ 'units count matches the array' 'd["count"] == len(d["units"])' "$UNITS" | ||
| 242 | +jq_ 'every unit offers a journal:<name> src' 'all(u["src"].startswith("journal:") for u in d["units"])' "$UNITS" | ||
| 243 | + | ||
| 244 | +INFO=$(body "$(QUERY_STRING='action=info' "$BIN")") | ||
| 245 | +check "info ok:true" '"ok":true' "$INFO" | ||
| 246 | +check "info action info" '"action":"info"' "$INFO" | ||
| 247 | +check "info declares zero network" '"zero_network":true' "$INFO" | ||
| 248 | +check "info declares read-only" '"read_only":true' "$INFO" | ||
| 249 | +check "info node_auth false when unset" '"node_auth":false' "$INFO" | ||
| 250 | +check "info publishes the line cap" '"lines_max":2000' "$INFO" | ||
| 251 | +check "info publishes the hit cap" '"search_hits_max":500' "$INFO" | ||
| 252 | +INFOAUTH=$(body "$(BOT_PASSWORD=pw QUERY_STRING='action=info&pwd=pw' "$BIN")") | ||
| 253 | +check "info node_auth true when set" '"node_auth":true' "$INFOAUTH" | ||
| 254 | +printf '%s' "$INFO" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | ||
| 255 | + && pass "info body is valid JSON" || fail "info body JSON invalid" | ||
| 256 | +check "format=json works as an alias" '"ok":true' "$(body "$(QUERY_STRING='format=json&action=info' "$BIN")")" | ||
| 257 | + | ||
| 258 | +# ---------------------------------------------------------------- html | ||
| 259 | +section "mode 3 HTML" | ||
| 260 | +HTML=$(QUERY_STRING='' "$BIN") | ||
| 261 | +check "html content-type" 'Content-Type: text/html; charset=utf-8' "$HTML" | ||
| 262 | +check_not "html has no Content-Length" 'Content-Length' "$HTML" | ||
| 263 | +check "html has viewport meta" 'width=device-width' "$HTML" | ||
| 264 | +check "html title logs" '<title>logs</title>' "$HTML" | ||
| 265 | +check "html back-link present" 'Back to Bot' "$HTML" | ||
| 266 | +check "html theme switch hook" 'bot_theme' "$HTML" | ||
| 267 | +check "html source picker present" "id='srcSel'" "$HTML" | ||
| 268 | +check "html log viewport present" "id='log'" "$HTML" | ||
| 269 | +check "html search input present" "id='q'" "$HTML" | ||
| 270 | +check "html follow toggle present" "id='btnFollow'" "$HTML" | ||
| 271 | +check "html wrap toggle present" "id='btnWrap'" "$HTML" | ||
| 272 | +check "html copy button present" "id='btnCopy'" "$HTML" | ||
| 273 | +check "html line-count segmented control" 'data-n=' "$HTML" | ||
| 274 | +check "html calls action=sources" 'action=sources' "$HTML" | ||
| 275 | +check "html calls action=tail" 'action=tail' "$HTML" | ||
| 276 | +check "html calls action=search" 'action=search' "$HTML" | ||
| 277 | +check "html uses /plugins?plugin= route" "/plugins?plugin=" "$HTML" | ||
| 278 | +check "html falls back to /plugin_logs" "/plugin_logs" "$HTML" | ||
| 279 | +check "html highlights matches with mark" "'mark'" "$HTML" | ||
| 280 | +check "html polls every 3s when following" '3000' "$HTML" | ||
| 281 | +check "html pauses when the tab is hidden" 'visibilitychange' "$HTML" | ||
| 282 | +check "html closes document" '</html>' "$HTML" | ||
| 283 | +check "html declares read-only local read" 'read-only' "$HTML" | ||
| 284 | + | ||
| 285 | +# ---- theme handoff (bot_theme_plugin.h) ---- | ||
| 286 | +check "html reads ?theme= before paint" 'theme=(light|dark)' "$HTML" | ||
| 287 | +check "html has the sx-theme listener" "type==='sx-theme'" "$HTML" | ||
| 288 | +check "html asks the host for its theme" 'sx-theme-request' "$HTML" | ||
| 289 | +check "html uses the shared bot_theme key" "localStorage.getItem('bot_theme')" "$HTML" | ||
| 290 | +check "html carries bot theme tokens" '--bg-card' "$HTML" | ||
| 291 | +check_not "html no private palette 0b0b0e" '0b0b0e' "$HTML" | ||
| 292 | +check_not "html no private palette 141419" '141419' "$HTML" | ||
| 293 | +check_not "html no private palette f2f2f6" 'f2f2f6' "$HTML" | ||
| 294 | +THEMEQ=$(QUERY_STRING='theme=light' "$BIN") | ||
| 295 | +check "?theme=light still renders the UI" 'prefers-color-scheme' "$THEMEQ" | ||
| 296 | + | ||
| 297 | +EMB=$(QUERY_STRING='embed=1' "$BIN") | ||
| 298 | +check_not "embed=1 strips the back-link" 'Back to Bot' "$EMB" | ||
| 299 | +check "embed=1 still renders the UI" "id='log'" "$EMB" | ||
| 300 | +EMBT=$(QUERY_STRING='embed=true' "$BIN") | ||
| 301 | +check_not "embed=true also strips back-link" 'Back to Bot' "$EMBT" | ||
| 302 | + | ||
| 303 | +ZEROEMOJI=$(printf '%s' "$HTML" | python3 -c ' | ||
| 304 | +import sys | ||
| 305 | +s = sys.stdin.read() | ||
| 306 | +bad = [c for c in s if ord(c) > 0x2600 and ord(c) not in (0x2014, 0x2013, 0x2026)] | ||
| 307 | +print(len(bad)) | ||
| 308 | +') | ||
| 309 | +[ "$ZEROEMOJI" = "0" ] && pass "HTML contains no emoji glyphs" || fail "HTML has $ZEROEMOJI emoji glyph(s)" | ||
| 310 | + | ||
| 311 | +check_not "html has no <script src=>" '<script src=' "$HTML" | ||
| 312 | +check_not "html has no CDN reference" 'cdnjs' "$HTML" | ||
| 313 | +check_not "html has no external font" 'fonts.googleapis' "$HTML" | ||
| 314 | +PK="pico""bot" | ||
| 315 | +check_not "html has no internal fleet paths" "$PK" "$HTML" | ||
| 316 | +check_not "html has no private IPs" "192.168." "$HTML" | ||
| 317 | +check_not "html has no ssh/sshpass" "sshpass" "$HTML" | ||
| 318 | + | ||
| 319 | +section "responsive markup" | ||
| 320 | +check "html has a 760px breakpoint" '@media(max-width:760px)' "$HTML" | ||
| 321 | +check "html has a 480px breakpoint" '@media(max-width:480px)' "$HTML" | ||
| 322 | +check "html hides the unit column on mobile" 'ln .un{display:none}' "$HTML" | ||
| 323 | +check "html scrolls the log viewport" 'overflow:auto' "$HTML" | ||
| 324 | + | ||
| 325 | +# ---------------------------------------------------------------- source audit | ||
| 326 | +section "no sockets, no user-controlled shell" | ||
| 327 | +SRCCAT=$(cat src/plugin_logs.c) | ||
| 328 | +check_not "source opens no sockets" 'socket(' "$SRCCAT" | ||
| 329 | +check_not "source has no curl or wget" 'wget' "$SRCCAT" | ||
| 330 | +check_not "source has no ssh invocation" 'ssh ' "$SRCCAT" | ||
| 331 | +check_not "source has no sshpass" 'sshpass' "$SRCCAT" | ||
| 332 | +check_not "source never calls system()" 'system(' "$SRCCAT" | ||
| 333 | +check "journal argv is built with snprintf" 'journalctl -o json --no-pager' "$SRCCAT" | ||
| 334 | +check "unit names are validated" 'valid_unit' "$SRCCAT" | ||
| 335 | +check "files are opened read-only" '"rb"' "$SRCCAT" | ||
| 336 | +check "tail reads are bounded" 'FILE_TAIL_BYTES' "$SRCCAT" | ||
| 337 | +check "walks have a per-root budget" 'ROOT_BUDGET' "$SRCCAT" | ||
| 338 | +check "symlinks are never followed" 'S_ISLNK' "$SRCCAT" | ||
| 339 | + | ||
| 340 | +# ---------------------------------------------------------------- optional targets | ||
| 341 | +section "optional cross builds" | ||
| 342 | +if [ -f plugin_logs.musl ]; then | ||
| 343 | + M=$(./plugin_logs.musl --meta) | ||
| 344 | + check "musl build --meta" '"name":"logs"' "$M" | ||
| 345 | + case $(head -c 4 plugin_logs.musl | od -An -tx1 | tr -d ' \n') in | ||
| 346 | + 7f454c46) pass "musl artifact is ELF" ;; | ||
| 347 | + *) fail "musl artifact is not ELF" ;; | ||
| 348 | + esac | ||
| 349 | +else | ||
| 350 | + echo " skip musl (not built)" | ||
| 351 | +fi | ||
| 352 | +if [ -f plugin_logs.arm64 ]; then | ||
| 353 | + case $(head -c 20 plugin_logs.arm64 | od -An -tx1 | tr -d ' \n') in | ||
| 354 | + 7f454c46*e500b700*|7f454c46*b700*) pass "arm64 artifact is an aarch64 ELF" ;; | ||
| 355 | + 7f454c46*) | ||
| 356 | + if od -An -tx1 -j18 -N2 plugin_logs.arm64 | tr -d ' \n' | grep -q 'b7'; then | ||
| 357 | + pass "arm64 artifact is an aarch64 ELF" | ||
| 358 | + else | ||
| 359 | + fail "arm64 artifact is not aarch64" | ||
| 360 | + fi ;; | ||
| 361 | + *) fail "arm64 artifact is not ELF" ;; | ||
| 362 | + esac | ||
| 363 | +else | ||
| 364 | + echo " skip arm64 (not built)" | ||
| 365 | +fi | ||
| 366 | +if [ -f plugin_logs.exe ]; then | ||
| 367 | + MAGIC=$(head -c 2 plugin_logs.exe) | ||
| 368 | + [ "$MAGIC" = "MZ" ] && pass "windows artifact has MZ header" || fail "windows artifact missing MZ" | ||
| 369 | + SZ=$(wc -c < plugin_logs.exe | tr -d ' ') | ||
| 370 | + [ "$SZ" -gt 20000 ] && pass "windows artifact is not an error page ($SZ bytes)" || fail "windows artifact suspiciously small ($SZ bytes)" | ||
| 371 | +else | ||
| 372 | + echo " skip windows PE (not built)" | ||
| 373 | +fi | ||
| 374 | +if [ -f plugin_logs.macos-arm64 ]; then | ||
| 375 | + case $(head -c 4 plugin_logs.macos-arm64 | od -An -tx1 | tr -d ' \n') in | ||
| 376 | + cffaedfe|cefaedfe) pass "macos-arm64 artifact is Mach-O" ;; | ||
| 377 | + *) fail "macos-arm64 artifact is not Mach-O" ;; | ||
| 378 | + esac | ||
| 379 | +else | ||
| 380 | + echo " skip macos-arm64 (not built)" | ||
| 381 | +fi | ||
| 382 | +if [ -f plugin_logs.macos-x86_64 ]; then | ||
| 383 | + case $(head -c 4 plugin_logs.macos-x86_64 | od -An -tx1 | tr -d ' \n') in | ||
| 384 | + cffaedfe|cefaedfe) pass "macos-x86_64 artifact is Mach-O" ;; | ||
| 385 | + *) fail "macos-x86_64 artifact is not Mach-O" ;; | ||
| 386 | + esac | ||
| 387 | +else | ||
| 388 | + echo " skip macos-x86_64 (not built)" | ||
| 389 | +fi | ||
| 390 | + | ||
| 391 | +# ---------------------------------------------------------------- history audit | ||
| 392 | +section "git history secret & LAN audit" | ||
| 393 | +if git rev-parse --git-dir >/dev/null 2>&1; then | ||
| 394 | + ALL="$TMP/history.txt" | ||
| 395 | + # Bookkeeping lines of this audit are excluded so the detector cannot flag | ||
| 396 | + # itself. Detector literals are also assembled from fragments below. | ||
| 397 | + git log -p --all 2>/dev/null \ | ||
| 398 | + | grep -v '^Author: ' \ | ||
| 399 | + | grep -vE 'audit "|HITS=|grep -E|scan "' \ | ||
| 400 | + > "$ALL" || : > "$ALL" | ||
| 401 | + | ||
| 402 | + audit() { # audit <label> <regex> | ||
| 403 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | ||
| 404 | + if [ -n "$H" ]; then | ||
| 405 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | ||
| 406 | + else | ||
| 407 | + pass "history clean: $1" | ||
| 408 | + fi | ||
| 409 | + } | ||
| 410 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 411 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 412 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 413 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 414 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 415 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 416 | + PK2="pico""bot"; WT=".work""trees" | ||
| 417 | + audit "fleet path" "/codebases/${PK2}|${WT}/" | ||
| 418 | + audit "internal hostname" 'intel-ultra2|macmini2018i5|lazarus' | ||
| 419 | +else | ||
| 420 | + echo " skip history audit (not a git checkout)" | ||
| 421 | +fi | ||
| 422 | + | ||
| 423 | +# ---------------------------------------------------------------- summary | ||
| 424 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | ||
| 425 | +printf ' passed: %d\n' "$PASS" | ||
| 426 | +printf ' failed: %d\n' "$FAIL" | ||
| 427 | +if [ "$FAIL" -ne 0 ]; then | ||
| 428 | + printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0" | ||
| 429 | + exit 1 | ||
| 430 | +fi | ||
| 431 | +printf ' %sRESULT: ALL PASSED%s\n' "$C_OK" "$C_0" | ||
| 432 | +exit 0 | ||
| 0 | 433 |