| 1 | 1 | new file mode 100644 |
| index 0000000..c3339a0 | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,17 @@ | ||
| 1 | +# build artifacts | |
| 2 | +plugin_files | |
| 3 | +plugin_files.exe | |
| 4 | +plugin_files.musl | |
| 5 | +plugin_files.arm64 | |
| 6 | +plugin_files.macos-arm64 | |
| 7 | +plugin_files.macos-x86_64 | |
| 8 | +bin/ | |
| 9 | + | |
| 10 | +# test scratch | |
| 11 | +*.tmp | |
| 12 | +fixture/ | |
| 13 | +.playwright/ | |
| 14 | + | |
| 15 | +# python tooling | |
| 16 | +__pycache__/ | |
| 17 | +*.pyc |
| 1 | 1 | new file mode 100644 |
| index 0000000..ef80120 | ||
| --- /dev/null | ||
| +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | |
| 2 | + | |
| 3 | +Copyright (c) 2026 SCORPIOX INC | |
| 4 | + | |
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 6 | +of this software and associated documentation files (the "Software"), to deal | |
| 7 | +in the Software without restriction, including without limitation the rights | |
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 9 | +copies of the Software, and to permit persons to whom the Software is | |
| 10 | +furnished to do so, subject to the following conditions: | |
| 11 | + | |
| 12 | +The above copyright notice and this permission notice shall be included in all | |
| 13 | +copies or substantial portions of the Software. | |
| 14 | + | |
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 21 | +SOFTWARE. |
| 1 | 1 | new file mode 100644 |
| index 0000000..7c714db | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,75 @@ | ||
| 1 | +# plugin_files - SCORPIOX BOT open-source read-only file browser for your node | |
| 2 | +# | |
| 3 | +# Targets: | |
| 4 | +# make native build -> ./plugin_files | |
| 5 | +# make musl static musl x86_64 -> ./plugin_files.musl | |
| 6 | +# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_files.arm64 | |
| 7 | +# make win64 MinGW-w64 static -> ./plugin_files.exe | |
| 8 | +# make macos Apple clang -> ./plugin_files (run this on macOS) | |
| 9 | +# make ui regenerate src/ui_html.h from src/ui.html | |
| 10 | +# make test build + run tests/run.sh | |
| 11 | +# make e2e build + run tests/e2e.py (Playwright) | |
| 12 | +# make clean | |
| 13 | + | |
| 14 | +CC ?= cc | |
| 15 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src | |
| 16 | +MUSL_CC ?= musl-gcc | |
| 17 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | |
| 18 | +ARM_CC ?= aarch64-linux-gnu-gcc | |
| 19 | +ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | |
| 20 | +WIN_CC ?= x86_64-w64-mingw32-gcc | |
| 21 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | |
| 22 | +SRC := src/plugin_files.c | |
| 23 | +UI_SRC := src/ui.html | |
| 24 | +UI_HDR := src/ui_html.h | |
| 25 | +BIN := plugin_files | |
| 26 | +EXE := plugin_files.exe | |
| 27 | + | |
| 28 | +.PHONY: all native musl arm64 win64 macos ui test e2e clean help | |
| 29 | + | |
| 30 | +all: native | |
| 31 | + | |
| 32 | +$(UI_HDR): $(UI_SRC) tools/gen_ui.py | |
| 33 | + @echo "==> regenerating $(UI_HDR)" | |
| 34 | + python3 tools/gen_ui.py | |
| 35 | + | |
| 36 | +ui: $(UI_HDR) | |
| 37 | + | |
| 38 | +native: $(BIN) | |
| 39 | + | |
| 40 | +$(BIN): $(SRC) $(UI_HDR) | |
| 41 | + @echo "==> native build ($(CC))" | |
| 42 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | |
| 43 | + | |
| 44 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | |
| 45 | +musl: $(SRC) $(UI_HDR) | |
| 46 | + @echo "==> static musl build ($(MUSL_CC))" | |
| 47 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC) | |
| 48 | + | |
| 49 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | |
| 50 | +arm64: $(SRC) $(UI_HDR) | |
| 51 | + @echo "==> static arm64 build ($(ARM_CC))" | |
| 52 | + $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC) | |
| 53 | + | |
| 54 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | |
| 55 | +win64: $(SRC) $(UI_HDR) | |
| 56 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | |
| 57 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) | |
| 58 | + | |
| 59 | +# Apple clang build (run this on macOS) | |
| 60 | +macos: $(SRC) $(UI_HDR) | |
| 61 | + @echo "==> Apple clang build" | |
| 62 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | |
| 63 | + | |
| 64 | +test: native | |
| 65 | + @sh tests/run.sh | |
| 66 | + | |
| 67 | +e2e: native | |
| 68 | + @python3 tests/e2e.py | |
| 69 | + | |
| 70 | +clean: | |
| 71 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64 | |
| 72 | + rm -rf bin | |
| 73 | + | |
| 74 | +help: | |
| 75 | + @echo "make | make musl | make arm64 | make win64 | make macos | make ui | make test | make e2e | make clean" |
| 1 | 1 | new file mode 100644 |
| index 0000000..77d6c84 | ||
| --- /dev/null | ||
| +++ b/README.md | ||
| @@ -0,0 +1,118 @@ | ||
| 1 | +# scorpiox-bot-plugin-files | |
| 2 | + | |
| 3 | +**`plugin_files`** — a read-only local file browser for a **SCORPIOX BOT** node. | |
| 4 | + | |
| 5 | +List directories inside an allowlist of roots, preview text and markdown with | |
| 6 | +line numbers, view images, and download files. It opens every file read-only | |
| 7 | +and contains no create, write, rename, chmod or delete code path at all. | |
| 8 | + | |
| 9 | +One clean-room C99 binary, zero dependencies, no CDN, no network requests. | |
| 10 | + | |
| 11 | +``` | |
| 12 | +files / File browser category: devtools MIT | |
| 13 | +``` | |
| 14 | + | |
| 15 | +## What it does | |
| 16 | + | |
| 17 | +| Route | Behaviour | | |
| 18 | +|---|---| | |
| 19 | +| `--meta` (or `SX_PLUGIN_META=1`) | `{"name":"files","desc":"File browser"}` — unauthenticated so discovery works | | |
| 20 | +| `?action=roots` | the allowlisted roots with a display name each | | |
| 21 | +| `?action=ls&path=<abs>[&hidden=1]` | up to 5000 entries, directories first then names, each with `type` / `size` / `mtime` / `mode`; reports `count`, `truncated`, `parent`, `root` | | |
| 22 | +| `?action=read&path=<abs>` | text preview up to 1 MiB, `binary:true` when a NUL byte appears in the first 8 KiB | | |
| 23 | +| `?action=raw&path=<abs>[&download=1]` | streams the file with a guessed `Content-Type`, capped at 64 MiB | | |
| 24 | +| `GET` (no action) | the browser page, `?embed=1` aware | | |
| 25 | + | |
| 26 | +All routes except `--meta` sit behind `require_node_auth()`: `X-Bot-Password`, | |
| 27 | +`Authorization: Bearer <pwd>`, or `?pwd=`. With `BOT_PASSWORD` unset the check | |
| 28 | +is a no-op, which is what local development wants. | |
| 29 | + | |
| 30 | +## Read-only, and enforced | |
| 31 | + | |
| 32 | +Consumption of a plugin is native code on your machine, so the interesting | |
| 33 | +question is not "does it say read-only" but "can it do anything else". | |
| 34 | + | |
| 35 | +* The source contains no `fopen` in write mode, no `remove`, `rmdir`, `mkdir`, | |
| 36 | + `rename`, `chmod`, `popen` or `system`. `tests/run.sh` greps for all of them. | |
| 37 | +* Every path is canonicalised **before** it is used: `realpath()` on POSIX and | |
| 38 | + `GetFullPathNameA` + `GetFinalPathNameByHandleA` on Windows. | |
| 39 | +* The canonical path is then prefix-checked against the allowlisted roots, so a | |
| 40 | + symlink that points out of a root is refused with `403` — the check happens | |
| 41 | + on the real target, not on the name that was typed. | |
| 42 | +* Any `..` in a browse path is rejected outright; `%2e%2e` decodes before the | |
| 43 | + check, so the encoding does not help. | |
| 44 | +* `/proc`, `/sys` and `/dev` are refused even when they sit under an allowed | |
| 45 | + root. | |
| 46 | +* A `GET` of a `.html` file on disk is served as `text/plain`. This route shares | |
| 47 | + an origin with the node API, so rendering a local page as `text/html` would | |
| 48 | + hand every HTML file on the node the ability to call the plugin API with the | |
| 49 | + user's password. Images keep their real type because `<img>` only decodes | |
| 50 | + them. | |
| 51 | +* The response never sets `Content-Length`; `scorpiox-server` owns framing. | |
| 52 | + | |
| 53 | +## Allowlisted roots | |
| 54 | + | |
| 55 | +| Platform | Defaults | | |
| 56 | +|---|---| | |
| 57 | +| Linux | `/workspace`, `/codebases`, `$HOME` | | |
| 58 | +| macOS | `/workspace`, `/codebases`, `$HOME` | | |
| 59 | +| Windows | `%USERPROFILE%`, `D:\codebases` | | |
| 60 | + | |
| 61 | +`$FILES_ALLOWED_ROOT` adds one more, or several separated by `:` on POSIX and | |
| 62 | +`;` on Windows. Directories that do not exist are skipped silently, so the | |
| 63 | +list is honest on every machine. | |
| 64 | + | |
| 65 | +## Build | |
| 66 | + | |
| 67 | +```sh | |
| 68 | +make # native -> ./plugin_files | |
| 69 | +make musl # static musl x86_64 (Alpine, Debian, Arch, Omarchy) | |
| 70 | +make arm64 # static aarch64 (Raspberry Pi 5, ARM64 servers) | |
| 71 | +make win64 # static PE via x86_64-w64-mingw32-gcc | |
| 72 | +make macos # Apple clang (run on macOS) | |
| 73 | +make test # build + tests/run.sh (offline, 150 checks) | |
| 74 | +make e2e # build + tests/e2e.py (Playwright, 6 viewport/theme pairs) | |
| 75 | +make clean | |
| 76 | +``` | |
| 77 | + | |
| 78 | +On Windows, `powershell -ExecutionPolicy Bypass -File build.ps1` produces | |
| 79 | +`plugin_files.exe`. | |
| 80 | + | |
| 81 | +The page lives in `src/ui.html` and is compiled into `src/ui_html.h` by | |
| 82 | +`tools/gen_ui.py`, which splices the bot theme macros in at two control-byte | |
| 83 | +placeholders. `make ui` regenerates it; `python3 tools/gen_ui.py --check` | |
| 84 | +fails when the header is stale. | |
| 85 | + | |
| 86 | +## Install on a node | |
| 87 | + | |
| 88 | +```sh | |
| 89 | +# prebuilt, from the market | |
| 90 | +curl -s -H "X-Bot-Password: $BOT_PASSWORD" \ | |
| 91 | + 'http://127.0.0.1:8150/plugin_manage?action=install&slug=files&mode=prebuilt' | |
| 92 | + | |
| 93 | +# or from source, agent-style | |
| 94 | +git clone https://plugingit.scorpiox.net/scorpiox-bot-plugin-files.git | |
| 95 | +cd scorpiox-bot-plugin-files && make | |
| 96 | +mkdir -p ~/.scorpiox/plugins && cp plugin_files ~/.scorpiox/plugins/ | |
| 97 | +``` | |
| 98 | + | |
| 99 | +Zero server restart: `scorpiox-server` resolves `plugin_*` executables live on | |
| 100 | +every request. The plugin then appears in `GET /plugins`, in the Hub `⋯` menu, | |
| 101 | +on session cards, and in the Chat floating window. | |
| 102 | + | |
| 103 | +## Layout | |
| 104 | + | |
| 105 | +``` | |
| 106 | +src/plugin_files.c the whole plugin (~1.0k lines) | |
| 107 | +src/bot_theme_plugin.h bot theme tokens, prepaint + handoff (trimmed copy) | |
| 108 | +src/ui.html the page, readable and diffable | |
| 109 | +src/ui_html.h generated from ui.html - do not edit | |
| 110 | +tools/gen_ui.py ui.html -> ui_html.h | |
| 111 | +tests/run.sh 150 offline assertions, no network | |
| 112 | +tests/e2e.py Playwright at 1440/1024/390, dark + light | |
| 113 | +plugin.json catalog sidecar (slug, id, title, capabilities, trust) | |
| 114 | +``` | |
| 115 | + | |
| 116 | +## Licence | |
| 117 | + | |
| 118 | +MIT. Copyright (c) 2026 SCORPIOX INC. |
| 1 | 1 | new file mode 100644 |
| index 0000000..f040e24 | ||
| --- /dev/null | ||
| +++ b/build.ps1 | ||
| @@ -0,0 +1,51 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_files | |
| 2 | +# | |
| 3 | +# Usage (from the repo root, PowerShell): | |
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | |
| 5 | +# | |
| 6 | +# Produces .\plugin_files.exe (static PE, runs on any Windows 10/11 x64 node). | |
| 7 | +# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin). | |
| 8 | + | |
| 9 | +$ErrorActionPreference = "Stop" | |
| 10 | +$ScriptDir = $PSScriptRoot | |
| 11 | +Push-Location $ScriptDir | |
| 12 | +try { | |
| 13 | + $Src = Join-Path $ScriptDir "src\plugin_files.c" | |
| 14 | + $Out = Join-Path $ScriptDir "plugin_files.exe" | |
| 15 | + $Cc = "x86_64-w64-mingw32-gcc" | |
| 16 | + | |
| 17 | + if (-not (Test-Path $Src)) { throw "source not found: $Src" } | |
| 18 | + | |
| 19 | + # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present. | |
| 20 | + if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) { | |
| 21 | + if (Test-Path "C:\gcc16\bin\gcc.exe") { | |
| 22 | + $Cc = "C:\gcc16\bin\gcc.exe" | |
| 23 | + } elseif (Get-Command gcc -ErrorAction SilentlyContinue) { | |
| 24 | + $Cc = "gcc" | |
| 25 | + } else { | |
| 26 | + throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)" | |
| 27 | + } | |
| 28 | + } | |
| 29 | + | |
| 30 | + # Regenerate the page header so the binary always matches src/ui.html. | |
| 31 | + if (Get-Command python -ErrorAction SilentlyContinue) { | |
| 32 | + python tools\gen_ui.py | |
| 33 | + } | |
| 34 | + | |
| 35 | + Write-Host "==> building plugin_files.exe with $Cc" | |
| 36 | + & $Cc -O2 -std=c99 -Wall -Wextra -I src -static -o $Out $Src | |
| 37 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | |
| 38 | + | |
| 39 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | |
| 40 | + | |
| 41 | + # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not. | |
| 42 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | |
| 43 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | |
| 44 | + throw "output is not a PE executable (missing MZ header)" | |
| 45 | + } | |
| 46 | + | |
| 47 | + Write-Host "==> ok: $Out ($($bytes.Length) bytes)" | |
| 48 | + Write-Host " smoke test: .\plugin_files.exe --meta" | |
| 49 | +} finally { | |
| 50 | + Pop-Location | |
| 51 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..57fe210 |

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

| 1 | 1 | new file mode 100644 |
| index 0000000..3814d6b |

| 1 | 1 | new file mode 100644 |
| index 0000000..3df2266 |

| 1 | 1 | new file mode 100644 |
| index 0000000..5014b45 |

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

| 1 | 1 | new file mode 100644 |
| index 0000000..726bfd8 | ||
| --- /dev/null | ||
| +++ b/plugin.json | ||
| @@ -0,0 +1,15 @@ | ||
| 1 | +{ | |
| 2 | + "slug": "files", | |
| 3 | + "id": "plugin_files", | |
| 4 | + "title": "Local File Browser", | |
| 5 | + "summary": "Zero-dependency read-only file browser for your node: list directories, preview text and markdown with line numbers, view images and download files, all inside an allowlist of roots. Every path is canonicalised and prefix-checked after symlink resolution, so traversal, symlink escapes and /proc, /sys, /dev are refused. It opens files O_RDONLY and never creates, writes, renames or deletes anything.", | |
| 6 | + "category": "devtools", | |
| 7 | + "license": "MIT", | |
| 8 | + "capabilities": [ | |
| 9 | + "fs_read", | |
| 10 | + "no_network" | |
| 11 | + ], | |
| 12 | + "trust_notice": "Executes native C code on your node. Strictly read-only: it opens files read-only inside an allowlist of roots (/workspace, /codebases, $HOME, $FILES_ALLOWED_ROOT; on Windows %USERPROFILE%, D:\\codebases, $FILES_ALLOWED_ROOT) and refuses anything outside them after symlink resolution. It writes nothing, makes zero outbound network requests, and never lists /proc, /sys or /dev.", | |
| 13 | + "author": "SCORPIOX INC", | |
| 14 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-files" | |
| 15 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..f308b20 | ||
| --- /dev/null | ||
| +++ b/release-dist.sh | ||
| @@ -0,0 +1,38 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# release-dist.sh - thin wrapper around the shared multi-arch release tool. | |
| 3 | +# | |
| 4 | +# The real cross-target build + dist publish lives in scorpiox-cli-botplugin | |
| 5 | +# (it owns the musl / aarch64 / MinGW / macOS toolchains and the plugingit | |
| 6 | +# mirror). This script only exists so the repo can be released the same way | |
| 7 | +# every other oss plugin is, and so a stale release-dist keeps failing loudly | |
| 8 | +# instead of shipping a 3-target manifest that says "release complete". | |
| 9 | +# | |
| 10 | +# ./release-dist.sh # build + publish version from plugin.json / 1.0.0 | |
| 11 | +# VERSION=1.0.1 ./release-dist.sh # explicit version | |
| 12 | +# | |
| 13 | +# Run it on the build host that has musl-gcc, aarch64-linux-gnu-gcc, | |
| 14 | +# x86_64-w64-mingw32-gcc and ssh access to the macOS builder. | |
| 15 | + | |
| 16 | +set -eu | |
| 17 | + | |
| 18 | +SLUG=files | |
| 19 | +VERSION="${VERSION:-1.0.0}" | |
| 20 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | |
| 21 | + | |
| 22 | +ROOT=$(cd "$(dirname "$0")" && pwd) | |
| 23 | + | |
| 24 | +if ! command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | |
| 25 | + echo "scorpiox-cli-botplugin not found on PATH" >&2 | |
| 26 | + exit 1 | |
| 27 | +fi | |
| 28 | + | |
| 29 | +echo "==> publish $SLUG $VERSION" | |
| 30 | +scorpiox-cli-botplugin publish "$ROOT" \ | |
| 31 | + --slug "$SLUG" \ | |
| 32 | + --version "$VERSION" \ | |
| 33 | + --macos-host "${MACOS_HOST:-yongchen@macos-builder}" \ | |
| 34 | + --json | |
| 35 | + | |
| 36 | +echo "==> verify target count in the published manifest" | |
| 37 | +scorpiox-cli-botplugin reindex --json >/dev/null 2>&1 || true | |
| 38 | +echo "check dist/bot-plugins/$SLUG/$VERSION/manifest.json has 6 targets before calling it done" |
| 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..af2a48d | ||
| --- /dev/null | ||
| +++ b/src/plugin_files.c | ||
| @@ -0,0 +1,1184 @@ | ||
| 1 | +/* | |
| 2 | + * plugin_files - SCORPIOX BOT open-source read-only file browser for your node | |
| 3 | + * | |
| 4 | + * A single clean-room C99 binary that serves THREE modes: | |
| 5 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata | |
| 6 | + * 2. ?action=... / ?format=json -> JSON node API | |
| 7 | + * 3. GET (default) -> browse + preview page | |
| 8 | + * | |
| 9 | + * Repo: https://plugingit.scorpiox.net/scorpiox-bot-plugin-files.git | |
| 10 | + * | |
| 11 | + * READ-ONLY BY CONSTRUCTION. There is no create, no write, no delete, no | |
| 12 | + * rename, no chmod anywhere in this file: the plugin exists to look at files, | |
| 13 | + * never to change them. | |
| 14 | + * | |
| 15 | + * Every path that arrives in a request is canonicalised on the real | |
| 16 | + * filesystem (realpath() on POSIX, GetFullPathNameA + GetFinalPathNameByHandleA | |
| 17 | + * on Windows) and then prefix-checked against the allowlisted roots AFTER | |
| 18 | + * symlink resolution. `..`, embedded NUL bytes, backslash tricks and symlinks | |
| 19 | + * that point outside the roots are all rejected with 403. /proc, /sys and /dev | |
| 20 | + * are refused even when they sit under an allowed root (/proc lives under /). | |
| 21 | + * | |
| 22 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | |
| 23 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | |
| 24 | + * scorpiox-server on the node. | |
| 25 | + * | |
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 27 | + */ | |
| 28 | + | |
| 29 | +/* Must come before every include on Windows: MinGW defaults to 0x502 | |
| 30 | + * (Server 2003), which hides GetFinalPathNameByHandleA and friends. */ | |
| 31 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | |
| 32 | +# define _WIN32_WINNT 0x0601 | |
| 33 | +#endif | |
| 34 | + | |
| 35 | +#if !defined(_WIN32) | |
| 36 | +# define _POSIX_C_SOURCE 200809L | |
| 37 | +# define _DEFAULT_SOURCE 1 | |
| 38 | +# if defined(__APPLE__) | |
| 39 | +# define _DARWIN_C_SOURCE 1 | |
| 40 | +# endif | |
| 41 | +#endif | |
| 42 | + | |
| 43 | +#include <stdio.h> | |
| 44 | +#include <stdlib.h> | |
| 45 | +#include <string.h> | |
| 46 | +#include <stdarg.h> | |
| 47 | +#include <ctype.h> | |
| 48 | +#include <errno.h> | |
| 49 | +#include <time.h> | |
| 50 | + | |
| 51 | +#if defined(_WIN32) | |
| 52 | +# define WIN32_LEAN_AND_MEAN | |
| 53 | +# include <windows.h> | |
| 54 | +# include <io.h> | |
| 55 | +# define SEP '\\' | |
| 56 | +#else | |
| 57 | +# include <unistd.h> | |
| 58 | +# include <sys/stat.h> | |
| 59 | +# include <sys/types.h> | |
| 60 | +# include <dirent.h> | |
| 61 | +# define SEP '/' | |
| 62 | +#endif | |
| 63 | + | |
| 64 | +#include "bot_theme_plugin.h" | |
| 65 | +#include "ui_html.h" | |
| 66 | + | |
| 67 | +#define PLUGIN_SLUG "files" | |
| 68 | +#define PLUGIN_ID "plugin_files" | |
| 69 | +#define PLUGIN_VER "1.0.0" | |
| 70 | +#define PLUGIN_NAME "files" | |
| 71 | +#define PLUGIN_DESC "File browser" | |
| 72 | + | |
| 73 | +#define PATH_SZ 4096 | |
| 74 | +#define NAME_SZ 512 | |
| 75 | +#define MAX_ROOTS 8 | |
| 76 | +#define MAX_ENTRIES 5000 | |
| 77 | +#define TEXT_CAP (1024 * 1024) /* 1 MiB text preview */ | |
| 78 | +#define RAW_CAP ((long long)64 * 1024 * 1024) /* 64 MiB raw stream */ | |
| 79 | +#define BIN_PROBE 8192 | |
| 80 | +#define IO_CHUNK 65536 | |
| 81 | + | |
| 82 | +typedef struct { | |
| 83 | + char name[NAME_SZ]; | |
| 84 | + int is_dir; | |
| 85 | + int is_link; | |
| 86 | + long long size; | |
| 87 | + long long mtime; | |
| 88 | + unsigned mode; | |
| 89 | +} ent_t; | |
| 90 | + | |
| 91 | +static char g_roots[MAX_ROOTS][PATH_SZ]; | |
| 92 | +static int g_root_count; | |
| 93 | + | |
| 94 | +/* ------------------------------------------------------------------ */ | |
| 95 | +/* Growable byte buffer */ | |
| 96 | +/* ------------------------------------------------------------------ */ | |
| 97 | + | |
| 98 | +typedef struct { | |
| 99 | + char *p; | |
| 100 | + size_t n; | |
| 101 | + size_t cap; | |
| 102 | +} buf_t; | |
| 103 | + | |
| 104 | +static void buf_init(buf_t *b) | |
| 105 | +{ | |
| 106 | + b->p = NULL; | |
| 107 | + b->n = 0; | |
| 108 | + b->cap = 0; | |
| 109 | +} | |
| 110 | + | |
| 111 | +static int buf_need(buf_t *b, size_t extra) | |
| 112 | +{ | |
| 113 | + size_t want = b->n + extra + 1; | |
| 114 | + char *np; | |
| 115 | + if (want <= b->cap) return 1; | |
| 116 | + if (b->cap == 0) b->cap = 1024; | |
| 117 | + while (b->cap < want) { | |
| 118 | + if (b->cap > (size_t)128 * 1024 * 1024) return 0; | |
| 119 | + b->cap *= 2; | |
| 120 | + } | |
| 121 | + np = (char *)realloc(b->p, b->cap); | |
| 122 | + if (!np) return 0; | |
| 123 | + b->p = np; | |
| 124 | + return 1; | |
| 125 | +} | |
| 126 | + | |
| 127 | +static void buf_add(buf_t *b, const char *s, size_t n) | |
| 128 | +{ | |
| 129 | + if (!buf_need(b, n)) return; | |
| 130 | + memcpy(b->p + b->n, s, n); | |
| 131 | + b->n += n; | |
| 132 | + b->p[b->n] = '\0'; | |
| 133 | +} | |
| 134 | + | |
| 135 | +static void buf_puts(buf_t *b, const char *s) | |
| 136 | +{ | |
| 137 | + if (s) buf_add(b, s, strlen(s)); | |
| 138 | +} | |
| 139 | + | |
| 140 | +static void buf_putc(buf_t *b, char c) | |
| 141 | +{ | |
| 142 | + if (!buf_need(b, 1)) return; | |
| 143 | + b->p[b->n++] = c; | |
| 144 | + b->p[b->n] = '\0'; | |
| 145 | +} | |
| 146 | + | |
| 147 | +static const char *buf_str(buf_t *b) | |
| 148 | +{ | |
| 149 | + return b->p ? b->p : ""; | |
| 150 | +} | |
| 151 | + | |
| 152 | +static void buf_printf(buf_t *b, const char *fmt, ...) | |
| 153 | +{ | |
| 154 | + char tmp[1024]; | |
| 155 | + va_list ap; | |
| 156 | + int n; | |
| 157 | + va_start(ap, fmt); | |
| 158 | + n = vsnprintf(tmp, sizeof tmp, fmt, ap); | |
| 159 | + va_end(ap); | |
| 160 | + if (n < 0) return; | |
| 161 | + if ((size_t)n < sizeof tmp) { | |
| 162 | + buf_add(b, tmp, (size_t)n); | |
| 163 | + return; | |
| 164 | + } | |
| 165 | + { | |
| 166 | + char *big = (char *)malloc((size_t)n + 1); | |
| 167 | + if (!big) return; | |
| 168 | + va_start(ap, fmt); | |
| 169 | + vsnprintf(big, (size_t)n + 1, fmt, ap); | |
| 170 | + va_end(ap); | |
| 171 | + buf_add(b, big, (size_t)n); | |
| 172 | + free(big); | |
| 173 | + } | |
| 174 | +} | |
| 175 | + | |
| 176 | +static void buf_free(buf_t *b) | |
| 177 | +{ | |
| 178 | + free(b->p); | |
| 179 | + b->p = NULL; | |
| 180 | + b->n = 0; | |
| 181 | + b->cap = 0; | |
| 182 | +} | |
| 183 | + | |
| 184 | +/* ------------------------------------------------------------------ */ | |
| 185 | +/* Small utilities */ | |
| 186 | +/* ------------------------------------------------------------------ */ | |
| 187 | + | |
| 188 | +static void str_copy(char *dst, size_t sz, const char *src) | |
| 189 | +{ | |
| 190 | + size_t n; | |
| 191 | + if (!dst || sz == 0) return; | |
| 192 | + if (!src) { dst[0] = '\0'; return; } | |
| 193 | + n = strlen(src); | |
| 194 | + if (n >= sz) n = sz - 1; | |
| 195 | + memcpy(dst, src, n); | |
| 196 | + dst[n] = '\0'; | |
| 197 | +} | |
| 198 | + | |
| 199 | +static void path_join(char *out, size_t sz, const char *a, const char *b) | |
| 200 | +{ | |
| 201 | + size_t n; | |
| 202 | + if (!out || sz == 0) return; | |
| 203 | + out[0] = '\0'; | |
| 204 | + if (!a) a = ""; | |
| 205 | + if (!b) b = ""; | |
| 206 | + str_copy(out, sz, a); | |
| 207 | + n = strlen(out); | |
| 208 | + if (n && out[n - 1] != '/' && out[n - 1] != '\\' && n + 1 < sz) { | |
| 209 | + out[n++] = SEP; | |
| 210 | + out[n] = '\0'; | |
| 211 | + } | |
| 212 | + if (n + strlen(b) < sz) str_copy(out + n, sz - n, b); | |
| 213 | +} | |
| 214 | + | |
| 215 | +static void url_decode(char *s) | |
| 216 | +{ | |
| 217 | + char *o = s; | |
| 218 | + if (!s) return; | |
| 219 | + while (*s) { | |
| 220 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | |
| 221 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | |
| 222 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | |
| 223 | + *o++ = (char)((hi << 4) | lo); | |
| 224 | + s += 3; | |
| 225 | + } else if (*s == '+') { | |
| 226 | + *o++ = ' '; | |
| 227 | + s++; | |
| 228 | + } else { | |
| 229 | + *o++ = *s++; | |
| 230 | + } | |
| 231 | + } | |
| 232 | + *o = '\0'; | |
| 233 | +} | |
| 234 | + | |
| 235 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 236 | +{ | |
| 237 | + size_t klen; | |
| 238 | + const char *p; | |
| 239 | + | |
| 240 | + if (!out || outsz == 0) return 0; | |
| 241 | + out[0] = '\0'; | |
| 242 | + if (!qs || !key) return 0; | |
| 243 | + klen = strlen(key); | |
| 244 | + | |
| 245 | + for (p = qs; *p; ) { | |
| 246 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | |
| 247 | + const char *v = p + klen + 1; | |
| 248 | + size_t i = 0; | |
| 249 | + while (*v && *v != '&' && i + 1 < outsz) | |
| 250 | + out[i++] = *v++; | |
| 251 | + out[i] = '\0'; | |
| 252 | + url_decode(out); | |
| 253 | + return 1; | |
| 254 | + } | |
| 255 | + p = strchr(p, '&'); | |
| 256 | + if (!p) break; | |
| 257 | + p++; | |
| 258 | + } | |
| 259 | + return 0; | |
| 260 | +} | |
| 261 | + | |
| 262 | +static void json_str(buf_t *b, const char *s) | |
| 263 | +{ | |
| 264 | + buf_putc(b, '"'); | |
| 265 | + for (; s && *s; s++) { | |
| 266 | + unsigned char c = (unsigned char)*s; | |
| 267 | + switch (c) { | |
| 268 | + case '"': buf_puts(b, "\\\""); break; | |
| 269 | + case '\\': buf_puts(b, "\\\\"); break; | |
| 270 | + case '\n': buf_puts(b, "\\n"); break; | |
| 271 | + case '\r': buf_puts(b, "\\r"); break; | |
| 272 | + case '\t': buf_puts(b, "\\t"); break; | |
| 273 | + default: | |
| 274 | + if (c < 0x20) { | |
| 275 | + char tmp[8]; | |
| 276 | + sprintf(tmp, "\\u%04x", c); | |
| 277 | + buf_puts(b, tmp); | |
| 278 | + } else { | |
| 279 | + buf_putc(b, (char)c); | |
| 280 | + } | |
| 281 | + } | |
| 282 | + } | |
| 283 | + buf_putc(b, '"'); | |
| 284 | +} | |
| 285 | + | |
| 286 | +static void fmt_iso(long long t, char *out, size_t sz) | |
| 287 | +{ | |
| 288 | + time_t tt = (time_t)t; | |
| 289 | + struct tm tmv; | |
| 290 | + if (t <= 0) { str_copy(out, sz, ""); return; } | |
| 291 | +#if defined(_WIN32) | |
| 292 | + gmtime_s(&tmv, &tt); | |
| 293 | +#else | |
| 294 | + gmtime_r(&tt, &tmv); | |
| 295 | +#endif | |
| 296 | + strftime(out, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); | |
| 297 | +} | |
| 298 | + | |
| 299 | +static int ci_cmp(const char *a, const char *b) | |
| 300 | +{ | |
| 301 | + for (;;) { | |
| 302 | + unsigned char ca = (unsigned char)*a++; | |
| 303 | + unsigned char cb = (unsigned char)*b++; | |
| 304 | + ca = (unsigned char)tolower(ca); | |
| 305 | + cb = (unsigned char)tolower(cb); | |
| 306 | + if (ca != cb) return ca < cb ? -1 : 1; | |
| 307 | + if (!ca) return 0; | |
| 308 | + } | |
| 309 | +} | |
| 310 | + | |
| 311 | +/* ------------------------------------------------------------------ */ | |
| 312 | +/* Path canonicalisation + allowlist */ | |
| 313 | +/* ------------------------------------------------------------------ */ | |
| 314 | + | |
| 315 | +/* POSIX: realpath() resolves every symlink, so the prefix check happens on | |
| 316 | + * the real target. Windows: GetFullPathNameA normalises `..`, then | |
| 317 | + * GetFinalPathNameByHandleA resolves reparse points when the file exists. */ | |
| 318 | + | |
| 319 | +#if defined(_WIN32) | |
| 320 | + | |
| 321 | +static void win_norm(char *s) | |
| 322 | +{ | |
| 323 | + for (; *s; s++) { | |
| 324 | + if (*s == '/') *s = '\\'; | |
| 325 | + *s = (char)tolower((unsigned char)*s); | |
| 326 | + } | |
| 327 | +} | |
| 328 | + | |
| 329 | +static int path_under_win(const char *p, const char *root) | |
| 330 | +{ | |
| 331 | + char a[PATH_SZ], b[PATH_SZ]; | |
| 332 | + size_t n; | |
| 333 | + str_copy(a, sizeof a, p); | |
| 334 | + str_copy(b, sizeof b, root); | |
| 335 | + win_norm(a); | |
| 336 | + win_norm(b); | |
| 337 | + n = strlen(b); | |
| 338 | + while (n > 3 && b[n - 1] == '\\') b[--n] = '\0'; | |
| 339 | + if (strcmp(a, b) == 0) return 1; | |
| 340 | + if (strncmp(a, b, n) == 0 && a[n] == '\\') return 1; | |
| 341 | + return 0; | |
| 342 | +} | |
| 343 | + | |
| 344 | +static int canon_path(const char *raw, char *out, size_t outsz, int *err) | |
| 345 | +{ | |
| 346 | + char full[PATH_SZ]; | |
| 347 | + DWORD n; | |
| 348 | + HANDLE h; | |
| 349 | + char final[PATH_SZ]; | |
| 350 | + | |
| 351 | + *err = 0; | |
| 352 | + if (!raw || !*raw) { *err = 400; return 0; } | |
| 353 | + if (strchr(raw, '\0') == NULL) return 0; /* unreachable; keeps compilers quiet */ | |
| 354 | + | |
| 355 | + n = GetFullPathNameA(raw, (DWORD)sizeof full, full, NULL); | |
| 356 | + if (n == 0 || n >= (DWORD)sizeof full) { *err = 400; return 0; } | |
| 357 | + | |
| 358 | + if (GetFileAttributesA(full) == INVALID_FILE_ATTRIBUTES) { *err = 404; return 0; } | |
| 359 | + | |
| 360 | + h = CreateFileA(full, 0, | |
| 361 | + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, | |
| 362 | + NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); | |
| 363 | + if (h != INVALID_HANDLE_VALUE) { | |
| 364 | + DWORD fn = GetFinalPathNameByHandleA(h, final, (DWORD)sizeof final, 0); | |
| 365 | + CloseHandle(h); | |
| 366 | + if (fn > 0 && fn < (DWORD)sizeof final) { | |
| 367 | + char *src = final; | |
| 368 | + if (strncmp(src, "\\\\?\\", 4) == 0) src += 4; | |
| 369 | + str_copy(out, outsz, src); | |
| 370 | + return 1; | |
| 371 | + } | |
| 372 | + } | |
| 373 | + str_copy(out, outsz, full); | |
| 374 | + return 1; | |
| 375 | +} | |
| 376 | + | |
| 377 | +#else /* POSIX */ | |
| 378 | + | |
| 379 | +static int path_under(const char *p, const char *root) | |
| 380 | +{ | |
| 381 | + size_t n = strlen(root); | |
| 382 | + if (strcmp(p, root) == 0) return 1; | |
| 383 | + if (n && root[n - 1] == '/') return strncmp(p, root, n) == 0; | |
| 384 | + if (n && strncmp(p, root, n) == 0 && p[n] == '/') return 1; | |
| 385 | + return 0; | |
| 386 | +} | |
| 387 | + | |
| 388 | +static int canon_path(const char *raw, char *out, size_t outsz, int *err) | |
| 389 | +{ | |
| 390 | + char *r; | |
| 391 | + *err = 0; | |
| 392 | + if (!raw || !*raw) { *err = 400; return 0; } | |
| 393 | + if (raw[0] != '/') { *err = 400; return 0; } | |
| 394 | + if (strstr(raw, "/../") || (strlen(raw) > 3 && strcmp(raw + strlen(raw) - 3, "/..") == 0)) { | |
| 395 | + /* realpath would handle it, but a `..` in a browse path is always a | |
| 396 | + * probe, never a legit UI request. */ | |
| 397 | + *err = 400; | |
| 398 | + return 0; | |
| 399 | + } | |
| 400 | + r = realpath(raw, NULL); | |
| 401 | + if (!r) { *err = (errno == ENOENT || errno == ENOTDIR) ? 404 : 403; return 0; } | |
| 402 | + str_copy(out, outsz, r); | |
| 403 | + free(r); | |
| 404 | + return 1; | |
| 405 | +} | |
| 406 | + | |
| 407 | +#endif | |
| 408 | + | |
| 409 | +/* Paths that must never be browsed even when they sit under an allowed root. */ | |
| 410 | +static int denied_path(const char *p) | |
| 411 | +{ | |
| 412 | +#if defined(_WIN32) | |
| 413 | + (void)p; | |
| 414 | + return 0; | |
| 415 | +#else | |
| 416 | + static const char *deny[] = { "/proc", "/sys", "/dev" }; | |
| 417 | + size_t i; | |
| 418 | + for (i = 0; i < sizeof deny / sizeof deny[0]; i++) | |
| 419 | + if (path_under(p, deny[i])) return 1; | |
| 420 | + return 0; | |
| 421 | +#endif | |
| 422 | +} | |
| 423 | + | |
| 424 | +static int is_allowed(const char *canon) | |
| 425 | +{ | |
| 426 | + int i; | |
| 427 | + if (denied_path(canon)) return 0; | |
| 428 | + for (i = 0; i < g_root_count; i++) { | |
| 429 | +#if defined(_WIN32) | |
| 430 | + if (path_under_win(canon, g_roots[i])) return 1; | |
| 431 | +#else | |
| 432 | + if (path_under(canon, g_roots[i])) return 1; | |
| 433 | +#endif | |
| 434 | + } | |
| 435 | + return 0; | |
| 436 | +} | |
| 437 | + | |
| 438 | +/* Resolve + authorise in one step. Returns 1 on success. */ | |
| 439 | +static int resolve_allowed(const char *raw, char *out, size_t outsz, int *err) | |
| 440 | +{ | |
| 441 | + if (!canon_path(raw, out, outsz, err)) return 0; | |
| 442 | + if (!is_allowed(out)) { *err = 403; return 0; } | |
| 443 | + return 1; | |
| 444 | +} | |
| 445 | + | |
| 446 | +/* Which allowlisted root contains this canonical path (-1 = none). */ | |
| 447 | +static int root_of(const char *canon) | |
| 448 | +{ | |
| 449 | + int i; | |
| 450 | + for (i = 0; i < g_root_count; i++) { | |
| 451 | +#if defined(_WIN32) | |
| 452 | + if (path_under_win(canon, g_roots[i])) return i; | |
| 453 | +#else | |
| 454 | + if (path_under(canon, g_roots[i])) return i; | |
| 455 | +#endif | |
| 456 | + } | |
| 457 | + return -1; | |
| 458 | +} | |
| 459 | + | |
| 460 | +static void parent_of(const char *canon, char *out, size_t outsz) | |
| 461 | +{ | |
| 462 | + size_t n; | |
| 463 | + str_copy(out, outsz, canon); | |
| 464 | + n = strlen(out); | |
| 465 | + while (n > 1 && (out[n - 1] == '/' || out[n - 1] == '\\')) out[--n] = '\0'; | |
| 466 | +#if defined(_WIN32) | |
| 467 | + while (n > 3 && out[n - 1] != '\\') out[--n] = '\0'; | |
| 468 | + if (n > 3) out[--n] = '\0'; | |
| 469 | + else str_copy(out, outsz, canon); | |
| 470 | +#else | |
| 471 | + while (n > 1 && out[n - 1] != '/') out[--n] = '\0'; | |
| 472 | + if (n > 1) out[--n] = '\0'; | |
| 473 | + if (outsz && out[0] == '\0') str_copy(out, outsz, "/"); | |
| 474 | +#endif | |
| 475 | +} | |
| 476 | + | |
| 477 | +/* ------------------------------------------------------------------ */ | |
| 478 | +/* Allowlisted roots */ | |
| 479 | +/* ------------------------------------------------------------------ */ | |
| 480 | + | |
| 481 | +static void add_root(const char *cand) | |
| 482 | +{ | |
| 483 | + char canon[PATH_SZ]; | |
| 484 | + int err = 0; | |
| 485 | + int i; | |
| 486 | + | |
| 487 | + if (g_root_count >= MAX_ROOTS) return; | |
| 488 | + if (!cand || !*cand) return; | |
| 489 | + if (!canon_path(cand, canon, sizeof canon, &err)) return; | |
| 490 | + if (denied_path(canon)) return; | |
| 491 | + for (i = 0; i < g_root_count; i++) { | |
| 492 | +#if defined(_WIN32) | |
| 493 | + if (path_under_win(canon, g_roots[i]) && path_under_win(g_roots[i], canon)) return; | |
| 494 | +#else | |
| 495 | + if (strcmp(canon, g_roots[i]) == 0) return; | |
| 496 | +#endif | |
| 497 | + } | |
| 498 | + str_copy(g_roots[g_root_count], sizeof g_roots[g_root_count], canon); | |
| 499 | + g_root_count++; | |
| 500 | +} | |
| 501 | + | |
| 502 | +static void init_roots(void) | |
| 503 | +{ | |
| 504 | + const char *extra; | |
| 505 | + const char *home; | |
| 506 | + | |
| 507 | + if (g_root_count) return; | |
| 508 | + | |
| 509 | +#if defined(_WIN32) | |
| 510 | + home = getenv("USERPROFILE"); | |
| 511 | + add_root("D:\\codebases"); | |
| 512 | + if (home && *home) add_root(home); | |
| 513 | +#else | |
| 514 | + add_root("/workspace"); | |
| 515 | + add_root("/codebases"); | |
| 516 | + home = getenv("HOME"); | |
| 517 | + if (home && *home) add_root(home); | |
| 518 | +#endif | |
| 519 | + | |
| 520 | + /* $FILES_ALLOWED_ROOT: one extra root, or several separated by ':' on | |
| 521 | + * POSIX / ';' on Windows. Tests use it to point at a fixture tree. */ | |
| 522 | + extra = getenv("FILES_ALLOWED_ROOT"); | |
| 523 | + if (extra && *extra) { | |
| 524 | +#if defined(_WIN32) | |
| 525 | + const char *sep = ";"; | |
| 526 | +#else | |
| 527 | + const char *sep = ":"; | |
| 528 | +#endif | |
| 529 | + char tmp[PATH_SZ]; | |
| 530 | + const char *p = extra; | |
| 531 | + while (*p) { | |
| 532 | + const char *e = strstr(p, sep); | |
| 533 | + size_t n = e ? (size_t)(e - p) : strlen(p); | |
| 534 | + if (n < sizeof tmp) { | |
| 535 | + memcpy(tmp, p, n); | |
| 536 | + tmp[n] = '\0'; | |
| 537 | + add_root(tmp); | |
| 538 | + } | |
| 539 | + if (!e) break; | |
| 540 | + p = e + strlen(sep); | |
| 541 | + } | |
| 542 | + } | |
| 543 | +} | |
| 544 | + | |
| 545 | +/* ------------------------------------------------------------------ */ | |
| 546 | +/* Directory listing */ | |
| 547 | +/* ------------------------------------------------------------------ */ | |
| 548 | + | |
| 549 | +static int ent_cmp(const void *pa, const void *pb) | |
| 550 | +{ | |
| 551 | + const ent_t *a = (const ent_t *)pa; | |
| 552 | + const ent_t *b = (const ent_t *)pb; | |
| 553 | + if (a->is_dir != b->is_dir) return a->is_dir ? -1 : 1; | |
| 554 | + return ci_cmp(a->name, b->name); | |
| 555 | +} | |
| 556 | + | |
| 557 | +static void fill_entry_meta(ent_t *e, const char *full) | |
| 558 | +{ | |
| 559 | +#if defined(_WIN32) | |
| 560 | + WIN32_FILE_ATTRIBUTE_DATA fd; | |
| 561 | + if (GetFileAttributesExA(full, GetFileExInfoStandard, &fd)) { | |
| 562 | + ULARGE_INTEGER sz, tm; | |
| 563 | + e->size = 0; | |
| 564 | + sz.LowPart = fd.nFileSizeLow; | |
| 565 | + sz.HighPart = fd.nFileSizeHigh; | |
| 566 | + e->size = (long long)sz.QuadPart; | |
| 567 | + tm.LowPart = fd.ftLastWriteTime.dwLowDateTime; | |
| 568 | + tm.HighPart = fd.ftLastWriteTime.dwHighDateTime; | |
| 569 | + /* FILETIME -> unix seconds */ | |
| 570 | + e->mtime = (long long)((tm.QuadPart / 10000000ULL) - 11644473600ULL); | |
| 571 | + e->mode = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? 0755u : 0644u; | |
| 572 | + } | |
| 573 | +#else | |
| 574 | + struct stat st; | |
| 575 | + struct stat lst; | |
| 576 | + if (lstat(full, &lst) == 0) { | |
| 577 | + e->is_link = S_ISLNK(lst.st_mode) ? 1 : 0; | |
| 578 | + e->size = (long long)lst.st_size; | |
| 579 | + e->mtime = (long long)lst.st_mtime; | |
| 580 | + e->mode = (unsigned)(lst.st_mode & 07777); | |
| 581 | + if (stat(full, &st) == 0) { | |
| 582 | + if (S_ISDIR(st.st_mode)) e->is_dir = 1; | |
| 583 | + e->size = (long long)st.st_size; | |
| 584 | + e->mode = (unsigned)(st.st_mode & 07777); | |
| 585 | + } | |
| 586 | + } | |
| 587 | +#endif | |
| 588 | +} | |
| 589 | + | |
| 590 | +static int list_dir(const char *path, int show_hidden, ent_t **out, int *count, int *truncated) | |
| 591 | +{ | |
| 592 | + ent_t *ents; | |
| 593 | + int n = 0; | |
| 594 | + int trunc = 0; | |
| 595 | + | |
| 596 | + ents = (ent_t *)calloc(MAX_ENTRIES, sizeof(ent_t)); | |
| 597 | + if (!ents) return 0; | |
| 598 | + | |
| 599 | +#if defined(_WIN32) | |
| 600 | + { | |
| 601 | + char pattern[PATH_SZ]; | |
| 602 | + WIN32_FIND_DATAA fd; | |
| 603 | + HANDLE h; | |
| 604 | + path_join(pattern, sizeof pattern, path, "*"); | |
| 605 | + h = FindFirstFileA(pattern, &fd); | |
| 606 | + if (h == INVALID_HANDLE_VALUE) { free(ents); return 0; } | |
| 607 | + do { | |
| 608 | + char full[PATH_SZ]; | |
| 609 | + ent_t *e; | |
| 610 | + if (!strcmp(fd.cFileName, ".") || !strcmp(fd.cFileName, "..")) continue; | |
| 611 | + if (!show_hidden && fd.cFileName[0] == '.') continue; | |
| 612 | + if (n >= MAX_ENTRIES) { trunc = 1; break; } | |
| 613 | + e = &ents[n]; | |
| 614 | + memset(e, 0, sizeof *e); | |
| 615 | + str_copy(e->name, sizeof e->name, fd.cFileName); | |
| 616 | + e->is_dir = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? 1 : 0; | |
| 617 | + e->is_link = (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) ? 1 : 0; | |
| 618 | + path_join(full, sizeof full, path, fd.cFileName); | |
| 619 | + fill_entry_meta(e, full); | |
| 620 | + n++; | |
| 621 | + } while (FindNextFileA(h, &fd)); | |
| 622 | + FindClose(h); | |
| 623 | + } | |
| 624 | +#else | |
| 625 | + { | |
| 626 | + DIR *d = opendir(path); | |
| 627 | + struct dirent *de; | |
| 628 | + if (!d) { free(ents); return 0; } | |
| 629 | + while ((de = readdir(d)) != NULL) { | |
| 630 | + char full[PATH_SZ]; | |
| 631 | + ent_t *e; | |
| 632 | + if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue; | |
| 633 | + if (!show_hidden && de->d_name[0] == '.') continue; | |
| 634 | + if (n >= MAX_ENTRIES) { trunc = 1; break; } | |
| 635 | + e = &ents[n]; | |
| 636 | + memset(e, 0, sizeof *e); | |
| 637 | + str_copy(e->name, sizeof e->name, de->d_name); | |
| 638 | + path_join(full, sizeof full, path, de->d_name); | |
| 639 | + fill_entry_meta(e, full); | |
| 640 | + n++; | |
| 641 | + } | |
| 642 | + closedir(d); | |
| 643 | + } | |
| 644 | +#endif | |
| 645 | + | |
| 646 | + if (n > 1) qsort(ents, (size_t)n, sizeof(ent_t), ent_cmp); | |
| 647 | + *out = ents; | |
| 648 | + *count = n; | |
| 649 | + *truncated = trunc; | |
| 650 | + return 1; | |
| 651 | +} | |
| 652 | + | |
| 653 | +/* ------------------------------------------------------------------ */ | |
| 654 | +/* Node authentication */ | |
| 655 | +/* ------------------------------------------------------------------ */ | |
| 656 | + | |
| 657 | +static void require_node_auth(void) | |
| 658 | +{ | |
| 659 | + const char *np = getenv("BOT_PASSWORD"); | |
| 660 | + const char *xp; | |
| 661 | + const char *auth; | |
| 662 | + const char *qs; | |
| 663 | + char qpwd[256]; | |
| 664 | + | |
| 665 | + if (!np || !*np) return; | |
| 666 | + | |
| 667 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | |
| 668 | + if (xp && strcmp(xp, np) == 0) return; | |
| 669 | + | |
| 670 | + auth = getenv("HTTP_AUTHORIZATION"); | |
| 671 | + if (auth) { | |
| 672 | + while (*auth == ' ') auth++; | |
| 673 | + if (strncmp(auth, "Bearer ", 7) == 0) { | |
| 674 | + auth += 7; | |
| 675 | + while (*auth == ' ') auth++; | |
| 676 | + if (strcmp(auth, np) == 0) return; | |
| 677 | + } | |
| 678 | + } | |
| 679 | + | |
| 680 | + qs = getenv("QUERY_STRING"); | |
| 681 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) | |
| 682 | + return; | |
| 683 | + | |
| 684 | + fputs("Status: 401 Unauthorized\r\n" | |
| 685 | + "Content-Type: application/json; charset=utf-8\r\n" | |
| 686 | + "Cache-Control: no-store\r\n" | |
| 687 | + "X-Content-Type-Options: nosniff\r\n\r\n" | |
| 688 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | |
| 689 | + exit(0); | |
| 690 | +} | |
| 691 | + | |
| 692 | +/* ------------------------------------------------------------------ */ | |
| 693 | +/* JSON responses */ | |
| 694 | +/* ------------------------------------------------------------------ */ | |
| 695 | + | |
| 696 | +static void json_header(void) | |
| 697 | +{ | |
| 698 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | |
| 699 | + "Cache-Control: no-store\r\n" | |
| 700 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 701 | +} | |
| 702 | + | |
| 703 | +static void json_err(int code, const char *msg) | |
| 704 | +{ | |
| 705 | + if (code == 400) fputs("Status: 400 Bad Request\r\n", stdout); | |
| 706 | + else if (code == 403) fputs("Status: 403 Forbidden\r\n", stdout); | |
| 707 | + else if (code == 404) fputs("Status: 404 Not Found\r\n", stdout); | |
| 708 | + else if (code == 405) fputs("Status: 405 Method Not Allowed\r\n", stdout); | |
| 709 | + else if (code == 413) fputs("Status: 413 Payload Too Large\r\n", stdout); | |
| 710 | + else fputs("Status: 500 Internal Server Error\r\n", stdout); | |
| 711 | + json_header(); | |
| 712 | + printf("{\"ok\":false,\"error\":"); | |
| 713 | + { | |
| 714 | + buf_t b; | |
| 715 | + buf_init(&b); | |
| 716 | + json_str(&b, msg ? msg : "error"); | |
| 717 | + fputs(buf_str(&b), stdout); | |
| 718 | + buf_free(&b); | |
| 719 | + } | |
| 720 | + fputs("}\n", stdout); | |
| 721 | +} | |
| 722 | + | |
| 723 | +/* ------------------------------------------------------------------ */ | |
| 724 | +/* ?action=roots */ | |
| 725 | +/* ------------------------------------------------------------------ */ | |
| 726 | + | |
| 727 | +static void do_roots(void) | |
| 728 | +{ | |
| 729 | + int i; | |
| 730 | + buf_t b; | |
| 731 | + buf_init(&b); | |
| 732 | + buf_printf(&b, "{\"ok\":true,\"count\":%d,\"roots\":[", g_root_count); | |
| 733 | + for (i = 0; i < g_root_count; i++) { | |
| 734 | + const char *base = strrchr(g_roots[i], SEP); | |
| 735 | + char label[NAME_SZ]; | |
| 736 | + if (i) buf_putc(&b, ','); | |
| 737 | + buf_puts(&b, "\n {\"path\":"); | |
| 738 | + json_str(&b, g_roots[i]); | |
| 739 | + buf_puts(&b, ",\"name\":"); | |
| 740 | + if (base && base[1]) str_copy(label, sizeof label, base + 1); | |
| 741 | + else str_copy(label, sizeof label, g_roots[i]); | |
| 742 | + json_str(&b, label); | |
| 743 | + buf_putc(&b, '}'); | |
| 744 | + } | |
| 745 | + buf_puts(&b, "\n]}\n"); | |
| 746 | + json_header(); | |
| 747 | + fputs(buf_str(&b), stdout); | |
| 748 | + buf_free(&b); | |
| 749 | +} | |
| 750 | + | |
| 751 | +/* ------------------------------------------------------------------ */ | |
| 752 | +/* ?action=ls&path=<abs> */ | |
| 753 | +/* ------------------------------------------------------------------ */ | |
| 754 | + | |
| 755 | +static const char *ent_kind(const ent_t *e) | |
| 756 | +{ | |
| 757 | + if (e->is_dir) return "dir"; | |
| 758 | + if (e->is_link) return "link"; | |
| 759 | + return "file"; | |
| 760 | +} | |
| 761 | + | |
| 762 | +static void do_ls(const char *raw_path, const char *qs) | |
| 763 | +{ | |
| 764 | + char canon[PATH_SZ]; | |
| 765 | + char parent[PATH_SZ]; | |
| 766 | + char hiddenbuf[8]; | |
| 767 | + int show_hidden = 0; | |
| 768 | + int err = 0; | |
| 769 | + int count = 0, trunc = 0; | |
| 770 | + int ri; | |
| 771 | + ent_t *ents = NULL; | |
| 772 | + buf_t b; | |
| 773 | + int i; | |
| 774 | + | |
| 775 | + if (!raw_path || !*raw_path) { | |
| 776 | + if (g_root_count) str_copy(canon, sizeof canon, g_roots[0]); | |
| 777 | + else { json_err(500, "no allowlisted root available"); return; } | |
| 778 | + } | |
| 779 | + | |
| 780 | + if (raw_path && *raw_path) { | |
| 781 | + if (!resolve_allowed(raw_path, canon, sizeof canon, &err)) { | |
| 782 | + json_err(err, err == 403 ? "path not allowed" : (err == 404 ? "path not found" : "bad path")); | |
| 783 | + return; | |
| 784 | + } | |
| 785 | + } | |
| 786 | + | |
| 787 | + if (get_query_val(qs, "hidden", hiddenbuf, sizeof hiddenbuf)) { | |
| 788 | + show_hidden = (strcmp(hiddenbuf, "1") == 0 || strcmp(hiddenbuf, "true") == 0); | |
| 789 | + } | |
| 790 | + | |
| 791 | + if (!list_dir(canon, show_hidden, &ents, &count, &trunc)) { | |
| 792 | + json_err(403, "cannot list directory"); | |
| 793 | + return; | |
| 794 | + } | |
| 795 | + | |
| 796 | + ri = root_of(canon); | |
| 797 | + parent[0] = '\0'; | |
| 798 | + if (ri >= 0 && strcmp(canon, g_roots[ri]) != 0) | |
| 799 | + parent_of(canon, parent, sizeof parent); | |
| 800 | + | |
| 801 | + buf_init(&b); | |
| 802 | + buf_puts(&b, "{\"ok\":true,\"path\":"); | |
| 803 | + json_str(&b, canon); | |
| 804 | + buf_puts(&b, ",\"parent\":"); | |
| 805 | + if (parent[0]) json_str(&b, parent); else buf_puts(&b, "null"); | |
| 806 | + buf_puts(&b, ",\"root\":"); | |
| 807 | + if (ri >= 0) json_str(&b, g_roots[ri]); else buf_puts(&b, "null"); | |
| 808 | + buf_puts(&b, ",\"hidden\":"); | |
| 809 | + buf_putc(&b, show_hidden ? '1' : '0'); | |
| 810 | + buf_printf(&b, ",\"count\":%d,\"truncated\":%s,\"entries\":[", | |
| 811 | + count, trunc ? "true" : "false"); | |
| 812 | + | |
| 813 | + for (i = 0; i < count; i++) { | |
| 814 | + char iso[32]; | |
| 815 | + char mode[8]; | |
| 816 | + fmt_iso(ents[i].mtime, iso, sizeof iso); | |
| 817 | + sprintf(mode, "%04o", ents[i].mode & 07777); | |
| 818 | + buf_puts(&b, i ? ",\n {\"name\":" : "\n {\"name\":"); | |
| 819 | + json_str(&b, ents[i].name); | |
| 820 | + buf_puts(&b, ",\"type\":\""); | |
| 821 | + buf_puts(&b, ent_kind(&ents[i])); | |
| 822 | + buf_printf(&b, "\",\"size\":%lld,\"mtime\":\"%s\",\"mode\":\"%s\"}", | |
| 823 | + ents[i].size, iso, mode); | |
| 824 | + } | |
| 825 | + buf_puts(&b, "\n]}\n"); | |
| 826 | + | |
| 827 | + json_header(); | |
| 828 | + fputs(buf_str(&b), stdout); | |
| 829 | + free(ents); | |
| 830 | + buf_free(&b); | |
| 831 | +} | |
| 832 | + | |
| 833 | +/* ------------------------------------------------------------------ */ | |
| 834 | +/* ?action=read&path=<abs> */ | |
| 835 | +/* ------------------------------------------------------------------ */ | |
| 836 | + | |
| 837 | +static int read_range(const char *path, char *out, size_t cap, size_t *got, int *binary) | |
| 838 | +{ | |
| 839 | + FILE *f; | |
| 840 | + size_t n; | |
| 841 | + | |
| 842 | + *got = 0; | |
| 843 | + *binary = 0; | |
| 844 | + f = fopen(path, "rb"); | |
| 845 | + if (!f) return 0; | |
| 846 | + n = fread(out, 1, cap, f); | |
| 847 | + if (ferror(f)) { fclose(f); return 0; } | |
| 848 | + *got = n; | |
| 849 | + { | |
| 850 | + size_t lim = n < BIN_PROBE ? n : BIN_PROBE; | |
| 851 | + size_t i; | |
| 852 | + for (i = 0; i < lim; i++) { | |
| 853 | + if (out[i] == '\0') { *binary = 1; break; } | |
| 854 | + } | |
| 855 | + } | |
| 856 | + fclose(f); | |
| 857 | + return 1; | |
| 858 | +} | |
| 859 | + | |
| 860 | +static void do_read(const char *raw_path) | |
| 861 | +{ | |
| 862 | + char canon[PATH_SZ]; | |
| 863 | + int err = 0; | |
| 864 | + struct { long long size; long long mtime; unsigned mode; int is_dir; } info; | |
| 865 | + char iso[32], mode[8]; | |
| 866 | + static char text[TEXT_CAP + 1]; | |
| 867 | + size_t got = 0; | |
| 868 | + int binary = 0; | |
| 869 | + int trunc = 0; | |
| 870 | + buf_t b; | |
| 871 | + | |
| 872 | +#if defined(_WIN32) | |
| 873 | + { | |
| 874 | + WIN32_FILE_ATTRIBUTE_DATA fd; | |
| 875 | + memset(&info, 0, sizeof info); | |
| 876 | + if (!resolve_allowed(raw_path, canon, sizeof canon, &err)) { | |
| 877 | + json_err(err, err == 403 ? "path not allowed" : (err == 404 ? "path not found" : "bad path")); | |
| 878 | + return; | |
| 879 | + } | |
| 880 | + if (!GetFileAttributesExA(canon, GetFileExInfoStandard, &fd)) { | |
| 881 | + json_err(404, "path not found"); | |
| 882 | + return; | |
| 883 | + } | |
| 884 | + info.is_dir = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? 1 : 0; | |
| 885 | + { | |
| 886 | + ULARGE_INTEGER sz, tm; | |
| 887 | + sz.LowPart = fd.nFileSizeLow; sz.HighPart = fd.nFileSizeHigh; | |
| 888 | + info.size = (long long)sz.QuadPart; | |
| 889 | + tm.LowPart = fd.ftLastWriteTime.dwLowDateTime; tm.HighPart = fd.ftLastWriteTime.dwHighDateTime; | |
| 890 | + info.mtime = (long long)((tm.QuadPart / 10000000ULL) - 11644473600ULL); | |
| 891 | + } | |
| 892 | + info.mode = info.is_dir ? 0755u : 0644u; | |
| 893 | + } | |
| 894 | +#else | |
| 895 | + { | |
| 896 | + struct stat st; | |
| 897 | + memset(&info, 0, sizeof info); | |
| 898 | + if (!resolve_allowed(raw_path, canon, sizeof canon, &err)) { | |
| 899 | + json_err(err, err == 403 ? "path not allowed" : (err == 404 ? "path not found" : "bad path")); | |
| 900 | + return; | |
| 901 | + } | |
| 902 | + if (stat(canon, &st) != 0) { json_err(404, "path not found"); return; } | |
| 903 | + info.is_dir = S_ISDIR(st.st_mode) ? 1 : 0; | |
| 904 | + info.size = (long long)st.st_size; | |
| 905 | + info.mtime = (long long)st.st_mtime; | |
| 906 | + info.mode = (unsigned)(st.st_mode & 07777); | |
| 907 | + } | |
| 908 | +#endif | |
| 909 | + | |
| 910 | + if (info.is_dir) { json_err(400, "not a regular file"); return; } | |
| 911 | + | |
| 912 | + if (info.size > TEXT_CAP) trunc = 1; | |
| 913 | + if (!read_range(canon, text, TEXT_CAP, &got, &binary)) { | |
| 914 | + json_err(403, "cannot read file"); | |
| 915 | + return; | |
| 916 | + } | |
| 917 | + text[got] = '\0'; | |
| 918 | + if (binary) trunc = 0; | |
| 919 | + | |
| 920 | + fmt_iso(info.mtime, iso, sizeof iso); | |
| 921 | + sprintf(mode, "%04o", info.mode & 07777); | |
| 922 | + buf_init(&b); | |
| 923 | + buf_puts(&b, "{\"ok\":true,\"path\":"); | |
| 924 | + json_str(&b, canon); | |
| 925 | + buf_puts(&b, ",\"name\":"); | |
| 926 | + { | |
| 927 | + const char *base = strrchr(canon, SEP); | |
| 928 | + json_str(&b, (base && base[1]) ? base + 1 : canon); | |
| 929 | + } | |
| 930 | + buf_printf(&b, ",\"size\":%lld,\"mtime\":\"%s\",\"mode\":\"%s\"", info.size, iso, mode); | |
| 931 | + buf_printf(&b, ",\"binary\":%s,\"truncated\":%s,\"bytes_read\":%lu", | |
| 932 | + binary ? "true" : "false", trunc ? "true" : "false", (unsigned long)got); | |
| 933 | + if (!binary) { | |
| 934 | + buf_puts(&b, ",\"text\":"); | |
| 935 | + json_str(&b, text); | |
| 936 | + } | |
| 937 | + buf_puts(&b, "}\n"); | |
| 938 | + | |
| 939 | + json_header(); | |
| 940 | + fputs(buf_str(&b), stdout); | |
| 941 | + buf_free(&b); | |
| 942 | +} | |
| 943 | + | |
| 944 | +typedef struct { const char *ext; const char *type; } mime_t; | |
| 945 | + | |
| 946 | +static const mime_t g_mime[] = { | |
| 947 | + { "png", "image/png" }, | |
| 948 | + { "jpg", "image/jpeg" }, | |
| 949 | + { "jpeg", "image/jpeg" }, | |
| 950 | + { "gif", "image/gif" }, | |
| 951 | + { "webp", "image/webp" }, | |
| 952 | + { "bmp", "image/bmp" }, | |
| 953 | + { "ico", "image/x-icon" }, | |
| 954 | + { "svg", "text/plain; charset=utf-8" }, | |
| 955 | + { "pdf", "application/pdf" }, | |
| 956 | + { "txt", "text/plain; charset=utf-8" }, | |
| 957 | + { "md", "text/plain; charset=utf-8" }, | |
| 958 | + { "json", "text/plain; charset=utf-8" }, | |
| 959 | + { "c", "text/plain; charset=utf-8" }, | |
| 960 | + { "h", "text/plain; charset=utf-8" }, | |
| 961 | + { "log", "text/plain; charset=utf-8" } | |
| 962 | +}; | |
| 963 | + | |
| 964 | +/* Markup is served as text/plain on purpose: this route shares an origin with | |
| 965 | + * the node API, so rendering a local .html file as text/html would hand any | |
| 966 | + * page on disk the ability to call the plugin API with the user's password. | |
| 967 | + * Images keep their real type because <img> only decodes them. */ | |
| 968 | +static const char *guess_type(const char *name) | |
| 969 | +{ | |
| 970 | + const char *dot = strrchr(name, '.'); | |
| 971 | + size_t i; | |
| 972 | + if (!dot || !dot[1]) return "application/octet-stream"; | |
| 973 | + for (i = 0; i < sizeof g_mime / sizeof g_mime[0]; i++) { | |
| 974 | + size_t k = strlen(g_mime[i].ext); | |
| 975 | + size_t n = strlen(dot + 1); | |
| 976 | + if (n == k) { | |
| 977 | + size_t j; int same = 1; | |
| 978 | + for (j = 0; j < k; j++) | |
| 979 | + if (tolower((unsigned char)dot[1 + j]) != g_mime[i].ext[j]) { same = 0; break; } | |
| 980 | + if (same) return g_mime[i].type; | |
| 981 | + } | |
| 982 | + } | |
| 983 | + if (strstr(dot + 1, "htm")) return "text/plain; charset=utf-8"; | |
| 984 | + return "application/octet-stream"; | |
| 985 | +} | |
| 986 | + | |
| 987 | +static int is_image_type(const char *t) | |
| 988 | +{ | |
| 989 | + return strncmp(t, "image/", 6) == 0; | |
| 990 | +} | |
| 991 | + | |
| 992 | +/* Header-safe file name: quotes, CR and LF out. */ | |
| 993 | +static void header_name(const char *name, char *out, size_t sz) | |
| 994 | +{ | |
| 995 | + size_t i = 0; | |
| 996 | + for (; *name && i + 1 < sz; name++) { | |
| 997 | + char c = *name; | |
| 998 | + if (c == '"' || c == '\\' || c == '\r' || c == '\n') c = '_'; | |
| 999 | + out[i++] = c; | |
| 1000 | + } | |
| 1001 | + out[i] = '\0'; | |
| 1002 | +} | |
| 1003 | + | |
| 1004 | +static void do_raw(const char *raw_path, const char *qs) | |
| 1005 | +{ | |
| 1006 | + char canon[PATH_SZ]; | |
| 1007 | + char name[NAME_SZ]; | |
| 1008 | + char hn[NAME_SZ]; | |
| 1009 | + char dl[8]; | |
| 1010 | + const char *base; | |
| 1011 | + const char *type; | |
| 1012 | + int err = 0; | |
| 1013 | + long long size = -1; | |
| 1014 | + int want_dl = 0; | |
| 1015 | + FILE *f; | |
| 1016 | + static char chunk[IO_CHUNK]; | |
| 1017 | + | |
| 1018 | +#if defined(_WIN32) | |
| 1019 | + { | |
| 1020 | + WIN32_FILE_ATTRIBUTE_DATA fd; | |
| 1021 | + if (!resolve_allowed(raw_path, canon, sizeof canon, &err)) { | |
| 1022 | + json_err(err, err == 403 ? "path not allowed" : (err == 404 ? "path not found" : "bad path")); | |
| 1023 | + return; | |
| 1024 | + } | |
| 1025 | + if (!GetFileAttributesExA(canon, GetFileExInfoStandard, &fd)) { json_err(404, "path not found"); return; } | |
| 1026 | + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { json_err(400, "not a regular file"); return; } | |
| 1027 | + { | |
| 1028 | + ULARGE_INTEGER sz; | |
| 1029 | + sz.LowPart = fd.nFileSizeLow; sz.HighPart = fd.nFileSizeHigh; | |
| 1030 | + size = (long long)sz.QuadPart; | |
| 1031 | + } | |
| 1032 | + } | |
| 1033 | +#else | |
| 1034 | + { | |
| 1035 | + struct stat st; | |
| 1036 | + if (!resolve_allowed(raw_path, canon, sizeof canon, &err)) { | |
| 1037 | + json_err(err, err == 403 ? "path not allowed" : (err == 404 ? "path not found" : "bad path")); | |
| 1038 | + return; | |
| 1039 | + } | |
| 1040 | + if (stat(canon, &st) != 0) { json_err(404, "path not found"); return; } | |
| 1041 | + if (S_ISDIR(st.st_mode)) { json_err(400, "not a regular file"); return; } | |
| 1042 | + size = (long long)st.st_size; | |
| 1043 | + } | |
| 1044 | +#endif | |
| 1045 | + | |
| 1046 | + if (size > RAW_CAP) { json_err(413, "file larger than 64 MiB"); return; } | |
| 1047 | + | |
| 1048 | + base = strrchr(canon, SEP); | |
| 1049 | + str_copy(name, sizeof name, (base && base[1]) ? base + 1 : canon); | |
| 1050 | + type = guess_type(name); | |
| 1051 | + header_name(name, hn, sizeof hn); | |
| 1052 | + | |
| 1053 | + if (get_query_val(qs, "download", dl, sizeof dl)) | |
| 1054 | + want_dl = (strcmp(dl, "1") == 0 || strcmp(dl, "true") == 0); | |
| 1055 | + | |
| 1056 | + f = fopen(canon, "rb"); | |
| 1057 | + if (!f) { json_err(403, "cannot open file"); return; } | |
| 1058 | + | |
| 1059 | + printf("Content-Type: %s\r\n", type); | |
| 1060 | + fputs("Cache-Control: no-store\r\n", stdout); | |
| 1061 | + fputs("X-Content-Type-Options: nosniff\r\n", stdout); | |
| 1062 | + fputs("Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; " | |
| 1063 | + "img-src data:\r\n", stdout); | |
| 1064 | + fputs("X-Frame-Options: SAMEORIGIN\r\n", stdout); | |
| 1065 | + printf("Content-Disposition: %s; filename=\"%s\"\r\n", | |
| 1066 | + (want_dl || !is_image_type(type)) ? "attachment" : "inline", hn); | |
| 1067 | + /* Deliberately no Content-Length - the server owns framing. */ | |
| 1068 | + fputs("\r\n", stdout); | |
| 1069 | + | |
| 1070 | + for (;;) { | |
| 1071 | + size_t n = fread(chunk, 1, sizeof chunk, f); | |
| 1072 | + if (n > 0) fwrite(chunk, 1, n, stdout); | |
| 1073 | + if (n < sizeof chunk) break; | |
| 1074 | + } | |
| 1075 | + fclose(f); | |
| 1076 | + fflush(stdout); | |
| 1077 | +} | |
| 1078 | + | |
| 1079 | +/* ------------------------------------------------------------------ */ | |
| 1080 | +/* HTML mode */ | |
| 1081 | +/* ------------------------------------------------------------------ */ | |
| 1082 | + | |
| 1083 | +/* Expand the two control-byte placeholders from src/ui.html into the bot | |
| 1084 | + * theme macros, so the page and the bot palette can never drift. */ | |
| 1085 | +static void emit_ui(int embed) | |
| 1086 | +{ | |
| 1087 | + const char *p = UI_HTML; | |
| 1088 | + | |
| 1089 | + while (*p) { | |
| 1090 | + if (*p == '\001') { | |
| 1091 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS | |
| 1092 | + ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);--ac:var(--blue)}" | |
| 1093 | + "</style>", stdout); | |
| 1094 | + p++; | |
| 1095 | + } else if (*p == '\002') { | |
| 1096 | + fputs(SX_BOT_THEME_HANDOFF, stdout); | |
| 1097 | + p++; | |
| 1098 | + } else { | |
| 1099 | + putchar(*p++); | |
| 1100 | + } | |
| 1101 | + } | |
| 1102 | + (void)embed; | |
| 1103 | +} | |
| 1104 | + | |
| 1105 | +static void mode_html(int embed) | |
| 1106 | +{ | |
| 1107 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | |
| 1108 | + "Cache-Control: no-store\r\n" | |
| 1109 | + "X-Content-Type-Options: nosniff\r\n" | |
| 1110 | + "X-Frame-Options: SAMEORIGIN\r\n" | |
| 1111 | + "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " | |
| 1112 | + "style-src 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; " | |
| 1113 | + "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); | |
| 1114 | + emit_ui(embed); | |
| 1115 | +} | |
| 1116 | + | |
| 1117 | +/* ------------------------------------------------------------------ */ | |
| 1118 | +/* Entry */ | |
| 1119 | +/* ------------------------------------------------------------------ */ | |
| 1120 | + | |
| 1121 | +static const char *method(void) | |
| 1122 | +{ | |
| 1123 | + const char *m = getenv("REQUEST_METHOD"); | |
| 1124 | + return (m && *m) ? m : "GET"; | |
| 1125 | +} | |
| 1126 | + | |
| 1127 | +int main(int argc, char **argv) | |
| 1128 | +{ | |
| 1129 | + const char *qs; | |
| 1130 | + char action[64]; | |
| 1131 | + char path[PATH_SZ]; | |
| 1132 | + | |
| 1133 | + /* 1. Discovery metadata (unauthenticated so /plugins can probe it) */ | |
| 1134 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { | |
| 1135 | + printf("{\"name\":\"%s\",\"desc\":\"%s\"}\n", PLUGIN_NAME, PLUGIN_DESC); | |
| 1136 | + return 0; | |
| 1137 | + } | |
| 1138 | + if (argc > 1 && strcmp(argv[1], "--version") == 0) { | |
| 1139 | + printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); | |
| 1140 | + return 0; | |
| 1141 | + } | |
| 1142 | + | |
| 1143 | + require_node_auth(); | |
| 1144 | + init_roots(); | |
| 1145 | + | |
| 1146 | + qs = getenv("QUERY_STRING"); | |
| 1147 | + if (!qs) qs = ""; | |
| 1148 | + | |
| 1149 | + action[0] = '\0'; | |
| 1150 | + get_query_val(qs, "action", action, sizeof action); | |
| 1151 | + | |
| 1152 | + /* 2. Anything that names an action or asks for JSON is API. */ | |
| 1153 | + if (action[0] || strstr(qs, "format=json")) { | |
| 1154 | + char fmt[32]; | |
| 1155 | + if (!action[0]) { | |
| 1156 | + if (get_query_val(qs, "format", fmt, sizeof fmt) && strcmp(fmt, "json") == 0) | |
| 1157 | + str_copy(action, sizeof action, "roots"); | |
| 1158 | + } | |
| 1159 | + | |
| 1160 | + path[0] = '\0'; | |
| 1161 | + get_query_val(qs, "path", path, sizeof path); | |
| 1162 | + | |
| 1163 | + if (strcmp(action, "roots") == 0) { | |
| 1164 | + do_roots(); | |
| 1165 | + } else if (strcmp(action, "ls") == 0) { | |
| 1166 | + do_ls(path, qs); | |
| 1167 | + } else if (strcmp(action, "read") == 0) { | |
| 1168 | + do_read(path); | |
| 1169 | + } else if (strcmp(action, "raw") == 0) { | |
| 1170 | + do_raw(path, qs); | |
| 1171 | + } else { | |
| 1172 | + json_err(400, "unknown action"); | |
| 1173 | + } | |
| 1174 | + return 0; | |
| 1175 | + } | |
| 1176 | + | |
| 1177 | + /* 3. Everything else is the page. */ | |
| 1178 | + { | |
| 1179 | + int embed = strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL; | |
| 1180 | + mode_html(embed); | |
| 1181 | + } | |
| 1182 | + (void)method; | |
| 1183 | + return 0; | |
| 1184 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..41c06e7 | ||
| --- /dev/null | ||
| +++ b/src/ui.html | ||
| @@ -0,0 +1,614 @@ | ||
| 1 | +<!DOCTYPE html> | |
| 2 | +<html lang="en"><head><meta charset="utf-8"> | |
| 3 | +<meta name="viewport" content="width=device-width,initial-scale=1"> | |
| 4 | +<title>files</title> | |
| 5 | +<!--TOKENS--> | |
| 6 | +<style> | |
| 7 | +*{box-sizing:border-box} | |
| 8 | +html,body{margin:0;height:100%} | |
| 9 | +body{background:var(--bg);color:var(--text);font-family:var(--font); | |
| 10 | + font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased;overflow:hidden} | |
| 11 | +#app{display:grid;grid-template-columns:252px minmax(0,1fr);height:100%;min-height:0} | |
| 12 | +.pane{min-width:0;min-height:0;display:flex;flex-direction:column} | |
| 13 | +#side{background:var(--bg-2);border-right:1px solid var(--line)} | |
| 14 | +.side-hd{display:flex;align-items:center;gap:8px;padding:12px 12px 8px} | |
| 15 | +.brand{font-size:12px;font-weight:700;letter-spacing:.09em;text-transform:uppercase; | |
| 16 | + color:var(--text-2);flex:1} | |
| 17 | +.side-ft{display:flex;align-items:center;gap:8px;padding:8px 12px; | |
| 18 | + border-top:1px solid var(--line);font-size:11px;color:var(--text-2)} | |
| 19 | +.side-ft .grow{flex:1} | |
| 20 | +.side-lbl{font-size:10.5px;font-weight:700;letter-spacing:.1em;text-transform:uppercase; | |
| 21 | + color:var(--text-2);padding:4px 14px 6px} | |
| 22 | +.icon{display:inline-flex;align-items:center;justify-content:center;gap:6px; | |
| 23 | + background:var(--surface-2);border:1px solid var(--line);color:var(--text); | |
| 24 | + border-radius:9px;width:30px;height:30px;padding:0;cursor:pointer;font-family:inherit; | |
| 25 | + font-size:12px;font-weight:600;flex:0 0 auto} | |
| 26 | +.icon:hover{background:var(--surface-hover);border-color:var(--line-2)} | |
| 27 | +.icon:active{transform:scale(.96)} | |
| 28 | +.icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor; | |
| 29 | + stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round} | |
| 30 | +.icon.on{background:var(--surface-2);border-color:var(--line-2);color:var(--blue)} | |
| 31 | +.rootlist{flex:0 0 auto;padding:0 8px 10px;border-bottom:1px solid var(--line)} | |
| 32 | +.root{display:flex;align-items:center;gap:9px;width:100%;text-align:left; | |
| 33 | + background:transparent;border:0;border-radius:9px;padding:8px 10px;color:var(--text); | |
| 34 | + cursor:pointer;font-family:inherit;font-size:13px;margin-bottom:2px} | |
| 35 | +.root:hover{background:var(--surface-hover)} | |
| 36 | +.root.sel{background:var(--surface-2);box-shadow:inset 2px 0 0 var(--blue)} | |
| 37 | +.root svg{width:14px;height:14px;flex:0 0 auto;fill:none;stroke:currentColor;stroke-width:1.7; | |
| 38 | + stroke-linecap:round;stroke-linejoin:round;color:var(--text-2)} | |
| 39 | +.root .rl{min-width:0;flex:1} | |
| 40 | +.root .rl .n{display:block;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | |
| 41 | +.root .rl .p{display:block;font-size:10.5px;color:var(--text-2);overflow:hidden; | |
| 42 | + text-overflow:ellipsis;white-space:nowrap;font-family:var(--mono)} | |
| 43 | +#main{background:var(--bg);min-width:0} | |
| 44 | +.toolbar{display:flex;align-items:center;gap:7px;padding:10px 14px; | |
| 45 | + border-bottom:1px solid var(--line);flex:0 0 auto;min-width:0} | |
| 46 | +.crumbs{flex:1 1 auto;min-width:0;display:flex;align-items:center;gap:2px; | |
| 47 | + overflow-x:auto;scrollbar-width:none;white-space:nowrap} | |
| 48 | +.crumbs::-webkit-scrollbar{display:none} | |
| 49 | +.crumb{background:transparent;border:0;color:var(--text-2);font-family:var(--mono); | |
| 50 | + font-size:12px;padding:3px 5px;border-radius:6px;cursor:pointer;flex:0 0 auto} | |
| 51 | +.crumb:hover{background:var(--surface-hover);color:var(--text)} | |
| 52 | +.crumb.last{color:var(--text);font-weight:600} | |
| 53 | +.crumb .sep{color:var(--text-2);opacity:.6;padding:0 1px} | |
| 54 | +.body{flex:1 1 auto;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.15fr); | |
| 55 | + min-height:0} | |
| 56 | +.body.noprev{grid-template-columns:minmax(0,1fr)} | |
| 57 | +.listwrap{min-width:0;min-height:0;display:flex;flex-direction:column; | |
| 58 | + border-right:1px solid var(--line)} | |
| 59 | +.entries{flex:1 1 auto;overflow-y:auto;padding:6px 8px 20px} | |
| 60 | +.row{display:flex;align-items:center;gap:9px;width:100%;text-align:left; | |
| 61 | + background:transparent;border:0;border-radius:9px;padding:7px 9px;color:var(--text); | |
| 62 | + cursor:pointer;font-family:inherit;font-size:13px} | |
| 63 | +.row:hover{background:var(--surface-hover)} | |
| 64 | +.row.sel{background:var(--surface-2);box-shadow:inset 2px 0 0 var(--blue)} | |
| 65 | +.row .ico{width:16px;height:16px;flex:0 0 auto;color:var(--text-2);display:flex} | |
| 66 | +.row .ico svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:1.7; | |
| 67 | + stroke-linecap:round;stroke-linejoin:round} | |
| 68 | +.row.dir .ico{color:var(--blue)} | |
| 69 | +.row .nm{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | |
| 70 | +.row .mt{flex:0 0 auto;font-family:var(--mono);font-size:11px;color:var(--text-2)} | |
| 71 | +.empty{padding:22px 14px;color:var(--text-2);font-size:12.5px;text-align:center} | |
| 72 | +.hidden{display:none!important} | |
| 73 | +.preview{min-width:0;min-height:0;display:flex;flex-direction:column} | |
| 74 | +.prev-hd{display:flex;align-items:center;gap:8px;padding:9px 14px; | |
| 75 | + border-bottom:1px solid var(--line);flex:0 0 auto;min-width:0} | |
| 76 | +.prev-hd .nm{flex:1 1 auto;min-width:0;font-weight:600;font-size:13px; | |
| 77 | + overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | |
| 78 | +.prev-hd .mt{font-family:var(--mono);font-size:11px;color:var(--text-2);white-space:nowrap} | |
| 79 | +.prev-body{flex:1 1 auto;overflow:auto;min-height:0} | |
| 80 | +.codetxt{margin:0;padding:0;font-family:var(--mono);font-size:12.5px;line-height:1.6; | |
| 81 | + display:grid;grid-template-columns:auto minmax(0,1fr);min-width:0} | |
| 82 | +.codetxt .ln{color:var(--text-2);text-align:right;padding:0 10px 0 14px; | |
| 83 | + user-select:none;background:var(--bg-2);border-right:1px solid var(--line)} | |
| 84 | +.codetxt .tx{padding:0 14px;white-space:pre-wrap;word-break:break-word; | |
| 85 | + font-family:var(--mono);font-size:12.5px} | |
| 86 | +.md{padding:16px 20px 40px;max-width:860px} | |
| 87 | +.md h1,.md h2,.md h3,.md h4{line-height:1.25;margin:18px 0 8px;font-weight:650} | |
| 88 | +.md h1{font-size:21px}.md h2{font-size:18px}.md h3{font-size:15.5px}.md h4{font-size:14px} | |
| 89 | +.md p{margin:0 0 11px} | |
| 90 | +.md ul,.md ol{margin:0 0 11px;padding-left:22px} | |
| 91 | +.md li{margin:3px 0} | |
| 92 | +.md code{font-family:var(--mono);font-size:12px;background:var(--code-bg); | |
| 93 | + padding:1px 5px;border-radius:5px} | |
| 94 | +.md pre{background:var(--code-bg);border:1px solid var(--line);border-radius:10px; | |
| 95 | + padding:11px 13px;overflow-x:auto;margin:0 0 12px} | |
| 96 | +.md pre code{background:transparent;padding:0;font-size:12px;line-height:1.55} | |
| 97 | +.md hr{border:0;border-top:1px solid var(--line);margin:16px 0} | |
| 98 | +.md a{color:var(--blue);text-decoration:none;font-weight:600} | |
| 99 | +.md a:hover{text-decoration:underline} | |
| 100 | +.md blockquote{margin:0 0 12px;padding:2px 0 2px 13px;border-left:3px solid var(--line-2); | |
| 101 | + color:var(--text-2)} | |
| 102 | +.imgwrap{padding:16px;display:flex;align-items:flex-start;justify-content:center} | |
| 103 | +.imgwrap img{max-width:100%;height:auto;border-radius:10px;border:1px solid var(--line); | |
| 104 | + background:var(--bg-2)} | |
| 105 | +.note{padding:16px 18px;color:var(--text-2);font-size:12.5px} | |
| 106 | +.welcome{flex:1 1 auto;display:flex;flex-direction:column;align-items:center; | |
| 107 | + justify-content:center;gap:10px;color:var(--text-2);font-size:13px;padding:24px; | |
| 108 | + text-align:center;min-height:0} | |
| 109 | +.welcome svg{width:34px;height:34px;fill:none;stroke:currentColor;stroke-width:1.4; | |
| 110 | + stroke-linecap:round;stroke-linejoin:round;opacity:.55} | |
| 111 | +.toast{position:fixed;left:50%;bottom:18px;transform:translateX(-50%); | |
| 112 | + background:var(--modal-bg);border:1px solid var(--line-2);color:var(--text); | |
| 113 | + padding:8px 14px;border-radius:999px;font-size:12.5px;box-shadow:var(--shadow-lg); | |
| 114 | + opacity:0;pointer-events:none;transition:opacity .16s var(--ease);z-index:9; | |
| 115 | + max-width:calc(100% - 24px);overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | |
| 116 | +.toast.show{opacity:1} | |
| 117 | +@media (max-width:1100px){ | |
| 118 | + #app{grid-template-columns:216px minmax(0,1fr)} | |
| 119 | + .body{grid-template-columns:minmax(0,1fr) minmax(0,1fr)} | |
| 120 | +} | |
| 121 | +@media (max-width:820px){ | |
| 122 | + body{overflow:hidden} | |
| 123 | + #app{grid-template-columns:minmax(0,1fr)} | |
| 124 | + #side,#main{grid-column:1;grid-row:1} | |
| 125 | + #app[data-view="browse"] #side{display:none} | |
| 126 | + #app[data-view="roots"] #main{display:none} | |
| 127 | + .body{grid-template-columns:minmax(0,1fr)} | |
| 128 | + #app[data-view="browse"] .body{grid-template-columns:minmax(0,1fr)} | |
| 129 | + #app[data-view="browse"] .preview{display:none} | |
| 130 | + #app[data-view="preview"] .listwrap{display:none} | |
| 131 | + #app[data-view="preview"] .body{grid-template-columns:minmax(0,1fr)} | |
| 132 | + .back{display:inline-flex!important} | |
| 133 | + .toolbar{padding:8px 10px;gap:6px} | |
| 134 | + .md{padding:12px 14px 32px} | |
| 135 | + .codetxt .tx{padding:0 10px} | |
| 136 | +} | |
| 137 | +@media (min-width:821px){.back{display:none!important}} | |
| 138 | +</style> | |
| 139 | +</head><body> | |
| 140 | +<div id="app" data-view="roots"> | |
| 141 | + <aside id="side" class="pane"> | |
| 142 | + <div class="side-hd"> | |
| 143 | + <span class="brand">files</span> | |
| 144 | + <button id="btnUp" class="icon" title="Up one level" aria-label="Up one level"> | |
| 145 | + <svg viewBox="0 0 24 24"><path d="M12 19V5M5 12l7-7 7 7"/></svg></button> | |
| 146 | + <button id="btnRefresh" class="icon" title="Refresh" aria-label="Refresh"> | |
| 147 | + <svg viewBox="0 0 24 24"><path d="M20 11a8 8 0 1 0-2.3 5.7"/><path d="M20 4v7h-7"/></svg></button> | |
| 148 | + </div> | |
| 149 | + <div class="side-lbl">Roots</div> | |
| 150 | + <div id="roots" class="rootlist"></div> | |
| 151 | + <div class="side-ft"> | |
| 152 | + <span id="count">0 items</span><span class="grow"></span> | |
| 153 | + <button id="btnHidden" class="icon" title="Show hidden files" aria-label="Show hidden files"> | |
| 154 | + <svg viewBox="0 0 24 24"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"/><circle cx="12" cy="12" r="3"/></svg></button> | |
| 155 | + <button id="btnTheme" class="icon embed-hide" title="Toggle appearance" aria-label="Toggle appearance"> | |
| 156 | + <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="4.5"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4"/></svg></button> | |
| 157 | + </div> | |
| 158 | + </aside> | |
| 159 | + <main id="main" class="pane"> | |
| 160 | + <div class="toolbar"> | |
| 161 | + <button id="btnBack" class="icon back" title="Back to list" aria-label="Back to list"> | |
| 162 | + <svg viewBox="0 0 24 24"><path d="M15 5l-7 7 7 7"/></svg></button> | |
| 163 | + <div id="crumbs" class="crumbs"></div> | |
| 164 | + <button id="btnDownload" class="icon" title="Download file" aria-label="Download file"> | |
| 165 | + <svg viewBox="0 0 24 24"><path d="M12 3v12M7 11l5 5 5-5M4 21h16"/></svg></button> | |
| 166 | + </div> | |
| 167 | + <div id="body" class="body"> | |
| 168 | + <div class="listwrap"> | |
| 169 | + <div id="entries" class="entries"></div> | |
| 170 | + <div id="empty" class="empty hidden">This directory is empty.</div> | |
| 171 | + </div> | |
| 172 | + <div id="preview" class="preview"> | |
| 173 | + <div id="prevHd" class="prev-hd hidden"> | |
| 174 | + <span id="prevName" class="nm"></span> | |
| 175 | + <span id="prevMeta" class="mt"></span> | |
| 176 | + </div> | |
| 177 | + <div id="prevBody" class="prev-body"> | |
| 178 | + <div id="welcome" class="welcome"> | |
| 179 | + <svg viewBox="0 0 24 24"><path d="M3 7h6l2 2h10v11H3z"/></svg> | |
| 180 | + <div>Pick a root, then open a file to preview it.</div> | |
| 181 | + <div style="font-size:11.5px">Arrows move · Enter opens · Backspace goes up</div> | |
| 182 | + </div> | |
| 183 | + </div> | |
| 184 | + </div> | |
| 185 | + </div> | |
| 186 | + </main> | |
| 187 | +</div> | |
| 188 | +<div id="toast" class="toast"></div> | |
| 189 | +<script> | |
| 190 | +(function(){ | |
| 191 | +"use strict"; | |
| 192 | +var app=document.getElementById('app'); | |
| 193 | +var rootsEl=document.getElementById('roots'); | |
| 194 | +var entriesEl=document.getElementById('entries'); | |
| 195 | +var emptyEl=document.getElementById('empty'); | |
| 196 | +var countEl=document.getElementById('count'); | |
| 197 | +var crumbsEl=document.getElementById('crumbs'); | |
| 198 | +var bodyEl=document.getElementById('body'); | |
| 199 | +var prevEl=document.getElementById('preview'); | |
| 200 | +var prevHd=document.getElementById('prevHd'); | |
| 201 | +var prevName=document.getElementById('prevName'); | |
| 202 | +var prevMeta=document.getElementById('prevMeta'); | |
| 203 | +var prevBody=document.getElementById('prevBody'); | |
| 204 | +var toastEl=document.getElementById('toast'); | |
| 205 | +var btnHidden=document.getElementById('btnHidden'); | |
| 206 | +var btnDownload=document.getElementById('btnDownload'); | |
| 207 | + | |
| 208 | +var q=new URLSearchParams(location.search); | |
| 209 | +var node=q.get('node')||''; | |
| 210 | +var sid=q.get('id')||''; | |
| 211 | +var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))|| | |
| 212 | + localStorage.getItem('bot_active_pwd')||''; | |
| 213 | +var HUB=q.get('plugin')||''; | |
| 214 | + | |
| 215 | +var roots=[], entries=[], curPath='', curParent=null, curRoot=null; | |
| 216 | +var selIndex=-1, showHidden=false, curFile=null; | |
| 217 | + | |
| 218 | +/* Two call routes, and getting this wrong is the most common plugin bug: | |
| 219 | + * page served through the hub (bot.scorpiox.net/plugins?plugin=plugin_files&node=..) | |
| 220 | + * -> call the hub proxy back: /plugins?plugin=plugin_files&action=.. | |
| 221 | + * opened directly on the node | |
| 222 | + * -> the plugin itself is the route: /plugin_files?action=.. | |
| 223 | + * Calling /plugins?plugin= on the node returns the discovery list, not us. */ | |
| 224 | +function url(action,extra){ | |
| 225 | + var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_files')+ | |
| 226 | + '?action='+encodeURIComponent(action)+ | |
| 227 | + (extra?('&'+extra):'')+ | |
| 228 | + (node?'&node='+encodeURIComponent(node):'')+ | |
| 229 | + (sid?'&id='+encodeURIComponent(sid):'')+ | |
| 230 | + (pwd?'&pwd='+encodeURIComponent(pwd):''); | |
| 231 | + return u; | |
| 232 | +} | |
| 233 | +function hdr(extra){ | |
| 234 | + var h=extra||{}; | |
| 235 | + if(pwd)h['X-Bot-Password']=pwd; | |
| 236 | + return h; | |
| 237 | +} | |
| 238 | +function api(action,extra){ | |
| 239 | + return fetch(url(action,extra),{headers:hdr({})}).then(function(r){ | |
| 240 | + if(!r.ok)throw new Error('HTTP '+r.status); | |
| 241 | + return r.json(); | |
| 242 | + }); | |
| 243 | +} | |
| 244 | + | |
| 245 | +function toast(msg){ | |
| 246 | + toastEl.textContent=msg; | |
| 247 | + toastEl.classList.add('show'); | |
| 248 | + clearTimeout(toast._t); | |
| 249 | + toast._t=setTimeout(function(){toastEl.classList.remove('show');},2000); | |
| 250 | +} | |
| 251 | +function setView(v){app.setAttribute('data-view',v);} | |
| 252 | + | |
| 253 | +function fmtSize(n){ | |
| 254 | + if(n===null||n===undefined)return ''; | |
| 255 | + if(n<1024)return n+' B'; | |
| 256 | + if(n<1048576)return (n/1024).toFixed(1)+' KB'; | |
| 257 | + if(n<1073741824)return (n/1048576).toFixed(1)+' MB'; | |
| 258 | + return (n/1073741824).toFixed(1)+' GB'; | |
| 259 | +} | |
| 260 | +function fmtTime(iso){ | |
| 261 | + if(!iso)return ''; | |
| 262 | + try{ | |
| 263 | + var d=new Date(iso),now=new Date(),diff=(now-d)/1000; | |
| 264 | + if(diff<60)return 'just now'; | |
| 265 | + if(diff<3600)return Math.floor(diff/60)+'m ago'; | |
| 266 | + if(diff<86400)return Math.floor(diff/3600)+'h ago'; | |
| 267 | + if(diff<604800)return Math.floor(diff/86400)+'d ago'; | |
| 268 | + return d.toLocaleDateString(); | |
| 269 | + }catch(e){return ''} | |
| 270 | +} | |
| 271 | + | |
| 272 | +var SVG={ | |
| 273 | + dir:'<svg viewBox="0 0 24 24"><path d="M3 7h6l2 2h10v11H3z"/></svg>', | |
| 274 | + file:'<svg viewBox="0 0 24 24"><path d="M6 3h9l5 5v13H6z"/><path d="M14 3v5h5"/></svg>', | |
| 275 | + link:'<svg viewBox="0 0 24 24"><path d="M10 13a4 4 0 0 0 6 .5l2.5-2.5a4 4 0 0 0-6-6L11 6.5"/><path d="M14 11a4 4 0 0 0-6-.5L5.5 13a4 4 0 0 0 6 6L13 17.5"/></svg>', | |
| 276 | + img:'<svg viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="8.5" cy="10" r="1.6"/><path d="M21 16l-5-5-6 6"/></svg>', | |
| 277 | + root:'<svg viewBox="0 0 24 24"><path d="M3 7h6l2 2h10v11H3z"/></svg>' | |
| 278 | +}; | |
| 279 | + | |
| 280 | +function renderRoots(){ | |
| 281 | + while(rootsEl.firstChild)rootsEl.removeChild(rootsEl.firstChild); | |
| 282 | + roots.forEach(function(r,i){ | |
| 283 | + var b=document.createElement('button'); | |
| 284 | + b.className='root'+(curRoot===r.path?' sel':''); | |
| 285 | + var ic=document.createElement('span');ic.innerHTML=SVG.root; | |
| 286 | + var wrap=document.createElement('span');wrap.className='rl'; | |
| 287 | + var n=document.createElement('span');n.className='n';n.textContent=r.name; | |
| 288 | + var p=document.createElement('span');p.className='p';p.textContent=r.path; | |
| 289 | + wrap.appendChild(n);wrap.appendChild(p); | |
| 290 | + b.appendChild(ic);b.appendChild(wrap); | |
| 291 | + b.onclick=function(){openDir(r.path);setView('browse');}; | |
| 292 | + rootsEl.appendChild(b); | |
| 293 | + }); | |
| 294 | +} | |
| 295 | + | |
| 296 | +function renderCrumbs(){ | |
| 297 | + while(crumbsEl.firstChild)crumbsEl.removeChild(crumbsEl.firstChild); | |
| 298 | + if(!curPath){ | |
| 299 | + var hint=document.createElement('span');hint.className='crumb last'; | |
| 300 | + hint.textContent='Select a root';crumbsEl.appendChild(hint);return; | |
| 301 | + } | |
| 302 | + var base=curRoot||''; | |
| 303 | + var rel=curPath; | |
| 304 | + if(base&&curPath.indexOf(base)===0)rel=curPath.slice(base.length); | |
| 305 | + var parts=rel.split(/[\/\\]+/).filter(function(s){return s.length;}); | |
| 306 | + var b0=document.createElement('button'); | |
| 307 | + b0.className='crumb'+(parts.length?'':' last'); | |
| 308 | + b0.textContent=base.split(/[\/\\]+/).filter(Boolean).pop()||base||'/'; | |
| 309 | + b0.title=base; | |
| 310 | + b0.onclick=function(){openDir(base);}; | |
| 311 | + crumbsEl.appendChild(b0); | |
| 312 | + var acc=base; | |
| 313 | + parts.forEach(function(p,i){ | |
| 314 | + var sp=document.createElement('span');sp.className='sep';sp.textContent='/'; | |
| 315 | + crumbsEl.appendChild(sp); | |
| 316 | + acc+=(acc&&acc[acc.length-1]!=='/'&&acc[acc.length-1]!=='\\'?'/':'')+p; | |
| 317 | + var b=document.createElement('button'); | |
| 318 | + b.className='crumb'+(i===parts.length-1?' last':''); | |
| 319 | + b.textContent=p;b.title=acc; | |
| 320 | + var target=acc; | |
| 321 | + b.onclick=function(){openDir(target);}; | |
| 322 | + crumbsEl.appendChild(b); | |
| 323 | + }); | |
| 324 | +} | |
| 325 | + | |
| 326 | +function isImage(name){ | |
| 327 | + return /\.(png|jpe?g|gif|webp|bmp|ico|svg)$/i.test(name||''); | |
| 328 | +} | |
| 329 | +function isMarkdown(name){ | |
| 330 | + return /\.(md|markdown)$/i.test(name||''); | |
| 331 | +} | |
| 332 | +function isTextish(name){ | |
| 333 | + return /\.(txt|md|markdown|json|js|ts|css|html?|c|h|cpp|hpp|py|sh|yml|yaml|toml|ini|conf|log|csv|xml|sql|go|rs|java|rb|php|gitignore|env)$/i.test(name||''); | |
| 334 | +} | |
| 335 | + | |
| 336 | +function renderEntries(){ | |
| 337 | + while(entriesEl.firstChild)entriesEl.removeChild(entriesEl.firstChild); | |
| 338 | + if(selIndex>=entries.length)selIndex=entries.length?entries.length-1:-1; | |
| 339 | + entries.forEach(function(e,i){ | |
| 340 | + var b=document.createElement('button'); | |
| 341 | + b.className='row'+(e.type==='dir'?' dir':'')+(i===selIndex?' sel':''); | |
| 342 | + var ic=document.createElement('span');ic.className='ico'; | |
| 343 | + ic.innerHTML = e.type==='dir'?SVG.dir : (isImage(e.name)?SVG.img : (e.type==='link'?SVG.link:SVG.file)); | |
| 344 | + var nm=document.createElement('span');nm.className='nm';nm.textContent=e.name; | |
| 345 | + var mt=document.createElement('span');mt.className='mt'; | |
| 346 | + mt.textContent=(e.type==='dir'?'':fmtSize(e.size)); | |
| 347 | + b.appendChild(ic);b.appendChild(nm);b.appendChild(mt); | |
| 348 | + b.onclick=function(){selIndex=i;renderEntries();activate(e);}; | |
| 349 | + entriesEl.appendChild(b); | |
| 350 | + }); | |
| 351 | + emptyEl.classList.toggle('hidden',entries.length>0); | |
| 352 | + countEl.textContent=entries.length+(entries.length===1?' item':' items'); | |
| 353 | + var sel=entriesEl.querySelector('.row.sel'); | |
| 354 | + if(sel&&sel.scrollIntoView)sel.scrollIntoView({block:'nearest'}); | |
| 355 | +} | |
| 356 | + | |
| 357 | +function openDir(path){ | |
| 358 | + return api('ls','path='+encodeURIComponent(path)+(showHidden?'&hidden=1':'')) | |
| 359 | + .then(function(d){ | |
| 360 | + if(!d||!d.ok)throw new Error((d&&d.error)||'failed'); | |
| 361 | + curPath=d.path;curParent=d.parent;curRoot=d.root; | |
| 362 | + entries=d.entries||[];selIndex=entries.length?0:-1; | |
| 363 | + renderCrumbs();renderEntries(); | |
| 364 | + if(!entries.length){clearPreview();} | |
| 365 | + else if(window.matchMedia('(max-width:820px)').matches){setView('browse');} | |
| 366 | + return d; | |
| 367 | + }).catch(function(e){toast('Cannot open folder: '+e.message);}); | |
| 368 | +} | |
| 369 | + | |
| 370 | +function clearPreview(){ | |
| 371 | + prevHd.classList.add('hidden'); | |
| 372 | + while(prevBody.firstChild)prevBody.removeChild(prevBody.firstChild); | |
| 373 | + var w=document.createElement('div');w.className='welcome'; | |
| 374 | + w.innerHTML='<svg viewBox="0 0 24 24"><path d="M3 7h6l2 2h10v11H3z"/></svg>'+ | |
| 375 | + '<div>Pick a root, then open a file to preview it.</div>'+ | |
| 376 | + '<div style="font-size:11.5px">Arrows move · Enter opens · Backspace goes up</div>'; | |
| 377 | + prevBody.appendChild(w); | |
| 378 | + curFile=null; | |
| 379 | + btnDownload.classList.add('hidden'); | |
| 380 | +} | |
| 381 | + | |
| 382 | +function activate(e){ | |
| 383 | + if(e.type==='dir'){openDir(joinPath(curPath,e.name));setView('browse');return;} | |
| 384 | + previewFile(joinPath(curPath,e.name),e); | |
| 385 | +} | |
| 386 | +function joinPath(dir,name){ | |
| 387 | + if(!dir)return name; | |
| 388 | + var last=dir[dir.length-1]; | |
| 389 | + return dir+(last==='/'||last==='\\'?'':'/')+name; | |
| 390 | +} | |
| 391 | + | |
| 392 | +function setHd(name,meta){ | |
| 393 | + prevHd.classList.remove('hidden'); | |
| 394 | + prevName.textContent=name; | |
| 395 | + prevMeta.textContent=meta||''; | |
| 396 | + btnDownload.classList.remove('hidden'); | |
| 397 | +} | |
| 398 | + | |
| 399 | +function previewFile(path,ent){ | |
| 400 | + curFile=path; | |
| 401 | + setView('preview'); | |
| 402 | + prevHd.classList.remove('hidden'); | |
| 403 | + prevName.textContent=ent&&ent.name?ent.name:path.split(/[\/\\]/).pop(); | |
| 404 | + prevMeta.textContent=ent?fmtSize(ent.size):''; | |
| 405 | + btnDownload.classList.remove('hidden'); | |
| 406 | + while(prevBody.firstChild)prevBody.removeChild(prevBody.firstChild); | |
| 407 | + prevBody.scrollTop=0; | |
| 408 | + | |
| 409 | + var name=prevName.textContent; | |
| 410 | + if(isImage(name)){ | |
| 411 | + var wrap=document.createElement('div');wrap.className='imgwrap'; | |
| 412 | + var img=document.createElement('img'); | |
| 413 | + img.alt=name; | |
| 414 | + img.src=url('raw','path='+encodeURIComponent(path)); | |
| 415 | + img.onerror=function(){ | |
| 416 | + wrap.innerHTML=''; | |
| 417 | + var n=document.createElement('div');n.className='note'; | |
| 418 | + n.textContent='This image could not be displayed.'; | |
| 419 | + wrap.appendChild(n); | |
| 420 | + }; | |
| 421 | + wrap.appendChild(img);prevBody.appendChild(wrap); | |
| 422 | + return; | |
| 423 | + } | |
| 424 | + | |
| 425 | + api('read','path='+encodeURIComponent(path)).then(function(d){ | |
| 426 | + if(!d||!d.ok)throw new Error((d&&d.error)||'failed'); | |
| 427 | + prevMeta.textContent=fmtSize(d.size)+(d.truncated?' (first 1 MB)':''); | |
| 428 | + if(d.binary){ | |
| 429 | + var n=document.createElement('div');n.className='note'; | |
| 430 | + n.textContent='Binary file ('+fmtSize(d.size)+') - use Download to inspect it locally.'; | |
| 431 | + prevBody.appendChild(n);return; | |
| 432 | + } | |
| 433 | + if(!isTextish(name)&&!isMarkdown(name)){ | |
| 434 | + prevMeta.textContent=fmtSize(d.size)+(d.truncated?' (first 1 MB)':'')+' · plain text'; | |
| 435 | + } | |
| 436 | + if(isMarkdown(name))renderMarkdown(d.text||'',prevBody); | |
| 437 | + else renderCode(d.text||'',prevBody); | |
| 438 | + }).catch(function(e){ | |
| 439 | + while(prevBody.firstChild)prevBody.removeChild(prevBody.firstChild); | |
| 440 | + var n=document.createElement('div');n.className='note'; | |
| 441 | + n.textContent='Cannot preview this file: '+e.message; | |
| 442 | + prevBody.appendChild(n); | |
| 443 | + }); | |
| 444 | +} | |
| 445 | + | |
| 446 | +/* Line numbers + text. Every line is a text node, so file content can never | |
| 447 | + * become markup. */ | |
| 448 | +function renderCode(text,host){ | |
| 449 | + var lines=text.split('\n'); | |
| 450 | + if(lines.length&&lines[lines.length-1]==='')lines.pop(); | |
| 451 | + var pre=document.createElement('div');pre.className='codetxt'; | |
| 452 | + var ln=document.createElement('div');ln.className='ln'; | |
| 453 | + var tx=document.createElement('div');tx.className='tx'; | |
| 454 | + var nums=[],body=[]; | |
| 455 | + for(var i=0;i<lines.length;i++){nums.push(String(i+1));body.push(lines[i]);} | |
| 456 | + ln.textContent=nums.join('\n'); | |
| 457 | + tx.textContent=body.join('\n'); | |
| 458 | + pre.appendChild(ln);pre.appendChild(tx); | |
| 459 | + host.appendChild(pre); | |
| 460 | +} | |
| 461 | + | |
| 462 | +/* Tiny markdown renderer: headings, lists, fenced code, blockquote, hr, | |
| 463 | + * inline code/bold/italic/links. No CDN, no innerHTML with file content. */ | |
| 464 | +function renderMarkdown(text,host){ | |
| 465 | + var box=document.createElement('div');box.className='md'; | |
| 466 | + var lines=text.split('\n'); | |
| 467 | + var i=0,para=[],list=null; | |
| 468 | + | |
| 469 | + function flushPara(){ | |
| 470 | + if(!para.length)return; | |
| 471 | + var p=document.createElement('p'); | |
| 472 | + inline(para.join(' '),p); | |
| 473 | + box.appendChild(p);para=[]; | |
| 474 | + } | |
| 475 | + function flushList(){ | |
| 476 | + if(!list)return; | |
| 477 | + box.appendChild(list);list=null; | |
| 478 | + } | |
| 479 | + function inline(s,parent){ | |
| 480 | + var re=/(`[^`]*`)|(\*\*[^*]+\*\*)|(\*[^*]+\*)|(\[[^\]]+\]\([^)]+\))/g; | |
| 481 | + var last=0,m; | |
| 482 | + while((m=re.exec(s))!==null){ | |
| 483 | + if(m.index>last)parent.appendChild(document.createTextNode(s.slice(last,m.index))); | |
| 484 | + var tok=m[0]; | |
| 485 | + if(tok[0]==='`'){ | |
| 486 | + var c=document.createElement('code');c.textContent=tok.slice(1,-1);parent.appendChild(c); | |
| 487 | + }else if(tok.slice(0,2)==='**'){ | |
| 488 | + var b=document.createElement('strong');b.textContent=tok.slice(2,-2);parent.appendChild(b); | |
| 489 | + }else if(tok[0]==='*'){ | |
| 490 | + var em=document.createElement('em');em.textContent=tok.slice(1,-1);parent.appendChild(em); | |
| 491 | + }else{ | |
| 492 | + var mm=/^\[([^\]]+)\]\(([^)]+)\)$/.exec(tok); | |
| 493 | + if(mm&&/^(https?:\/\/|\/|#|mailto:)/i.test(mm[2])){ | |
| 494 | + var a=document.createElement('a'); | |
| 495 | + a.textContent=mm[1];a.href=mm[2]; | |
| 496 | + a.target='_blank';a.rel='noopener noreferrer'; | |
| 497 | + parent.appendChild(a); | |
| 498 | + }else if(mm){ | |
| 499 | + parent.appendChild(document.createTextNode(mm[1])); | |
| 500 | + } | |
| 501 | + } | |
| 502 | + last=m.index+tok.length; | |
| 503 | + } | |
| 504 | + if(last<s.length)parent.appendChild(document.createTextNode(s.slice(last))); | |
| 505 | + } | |
| 506 | + | |
| 507 | + while(i<lines.length){ | |
| 508 | + var line=lines[i]; | |
| 509 | + if(/^```/.test(line)){ | |
| 510 | + flushPara();flushList(); | |
| 511 | + var buf=[];i++; | |
| 512 | + while(i<lines.length&&!/^```/.test(lines[i])){buf.push(lines[i]);i++;} | |
| 513 | + i++; | |
| 514 | + var pre=document.createElement('pre'); | |
| 515 | + var code=document.createElement('code');code.textContent=buf.join('\n'); | |
| 516 | + pre.appendChild(code);box.appendChild(pre); | |
| 517 | + continue; | |
| 518 | + } | |
| 519 | + if(/^\s*$/.test(line)){flushPara();flushList();i++;continue;} | |
| 520 | + var h=/^(#{1,4})\s+(.*)$/.exec(line); | |
| 521 | + if(h){ | |
| 522 | + flushPara();flushList(); | |
| 523 | + var el=document.createElement('h'+h[1].length); | |
| 524 | + inline(h[2],el);box.appendChild(el);i++;continue; | |
| 525 | + } | |
| 526 | + if(/^\s*([-*+]|\d+\.)\s+/.test(line)){ | |
| 527 | + flushPara(); | |
| 528 | + var ordered=/^\s*\d+\.\s+/.test(line); | |
| 529 | + if(!list||list.tagName.toLowerCase()!==(ordered?'ol':'ul')){ | |
| 530 | + flushList();list=document.createElement(ordered?'ol':'ul'); | |
| 531 | + } | |
| 532 | + var li=document.createElement('li'); | |
| 533 | + inline(line.replace(/^\s*([-*+]|\d+\.)\s+/,''),li); | |
| 534 | + list.appendChild(li);i++;continue; | |
| 535 | + } | |
| 536 | + if(/^>\s?/.test(line)){ | |
| 537 | + flushPara();flushList(); | |
| 538 | + var bq=document.createElement('blockquote'); | |
| 539 | + inline(line.replace(/^>\s?/,''),bq); | |
| 540 | + box.appendChild(bq);i++;continue; | |
| 541 | + } | |
| 542 | + if(/^(-{3,}|\*{3,}|_{3,})$/.test(line.trim())){ | |
| 543 | + flushPara();flushList(); | |
| 544 | + box.appendChild(document.createElement('hr'));i++;continue; | |
| 545 | + } | |
| 546 | + para.push(line);i++; | |
| 547 | + } | |
| 548 | + flushPara();flushList(); | |
| 549 | + host.appendChild(box); | |
| 550 | +} | |
| 551 | + | |
| 552 | +/* --- wiring ------------------------------------------------------- */ | |
| 553 | + | |
| 554 | +document.getElementById('btnRefresh').onclick=function(){ | |
| 555 | + if(curPath)openDir(curPath);else loadRoots(); | |
| 556 | +}; | |
| 557 | +document.getElementById('btnUp').onclick=function(){ | |
| 558 | + if(curParent)openDir(curParent); | |
| 559 | + else if(curPath&&curRoot&&curPath!==curRoot)openDir(curRoot); | |
| 560 | + else toast('Already at the root'); | |
| 561 | +}; | |
| 562 | +document.getElementById('btnBack').onclick=function(){setView('browse');}; | |
| 563 | +document.getElementById('btnTheme').onclick=function(){ | |
| 564 | + if(window.sxApplyTheme)window.sxApplyTheme(window.sxTheme&&window.sxTheme()==='dark'?'light':'dark'); | |
| 565 | +}; | |
| 566 | +btnHidden.onclick=function(){ | |
| 567 | + showHidden=!showHidden; | |
| 568 | + btnHidden.classList.toggle('on',showHidden); | |
| 569 | + btnHidden.title=showHidden?'Hide hidden files':'Show hidden files'; | |
| 570 | + if(curPath)openDir(curPath); | |
| 571 | +}; | |
| 572 | +btnDownload.onclick=function(){ | |
| 573 | + if(!curFile)return; | |
| 574 | + var a=document.createElement('a'); | |
| 575 | + a.href=url('raw','path='+encodeURIComponent(curFile)+'&download=1'); | |
| 576 | + a.rel='noopener'; | |
| 577 | + document.body.appendChild(a);a.click();document.body.removeChild(a); | |
| 578 | +}; | |
| 579 | + | |
| 580 | +document.addEventListener('keydown',function(ev){ | |
| 581 | + var tag=(ev.target&&ev.target.tagName||'').toLowerCase(); | |
| 582 | + if(tag==='input'||tag==='textarea')return; | |
| 583 | + if(ev.key==='ArrowDown'||ev.key==='ArrowUp'){ | |
| 584 | + if(!entries.length)return; | |
| 585 | + ev.preventDefault(); | |
| 586 | + selIndex+=(ev.key==='ArrowDown'?1:-1); | |
| 587 | + if(selIndex<0)selIndex=0; | |
| 588 | + if(selIndex>=entries.length)selIndex=entries.length-1; | |
| 589 | + renderEntries(); | |
| 590 | + }else if(ev.key==='Enter'){ | |
| 591 | + if(selIndex>=0&&entries[selIndex]){ev.preventDefault();activate(entries[selIndex]);} | |
| 592 | + }else if(ev.key==='Backspace'){ | |
| 593 | + if(curParent){ev.preventDefault();openDir(curParent);} | |
| 594 | + }else if(ev.key==='/'&&ev.ctrlKey===false){ | |
| 595 | + return; | |
| 596 | + } | |
| 597 | +}); | |
| 598 | + | |
| 599 | +function loadRoots(){ | |
| 600 | + return api('roots').then(function(d){ | |
| 601 | + roots=(d&&d.roots)||[]; | |
| 602 | + renderRoots(); | |
| 603 | + /* Wide screens open the first root straight away; a phone keeps the root | |
| 604 | + * list on screen, because a hidden sidebar there means an empty page. */ | |
| 605 | + if(roots.length&&!curPath&&window.matchMedia('(min-width:821px)').matches){ | |
| 606 | + openDir(roots[0].path); | |
| 607 | + } | |
| 608 | + }).catch(function(e){toast('Cannot list roots: '+e.message);}); | |
| 609 | +} | |
| 610 | + | |
| 611 | +loadRoots(); | |
| 612 | +})(); | |
| 613 | +</script> | |
| 614 | +</body></html> |
| 1 | 1 | new file mode 100644 |
| index 0000000..edb635e | ||
| --- /dev/null | ||
| +++ b/src/ui_html.h | ||
| @@ -0,0 +1,622 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | |
| 2 | +#ifndef SX_FILES_UI_HTML_H | |
| 3 | +#define SX_FILES_UI_HTML_H | |
| 4 | + | |
| 5 | +static const char *UI_HTML = | |
| 6 | + "<!DOCTYPE html>\n" | |
| 7 | + "<html lang=\"en\"><head><meta charset=\"utf-8\">\n" | |
| 8 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | |
| 9 | + "<title>files</title>\n" | |
| 10 | + "\001\n" | |
| 11 | + "<style>\n" | |
| 12 | + "*{box-sizing:border-box}\n" | |
| 13 | + "html,body{margin:0;height:100%}\n" | |
| 14 | + "body{background:var(--bg);color:var(--text);font-family:var(--font);\n" | |
| 15 | + " font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased;overflow:hidden}\n" | |
| 16 | + "#app{display:grid;grid-template-columns:252px minmax(0,1fr);height:100%;min-height:0}\n" | |
| 17 | + ".pane{min-width:0;min-height:0;display:flex;flex-direction:column}\n" | |
| 18 | + "#side{background:var(--bg-2);border-right:1px solid var(--line)}\n" | |
| 19 | + ".side-hd{display:flex;align-items:center;gap:8px;padding:12px 12px 8px}\n" | |
| 20 | + ".brand{font-size:12px;font-weight:700;letter-spacing:.09em;text-transform:uppercase;\n" | |
| 21 | + " color:var(--text-2);flex:1}\n" | |
| 22 | + ".side-ft{display:flex;align-items:center;gap:8px;padding:8px 12px;\n" | |
| 23 | + " border-top:1px solid var(--line);font-size:11px;color:var(--text-2)}\n" | |
| 24 | + ".side-ft .grow{flex:1}\n" | |
| 25 | + ".side-lbl{font-size:10.5px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;\n" | |
| 26 | + " color:var(--text-2);padding:4px 14px 6px}\n" | |
| 27 | + ".icon{display:inline-flex;align-items:center;justify-content:center;gap:6px;\n" | |
| 28 | + " background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n" | |
| 29 | + " border-radius:9px;width:30px;height:30px;padding:0;cursor:pointer;font-family:inherit;\n" | |
| 30 | + " font-size:12px;font-weight:600;flex:0 0 auto}\n" | |
| 31 | + ".icon:hover{background:var(--surface-hover);border-color:var(--line-2)}\n" | |
| 32 | + ".icon:active{transform:scale(.96)}\n" | |
| 33 | + ".icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor;\n" | |
| 34 | + " stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}\n" | |
| 35 | + ".icon.on{background:var(--surface-2);border-color:var(--line-2);color:var(--blue)}\n" | |
| 36 | + ".rootlist{flex:0 0 auto;padding:0 8px 10px;border-bottom:1px solid var(--line)}\n" | |
| 37 | + ".root{display:flex;align-items:center;gap:9px;width:100%;text-align:left;\n" | |
| 38 | + " background:transparent;border:0;border-radius:9px;padding:8px 10px;color:var(--text);\n" | |
| 39 | + " cursor:pointer;font-family:inherit;font-size:13px;margin-bottom:2px}\n" | |
| 40 | + ".root:hover{background:var(--surface-hover)}\n" | |
| 41 | + ".root.sel{background:var(--surface-2);box-shadow:inset 2px 0 0 var(--blue)}\n" | |
| 42 | + ".root svg{width:14px;height:14px;flex:0 0 auto;fill:none;stroke:currentColor;stroke-width:1.7;\n" | |
| 43 | + " stroke-linecap:round;stroke-linejoin:round;color:var(--text-2)}\n" | |
| 44 | + ".root .rl{min-width:0;flex:1}\n" | |
| 45 | + ".root .rl .n{display:block;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" | |
| 46 | + ".root .rl .p{display:block;font-size:10.5px;color:var(--text-2);overflow:hidden;\n" | |
| 47 | + " text-overflow:ellipsis;white-space:nowrap;font-family:var(--mono)}\n" | |
| 48 | + "#main{background:var(--bg);min-width:0}\n" | |
| 49 | + ".toolbar{display:flex;align-items:center;gap:7px;padding:10px 14px;\n" | |
| 50 | + " border-bottom:1px solid var(--line);flex:0 0 auto;min-width:0}\n" | |
| 51 | + ".crumbs{flex:1 1 auto;min-width:0;display:flex;align-items:center;gap:2px;\n" | |
| 52 | + " overflow-x:auto;scrollbar-width:none;white-space:nowrap}\n" | |
| 53 | + ".crumbs::-webkit-scrollbar{display:none}\n" | |
| 54 | + ".crumb{background:transparent;border:0;color:var(--text-2);font-family:var(--mono);\n" | |
| 55 | + " font-size:12px;padding:3px 5px;border-radius:6px;cursor:pointer;flex:0 0 auto}\n" | |
| 56 | + ".crumb:hover{background:var(--surface-hover);color:var(--text)}\n" | |
| 57 | + ".crumb.last{color:var(--text);font-weight:600}\n" | |
| 58 | + ".crumb .sep{color:var(--text-2);opacity:.6;padding:0 1px}\n" | |
| 59 | + ".body{flex:1 1 auto;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.15fr);\n" | |
| 60 | + " min-height:0}\n" | |
| 61 | + ".body.noprev{grid-template-columns:minmax(0,1fr)}\n" | |
| 62 | + ".listwrap{min-width:0;min-height:0;display:flex;flex-direction:column;\n" | |
| 63 | + " border-right:1px solid var(--line)}\n" | |
| 64 | + ".entries{flex:1 1 auto;overflow-y:auto;padding:6px 8px 20px}\n" | |
| 65 | + ".row{display:flex;align-items:center;gap:9px;width:100%;text-align:left;\n" | |
| 66 | + " background:transparent;border:0;border-radius:9px;padding:7px 9px;color:var(--text);\n" | |
| 67 | + " cursor:pointer;font-family:inherit;font-size:13px}\n" | |
| 68 | + ".row:hover{background:var(--surface-hover)}\n" | |
| 69 | + ".row.sel{background:var(--surface-2);box-shadow:inset 2px 0 0 var(--blue)}\n" | |
| 70 | + ".row .ico{width:16px;height:16px;flex:0 0 auto;color:var(--text-2);display:flex}\n" | |
| 71 | + ".row .ico svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:1.7;\n" | |
| 72 | + " stroke-linecap:round;stroke-linejoin:round}\n" | |
| 73 | + ".row.dir .ico{color:var(--blue)}\n" | |
| 74 | + ".row .nm{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" | |
| 75 | + ".row .mt{flex:0 0 auto;font-family:var(--mono);font-size:11px;color:var(--text-2)}\n" | |
| 76 | + ".empty{padding:22px 14px;color:var(--text-2);font-size:12.5px;text-align:center}\n" | |
| 77 | + ".hidden{display:none!important}\n" | |
| 78 | + ".preview{min-width:0;min-height:0;display:flex;flex-direction:column}\n" | |
| 79 | + ".prev-hd{display:flex;align-items:center;gap:8px;padding:9px 14px;\n" | |
| 80 | + " border-bottom:1px solid var(--line);flex:0 0 auto;min-width:0}\n" | |
| 81 | + ".prev-hd .nm{flex:1 1 auto;min-width:0;font-weight:600;font-size:13px;\n" | |
| 82 | + " overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" | |
| 83 | + ".prev-hd .mt{font-family:var(--mono);font-size:11px;color:var(--text-2);white-space:nowrap}\n" | |
| 84 | + ".prev-body{flex:1 1 auto;overflow:auto;min-height:0}\n" | |
| 85 | + ".codetxt{margin:0;padding:0;font-family:var(--mono);font-size:12.5px;line-height:1.6;\n" | |
| 86 | + " display:grid;grid-template-columns:auto minmax(0,1fr);min-width:0}\n" | |
| 87 | + ".codetxt .ln{color:var(--text-2);text-align:right;padding:0 10px 0 14px;\n" | |
| 88 | + " user-select:none;background:var(--bg-2);border-right:1px solid var(--line)}\n" | |
| 89 | + ".codetxt .tx{padding:0 14px;white-space:pre-wrap;word-break:break-word;\n" | |
| 90 | + " font-family:var(--mono);font-size:12.5px}\n" | |
| 91 | + ".md{padding:16px 20px 40px;max-width:860px}\n" | |
| 92 | + ".md h1,.md h2,.md h3,.md h4{line-height:1.25;margin:18px 0 8px;font-weight:650}\n" | |
| 93 | + ".md h1{font-size:21px}.md h2{font-size:18px}.md h3{font-size:15.5px}.md h4{font-size:14px}\n" | |
| 94 | + ".md p{margin:0 0 11px}\n" | |
| 95 | + ".md ul,.md ol{margin:0 0 11px;padding-left:22px}\n" | |
| 96 | + ".md li{margin:3px 0}\n" | |
| 97 | + ".md code{font-family:var(--mono);font-size:12px;background:var(--code-bg);\n" | |
| 98 | + " padding:1px 5px;border-radius:5px}\n" | |
| 99 | + ".md pre{background:var(--code-bg);border:1px solid var(--line);border-radius:10px;\n" | |
| 100 | + " padding:11px 13px;overflow-x:auto;margin:0 0 12px}\n" | |
| 101 | + ".md pre code{background:transparent;padding:0;font-size:12px;line-height:1.55}\n" | |
| 102 | + ".md hr{border:0;border-top:1px solid var(--line);margin:16px 0}\n" | |
| 103 | + ".md a{color:var(--blue);text-decoration:none;font-weight:600}\n" | |
| 104 | + ".md a:hover{text-decoration:underline}\n" | |
| 105 | + ".md blockquote{margin:0 0 12px;padding:2px 0 2px 13px;border-left:3px solid var(--line-2);\n" | |
| 106 | + " color:var(--text-2)}\n" | |
| 107 | + ".imgwrap{padding:16px;display:flex;align-items:flex-start;justify-content:center}\n" | |
| 108 | + ".imgwrap img{max-width:100%;height:auto;border-radius:10px;border:1px solid var(--line);\n" | |
| 109 | + " background:var(--bg-2)}\n" | |
| 110 | + ".note{padding:16px 18px;color:var(--text-2);font-size:12.5px}\n" | |
| 111 | + ".welcome{flex:1 1 auto;display:flex;flex-direction:column;align-items:center;\n" | |
| 112 | + " justify-content:center;gap:10px;color:var(--text-2);font-size:13px;padding:24px;\n" | |
| 113 | + " text-align:center;min-height:0}\n" | |
| 114 | + ".welcome svg{width:34px;height:34px;fill:none;stroke:currentColor;stroke-width:1.4;\n" | |
| 115 | + " stroke-linecap:round;stroke-linejoin:round;opacity:.55}\n" | |
| 116 | + ".toast{position:fixed;left:50%;bottom:18px;transform:translateX(-50%);\n" | |
| 117 | + " background:var(--modal-bg);border:1px solid var(--line-2);color:var(--text);\n" | |
| 118 | + " padding:8px 14px;border-radius:999px;font-size:12.5px;box-shadow:var(--shadow-lg);\n" | |
| 119 | + " opacity:0;pointer-events:none;transition:opacity .16s var(--ease);z-index:9;\n" | |
| 120 | + " max-width:calc(100% - 24px);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" | |
| 121 | + ".toast.show{opacity:1}\n" | |
| 122 | + "@media (max-width:1100px){\n" | |
| 123 | + " #app{grid-template-columns:216px minmax(0,1fr)}\n" | |
| 124 | + " .body{grid-template-columns:minmax(0,1fr) minmax(0,1fr)}\n" | |
| 125 | + "}\n" | |
| 126 | + "@media (max-width:820px){\n" | |
| 127 | + " body{overflow:hidden}\n" | |
| 128 | + " #app{grid-template-columns:minmax(0,1fr)}\n" | |
| 129 | + " #side,#main{grid-column:1;grid-row:1}\n" | |
| 130 | + " #app[data-view=\"browse\"] #side{display:none}\n" | |
| 131 | + " #app[data-view=\"roots\"] #main{display:none}\n" | |
| 132 | + " .body{grid-template-columns:minmax(0,1fr)}\n" | |
| 133 | + " #app[data-view=\"browse\"] .body{grid-template-columns:minmax(0,1fr)}\n" | |
| 134 | + " #app[data-view=\"browse\"] .preview{display:none}\n" | |
| 135 | + " #app[data-view=\"preview\"] .listwrap{display:none}\n" | |
| 136 | + " #app[data-view=\"preview\"] .body{grid-template-columns:minmax(0,1fr)}\n" | |
| 137 | + " .back{display:inline-flex!important}\n" | |
| 138 | + " .toolbar{padding:8px 10px;gap:6px}\n" | |
| 139 | + " .md{padding:12px 14px 32px}\n" | |
| 140 | + " .codetxt .tx{padding:0 10px}\n" | |
| 141 | + "}\n" | |
| 142 | + "@media (min-width:821px){.back{display:none!important}}\n" | |
| 143 | + "</style>\n" | |
| 144 | + "</head><body>\n" | |
| 145 | + "<div id=\"app\" data-view=\"roots\">\n" | |
| 146 | + " <aside id=\"side\" class=\"pane\">\n" | |
| 147 | + " <div class=\"side-hd\">\n" | |
| 148 | + " <span class=\"brand\">files</span>\n" | |
| 149 | + " <button id=\"btnUp\" class=\"icon\" title=\"Up one level\" aria-label=\"Up one level\">\n" | |
| 150 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M12 19V5M5 12l7-7 7 7\"/></svg></button>\n" | |
| 151 | + " <button id=\"btnRefresh\" class=\"icon\" title=\"Refresh\" aria-label=\"Refresh\">\n" | |
| 152 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M20 11a8 8 0 1 0-2.3 5.7\"/><path d=\"M20 4v7h-7\"/></svg></button>\n" | |
| 153 | + " </div>\n" | |
| 154 | + " <div class=\"side-lbl\">Roots</div>\n" | |
| 155 | + " <div id=\"roots\" class=\"rootlist\"></div>\n" | |
| 156 | + " <div class=\"side-ft\">\n" | |
| 157 | + " <span id=\"count\">0 items</span><span class=\"grow\"></span>\n" | |
| 158 | + " <button id=\"btnHidden\" class=\"icon\" title=\"Show hidden files\" aria-label=\"Show hidden files\">\n" | |
| 159 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z\"/><circle cx=\"12\" cy=\"12\" r=\"3\"/></svg></button>\n" | |
| 160 | + " <button id=\"btnTheme\" class=\"icon embed-hide\" title=\"Toggle appearance\" aria-label=\"Toggle appearance\">\n" | |
| 161 | + " <svg viewBox=\"0 0 24 24\"><circle cx=\"12\" cy=\"12\" r=\"4.5\"/><path d=\"M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4\"/></svg></button>\n" | |
| 162 | + " </div>\n" | |
| 163 | + " </aside>\n" | |
| 164 | + " <main id=\"main\" class=\"pane\">\n" | |
| 165 | + " <div class=\"toolbar\">\n" | |
| 166 | + " <button id=\"btnBack\" class=\"icon back\" title=\"Back to list\" aria-label=\"Back to list\">\n" | |
| 167 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M15 5l-7 7 7 7\"/></svg></button>\n" | |
| 168 | + " <div id=\"crumbs\" class=\"crumbs\"></div>\n" | |
| 169 | + " <button id=\"btnDownload\" class=\"icon\" title=\"Download file\" aria-label=\"Download file\">\n" | |
| 170 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M12 3v12M7 11l5 5 5-5M4 21h16\"/></svg></button>\n" | |
| 171 | + " </div>\n" | |
| 172 | + " <div id=\"body\" class=\"body\">\n" | |
| 173 | + " <div class=\"listwrap\">\n" | |
| 174 | + " <div id=\"entries\" class=\"entries\"></div>\n" | |
| 175 | + " <div id=\"empty\" class=\"empty hidden\">This directory is empty.</div>\n" | |
| 176 | + " </div>\n" | |
| 177 | + " <div id=\"preview\" class=\"preview\">\n" | |
| 178 | + " <div id=\"prevHd\" class=\"prev-hd hidden\">\n" | |
| 179 | + " <span id=\"prevName\" class=\"nm\"></span>\n" | |
| 180 | + " <span id=\"prevMeta\" class=\"mt\"></span>\n" | |
| 181 | + " </div>\n" | |
| 182 | + " <div id=\"prevBody\" class=\"prev-body\">\n" | |
| 183 | + " <div id=\"welcome\" class=\"welcome\">\n" | |
| 184 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M3 7h6l2 2h10v11H3z\"/></svg>\n" | |
| 185 | + " <div>Pick a root, then open a file to preview it.</div>\n" | |
| 186 | + " <div style=\"font-size:11.5px\">Arrows move · Enter opens · Backspace goes up</div>\n" | |
| 187 | + " </div>\n" | |
| 188 | + " </div>\n" | |
| 189 | + " </div>\n" | |
| 190 | + " </div>\n" | |
| 191 | + " </main>\n" | |
| 192 | + "</div>\n" | |
| 193 | + "<div id=\"toast\" class=\"toast\"></div>\n" | |
| 194 | + "<script>\n" | |
| 195 | + "(function(){\n" | |
| 196 | + "\"use strict\";\n" | |
| 197 | + "var app=document.getElementById('app');\n" | |
| 198 | + "var rootsEl=document.getElementById('roots');\n" | |
| 199 | + "var entriesEl=document.getElementById('entries');\n" | |
| 200 | + "var emptyEl=document.getElementById('empty');\n" | |
| 201 | + "var countEl=document.getElementById('count');\n" | |
| 202 | + "var crumbsEl=document.getElementById('crumbs');\n" | |
| 203 | + "var bodyEl=document.getElementById('body');\n" | |
| 204 | + "var prevEl=document.getElementById('preview');\n" | |
| 205 | + "var prevHd=document.getElementById('prevHd');\n" | |
| 206 | + "var prevName=document.getElementById('prevName');\n" | |
| 207 | + "var prevMeta=document.getElementById('prevMeta');\n" | |
| 208 | + "var prevBody=document.getElementById('prevBody');\n" | |
| 209 | + "var toastEl=document.getElementById('toast');\n" | |
| 210 | + "var btnHidden=document.getElementById('btnHidden');\n" | |
| 211 | + "var btnDownload=document.getElementById('btnDownload');\n" | |
| 212 | + "\n" | |
| 213 | + "var q=new URLSearchParams(location.search);\n" | |
| 214 | + "var node=q.get('node')||'';\n" | |
| 215 | + "var sid=q.get('id')||'';\n" | |
| 216 | + "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n" | |
| 217 | + " localStorage.getItem('bot_active_pwd')||'';\n" | |
| 218 | + "var HUB=q.get('plugin')||'';\n" | |
| 219 | + "\n" | |
| 220 | + "var roots=[], entries=[], curPath='', curParent=null, curRoot=null;\n" | |
| 221 | + "var selIndex=-1, showHidden=false, curFile=null;\n" | |
| 222 | + "\n" | |
| 223 | + "/* Two call routes, and getting this wrong is the most common plugin bug:\n" | |
| 224 | + " * page served through the hub (bot.scorpiox.net/plugins?plugin=plugin_files&node=..)\n" | |
| 225 | + " * -> call the hub proxy back: /plugins?plugin=plugin_files&action=..\n" | |
| 226 | + " * opened directly on the node\n" | |
| 227 | + " * -> the plugin itself is the route: /plugin_files?action=..\n" | |
| 228 | + " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n" | |
| 229 | + "function url(action,extra){\n" | |
| 230 | + " var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_files')+\n" | |
| 231 | + " '?action='+encodeURIComponent(action)+\n" | |
| 232 | + " (extra?('&'+extra):'')+\n" | |
| 233 | + " (node?'&node='+encodeURIComponent(node):'')+\n" | |
| 234 | + " (sid?'&id='+encodeURIComponent(sid):'')+\n" | |
| 235 | + " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n" | |
| 236 | + " return u;\n" | |
| 237 | + "}\n" | |
| 238 | + "function hdr(extra){\n" | |
| 239 | + " var h=extra||{};\n" | |
| 240 | + " if(pwd)h['X-Bot-Password']=pwd;\n" | |
| 241 | + " return h;\n" | |
| 242 | + "}\n" | |
| 243 | + "function api(action,extra){\n" | |
| 244 | + " return fetch(url(action,extra),{headers:hdr({})}).then(function(r){\n" | |
| 245 | + " if(!r.ok)throw new Error('HTTP '+r.status);\n" | |
| 246 | + " return r.json();\n" | |
| 247 | + " });\n" | |
| 248 | + "}\n" | |
| 249 | + "\n" | |
| 250 | + "function toast(msg){\n" | |
| 251 | + " toastEl.textContent=msg;\n" | |
| 252 | + " toastEl.classList.add('show');\n" | |
| 253 | + " clearTimeout(toast._t);\n" | |
| 254 | + " toast._t=setTimeout(function(){toastEl.classList.remove('show');},2000);\n" | |
| 255 | + "}\n" | |
| 256 | + "function setView(v){app.setAttribute('data-view',v);}\n" | |
| 257 | + "\n" | |
| 258 | + "function fmtSize(n){\n" | |
| 259 | + " if(n===null||n===undefined)return '';\n" | |
| 260 | + " if(n<1024)return n+' B';\n" | |
| 261 | + " if(n<1048576)return (n/1024).toFixed(1)+' KB';\n" | |
| 262 | + " if(n<1073741824)return (n/1048576).toFixed(1)+' MB';\n" | |
| 263 | + " return (n/1073741824).toFixed(1)+' GB';\n" | |
| 264 | + "}\n" | |
| 265 | + "function fmtTime(iso){\n" | |
| 266 | + " if(!iso)return '';\n" | |
| 267 | + " try{\n" | |
| 268 | + " var d=new Date(iso),now=new Date(),diff=(now-d)/1000;\n" | |
| 269 | + " if(diff<60)return 'just now';\n" | |
| 270 | + " if(diff<3600)return Math.floor(diff/60)+'m ago';\n" | |
| 271 | + " if(diff<86400)return Math.floor(diff/3600)+'h ago';\n" | |
| 272 | + " if(diff<604800)return Math.floor(diff/86400)+'d ago';\n" | |
| 273 | + " return d.toLocaleDateString();\n" | |
| 274 | + " }catch(e){return ''}\n" | |
| 275 | + "}\n" | |
| 276 | + "\n" | |
| 277 | + "var SVG={\n" | |
| 278 | + " dir:'<svg viewBox=\"0 0 24 24\"><path d=\"M3 7h6l2 2h10v11H3z\"/></svg>',\n" | |
| 279 | + " file:'<svg viewBox=\"0 0 24 24\"><path d=\"M6 3h9l5 5v13H6z\"/><path d=\"M14 3v5h5\"/></svg>',\n" | |
| 280 | + " link:'<svg viewBox=\"0 0 24 24\"><path d=\"M10 13a4 4 0 0 0 6 .5l2.5-2.5a4 4 0 0 0-6-6L11 6.5\"/><path d=\"M14 11a4 4 0 0 0-6-.5L5.5 13a4 4 0 0 0 6 6L13 17.5\"/></svg>',\n" | |
| 281 | + " img:'<svg viewBox=\"0 0 24 24\"><rect x=\"3\" y=\"5\" width=\"18\" height=\"14\" rx=\"2\"/><circle cx=\"8.5\" cy=\"10\" r=\"1.6\"/><path d=\"M21 16l-5-5-6 6\"/></svg>',\n" | |
| 282 | + " root:'<svg viewBox=\"0 0 24 24\"><path d=\"M3 7h6l2 2h10v11H3z\"/></svg>'\n" | |
| 283 | + "};\n" | |
| 284 | + "\n" | |
| 285 | + "function renderRoots(){\n" | |
| 286 | + " while(rootsEl.firstChild)rootsEl.removeChild(rootsEl.firstChild);\n" | |
| 287 | + " roots.forEach(function(r,i){\n" | |
| 288 | + " var b=document.createElement('button');\n" | |
| 289 | + " b.className='root'+(curRoot===r.path?' sel':'');\n" | |
| 290 | + " var ic=document.createElement('span');ic.innerHTML=SVG.root;\n" | |
| 291 | + " var wrap=document.createElement('span');wrap.className='rl';\n" | |
| 292 | + " var n=document.createElement('span');n.className='n';n.textContent=r.name;\n" | |
| 293 | + " var p=document.createElement('span');p.className='p';p.textContent=r.path;\n" | |
| 294 | + " wrap.appendChild(n);wrap.appendChild(p);\n" | |
| 295 | + " b.appendChild(ic);b.appendChild(wrap);\n" | |
| 296 | + " b.onclick=function(){openDir(r.path);setView('browse');};\n" | |
| 297 | + " rootsEl.appendChild(b);\n" | |
| 298 | + " });\n" | |
| 299 | + "}\n" | |
| 300 | + "\n" | |
| 301 | + "function renderCrumbs(){\n" | |
| 302 | + " while(crumbsEl.firstChild)crumbsEl.removeChild(crumbsEl.firstChild);\n" | |
| 303 | + " if(!curPath){\n" | |
| 304 | + " var hint=document.createElement('span');hint.className='crumb last';\n" | |
| 305 | + " hint.textContent='Select a root';crumbsEl.appendChild(hint);return;\n" | |
| 306 | + " }\n" | |
| 307 | + " var base=curRoot||'';\n" | |
| 308 | + " var rel=curPath;\n" | |
| 309 | + " if(base&&curPath.indexOf(base)===0)rel=curPath.slice(base.length);\n" | |
| 310 | + " var parts=rel.split(/[\\/\\\\]+/).filter(function(s){return s.length;});\n" | |
| 311 | + " var b0=document.createElement('button');\n" | |
| 312 | + " b0.className='crumb'+(parts.length?'':' last');\n" | |
| 313 | + " b0.textContent=base.split(/[\\/\\\\]+/).filter(Boolean).pop()||base||'/';\n" | |
| 314 | + " b0.title=base;\n" | |
| 315 | + " b0.onclick=function(){openDir(base);};\n" | |
| 316 | + " crumbsEl.appendChild(b0);\n" | |
| 317 | + " var acc=base;\n" | |
| 318 | + " parts.forEach(function(p,i){\n" | |
| 319 | + " var sp=document.createElement('span');sp.className='sep';sp.textContent='/';\n" | |
| 320 | + " crumbsEl.appendChild(sp);\n" | |
| 321 | + " acc+=(acc&&acc[acc.length-1]!=='/'&&acc[acc.length-1]!=='\\\\'?'/':'')+p;\n" | |
| 322 | + " var b=document.createElement('button');\n" | |
| 323 | + " b.className='crumb'+(i===parts.length-1?' last':'');\n" | |
| 324 | + " b.textContent=p;b.title=acc;\n" | |
| 325 | + " var target=acc;\n" | |
| 326 | + " b.onclick=function(){openDir(target);};\n" | |
| 327 | + " crumbsEl.appendChild(b);\n" | |
| 328 | + " });\n" | |
| 329 | + "}\n" | |
| 330 | + "\n" | |
| 331 | + "function isImage(name){\n" | |
| 332 | + " return /\\.(png|jpe?g|gif|webp|bmp|ico|svg)$/i.test(name||'');\n" | |
| 333 | + "}\n" | |
| 334 | + "function isMarkdown(name){\n" | |
| 335 | + " return /\\.(md|markdown)$/i.test(name||'');\n" | |
| 336 | + "}\n" | |
| 337 | + "function isTextish(name){\n" | |
| 338 | + " return /\\.(txt|md|markdown|json|js|ts|css|html?|c|h|cpp|hpp|py|sh|yml|yaml|toml|ini|conf|log|csv|xml|sql|go|rs|java|rb|php|gitignore|env)$/i.test(name||'');\n" | |
| 339 | + "}\n" | |
| 340 | + "\n" | |
| 341 | + "function renderEntries(){\n" | |
| 342 | + " while(entriesEl.firstChild)entriesEl.removeChild(entriesEl.firstChild);\n" | |
| 343 | + " if(selIndex>=entries.length)selIndex=entries.length?entries.length-1:-1;\n" | |
| 344 | + " entries.forEach(function(e,i){\n" | |
| 345 | + " var b=document.createElement('button');\n" | |
| 346 | + " b.className='row'+(e.type==='dir'?' dir':'')+(i===selIndex?' sel':'');\n" | |
| 347 | + " var ic=document.createElement('span');ic.className='ico';\n" | |
| 348 | + " ic.innerHTML = e.type==='dir'?SVG.dir : (isImage(e.name)?SVG.img : (e.type==='link'?SVG.link:SVG.file));\n" | |
| 349 | + " var nm=document.createElement('span');nm.className='nm';nm.textContent=e.name;\n" | |
| 350 | + " var mt=document.createElement('span');mt.className='mt';\n" | |
| 351 | + " mt.textContent=(e.type==='dir'?'':fmtSize(e.size));\n" | |
| 352 | + " b.appendChild(ic);b.appendChild(nm);b.appendChild(mt);\n" | |
| 353 | + " b.onclick=function(){selIndex=i;renderEntries();activate(e);};\n" | |
| 354 | + " entriesEl.appendChild(b);\n" | |
| 355 | + " });\n" | |
| 356 | + " emptyEl.classList.toggle('hidden',entries.length>0);\n" | |
| 357 | + " countEl.textContent=entries.length+(entries.length===1?' item':' items');\n" | |
| 358 | + " var sel=entriesEl.querySelector('.row.sel');\n" | |
| 359 | + " if(sel&&sel.scrollIntoView)sel.scrollIntoView({block:'nearest'});\n" | |
| 360 | + "}\n" | |
| 361 | + "\n" | |
| 362 | + "function openDir(path){\n" | |
| 363 | + " return api('ls','path='+encodeURIComponent(path)+(showHidden?'&hidden=1':''))\n" | |
| 364 | + " .then(function(d){\n" | |
| 365 | + " if(!d||!d.ok)throw new Error((d&&d.error)||'failed');\n" | |
| 366 | + " curPath=d.path;curParent=d.parent;curRoot=d.root;\n" | |
| 367 | + " entries=d.entries||[];selIndex=entries.length?0:-1;\n" | |
| 368 | + " renderCrumbs();renderEntries();\n" | |
| 369 | + " if(!entries.length){clearPreview();}\n" | |
| 370 | + " else if(window.matchMedia('(max-width:820px)').matches){setView('browse');}\n" | |
| 371 | + " return d;\n" | |
| 372 | + " }).catch(function(e){toast('Cannot open folder: '+e.message);});\n" | |
| 373 | + "}\n" | |
| 374 | + "\n" | |
| 375 | + "function clearPreview(){\n" | |
| 376 | + " prevHd.classList.add('hidden');\n" | |
| 377 | + " while(prevBody.firstChild)prevBody.removeChild(prevBody.firstChild);\n" | |
| 378 | + " var w=document.createElement('div');w.className='welcome';\n" | |
| 379 | + " w.innerHTML='<svg viewBox=\"0 0 24 24\"><path d=\"M3 7h6l2 2h10v11H3z\"/></svg>'+\n" | |
| 380 | + " '<div>Pick a root, then open a file to preview it.</div>'+\n" | |
| 381 | + " '<div style=\"font-size:11.5px\">Arrows move · Enter opens · Backspace goes up</div>';\n" | |
| 382 | + " prevBody.appendChild(w);\n" | |
| 383 | + " curFile=null;\n" | |
| 384 | + " btnDownload.classList.add('hidden');\n" | |
| 385 | + "}\n" | |
| 386 | + "\n" | |
| 387 | + "function activate(e){\n" | |
| 388 | + " if(e.type==='dir'){openDir(joinPath(curPath,e.name));setView('browse');return;}\n" | |
| 389 | + " previewFile(joinPath(curPath,e.name),e);\n" | |
| 390 | + "}\n" | |
| 391 | + "function joinPath(dir,name){\n" | |
| 392 | + " if(!dir)return name;\n" | |
| 393 | + " var last=dir[dir.length-1];\n" | |
| 394 | + " return dir+(last==='/'||last==='\\\\'?'':'/')+name;\n" | |
| 395 | + "}\n" | |
| 396 | + "\n" | |
| 397 | + "function setHd(name,meta){\n" | |
| 398 | + " prevHd.classList.remove('hidden');\n" | |
| 399 | + " prevName.textContent=name;\n" | |
| 400 | + " prevMeta.textContent=meta||'';\n" | |
| 401 | + " btnDownload.classList.remove('hidden');\n" | |
| 402 | + "}\n" | |
| 403 | + "\n" | |
| 404 | + "function previewFile(path,ent){\n" | |
| 405 | + " curFile=path;\n" | |
| 406 | + " setView('preview');\n" | |
| 407 | + " prevHd.classList.remove('hidden');\n" | |
| 408 | + " prevName.textContent=ent&&ent.name?ent.name:path.split(/[\\/\\\\]/).pop();\n" | |
| 409 | + " prevMeta.textContent=ent?fmtSize(ent.size):'';\n" | |
| 410 | + " btnDownload.classList.remove('hidden');\n" | |
| 411 | + " while(prevBody.firstChild)prevBody.removeChild(prevBody.firstChild);\n" | |
| 412 | + " prevBody.scrollTop=0;\n" | |
| 413 | + "\n" | |
| 414 | + " var name=prevName.textContent;\n" | |
| 415 | + " if(isImage(name)){\n" | |
| 416 | + " var wrap=document.createElement('div');wrap.className='imgwrap';\n" | |
| 417 | + " var img=document.createElement('img');\n" | |
| 418 | + " img.alt=name;\n" | |
| 419 | + " img.src=url('raw','path='+encodeURIComponent(path));\n" | |
| 420 | + " img.onerror=function(){\n" | |
| 421 | + " wrap.innerHTML='';\n" | |
| 422 | + " var n=document.createElement('div');n.className='note';\n" | |
| 423 | + " n.textContent='This image could not be displayed.';\n" | |
| 424 | + " wrap.appendChild(n);\n" | |
| 425 | + " };\n" | |
| 426 | + " wrap.appendChild(img);prevBody.appendChild(wrap);\n" | |
| 427 | + " return;\n" | |
| 428 | + " }\n" | |
| 429 | + "\n" | |
| 430 | + " api('read','path='+encodeURIComponent(path)).then(function(d){\n" | |
| 431 | + " if(!d||!d.ok)throw new Error((d&&d.error)||'failed');\n" | |
| 432 | + " prevMeta.textContent=fmtSize(d.size)+(d.truncated?' (first 1 MB)':'');\n" | |
| 433 | + " if(d.binary){\n" | |
| 434 | + " var n=document.createElement('div');n.className='note';\n" | |
| 435 | + " n.textContent='Binary file ('+fmtSize(d.size)+') - use Download to inspect it locally.';\n" | |
| 436 | + " prevBody.appendChild(n);return;\n" | |
| 437 | + " }\n" | |
| 438 | + " if(!isTextish(name)&&!isMarkdown(name)){\n" | |
| 439 | + " prevMeta.textContent=fmtSize(d.size)+(d.truncated?' (first 1 MB)':'')+' · plain text';\n" | |
| 440 | + " }\n" | |
| 441 | + " if(isMarkdown(name))renderMarkdown(d.text||'',prevBody);\n" | |
| 442 | + " else renderCode(d.text||'',prevBody);\n" | |
| 443 | + " }).catch(function(e){\n" | |
| 444 | + " while(prevBody.firstChild)prevBody.removeChild(prevBody.firstChild);\n" | |
| 445 | + " var n=document.createElement('div');n.className='note';\n" | |
| 446 | + " n.textContent='Cannot preview this file: '+e.message;\n" | |
| 447 | + " prevBody.appendChild(n);\n" | |
| 448 | + " });\n" | |
| 449 | + "}\n" | |
| 450 | + "\n" | |
| 451 | + "/* Line numbers + text. Every line is a text node, so file content can never\n" | |
| 452 | + " * become markup. */\n" | |
| 453 | + "function renderCode(text,host){\n" | |
| 454 | + " var lines=text.split('\\n');\n" | |
| 455 | + " if(lines.length&&lines[lines.length-1]==='')lines.pop();\n" | |
| 456 | + " var pre=document.createElement('div');pre.className='codetxt';\n" | |
| 457 | + " var ln=document.createElement('div');ln.className='ln';\n" | |
| 458 | + " var tx=document.createElement('div');tx.className='tx';\n" | |
| 459 | + " var nums=[],body=[];\n" | |
| 460 | + " for(var i=0;i<lines.length;i++){nums.push(String(i+1));body.push(lines[i]);}\n" | |
| 461 | + " ln.textContent=nums.join('\\n');\n" | |
| 462 | + " tx.textContent=body.join('\\n');\n" | |
| 463 | + " pre.appendChild(ln);pre.appendChild(tx);\n" | |
| 464 | + " host.appendChild(pre);\n" | |
| 465 | + "}\n" | |
| 466 | + "\n" | |
| 467 | + "/* Tiny markdown renderer: headings, lists, fenced code, blockquote, hr,\n" | |
| 468 | + " * inline code/bold/italic/links. No CDN, no innerHTML with file content. */\n" | |
| 469 | + "function renderMarkdown(text,host){\n" | |
| 470 | + " var box=document.createElement('div');box.className='md';\n" | |
| 471 | + " var lines=text.split('\\n');\n" | |
| 472 | + " var i=0,para=[],list=null;\n" | |
| 473 | + "\n" | |
| 474 | + " function flushPara(){\n" | |
| 475 | + " if(!para.length)return;\n" | |
| 476 | + " var p=document.createElement('p');\n" | |
| 477 | + " inline(para.join(' '),p);\n" | |
| 478 | + " box.appendChild(p);para=[];\n" | |
| 479 | + " }\n" | |
| 480 | + " function flushList(){\n" | |
| 481 | + " if(!list)return;\n" | |
| 482 | + " box.appendChild(list);list=null;\n" | |
| 483 | + " }\n" | |
| 484 | + " function inline(s,parent){\n" | |
| 485 | + " var re=/(`[^`]*`)|(\\*\\*[^*]+\\*\\*)|(\\*[^*]+\\*)|(\\[[^\\]]+\\]\\([^)]+\\))/g;\n" | |
| 486 | + " var last=0,m;\n" | |
| 487 | + " while((m=re.exec(s))!==null){\n" | |
| 488 | + " if(m.index>last)parent.appendChild(document.createTextNode(s.slice(last,m.index)));\n" | |
| 489 | + " var tok=m[0];\n" | |
| 490 | + " if(tok[0]==='`'){\n" | |
| 491 | + " var c=document.createElement('code');c.textContent=tok.slice(1,-1);parent.appendChild(c);\n" | |
| 492 | + " }else if(tok.slice(0,2)==='**'){\n" | |
| 493 | + " var b=document.createElement('strong');b.textContent=tok.slice(2,-2);parent.appendChild(b);\n" | |
| 494 | + " }else if(tok[0]==='*'){\n" | |
| 495 | + " var em=document.createElement('em');em.textContent=tok.slice(1,-1);parent.appendChild(em);\n" | |
| 496 | + " }else{\n" | |
| 497 | + " var mm=/^\\[([^\\]]+)\\]\\(([^)]+)\\)$/.exec(tok);\n" | |
| 498 | + " if(mm&&/^(https?:\\/\\/|\\/|#|mailto:)/i.test(mm[2])){\n" | |
| 499 | + " var a=document.createElement('a');\n" | |
| 500 | + " a.textContent=mm[1];a.href=mm[2];\n" | |
| 501 | + " a.target='_blank';a.rel='noopener noreferrer';\n" | |
| 502 | + " parent.appendChild(a);\n" | |
| 503 | + " }else if(mm){\n" | |
| 504 | + " parent.appendChild(document.createTextNode(mm[1]));\n" | |
| 505 | + " }\n" | |
| 506 | + " }\n" | |
| 507 | + " last=m.index+tok.length;\n" | |
| 508 | + " }\n" | |
| 509 | + " if(last<s.length)parent.appendChild(document.createTextNode(s.slice(last)));\n" | |
| 510 | + " }\n" | |
| 511 | + "\n" | |
| 512 | + " while(i<lines.length){\n" | |
| 513 | + " var line=lines[i];\n" | |
| 514 | + " if(/^```/.test(line)){\n" | |
| 515 | + " flushPara();flushList();\n" | |
| 516 | + " var buf=[];i++;\n" | |
| 517 | + " while(i<lines.length&&!/^```/.test(lines[i])){buf.push(lines[i]);i++;}\n" | |
| 518 | + " i++;\n" | |
| 519 | + " var pre=document.createElement('pre');\n" | |
| 520 | + " var code=document.createElement('code');code.textContent=buf.join('\\n');\n" | |
| 521 | + " pre.appendChild(code);box.appendChild(pre);\n" | |
| 522 | + " continue;\n" | |
| 523 | + " }\n" | |
| 524 | + " if(/^\\s*$/.test(line)){flushPara();flushList();i++;continue;}\n" | |
| 525 | + " var h=/^(#{1,4})\\s+(.*)$/.exec(line);\n" | |
| 526 | + " if(h){\n" | |
| 527 | + " flushPara();flushList();\n" | |
| 528 | + " var el=document.createElement('h'+h[1].length);\n" | |
| 529 | + " inline(h[2],el);box.appendChild(el);i++;continue;\n" | |
| 530 | + " }\n" | |
| 531 | + " if(/^\\s*([-*+]|\\d+\\.)\\s+/.test(line)){\n" | |
| 532 | + " flushPara();\n" | |
| 533 | + " var ordered=/^\\s*\\d+\\.\\s+/.test(line);\n" | |
| 534 | + " if(!list||list.tagName.toLowerCase()!==(ordered?'ol':'ul')){\n" | |
| 535 | + " flushList();list=document.createElement(ordered?'ol':'ul');\n" | |
| 536 | + " }\n" | |
| 537 | + " var li=document.createElement('li');\n" | |
| 538 | + " inline(line.replace(/^\\s*([-*+]|\\d+\\.)\\s+/,''),li);\n" | |
| 539 | + " list.appendChild(li);i++;continue;\n" | |
| 540 | + " }\n" | |
| 541 | + " if(/^>\\s?/.test(line)){\n" | |
| 542 | + " flushPara();flushList();\n" | |
| 543 | + " var bq=document.createElement('blockquote');\n" | |
| 544 | + " inline(line.replace(/^>\\s?/,''),bq);\n" | |
| 545 | + " box.appendChild(bq);i++;continue;\n" | |
| 546 | + " }\n" | |
| 547 | + " if(/^(-{3,}|\\*{3,}|_{3,})$/.test(line.trim())){\n" | |
| 548 | + " flushPara();flushList();\n" | |
| 549 | + " box.appendChild(document.createElement('hr'));i++;continue;\n" | |
| 550 | + " }\n" | |
| 551 | + " para.push(line);i++;\n" | |
| 552 | + " }\n" | |
| 553 | + " flushPara();flushList();\n" | |
| 554 | + " host.appendChild(box);\n" | |
| 555 | + "}\n" | |
| 556 | + "\n" | |
| 557 | + "/* --- wiring ------------------------------------------------------- */\n" | |
| 558 | + "\n" | |
| 559 | + "document.getElementById('btnRefresh').onclick=function(){\n" | |
| 560 | + " if(curPath)openDir(curPath);else loadRoots();\n" | |
| 561 | + "};\n" | |
| 562 | + "document.getElementById('btnUp').onclick=function(){\n" | |
| 563 | + " if(curParent)openDir(curParent);\n" | |
| 564 | + " else if(curPath&&curRoot&&curPath!==curRoot)openDir(curRoot);\n" | |
| 565 | + " else toast('Already at the root');\n" | |
| 566 | + "};\n" | |
| 567 | + "document.getElementById('btnBack').onclick=function(){setView('browse');};\n" | |
| 568 | + "document.getElementById('btnTheme').onclick=function(){\n" | |
| 569 | + " if(window.sxApplyTheme)window.sxApplyTheme(window.sxTheme&&window.sxTheme()==='dark'?'light':'dark');\n" | |
| 570 | + "};\n" | |
| 571 | + "btnHidden.onclick=function(){\n" | |
| 572 | + " showHidden=!showHidden;\n" | |
| 573 | + " btnHidden.classList.toggle('on',showHidden);\n" | |
| 574 | + " btnHidden.title=showHidden?'Hide hidden files':'Show hidden files';\n" | |
| 575 | + " if(curPath)openDir(curPath);\n" | |
| 576 | + "};\n" | |
| 577 | + "btnDownload.onclick=function(){\n" | |
| 578 | + " if(!curFile)return;\n" | |
| 579 | + " var a=document.createElement('a');\n" | |
| 580 | + " a.href=url('raw','path='+encodeURIComponent(curFile)+'&download=1');\n" | |
| 581 | + " a.rel='noopener';\n" | |
| 582 | + " document.body.appendChild(a);a.click();document.body.removeChild(a);\n" | |
| 583 | + "};\n" | |
| 584 | + "\n" | |
| 585 | + "document.addEventListener('keydown',function(ev){\n" | |
| 586 | + " var tag=(ev.target&&ev.target.tagName||'').toLowerCase();\n" | |
| 587 | + " if(tag==='input'||tag==='textarea')return;\n" | |
| 588 | + " if(ev.key==='ArrowDown'||ev.key==='ArrowUp'){\n" | |
| 589 | + " if(!entries.length)return;\n" | |
| 590 | + " ev.preventDefault();\n" | |
| 591 | + " selIndex+=(ev.key==='ArrowDown'?1:-1);\n" | |
| 592 | + " if(selIndex<0)selIndex=0;\n" | |
| 593 | + " if(selIndex>=entries.length)selIndex=entries.length-1;\n" | |
| 594 | + " renderEntries();\n" | |
| 595 | + " }else if(ev.key==='Enter'){\n" | |
| 596 | + " if(selIndex>=0&&entries[selIndex]){ev.preventDefault();activate(entries[selIndex]);}\n" | |
| 597 | + " }else if(ev.key==='Backspace'){\n" | |
| 598 | + " if(curParent){ev.preventDefault();openDir(curParent);}\n" | |
| 599 | + " }else if(ev.key==='/'&&ev.ctrlKey===false){\n" | |
| 600 | + " return;\n" | |
| 601 | + " }\n" | |
| 602 | + "});\n" | |
| 603 | + "\n" | |
| 604 | + "function loadRoots(){\n" | |
| 605 | + " return api('roots').then(function(d){\n" | |
| 606 | + " roots=(d&&d.roots)||[];\n" | |
| 607 | + " renderRoots();\n" | |
| 608 | + " /* Wide screens open the first root straight away; a phone keeps the root\n" | |
| 609 | + " * list on screen, because a hidden sidebar there means an empty page. */\n" | |
| 610 | + " if(roots.length&&!curPath&&window.matchMedia('(min-width:821px)').matches){\n" | |
| 611 | + " openDir(roots[0].path);\n" | |
| 612 | + " }\n" | |
| 613 | + " }).catch(function(e){toast('Cannot list roots: '+e.message);});\n" | |
| 614 | + "}\n" | |
| 615 | + "\n" | |
| 616 | + "loadRoots();\n" | |
| 617 | + "})();\n" | |
| 618 | + "</script>\n" | |
| 619 | + "\002</body></html>\n" | |
| 620 | + ; | |
| 621 | + | |
| 622 | +#endif /* SX_FILES_UI_HTML_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..96f389a | ||
| --- /dev/null | ||
| +++ b/tests/e2e.py | ||
| @@ -0,0 +1,317 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""tests/e2e.py - viewport checks for the plugin_files browser. | |
| 3 | + | |
| 4 | +Serves the plugin through a small CGI-ish HTTP shim on a loopback port, opens | |
| 5 | +it with Playwright at 1440 / 1024 / 390 CSS pixels in both themes, and asserts: | |
| 6 | + | |
| 7 | + * no console error and no page error at any viewport | |
| 8 | + * scrollWidth <= innerWidth (no horizontal overflow) | |
| 9 | + * the root list renders, a directory opens, a text file previews with line | |
| 10 | + numbers, a markdown file renders, an image previews | |
| 11 | + * the rendered page really has a stylesheet and a working script | |
| 12 | + * screenshots land in docs/ for the README | |
| 13 | + | |
| 14 | +Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays | |
| 15 | +dependency-free. | |
| 16 | + | |
| 17 | + python3 tests/e2e.py # run if Playwright is available | |
| 18 | + python3 tests/e2e.py --strict # exit 2 when Playwright is missing | |
| 19 | +""" | |
| 20 | + | |
| 21 | +import argparse | |
| 22 | +import http.server | |
| 23 | +import os | |
| 24 | +import shutil | |
| 25 | +import socketserver | |
| 26 | +import subprocess | |
| 27 | +import sys | |
| 28 | +import tempfile | |
| 29 | +import threading | |
| 30 | +from urllib.parse import urlparse | |
| 31 | + | |
| 32 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| 33 | +BIN = os.path.join(ROOT, "plugin_files") | |
| 34 | +DOCS = os.path.join(ROOT, "docs") | |
| 35 | +VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] | |
| 36 | +THEMES = ["dark", "light"] | |
| 37 | + | |
| 38 | +PNG_1PX = ( | |
| 39 | + b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01" | |
| 40 | + b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00\x01" | |
| 41 | + b"\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82" | |
| 42 | +) | |
| 43 | + | |
| 44 | + | |
| 45 | +class Handler(http.server.BaseHTTPRequestHandler): | |
| 46 | + root_dir = "" | |
| 47 | + | |
| 48 | + def _run(self, method): | |
| 49 | + u = urlparse(self.path) | |
| 50 | + length = int(self.headers.get("Content-Length") or 0) | |
| 51 | + body = self.rfile.read(length) if length else b"" | |
| 52 | + env = dict(os.environ) | |
| 53 | + env["QUERY_STRING"] = u.query | |
| 54 | + env["REQUEST_METHOD"] = method | |
| 55 | + env["FILES_ALLOWED_ROOT"] = self.root_dir | |
| 56 | + env.pop("BOT_PASSWORD", None) | |
| 57 | + env["CONTENT_LENGTH"] = str(len(body)) | |
| 58 | + out = subprocess.run( | |
| 59 | + [BIN], input=body, capture_output=True, env=env, timeout=60 | |
| 60 | + ).stdout | |
| 61 | + sep = out.find(b"\r\n\r\n") | |
| 62 | + headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" | |
| 63 | + payload = out[sep + 4:] if sep >= 0 else out | |
| 64 | + status = 200 | |
| 65 | + ctype = "application/json; charset=utf-8" | |
| 66 | + for line in headers.splitlines(): | |
| 67 | + low = line.lower() | |
| 68 | + if low.startswith("content-type:"): | |
| 69 | + ctype = line.split(":", 1)[1].strip() | |
| 70 | + elif low.startswith("status:"): | |
| 71 | + try: | |
| 72 | + status = int(line.split(":", 1)[1].strip().split()[0]) | |
| 73 | + except (IndexError, ValueError): | |
| 74 | + status = 200 | |
| 75 | + self.send_response(status) | |
| 76 | + self.send_header("Content-Type", ctype) | |
| 77 | + self.send_header("Cache-Control", "no-store") | |
| 78 | + self.send_header("Content-Length", str(len(payload))) | |
| 79 | + self.end_headers() | |
| 80 | + self.wfile.write(payload) | |
| 81 | + | |
| 82 | + def do_GET(self): # noqa: N802 | |
| 83 | + self._run("GET") | |
| 84 | + | |
| 85 | + def do_POST(self): # noqa: N802 | |
| 86 | + self._run("POST") | |
| 87 | + | |
| 88 | + def log_message(self, *_a): | |
| 89 | + pass | |
| 90 | + | |
| 91 | + | |
| 92 | +def seed(root_dir): | |
| 93 | + os.makedirs(os.path.join(root_dir, "src"), exist_ok=True) | |
| 94 | + os.makedirs(os.path.join(root_dir, "docs"), exist_ok=True) | |
| 95 | + | |
| 96 | + with open(os.path.join(root_dir, "README.md"), "w", encoding="utf-8") as f: | |
| 97 | + f.write( | |
| 98 | + "# Local File Browser\n\n" | |
| 99 | + "A read-only browser for **SCORPIOX BOT** nodes.\n\n" | |
| 100 | + "- list directories inside the allowlisted roots\n" | |
| 101 | + "- preview text with line numbers\n" | |
| 102 | + "- view images and download files\n\n" | |
| 103 | + "> Nothing on disk can be modified by this plugin.\n\n" | |
| 104 | + "```\ncurl 'http://node:8150/plugin_files?action=roots'\n```\n" | |
| 105 | + ) | |
| 106 | + with open(os.path.join(root_dir, "src", "main.c"), "w", encoding="utf-8") as f: | |
| 107 | + f.write("#include <stdio.h>\n\nint main(void)\n{\n puts(\"hi\");\n return 0;\n}\n") | |
| 108 | + with open(os.path.join(root_dir, "notes.txt"), "w", encoding="utf-8") as f: | |
| 109 | + f.write("line one\nline two\nline three\n") | |
| 110 | + with open(os.path.join(root_dir, "blob.bin"), "wb") as f: | |
| 111 | + f.write(b"PK\x03\x04\x00\x00binary\x00data\x00") | |
| 112 | + with open(os.path.join(root_dir, "docs", "pixel.png"), "wb") as f: | |
| 113 | + f.write(PNG_1PX) | |
| 114 | + with open(os.path.join(root_dir, ".hiddenrc"), "w", encoding="utf-8") as f: | |
| 115 | + f.write("hidden\n") | |
| 116 | + | |
| 117 | + | |
| 118 | +def main(): | |
| 119 | + ap = argparse.ArgumentParser() | |
| 120 | + ap.add_argument("--strict", action="store_true", | |
| 121 | + help="exit 2 when Playwright is not installed") | |
| 122 | + args = ap.parse_args() | |
| 123 | + | |
| 124 | + try: | |
| 125 | + from playwright.sync_api import sync_playwright | |
| 126 | + except Exception: | |
| 127 | + print("playwright not installed - skipping e2e (offline suite is unaffected)") | |
| 128 | + return 2 if args.strict else 0 | |
| 129 | + | |
| 130 | + if not os.path.exists(BIN): | |
| 131 | + print("plugin_files not built - run make first") | |
| 132 | + return 1 | |
| 133 | + | |
| 134 | + work = tempfile.mkdtemp(prefix="files-e2e-") | |
| 135 | + root_dir = os.path.join(work, "root") | |
| 136 | + os.makedirs(root_dir, exist_ok=True) | |
| 137 | + seed(root_dir) | |
| 138 | + Handler.root_dir = root_dir | |
| 139 | + | |
| 140 | + httpd = socketserver.TCPServer(("127.0.0.1", 0), Handler) | |
| 141 | + port = httpd.server_address[1] | |
| 142 | + threading.Thread(target=httpd.serve_forever, daemon=True).start() | |
| 143 | + base = "http://127.0.0.1:%d/" % port | |
| 144 | + | |
| 145 | + os.makedirs(DOCS, exist_ok=True) | |
| 146 | + failures = [] | |
| 147 | + checks = 0 | |
| 148 | + | |
| 149 | + def ok(cond, label): | |
| 150 | + nonlocal checks | |
| 151 | + checks += 1 | |
| 152 | + if not cond: | |
| 153 | + failures.append(label) | |
| 154 | + print(" FAIL %s" % label) | |
| 155 | + | |
| 156 | + try: | |
| 157 | + with sync_playwright() as pw: | |
| 158 | + browser = pw.chromium.launch() | |
| 159 | + for w, h in VIEWPORTS: | |
| 160 | + for theme in THEMES: | |
| 161 | + page = browser.new_page(viewport={"width": w, "height": h}, | |
| 162 | + color_scheme=theme) | |
| 163 | + errors = [] | |
| 164 | + page.on("console", lambda m: errors.append(m.text) | |
| 165 | + if m.type == "error" else None) | |
| 166 | + page.on("pageerror", lambda e: errors.append(str(e))) | |
| 167 | + | |
| 168 | + page.goto(base + "?theme=%s" % theme, wait_until="load") | |
| 169 | + page.wait_for_selector(".root", timeout=8000) | |
| 170 | + | |
| 171 | + ok(page.locator(".root").count() >= 1, | |
| 172 | + "roots rendered @%dx%d %s" % (w, h, theme)) | |
| 173 | + # the seeded root is the last one, so pick it by its path | |
| 174 | + page.evaluate( | |
| 175 | + "ROOTPATH => Array.from(document.querySelectorAll('.root'))" | |
| 176 | + ".filter(function(b){return b.textContent.indexOf(ROOTPATH)>=0;})[0]" | |
| 177 | + ".click()", root_dir) | |
| 178 | + page.wait_for_function( | |
| 179 | + "document.querySelectorAll('.row').length >= 4", | |
| 180 | + timeout=8000) | |
| 181 | + page.wait_for_selector(".row", timeout=8000) | |
| 182 | + | |
| 183 | + ok(page.locator(".row").count() >= 4, | |
| 184 | + "entries listed @%dx%d %s" % (w, h, theme)) | |
| 185 | + ok(page.locator(".row.dir").count() >= 2, | |
| 186 | + "directories first @%dx%d %s" % (w, h, theme)) | |
| 187 | + ok(".hiddenrc" not in page.inner_text("#entries"), | |
| 188 | + "hidden files hidden by default @%dx%d %s" % (w, h, theme)) | |
| 189 | + | |
| 190 | + sw = page.evaluate("document.documentElement.scrollWidth") | |
| 191 | + iw = page.evaluate("window.innerWidth") | |
| 192 | + ok(sw <= iw + 1, "no h-overflow (%d<=%d) @%dx%d %s" | |
| 193 | + % (sw, iw, w, h, theme)) | |
| 194 | + | |
| 195 | + # a real stylesheet, not plain text in the page | |
| 196 | + ok(page.evaluate( | |
| 197 | + "document.styleSheets.length>0 && " | |
| 198 | + "Array.from(document.styleSheets)" | |
| 199 | + ".reduce(function(n,s){return n+s.cssRules.length;},0)>80"), | |
| 200 | + "stylesheet parsed @%dx%d %s" % (w, h, theme)) | |
| 201 | + | |
| 202 | + # open the markdown file -> rendered headings and bold | |
| 203 | + page.evaluate( | |
| 204 | + "Array.from(document.querySelectorAll('.row'))" | |
| 205 | + ".filter(function(b){return b.textContent.indexOf('README.md')>=0;})[0]" | |
| 206 | + ".click()") | |
| 207 | + page.wait_for_selector(".md h1", timeout=8000) | |
| 208 | + html = page.inner_html(".md") | |
| 209 | + ok("<h1>Local File Browser</h1>" in html, | |
| 210 | + "markdown h1 rendered @%dx%d %s" % (w, h, theme)) | |
| 211 | + ok("<strong>SCORPIOX BOT</strong>" in html, | |
| 212 | + "markdown bold rendered @%dx%d %s" % (w, h, theme)) | |
| 213 | + ok("<script>" not in html, | |
| 214 | + "no raw script tag in preview @%dx%d %s" % (w, h, theme)) | |
| 215 | + | |
| 216 | + # text preview has line numbers | |
| 217 | + page.evaluate( | |
| 218 | + "Array.from(document.querySelectorAll('.row'))" | |
| 219 | + ".filter(function(b){return b.textContent.indexOf('notes.txt')>=0;})[0]" | |
| 220 | + ".click()") | |
| 221 | + page.wait_for_selector(".codetxt", timeout=8000) | |
| 222 | + ok(page.inner_text(".codetxt .ln").startswith("1"), | |
| 223 | + "line numbers start at 1 @%dx%d %s" % (w, h, theme)) | |
| 224 | + ok("line three" in page.inner_text(".codetxt .tx"), | |
| 225 | + "text body rendered @%dx%d %s" % (w, h, theme)) | |
| 226 | + | |
| 227 | + # binary file degrades to a note, never to mojibake | |
| 228 | + page.evaluate( | |
| 229 | + "Array.from(document.querySelectorAll('.row'))" | |
| 230 | + ".filter(function(b){return b.textContent.indexOf('blob.bin')>=0;})[0]" | |
| 231 | + ".click()") | |
| 232 | + page.wait_for_selector(".note", timeout=8000) | |
| 233 | + ok("Binary file" in page.inner_text(".note"), | |
| 234 | + "binary file explained @%dx%d %s" % (w, h, theme)) | |
| 235 | + | |
| 236 | + # image opens in an <img> | |
| 237 | + page.evaluate( | |
| 238 | + "Array.from(document.querySelectorAll('.row.dir'))" | |
| 239 | + ".filter(function(b){return b.textContent.indexOf('docs')>=0;})[0]" | |
| 240 | + ".click()") | |
| 241 | + page.wait_for_function( | |
| 242 | + "Array.from(document.querySelectorAll('.row'))" | |
| 243 | + ".some(function(b){return b.textContent.indexOf('pixel.png')>=0;})", | |
| 244 | + timeout=8000) | |
| 245 | + page.evaluate( | |
| 246 | + "Array.from(document.querySelectorAll('.row'))" | |
| 247 | + ".filter(function(b){return b.textContent.indexOf('pixel.png')>=0;})[0]" | |
| 248 | + ".click()") | |
| 249 | + page.wait_for_selector(".imgwrap img", timeout=8000) | |
| 250 | + ok(page.evaluate( | |
| 251 | + "document.querySelector('.imgwrap img').naturalWidth > 0"), | |
| 252 | + "image decoded @%dx%d %s" % (w, h, theme)) | |
| 253 | + | |
| 254 | + # hidden toggle reveals the dotfile | |
| 255 | + # the sidebar is hidden on a phone while a preview is open, | |
| 256 | + # so drive the toggle the way a user would after Back | |
| 257 | + page.evaluate("document.getElementById('btnHidden').click()") | |
| 258 | + page.wait_for_function( | |
| 259 | + "Array.from(document.querySelectorAll('.row'))" | |
| 260 | + ".some(function(b){return b.textContent.indexOf('pixel.png')>=0;})", | |
| 261 | + timeout=8000) | |
| 262 | + ok(page.evaluate( | |
| 263 | + "document.documentElement.scrollWidth <= window.innerWidth + 1"), | |
| 264 | + "no h-overflow after toggle @%dx%d %s" % (w, h, theme)) | |
| 265 | + | |
| 266 | + # put the toggle back so the README shot is the default view | |
| 267 | + page.evaluate("document.getElementById('btnHidden').click()") | |
| 268 | + page.wait_for_function( | |
| 269 | + "!Array.from(document.querySelectorAll('.row'))" | |
| 270 | + ".some(function(b){return b.textContent.indexOf('.hiddenrc')>=0;})", | |
| 271 | + timeout=8000) | |
| 272 | + | |
| 273 | + # screenshot of the browser with a markdown preview open | |
| 274 | + page.evaluate( | |
| 275 | + "Array.from(document.querySelectorAll('.crumb'))[0].click()") | |
| 276 | + page.wait_for_function( | |
| 277 | + "Array.from(document.querySelectorAll('.row'))" | |
| 278 | + ".some(function(b){return b.textContent.indexOf('README.md')>=0;})", | |
| 279 | + timeout=8000) | |
| 280 | + page.evaluate( | |
| 281 | + "Array.from(document.querySelectorAll('.row'))" | |
| 282 | + ".filter(function(b){return b.textContent.indexOf('README.md')>=0;})[0]" | |
| 283 | + ".click()") | |
| 284 | + page.wait_for_selector(".md h1", timeout=8000) | |
| 285 | + page.evaluate("document.querySelector('.prev-body').scrollTop = 0") | |
| 286 | + shot = os.path.join(DOCS, "ui-%d-%s.png" % (w, theme)) | |
| 287 | + page.screenshot(path=shot) | |
| 288 | + | |
| 289 | + ok(len(errors) == 0, "no console/page errors @%dx%d %s (%s)" | |
| 290 | + % (w, h, theme, "; ".join(errors[:2]))) | |
| 291 | + page.close() | |
| 292 | + | |
| 293 | + # embed mode hides the theme toggle | |
| 294 | + page = browser.new_page(viewport={"width": 1024, "height": 768}) | |
| 295 | + page.goto(base + "?embed=1&theme=dark", wait_until="load") | |
| 296 | + page.wait_for_selector(".root", timeout=8000) | |
| 297 | + ok(not page.is_visible("#btnTheme"), "embed hides the theme toggle") | |
| 298 | + ok(page.evaluate( | |
| 299 | + "document.documentElement.classList.contains('embedded')"), | |
| 300 | + "embed marks html.embedded") | |
| 301 | + page.close() | |
| 302 | + browser.close() | |
| 303 | + finally: | |
| 304 | + httpd.shutdown() | |
| 305 | + shutil.rmtree(work, ignore_errors=True) | |
| 306 | + | |
| 307 | + print("\n%d checks, %d failure(s)" % (checks, len(failures))) | |
| 308 | + if failures: | |
| 309 | + for f in failures: | |
| 310 | + print(" - %s" % f) | |
| 311 | + return 1 | |
| 312 | + print("RESULT: OK") | |
| 313 | + return 0 | |
| 314 | + | |
| 315 | + | |
| 316 | +if __name__ == "__main__": | |
| 317 | + sys.exit(main()) |
| 1 | 1 | new file mode 100755 |
| index 0000000..d8a02de | ||
| --- /dev/null | ||
| +++ b/tests/run.sh | ||
| @@ -0,0 +1,490 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/run.sh - offline checks for plugin_files across all 3 modes. | |
| 3 | +# | |
| 4 | +# Every check runs against ./plugin_files with FILES_ALLOWED_ROOT pointing at a | |
| 5 | +# throwaway fixture tree, so the suite never reads anything real. It proves the | |
| 6 | +# public contract end to end: --meta, node auth on every action, each action's | |
| 7 | +# JSON shape, the read-only promise, the 1 MiB preview cap, binary detection, | |
| 8 | +# raw streaming checksums, directory ordering, hidden-file toggle, traversal | |
| 9 | +# and symlink negatives -> 403/400, the generated UI (no CDN, no <script src=>), | |
| 10 | +# the MinGW PE header when present, a _FORTIFY_SOURCE=2 build that must run | |
| 11 | +# clean, and a full-history audit for secrets and LAN addresses. | |
| 12 | +# | |
| 13 | +# Exit code 0 = everything passed. | |
| 14 | + | |
| 15 | +set -u | |
| 16 | + | |
| 17 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | |
| 18 | +cd "$ROOT" || exit 1 | |
| 19 | + | |
| 20 | +BIN=./plugin_files | |
| 21 | +PASS=0 | |
| 22 | +FAIL=0 | |
| 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 400)" | |
| 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 | + | |
| 46 | +# strip CGI headers if present, drop CRs, keep the payload | |
| 47 | +body() { | |
| 48 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | |
| 49 | + BEGIN { inhdr = 0 } | |
| 50 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Content-Security-Policy|Content-Disposition):/) { inhdr = 1; next } | |
| 51 | + inhdr && $0 == "" { inhdr = 0; next } | |
| 52 | + inhdr { next } | |
| 53 | + { print } | |
| 54 | + ' | |
| 55 | +} | |
| 56 | + | |
| 57 | +json_ok() { # json_ok <desc> <json> [python-expression] | |
| 58 | + expr=${3:-True} | |
| 59 | + printf '%s' "$2" > "$WORK/j.json" | |
| 60 | + if python3 -c "import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if ($expr) else 1)" "$WORK/j.json" 2>/dev/null; then | |
| 61 | + pass "$1" | |
| 62 | + else | |
| 63 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | |
| 64 | + fi | |
| 65 | +} | |
| 66 | + | |
| 67 | +api() { body "$(QUERY_STRING="$1" $BIN)"; } | |
| 68 | + | |
| 69 | +# raw output including CGI headers, for the Status: assertions | |
| 70 | +apiraw() { QUERY_STRING="$1" $BIN; } | |
| 71 | + | |
| 72 | +status_of() { printf '%s' "$1" | tr -d '\r' | sed -n 's/^Status: \([0-9][0-9][0-9]\).*/\1/p' | head -1; } | |
| 73 | + | |
| 74 | +# ---------------------------------------------------------------- build | |
| 75 | +section "build" | |
| 76 | +if [ ! -x "$BIN" ]; then | |
| 77 | + echo " building native binary..." | |
| 78 | + cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o "$BIN" src/plugin_files.c \ | |
| 79 | + || { echo " build failed"; exit 1; } | |
| 80 | + pass "native build" | |
| 81 | +else | |
| 82 | + pass "native binary present" | |
| 83 | +fi | |
| 84 | + | |
| 85 | +WORK=$(mktemp -d "${TMPDIR:-/tmp}/files-test.XXXXXX") || exit 1 | |
| 86 | +trap 'rm -rf "$WORK"' INT TERM EXIT | |
| 87 | +FX="$WORK/root" | |
| 88 | +mkdir -p "$FX/sub/deep/deeper" "$FX/emptydir" "$FX/.hiddendir" "$FX/pics" || exit 1 | |
| 89 | + | |
| 90 | +printf 'hello world\nsecond line\n' > "$FX/a.txt" | |
| 91 | +printf '# Title\n\nSome **bold** text and a [link](https://example.com).\n\n- one\n- two\n' > "$FX/readme.md" | |
| 92 | +printf 'abc\000def\000ghi' > "$FX/bin.dat" | |
| 93 | +printf 'hidden content\n' > "$FX/.hidden" | |
| 94 | +: > "$FX/empty.txt" | |
| 95 | +printf 'deep\n' > "$FX/sub/deep/deeper/leaf.txt" | |
| 96 | +printf 'in sub\n' > "$FX/sub/inner.txt" | |
| 97 | +python3 -c "open('$FX/big.txt','w').write('x'*(2*1024*1024))" | |
| 98 | +python3 -c " | |
| 99 | +import struct,zlib | |
| 100 | +def chunk(t,d): | |
| 101 | + return struct.pack('>I',len(d))+t+d+struct.pack('>I',zlib.crc32(t+d)&0xffffffff) | |
| 102 | +raw=b'\x00\xff\x00\xff' | |
| 103 | +idat=zlib.compress(raw) | |
| 104 | +png=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',2,1,8,2,0,0,0))+chunk(b'IDAT',idat)+chunk(b'IEND',b'') | |
| 105 | +open('$FX/pics/px.png','wb').write(png) | |
| 106 | +" | |
| 107 | +ln -s /etc "$FX/etclink" | |
| 108 | +ln -s "$FX/a.txt" "$FX/goodlink" | |
| 109 | + | |
| 110 | +export FILES_ALLOWED_ROOT="$FX" | |
| 111 | +unset BOT_PASSWORD | |
| 112 | + | |
| 113 | +# ---------------------------------------------------------------- meta | |
| 114 | +section "--meta / --version" | |
| 115 | +M=$($BIN --meta) | |
| 116 | +check "--meta emits name" '"name":"files"' "$M" | |
| 117 | +check "--meta desc" '"desc":"File browser"' "$M" | |
| 118 | +json_ok "--meta is valid JSON" "$M" "d['name']=='files' and d['desc']=='File browser'" | |
| 119 | +M2=$(SX_PLUGIN_META=1 $BIN) | |
| 120 | +check "SX_PLUGIN_META also emits meta" '"name":"files"' "$M2" | |
| 121 | +V=$($BIN --version) | |
| 122 | +check "--version" 'plugin_files 1.0.0' "$V" | |
| 123 | + | |
| 124 | +# ---------------------------------------------------------------- auth | |
| 125 | +section "node auth" | |
| 126 | +export BOT_PASSWORD=testpw | |
| 127 | +R=$(apiraw "action=roots") | |
| 128 | +check "no password -> 401" '401' "$(status_of "$R")" | |
| 129 | +R=$(apiraw "action=ls&path=$FX") | |
| 130 | +check "ls without password -> 401" '401' "$(status_of "$R")" | |
| 131 | +R=$(apiraw "action=read&path=$FX/a.txt") | |
| 132 | +check "read without password -> 401" '401' "$(status_of "$R")" | |
| 133 | +R=$(apiraw "action=raw&path=$FX/a.txt") | |
| 134 | +check "raw without password -> 401" '401' "$(status_of "$R")" | |
| 135 | +R=$(apiraw "") | |
| 136 | +check "HTML page without password -> 401" '401' "$(status_of "$R")" | |
| 137 | +M=$($BIN --meta) | |
| 138 | +check "--meta stays unauthenticated" '"name":"files"' "$M" | |
| 139 | +R=$(HTTP_X_BOT_PASSWORD=testpw apiraw "action=roots") | |
| 140 | +check "X-Bot-Password accepted" '"ok":true' "$(body "$R")" | |
| 141 | +R=$(HTTP_AUTHORIZATION="Bearer testpw" apiraw "action=roots") | |
| 142 | +check "Bearer token accepted" '"ok":true' "$(body "$R")" | |
| 143 | +R=$(apiraw "action=roots&pwd=testpw") | |
| 144 | +check "?pwd= accepted" '"ok":true' "$(body "$R")" | |
| 145 | +R=$(apiraw "action=roots&pwd=wrong") | |
| 146 | +check "wrong ?pwd= -> 401" '401' "$(status_of "$R")" | |
| 147 | +unset BOT_PASSWORD | |
| 148 | + | |
| 149 | +# ---------------------------------------------------------------- roots | |
| 150 | +section "?action=roots" | |
| 151 | +R=$(api "action=roots") | |
| 152 | +json_ok "roots ok" "$R" "d['ok'] is True" | |
| 153 | +json_ok "roots has a list" "$R" "isinstance(d['roots'],list) and len(d['roots'])>=1" | |
| 154 | +json_ok "fixture root is present" "$R" "any(r['path']=='$FX' for r in d['roots'])" | |
| 155 | +json_ok "each root has name+path" "$R" "all('name' in r and 'path' in r for r in d['roots'])" | |
| 156 | +json_ok "count matches list length" "$R" "d['count']==len(d['roots'])" | |
| 157 | +json_ok "no /proc root" "$R" "all(r['path']!='/proc' for r in d['roots'])" | |
| 158 | +json_ok "no /sys root" "$R" "all(r['path']!='/sys' for r in d['roots'])" | |
| 159 | +json_ok "no /dev root" "$R" "all(r['path']!='/dev' for r in d['roots'])" | |
| 160 | +R=$(api "format=json") | |
| 161 | +json_ok "format=json falls back to roots" "$R" "d['ok'] is True and 'roots' in d" | |
| 162 | + | |
| 163 | +# ---------------------------------------------------------------- ls | |
| 164 | +section "?action=ls" | |
| 165 | +R=$(api "action=ls&path=$FX") | |
| 166 | +json_ok "ls ok" "$R" "d['ok'] is True" | |
| 167 | +json_ok "ls path echoed" "$R" "d['path']=='$FX'" | |
| 168 | +json_ok "ls root is the fixture" "$R" "d['root']=='$FX'" | |
| 169 | +json_ok "ls parent is null at a root" "$R" "d['parent'] is None" | |
| 170 | +json_ok "ls count matches entries" "$R" "d['count']==len(d['entries'])" | |
| 171 | +json_ok "ls not truncated" "$R" "d['truncated'] is False" | |
| 172 | +json_ok "hidden off by default" "$R" "d['hidden']==0" | |
| 173 | +json_ok "no dotfiles by default" "$R" "not any(e['name'].startswith('.') for e in d['entries'])" | |
| 174 | +json_ok "dirs sort before files" "$R" "[e['type'] for e in d['entries']]==sorted([e['type'] for e in d['entries']], key=lambda t:(t!='dir'))" | |
| 175 | +json_ok "names sorted dirs-first" "$R" "(lambda d:[e['name'] for e in d['entries'] if e['type']=='dir']==sorted([e['name'] for e in d['entries'] if e['type']=='dir'],key=str.lower) and [e['name'] for e in d['entries'] if e['type']!='dir']==sorted([e['name'] for e in d['entries'] if e['type']!='dir'],key=str.lower))(d)" | |
| 176 | +json_ok "entry has size/mtime/mode" "$R" "all('size' in e and 'mtime' in e and 'mode' in e for e in d['entries'])" | |
| 177 | +json_ok "dir entry flagged" "$R" "any(e['name']=='sub' and e['type']=='dir' for e in d['entries'])" | |
| 178 | +json_ok "file entry flagged" "$R" "any(e['name']=='a.txt' and e['type']=='file' for e in d['entries'])" | |
| 179 | +json_ok "a.txt size is 24" "$R" "any(e['name']=='a.txt' and e['size']==24 for e in d['entries'])" | |
| 180 | +json_ok "mtime is ISO-8601" "$R" "all(len(e['mtime'])==20 and e['mtime'].endswith('Z') for e in d['entries'] if e['mtime'])" | |
| 181 | +json_ok "mode is octal string" "$R" "all(e['mode'].isdigit() and len(e['mode'])==4 for e in d['entries'])" | |
| 182 | +json_ok "empty file listed with size 0" "$R" "any(e['name']=='empty.txt' and e['size']==0 for e in d['entries'])" | |
| 183 | + | |
| 184 | +R=$(api "action=ls&path=$FX&hidden=1") | |
| 185 | +json_ok "hidden=1 flags hidden" "$R" "d['hidden']==1" | |
| 186 | +json_ok "hidden=1 shows dotfile" "$R" "any(e['name']=='.hidden' for e in d['entries'])" | |
| 187 | +json_ok "hidden=1 shows dotdir" "$R" "any(e['name']=='.hiddendir' and e['type']=='dir' for e in d['entries'])" | |
| 188 | + | |
| 189 | +R=$(api "action=ls&path=$FX&hidden=true") | |
| 190 | +json_ok "hidden=true also works" "$R" "any(e['name']=='.hidden' for e in d['entries'])" | |
| 191 | + | |
| 192 | +R=$(api "action=ls&path=$FX/sub") | |
| 193 | +json_ok "nested parent is computed" "$R" "d['parent']=='$FX'" | |
| 194 | +json_ok "nested root is still the fixture" "$R" "d['root']=='$FX'" | |
| 195 | +json_ok "nested lists its own children" "$R" "any(e['name']=='inner.txt' for e in d['entries'])" | |
| 196 | + | |
| 197 | +R=$(api "action=ls&path=$FX/emptydir") | |
| 198 | +json_ok "empty dir answers count 0" "$R" "d['count']==0 and d['entries']==[]" | |
| 199 | + | |
| 200 | +R=$(api "action=ls&path=$FX/goodlink") | |
| 201 | +json_ok "symlink inside the root is browsable as a file" "$R" "'ok' in d" | |
| 202 | + | |
| 203 | +R=$(api "action=ls") | |
| 204 | +json_ok "ls without path defaults to the first root" "$R" "d['ok'] is True and d['path'].startswith('/')" | |
| 205 | + | |
| 206 | +# ---------------------------------------------------------------- read | |
| 207 | +section "?action=read" | |
| 208 | +R=$(api "action=read&path=$FX/a.txt") | |
| 209 | +json_ok "read ok" "$R" "d['ok'] is True" | |
| 210 | +json_ok "read text" "$R" "d['text']=='hello world\\nsecond line\\n'" | |
| 211 | +json_ok "read binary false" "$R" "d['binary'] is False" | |
| 212 | +json_ok "read truncated false" "$R" "d['truncated'] is False" | |
| 213 | +json_ok "read bytes_read matches file" "$R" "d['bytes_read']==24" | |
| 214 | +json_ok "read name echoed" "$R" "d['name']=='a.txt'" | |
| 215 | +json_ok "read size echoed" "$R" "d['size']==24" | |
| 216 | +json_ok "read mode present" "$R" "len(d['mode'])==4" | |
| 217 | +json_ok "read has no text key for binary" "$R" "True" | |
| 218 | + | |
| 219 | +R=$(api "action=read&path=$FX/bin.dat") | |
| 220 | +json_ok "binary detected by NUL" "$R" "d['binary'] is True" | |
| 221 | +json_ok "binary omits text" "$R" "'text' not in d" | |
| 222 | +json_ok "binary still reports size" "$R" "d['size']==11" | |
| 223 | + | |
| 224 | +R=$(api "action=read&path=$FX/big.txt") | |
| 225 | +json_ok "big file truncated" "$R" "d['truncated'] is True" | |
| 226 | +json_ok "big file capped at 1 MiB" "$R" "d['bytes_read']==1048576" | |
| 227 | +json_ok "big file still reports real size" "$R" "d['size']==2097152" | |
| 228 | + | |
| 229 | +R=$(api "action=read&path=$FX/empty.txt") | |
| 230 | +json_ok "empty file reads as empty text" "$R" "d['text']=='' and d['bytes_read']==0" | |
| 231 | + | |
| 232 | +R=$(apiraw "action=read&path=$FX") | |
| 233 | +check "read a directory -> 400" '400' "$(status_of "$R")" | |
| 234 | + | |
| 235 | +# ---------------------------------------------------------------- raw | |
| 236 | +section "?action=raw" | |
| 237 | +RAWR=$(apiraw "action=raw&path=$FX/a.txt") | |
| 238 | +HDRS=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p') | |
| 239 | +check "raw content-type text/plain" 'Content-Type: text/plain; charset=utf-8' "$HDRS" | |
| 240 | +check "raw attachment for text" 'Content-Disposition: attachment' "$HDRS" | |
| 241 | +check "raw has no manual Content-Length" '0' "$(printf '%s' "$HDRS" | grep -c 'Content-Length')" | |
| 242 | +check "raw nosniff" 'X-Content-Type-Options: nosniff' "$HDRS" | |
| 243 | +check "raw sameorigin" 'X-Frame-Options: SAMEORIGIN' "$HDRS" | |
| 244 | + | |
| 245 | +# payload after the blank line must be byte-identical to the file | |
| 246 | +python3 -c " | |
| 247 | +import subprocess,sys,os,hashlib | |
| 248 | +env=dict(os.environ); env['QUERY_STRING']='action=raw&path=$FX/a.txt' | |
| 249 | +out=subprocess.run(['$BIN'],capture_output=True,env=env).stdout | |
| 250 | +sep=out.find(b'\r\n\r\n') | |
| 251 | +payload=out[sep+4:] | |
| 252 | +want=open('$FX/a.txt','rb').read() | |
| 253 | +sys.exit(0 if payload==want else 1) | |
| 254 | +" && pass "raw payload equals the file byte-for-byte" || fail "raw payload equals the file byte-for-byte" | |
| 255 | + | |
| 256 | +python3 -c " | |
| 257 | +import subprocess,sys,os,hashlib | |
| 258 | +env=dict(os.environ); env['QUERY_STRING']='action=raw&path=$FX/pics/px.png' | |
| 259 | +out=subprocess.run(['$BIN'],capture_output=True,env=env).stdout | |
| 260 | +sep=out.find(b'\r\n\r\n') | |
| 261 | +hdr=out[:sep].decode() | |
| 262 | +payload=out[sep+4:] | |
| 263 | +want=open('$FX/pics/px.png','rb').read() | |
| 264 | +ok = payload==want and 'image/png' in hdr and 'inline' in hdr | |
| 265 | +sys.exit(0 if ok else 1) | |
| 266 | +" && pass "raw png is image/png, inline, byte-identical" || fail "raw png is image/png, inline, byte-identical" | |
| 267 | + | |
| 268 | +RAWR=$(apiraw "action=raw&path=$FX/pics/px.png&download=1") | |
| 269 | +HDRS=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p') | |
| 270 | +check "download=1 forces attachment on an image" 'Content-Disposition: attachment' "$HDRS" | |
| 271 | + | |
| 272 | +RAWR=$(apiraw "action=raw&path=$FX/readme.md") | |
| 273 | +HDRS=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p') | |
| 274 | +check "markdown served as text/plain (never text/html)" 'Content-Type: text/plain; charset=utf-8' "$HDRS" | |
| 275 | +HDRS_HTML=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p' | grep -c 'text/html') | |
| 276 | +check "no text/html on raw markdown" '0' "$HDRS_HTML" | |
| 277 | + | |
| 278 | +printf 'PK\003\004xxxx' > "$FX/thing.zip" | |
| 279 | +RAWR=$(apiraw "action=raw&path=$FX/thing.zip") | |
| 280 | +HDRS=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p') | |
| 281 | +check "unknown type is octet-stream" 'application/octet-stream' "$HDRS" | |
| 282 | +check "unknown type is attachment" 'Content-Disposition: attachment' "$HDRS" | |
| 283 | + | |
| 284 | +printf '<html><body><script>alert(1)</script></body></html>' > "$FX/evil.html" | |
| 285 | +RAWR=$(apiraw "action=raw&path=$FX/evil.html") | |
| 286 | +HDRS=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p') | |
| 287 | +check "html file is served as plain text" 'text/plain' "$HDRS" | |
| 288 | + | |
| 289 | +RAWR=$(apiraw "action=raw&path=$FX/big.txt") | |
| 290 | +PLEN=$(printf '%s' "$RAWR" | wc -c | tr -d ' ') | |
| 291 | +if [ "$PLEN" -gt 2000000 ]; then pass "raw streams a 2 MB file whole"; else fail "raw streams a 2 MB file whole ($PLEN)"; fi | |
| 292 | + | |
| 293 | +# ---------------------------------------------------------------- security | |
| 294 | +section "security: traversal, symlink escape, denied roots" | |
| 295 | +R=$(apiraw "action=ls&path=$FX/../..") | |
| 296 | +check ".. in a path -> 400" '400' "$(status_of "$R")" | |
| 297 | +R=$(apiraw "action=ls&path=$FX/sub/../../etc") | |
| 298 | +check "nested .. -> 400" '400' "$(status_of "$R")" | |
| 299 | +R=$(apiraw "action=ls&path=../../etc") | |
| 300 | +check "relative .. path -> 400" '400' "$(status_of "$R")" | |
| 301 | +R=$(apiraw "action=ls&path=$FX/%2e%2e/%2e%2e/etc") | |
| 302 | +check "percent-encoded .. -> 400" '400' "$(status_of "$R")" | |
| 303 | +R=$(apiraw "action=read&path=/etc/passwd") | |
| 304 | +check "read outside every root -> 403" '403' "$(status_of "$R")" | |
| 305 | +R=$(apiraw "action=ls&path=/etc") | |
| 306 | +check "ls outside every root -> 403" '403' "$(status_of "$R")" | |
| 307 | +R=$(apiraw "action=read&path=$FX/etclink/passwd") | |
| 308 | +check "symlink pointing outside -> 403" '403' "$(status_of "$R")" | |
| 309 | +R=$(apiraw "action=ls&path=$FX/etclink") | |
| 310 | +check "ls a symlink that escapes -> 403" '403' "$(status_of "$R")" | |
| 311 | +R=$(apiraw "action=raw&path=$FX/etclink/hostname") | |
| 312 | +check "raw through an escaping symlink -> 403" '403' "$(status_of "$R")" | |
| 313 | +R=$(apiraw "action=ls&path=/proc") | |
| 314 | +check "/proc refused" '403' "$(status_of "$R")" | |
| 315 | +R=$(apiraw "action=ls&path=/proc/self") | |
| 316 | +check "/proc/self refused" '403' "$(status_of "$R")" | |
| 317 | +R=$(apiraw "action=ls&path=/sys") | |
| 318 | +check "/sys refused" '403' "$(status_of "$R")" | |
| 319 | +R=$(apiraw "action=ls&path=/dev") | |
| 320 | +check "/dev refused" '403' "$(status_of "$R")" | |
| 321 | +R=$(apiraw "action=ls&path=") | |
| 322 | +check "empty path falls back to a root, not the filesystem" '"ok":true' "$(body "$R")" | |
| 323 | +R=$(apiraw "action=ls&path=$FX/missing") | |
| 324 | +check "missing path -> 404" '404' "$(status_of "$R")" | |
| 325 | +R=$(apiraw "action=read&path=$FX/missing.txt") | |
| 326 | +check "missing file -> 404" '404' "$(status_of "$R")" | |
| 327 | +R=$(apiraw "action=nope") | |
| 328 | +check "unknown action -> 400" '400' "$(status_of "$R")" | |
| 329 | +R=$(apiraw "action=ls&path=$FX/a.txt") | |
| 330 | +check "ls a regular file -> 403 (cannot list)" '403' "$(status_of "$R")" | |
| 331 | + | |
| 332 | +# read-only by construction: no write-ish action exists | |
| 333 | +for a in save write delete rename mkdir touch chmod upload put; do | |
| 334 | + R=$(apiraw "action=$a&path=$FX/a.txt") | |
| 335 | + check_not "no '$a' action" '"ok":true' "$(body "$R")" | |
| 336 | +done | |
| 337 | +SUM_BEFORE=$(python3 -c " | |
| 338 | +import hashlib,os | |
| 339 | +h=hashlib.sha256() | |
| 340 | +for root,dirs,files in os.walk('$FX'): | |
| 341 | + for f in sorted(files): | |
| 342 | + p=os.path.join(root,f) | |
| 343 | + try: h.update(open(p,'rb').read()) | |
| 344 | + except OSError: pass | |
| 345 | +print(h.hexdigest()) | |
| 346 | +") | |
| 347 | +api "action=read&path=$FX/a.txt" > /dev/null | |
| 348 | +apiraw "action=raw&path=$FX/a.txt" > /dev/null | |
| 349 | +api "action=ls&path=$FX" > /dev/null | |
| 350 | +SUM_AFTER=$(python3 -c " | |
| 351 | +import hashlib,os | |
| 352 | +h=hashlib.sha256() | |
| 353 | +for root,dirs,files in os.walk('$FX'): | |
| 354 | + for f in sorted(files): | |
| 355 | + p=os.path.join(root,f) | |
| 356 | + try: h.update(open(p,'rb').read()) | |
| 357 | + except OSError: pass | |
| 358 | +print(h.hexdigest()) | |
| 359 | +") | |
| 360 | +check "fixture unchanged after every action" "$SUM_BEFORE" "$SUM_AFTER" | |
| 361 | + | |
| 362 | +# the source must contain no write syscall at all | |
| 363 | +SRC=src/plugin_files.c | |
| 364 | +W=$(grep -nE 'fopen\([^)]*"[wa]' "$SRC" | wc -l | tr -d ' ') | |
| 365 | +check "no fopen for writing in the source" '0' "$W" | |
| 366 | +for fn in fprintf fputc fwrite_never_used; do :; done | |
| 367 | +check_not "no remove()" 'remove(' "$(grep -o 'remove(' "$SRC" | head -1)" | |
| 368 | +check_not "no rmdir()" 'rmdir(' "$(grep -o 'rmdir(' "$SRC" | head -1)" | |
| 369 | +check_not "no mkdir()" 'mkdir(' "$(grep -o 'mkdir(' "$SRC" | head -1)" | |
| 370 | +check_not "no rename()" 'rename(' "$(grep -o 'rename(' "$SRC" | head -1)" | |
| 371 | +check_not "no chmod()" 'chmod(' "$(grep -o 'chmod(' "$SRC" | head -1)" | |
| 372 | +check_not "no popen()" 'popen(' "$(grep -o 'popen(' "$SRC" | head -1)" | |
| 373 | +check_not "no system()" 'system(' "$(grep -o 'system(' "$SRC" | head -1)" | |
| 374 | + | |
| 375 | +# ---------------------------------------------------------------- HTML UI | |
| 376 | +section "HTML UI" | |
| 377 | +P=$(apiraw "") | |
| 378 | +check "page content-type" 'Content-Type: text/html; charset=utf-8' "$(printf '%s' "$P" | tr -d '\r' | head -1)" | |
| 379 | +check "page has DOCTYPE" '<!DOCTYPE html>' "$P" | |
| 380 | +check "page title" '<title>files</title>' "$P" | |
| 381 | +check "page has no <script src=" '0' "$(printf '%s' "$P" | grep -c '<script src=')" | |
| 382 | +check "page has no CDN link" '0' "$(printf '%s' "$P" | grep -ciE '(cdn\.|unpkg|jsdelivr|cdnjs)')" | |
| 383 | +check "page has no http:// asset" '0' "$(printf '%s' "$P" | grep -c 'src="http')" | |
| 384 | +check "page embeds the theme tokens" '--bg-card:#1c1c1e' "$P" | |
| 385 | +check "page embeds the theme handoff" 'sx-theme-request' "$P" | |
| 386 | +check "page embeds the prepaint" 'data-theme' "$P" | |
| 387 | +check "page marks embed mode" "classList.add('embedded')" "$P" | |
| 388 | +check "page uses <style>" 'font-family:var(--font)' "$P" | |
| 389 | +check "page has an inline <script>" '<script>' "$P" | |
| 390 | +check "page CSP is tight" "default-src 'none'" "$P" | |
| 391 | +check "page CSP allows no remote script" "script-src 'unsafe-inline'" "$P" | |
| 392 | +check "page has the fs route constant" "'/plugin_files'" "$P" | |
| 393 | +check "page has the hub route branch" "'/plugins?plugin='" "$P" | |
| 394 | +check "page has no emoji" '0' "$(printf '%s' "$P" | python3 -c 'import sys,re; t=sys.stdin.read(); print(len(re.findall(r"[\U0001F300-\U0001FAFF]",t)))')" | |
| 395 | +check "page uses inline SVG" '<svg viewBox=' "$P" | |
| 396 | +PEMB=$(apiraw "embed=1") | |
| 397 | +check "embed=1 still serves the page" '<title>files</title>' "$PEMB" | |
| 398 | +PNO=$(apiraw "?theme=light") | |
| 399 | +check "theme param passes through" '<title>files</title>' "$PNO" | |
| 400 | + | |
| 401 | +# ---------------------------------------------------------------- generated header | |
| 402 | +section "generated UI header" | |
| 403 | +if [ -f src/ui_html.h ] && [ -f src/ui.html ]; then | |
| 404 | + if python3 tools/gen_ui.py --check >/dev/null 2>&1; then | |
| 405 | + pass "src/ui_html.h matches src/ui.html" | |
| 406 | + else | |
| 407 | + fail "src/ui_html.h is stale - run tools/gen_ui.py" | |
| 408 | + fi | |
| 409 | +else | |
| 410 | + fail "missing src/ui.html or src/ui_html.h" | |
| 411 | +fi | |
| 412 | + | |
| 413 | +# ---------------------------------------------------------------- plugin.json | |
| 414 | +section "plugin.json sidecar" | |
| 415 | +if [ -f plugin.json ]; then | |
| 416 | + pass "plugin.json present" | |
| 417 | + J=$(cat plugin.json) | |
| 418 | + json_ok "plugin.json is valid JSON" "$J" \ | |
| 419 | + "d['slug']=='files' and d['id']=='plugin_files' and d['category']=='devtools' and d['license']=='MIT'" | |
| 420 | + json_ok "plugin.json declares fs_read" "$J" "'fs_read' in d['capabilities']" | |
| 421 | + json_ok "plugin.json has a trust notice" "$J" "len(d['trust_notice'])>40" | |
| 422 | + json_ok "plugin.json title is a title" "$J" "len(d['title'])>6" | |
| 423 | +else | |
| 424 | + fail "plugin.json missing (catalog would be blank)" | |
| 425 | +fi | |
| 426 | + | |
| 427 | +# ---------------------------------------------------------------- fortify | |
| 428 | +section "_FORTIFY_SOURCE=2 build" | |
| 429 | +if cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src \ | |
| 430 | + -D_FORTIFY_SOURCE=2 -o "$WORK/plugin_files.fort" src/plugin_files.c 2>"$WORK/fort.log"; then | |
| 431 | + pass "fortify build compiles" | |
| 432 | + OUT=$(QUERY_STRING="action=ls&path=$FX" "$WORK/plugin_files.fort" | tail -n +5) | |
| 433 | + check "fortify build lists entries" '"entries"' "$OUT" | |
| 434 | + OUT=$(QUERY_STRING="action=read&path=$FX/big.txt" "$WORK/plugin_files.fort") | |
| 435 | + check "fortify build caps the 1 MiB read" '"bytes_read":1048576' "$OUT" | |
| 436 | + OUT=$(QUERY_STRING="action=ls&path=$FX/etclink" "$WORK/plugin_files.fort") | |
| 437 | + check "fortify build still refuses the symlink escape" '403' "$(status_of "$OUT")" | |
| 438 | + check "fortify build printed no warning" '0' "$(wc -c < "$WORK/fort.log" | tr -d ' ')" | |
| 439 | +else | |
| 440 | + fail "fortify build failed: $(head -3 "$WORK/fort.log")" | |
| 441 | +fi | |
| 442 | + | |
| 443 | +# ---------------------------------------------------------------- PE header | |
| 444 | +section "MinGW PE (when present)" | |
| 445 | +if [ -f plugin_files.exe ]; then | |
| 446 | + MAGIC=$(od -An -tx1 -N2 plugin_files.exe | tr -d ' \n') | |
| 447 | + check "plugin_files.exe starts with the MZ magic" '4d5a' "$MAGIC" | |
| 448 | + SZ=$(wc -c < plugin_files.exe | tr -d ' ') | |
| 449 | + if [ "$SZ" -gt 20000 ]; then pass "plugin_files.exe looks like a real binary ($SZ bytes)"; else fail "plugin_files.exe suspiciously small ($SZ bytes)"; fi | |
| 450 | +else | |
| 451 | + echo " skip (plugin_files.exe not built here)" | |
| 452 | +fi | |
| 453 | + | |
| 454 | +# ---------------------------------------------------------------- history audit | |
| 455 | +section "full-history audit" | |
| 456 | +if [ -d .git ]; then | |
| 457 | + ALL="$WORK/all-history.txt" | |
| 458 | + git log -p --all > "$ALL" 2>/dev/null || : > "$ALL" | |
| 459 | + | |
| 460 | + audit() { # audit <label> <regex> | |
| 461 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | |
| 462 | + if [ -n "$H" ]; then | |
| 463 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | |
| 464 | + else | |
| 465 | + pass "history clean: $1" | |
| 466 | + fi | |
| 467 | + } | |
| 468 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 469 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 470 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 471 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 472 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 473 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 474 | + PK="pico""bot"; WT=".work""trees" | |
| 475 | + audit "internal fleet path" "/codebases/${PK}|${WT}" | |
| 476 | + audit "run token assignment" 'RUNNER_'"PASS=" | |
| 477 | +else | |
| 478 | + echo " skip history audit (not a git checkout)" | |
| 479 | +fi | |
| 480 | + | |
| 481 | +# ---------------------------------------------------------------- summary | |
| 482 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | |
| 483 | +printf ' passed: %d\n' "$PASS" | |
| 484 | +printf ' failed: %d\n' "$FAIL" | |
| 485 | +if [ "$FAIL" -ne 0 ]; then | |
| 486 | + printf ' %sRESULT: FAIL%s\n' "$C_BAD" "$C_0" | |
| 487 | + exit 1 | |
| 488 | +fi | |
| 489 | +printf ' %sRESULT: OK%s\n' "$C_OK" "$C_0" | |
| 490 | +exit 0 |
| 1 | 1 | new file mode 100755 |
| index 0000000..cc1c0bd | ||
| --- /dev/null | ||
| +++ b/tools/gen_ui.py | ||
| @@ -0,0 +1,105 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""tools/gen_ui.py - compile src/ui.html into src/ui_html.h. | |
| 3 | + | |
| 4 | +The page lives in one readable file (src/ui.html) so it can be diffed and | |
| 5 | +reviewed like any other source. This script turns it into a single C string | |
| 6 | +constant with two control-character placeholders: | |
| 7 | + | |
| 8 | + 0x01 -> the bot theme prepaint script + <style> + theme tokens | |
| 9 | + 0x02 -> the bot theme handoff script (just before </body>) | |
| 10 | + | |
| 11 | +main() splits the constant on those bytes and emits the macros from | |
| 12 | +src/bot_theme_plugin.h in their place, so the theme can never drift out of | |
| 13 | +sync with the rest of the bot. | |
| 14 | + | |
| 15 | + python3 tools/gen_ui.py # write src/ui_html.h | |
| 16 | + python3 tools/gen_ui.py --check # exit 1 when the header is stale | |
| 17 | +""" | |
| 18 | + | |
| 19 | +import os | |
| 20 | +import sys | |
| 21 | + | |
| 22 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| 23 | +SRC = os.path.join(ROOT, "src", "ui.html") | |
| 24 | +OUT = os.path.join(ROOT, "src", "ui_html.h") | |
| 25 | + | |
| 26 | +TOKENS = "<!--TOKENS-->" | |
| 27 | +MARK_TOKENS = "\u0001" | |
| 28 | +MARK_HANDOFF = "\u0002" | |
| 29 | + | |
| 30 | + | |
| 31 | +def c_literal(text): | |
| 32 | + """Escape text for a C string literal, one line per source line.""" | |
| 33 | + out = [] | |
| 34 | + for line in text.splitlines(True): | |
| 35 | + piece = [] | |
| 36 | + for ch in line: | |
| 37 | + if ch == "\\": | |
| 38 | + piece.append("\\\\") | |
| 39 | + elif ch == '"': | |
| 40 | + piece.append('\\"') | |
| 41 | + elif ch == "\n": | |
| 42 | + piece.append("\\n") | |
| 43 | + elif ch == "\r": | |
| 44 | + piece.append("\\r") | |
| 45 | + elif ch == "\t": | |
| 46 | + piece.append("\\t") | |
| 47 | + elif ch == MARK_TOKENS: | |
| 48 | + piece.append("\\001") | |
| 49 | + elif ch == MARK_HANDOFF: | |
| 50 | + piece.append("\\002") | |
| 51 | + elif ord(ch) < 0x20: | |
| 52 | + piece.append("\\%03o" % ord(ch)) | |
| 53 | + else: | |
| 54 | + piece.append(ch) | |
| 55 | + out.append(' "%s"\n' % "".join(piece)) | |
| 56 | + return "".join(out) | |
| 57 | + | |
| 58 | + | |
| 59 | +def render(): | |
| 60 | + with open(SRC, "r", encoding="utf-8") as f: | |
| 61 | + html = f.read() | |
| 62 | + | |
| 63 | + if TOKENS not in html: | |
| 64 | + raise SystemExit("src/ui.html has no %s placeholder" % TOKENS) | |
| 65 | + html = html.replace(TOKENS, MARK_TOKENS) | |
| 66 | + | |
| 67 | + # Handoff script goes right before the closing body tag. | |
| 68 | + if "</body>" not in html: | |
| 69 | + raise SystemExit("src/ui.html has no </body>") | |
| 70 | + html = html.replace("</body>", MARK_HANDOFF + "</body>", 1) | |
| 71 | + | |
| 72 | + header = ( | |
| 73 | + "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n" | |
| 74 | + "#ifndef SX_FILES_UI_HTML_H\n" | |
| 75 | + "#define SX_FILES_UI_HTML_H\n" | |
| 76 | + "\n" | |
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | |
| 78 | + "\n" | |
| 79 | + "#endif /* SX_FILES_UI_HTML_H */\n" | |
| 80 | + ) | |
| 81 | + return header | |
| 82 | + | |
| 83 | + | |
| 84 | +def main(): | |
| 85 | + header = render() | |
| 86 | + check = "--check" in sys.argv[1:] | |
| 87 | + if check: | |
| 88 | + try: | |
| 89 | + with open(OUT, "r", encoding="utf-8") as f: | |
| 90 | + cur = f.read() | |
| 91 | + except OSError: | |
| 92 | + cur = "" | |
| 93 | + if cur != header: | |
| 94 | + sys.stderr.write("src/ui_html.h is stale - run tools/gen_ui.py\n") | |
| 95 | + return 1 | |
| 96 | + print("src/ui_html.h is up to date") | |
| 97 | + return 0 | |
| 98 | + with open(OUT, "w", encoding="utf-8") as f: | |
| 99 | + f.write(header) | |
| 100 | + print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header))) | |
| 101 | + return 0 | |
| 102 | + | |
| 103 | + | |
| 104 | +if __name__ == "__main__": | |
| 105 | + sys.exit(main()) | |
| 0 | 106 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..c3339a0 | index 0000000..c3339a0 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,17 @@ | @@ -0,0 +1,17 @@ | ||
| 1 | +# build artifacts | ||
| 2 | +plugin_files | ||
| 3 | +plugin_files.exe | ||
| 4 | +plugin_files.musl | ||
| 5 | +plugin_files.arm64 | ||
| 6 | +plugin_files.macos-arm64 | ||
| 7 | +plugin_files.macos-x86_64 | ||
| 8 | +bin/ | ||
| 9 | + | ||
| 10 | +# test scratch | ||
| 11 | +*.tmp | ||
| 12 | +fixture/ | ||
| 13 | +.playwright/ | ||
| 14 | + | ||
| 15 | +# python tooling | ||
| 16 | +__pycache__/ | ||
| 17 | +*.pyc |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..ef80120 | index 0000000..ef80120 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/LICENSE | +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | ||
| 2 | + | ||
| 3 | +Copyright (c) 2026 SCORPIOX INC | ||
| 4 | + | ||
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 6 | +of this software and associated documentation files (the "Software"), to deal | ||
| 7 | +in the Software without restriction, including without limitation the rights | ||
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 9 | +copies of the Software, and to permit persons to whom the Software is | ||
| 10 | +furnished to do so, subject to the following conditions: | ||
| 11 | + | ||
| 12 | +The above copyright notice and this permission notice shall be included in all | ||
| 13 | +copies or substantial portions of the Software. | ||
| 14 | + | ||
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 21 | +SOFTWARE. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..7c714db | index 0000000..7c714db | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,75 @@ | @@ -0,0 +1,75 @@ | ||
| 1 | +# plugin_files - SCORPIOX BOT open-source read-only file browser for your node | ||
| 2 | +# | ||
| 3 | +# Targets: | ||
| 4 | +# make native build -> ./plugin_files | ||
| 5 | +# make musl static musl x86_64 -> ./plugin_files.musl | ||
| 6 | +# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_files.arm64 | ||
| 7 | +# make win64 MinGW-w64 static -> ./plugin_files.exe | ||
| 8 | +# make macos Apple clang -> ./plugin_files (run this on macOS) | ||
| 9 | +# make ui regenerate src/ui_html.h from src/ui.html | ||
| 10 | +# make test build + run tests/run.sh | ||
| 11 | +# make e2e build + run tests/e2e.py (Playwright) | ||
| 12 | +# make clean | ||
| 13 | + | ||
| 14 | +CC ?= cc | ||
| 15 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src | ||
| 16 | +MUSL_CC ?= musl-gcc | ||
| 17 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | ||
| 18 | +ARM_CC ?= aarch64-linux-gnu-gcc | ||
| 19 | +ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | ||
| 20 | +WIN_CC ?= x86_64-w64-mingw32-gcc | ||
| 21 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | ||
| 22 | +SRC := src/plugin_files.c | ||
| 23 | +UI_SRC := src/ui.html | ||
| 24 | +UI_HDR := src/ui_html.h | ||
| 25 | +BIN := plugin_files | ||
| 26 | +EXE := plugin_files.exe | ||
| 27 | + | ||
| 28 | +.PHONY: all native musl arm64 win64 macos ui test e2e clean help | ||
| 29 | + | ||
| 30 | +all: native | ||
| 31 | + | ||
| 32 | +$(UI_HDR): $(UI_SRC) tools/gen_ui.py | ||
| 33 | + @echo "==> regenerating $(UI_HDR)" | ||
| 34 | + python3 tools/gen_ui.py | ||
| 35 | + | ||
| 36 | +ui: $(UI_HDR) | ||
| 37 | + | ||
| 38 | +native: $(BIN) | ||
| 39 | + | ||
| 40 | +$(BIN): $(SRC) $(UI_HDR) | ||
| 41 | + @echo "==> native build ($(CC))" | ||
| 42 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | ||
| 43 | + | ||
| 44 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | ||
| 45 | +musl: $(SRC) $(UI_HDR) | ||
| 46 | + @echo "==> static musl build ($(MUSL_CC))" | ||
| 47 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC) | ||
| 48 | + | ||
| 49 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | ||
| 50 | +arm64: $(SRC) $(UI_HDR) | ||
| 51 | + @echo "==> static arm64 build ($(ARM_CC))" | ||
| 52 | + $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC) | ||
| 53 | + | ||
| 54 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | ||
| 55 | +win64: $(SRC) $(UI_HDR) | ||
| 56 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | ||
| 57 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) | ||
| 58 | + | ||
| 59 | +# Apple clang build (run this on macOS) | ||
| 60 | +macos: $(SRC) $(UI_HDR) | ||
| 61 | + @echo "==> Apple clang build" | ||
| 62 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | ||
| 63 | + | ||
| 64 | +test: native | ||
| 65 | + @sh tests/run.sh | ||
| 66 | + | ||
| 67 | +e2e: native | ||
| 68 | + @python3 tests/e2e.py | ||
| 69 | + | ||
| 70 | +clean: | ||
| 71 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64 | ||
| 72 | + rm -rf bin | ||
| 73 | + | ||
| 74 | +help: | ||
| 75 | + @echo "make | make musl | make arm64 | make win64 | make macos | make ui | make test | make e2e | make clean" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..77d6c84 | index 0000000..77d6c84 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/README.md | +++ b/README.md | ||
| @@ -0,0 +1,118 @@ | @@ -0,0 +1,118 @@ | ||
| 1 | +# scorpiox-bot-plugin-files | ||
| 2 | + | ||
| 3 | +**`plugin_files`** — a read-only local file browser for a **SCORPIOX BOT** node. | ||
| 4 | + | ||
| 5 | +List directories inside an allowlist of roots, preview text and markdown with | ||
| 6 | +line numbers, view images, and download files. It opens every file read-only | ||
| 7 | +and contains no create, write, rename, chmod or delete code path at all. | ||
| 8 | + | ||
| 9 | +One clean-room C99 binary, zero dependencies, no CDN, no network requests. | ||
| 10 | + | ||
| 11 | +``` | ||
| 12 | +files / File browser category: devtools MIT | ||
| 13 | +``` | ||
| 14 | + | ||
| 15 | +## What it does | ||
| 16 | + | ||
| 17 | +| Route | Behaviour | | ||
| 18 | +|---|---| | ||
| 19 | +| `--meta` (or `SX_PLUGIN_META=1`) | `{"name":"files","desc":"File browser"}` — unauthenticated so discovery works | | ||
| 20 | +| `?action=roots` | the allowlisted roots with a display name each | | ||
| 21 | +| `?action=ls&path=<abs>[&hidden=1]` | up to 5000 entries, directories first then names, each with `type` / `size` / `mtime` / `mode`; reports `count`, `truncated`, `parent`, `root` | | ||
| 22 | +| `?action=read&path=<abs>` | text preview up to 1 MiB, `binary:true` when a NUL byte appears in the first 8 KiB | | ||
| 23 | +| `?action=raw&path=<abs>[&download=1]` | streams the file with a guessed `Content-Type`, capped at 64 MiB | | ||
| 24 | +| `GET` (no action) | the browser page, `?embed=1` aware | | ||
| 25 | + | ||
| 26 | +All routes except `--meta` sit behind `require_node_auth()`: `X-Bot-Password`, | ||
| 27 | +`Authorization: Bearer <pwd>`, or `?pwd=`. With `BOT_PASSWORD` unset the check | ||
| 28 | +is a no-op, which is what local development wants. | ||
| 29 | + | ||
| 30 | +## Read-only, and enforced | ||
| 31 | + | ||
| 32 | +Consumption of a plugin is native code on your machine, so the interesting | ||
| 33 | +question is not "does it say read-only" but "can it do anything else". | ||
| 34 | + | ||
| 35 | +* The source contains no `fopen` in write mode, no `remove`, `rmdir`, `mkdir`, | ||
| 36 | + `rename`, `chmod`, `popen` or `system`. `tests/run.sh` greps for all of them. | ||
| 37 | +* Every path is canonicalised **before** it is used: `realpath()` on POSIX and | ||
| 38 | + `GetFullPathNameA` + `GetFinalPathNameByHandleA` on Windows. | ||
| 39 | +* The canonical path is then prefix-checked against the allowlisted roots, so a | ||
| 40 | + symlink that points out of a root is refused with `403` — the check happens | ||
| 41 | + on the real target, not on the name that was typed. | ||
| 42 | +* Any `..` in a browse path is rejected outright; `%2e%2e` decodes before the | ||
| 43 | + check, so the encoding does not help. | ||
| 44 | +* `/proc`, `/sys` and `/dev` are refused even when they sit under an allowed | ||
| 45 | + root. | ||
| 46 | +* A `GET` of a `.html` file on disk is served as `text/plain`. This route shares | ||
| 47 | + an origin with the node API, so rendering a local page as `text/html` would | ||
| 48 | + hand every HTML file on the node the ability to call the plugin API with the | ||
| 49 | + user's password. Images keep their real type because `<img>` only decodes | ||
| 50 | + them. | ||
| 51 | +* The response never sets `Content-Length`; `scorpiox-server` owns framing. | ||
| 52 | + | ||
| 53 | +## Allowlisted roots | ||
| 54 | + | ||
| 55 | +| Platform | Defaults | | ||
| 56 | +|---|---| | ||
| 57 | +| Linux | `/workspace`, `/codebases`, `$HOME` | | ||
| 58 | +| macOS | `/workspace`, `/codebases`, `$HOME` | | ||
| 59 | +| Windows | `%USERPROFILE%`, `D:\codebases` | | ||
| 60 | + | ||
| 61 | +`$FILES_ALLOWED_ROOT` adds one more, or several separated by `:` on POSIX and | ||
| 62 | +`;` on Windows. Directories that do not exist are skipped silently, so the | ||
| 63 | +list is honest on every machine. | ||
| 64 | + | ||
| 65 | +## Build | ||
| 66 | + | ||
| 67 | +```sh | ||
| 68 | +make # native -> ./plugin_files | ||
| 69 | +make musl # static musl x86_64 (Alpine, Debian, Arch, Omarchy) | ||
| 70 | +make arm64 # static aarch64 (Raspberry Pi 5, ARM64 servers) | ||
| 71 | +make win64 # static PE via x86_64-w64-mingw32-gcc | ||
| 72 | +make macos # Apple clang (run on macOS) | ||
| 73 | +make test # build + tests/run.sh (offline, 150 checks) | ||
| 74 | +make e2e # build + tests/e2e.py (Playwright, 6 viewport/theme pairs) | ||
| 75 | +make clean | ||
| 76 | +``` | ||
| 77 | + | ||
| 78 | +On Windows, `powershell -ExecutionPolicy Bypass -File build.ps1` produces | ||
| 79 | +`plugin_files.exe`. | ||
| 80 | + | ||
| 81 | +The page lives in `src/ui.html` and is compiled into `src/ui_html.h` by | ||
| 82 | +`tools/gen_ui.py`, which splices the bot theme macros in at two control-byte | ||
| 83 | +placeholders. `make ui` regenerates it; `python3 tools/gen_ui.py --check` | ||
| 84 | +fails when the header is stale. | ||
| 85 | + | ||
| 86 | +## Install on a node | ||
| 87 | + | ||
| 88 | +```sh | ||
| 89 | +# prebuilt, from the market | ||
| 90 | +curl -s -H "X-Bot-Password: $BOT_PASSWORD" \ | ||
| 91 | + 'http://127.0.0.1:8150/plugin_manage?action=install&slug=files&mode=prebuilt' | ||
| 92 | + | ||
| 93 | +# or from source, agent-style | ||
| 94 | +git clone https://plugingit.scorpiox.net/scorpiox-bot-plugin-files.git | ||
| 95 | +cd scorpiox-bot-plugin-files && make | ||
| 96 | +mkdir -p ~/.scorpiox/plugins && cp plugin_files ~/.scorpiox/plugins/ | ||
| 97 | +``` | ||
| 98 | + | ||
| 99 | +Zero server restart: `scorpiox-server` resolves `plugin_*` executables live on | ||
| 100 | +every request. The plugin then appears in `GET /plugins`, in the Hub `⋯` menu, | ||
| 101 | +on session cards, and in the Chat floating window. | ||
| 102 | + | ||
| 103 | +## Layout | ||
| 104 | + | ||
| 105 | +``` | ||
| 106 | +src/plugin_files.c the whole plugin (~1.0k lines) | ||
| 107 | +src/bot_theme_plugin.h bot theme tokens, prepaint + handoff (trimmed copy) | ||
| 108 | +src/ui.html the page, readable and diffable | ||
| 109 | +src/ui_html.h generated from ui.html - do not edit | ||
| 110 | +tools/gen_ui.py ui.html -> ui_html.h | ||
| 111 | +tests/run.sh 150 offline assertions, no network | ||
| 112 | +tests/e2e.py Playwright at 1440/1024/390, dark + light | ||
| 113 | +plugin.json catalog sidecar (slug, id, title, capabilities, trust) | ||
| 114 | +``` | ||
| 115 | + | ||
| 116 | +## Licence | ||
| 117 | + | ||
| 118 | +MIT. Copyright (c) 2026 SCORPIOX INC. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..f040e24 | index 0000000..f040e24 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/build.ps1 | +++ b/build.ps1 | ||
| @@ -0,0 +1,51 @@ | @@ -0,0 +1,51 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_files | ||
| 2 | +# | ||
| 3 | +# Usage (from the repo root, PowerShell): | ||
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | ||
| 5 | +# | ||
| 6 | +# Produces .\plugin_files.exe (static PE, runs on any Windows 10/11 x64 node). | ||
| 7 | +# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin). | ||
| 8 | + | ||
| 9 | +$ErrorActionPreference = "Stop" | ||
| 10 | +$ScriptDir = $PSScriptRoot | ||
| 11 | +Push-Location $ScriptDir | ||
| 12 | +try { | ||
| 13 | + $Src = Join-Path $ScriptDir "src\plugin_files.c" | ||
| 14 | + $Out = Join-Path $ScriptDir "plugin_files.exe" | ||
| 15 | + $Cc = "x86_64-w64-mingw32-gcc" | ||
| 16 | + | ||
| 17 | + if (-not (Test-Path $Src)) { throw "source not found: $Src" } | ||
| 18 | + | ||
| 19 | + # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present. | ||
| 20 | + if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) { | ||
| 21 | + if (Test-Path "C:\gcc16\bin\gcc.exe") { | ||
| 22 | + $Cc = "C:\gcc16\bin\gcc.exe" | ||
| 23 | + } elseif (Get-Command gcc -ErrorAction SilentlyContinue) { | ||
| 24 | + $Cc = "gcc" | ||
| 25 | + } else { | ||
| 26 | + throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)" | ||
| 27 | + } | ||
| 28 | + } | ||
| 29 | + | ||
| 30 | + # Regenerate the page header so the binary always matches src/ui.html. | ||
| 31 | + if (Get-Command python -ErrorAction SilentlyContinue) { | ||
| 32 | + python tools\gen_ui.py | ||
| 33 | + } | ||
| 34 | + | ||
| 35 | + Write-Host "==> building plugin_files.exe with $Cc" | ||
| 36 | + & $Cc -O2 -std=c99 -Wall -Wextra -I src -static -o $Out $Src | ||
| 37 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | ||
| 38 | + | ||
| 39 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | ||
| 40 | + | ||
| 41 | + # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not. | ||
| 42 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | ||
| 43 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | ||
| 44 | + throw "output is not a PE executable (missing MZ header)" | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + Write-Host "==> ok: $Out ($($bytes.Length) bytes)" | ||
| 48 | + Write-Host " smoke test: .\plugin_files.exe --meta" | ||
| 49 | +} finally { | ||
| 50 | + Pop-Location | ||
| 51 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..57fe210 | index 0000000..57fe210 |

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

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..3814d6b | index 0000000..3814d6b |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..3df2266 | index 0000000..3df2266 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..5014b45 | index 0000000..5014b45 |

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

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..726bfd8 | index 0000000..726bfd8 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/plugin.json | +++ b/plugin.json | ||
| @@ -0,0 +1,15 @@ | @@ -0,0 +1,15 @@ | ||
| 1 | +{ | ||
| 2 | + "slug": "files", | ||
| 3 | + "id": "plugin_files", | ||
| 4 | + "title": "Local File Browser", | ||
| 5 | + "summary": "Zero-dependency read-only file browser for your node: list directories, preview text and markdown with line numbers, view images and download files, all inside an allowlist of roots. Every path is canonicalised and prefix-checked after symlink resolution, so traversal, symlink escapes and /proc, /sys, /dev are refused. It opens files O_RDONLY and never creates, writes, renames or deletes anything.", | ||
| 6 | + "category": "devtools", | ||
| 7 | + "license": "MIT", | ||
| 8 | + "capabilities": [ | ||
| 9 | + "fs_read", | ||
| 10 | + "no_network" | ||
| 11 | + ], | ||
| 12 | + "trust_notice": "Executes native C code on your node. Strictly read-only: it opens files read-only inside an allowlist of roots (/workspace, /codebases, $HOME, $FILES_ALLOWED_ROOT; on Windows %USERPROFILE%, D:\\codebases, $FILES_ALLOWED_ROOT) and refuses anything outside them after symlink resolution. It writes nothing, makes zero outbound network requests, and never lists /proc, /sys or /dev.", | ||
| 13 | + "author": "SCORPIOX INC", | ||
| 14 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-files" | ||
| 15 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..f308b20 | index 0000000..f308b20 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/release-dist.sh | +++ b/release-dist.sh | ||
| @@ -0,0 +1,38 @@ | @@ -0,0 +1,38 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# release-dist.sh - thin wrapper around the shared multi-arch release tool. | ||
| 3 | +# | ||
| 4 | +# The real cross-target build + dist publish lives in scorpiox-cli-botplugin | ||
| 5 | +# (it owns the musl / aarch64 / MinGW / macOS toolchains and the plugingit | ||
| 6 | +# mirror). This script only exists so the repo can be released the same way | ||
| 7 | +# every other oss plugin is, and so a stale release-dist keeps failing loudly | ||
| 8 | +# instead of shipping a 3-target manifest that says "release complete". | ||
| 9 | +# | ||
| 10 | +# ./release-dist.sh # build + publish version from plugin.json / 1.0.0 | ||
| 11 | +# VERSION=1.0.1 ./release-dist.sh # explicit version | ||
| 12 | +# | ||
| 13 | +# Run it on the build host that has musl-gcc, aarch64-linux-gnu-gcc, | ||
| 14 | +# x86_64-w64-mingw32-gcc and ssh access to the macOS builder. | ||
| 15 | + | ||
| 16 | +set -eu | ||
| 17 | + | ||
| 18 | +SLUG=files | ||
| 19 | +VERSION="${VERSION:-1.0.0}" | ||
| 20 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | ||
| 21 | + | ||
| 22 | +ROOT=$(cd "$(dirname "$0")" && pwd) | ||
| 23 | + | ||
| 24 | +if ! command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | ||
| 25 | + echo "scorpiox-cli-botplugin not found on PATH" >&2 | ||
| 26 | + exit 1 | ||
| 27 | +fi | ||
| 28 | + | ||
| 29 | +echo "==> publish $SLUG $VERSION" | ||
| 30 | +scorpiox-cli-botplugin publish "$ROOT" \ | ||
| 31 | + --slug "$SLUG" \ | ||
| 32 | + --version "$VERSION" \ | ||
| 33 | + --macos-host "${MACOS_HOST:-yongchen@macos-builder}" \ | ||
| 34 | + --json | ||
| 35 | + | ||
| 36 | +echo "==> verify target count in the published manifest" | ||
| 37 | +scorpiox-cli-botplugin reindex --json >/dev/null 2>&1 || true | ||
| 38 | +echo "check dist/bot-plugins/$SLUG/$VERSION/manifest.json has 6 targets before calling it done" |
| 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..af2a48d | index 0000000..af2a48d | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_files.c | +++ b/src/plugin_files.c | ||
| @@ -0,0 +1,1184 @@ | @@ -0,0 +1,1184 @@ | ||
| 1 | +/* | ||
| 2 | + * plugin_files - SCORPIOX BOT open-source read-only file browser for your node | ||
| 3 | + * | ||
| 4 | + * A single clean-room C99 binary that serves THREE modes: | ||
| 5 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata | ||
| 6 | + * 2. ?action=... / ?format=json -> JSON node API | ||
| 7 | + * 3. GET (default) -> browse + preview page | ||
| 8 | + * | ||
| 9 | + * Repo: https://plugingit.scorpiox.net/scorpiox-bot-plugin-files.git | ||
| 10 | + * | ||
| 11 | + * READ-ONLY BY CONSTRUCTION. There is no create, no write, no delete, no | ||
| 12 | + * rename, no chmod anywhere in this file: the plugin exists to look at files, | ||
| 13 | + * never to change them. | ||
| 14 | + * | ||
| 15 | + * Every path that arrives in a request is canonicalised on the real | ||
| 16 | + * filesystem (realpath() on POSIX, GetFullPathNameA + GetFinalPathNameByHandleA | ||
| 17 | + * on Windows) and then prefix-checked against the allowlisted roots AFTER | ||
| 18 | + * symlink resolution. `..`, embedded NUL bytes, backslash tricks and symlinks | ||
| 19 | + * that point outside the roots are all rejected with 403. /proc, /sys and /dev | ||
| 20 | + * are refused even when they sit under an allowed root (/proc lives under /). | ||
| 21 | + * | ||
| 22 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | ||
| 23 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | ||
| 24 | + * scorpiox-server on the node. | ||
| 25 | + * | ||
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 27 | + */ | ||
| 28 | + | ||
| 29 | +/* Must come before every include on Windows: MinGW defaults to 0x502 | ||
| 30 | + * (Server 2003), which hides GetFinalPathNameByHandleA and friends. */ | ||
| 31 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | ||
| 32 | +# define _WIN32_WINNT 0x0601 | ||
| 33 | +#endif | ||
| 34 | + | ||
| 35 | +#if !defined(_WIN32) | ||
| 36 | +# define _POSIX_C_SOURCE 200809L | ||
| 37 | +# define _DEFAULT_SOURCE 1 | ||
| 38 | +# if defined(__APPLE__) | ||
| 39 | +# define _DARWIN_C_SOURCE 1 | ||
| 40 | +# endif | ||
| 41 | +#endif | ||
| 42 | + | ||
| 43 | +#include <stdio.h> | ||
| 44 | +#include <stdlib.h> | ||
| 45 | +#include <string.h> | ||
| 46 | +#include <stdarg.h> | ||
| 47 | +#include <ctype.h> | ||
| 48 | +#include <errno.h> | ||
| 49 | +#include <time.h> | ||
| 50 | + | ||
| 51 | +#if defined(_WIN32) | ||
| 52 | +# define WIN32_LEAN_AND_MEAN | ||
| 53 | +# include <windows.h> | ||
| 54 | +# include <io.h> | ||
| 55 | +# define SEP '\\' | ||
| 56 | +#else | ||
| 57 | +# include <unistd.h> | ||
| 58 | +# include <sys/stat.h> | ||
| 59 | +# include <sys/types.h> | ||
| 60 | +# include <dirent.h> | ||
| 61 | +# define SEP '/' | ||
| 62 | +#endif | ||
| 63 | + | ||
| 64 | +#include "bot_theme_plugin.h" | ||
| 65 | +#include "ui_html.h" | ||
| 66 | + | ||
| 67 | +#define PLUGIN_SLUG "files" | ||
| 68 | +#define PLUGIN_ID "plugin_files" | ||
| 69 | +#define PLUGIN_VER "1.0.0" | ||
| 70 | +#define PLUGIN_NAME "files" | ||
| 71 | +#define PLUGIN_DESC "File browser" | ||
| 72 | + | ||
| 73 | +#define PATH_SZ 4096 | ||
| 74 | +#define NAME_SZ 512 | ||
| 75 | +#define MAX_ROOTS 8 | ||
| 76 | +#define MAX_ENTRIES 5000 | ||
| 77 | +#define TEXT_CAP (1024 * 1024) /* 1 MiB text preview */ | ||
| 78 | +#define RAW_CAP ((long long)64 * 1024 * 1024) /* 64 MiB raw stream */ | ||
| 79 | +#define BIN_PROBE 8192 | ||
| 80 | +#define IO_CHUNK 65536 | ||
| 81 | + | ||
| 82 | +typedef struct { | ||
| 83 | + char name[NAME_SZ]; | ||
| 84 | + int is_dir; | ||
| 85 | + int is_link; | ||
| 86 | + long long size; | ||
| 87 | + long long mtime; | ||
| 88 | + unsigned mode; | ||
| 89 | +} ent_t; | ||
| 90 | + | ||
| 91 | +static char g_roots[MAX_ROOTS][PATH_SZ]; | ||
| 92 | +static int g_root_count; | ||
| 93 | + | ||
| 94 | +/* ------------------------------------------------------------------ */ | ||
| 95 | +/* Growable byte buffer */ | ||
| 96 | +/* ------------------------------------------------------------------ */ | ||
| 97 | + | ||
| 98 | +typedef struct { | ||
| 99 | + char *p; | ||
| 100 | + size_t n; | ||
| 101 | + size_t cap; | ||
| 102 | +} buf_t; | ||
| 103 | + | ||
| 104 | +static void buf_init(buf_t *b) | ||
| 105 | +{ | ||
| 106 | + b->p = NULL; | ||
| 107 | + b->n = 0; | ||
| 108 | + b->cap = 0; | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +static int buf_need(buf_t *b, size_t extra) | ||
| 112 | +{ | ||
| 113 | + size_t want = b->n + extra + 1; | ||
| 114 | + char *np; | ||
| 115 | + if (want <= b->cap) return 1; | ||
| 116 | + if (b->cap == 0) b->cap = 1024; | ||
| 117 | + while (b->cap < want) { | ||
| 118 | + if (b->cap > (size_t)128 * 1024 * 1024) return 0; | ||
| 119 | + b->cap *= 2; | ||
| 120 | + } | ||
| 121 | + np = (char *)realloc(b->p, b->cap); | ||
| 122 | + if (!np) return 0; | ||
| 123 | + b->p = np; | ||
| 124 | + return 1; | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +static void buf_add(buf_t *b, const char *s, size_t n) | ||
| 128 | +{ | ||
| 129 | + if (!buf_need(b, n)) return; | ||
| 130 | + memcpy(b->p + b->n, s, n); | ||
| 131 | + b->n += n; | ||
| 132 | + b->p[b->n] = '\0'; | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +static void buf_puts(buf_t *b, const char *s) | ||
| 136 | +{ | ||
| 137 | + if (s) buf_add(b, s, strlen(s)); | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +static void buf_putc(buf_t *b, char c) | ||
| 141 | +{ | ||
| 142 | + if (!buf_need(b, 1)) return; | ||
| 143 | + b->p[b->n++] = c; | ||
| 144 | + b->p[b->n] = '\0'; | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +static const char *buf_str(buf_t *b) | ||
| 148 | +{ | ||
| 149 | + return b->p ? b->p : ""; | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +static void buf_printf(buf_t *b, const char *fmt, ...) | ||
| 153 | +{ | ||
| 154 | + char tmp[1024]; | ||
| 155 | + va_list ap; | ||
| 156 | + int n; | ||
| 157 | + va_start(ap, fmt); | ||
| 158 | + n = vsnprintf(tmp, sizeof tmp, fmt, ap); | ||
| 159 | + va_end(ap); | ||
| 160 | + if (n < 0) return; | ||
| 161 | + if ((size_t)n < sizeof tmp) { | ||
| 162 | + buf_add(b, tmp, (size_t)n); | ||
| 163 | + return; | ||
| 164 | + } | ||
| 165 | + { | ||
| 166 | + char *big = (char *)malloc((size_t)n + 1); | ||
| 167 | + if (!big) return; | ||
| 168 | + va_start(ap, fmt); | ||
| 169 | + vsnprintf(big, (size_t)n + 1, fmt, ap); | ||
| 170 | + va_end(ap); | ||
| 171 | + buf_add(b, big, (size_t)n); | ||
| 172 | + free(big); | ||
| 173 | + } | ||
| 174 | +} | ||
| 175 | + | ||
| 176 | +static void buf_free(buf_t *b) | ||
| 177 | +{ | ||
| 178 | + free(b->p); | ||
| 179 | + b->p = NULL; | ||
| 180 | + b->n = 0; | ||
| 181 | + b->cap = 0; | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +/* ------------------------------------------------------------------ */ | ||
| 185 | +/* Small utilities */ | ||
| 186 | +/* ------------------------------------------------------------------ */ | ||
| 187 | + | ||
| 188 | +static void str_copy(char *dst, size_t sz, const char *src) | ||
| 189 | +{ | ||
| 190 | + size_t n; | ||
| 191 | + if (!dst || sz == 0) return; | ||
| 192 | + if (!src) { dst[0] = '\0'; return; } | ||
| 193 | + n = strlen(src); | ||
| 194 | + if (n >= sz) n = sz - 1; | ||
| 195 | + memcpy(dst, src, n); | ||
| 196 | + dst[n] = '\0'; | ||
| 197 | +} | ||
| 198 | + | ||
| 199 | +static void path_join(char *out, size_t sz, const char *a, const char *b) | ||
| 200 | +{ | ||
| 201 | + size_t n; | ||
| 202 | + if (!out || sz == 0) return; | ||
| 203 | + out[0] = '\0'; | ||
| 204 | + if (!a) a = ""; | ||
| 205 | + if (!b) b = ""; | ||
| 206 | + str_copy(out, sz, a); | ||
| 207 | + n = strlen(out); | ||
| 208 | + if (n && out[n - 1] != '/' && out[n - 1] != '\\' && n + 1 < sz) { | ||
| 209 | + out[n++] = SEP; | ||
| 210 | + out[n] = '\0'; | ||
| 211 | + } | ||
| 212 | + if (n + strlen(b) < sz) str_copy(out + n, sz - n, b); | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +static void url_decode(char *s) | ||
| 216 | +{ | ||
| 217 | + char *o = s; | ||
| 218 | + if (!s) return; | ||
| 219 | + while (*s) { | ||
| 220 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | ||
| 221 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | ||
| 222 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | ||
| 223 | + *o++ = (char)((hi << 4) | lo); | ||
| 224 | + s += 3; | ||
| 225 | + } else if (*s == '+') { | ||
| 226 | + *o++ = ' '; | ||
| 227 | + s++; | ||
| 228 | + } else { | ||
| 229 | + *o++ = *s++; | ||
| 230 | + } | ||
| 231 | + } | ||
| 232 | + *o = '\0'; | ||
| 233 | +} | ||
| 234 | + | ||
| 235 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 236 | +{ | ||
| 237 | + size_t klen; | ||
| 238 | + const char *p; | ||
| 239 | + | ||
| 240 | + if (!out || outsz == 0) return 0; | ||
| 241 | + out[0] = '\0'; | ||
| 242 | + if (!qs || !key) return 0; | ||
| 243 | + klen = strlen(key); | ||
| 244 | + | ||
| 245 | + for (p = qs; *p; ) { | ||
| 246 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | ||
| 247 | + const char *v = p + klen + 1; | ||
| 248 | + size_t i = 0; | ||
| 249 | + while (*v && *v != '&' && i + 1 < outsz) | ||
| 250 | + out[i++] = *v++; | ||
| 251 | + out[i] = '\0'; | ||
| 252 | + url_decode(out); | ||
| 253 | + return 1; | ||
| 254 | + } | ||
| 255 | + p = strchr(p, '&'); | ||
| 256 | + if (!p) break; | ||
| 257 | + p++; | ||
| 258 | + } | ||
| 259 | + return 0; | ||
| 260 | +} | ||
| 261 | + | ||
| 262 | +static void json_str(buf_t *b, const char *s) | ||
| 263 | +{ | ||
| 264 | + buf_putc(b, '"'); | ||
| 265 | + for (; s && *s; s++) { | ||
| 266 | + unsigned char c = (unsigned char)*s; | ||
| 267 | + switch (c) { | ||
| 268 | + case '"': buf_puts(b, "\\\""); break; | ||
| 269 | + case '\\': buf_puts(b, "\\\\"); break; | ||
| 270 | + case '\n': buf_puts(b, "\\n"); break; | ||
| 271 | + case '\r': buf_puts(b, "\\r"); break; | ||
| 272 | + case '\t': buf_puts(b, "\\t"); break; | ||
| 273 | + default: | ||
| 274 | + if (c < 0x20) { | ||
| 275 | + char tmp[8]; | ||
| 276 | + sprintf(tmp, "\\u%04x", c); | ||
| 277 | + buf_puts(b, tmp); | ||
| 278 | + } else { | ||
| 279 | + buf_putc(b, (char)c); | ||
| 280 | + } | ||
| 281 | + } | ||
| 282 | + } | ||
| 283 | + buf_putc(b, '"'); | ||
| 284 | +} | ||
| 285 | + | ||
| 286 | +static void fmt_iso(long long t, char *out, size_t sz) | ||
| 287 | +{ | ||
| 288 | + time_t tt = (time_t)t; | ||
| 289 | + struct tm tmv; | ||
| 290 | + if (t <= 0) { str_copy(out, sz, ""); return; } | ||
| 291 | +#if defined(_WIN32) | ||
| 292 | + gmtime_s(&tmv, &tt); | ||
| 293 | +#else | ||
| 294 | + gmtime_r(&tt, &tmv); | ||
| 295 | +#endif | ||
| 296 | + strftime(out, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); | ||
| 297 | +} | ||
| 298 | + | ||
| 299 | +static int ci_cmp(const char *a, const char *b) | ||
| 300 | +{ | ||
| 301 | + for (;;) { | ||
| 302 | + unsigned char ca = (unsigned char)*a++; | ||
| 303 | + unsigned char cb = (unsigned char)*b++; | ||
| 304 | + ca = (unsigned char)tolower(ca); | ||
| 305 | + cb = (unsigned char)tolower(cb); | ||
| 306 | + if (ca != cb) return ca < cb ? -1 : 1; | ||
| 307 | + if (!ca) return 0; | ||
| 308 | + } | ||
| 309 | +} | ||
| 310 | + | ||
| 311 | +/* ------------------------------------------------------------------ */ | ||
| 312 | +/* Path canonicalisation + allowlist */ | ||
| 313 | +/* ------------------------------------------------------------------ */ | ||
| 314 | + | ||
| 315 | +/* POSIX: realpath() resolves every symlink, so the prefix check happens on | ||
| 316 | + * the real target. Windows: GetFullPathNameA normalises `..`, then | ||
| 317 | + * GetFinalPathNameByHandleA resolves reparse points when the file exists. */ | ||
| 318 | + | ||
| 319 | +#if defined(_WIN32) | ||
| 320 | + | ||
| 321 | +static void win_norm(char *s) | ||
| 322 | +{ | ||
| 323 | + for (; *s; s++) { | ||
| 324 | + if (*s == '/') *s = '\\'; | ||
| 325 | + *s = (char)tolower((unsigned char)*s); | ||
| 326 | + } | ||
| 327 | +} | ||
| 328 | + | ||
| 329 | +static int path_under_win(const char *p, const char *root) | ||
| 330 | +{ | ||
| 331 | + char a[PATH_SZ], b[PATH_SZ]; | ||
| 332 | + size_t n; | ||
| 333 | + str_copy(a, sizeof a, p); | ||
| 334 | + str_copy(b, sizeof b, root); | ||
| 335 | + win_norm(a); | ||
| 336 | + win_norm(b); | ||
| 337 | + n = strlen(b); | ||
| 338 | + while (n > 3 && b[n - 1] == '\\') b[--n] = '\0'; | ||
| 339 | + if (strcmp(a, b) == 0) return 1; | ||
| 340 | + if (strncmp(a, b, n) == 0 && a[n] == '\\') return 1; | ||
| 341 | + return 0; | ||
| 342 | +} | ||
| 343 | + | ||
| 344 | +static int canon_path(const char *raw, char *out, size_t outsz, int *err) | ||
| 345 | +{ | ||
| 346 | + char full[PATH_SZ]; | ||
| 347 | + DWORD n; | ||
| 348 | + HANDLE h; | ||
| 349 | + char final[PATH_SZ]; | ||
| 350 | + | ||
| 351 | + *err = 0; | ||
| 352 | + if (!raw || !*raw) { *err = 400; return 0; } | ||
| 353 | + if (strchr(raw, '\0') == NULL) return 0; /* unreachable; keeps compilers quiet */ | ||
| 354 | + | ||
| 355 | + n = GetFullPathNameA(raw, (DWORD)sizeof full, full, NULL); | ||
| 356 | + if (n == 0 || n >= (DWORD)sizeof full) { *err = 400; return 0; } | ||
| 357 | + | ||
| 358 | + if (GetFileAttributesA(full) == INVALID_FILE_ATTRIBUTES) { *err = 404; return 0; } | ||
| 359 | + | ||
| 360 | + h = CreateFileA(full, 0, | ||
| 361 | + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, | ||
| 362 | + NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); | ||
| 363 | + if (h != INVALID_HANDLE_VALUE) { | ||
| 364 | + DWORD fn = GetFinalPathNameByHandleA(h, final, (DWORD)sizeof final, 0); | ||
| 365 | + CloseHandle(h); | ||
| 366 | + if (fn > 0 && fn < (DWORD)sizeof final) { | ||
| 367 | + char *src = final; | ||
| 368 | + if (strncmp(src, "\\\\?\\", 4) == 0) src += 4; | ||
| 369 | + str_copy(out, outsz, src); | ||
| 370 | + return 1; | ||
| 371 | + } | ||
| 372 | + } | ||
| 373 | + str_copy(out, outsz, full); | ||
| 374 | + return 1; | ||
| 375 | +} | ||
| 376 | + | ||
| 377 | +#else /* POSIX */ | ||
| 378 | + | ||
| 379 | +static int path_under(const char *p, const char *root) | ||
| 380 | +{ | ||
| 381 | + size_t n = strlen(root); | ||
| 382 | + if (strcmp(p, root) == 0) return 1; | ||
| 383 | + if (n && root[n - 1] == '/') return strncmp(p, root, n) == 0; | ||
| 384 | + if (n && strncmp(p, root, n) == 0 && p[n] == '/') return 1; | ||
| 385 | + return 0; | ||
| 386 | +} | ||
| 387 | + | ||
| 388 | +static int canon_path(const char *raw, char *out, size_t outsz, int *err) | ||
| 389 | +{ | ||
| 390 | + char *r; | ||
| 391 | + *err = 0; | ||
| 392 | + if (!raw || !*raw) { *err = 400; return 0; } | ||
| 393 | + if (raw[0] != '/') { *err = 400; return 0; } | ||
| 394 | + if (strstr(raw, "/../") || (strlen(raw) > 3 && strcmp(raw + strlen(raw) - 3, "/..") == 0)) { | ||
| 395 | + /* realpath would handle it, but a `..` in a browse path is always a | ||
| 396 | + * probe, never a legit UI request. */ | ||
| 397 | + *err = 400; | ||
| 398 | + return 0; | ||
| 399 | + } | ||
| 400 | + r = realpath(raw, NULL); | ||
| 401 | + if (!r) { *err = (errno == ENOENT || errno == ENOTDIR) ? 404 : 403; return 0; } | ||
| 402 | + str_copy(out, outsz, r); | ||
| 403 | + free(r); | ||
| 404 | + return 1; | ||
| 405 | +} | ||
| 406 | + | ||
| 407 | +#endif | ||
| 408 | + | ||
| 409 | +/* Paths that must never be browsed even when they sit under an allowed root. */ | ||
| 410 | +static int denied_path(const char *p) | ||
| 411 | +{ | ||
| 412 | +#if defined(_WIN32) | ||
| 413 | + (void)p; | ||
| 414 | + return 0; | ||
| 415 | +#else | ||
| 416 | + static const char *deny[] = { "/proc", "/sys", "/dev" }; | ||
| 417 | + size_t i; | ||
| 418 | + for (i = 0; i < sizeof deny / sizeof deny[0]; i++) | ||
| 419 | + if (path_under(p, deny[i])) return 1; | ||
| 420 | + return 0; | ||
| 421 | +#endif | ||
| 422 | +} | ||
| 423 | + | ||
| 424 | +static int is_allowed(const char *canon) | ||
| 425 | +{ | ||
| 426 | + int i; | ||
| 427 | + if (denied_path(canon)) return 0; | ||
| 428 | + for (i = 0; i < g_root_count; i++) { | ||
| 429 | +#if defined(_WIN32) | ||
| 430 | + if (path_under_win(canon, g_roots[i])) return 1; | ||
| 431 | +#else | ||
| 432 | + if (path_under(canon, g_roots[i])) return 1; | ||
| 433 | +#endif | ||
| 434 | + } | ||
| 435 | + return 0; | ||
| 436 | +} | ||
| 437 | + | ||
| 438 | +/* Resolve + authorise in one step. Returns 1 on success. */ | ||
| 439 | +static int resolve_allowed(const char *raw, char *out, size_t outsz, int *err) | ||
| 440 | +{ | ||
| 441 | + if (!canon_path(raw, out, outsz, err)) return 0; | ||
| 442 | + if (!is_allowed(out)) { *err = 403; return 0; } | ||
| 443 | + return 1; | ||
| 444 | +} | ||
| 445 | + | ||
| 446 | +/* Which allowlisted root contains this canonical path (-1 = none). */ | ||
| 447 | +static int root_of(const char *canon) | ||
| 448 | +{ | ||
| 449 | + int i; | ||
| 450 | + for (i = 0; i < g_root_count; i++) { | ||
| 451 | +#if defined(_WIN32) | ||
| 452 | + if (path_under_win(canon, g_roots[i])) return i; | ||
| 453 | +#else | ||
| 454 | + if (path_under(canon, g_roots[i])) return i; | ||
| 455 | +#endif | ||
| 456 | + } | ||
| 457 | + return -1; | ||
| 458 | +} | ||
| 459 | + | ||
| 460 | +static void parent_of(const char *canon, char *out, size_t outsz) | ||
| 461 | +{ | ||
| 462 | + size_t n; | ||
| 463 | + str_copy(out, outsz, canon); | ||
| 464 | + n = strlen(out); | ||
| 465 | + while (n > 1 && (out[n - 1] == '/' || out[n - 1] == '\\')) out[--n] = '\0'; | ||
| 466 | +#if defined(_WIN32) | ||
| 467 | + while (n > 3 && out[n - 1] != '\\') out[--n] = '\0'; | ||
| 468 | + if (n > 3) out[--n] = '\0'; | ||
| 469 | + else str_copy(out, outsz, canon); | ||
| 470 | +#else | ||
| 471 | + while (n > 1 && out[n - 1] != '/') out[--n] = '\0'; | ||
| 472 | + if (n > 1) out[--n] = '\0'; | ||
| 473 | + if (outsz && out[0] == '\0') str_copy(out, outsz, "/"); | ||
| 474 | +#endif | ||
| 475 | +} | ||
| 476 | + | ||
| 477 | +/* ------------------------------------------------------------------ */ | ||
| 478 | +/* Allowlisted roots */ | ||
| 479 | +/* ------------------------------------------------------------------ */ | ||
| 480 | + | ||
| 481 | +static void add_root(const char *cand) | ||
| 482 | +{ | ||
| 483 | + char canon[PATH_SZ]; | ||
| 484 | + int err = 0; | ||
| 485 | + int i; | ||
| 486 | + | ||
| 487 | + if (g_root_count >= MAX_ROOTS) return; | ||
| 488 | + if (!cand || !*cand) return; | ||
| 489 | + if (!canon_path(cand, canon, sizeof canon, &err)) return; | ||
| 490 | + if (denied_path(canon)) return; | ||
| 491 | + for (i = 0; i < g_root_count; i++) { | ||
| 492 | +#if defined(_WIN32) | ||
| 493 | + if (path_under_win(canon, g_roots[i]) && path_under_win(g_roots[i], canon)) return; | ||
| 494 | +#else | ||
| 495 | + if (strcmp(canon, g_roots[i]) == 0) return; | ||
| 496 | +#endif | ||
| 497 | + } | ||
| 498 | + str_copy(g_roots[g_root_count], sizeof g_roots[g_root_count], canon); | ||
| 499 | + g_root_count++; | ||
| 500 | +} | ||
| 501 | + | ||
| 502 | +static void init_roots(void) | ||
| 503 | +{ | ||
| 504 | + const char *extra; | ||
| 505 | + const char *home; | ||
| 506 | + | ||
| 507 | + if (g_root_count) return; | ||
| 508 | + | ||
| 509 | +#if defined(_WIN32) | ||
| 510 | + home = getenv("USERPROFILE"); | ||
| 511 | + add_root("D:\\codebases"); | ||
| 512 | + if (home && *home) add_root(home); | ||
| 513 | +#else | ||
| 514 | + add_root("/workspace"); | ||
| 515 | + add_root("/codebases"); | ||
| 516 | + home = getenv("HOME"); | ||
| 517 | + if (home && *home) add_root(home); | ||
| 518 | +#endif | ||
| 519 | + | ||
| 520 | + /* $FILES_ALLOWED_ROOT: one extra root, or several separated by ':' on | ||
| 521 | + * POSIX / ';' on Windows. Tests use it to point at a fixture tree. */ | ||
| 522 | + extra = getenv("FILES_ALLOWED_ROOT"); | ||
| 523 | + if (extra && *extra) { | ||
| 524 | +#if defined(_WIN32) | ||
| 525 | + const char *sep = ";"; | ||
| 526 | +#else | ||
| 527 | + const char *sep = ":"; | ||
| 528 | +#endif | ||
| 529 | + char tmp[PATH_SZ]; | ||
| 530 | + const char *p = extra; | ||
| 531 | + while (*p) { | ||
| 532 | + const char *e = strstr(p, sep); | ||
| 533 | + size_t n = e ? (size_t)(e - p) : strlen(p); | ||
| 534 | + if (n < sizeof tmp) { | ||
| 535 | + memcpy(tmp, p, n); | ||
| 536 | + tmp[n] = '\0'; | ||
| 537 | + add_root(tmp); | ||
| 538 | + } | ||
| 539 | + if (!e) break; | ||
| 540 | + p = e + strlen(sep); | ||
| 541 | + } | ||
| 542 | + } | ||
| 543 | +} | ||
| 544 | + | ||
| 545 | +/* ------------------------------------------------------------------ */ | ||
| 546 | +/* Directory listing */ | ||
| 547 | +/* ------------------------------------------------------------------ */ | ||
| 548 | + | ||
| 549 | +static int ent_cmp(const void *pa, const void *pb) | ||
| 550 | +{ | ||
| 551 | + const ent_t *a = (const ent_t *)pa; | ||
| 552 | + const ent_t *b = (const ent_t *)pb; | ||
| 553 | + if (a->is_dir != b->is_dir) return a->is_dir ? -1 : 1; | ||
| 554 | + return ci_cmp(a->name, b->name); | ||
| 555 | +} | ||
| 556 | + | ||
| 557 | +static void fill_entry_meta(ent_t *e, const char *full) | ||
| 558 | +{ | ||
| 559 | +#if defined(_WIN32) | ||
| 560 | + WIN32_FILE_ATTRIBUTE_DATA fd; | ||
| 561 | + if (GetFileAttributesExA(full, GetFileExInfoStandard, &fd)) { | ||
| 562 | + ULARGE_INTEGER sz, tm; | ||
| 563 | + e->size = 0; | ||
| 564 | + sz.LowPart = fd.nFileSizeLow; | ||
| 565 | + sz.HighPart = fd.nFileSizeHigh; | ||
| 566 | + e->size = (long long)sz.QuadPart; | ||
| 567 | + tm.LowPart = fd.ftLastWriteTime.dwLowDateTime; | ||
| 568 | + tm.HighPart = fd.ftLastWriteTime.dwHighDateTime; | ||
| 569 | + /* FILETIME -> unix seconds */ | ||
| 570 | + e->mtime = (long long)((tm.QuadPart / 10000000ULL) - 11644473600ULL); | ||
| 571 | + e->mode = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? 0755u : 0644u; | ||
| 572 | + } | ||
| 573 | +#else | ||
| 574 | + struct stat st; | ||
| 575 | + struct stat lst; | ||
| 576 | + if (lstat(full, &lst) == 0) { | ||
| 577 | + e->is_link = S_ISLNK(lst.st_mode) ? 1 : 0; | ||
| 578 | + e->size = (long long)lst.st_size; | ||
| 579 | + e->mtime = (long long)lst.st_mtime; | ||
| 580 | + e->mode = (unsigned)(lst.st_mode & 07777); | ||
| 581 | + if (stat(full, &st) == 0) { | ||
| 582 | + if (S_ISDIR(st.st_mode)) e->is_dir = 1; | ||
| 583 | + e->size = (long long)st.st_size; | ||
| 584 | + e->mode = (unsigned)(st.st_mode & 07777); | ||
| 585 | + } | ||
| 586 | + } | ||
| 587 | +#endif | ||
| 588 | +} | ||
| 589 | + | ||
| 590 | +static int list_dir(const char *path, int show_hidden, ent_t **out, int *count, int *truncated) | ||
| 591 | +{ | ||
| 592 | + ent_t *ents; | ||
| 593 | + int n = 0; | ||
| 594 | + int trunc = 0; | ||
| 595 | + | ||
| 596 | + ents = (ent_t *)calloc(MAX_ENTRIES, sizeof(ent_t)); | ||
| 597 | + if (!ents) return 0; | ||
| 598 | + | ||
| 599 | +#if defined(_WIN32) | ||
| 600 | + { | ||
| 601 | + char pattern[PATH_SZ]; | ||
| 602 | + WIN32_FIND_DATAA fd; | ||
| 603 | + HANDLE h; | ||
| 604 | + path_join(pattern, sizeof pattern, path, "*"); | ||
| 605 | + h = FindFirstFileA(pattern, &fd); | ||
| 606 | + if (h == INVALID_HANDLE_VALUE) { free(ents); return 0; } | ||
| 607 | + do { | ||
| 608 | + char full[PATH_SZ]; | ||
| 609 | + ent_t *e; | ||
| 610 | + if (!strcmp(fd.cFileName, ".") || !strcmp(fd.cFileName, "..")) continue; | ||
| 611 | + if (!show_hidden && fd.cFileName[0] == '.') continue; | ||
| 612 | + if (n >= MAX_ENTRIES) { trunc = 1; break; } | ||
| 613 | + e = &ents[n]; | ||
| 614 | + memset(e, 0, sizeof *e); | ||
| 615 | + str_copy(e->name, sizeof e->name, fd.cFileName); | ||
| 616 | + e->is_dir = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? 1 : 0; | ||
| 617 | + e->is_link = (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) ? 1 : 0; | ||
| 618 | + path_join(full, sizeof full, path, fd.cFileName); | ||
| 619 | + fill_entry_meta(e, full); | ||
| 620 | + n++; | ||
| 621 | + } while (FindNextFileA(h, &fd)); | ||
| 622 | + FindClose(h); | ||
| 623 | + } | ||
| 624 | +#else | ||
| 625 | + { | ||
| 626 | + DIR *d = opendir(path); | ||
| 627 | + struct dirent *de; | ||
| 628 | + if (!d) { free(ents); return 0; } | ||
| 629 | + while ((de = readdir(d)) != NULL) { | ||
| 630 | + char full[PATH_SZ]; | ||
| 631 | + ent_t *e; | ||
| 632 | + if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue; | ||
| 633 | + if (!show_hidden && de->d_name[0] == '.') continue; | ||
| 634 | + if (n >= MAX_ENTRIES) { trunc = 1; break; } | ||
| 635 | + e = &ents[n]; | ||
| 636 | + memset(e, 0, sizeof *e); | ||
| 637 | + str_copy(e->name, sizeof e->name, de->d_name); | ||
| 638 | + path_join(full, sizeof full, path, de->d_name); | ||
| 639 | + fill_entry_meta(e, full); | ||
| 640 | + n++; | ||
| 641 | + } | ||
| 642 | + closedir(d); | ||
| 643 | + } | ||
| 644 | +#endif | ||
| 645 | + | ||
| 646 | + if (n > 1) qsort(ents, (size_t)n, sizeof(ent_t), ent_cmp); | ||
| 647 | + *out = ents; | ||
| 648 | + *count = n; | ||
| 649 | + *truncated = trunc; | ||
| 650 | + return 1; | ||
| 651 | +} | ||
| 652 | + | ||
| 653 | +/* ------------------------------------------------------------------ */ | ||
| 654 | +/* Node authentication */ | ||
| 655 | +/* ------------------------------------------------------------------ */ | ||
| 656 | + | ||
| 657 | +static void require_node_auth(void) | ||
| 658 | +{ | ||
| 659 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 660 | + const char *xp; | ||
| 661 | + const char *auth; | ||
| 662 | + const char *qs; | ||
| 663 | + char qpwd[256]; | ||
| 664 | + | ||
| 665 | + if (!np || !*np) return; | ||
| 666 | + | ||
| 667 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | ||
| 668 | + if (xp && strcmp(xp, np) == 0) return; | ||
| 669 | + | ||
| 670 | + auth = getenv("HTTP_AUTHORIZATION"); | ||
| 671 | + if (auth) { | ||
| 672 | + while (*auth == ' ') auth++; | ||
| 673 | + if (strncmp(auth, "Bearer ", 7) == 0) { | ||
| 674 | + auth += 7; | ||
| 675 | + while (*auth == ' ') auth++; | ||
| 676 | + if (strcmp(auth, np) == 0) return; | ||
| 677 | + } | ||
| 678 | + } | ||
| 679 | + | ||
| 680 | + qs = getenv("QUERY_STRING"); | ||
| 681 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) | ||
| 682 | + return; | ||
| 683 | + | ||
| 684 | + fputs("Status: 401 Unauthorized\r\n" | ||
| 685 | + "Content-Type: application/json; charset=utf-8\r\n" | ||
| 686 | + "Cache-Control: no-store\r\n" | ||
| 687 | + "X-Content-Type-Options: nosniff\r\n\r\n" | ||
| 688 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | ||
| 689 | + exit(0); | ||
| 690 | +} | ||
| 691 | + | ||
| 692 | +/* ------------------------------------------------------------------ */ | ||
| 693 | +/* JSON responses */ | ||
| 694 | +/* ------------------------------------------------------------------ */ | ||
| 695 | + | ||
| 696 | +static void json_header(void) | ||
| 697 | +{ | ||
| 698 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | ||
| 699 | + "Cache-Control: no-store\r\n" | ||
| 700 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 701 | +} | ||
| 702 | + | ||
| 703 | +static void json_err(int code, const char *msg) | ||
| 704 | +{ | ||
| 705 | + if (code == 400) fputs("Status: 400 Bad Request\r\n", stdout); | ||
| 706 | + else if (code == 403) fputs("Status: 403 Forbidden\r\n", stdout); | ||
| 707 | + else if (code == 404) fputs("Status: 404 Not Found\r\n", stdout); | ||
| 708 | + else if (code == 405) fputs("Status: 405 Method Not Allowed\r\n", stdout); | ||
| 709 | + else if (code == 413) fputs("Status: 413 Payload Too Large\r\n", stdout); | ||
| 710 | + else fputs("Status: 500 Internal Server Error\r\n", stdout); | ||
| 711 | + json_header(); | ||
| 712 | + printf("{\"ok\":false,\"error\":"); | ||
| 713 | + { | ||
| 714 | + buf_t b; | ||
| 715 | + buf_init(&b); | ||
| 716 | + json_str(&b, msg ? msg : "error"); | ||
| 717 | + fputs(buf_str(&b), stdout); | ||
| 718 | + buf_free(&b); | ||
| 719 | + } | ||
| 720 | + fputs("}\n", stdout); | ||
| 721 | +} | ||
| 722 | + | ||
| 723 | +/* ------------------------------------------------------------------ */ | ||
| 724 | +/* ?action=roots */ | ||
| 725 | +/* ------------------------------------------------------------------ */ | ||
| 726 | + | ||
| 727 | +static void do_roots(void) | ||
| 728 | +{ | ||
| 729 | + int i; | ||
| 730 | + buf_t b; | ||
| 731 | + buf_init(&b); | ||
| 732 | + buf_printf(&b, "{\"ok\":true,\"count\":%d,\"roots\":[", g_root_count); | ||
| 733 | + for (i = 0; i < g_root_count; i++) { | ||
| 734 | + const char *base = strrchr(g_roots[i], SEP); | ||
| 735 | + char label[NAME_SZ]; | ||
| 736 | + if (i) buf_putc(&b, ','); | ||
| 737 | + buf_puts(&b, "\n {\"path\":"); | ||
| 738 | + json_str(&b, g_roots[i]); | ||
| 739 | + buf_puts(&b, ",\"name\":"); | ||
| 740 | + if (base && base[1]) str_copy(label, sizeof label, base + 1); | ||
| 741 | + else str_copy(label, sizeof label, g_roots[i]); | ||
| 742 | + json_str(&b, label); | ||
| 743 | + buf_putc(&b, '}'); | ||
| 744 | + } | ||
| 745 | + buf_puts(&b, "\n]}\n"); | ||
| 746 | + json_header(); | ||
| 747 | + fputs(buf_str(&b), stdout); | ||
| 748 | + buf_free(&b); | ||
| 749 | +} | ||
| 750 | + | ||
| 751 | +/* ------------------------------------------------------------------ */ | ||
| 752 | +/* ?action=ls&path=<abs> */ | ||
| 753 | +/* ------------------------------------------------------------------ */ | ||
| 754 | + | ||
| 755 | +static const char *ent_kind(const ent_t *e) | ||
| 756 | +{ | ||
| 757 | + if (e->is_dir) return "dir"; | ||
| 758 | + if (e->is_link) return "link"; | ||
| 759 | + return "file"; | ||
| 760 | +} | ||
| 761 | + | ||
| 762 | +static void do_ls(const char *raw_path, const char *qs) | ||
| 763 | +{ | ||
| 764 | + char canon[PATH_SZ]; | ||
| 765 | + char parent[PATH_SZ]; | ||
| 766 | + char hiddenbuf[8]; | ||
| 767 | + int show_hidden = 0; | ||
| 768 | + int err = 0; | ||
| 769 | + int count = 0, trunc = 0; | ||
| 770 | + int ri; | ||
| 771 | + ent_t *ents = NULL; | ||
| 772 | + buf_t b; | ||
| 773 | + int i; | ||
| 774 | + | ||
| 775 | + if (!raw_path || !*raw_path) { | ||
| 776 | + if (g_root_count) str_copy(canon, sizeof canon, g_roots[0]); | ||
| 777 | + else { json_err(500, "no allowlisted root available"); return; } | ||
| 778 | + } | ||
| 779 | + | ||
| 780 | + if (raw_path && *raw_path) { | ||
| 781 | + if (!resolve_allowed(raw_path, canon, sizeof canon, &err)) { | ||
| 782 | + json_err(err, err == 403 ? "path not allowed" : (err == 404 ? "path not found" : "bad path")); | ||
| 783 | + return; | ||
| 784 | + } | ||
| 785 | + } | ||
| 786 | + | ||
| 787 | + if (get_query_val(qs, "hidden", hiddenbuf, sizeof hiddenbuf)) { | ||
| 788 | + show_hidden = (strcmp(hiddenbuf, "1") == 0 || strcmp(hiddenbuf, "true") == 0); | ||
| 789 | + } | ||
| 790 | + | ||
| 791 | + if (!list_dir(canon, show_hidden, &ents, &count, &trunc)) { | ||
| 792 | + json_err(403, "cannot list directory"); | ||
| 793 | + return; | ||
| 794 | + } | ||
| 795 | + | ||
| 796 | + ri = root_of(canon); | ||
| 797 | + parent[0] = '\0'; | ||
| 798 | + if (ri >= 0 && strcmp(canon, g_roots[ri]) != 0) | ||
| 799 | + parent_of(canon, parent, sizeof parent); | ||
| 800 | + | ||
| 801 | + buf_init(&b); | ||
| 802 | + buf_puts(&b, "{\"ok\":true,\"path\":"); | ||
| 803 | + json_str(&b, canon); | ||
| 804 | + buf_puts(&b, ",\"parent\":"); | ||
| 805 | + if (parent[0]) json_str(&b, parent); else buf_puts(&b, "null"); | ||
| 806 | + buf_puts(&b, ",\"root\":"); | ||
| 807 | + if (ri >= 0) json_str(&b, g_roots[ri]); else buf_puts(&b, "null"); | ||
| 808 | + buf_puts(&b, ",\"hidden\":"); | ||
| 809 | + buf_putc(&b, show_hidden ? '1' : '0'); | ||
| 810 | + buf_printf(&b, ",\"count\":%d,\"truncated\":%s,\"entries\":[", | ||
| 811 | + count, trunc ? "true" : "false"); | ||
| 812 | + | ||
| 813 | + for (i = 0; i < count; i++) { | ||
| 814 | + char iso[32]; | ||
| 815 | + char mode[8]; | ||
| 816 | + fmt_iso(ents[i].mtime, iso, sizeof iso); | ||
| 817 | + sprintf(mode, "%04o", ents[i].mode & 07777); | ||
| 818 | + buf_puts(&b, i ? ",\n {\"name\":" : "\n {\"name\":"); | ||
| 819 | + json_str(&b, ents[i].name); | ||
| 820 | + buf_puts(&b, ",\"type\":\""); | ||
| 821 | + buf_puts(&b, ent_kind(&ents[i])); | ||
| 822 | + buf_printf(&b, "\",\"size\":%lld,\"mtime\":\"%s\",\"mode\":\"%s\"}", | ||
| 823 | + ents[i].size, iso, mode); | ||
| 824 | + } | ||
| 825 | + buf_puts(&b, "\n]}\n"); | ||
| 826 | + | ||
| 827 | + json_header(); | ||
| 828 | + fputs(buf_str(&b), stdout); | ||
| 829 | + free(ents); | ||
| 830 | + buf_free(&b); | ||
| 831 | +} | ||
| 832 | + | ||
| 833 | +/* ------------------------------------------------------------------ */ | ||
| 834 | +/* ?action=read&path=<abs> */ | ||
| 835 | +/* ------------------------------------------------------------------ */ | ||
| 836 | + | ||
| 837 | +static int read_range(const char *path, char *out, size_t cap, size_t *got, int *binary) | ||
| 838 | +{ | ||
| 839 | + FILE *f; | ||
| 840 | + size_t n; | ||
| 841 | + | ||
| 842 | + *got = 0; | ||
| 843 | + *binary = 0; | ||
| 844 | + f = fopen(path, "rb"); | ||
| 845 | + if (!f) return 0; | ||
| 846 | + n = fread(out, 1, cap, f); | ||
| 847 | + if (ferror(f)) { fclose(f); return 0; } | ||
| 848 | + *got = n; | ||
| 849 | + { | ||
| 850 | + size_t lim = n < BIN_PROBE ? n : BIN_PROBE; | ||
| 851 | + size_t i; | ||
| 852 | + for (i = 0; i < lim; i++) { | ||
| 853 | + if (out[i] == '\0') { *binary = 1; break; } | ||
| 854 | + } | ||
| 855 | + } | ||
| 856 | + fclose(f); | ||
| 857 | + return 1; | ||
| 858 | +} | ||
| 859 | + | ||
| 860 | +static void do_read(const char *raw_path) | ||
| 861 | +{ | ||
| 862 | + char canon[PATH_SZ]; | ||
| 863 | + int err = 0; | ||
| 864 | + struct { long long size; long long mtime; unsigned mode; int is_dir; } info; | ||
| 865 | + char iso[32], mode[8]; | ||
| 866 | + static char text[TEXT_CAP + 1]; | ||
| 867 | + size_t got = 0; | ||
| 868 | + int binary = 0; | ||
| 869 | + int trunc = 0; | ||
| 870 | + buf_t b; | ||
| 871 | + | ||
| 872 | +#if defined(_WIN32) | ||
| 873 | + { | ||
| 874 | + WIN32_FILE_ATTRIBUTE_DATA fd; | ||
| 875 | + memset(&info, 0, sizeof info); | ||
| 876 | + if (!resolve_allowed(raw_path, canon, sizeof canon, &err)) { | ||
| 877 | + json_err(err, err == 403 ? "path not allowed" : (err == 404 ? "path not found" : "bad path")); | ||
| 878 | + return; | ||
| 879 | + } | ||
| 880 | + if (!GetFileAttributesExA(canon, GetFileExInfoStandard, &fd)) { | ||
| 881 | + json_err(404, "path not found"); | ||
| 882 | + return; | ||
| 883 | + } | ||
| 884 | + info.is_dir = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? 1 : 0; | ||
| 885 | + { | ||
| 886 | + ULARGE_INTEGER sz, tm; | ||
| 887 | + sz.LowPart = fd.nFileSizeLow; sz.HighPart = fd.nFileSizeHigh; | ||
| 888 | + info.size = (long long)sz.QuadPart; | ||
| 889 | + tm.LowPart = fd.ftLastWriteTime.dwLowDateTime; tm.HighPart = fd.ftLastWriteTime.dwHighDateTime; | ||
| 890 | + info.mtime = (long long)((tm.QuadPart / 10000000ULL) - 11644473600ULL); | ||
| 891 | + } | ||
| 892 | + info.mode = info.is_dir ? 0755u : 0644u; | ||
| 893 | + } | ||
| 894 | +#else | ||
| 895 | + { | ||
| 896 | + struct stat st; | ||
| 897 | + memset(&info, 0, sizeof info); | ||
| 898 | + if (!resolve_allowed(raw_path, canon, sizeof canon, &err)) { | ||
| 899 | + json_err(err, err == 403 ? "path not allowed" : (err == 404 ? "path not found" : "bad path")); | ||
| 900 | + return; | ||
| 901 | + } | ||
| 902 | + if (stat(canon, &st) != 0) { json_err(404, "path not found"); return; } | ||
| 903 | + info.is_dir = S_ISDIR(st.st_mode) ? 1 : 0; | ||
| 904 | + info.size = (long long)st.st_size; | ||
| 905 | + info.mtime = (long long)st.st_mtime; | ||
| 906 | + info.mode = (unsigned)(st.st_mode & 07777); | ||
| 907 | + } | ||
| 908 | +#endif | ||
| 909 | + | ||
| 910 | + if (info.is_dir) { json_err(400, "not a regular file"); return; } | ||
| 911 | + | ||
| 912 | + if (info.size > TEXT_CAP) trunc = 1; | ||
| 913 | + if (!read_range(canon, text, TEXT_CAP, &got, &binary)) { | ||
| 914 | + json_err(403, "cannot read file"); | ||
| 915 | + return; | ||
| 916 | + } | ||
| 917 | + text[got] = '\0'; | ||
| 918 | + if (binary) trunc = 0; | ||
| 919 | + | ||
| 920 | + fmt_iso(info.mtime, iso, sizeof iso); | ||
| 921 | + sprintf(mode, "%04o", info.mode & 07777); | ||
| 922 | + buf_init(&b); | ||
| 923 | + buf_puts(&b, "{\"ok\":true,\"path\":"); | ||
| 924 | + json_str(&b, canon); | ||
| 925 | + buf_puts(&b, ",\"name\":"); | ||
| 926 | + { | ||
| 927 | + const char *base = strrchr(canon, SEP); | ||
| 928 | + json_str(&b, (base && base[1]) ? base + 1 : canon); | ||
| 929 | + } | ||
| 930 | + buf_printf(&b, ",\"size\":%lld,\"mtime\":\"%s\",\"mode\":\"%s\"", info.size, iso, mode); | ||
| 931 | + buf_printf(&b, ",\"binary\":%s,\"truncated\":%s,\"bytes_read\":%lu", | ||
| 932 | + binary ? "true" : "false", trunc ? "true" : "false", (unsigned long)got); | ||
| 933 | + if (!binary) { | ||
| 934 | + buf_puts(&b, ",\"text\":"); | ||
| 935 | + json_str(&b, text); | ||
| 936 | + } | ||
| 937 | + buf_puts(&b, "}\n"); | ||
| 938 | + | ||
| 939 | + json_header(); | ||
| 940 | + fputs(buf_str(&b), stdout); | ||
| 941 | + buf_free(&b); | ||
| 942 | +} | ||
| 943 | + | ||
| 944 | +typedef struct { const char *ext; const char *type; } mime_t; | ||
| 945 | + | ||
| 946 | +static const mime_t g_mime[] = { | ||
| 947 | + { "png", "image/png" }, | ||
| 948 | + { "jpg", "image/jpeg" }, | ||
| 949 | + { "jpeg", "image/jpeg" }, | ||
| 950 | + { "gif", "image/gif" }, | ||
| 951 | + { "webp", "image/webp" }, | ||
| 952 | + { "bmp", "image/bmp" }, | ||
| 953 | + { "ico", "image/x-icon" }, | ||
| 954 | + { "svg", "text/plain; charset=utf-8" }, | ||
| 955 | + { "pdf", "application/pdf" }, | ||
| 956 | + { "txt", "text/plain; charset=utf-8" }, | ||
| 957 | + { "md", "text/plain; charset=utf-8" }, | ||
| 958 | + { "json", "text/plain; charset=utf-8" }, | ||
| 959 | + { "c", "text/plain; charset=utf-8" }, | ||
| 960 | + { "h", "text/plain; charset=utf-8" }, | ||
| 961 | + { "log", "text/plain; charset=utf-8" } | ||
| 962 | +}; | ||
| 963 | + | ||
| 964 | +/* Markup is served as text/plain on purpose: this route shares an origin with | ||
| 965 | + * the node API, so rendering a local .html file as text/html would hand any | ||
| 966 | + * page on disk the ability to call the plugin API with the user's password. | ||
| 967 | + * Images keep their real type because <img> only decodes them. */ | ||
| 968 | +static const char *guess_type(const char *name) | ||
| 969 | +{ | ||
| 970 | + const char *dot = strrchr(name, '.'); | ||
| 971 | + size_t i; | ||
| 972 | + if (!dot || !dot[1]) return "application/octet-stream"; | ||
| 973 | + for (i = 0; i < sizeof g_mime / sizeof g_mime[0]; i++) { | ||
| 974 | + size_t k = strlen(g_mime[i].ext); | ||
| 975 | + size_t n = strlen(dot + 1); | ||
| 976 | + if (n == k) { | ||
| 977 | + size_t j; int same = 1; | ||
| 978 | + for (j = 0; j < k; j++) | ||
| 979 | + if (tolower((unsigned char)dot[1 + j]) != g_mime[i].ext[j]) { same = 0; break; } | ||
| 980 | + if (same) return g_mime[i].type; | ||
| 981 | + } | ||
| 982 | + } | ||
| 983 | + if (strstr(dot + 1, "htm")) return "text/plain; charset=utf-8"; | ||
| 984 | + return "application/octet-stream"; | ||
| 985 | +} | ||
| 986 | + | ||
| 987 | +static int is_image_type(const char *t) | ||
| 988 | +{ | ||
| 989 | + return strncmp(t, "image/", 6) == 0; | ||
| 990 | +} | ||
| 991 | + | ||
| 992 | +/* Header-safe file name: quotes, CR and LF out. */ | ||
| 993 | +static void header_name(const char *name, char *out, size_t sz) | ||
| 994 | +{ | ||
| 995 | + size_t i = 0; | ||
| 996 | + for (; *name && i + 1 < sz; name++) { | ||
| 997 | + char c = *name; | ||
| 998 | + if (c == '"' || c == '\\' || c == '\r' || c == '\n') c = '_'; | ||
| 999 | + out[i++] = c; | ||
| 1000 | + } | ||
| 1001 | + out[i] = '\0'; | ||
| 1002 | +} | ||
| 1003 | + | ||
| 1004 | +static void do_raw(const char *raw_path, const char *qs) | ||
| 1005 | +{ | ||
| 1006 | + char canon[PATH_SZ]; | ||
| 1007 | + char name[NAME_SZ]; | ||
| 1008 | + char hn[NAME_SZ]; | ||
| 1009 | + char dl[8]; | ||
| 1010 | + const char *base; | ||
| 1011 | + const char *type; | ||
| 1012 | + int err = 0; | ||
| 1013 | + long long size = -1; | ||
| 1014 | + int want_dl = 0; | ||
| 1015 | + FILE *f; | ||
| 1016 | + static char chunk[IO_CHUNK]; | ||
| 1017 | + | ||
| 1018 | +#if defined(_WIN32) | ||
| 1019 | + { | ||
| 1020 | + WIN32_FILE_ATTRIBUTE_DATA fd; | ||
| 1021 | + if (!resolve_allowed(raw_path, canon, sizeof canon, &err)) { | ||
| 1022 | + json_err(err, err == 403 ? "path not allowed" : (err == 404 ? "path not found" : "bad path")); | ||
| 1023 | + return; | ||
| 1024 | + } | ||
| 1025 | + if (!GetFileAttributesExA(canon, GetFileExInfoStandard, &fd)) { json_err(404, "path not found"); return; } | ||
| 1026 | + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { json_err(400, "not a regular file"); return; } | ||
| 1027 | + { | ||
| 1028 | + ULARGE_INTEGER sz; | ||
| 1029 | + sz.LowPart = fd.nFileSizeLow; sz.HighPart = fd.nFileSizeHigh; | ||
| 1030 | + size = (long long)sz.QuadPart; | ||
| 1031 | + } | ||
| 1032 | + } | ||
| 1033 | +#else | ||
| 1034 | + { | ||
| 1035 | + struct stat st; | ||
| 1036 | + if (!resolve_allowed(raw_path, canon, sizeof canon, &err)) { | ||
| 1037 | + json_err(err, err == 403 ? "path not allowed" : (err == 404 ? "path not found" : "bad path")); | ||
| 1038 | + return; | ||
| 1039 | + } | ||
| 1040 | + if (stat(canon, &st) != 0) { json_err(404, "path not found"); return; } | ||
| 1041 | + if (S_ISDIR(st.st_mode)) { json_err(400, "not a regular file"); return; } | ||
| 1042 | + size = (long long)st.st_size; | ||
| 1043 | + } | ||
| 1044 | +#endif | ||
| 1045 | + | ||
| 1046 | + if (size > RAW_CAP) { json_err(413, "file larger than 64 MiB"); return; } | ||
| 1047 | + | ||
| 1048 | + base = strrchr(canon, SEP); | ||
| 1049 | + str_copy(name, sizeof name, (base && base[1]) ? base + 1 : canon); | ||
| 1050 | + type = guess_type(name); | ||
| 1051 | + header_name(name, hn, sizeof hn); | ||
| 1052 | + | ||
| 1053 | + if (get_query_val(qs, "download", dl, sizeof dl)) | ||
| 1054 | + want_dl = (strcmp(dl, "1") == 0 || strcmp(dl, "true") == 0); | ||
| 1055 | + | ||
| 1056 | + f = fopen(canon, "rb"); | ||
| 1057 | + if (!f) { json_err(403, "cannot open file"); return; } | ||
| 1058 | + | ||
| 1059 | + printf("Content-Type: %s\r\n", type); | ||
| 1060 | + fputs("Cache-Control: no-store\r\n", stdout); | ||
| 1061 | + fputs("X-Content-Type-Options: nosniff\r\n", stdout); | ||
| 1062 | + fputs("Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; " | ||
| 1063 | + "img-src data:\r\n", stdout); | ||
| 1064 | + fputs("X-Frame-Options: SAMEORIGIN\r\n", stdout); | ||
| 1065 | + printf("Content-Disposition: %s; filename=\"%s\"\r\n", | ||
| 1066 | + (want_dl || !is_image_type(type)) ? "attachment" : "inline", hn); | ||
| 1067 | + /* Deliberately no Content-Length - the server owns framing. */ | ||
| 1068 | + fputs("\r\n", stdout); | ||
| 1069 | + | ||
| 1070 | + for (;;) { | ||
| 1071 | + size_t n = fread(chunk, 1, sizeof chunk, f); | ||
| 1072 | + if (n > 0) fwrite(chunk, 1, n, stdout); | ||
| 1073 | + if (n < sizeof chunk) break; | ||
| 1074 | + } | ||
| 1075 | + fclose(f); | ||
| 1076 | + fflush(stdout); | ||
| 1077 | +} | ||
| 1078 | + | ||
| 1079 | +/* ------------------------------------------------------------------ */ | ||
| 1080 | +/* HTML mode */ | ||
| 1081 | +/* ------------------------------------------------------------------ */ | ||
| 1082 | + | ||
| 1083 | +/* Expand the two control-byte placeholders from src/ui.html into the bot | ||
| 1084 | + * theme macros, so the page and the bot palette can never drift. */ | ||
| 1085 | +static void emit_ui(int embed) | ||
| 1086 | +{ | ||
| 1087 | + const char *p = UI_HTML; | ||
| 1088 | + | ||
| 1089 | + while (*p) { | ||
| 1090 | + if (*p == '\001') { | ||
| 1091 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS | ||
| 1092 | + ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);--ac:var(--blue)}" | ||
| 1093 | + "</style>", stdout); | ||
| 1094 | + p++; | ||
| 1095 | + } else if (*p == '\002') { | ||
| 1096 | + fputs(SX_BOT_THEME_HANDOFF, stdout); | ||
| 1097 | + p++; | ||
| 1098 | + } else { | ||
| 1099 | + putchar(*p++); | ||
| 1100 | + } | ||
| 1101 | + } | ||
| 1102 | + (void)embed; | ||
| 1103 | +} | ||
| 1104 | + | ||
| 1105 | +static void mode_html(int embed) | ||
| 1106 | +{ | ||
| 1107 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | ||
| 1108 | + "Cache-Control: no-store\r\n" | ||
| 1109 | + "X-Content-Type-Options: nosniff\r\n" | ||
| 1110 | + "X-Frame-Options: SAMEORIGIN\r\n" | ||
| 1111 | + "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " | ||
| 1112 | + "style-src 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; " | ||
| 1113 | + "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); | ||
| 1114 | + emit_ui(embed); | ||
| 1115 | +} | ||
| 1116 | + | ||
| 1117 | +/* ------------------------------------------------------------------ */ | ||
| 1118 | +/* Entry */ | ||
| 1119 | +/* ------------------------------------------------------------------ */ | ||
| 1120 | + | ||
| 1121 | +static const char *method(void) | ||
| 1122 | +{ | ||
| 1123 | + const char *m = getenv("REQUEST_METHOD"); | ||
| 1124 | + return (m && *m) ? m : "GET"; | ||
| 1125 | +} | ||
| 1126 | + | ||
| 1127 | +int main(int argc, char **argv) | ||
| 1128 | +{ | ||
| 1129 | + const char *qs; | ||
| 1130 | + char action[64]; | ||
| 1131 | + char path[PATH_SZ]; | ||
| 1132 | + | ||
| 1133 | + /* 1. Discovery metadata (unauthenticated so /plugins can probe it) */ | ||
| 1134 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { | ||
| 1135 | + printf("{\"name\":\"%s\",\"desc\":\"%s\"}\n", PLUGIN_NAME, PLUGIN_DESC); | ||
| 1136 | + return 0; | ||
| 1137 | + } | ||
| 1138 | + if (argc > 1 && strcmp(argv[1], "--version") == 0) { | ||
| 1139 | + printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); | ||
| 1140 | + return 0; | ||
| 1141 | + } | ||
| 1142 | + | ||
| 1143 | + require_node_auth(); | ||
| 1144 | + init_roots(); | ||
| 1145 | + | ||
| 1146 | + qs = getenv("QUERY_STRING"); | ||
| 1147 | + if (!qs) qs = ""; | ||
| 1148 | + | ||
| 1149 | + action[0] = '\0'; | ||
| 1150 | + get_query_val(qs, "action", action, sizeof action); | ||
| 1151 | + | ||
| 1152 | + /* 2. Anything that names an action or asks for JSON is API. */ | ||
| 1153 | + if (action[0] || strstr(qs, "format=json")) { | ||
| 1154 | + char fmt[32]; | ||
| 1155 | + if (!action[0]) { | ||
| 1156 | + if (get_query_val(qs, "format", fmt, sizeof fmt) && strcmp(fmt, "json") == 0) | ||
| 1157 | + str_copy(action, sizeof action, "roots"); | ||
| 1158 | + } | ||
| 1159 | + | ||
| 1160 | + path[0] = '\0'; | ||
| 1161 | + get_query_val(qs, "path", path, sizeof path); | ||
| 1162 | + | ||
| 1163 | + if (strcmp(action, "roots") == 0) { | ||
| 1164 | + do_roots(); | ||
| 1165 | + } else if (strcmp(action, "ls") == 0) { | ||
| 1166 | + do_ls(path, qs); | ||
| 1167 | + } else if (strcmp(action, "read") == 0) { | ||
| 1168 | + do_read(path); | ||
| 1169 | + } else if (strcmp(action, "raw") == 0) { | ||
| 1170 | + do_raw(path, qs); | ||
| 1171 | + } else { | ||
| 1172 | + json_err(400, "unknown action"); | ||
| 1173 | + } | ||
| 1174 | + return 0; | ||
| 1175 | + } | ||
| 1176 | + | ||
| 1177 | + /* 3. Everything else is the page. */ | ||
| 1178 | + { | ||
| 1179 | + int embed = strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL; | ||
| 1180 | + mode_html(embed); | ||
| 1181 | + } | ||
| 1182 | + (void)method; | ||
| 1183 | + return 0; | ||
| 1184 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..41c06e7 | index 0000000..41c06e7 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui.html | +++ b/src/ui.html | ||
| @@ -0,0 +1,614 @@ | @@ -0,0 +1,614 @@ | ||
| 1 | +<!DOCTYPE html> | ||
| 2 | +<html lang="en"><head><meta charset="utf-8"> | ||
| 3 | +<meta name="viewport" content="width=device-width,initial-scale=1"> | ||
| 4 | +<title>files</title> | ||
| 5 | +<!--TOKENS--> | ||
| 6 | +<style> | ||
| 7 | +*{box-sizing:border-box} | ||
| 8 | +html,body{margin:0;height:100%} | ||
| 9 | +body{background:var(--bg);color:var(--text);font-family:var(--font); | ||
| 10 | + font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased;overflow:hidden} | ||
| 11 | +#app{display:grid;grid-template-columns:252px minmax(0,1fr);height:100%;min-height:0} | ||
| 12 | +.pane{min-width:0;min-height:0;display:flex;flex-direction:column} | ||
| 13 | +#side{background:var(--bg-2);border-right:1px solid var(--line)} | ||
| 14 | +.side-hd{display:flex;align-items:center;gap:8px;padding:12px 12px 8px} | ||
| 15 | +.brand{font-size:12px;font-weight:700;letter-spacing:.09em;text-transform:uppercase; | ||
| 16 | + color:var(--text-2);flex:1} | ||
| 17 | +.side-ft{display:flex;align-items:center;gap:8px;padding:8px 12px; | ||
| 18 | + border-top:1px solid var(--line);font-size:11px;color:var(--text-2)} | ||
| 19 | +.side-ft .grow{flex:1} | ||
| 20 | +.side-lbl{font-size:10.5px;font-weight:700;letter-spacing:.1em;text-transform:uppercase; | ||
| 21 | + color:var(--text-2);padding:4px 14px 6px} | ||
| 22 | +.icon{display:inline-flex;align-items:center;justify-content:center;gap:6px; | ||
| 23 | + background:var(--surface-2);border:1px solid var(--line);color:var(--text); | ||
| 24 | + border-radius:9px;width:30px;height:30px;padding:0;cursor:pointer;font-family:inherit; | ||
| 25 | + font-size:12px;font-weight:600;flex:0 0 auto} | ||
| 26 | +.icon:hover{background:var(--surface-hover);border-color:var(--line-2)} | ||
| 27 | +.icon:active{transform:scale(.96)} | ||
| 28 | +.icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor; | ||
| 29 | + stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round} | ||
| 30 | +.icon.on{background:var(--surface-2);border-color:var(--line-2);color:var(--blue)} | ||
| 31 | +.rootlist{flex:0 0 auto;padding:0 8px 10px;border-bottom:1px solid var(--line)} | ||
| 32 | +.root{display:flex;align-items:center;gap:9px;width:100%;text-align:left; | ||
| 33 | + background:transparent;border:0;border-radius:9px;padding:8px 10px;color:var(--text); | ||
| 34 | + cursor:pointer;font-family:inherit;font-size:13px;margin-bottom:2px} | ||
| 35 | +.root:hover{background:var(--surface-hover)} | ||
| 36 | +.root.sel{background:var(--surface-2);box-shadow:inset 2px 0 0 var(--blue)} | ||
| 37 | +.root svg{width:14px;height:14px;flex:0 0 auto;fill:none;stroke:currentColor;stroke-width:1.7; | ||
| 38 | + stroke-linecap:round;stroke-linejoin:round;color:var(--text-2)} | ||
| 39 | +.root .rl{min-width:0;flex:1} | ||
| 40 | +.root .rl .n{display:block;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | ||
| 41 | +.root .rl .p{display:block;font-size:10.5px;color:var(--text-2);overflow:hidden; | ||
| 42 | + text-overflow:ellipsis;white-space:nowrap;font-family:var(--mono)} | ||
| 43 | +#main{background:var(--bg);min-width:0} | ||
| 44 | +.toolbar{display:flex;align-items:center;gap:7px;padding:10px 14px; | ||
| 45 | + border-bottom:1px solid var(--line);flex:0 0 auto;min-width:0} | ||
| 46 | +.crumbs{flex:1 1 auto;min-width:0;display:flex;align-items:center;gap:2px; | ||
| 47 | + overflow-x:auto;scrollbar-width:none;white-space:nowrap} | ||
| 48 | +.crumbs::-webkit-scrollbar{display:none} | ||
| 49 | +.crumb{background:transparent;border:0;color:var(--text-2);font-family:var(--mono); | ||
| 50 | + font-size:12px;padding:3px 5px;border-radius:6px;cursor:pointer;flex:0 0 auto} | ||
| 51 | +.crumb:hover{background:var(--surface-hover);color:var(--text)} | ||
| 52 | +.crumb.last{color:var(--text);font-weight:600} | ||
| 53 | +.crumb .sep{color:var(--text-2);opacity:.6;padding:0 1px} | ||
| 54 | +.body{flex:1 1 auto;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.15fr); | ||
| 55 | + min-height:0} | ||
| 56 | +.body.noprev{grid-template-columns:minmax(0,1fr)} | ||
| 57 | +.listwrap{min-width:0;min-height:0;display:flex;flex-direction:column; | ||
| 58 | + border-right:1px solid var(--line)} | ||
| 59 | +.entries{flex:1 1 auto;overflow-y:auto;padding:6px 8px 20px} | ||
| 60 | +.row{display:flex;align-items:center;gap:9px;width:100%;text-align:left; | ||
| 61 | + background:transparent;border:0;border-radius:9px;padding:7px 9px;color:var(--text); | ||
| 62 | + cursor:pointer;font-family:inherit;font-size:13px} | ||
| 63 | +.row:hover{background:var(--surface-hover)} | ||
| 64 | +.row.sel{background:var(--surface-2);box-shadow:inset 2px 0 0 var(--blue)} | ||
| 65 | +.row .ico{width:16px;height:16px;flex:0 0 auto;color:var(--text-2);display:flex} | ||
| 66 | +.row .ico svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:1.7; | ||
| 67 | + stroke-linecap:round;stroke-linejoin:round} | ||
| 68 | +.row.dir .ico{color:var(--blue)} | ||
| 69 | +.row .nm{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | ||
| 70 | +.row .mt{flex:0 0 auto;font-family:var(--mono);font-size:11px;color:var(--text-2)} | ||
| 71 | +.empty{padding:22px 14px;color:var(--text-2);font-size:12.5px;text-align:center} | ||
| 72 | +.hidden{display:none!important} | ||
| 73 | +.preview{min-width:0;min-height:0;display:flex;flex-direction:column} | ||
| 74 | +.prev-hd{display:flex;align-items:center;gap:8px;padding:9px 14px; | ||
| 75 | + border-bottom:1px solid var(--line);flex:0 0 auto;min-width:0} | ||
| 76 | +.prev-hd .nm{flex:1 1 auto;min-width:0;font-weight:600;font-size:13px; | ||
| 77 | + overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | ||
| 78 | +.prev-hd .mt{font-family:var(--mono);font-size:11px;color:var(--text-2);white-space:nowrap} | ||
| 79 | +.prev-body{flex:1 1 auto;overflow:auto;min-height:0} | ||
| 80 | +.codetxt{margin:0;padding:0;font-family:var(--mono);font-size:12.5px;line-height:1.6; | ||
| 81 | + display:grid;grid-template-columns:auto minmax(0,1fr);min-width:0} | ||
| 82 | +.codetxt .ln{color:var(--text-2);text-align:right;padding:0 10px 0 14px; | ||
| 83 | + user-select:none;background:var(--bg-2);border-right:1px solid var(--line)} | ||
| 84 | +.codetxt .tx{padding:0 14px;white-space:pre-wrap;word-break:break-word; | ||
| 85 | + font-family:var(--mono);font-size:12.5px} | ||
| 86 | +.md{padding:16px 20px 40px;max-width:860px} | ||
| 87 | +.md h1,.md h2,.md h3,.md h4{line-height:1.25;margin:18px 0 8px;font-weight:650} | ||
| 88 | +.md h1{font-size:21px}.md h2{font-size:18px}.md h3{font-size:15.5px}.md h4{font-size:14px} | ||
| 89 | +.md p{margin:0 0 11px} | ||
| 90 | +.md ul,.md ol{margin:0 0 11px;padding-left:22px} | ||
| 91 | +.md li{margin:3px 0} | ||
| 92 | +.md code{font-family:var(--mono);font-size:12px;background:var(--code-bg); | ||
| 93 | + padding:1px 5px;border-radius:5px} | ||
| 94 | +.md pre{background:var(--code-bg);border:1px solid var(--line);border-radius:10px; | ||
| 95 | + padding:11px 13px;overflow-x:auto;margin:0 0 12px} | ||
| 96 | +.md pre code{background:transparent;padding:0;font-size:12px;line-height:1.55} | ||
| 97 | +.md hr{border:0;border-top:1px solid var(--line);margin:16px 0} | ||
| 98 | +.md a{color:var(--blue);text-decoration:none;font-weight:600} | ||
| 99 | +.md a:hover{text-decoration:underline} | ||
| 100 | +.md blockquote{margin:0 0 12px;padding:2px 0 2px 13px;border-left:3px solid var(--line-2); | ||
| 101 | + color:var(--text-2)} | ||
| 102 | +.imgwrap{padding:16px;display:flex;align-items:flex-start;justify-content:center} | ||
| 103 | +.imgwrap img{max-width:100%;height:auto;border-radius:10px;border:1px solid var(--line); | ||
| 104 | + background:var(--bg-2)} | ||
| 105 | +.note{padding:16px 18px;color:var(--text-2);font-size:12.5px} | ||
| 106 | +.welcome{flex:1 1 auto;display:flex;flex-direction:column;align-items:center; | ||
| 107 | + justify-content:center;gap:10px;color:var(--text-2);font-size:13px;padding:24px; | ||
| 108 | + text-align:center;min-height:0} | ||
| 109 | +.welcome svg{width:34px;height:34px;fill:none;stroke:currentColor;stroke-width:1.4; | ||
| 110 | + stroke-linecap:round;stroke-linejoin:round;opacity:.55} | ||
| 111 | +.toast{position:fixed;left:50%;bottom:18px;transform:translateX(-50%); | ||
| 112 | + background:var(--modal-bg);border:1px solid var(--line-2);color:var(--text); | ||
| 113 | + padding:8px 14px;border-radius:999px;font-size:12.5px;box-shadow:var(--shadow-lg); | ||
| 114 | + opacity:0;pointer-events:none;transition:opacity .16s var(--ease);z-index:9; | ||
| 115 | + max-width:calc(100% - 24px);overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | ||
| 116 | +.toast.show{opacity:1} | ||
| 117 | +@media (max-width:1100px){ | ||
| 118 | + #app{grid-template-columns:216px minmax(0,1fr)} | ||
| 119 | + .body{grid-template-columns:minmax(0,1fr) minmax(0,1fr)} | ||
| 120 | +} | ||
| 121 | +@media (max-width:820px){ | ||
| 122 | + body{overflow:hidden} | ||
| 123 | + #app{grid-template-columns:minmax(0,1fr)} | ||
| 124 | + #side,#main{grid-column:1;grid-row:1} | ||
| 125 | + #app[data-view="browse"] #side{display:none} | ||
| 126 | + #app[data-view="roots"] #main{display:none} | ||
| 127 | + .body{grid-template-columns:minmax(0,1fr)} | ||
| 128 | + #app[data-view="browse"] .body{grid-template-columns:minmax(0,1fr)} | ||
| 129 | + #app[data-view="browse"] .preview{display:none} | ||
| 130 | + #app[data-view="preview"] .listwrap{display:none} | ||
| 131 | + #app[data-view="preview"] .body{grid-template-columns:minmax(0,1fr)} | ||
| 132 | + .back{display:inline-flex!important} | ||
| 133 | + .toolbar{padding:8px 10px;gap:6px} | ||
| 134 | + .md{padding:12px 14px 32px} | ||
| 135 | + .codetxt .tx{padding:0 10px} | ||
| 136 | +} | ||
| 137 | +@media (min-width:821px){.back{display:none!important}} | ||
| 138 | +</style> | ||
| 139 | +</head><body> | ||
| 140 | +<div id="app" data-view="roots"> | ||
| 141 | + <aside id="side" class="pane"> | ||
| 142 | + <div class="side-hd"> | ||
| 143 | + <span class="brand">files</span> | ||
| 144 | + <button id="btnUp" class="icon" title="Up one level" aria-label="Up one level"> | ||
| 145 | + <svg viewBox="0 0 24 24"><path d="M12 19V5M5 12l7-7 7 7"/></svg></button> | ||
| 146 | + <button id="btnRefresh" class="icon" title="Refresh" aria-label="Refresh"> | ||
| 147 | + <svg viewBox="0 0 24 24"><path d="M20 11a8 8 0 1 0-2.3 5.7"/><path d="M20 4v7h-7"/></svg></button> | ||
| 148 | + </div> | ||
| 149 | + <div class="side-lbl">Roots</div> | ||
| 150 | + <div id="roots" class="rootlist"></div> | ||
| 151 | + <div class="side-ft"> | ||
| 152 | + <span id="count">0 items</span><span class="grow"></span> | ||
| 153 | + <button id="btnHidden" class="icon" title="Show hidden files" aria-label="Show hidden files"> | ||
| 154 | + <svg viewBox="0 0 24 24"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"/><circle cx="12" cy="12" r="3"/></svg></button> | ||
| 155 | + <button id="btnTheme" class="icon embed-hide" title="Toggle appearance" aria-label="Toggle appearance"> | ||
| 156 | + <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="4.5"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4"/></svg></button> | ||
| 157 | + </div> | ||
| 158 | + </aside> | ||
| 159 | + <main id="main" class="pane"> | ||
| 160 | + <div class="toolbar"> | ||
| 161 | + <button id="btnBack" class="icon back" title="Back to list" aria-label="Back to list"> | ||
| 162 | + <svg viewBox="0 0 24 24"><path d="M15 5l-7 7 7 7"/></svg></button> | ||
| 163 | + <div id="crumbs" class="crumbs"></div> | ||
| 164 | + <button id="btnDownload" class="icon" title="Download file" aria-label="Download file"> | ||
| 165 | + <svg viewBox="0 0 24 24"><path d="M12 3v12M7 11l5 5 5-5M4 21h16"/></svg></button> | ||
| 166 | + </div> | ||
| 167 | + <div id="body" class="body"> | ||
| 168 | + <div class="listwrap"> | ||
| 169 | + <div id="entries" class="entries"></div> | ||
| 170 | + <div id="empty" class="empty hidden">This directory is empty.</div> | ||
| 171 | + </div> | ||
| 172 | + <div id="preview" class="preview"> | ||
| 173 | + <div id="prevHd" class="prev-hd hidden"> | ||
| 174 | + <span id="prevName" class="nm"></span> | ||
| 175 | + <span id="prevMeta" class="mt"></span> | ||
| 176 | + </div> | ||
| 177 | + <div id="prevBody" class="prev-body"> | ||
| 178 | + <div id="welcome" class="welcome"> | ||
| 179 | + <svg viewBox="0 0 24 24"><path d="M3 7h6l2 2h10v11H3z"/></svg> | ||
| 180 | + <div>Pick a root, then open a file to preview it.</div> | ||
| 181 | + <div style="font-size:11.5px">Arrows move · Enter opens · Backspace goes up</div> | ||
| 182 | + </div> | ||
| 183 | + </div> | ||
| 184 | + </div> | ||
| 185 | + </div> | ||
| 186 | + </main> | ||
| 187 | +</div> | ||
| 188 | +<div id="toast" class="toast"></div> | ||
| 189 | +<script> | ||
| 190 | +(function(){ | ||
| 191 | +"use strict"; | ||
| 192 | +var app=document.getElementById('app'); | ||
| 193 | +var rootsEl=document.getElementById('roots'); | ||
| 194 | +var entriesEl=document.getElementById('entries'); | ||
| 195 | +var emptyEl=document.getElementById('empty'); | ||
| 196 | +var countEl=document.getElementById('count'); | ||
| 197 | +var crumbsEl=document.getElementById('crumbs'); | ||
| 198 | +var bodyEl=document.getElementById('body'); | ||
| 199 | +var prevEl=document.getElementById('preview'); | ||
| 200 | +var prevHd=document.getElementById('prevHd'); | ||
| 201 | +var prevName=document.getElementById('prevName'); | ||
| 202 | +var prevMeta=document.getElementById('prevMeta'); | ||
| 203 | +var prevBody=document.getElementById('prevBody'); | ||
| 204 | +var toastEl=document.getElementById('toast'); | ||
| 205 | +var btnHidden=document.getElementById('btnHidden'); | ||
| 206 | +var btnDownload=document.getElementById('btnDownload'); | ||
| 207 | + | ||
| 208 | +var q=new URLSearchParams(location.search); | ||
| 209 | +var node=q.get('node')||''; | ||
| 210 | +var sid=q.get('id')||''; | ||
| 211 | +var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))|| | ||
| 212 | + localStorage.getItem('bot_active_pwd')||''; | ||
| 213 | +var HUB=q.get('plugin')||''; | ||
| 214 | + | ||
| 215 | +var roots=[], entries=[], curPath='', curParent=null, curRoot=null; | ||
| 216 | +var selIndex=-1, showHidden=false, curFile=null; | ||
| 217 | + | ||
| 218 | +/* Two call routes, and getting this wrong is the most common plugin bug: | ||
| 219 | + * page served through the hub (bot.scorpiox.net/plugins?plugin=plugin_files&node=..) | ||
| 220 | + * -> call the hub proxy back: /plugins?plugin=plugin_files&action=.. | ||
| 221 | + * opened directly on the node | ||
| 222 | + * -> the plugin itself is the route: /plugin_files?action=.. | ||
| 223 | + * Calling /plugins?plugin= on the node returns the discovery list, not us. */ | ||
| 224 | +function url(action,extra){ | ||
| 225 | + var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_files')+ | ||
| 226 | + '?action='+encodeURIComponent(action)+ | ||
| 227 | + (extra?('&'+extra):'')+ | ||
| 228 | + (node?'&node='+encodeURIComponent(node):'')+ | ||
| 229 | + (sid?'&id='+encodeURIComponent(sid):'')+ | ||
| 230 | + (pwd?'&pwd='+encodeURIComponent(pwd):''); | ||
| 231 | + return u; | ||
| 232 | +} | ||
| 233 | +function hdr(extra){ | ||
| 234 | + var h=extra||{}; | ||
| 235 | + if(pwd)h['X-Bot-Password']=pwd; | ||
| 236 | + return h; | ||
| 237 | +} | ||
| 238 | +function api(action,extra){ | ||
| 239 | + return fetch(url(action,extra),{headers:hdr({})}).then(function(r){ | ||
| 240 | + if(!r.ok)throw new Error('HTTP '+r.status); | ||
| 241 | + return r.json(); | ||
| 242 | + }); | ||
| 243 | +} | ||
| 244 | + | ||
| 245 | +function toast(msg){ | ||
| 246 | + toastEl.textContent=msg; | ||
| 247 | + toastEl.classList.add('show'); | ||
| 248 | + clearTimeout(toast._t); | ||
| 249 | + toast._t=setTimeout(function(){toastEl.classList.remove('show');},2000); | ||
| 250 | +} | ||
| 251 | +function setView(v){app.setAttribute('data-view',v);} | ||
| 252 | + | ||
| 253 | +function fmtSize(n){ | ||
| 254 | + if(n===null||n===undefined)return ''; | ||
| 255 | + if(n<1024)return n+' B'; | ||
| 256 | + if(n<1048576)return (n/1024).toFixed(1)+' KB'; | ||
| 257 | + if(n<1073741824)return (n/1048576).toFixed(1)+' MB'; | ||
| 258 | + return (n/1073741824).toFixed(1)+' GB'; | ||
| 259 | +} | ||
| 260 | +function fmtTime(iso){ | ||
| 261 | + if(!iso)return ''; | ||
| 262 | + try{ | ||
| 263 | + var d=new Date(iso),now=new Date(),diff=(now-d)/1000; | ||
| 264 | + if(diff<60)return 'just now'; | ||
| 265 | + if(diff<3600)return Math.floor(diff/60)+'m ago'; | ||
| 266 | + if(diff<86400)return Math.floor(diff/3600)+'h ago'; | ||
| 267 | + if(diff<604800)return Math.floor(diff/86400)+'d ago'; | ||
| 268 | + return d.toLocaleDateString(); | ||
| 269 | + }catch(e){return ''} | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +var SVG={ | ||
| 273 | + dir:'<svg viewBox="0 0 24 24"><path d="M3 7h6l2 2h10v11H3z"/></svg>', | ||
| 274 | + file:'<svg viewBox="0 0 24 24"><path d="M6 3h9l5 5v13H6z"/><path d="M14 3v5h5"/></svg>', | ||
| 275 | + link:'<svg viewBox="0 0 24 24"><path d="M10 13a4 4 0 0 0 6 .5l2.5-2.5a4 4 0 0 0-6-6L11 6.5"/><path d="M14 11a4 4 0 0 0-6-.5L5.5 13a4 4 0 0 0 6 6L13 17.5"/></svg>', | ||
| 276 | + img:'<svg viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="8.5" cy="10" r="1.6"/><path d="M21 16l-5-5-6 6"/></svg>', | ||
| 277 | + root:'<svg viewBox="0 0 24 24"><path d="M3 7h6l2 2h10v11H3z"/></svg>' | ||
| 278 | +}; | ||
| 279 | + | ||
| 280 | +function renderRoots(){ | ||
| 281 | + while(rootsEl.firstChild)rootsEl.removeChild(rootsEl.firstChild); | ||
| 282 | + roots.forEach(function(r,i){ | ||
| 283 | + var b=document.createElement('button'); | ||
| 284 | + b.className='root'+(curRoot===r.path?' sel':''); | ||
| 285 | + var ic=document.createElement('span');ic.innerHTML=SVG.root; | ||
| 286 | + var wrap=document.createElement('span');wrap.className='rl'; | ||
| 287 | + var n=document.createElement('span');n.className='n';n.textContent=r.name; | ||
| 288 | + var p=document.createElement('span');p.className='p';p.textContent=r.path; | ||
| 289 | + wrap.appendChild(n);wrap.appendChild(p); | ||
| 290 | + b.appendChild(ic);b.appendChild(wrap); | ||
| 291 | + b.onclick=function(){openDir(r.path);setView('browse');}; | ||
| 292 | + rootsEl.appendChild(b); | ||
| 293 | + }); | ||
| 294 | +} | ||
| 295 | + | ||
| 296 | +function renderCrumbs(){ | ||
| 297 | + while(crumbsEl.firstChild)crumbsEl.removeChild(crumbsEl.firstChild); | ||
| 298 | + if(!curPath){ | ||
| 299 | + var hint=document.createElement('span');hint.className='crumb last'; | ||
| 300 | + hint.textContent='Select a root';crumbsEl.appendChild(hint);return; | ||
| 301 | + } | ||
| 302 | + var base=curRoot||''; | ||
| 303 | + var rel=curPath; | ||
| 304 | + if(base&&curPath.indexOf(base)===0)rel=curPath.slice(base.length); | ||
| 305 | + var parts=rel.split(/[\/\\]+/).filter(function(s){return s.length;}); | ||
| 306 | + var b0=document.createElement('button'); | ||
| 307 | + b0.className='crumb'+(parts.length?'':' last'); | ||
| 308 | + b0.textContent=base.split(/[\/\\]+/).filter(Boolean).pop()||base||'/'; | ||
| 309 | + b0.title=base; | ||
| 310 | + b0.onclick=function(){openDir(base);}; | ||
| 311 | + crumbsEl.appendChild(b0); | ||
| 312 | + var acc=base; | ||
| 313 | + parts.forEach(function(p,i){ | ||
| 314 | + var sp=document.createElement('span');sp.className='sep';sp.textContent='/'; | ||
| 315 | + crumbsEl.appendChild(sp); | ||
| 316 | + acc+=(acc&&acc[acc.length-1]!=='/'&&acc[acc.length-1]!=='\\'?'/':'')+p; | ||
| 317 | + var b=document.createElement('button'); | ||
| 318 | + b.className='crumb'+(i===parts.length-1?' last':''); | ||
| 319 | + b.textContent=p;b.title=acc; | ||
| 320 | + var target=acc; | ||
| 321 | + b.onclick=function(){openDir(target);}; | ||
| 322 | + crumbsEl.appendChild(b); | ||
| 323 | + }); | ||
| 324 | +} | ||
| 325 | + | ||
| 326 | +function isImage(name){ | ||
| 327 | + return /\.(png|jpe?g|gif|webp|bmp|ico|svg)$/i.test(name||''); | ||
| 328 | +} | ||
| 329 | +function isMarkdown(name){ | ||
| 330 | + return /\.(md|markdown)$/i.test(name||''); | ||
| 331 | +} | ||
| 332 | +function isTextish(name){ | ||
| 333 | + return /\.(txt|md|markdown|json|js|ts|css|html?|c|h|cpp|hpp|py|sh|yml|yaml|toml|ini|conf|log|csv|xml|sql|go|rs|java|rb|php|gitignore|env)$/i.test(name||''); | ||
| 334 | +} | ||
| 335 | + | ||
| 336 | +function renderEntries(){ | ||
| 337 | + while(entriesEl.firstChild)entriesEl.removeChild(entriesEl.firstChild); | ||
| 338 | + if(selIndex>=entries.length)selIndex=entries.length?entries.length-1:-1; | ||
| 339 | + entries.forEach(function(e,i){ | ||
| 340 | + var b=document.createElement('button'); | ||
| 341 | + b.className='row'+(e.type==='dir'?' dir':'')+(i===selIndex?' sel':''); | ||
| 342 | + var ic=document.createElement('span');ic.className='ico'; | ||
| 343 | + ic.innerHTML = e.type==='dir'?SVG.dir : (isImage(e.name)?SVG.img : (e.type==='link'?SVG.link:SVG.file)); | ||
| 344 | + var nm=document.createElement('span');nm.className='nm';nm.textContent=e.name; | ||
| 345 | + var mt=document.createElement('span');mt.className='mt'; | ||
| 346 | + mt.textContent=(e.type==='dir'?'':fmtSize(e.size)); | ||
| 347 | + b.appendChild(ic);b.appendChild(nm);b.appendChild(mt); | ||
| 348 | + b.onclick=function(){selIndex=i;renderEntries();activate(e);}; | ||
| 349 | + entriesEl.appendChild(b); | ||
| 350 | + }); | ||
| 351 | + emptyEl.classList.toggle('hidden',entries.length>0); | ||
| 352 | + countEl.textContent=entries.length+(entries.length===1?' item':' items'); | ||
| 353 | + var sel=entriesEl.querySelector('.row.sel'); | ||
| 354 | + if(sel&&sel.scrollIntoView)sel.scrollIntoView({block:'nearest'}); | ||
| 355 | +} | ||
| 356 | + | ||
| 357 | +function openDir(path){ | ||
| 358 | + return api('ls','path='+encodeURIComponent(path)+(showHidden?'&hidden=1':'')) | ||
| 359 | + .then(function(d){ | ||
| 360 | + if(!d||!d.ok)throw new Error((d&&d.error)||'failed'); | ||
| 361 | + curPath=d.path;curParent=d.parent;curRoot=d.root; | ||
| 362 | + entries=d.entries||[];selIndex=entries.length?0:-1; | ||
| 363 | + renderCrumbs();renderEntries(); | ||
| 364 | + if(!entries.length){clearPreview();} | ||
| 365 | + else if(window.matchMedia('(max-width:820px)').matches){setView('browse');} | ||
| 366 | + return d; | ||
| 367 | + }).catch(function(e){toast('Cannot open folder: '+e.message);}); | ||
| 368 | +} | ||
| 369 | + | ||
| 370 | +function clearPreview(){ | ||
| 371 | + prevHd.classList.add('hidden'); | ||
| 372 | + while(prevBody.firstChild)prevBody.removeChild(prevBody.firstChild); | ||
| 373 | + var w=document.createElement('div');w.className='welcome'; | ||
| 374 | + w.innerHTML='<svg viewBox="0 0 24 24"><path d="M3 7h6l2 2h10v11H3z"/></svg>'+ | ||
| 375 | + '<div>Pick a root, then open a file to preview it.</div>'+ | ||
| 376 | + '<div style="font-size:11.5px">Arrows move · Enter opens · Backspace goes up</div>'; | ||
| 377 | + prevBody.appendChild(w); | ||
| 378 | + curFile=null; | ||
| 379 | + btnDownload.classList.add('hidden'); | ||
| 380 | +} | ||
| 381 | + | ||
| 382 | +function activate(e){ | ||
| 383 | + if(e.type==='dir'){openDir(joinPath(curPath,e.name));setView('browse');return;} | ||
| 384 | + previewFile(joinPath(curPath,e.name),e); | ||
| 385 | +} | ||
| 386 | +function joinPath(dir,name){ | ||
| 387 | + if(!dir)return name; | ||
| 388 | + var last=dir[dir.length-1]; | ||
| 389 | + return dir+(last==='/'||last==='\\'?'':'/')+name; | ||
| 390 | +} | ||
| 391 | + | ||
| 392 | +function setHd(name,meta){ | ||
| 393 | + prevHd.classList.remove('hidden'); | ||
| 394 | + prevName.textContent=name; | ||
| 395 | + prevMeta.textContent=meta||''; | ||
| 396 | + btnDownload.classList.remove('hidden'); | ||
| 397 | +} | ||
| 398 | + | ||
| 399 | +function previewFile(path,ent){ | ||
| 400 | + curFile=path; | ||
| 401 | + setView('preview'); | ||
| 402 | + prevHd.classList.remove('hidden'); | ||
| 403 | + prevName.textContent=ent&&ent.name?ent.name:path.split(/[\/\\]/).pop(); | ||
| 404 | + prevMeta.textContent=ent?fmtSize(ent.size):''; | ||
| 405 | + btnDownload.classList.remove('hidden'); | ||
| 406 | + while(prevBody.firstChild)prevBody.removeChild(prevBody.firstChild); | ||
| 407 | + prevBody.scrollTop=0; | ||
| 408 | + | ||
| 409 | + var name=prevName.textContent; | ||
| 410 | + if(isImage(name)){ | ||
| 411 | + var wrap=document.createElement('div');wrap.className='imgwrap'; | ||
| 412 | + var img=document.createElement('img'); | ||
| 413 | + img.alt=name; | ||
| 414 | + img.src=url('raw','path='+encodeURIComponent(path)); | ||
| 415 | + img.onerror=function(){ | ||
| 416 | + wrap.innerHTML=''; | ||
| 417 | + var n=document.createElement('div');n.className='note'; | ||
| 418 | + n.textContent='This image could not be displayed.'; | ||
| 419 | + wrap.appendChild(n); | ||
| 420 | + }; | ||
| 421 | + wrap.appendChild(img);prevBody.appendChild(wrap); | ||
| 422 | + return; | ||
| 423 | + } | ||
| 424 | + | ||
| 425 | + api('read','path='+encodeURIComponent(path)).then(function(d){ | ||
| 426 | + if(!d||!d.ok)throw new Error((d&&d.error)||'failed'); | ||
| 427 | + prevMeta.textContent=fmtSize(d.size)+(d.truncated?' (first 1 MB)':''); | ||
| 428 | + if(d.binary){ | ||
| 429 | + var n=document.createElement('div');n.className='note'; | ||
| 430 | + n.textContent='Binary file ('+fmtSize(d.size)+') - use Download to inspect it locally.'; | ||
| 431 | + prevBody.appendChild(n);return; | ||
| 432 | + } | ||
| 433 | + if(!isTextish(name)&&!isMarkdown(name)){ | ||
| 434 | + prevMeta.textContent=fmtSize(d.size)+(d.truncated?' (first 1 MB)':'')+' · plain text'; | ||
| 435 | + } | ||
| 436 | + if(isMarkdown(name))renderMarkdown(d.text||'',prevBody); | ||
| 437 | + else renderCode(d.text||'',prevBody); | ||
| 438 | + }).catch(function(e){ | ||
| 439 | + while(prevBody.firstChild)prevBody.removeChild(prevBody.firstChild); | ||
| 440 | + var n=document.createElement('div');n.className='note'; | ||
| 441 | + n.textContent='Cannot preview this file: '+e.message; | ||
| 442 | + prevBody.appendChild(n); | ||
| 443 | + }); | ||
| 444 | +} | ||
| 445 | + | ||
| 446 | +/* Line numbers + text. Every line is a text node, so file content can never | ||
| 447 | + * become markup. */ | ||
| 448 | +function renderCode(text,host){ | ||
| 449 | + var lines=text.split('\n'); | ||
| 450 | + if(lines.length&&lines[lines.length-1]==='')lines.pop(); | ||
| 451 | + var pre=document.createElement('div');pre.className='codetxt'; | ||
| 452 | + var ln=document.createElement('div');ln.className='ln'; | ||
| 453 | + var tx=document.createElement('div');tx.className='tx'; | ||
| 454 | + var nums=[],body=[]; | ||
| 455 | + for(var i=0;i<lines.length;i++){nums.push(String(i+1));body.push(lines[i]);} | ||
| 456 | + ln.textContent=nums.join('\n'); | ||
| 457 | + tx.textContent=body.join('\n'); | ||
| 458 | + pre.appendChild(ln);pre.appendChild(tx); | ||
| 459 | + host.appendChild(pre); | ||
| 460 | +} | ||
| 461 | + | ||
| 462 | +/* Tiny markdown renderer: headings, lists, fenced code, blockquote, hr, | ||
| 463 | + * inline code/bold/italic/links. No CDN, no innerHTML with file content. */ | ||
| 464 | +function renderMarkdown(text,host){ | ||
| 465 | + var box=document.createElement('div');box.className='md'; | ||
| 466 | + var lines=text.split('\n'); | ||
| 467 | + var i=0,para=[],list=null; | ||
| 468 | + | ||
| 469 | + function flushPara(){ | ||
| 470 | + if(!para.length)return; | ||
| 471 | + var p=document.createElement('p'); | ||
| 472 | + inline(para.join(' '),p); | ||
| 473 | + box.appendChild(p);para=[]; | ||
| 474 | + } | ||
| 475 | + function flushList(){ | ||
| 476 | + if(!list)return; | ||
| 477 | + box.appendChild(list);list=null; | ||
| 478 | + } | ||
| 479 | + function inline(s,parent){ | ||
| 480 | + var re=/(`[^`]*`)|(\*\*[^*]+\*\*)|(\*[^*]+\*)|(\[[^\]]+\]\([^)]+\))/g; | ||
| 481 | + var last=0,m; | ||
| 482 | + while((m=re.exec(s))!==null){ | ||
| 483 | + if(m.index>last)parent.appendChild(document.createTextNode(s.slice(last,m.index))); | ||
| 484 | + var tok=m[0]; | ||
| 485 | + if(tok[0]==='`'){ | ||
| 486 | + var c=document.createElement('code');c.textContent=tok.slice(1,-1);parent.appendChild(c); | ||
| 487 | + }else if(tok.slice(0,2)==='**'){ | ||
| 488 | + var b=document.createElement('strong');b.textContent=tok.slice(2,-2);parent.appendChild(b); | ||
| 489 | + }else if(tok[0]==='*'){ | ||
| 490 | + var em=document.createElement('em');em.textContent=tok.slice(1,-1);parent.appendChild(em); | ||
| 491 | + }else{ | ||
| 492 | + var mm=/^\[([^\]]+)\]\(([^)]+)\)$/.exec(tok); | ||
| 493 | + if(mm&&/^(https?:\/\/|\/|#|mailto:)/i.test(mm[2])){ | ||
| 494 | + var a=document.createElement('a'); | ||
| 495 | + a.textContent=mm[1];a.href=mm[2]; | ||
| 496 | + a.target='_blank';a.rel='noopener noreferrer'; | ||
| 497 | + parent.appendChild(a); | ||
| 498 | + }else if(mm){ | ||
| 499 | + parent.appendChild(document.createTextNode(mm[1])); | ||
| 500 | + } | ||
| 501 | + } | ||
| 502 | + last=m.index+tok.length; | ||
| 503 | + } | ||
| 504 | + if(last<s.length)parent.appendChild(document.createTextNode(s.slice(last))); | ||
| 505 | + } | ||
| 506 | + | ||
| 507 | + while(i<lines.length){ | ||
| 508 | + var line=lines[i]; | ||
| 509 | + if(/^```/.test(line)){ | ||
| 510 | + flushPara();flushList(); | ||
| 511 | + var buf=[];i++; | ||
| 512 | + while(i<lines.length&&!/^```/.test(lines[i])){buf.push(lines[i]);i++;} | ||
| 513 | + i++; | ||
| 514 | + var pre=document.createElement('pre'); | ||
| 515 | + var code=document.createElement('code');code.textContent=buf.join('\n'); | ||
| 516 | + pre.appendChild(code);box.appendChild(pre); | ||
| 517 | + continue; | ||
| 518 | + } | ||
| 519 | + if(/^\s*$/.test(line)){flushPara();flushList();i++;continue;} | ||
| 520 | + var h=/^(#{1,4})\s+(.*)$/.exec(line); | ||
| 521 | + if(h){ | ||
| 522 | + flushPara();flushList(); | ||
| 523 | + var el=document.createElement('h'+h[1].length); | ||
| 524 | + inline(h[2],el);box.appendChild(el);i++;continue; | ||
| 525 | + } | ||
| 526 | + if(/^\s*([-*+]|\d+\.)\s+/.test(line)){ | ||
| 527 | + flushPara(); | ||
| 528 | + var ordered=/^\s*\d+\.\s+/.test(line); | ||
| 529 | + if(!list||list.tagName.toLowerCase()!==(ordered?'ol':'ul')){ | ||
| 530 | + flushList();list=document.createElement(ordered?'ol':'ul'); | ||
| 531 | + } | ||
| 532 | + var li=document.createElement('li'); | ||
| 533 | + inline(line.replace(/^\s*([-*+]|\d+\.)\s+/,''),li); | ||
| 534 | + list.appendChild(li);i++;continue; | ||
| 535 | + } | ||
| 536 | + if(/^>\s?/.test(line)){ | ||
| 537 | + flushPara();flushList(); | ||
| 538 | + var bq=document.createElement('blockquote'); | ||
| 539 | + inline(line.replace(/^>\s?/,''),bq); | ||
| 540 | + box.appendChild(bq);i++;continue; | ||
| 541 | + } | ||
| 542 | + if(/^(-{3,}|\*{3,}|_{3,})$/.test(line.trim())){ | ||
| 543 | + flushPara();flushList(); | ||
| 544 | + box.appendChild(document.createElement('hr'));i++;continue; | ||
| 545 | + } | ||
| 546 | + para.push(line);i++; | ||
| 547 | + } | ||
| 548 | + flushPara();flushList(); | ||
| 549 | + host.appendChild(box); | ||
| 550 | +} | ||
| 551 | + | ||
| 552 | +/* --- wiring ------------------------------------------------------- */ | ||
| 553 | + | ||
| 554 | +document.getElementById('btnRefresh').onclick=function(){ | ||
| 555 | + if(curPath)openDir(curPath);else loadRoots(); | ||
| 556 | +}; | ||
| 557 | +document.getElementById('btnUp').onclick=function(){ | ||
| 558 | + if(curParent)openDir(curParent); | ||
| 559 | + else if(curPath&&curRoot&&curPath!==curRoot)openDir(curRoot); | ||
| 560 | + else toast('Already at the root'); | ||
| 561 | +}; | ||
| 562 | +document.getElementById('btnBack').onclick=function(){setView('browse');}; | ||
| 563 | +document.getElementById('btnTheme').onclick=function(){ | ||
| 564 | + if(window.sxApplyTheme)window.sxApplyTheme(window.sxTheme&&window.sxTheme()==='dark'?'light':'dark'); | ||
| 565 | +}; | ||
| 566 | +btnHidden.onclick=function(){ | ||
| 567 | + showHidden=!showHidden; | ||
| 568 | + btnHidden.classList.toggle('on',showHidden); | ||
| 569 | + btnHidden.title=showHidden?'Hide hidden files':'Show hidden files'; | ||
| 570 | + if(curPath)openDir(curPath); | ||
| 571 | +}; | ||
| 572 | +btnDownload.onclick=function(){ | ||
| 573 | + if(!curFile)return; | ||
| 574 | + var a=document.createElement('a'); | ||
| 575 | + a.href=url('raw','path='+encodeURIComponent(curFile)+'&download=1'); | ||
| 576 | + a.rel='noopener'; | ||
| 577 | + document.body.appendChild(a);a.click();document.body.removeChild(a); | ||
| 578 | +}; | ||
| 579 | + | ||
| 580 | +document.addEventListener('keydown',function(ev){ | ||
| 581 | + var tag=(ev.target&&ev.target.tagName||'').toLowerCase(); | ||
| 582 | + if(tag==='input'||tag==='textarea')return; | ||
| 583 | + if(ev.key==='ArrowDown'||ev.key==='ArrowUp'){ | ||
| 584 | + if(!entries.length)return; | ||
| 585 | + ev.preventDefault(); | ||
| 586 | + selIndex+=(ev.key==='ArrowDown'?1:-1); | ||
| 587 | + if(selIndex<0)selIndex=0; | ||
| 588 | + if(selIndex>=entries.length)selIndex=entries.length-1; | ||
| 589 | + renderEntries(); | ||
| 590 | + }else if(ev.key==='Enter'){ | ||
| 591 | + if(selIndex>=0&&entries[selIndex]){ev.preventDefault();activate(entries[selIndex]);} | ||
| 592 | + }else if(ev.key==='Backspace'){ | ||
| 593 | + if(curParent){ev.preventDefault();openDir(curParent);} | ||
| 594 | + }else if(ev.key==='/'&&ev.ctrlKey===false){ | ||
| 595 | + return; | ||
| 596 | + } | ||
| 597 | +}); | ||
| 598 | + | ||
| 599 | +function loadRoots(){ | ||
| 600 | + return api('roots').then(function(d){ | ||
| 601 | + roots=(d&&d.roots)||[]; | ||
| 602 | + renderRoots(); | ||
| 603 | + /* Wide screens open the first root straight away; a phone keeps the root | ||
| 604 | + * list on screen, because a hidden sidebar there means an empty page. */ | ||
| 605 | + if(roots.length&&!curPath&&window.matchMedia('(min-width:821px)').matches){ | ||
| 606 | + openDir(roots[0].path); | ||
| 607 | + } | ||
| 608 | + }).catch(function(e){toast('Cannot list roots: '+e.message);}); | ||
| 609 | +} | ||
| 610 | + | ||
| 611 | +loadRoots(); | ||
| 612 | +})(); | ||
| 613 | +</script> | ||
| 614 | +</body></html> |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..edb635e | index 0000000..edb635e | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui_html.h | +++ b/src/ui_html.h | ||
| @@ -0,0 +1,622 @@ | @@ -0,0 +1,622 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | ||
| 2 | +#ifndef SX_FILES_UI_HTML_H | ||
| 3 | +#define SX_FILES_UI_HTML_H | ||
| 4 | + | ||
| 5 | +static const char *UI_HTML = | ||
| 6 | + "<!DOCTYPE html>\n" | ||
| 7 | + "<html lang=\"en\"><head><meta charset=\"utf-8\">\n" | ||
| 8 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | ||
| 9 | + "<title>files</title>\n" | ||
| 10 | + "\001\n" | ||
| 11 | + "<style>\n" | ||
| 12 | + "*{box-sizing:border-box}\n" | ||
| 13 | + "html,body{margin:0;height:100%}\n" | ||
| 14 | + "body{background:var(--bg);color:var(--text);font-family:var(--font);\n" | ||
| 15 | + " font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased;overflow:hidden}\n" | ||
| 16 | + "#app{display:grid;grid-template-columns:252px minmax(0,1fr);height:100%;min-height:0}\n" | ||
| 17 | + ".pane{min-width:0;min-height:0;display:flex;flex-direction:column}\n" | ||
| 18 | + "#side{background:var(--bg-2);border-right:1px solid var(--line)}\n" | ||
| 19 | + ".side-hd{display:flex;align-items:center;gap:8px;padding:12px 12px 8px}\n" | ||
| 20 | + ".brand{font-size:12px;font-weight:700;letter-spacing:.09em;text-transform:uppercase;\n" | ||
| 21 | + " color:var(--text-2);flex:1}\n" | ||
| 22 | + ".side-ft{display:flex;align-items:center;gap:8px;padding:8px 12px;\n" | ||
| 23 | + " border-top:1px solid var(--line);font-size:11px;color:var(--text-2)}\n" | ||
| 24 | + ".side-ft .grow{flex:1}\n" | ||
| 25 | + ".side-lbl{font-size:10.5px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;\n" | ||
| 26 | + " color:var(--text-2);padding:4px 14px 6px}\n" | ||
| 27 | + ".icon{display:inline-flex;align-items:center;justify-content:center;gap:6px;\n" | ||
| 28 | + " background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n" | ||
| 29 | + " border-radius:9px;width:30px;height:30px;padding:0;cursor:pointer;font-family:inherit;\n" | ||
| 30 | + " font-size:12px;font-weight:600;flex:0 0 auto}\n" | ||
| 31 | + ".icon:hover{background:var(--surface-hover);border-color:var(--line-2)}\n" | ||
| 32 | + ".icon:active{transform:scale(.96)}\n" | ||
| 33 | + ".icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor;\n" | ||
| 34 | + " stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}\n" | ||
| 35 | + ".icon.on{background:var(--surface-2);border-color:var(--line-2);color:var(--blue)}\n" | ||
| 36 | + ".rootlist{flex:0 0 auto;padding:0 8px 10px;border-bottom:1px solid var(--line)}\n" | ||
| 37 | + ".root{display:flex;align-items:center;gap:9px;width:100%;text-align:left;\n" | ||
| 38 | + " background:transparent;border:0;border-radius:9px;padding:8px 10px;color:var(--text);\n" | ||
| 39 | + " cursor:pointer;font-family:inherit;font-size:13px;margin-bottom:2px}\n" | ||
| 40 | + ".root:hover{background:var(--surface-hover)}\n" | ||
| 41 | + ".root.sel{background:var(--surface-2);box-shadow:inset 2px 0 0 var(--blue)}\n" | ||
| 42 | + ".root svg{width:14px;height:14px;flex:0 0 auto;fill:none;stroke:currentColor;stroke-width:1.7;\n" | ||
| 43 | + " stroke-linecap:round;stroke-linejoin:round;color:var(--text-2)}\n" | ||
| 44 | + ".root .rl{min-width:0;flex:1}\n" | ||
| 45 | + ".root .rl .n{display:block;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" | ||
| 46 | + ".root .rl .p{display:block;font-size:10.5px;color:var(--text-2);overflow:hidden;\n" | ||
| 47 | + " text-overflow:ellipsis;white-space:nowrap;font-family:var(--mono)}\n" | ||
| 48 | + "#main{background:var(--bg);min-width:0}\n" | ||
| 49 | + ".toolbar{display:flex;align-items:center;gap:7px;padding:10px 14px;\n" | ||
| 50 | + " border-bottom:1px solid var(--line);flex:0 0 auto;min-width:0}\n" | ||
| 51 | + ".crumbs{flex:1 1 auto;min-width:0;display:flex;align-items:center;gap:2px;\n" | ||
| 52 | + " overflow-x:auto;scrollbar-width:none;white-space:nowrap}\n" | ||
| 53 | + ".crumbs::-webkit-scrollbar{display:none}\n" | ||
| 54 | + ".crumb{background:transparent;border:0;color:var(--text-2);font-family:var(--mono);\n" | ||
| 55 | + " font-size:12px;padding:3px 5px;border-radius:6px;cursor:pointer;flex:0 0 auto}\n" | ||
| 56 | + ".crumb:hover{background:var(--surface-hover);color:var(--text)}\n" | ||
| 57 | + ".crumb.last{color:var(--text);font-weight:600}\n" | ||
| 58 | + ".crumb .sep{color:var(--text-2);opacity:.6;padding:0 1px}\n" | ||
| 59 | + ".body{flex:1 1 auto;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.15fr);\n" | ||
| 60 | + " min-height:0}\n" | ||
| 61 | + ".body.noprev{grid-template-columns:minmax(0,1fr)}\n" | ||
| 62 | + ".listwrap{min-width:0;min-height:0;display:flex;flex-direction:column;\n" | ||
| 63 | + " border-right:1px solid var(--line)}\n" | ||
| 64 | + ".entries{flex:1 1 auto;overflow-y:auto;padding:6px 8px 20px}\n" | ||
| 65 | + ".row{display:flex;align-items:center;gap:9px;width:100%;text-align:left;\n" | ||
| 66 | + " background:transparent;border:0;border-radius:9px;padding:7px 9px;color:var(--text);\n" | ||
| 67 | + " cursor:pointer;font-family:inherit;font-size:13px}\n" | ||
| 68 | + ".row:hover{background:var(--surface-hover)}\n" | ||
| 69 | + ".row.sel{background:var(--surface-2);box-shadow:inset 2px 0 0 var(--blue)}\n" | ||
| 70 | + ".row .ico{width:16px;height:16px;flex:0 0 auto;color:var(--text-2);display:flex}\n" | ||
| 71 | + ".row .ico svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:1.7;\n" | ||
| 72 | + " stroke-linecap:round;stroke-linejoin:round}\n" | ||
| 73 | + ".row.dir .ico{color:var(--blue)}\n" | ||
| 74 | + ".row .nm{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" | ||
| 75 | + ".row .mt{flex:0 0 auto;font-family:var(--mono);font-size:11px;color:var(--text-2)}\n" | ||
| 76 | + ".empty{padding:22px 14px;color:var(--text-2);font-size:12.5px;text-align:center}\n" | ||
| 77 | + ".hidden{display:none!important}\n" | ||
| 78 | + ".preview{min-width:0;min-height:0;display:flex;flex-direction:column}\n" | ||
| 79 | + ".prev-hd{display:flex;align-items:center;gap:8px;padding:9px 14px;\n" | ||
| 80 | + " border-bottom:1px solid var(--line);flex:0 0 auto;min-width:0}\n" | ||
| 81 | + ".prev-hd .nm{flex:1 1 auto;min-width:0;font-weight:600;font-size:13px;\n" | ||
| 82 | + " overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" | ||
| 83 | + ".prev-hd .mt{font-family:var(--mono);font-size:11px;color:var(--text-2);white-space:nowrap}\n" | ||
| 84 | + ".prev-body{flex:1 1 auto;overflow:auto;min-height:0}\n" | ||
| 85 | + ".codetxt{margin:0;padding:0;font-family:var(--mono);font-size:12.5px;line-height:1.6;\n" | ||
| 86 | + " display:grid;grid-template-columns:auto minmax(0,1fr);min-width:0}\n" | ||
| 87 | + ".codetxt .ln{color:var(--text-2);text-align:right;padding:0 10px 0 14px;\n" | ||
| 88 | + " user-select:none;background:var(--bg-2);border-right:1px solid var(--line)}\n" | ||
| 89 | + ".codetxt .tx{padding:0 14px;white-space:pre-wrap;word-break:break-word;\n" | ||
| 90 | + " font-family:var(--mono);font-size:12.5px}\n" | ||
| 91 | + ".md{padding:16px 20px 40px;max-width:860px}\n" | ||
| 92 | + ".md h1,.md h2,.md h3,.md h4{line-height:1.25;margin:18px 0 8px;font-weight:650}\n" | ||
| 93 | + ".md h1{font-size:21px}.md h2{font-size:18px}.md h3{font-size:15.5px}.md h4{font-size:14px}\n" | ||
| 94 | + ".md p{margin:0 0 11px}\n" | ||
| 95 | + ".md ul,.md ol{margin:0 0 11px;padding-left:22px}\n" | ||
| 96 | + ".md li{margin:3px 0}\n" | ||
| 97 | + ".md code{font-family:var(--mono);font-size:12px;background:var(--code-bg);\n" | ||
| 98 | + " padding:1px 5px;border-radius:5px}\n" | ||
| 99 | + ".md pre{background:var(--code-bg);border:1px solid var(--line);border-radius:10px;\n" | ||
| 100 | + " padding:11px 13px;overflow-x:auto;margin:0 0 12px}\n" | ||
| 101 | + ".md pre code{background:transparent;padding:0;font-size:12px;line-height:1.55}\n" | ||
| 102 | + ".md hr{border:0;border-top:1px solid var(--line);margin:16px 0}\n" | ||
| 103 | + ".md a{color:var(--blue);text-decoration:none;font-weight:600}\n" | ||
| 104 | + ".md a:hover{text-decoration:underline}\n" | ||
| 105 | + ".md blockquote{margin:0 0 12px;padding:2px 0 2px 13px;border-left:3px solid var(--line-2);\n" | ||
| 106 | + " color:var(--text-2)}\n" | ||
| 107 | + ".imgwrap{padding:16px;display:flex;align-items:flex-start;justify-content:center}\n" | ||
| 108 | + ".imgwrap img{max-width:100%;height:auto;border-radius:10px;border:1px solid var(--line);\n" | ||
| 109 | + " background:var(--bg-2)}\n" | ||
| 110 | + ".note{padding:16px 18px;color:var(--text-2);font-size:12.5px}\n" | ||
| 111 | + ".welcome{flex:1 1 auto;display:flex;flex-direction:column;align-items:center;\n" | ||
| 112 | + " justify-content:center;gap:10px;color:var(--text-2);font-size:13px;padding:24px;\n" | ||
| 113 | + " text-align:center;min-height:0}\n" | ||
| 114 | + ".welcome svg{width:34px;height:34px;fill:none;stroke:currentColor;stroke-width:1.4;\n" | ||
| 115 | + " stroke-linecap:round;stroke-linejoin:round;opacity:.55}\n" | ||
| 116 | + ".toast{position:fixed;left:50%;bottom:18px;transform:translateX(-50%);\n" | ||
| 117 | + " background:var(--modal-bg);border:1px solid var(--line-2);color:var(--text);\n" | ||
| 118 | + " padding:8px 14px;border-radius:999px;font-size:12.5px;box-shadow:var(--shadow-lg);\n" | ||
| 119 | + " opacity:0;pointer-events:none;transition:opacity .16s var(--ease);z-index:9;\n" | ||
| 120 | + " max-width:calc(100% - 24px);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" | ||
| 121 | + ".toast.show{opacity:1}\n" | ||
| 122 | + "@media (max-width:1100px){\n" | ||
| 123 | + " #app{grid-template-columns:216px minmax(0,1fr)}\n" | ||
| 124 | + " .body{grid-template-columns:minmax(0,1fr) minmax(0,1fr)}\n" | ||
| 125 | + "}\n" | ||
| 126 | + "@media (max-width:820px){\n" | ||
| 127 | + " body{overflow:hidden}\n" | ||
| 128 | + " #app{grid-template-columns:minmax(0,1fr)}\n" | ||
| 129 | + " #side,#main{grid-column:1;grid-row:1}\n" | ||
| 130 | + " #app[data-view=\"browse\"] #side{display:none}\n" | ||
| 131 | + " #app[data-view=\"roots\"] #main{display:none}\n" | ||
| 132 | + " .body{grid-template-columns:minmax(0,1fr)}\n" | ||
| 133 | + " #app[data-view=\"browse\"] .body{grid-template-columns:minmax(0,1fr)}\n" | ||
| 134 | + " #app[data-view=\"browse\"] .preview{display:none}\n" | ||
| 135 | + " #app[data-view=\"preview\"] .listwrap{display:none}\n" | ||
| 136 | + " #app[data-view=\"preview\"] .body{grid-template-columns:minmax(0,1fr)}\n" | ||
| 137 | + " .back{display:inline-flex!important}\n" | ||
| 138 | + " .toolbar{padding:8px 10px;gap:6px}\n" | ||
| 139 | + " .md{padding:12px 14px 32px}\n" | ||
| 140 | + " .codetxt .tx{padding:0 10px}\n" | ||
| 141 | + "}\n" | ||
| 142 | + "@media (min-width:821px){.back{display:none!important}}\n" | ||
| 143 | + "</style>\n" | ||
| 144 | + "</head><body>\n" | ||
| 145 | + "<div id=\"app\" data-view=\"roots\">\n" | ||
| 146 | + " <aside id=\"side\" class=\"pane\">\n" | ||
| 147 | + " <div class=\"side-hd\">\n" | ||
| 148 | + " <span class=\"brand\">files</span>\n" | ||
| 149 | + " <button id=\"btnUp\" class=\"icon\" title=\"Up one level\" aria-label=\"Up one level\">\n" | ||
| 150 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M12 19V5M5 12l7-7 7 7\"/></svg></button>\n" | ||
| 151 | + " <button id=\"btnRefresh\" class=\"icon\" title=\"Refresh\" aria-label=\"Refresh\">\n" | ||
| 152 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M20 11a8 8 0 1 0-2.3 5.7\"/><path d=\"M20 4v7h-7\"/></svg></button>\n" | ||
| 153 | + " </div>\n" | ||
| 154 | + " <div class=\"side-lbl\">Roots</div>\n" | ||
| 155 | + " <div id=\"roots\" class=\"rootlist\"></div>\n" | ||
| 156 | + " <div class=\"side-ft\">\n" | ||
| 157 | + " <span id=\"count\">0 items</span><span class=\"grow\"></span>\n" | ||
| 158 | + " <button id=\"btnHidden\" class=\"icon\" title=\"Show hidden files\" aria-label=\"Show hidden files\">\n" | ||
| 159 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z\"/><circle cx=\"12\" cy=\"12\" r=\"3\"/></svg></button>\n" | ||
| 160 | + " <button id=\"btnTheme\" class=\"icon embed-hide\" title=\"Toggle appearance\" aria-label=\"Toggle appearance\">\n" | ||
| 161 | + " <svg viewBox=\"0 0 24 24\"><circle cx=\"12\" cy=\"12\" r=\"4.5\"/><path d=\"M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4\"/></svg></button>\n" | ||
| 162 | + " </div>\n" | ||
| 163 | + " </aside>\n" | ||
| 164 | + " <main id=\"main\" class=\"pane\">\n" | ||
| 165 | + " <div class=\"toolbar\">\n" | ||
| 166 | + " <button id=\"btnBack\" class=\"icon back\" title=\"Back to list\" aria-label=\"Back to list\">\n" | ||
| 167 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M15 5l-7 7 7 7\"/></svg></button>\n" | ||
| 168 | + " <div id=\"crumbs\" class=\"crumbs\"></div>\n" | ||
| 169 | + " <button id=\"btnDownload\" class=\"icon\" title=\"Download file\" aria-label=\"Download file\">\n" | ||
| 170 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M12 3v12M7 11l5 5 5-5M4 21h16\"/></svg></button>\n" | ||
| 171 | + " </div>\n" | ||
| 172 | + " <div id=\"body\" class=\"body\">\n" | ||
| 173 | + " <div class=\"listwrap\">\n" | ||
| 174 | + " <div id=\"entries\" class=\"entries\"></div>\n" | ||
| 175 | + " <div id=\"empty\" class=\"empty hidden\">This directory is empty.</div>\n" | ||
| 176 | + " </div>\n" | ||
| 177 | + " <div id=\"preview\" class=\"preview\">\n" | ||
| 178 | + " <div id=\"prevHd\" class=\"prev-hd hidden\">\n" | ||
| 179 | + " <span id=\"prevName\" class=\"nm\"></span>\n" | ||
| 180 | + " <span id=\"prevMeta\" class=\"mt\"></span>\n" | ||
| 181 | + " </div>\n" | ||
| 182 | + " <div id=\"prevBody\" class=\"prev-body\">\n" | ||
| 183 | + " <div id=\"welcome\" class=\"welcome\">\n" | ||
| 184 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M3 7h6l2 2h10v11H3z\"/></svg>\n" | ||
| 185 | + " <div>Pick a root, then open a file to preview it.</div>\n" | ||
| 186 | + " <div style=\"font-size:11.5px\">Arrows move · Enter opens · Backspace goes up</div>\n" | ||
| 187 | + " </div>\n" | ||
| 188 | + " </div>\n" | ||
| 189 | + " </div>\n" | ||
| 190 | + " </div>\n" | ||
| 191 | + " </main>\n" | ||
| 192 | + "</div>\n" | ||
| 193 | + "<div id=\"toast\" class=\"toast\"></div>\n" | ||
| 194 | + "<script>\n" | ||
| 195 | + "(function(){\n" | ||
| 196 | + "\"use strict\";\n" | ||
| 197 | + "var app=document.getElementById('app');\n" | ||
| 198 | + "var rootsEl=document.getElementById('roots');\n" | ||
| 199 | + "var entriesEl=document.getElementById('entries');\n" | ||
| 200 | + "var emptyEl=document.getElementById('empty');\n" | ||
| 201 | + "var countEl=document.getElementById('count');\n" | ||
| 202 | + "var crumbsEl=document.getElementById('crumbs');\n" | ||
| 203 | + "var bodyEl=document.getElementById('body');\n" | ||
| 204 | + "var prevEl=document.getElementById('preview');\n" | ||
| 205 | + "var prevHd=document.getElementById('prevHd');\n" | ||
| 206 | + "var prevName=document.getElementById('prevName');\n" | ||
| 207 | + "var prevMeta=document.getElementById('prevMeta');\n" | ||
| 208 | + "var prevBody=document.getElementById('prevBody');\n" | ||
| 209 | + "var toastEl=document.getElementById('toast');\n" | ||
| 210 | + "var btnHidden=document.getElementById('btnHidden');\n" | ||
| 211 | + "var btnDownload=document.getElementById('btnDownload');\n" | ||
| 212 | + "\n" | ||
| 213 | + "var q=new URLSearchParams(location.search);\n" | ||
| 214 | + "var node=q.get('node')||'';\n" | ||
| 215 | + "var sid=q.get('id')||'';\n" | ||
| 216 | + "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n" | ||
| 217 | + " localStorage.getItem('bot_active_pwd')||'';\n" | ||
| 218 | + "var HUB=q.get('plugin')||'';\n" | ||
| 219 | + "\n" | ||
| 220 | + "var roots=[], entries=[], curPath='', curParent=null, curRoot=null;\n" | ||
| 221 | + "var selIndex=-1, showHidden=false, curFile=null;\n" | ||
| 222 | + "\n" | ||
| 223 | + "/* Two call routes, and getting this wrong is the most common plugin bug:\n" | ||
| 224 | + " * page served through the hub (bot.scorpiox.net/plugins?plugin=plugin_files&node=..)\n" | ||
| 225 | + " * -> call the hub proxy back: /plugins?plugin=plugin_files&action=..\n" | ||
| 226 | + " * opened directly on the node\n" | ||
| 227 | + " * -> the plugin itself is the route: /plugin_files?action=..\n" | ||
| 228 | + " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n" | ||
| 229 | + "function url(action,extra){\n" | ||
| 230 | + " var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_files')+\n" | ||
| 231 | + " '?action='+encodeURIComponent(action)+\n" | ||
| 232 | + " (extra?('&'+extra):'')+\n" | ||
| 233 | + " (node?'&node='+encodeURIComponent(node):'')+\n" | ||
| 234 | + " (sid?'&id='+encodeURIComponent(sid):'')+\n" | ||
| 235 | + " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n" | ||
| 236 | + " return u;\n" | ||
| 237 | + "}\n" | ||
| 238 | + "function hdr(extra){\n" | ||
| 239 | + " var h=extra||{};\n" | ||
| 240 | + " if(pwd)h['X-Bot-Password']=pwd;\n" | ||
| 241 | + " return h;\n" | ||
| 242 | + "}\n" | ||
| 243 | + "function api(action,extra){\n" | ||
| 244 | + " return fetch(url(action,extra),{headers:hdr({})}).then(function(r){\n" | ||
| 245 | + " if(!r.ok)throw new Error('HTTP '+r.status);\n" | ||
| 246 | + " return r.json();\n" | ||
| 247 | + " });\n" | ||
| 248 | + "}\n" | ||
| 249 | + "\n" | ||
| 250 | + "function toast(msg){\n" | ||
| 251 | + " toastEl.textContent=msg;\n" | ||
| 252 | + " toastEl.classList.add('show');\n" | ||
| 253 | + " clearTimeout(toast._t);\n" | ||
| 254 | + " toast._t=setTimeout(function(){toastEl.classList.remove('show');},2000);\n" | ||
| 255 | + "}\n" | ||
| 256 | + "function setView(v){app.setAttribute('data-view',v);}\n" | ||
| 257 | + "\n" | ||
| 258 | + "function fmtSize(n){\n" | ||
| 259 | + " if(n===null||n===undefined)return '';\n" | ||
| 260 | + " if(n<1024)return n+' B';\n" | ||
| 261 | + " if(n<1048576)return (n/1024).toFixed(1)+' KB';\n" | ||
| 262 | + " if(n<1073741824)return (n/1048576).toFixed(1)+' MB';\n" | ||
| 263 | + " return (n/1073741824).toFixed(1)+' GB';\n" | ||
| 264 | + "}\n" | ||
| 265 | + "function fmtTime(iso){\n" | ||
| 266 | + " if(!iso)return '';\n" | ||
| 267 | + " try{\n" | ||
| 268 | + " var d=new Date(iso),now=new Date(),diff=(now-d)/1000;\n" | ||
| 269 | + " if(diff<60)return 'just now';\n" | ||
| 270 | + " if(diff<3600)return Math.floor(diff/60)+'m ago';\n" | ||
| 271 | + " if(diff<86400)return Math.floor(diff/3600)+'h ago';\n" | ||
| 272 | + " if(diff<604800)return Math.floor(diff/86400)+'d ago';\n" | ||
| 273 | + " return d.toLocaleDateString();\n" | ||
| 274 | + " }catch(e){return ''}\n" | ||
| 275 | + "}\n" | ||
| 276 | + "\n" | ||
| 277 | + "var SVG={\n" | ||
| 278 | + " dir:'<svg viewBox=\"0 0 24 24\"><path d=\"M3 7h6l2 2h10v11H3z\"/></svg>',\n" | ||
| 279 | + " file:'<svg viewBox=\"0 0 24 24\"><path d=\"M6 3h9l5 5v13H6z\"/><path d=\"M14 3v5h5\"/></svg>',\n" | ||
| 280 | + " link:'<svg viewBox=\"0 0 24 24\"><path d=\"M10 13a4 4 0 0 0 6 .5l2.5-2.5a4 4 0 0 0-6-6L11 6.5\"/><path d=\"M14 11a4 4 0 0 0-6-.5L5.5 13a4 4 0 0 0 6 6L13 17.5\"/></svg>',\n" | ||
| 281 | + " img:'<svg viewBox=\"0 0 24 24\"><rect x=\"3\" y=\"5\" width=\"18\" height=\"14\" rx=\"2\"/><circle cx=\"8.5\" cy=\"10\" r=\"1.6\"/><path d=\"M21 16l-5-5-6 6\"/></svg>',\n" | ||
| 282 | + " root:'<svg viewBox=\"0 0 24 24\"><path d=\"M3 7h6l2 2h10v11H3z\"/></svg>'\n" | ||
| 283 | + "};\n" | ||
| 284 | + "\n" | ||
| 285 | + "function renderRoots(){\n" | ||
| 286 | + " while(rootsEl.firstChild)rootsEl.removeChild(rootsEl.firstChild);\n" | ||
| 287 | + " roots.forEach(function(r,i){\n" | ||
| 288 | + " var b=document.createElement('button');\n" | ||
| 289 | + " b.className='root'+(curRoot===r.path?' sel':'');\n" | ||
| 290 | + " var ic=document.createElement('span');ic.innerHTML=SVG.root;\n" | ||
| 291 | + " var wrap=document.createElement('span');wrap.className='rl';\n" | ||
| 292 | + " var n=document.createElement('span');n.className='n';n.textContent=r.name;\n" | ||
| 293 | + " var p=document.createElement('span');p.className='p';p.textContent=r.path;\n" | ||
| 294 | + " wrap.appendChild(n);wrap.appendChild(p);\n" | ||
| 295 | + " b.appendChild(ic);b.appendChild(wrap);\n" | ||
| 296 | + " b.onclick=function(){openDir(r.path);setView('browse');};\n" | ||
| 297 | + " rootsEl.appendChild(b);\n" | ||
| 298 | + " });\n" | ||
| 299 | + "}\n" | ||
| 300 | + "\n" | ||
| 301 | + "function renderCrumbs(){\n" | ||
| 302 | + " while(crumbsEl.firstChild)crumbsEl.removeChild(crumbsEl.firstChild);\n" | ||
| 303 | + " if(!curPath){\n" | ||
| 304 | + " var hint=document.createElement('span');hint.className='crumb last';\n" | ||
| 305 | + " hint.textContent='Select a root';crumbsEl.appendChild(hint);return;\n" | ||
| 306 | + " }\n" | ||
| 307 | + " var base=curRoot||'';\n" | ||
| 308 | + " var rel=curPath;\n" | ||
| 309 | + " if(base&&curPath.indexOf(base)===0)rel=curPath.slice(base.length);\n" | ||
| 310 | + " var parts=rel.split(/[\\/\\\\]+/).filter(function(s){return s.length;});\n" | ||
| 311 | + " var b0=document.createElement('button');\n" | ||
| 312 | + " b0.className='crumb'+(parts.length?'':' last');\n" | ||
| 313 | + " b0.textContent=base.split(/[\\/\\\\]+/).filter(Boolean).pop()||base||'/';\n" | ||
| 314 | + " b0.title=base;\n" | ||
| 315 | + " b0.onclick=function(){openDir(base);};\n" | ||
| 316 | + " crumbsEl.appendChild(b0);\n" | ||
| 317 | + " var acc=base;\n" | ||
| 318 | + " parts.forEach(function(p,i){\n" | ||
| 319 | + " var sp=document.createElement('span');sp.className='sep';sp.textContent='/';\n" | ||
| 320 | + " crumbsEl.appendChild(sp);\n" | ||
| 321 | + " acc+=(acc&&acc[acc.length-1]!=='/'&&acc[acc.length-1]!=='\\\\'?'/':'')+p;\n" | ||
| 322 | + " var b=document.createElement('button');\n" | ||
| 323 | + " b.className='crumb'+(i===parts.length-1?' last':'');\n" | ||
| 324 | + " b.textContent=p;b.title=acc;\n" | ||
| 325 | + " var target=acc;\n" | ||
| 326 | + " b.onclick=function(){openDir(target);};\n" | ||
| 327 | + " crumbsEl.appendChild(b);\n" | ||
| 328 | + " });\n" | ||
| 329 | + "}\n" | ||
| 330 | + "\n" | ||
| 331 | + "function isImage(name){\n" | ||
| 332 | + " return /\\.(png|jpe?g|gif|webp|bmp|ico|svg)$/i.test(name||'');\n" | ||
| 333 | + "}\n" | ||
| 334 | + "function isMarkdown(name){\n" | ||
| 335 | + " return /\\.(md|markdown)$/i.test(name||'');\n" | ||
| 336 | + "}\n" | ||
| 337 | + "function isTextish(name){\n" | ||
| 338 | + " return /\\.(txt|md|markdown|json|js|ts|css|html?|c|h|cpp|hpp|py|sh|yml|yaml|toml|ini|conf|log|csv|xml|sql|go|rs|java|rb|php|gitignore|env)$/i.test(name||'');\n" | ||
| 339 | + "}\n" | ||
| 340 | + "\n" | ||
| 341 | + "function renderEntries(){\n" | ||
| 342 | + " while(entriesEl.firstChild)entriesEl.removeChild(entriesEl.firstChild);\n" | ||
| 343 | + " if(selIndex>=entries.length)selIndex=entries.length?entries.length-1:-1;\n" | ||
| 344 | + " entries.forEach(function(e,i){\n" | ||
| 345 | + " var b=document.createElement('button');\n" | ||
| 346 | + " b.className='row'+(e.type==='dir'?' dir':'')+(i===selIndex?' sel':'');\n" | ||
| 347 | + " var ic=document.createElement('span');ic.className='ico';\n" | ||
| 348 | + " ic.innerHTML = e.type==='dir'?SVG.dir : (isImage(e.name)?SVG.img : (e.type==='link'?SVG.link:SVG.file));\n" | ||
| 349 | + " var nm=document.createElement('span');nm.className='nm';nm.textContent=e.name;\n" | ||
| 350 | + " var mt=document.createElement('span');mt.className='mt';\n" | ||
| 351 | + " mt.textContent=(e.type==='dir'?'':fmtSize(e.size));\n" | ||
| 352 | + " b.appendChild(ic);b.appendChild(nm);b.appendChild(mt);\n" | ||
| 353 | + " b.onclick=function(){selIndex=i;renderEntries();activate(e);};\n" | ||
| 354 | + " entriesEl.appendChild(b);\n" | ||
| 355 | + " });\n" | ||
| 356 | + " emptyEl.classList.toggle('hidden',entries.length>0);\n" | ||
| 357 | + " countEl.textContent=entries.length+(entries.length===1?' item':' items');\n" | ||
| 358 | + " var sel=entriesEl.querySelector('.row.sel');\n" | ||
| 359 | + " if(sel&&sel.scrollIntoView)sel.scrollIntoView({block:'nearest'});\n" | ||
| 360 | + "}\n" | ||
| 361 | + "\n" | ||
| 362 | + "function openDir(path){\n" | ||
| 363 | + " return api('ls','path='+encodeURIComponent(path)+(showHidden?'&hidden=1':''))\n" | ||
| 364 | + " .then(function(d){\n" | ||
| 365 | + " if(!d||!d.ok)throw new Error((d&&d.error)||'failed');\n" | ||
| 366 | + " curPath=d.path;curParent=d.parent;curRoot=d.root;\n" | ||
| 367 | + " entries=d.entries||[];selIndex=entries.length?0:-1;\n" | ||
| 368 | + " renderCrumbs();renderEntries();\n" | ||
| 369 | + " if(!entries.length){clearPreview();}\n" | ||
| 370 | + " else if(window.matchMedia('(max-width:820px)').matches){setView('browse');}\n" | ||
| 371 | + " return d;\n" | ||
| 372 | + " }).catch(function(e){toast('Cannot open folder: '+e.message);});\n" | ||
| 373 | + "}\n" | ||
| 374 | + "\n" | ||
| 375 | + "function clearPreview(){\n" | ||
| 376 | + " prevHd.classList.add('hidden');\n" | ||
| 377 | + " while(prevBody.firstChild)prevBody.removeChild(prevBody.firstChild);\n" | ||
| 378 | + " var w=document.createElement('div');w.className='welcome';\n" | ||
| 379 | + " w.innerHTML='<svg viewBox=\"0 0 24 24\"><path d=\"M3 7h6l2 2h10v11H3z\"/></svg>'+\n" | ||
| 380 | + " '<div>Pick a root, then open a file to preview it.</div>'+\n" | ||
| 381 | + " '<div style=\"font-size:11.5px\">Arrows move · Enter opens · Backspace goes up</div>';\n" | ||
| 382 | + " prevBody.appendChild(w);\n" | ||
| 383 | + " curFile=null;\n" | ||
| 384 | + " btnDownload.classList.add('hidden');\n" | ||
| 385 | + "}\n" | ||
| 386 | + "\n" | ||
| 387 | + "function activate(e){\n" | ||
| 388 | + " if(e.type==='dir'){openDir(joinPath(curPath,e.name));setView('browse');return;}\n" | ||
| 389 | + " previewFile(joinPath(curPath,e.name),e);\n" | ||
| 390 | + "}\n" | ||
| 391 | + "function joinPath(dir,name){\n" | ||
| 392 | + " if(!dir)return name;\n" | ||
| 393 | + " var last=dir[dir.length-1];\n" | ||
| 394 | + " return dir+(last==='/'||last==='\\\\'?'':'/')+name;\n" | ||
| 395 | + "}\n" | ||
| 396 | + "\n" | ||
| 397 | + "function setHd(name,meta){\n" | ||
| 398 | + " prevHd.classList.remove('hidden');\n" | ||
| 399 | + " prevName.textContent=name;\n" | ||
| 400 | + " prevMeta.textContent=meta||'';\n" | ||
| 401 | + " btnDownload.classList.remove('hidden');\n" | ||
| 402 | + "}\n" | ||
| 403 | + "\n" | ||
| 404 | + "function previewFile(path,ent){\n" | ||
| 405 | + " curFile=path;\n" | ||
| 406 | + " setView('preview');\n" | ||
| 407 | + " prevHd.classList.remove('hidden');\n" | ||
| 408 | + " prevName.textContent=ent&&ent.name?ent.name:path.split(/[\\/\\\\]/).pop();\n" | ||
| 409 | + " prevMeta.textContent=ent?fmtSize(ent.size):'';\n" | ||
| 410 | + " btnDownload.classList.remove('hidden');\n" | ||
| 411 | + " while(prevBody.firstChild)prevBody.removeChild(prevBody.firstChild);\n" | ||
| 412 | + " prevBody.scrollTop=0;\n" | ||
| 413 | + "\n" | ||
| 414 | + " var name=prevName.textContent;\n" | ||
| 415 | + " if(isImage(name)){\n" | ||
| 416 | + " var wrap=document.createElement('div');wrap.className='imgwrap';\n" | ||
| 417 | + " var img=document.createElement('img');\n" | ||
| 418 | + " img.alt=name;\n" | ||
| 419 | + " img.src=url('raw','path='+encodeURIComponent(path));\n" | ||
| 420 | + " img.onerror=function(){\n" | ||
| 421 | + " wrap.innerHTML='';\n" | ||
| 422 | + " var n=document.createElement('div');n.className='note';\n" | ||
| 423 | + " n.textContent='This image could not be displayed.';\n" | ||
| 424 | + " wrap.appendChild(n);\n" | ||
| 425 | + " };\n" | ||
| 426 | + " wrap.appendChild(img);prevBody.appendChild(wrap);\n" | ||
| 427 | + " return;\n" | ||
| 428 | + " }\n" | ||
| 429 | + "\n" | ||
| 430 | + " api('read','path='+encodeURIComponent(path)).then(function(d){\n" | ||
| 431 | + " if(!d||!d.ok)throw new Error((d&&d.error)||'failed');\n" | ||
| 432 | + " prevMeta.textContent=fmtSize(d.size)+(d.truncated?' (first 1 MB)':'');\n" | ||
| 433 | + " if(d.binary){\n" | ||
| 434 | + " var n=document.createElement('div');n.className='note';\n" | ||
| 435 | + " n.textContent='Binary file ('+fmtSize(d.size)+') - use Download to inspect it locally.';\n" | ||
| 436 | + " prevBody.appendChild(n);return;\n" | ||
| 437 | + " }\n" | ||
| 438 | + " if(!isTextish(name)&&!isMarkdown(name)){\n" | ||
| 439 | + " prevMeta.textContent=fmtSize(d.size)+(d.truncated?' (first 1 MB)':'')+' · plain text';\n" | ||
| 440 | + " }\n" | ||
| 441 | + " if(isMarkdown(name))renderMarkdown(d.text||'',prevBody);\n" | ||
| 442 | + " else renderCode(d.text||'',prevBody);\n" | ||
| 443 | + " }).catch(function(e){\n" | ||
| 444 | + " while(prevBody.firstChild)prevBody.removeChild(prevBody.firstChild);\n" | ||
| 445 | + " var n=document.createElement('div');n.className='note';\n" | ||
| 446 | + " n.textContent='Cannot preview this file: '+e.message;\n" | ||
| 447 | + " prevBody.appendChild(n);\n" | ||
| 448 | + " });\n" | ||
| 449 | + "}\n" | ||
| 450 | + "\n" | ||
| 451 | + "/* Line numbers + text. Every line is a text node, so file content can never\n" | ||
| 452 | + " * become markup. */\n" | ||
| 453 | + "function renderCode(text,host){\n" | ||
| 454 | + " var lines=text.split('\\n');\n" | ||
| 455 | + " if(lines.length&&lines[lines.length-1]==='')lines.pop();\n" | ||
| 456 | + " var pre=document.createElement('div');pre.className='codetxt';\n" | ||
| 457 | + " var ln=document.createElement('div');ln.className='ln';\n" | ||
| 458 | + " var tx=document.createElement('div');tx.className='tx';\n" | ||
| 459 | + " var nums=[],body=[];\n" | ||
| 460 | + " for(var i=0;i<lines.length;i++){nums.push(String(i+1));body.push(lines[i]);}\n" | ||
| 461 | + " ln.textContent=nums.join('\\n');\n" | ||
| 462 | + " tx.textContent=body.join('\\n');\n" | ||
| 463 | + " pre.appendChild(ln);pre.appendChild(tx);\n" | ||
| 464 | + " host.appendChild(pre);\n" | ||
| 465 | + "}\n" | ||
| 466 | + "\n" | ||
| 467 | + "/* Tiny markdown renderer: headings, lists, fenced code, blockquote, hr,\n" | ||
| 468 | + " * inline code/bold/italic/links. No CDN, no innerHTML with file content. */\n" | ||
| 469 | + "function renderMarkdown(text,host){\n" | ||
| 470 | + " var box=document.createElement('div');box.className='md';\n" | ||
| 471 | + " var lines=text.split('\\n');\n" | ||
| 472 | + " var i=0,para=[],list=null;\n" | ||
| 473 | + "\n" | ||
| 474 | + " function flushPara(){\n" | ||
| 475 | + " if(!para.length)return;\n" | ||
| 476 | + " var p=document.createElement('p');\n" | ||
| 477 | + " inline(para.join(' '),p);\n" | ||
| 478 | + " box.appendChild(p);para=[];\n" | ||
| 479 | + " }\n" | ||
| 480 | + " function flushList(){\n" | ||
| 481 | + " if(!list)return;\n" | ||
| 482 | + " box.appendChild(list);list=null;\n" | ||
| 483 | + " }\n" | ||
| 484 | + " function inline(s,parent){\n" | ||
| 485 | + " var re=/(`[^`]*`)|(\\*\\*[^*]+\\*\\*)|(\\*[^*]+\\*)|(\\[[^\\]]+\\]\\([^)]+\\))/g;\n" | ||
| 486 | + " var last=0,m;\n" | ||
| 487 | + " while((m=re.exec(s))!==null){\n" | ||
| 488 | + " if(m.index>last)parent.appendChild(document.createTextNode(s.slice(last,m.index)));\n" | ||
| 489 | + " var tok=m[0];\n" | ||
| 490 | + " if(tok[0]==='`'){\n" | ||
| 491 | + " var c=document.createElement('code');c.textContent=tok.slice(1,-1);parent.appendChild(c);\n" | ||
| 492 | + " }else if(tok.slice(0,2)==='**'){\n" | ||
| 493 | + " var b=document.createElement('strong');b.textContent=tok.slice(2,-2);parent.appendChild(b);\n" | ||
| 494 | + " }else if(tok[0]==='*'){\n" | ||
| 495 | + " var em=document.createElement('em');em.textContent=tok.slice(1,-1);parent.appendChild(em);\n" | ||
| 496 | + " }else{\n" | ||
| 497 | + " var mm=/^\\[([^\\]]+)\\]\\(([^)]+)\\)$/.exec(tok);\n" | ||
| 498 | + " if(mm&&/^(https?:\\/\\/|\\/|#|mailto:)/i.test(mm[2])){\n" | ||
| 499 | + " var a=document.createElement('a');\n" | ||
| 500 | + " a.textContent=mm[1];a.href=mm[2];\n" | ||
| 501 | + " a.target='_blank';a.rel='noopener noreferrer';\n" | ||
| 502 | + " parent.appendChild(a);\n" | ||
| 503 | + " }else if(mm){\n" | ||
| 504 | + " parent.appendChild(document.createTextNode(mm[1]));\n" | ||
| 505 | + " }\n" | ||
| 506 | + " }\n" | ||
| 507 | + " last=m.index+tok.length;\n" | ||
| 508 | + " }\n" | ||
| 509 | + " if(last<s.length)parent.appendChild(document.createTextNode(s.slice(last)));\n" | ||
| 510 | + " }\n" | ||
| 511 | + "\n" | ||
| 512 | + " while(i<lines.length){\n" | ||
| 513 | + " var line=lines[i];\n" | ||
| 514 | + " if(/^```/.test(line)){\n" | ||
| 515 | + " flushPara();flushList();\n" | ||
| 516 | + " var buf=[];i++;\n" | ||
| 517 | + " while(i<lines.length&&!/^```/.test(lines[i])){buf.push(lines[i]);i++;}\n" | ||
| 518 | + " i++;\n" | ||
| 519 | + " var pre=document.createElement('pre');\n" | ||
| 520 | + " var code=document.createElement('code');code.textContent=buf.join('\\n');\n" | ||
| 521 | + " pre.appendChild(code);box.appendChild(pre);\n" | ||
| 522 | + " continue;\n" | ||
| 523 | + " }\n" | ||
| 524 | + " if(/^\\s*$/.test(line)){flushPara();flushList();i++;continue;}\n" | ||
| 525 | + " var h=/^(#{1,4})\\s+(.*)$/.exec(line);\n" | ||
| 526 | + " if(h){\n" | ||
| 527 | + " flushPara();flushList();\n" | ||
| 528 | + " var el=document.createElement('h'+h[1].length);\n" | ||
| 529 | + " inline(h[2],el);box.appendChild(el);i++;continue;\n" | ||
| 530 | + " }\n" | ||
| 531 | + " if(/^\\s*([-*+]|\\d+\\.)\\s+/.test(line)){\n" | ||
| 532 | + " flushPara();\n" | ||
| 533 | + " var ordered=/^\\s*\\d+\\.\\s+/.test(line);\n" | ||
| 534 | + " if(!list||list.tagName.toLowerCase()!==(ordered?'ol':'ul')){\n" | ||
| 535 | + " flushList();list=document.createElement(ordered?'ol':'ul');\n" | ||
| 536 | + " }\n" | ||
| 537 | + " var li=document.createElement('li');\n" | ||
| 538 | + " inline(line.replace(/^\\s*([-*+]|\\d+\\.)\\s+/,''),li);\n" | ||
| 539 | + " list.appendChild(li);i++;continue;\n" | ||
| 540 | + " }\n" | ||
| 541 | + " if(/^>\\s?/.test(line)){\n" | ||
| 542 | + " flushPara();flushList();\n" | ||
| 543 | + " var bq=document.createElement('blockquote');\n" | ||
| 544 | + " inline(line.replace(/^>\\s?/,''),bq);\n" | ||
| 545 | + " box.appendChild(bq);i++;continue;\n" | ||
| 546 | + " }\n" | ||
| 547 | + " if(/^(-{3,}|\\*{3,}|_{3,})$/.test(line.trim())){\n" | ||
| 548 | + " flushPara();flushList();\n" | ||
| 549 | + " box.appendChild(document.createElement('hr'));i++;continue;\n" | ||
| 550 | + " }\n" | ||
| 551 | + " para.push(line);i++;\n" | ||
| 552 | + " }\n" | ||
| 553 | + " flushPara();flushList();\n" | ||
| 554 | + " host.appendChild(box);\n" | ||
| 555 | + "}\n" | ||
| 556 | + "\n" | ||
| 557 | + "/* --- wiring ------------------------------------------------------- */\n" | ||
| 558 | + "\n" | ||
| 559 | + "document.getElementById('btnRefresh').onclick=function(){\n" | ||
| 560 | + " if(curPath)openDir(curPath);else loadRoots();\n" | ||
| 561 | + "};\n" | ||
| 562 | + "document.getElementById('btnUp').onclick=function(){\n" | ||
| 563 | + " if(curParent)openDir(curParent);\n" | ||
| 564 | + " else if(curPath&&curRoot&&curPath!==curRoot)openDir(curRoot);\n" | ||
| 565 | + " else toast('Already at the root');\n" | ||
| 566 | + "};\n" | ||
| 567 | + "document.getElementById('btnBack').onclick=function(){setView('browse');};\n" | ||
| 568 | + "document.getElementById('btnTheme').onclick=function(){\n" | ||
| 569 | + " if(window.sxApplyTheme)window.sxApplyTheme(window.sxTheme&&window.sxTheme()==='dark'?'light':'dark');\n" | ||
| 570 | + "};\n" | ||
| 571 | + "btnHidden.onclick=function(){\n" | ||
| 572 | + " showHidden=!showHidden;\n" | ||
| 573 | + " btnHidden.classList.toggle('on',showHidden);\n" | ||
| 574 | + " btnHidden.title=showHidden?'Hide hidden files':'Show hidden files';\n" | ||
| 575 | + " if(curPath)openDir(curPath);\n" | ||
| 576 | + "};\n" | ||
| 577 | + "btnDownload.onclick=function(){\n" | ||
| 578 | + " if(!curFile)return;\n" | ||
| 579 | + " var a=document.createElement('a');\n" | ||
| 580 | + " a.href=url('raw','path='+encodeURIComponent(curFile)+'&download=1');\n" | ||
| 581 | + " a.rel='noopener';\n" | ||
| 582 | + " document.body.appendChild(a);a.click();document.body.removeChild(a);\n" | ||
| 583 | + "};\n" | ||
| 584 | + "\n" | ||
| 585 | + "document.addEventListener('keydown',function(ev){\n" | ||
| 586 | + " var tag=(ev.target&&ev.target.tagName||'').toLowerCase();\n" | ||
| 587 | + " if(tag==='input'||tag==='textarea')return;\n" | ||
| 588 | + " if(ev.key==='ArrowDown'||ev.key==='ArrowUp'){\n" | ||
| 589 | + " if(!entries.length)return;\n" | ||
| 590 | + " ev.preventDefault();\n" | ||
| 591 | + " selIndex+=(ev.key==='ArrowDown'?1:-1);\n" | ||
| 592 | + " if(selIndex<0)selIndex=0;\n" | ||
| 593 | + " if(selIndex>=entries.length)selIndex=entries.length-1;\n" | ||
| 594 | + " renderEntries();\n" | ||
| 595 | + " }else if(ev.key==='Enter'){\n" | ||
| 596 | + " if(selIndex>=0&&entries[selIndex]){ev.preventDefault();activate(entries[selIndex]);}\n" | ||
| 597 | + " }else if(ev.key==='Backspace'){\n" | ||
| 598 | + " if(curParent){ev.preventDefault();openDir(curParent);}\n" | ||
| 599 | + " }else if(ev.key==='/'&&ev.ctrlKey===false){\n" | ||
| 600 | + " return;\n" | ||
| 601 | + " }\n" | ||
| 602 | + "});\n" | ||
| 603 | + "\n" | ||
| 604 | + "function loadRoots(){\n" | ||
| 605 | + " return api('roots').then(function(d){\n" | ||
| 606 | + " roots=(d&&d.roots)||[];\n" | ||
| 607 | + " renderRoots();\n" | ||
| 608 | + " /* Wide screens open the first root straight away; a phone keeps the root\n" | ||
| 609 | + " * list on screen, because a hidden sidebar there means an empty page. */\n" | ||
| 610 | + " if(roots.length&&!curPath&&window.matchMedia('(min-width:821px)').matches){\n" | ||
| 611 | + " openDir(roots[0].path);\n" | ||
| 612 | + " }\n" | ||
| 613 | + " }).catch(function(e){toast('Cannot list roots: '+e.message);});\n" | ||
| 614 | + "}\n" | ||
| 615 | + "\n" | ||
| 616 | + "loadRoots();\n" | ||
| 617 | + "})();\n" | ||
| 618 | + "</script>\n" | ||
| 619 | + "\002</body></html>\n" | ||
| 620 | + ; | ||
| 621 | + | ||
| 622 | +#endif /* SX_FILES_UI_HTML_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..96f389a | index 0000000..96f389a | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/e2e.py | +++ b/tests/e2e.py | ||
| @@ -0,0 +1,317 @@ | @@ -0,0 +1,317 @@ | ||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""tests/e2e.py - viewport checks for the plugin_files browser. | ||
| 3 | + | ||
| 4 | +Serves the plugin through a small CGI-ish HTTP shim on a loopback port, opens | ||
| 5 | +it with Playwright at 1440 / 1024 / 390 CSS pixels in both themes, and asserts: | ||
| 6 | + | ||
| 7 | + * no console error and no page error at any viewport | ||
| 8 | + * scrollWidth <= innerWidth (no horizontal overflow) | ||
| 9 | + * the root list renders, a directory opens, a text file previews with line | ||
| 10 | + numbers, a markdown file renders, an image previews | ||
| 11 | + * the rendered page really has a stylesheet and a working script | ||
| 12 | + * screenshots land in docs/ for the README | ||
| 13 | + | ||
| 14 | +Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays | ||
| 15 | +dependency-free. | ||
| 16 | + | ||
| 17 | + python3 tests/e2e.py # run if Playwright is available | ||
| 18 | + python3 tests/e2e.py --strict # exit 2 when Playwright is missing | ||
| 19 | +""" | ||
| 20 | + | ||
| 21 | +import argparse | ||
| 22 | +import http.server | ||
| 23 | +import os | ||
| 24 | +import shutil | ||
| 25 | +import socketserver | ||
| 26 | +import subprocess | ||
| 27 | +import sys | ||
| 28 | +import tempfile | ||
| 29 | +import threading | ||
| 30 | +from urllib.parse import urlparse | ||
| 31 | + | ||
| 32 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 33 | +BIN = os.path.join(ROOT, "plugin_files") | ||
| 34 | +DOCS = os.path.join(ROOT, "docs") | ||
| 35 | +VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] | ||
| 36 | +THEMES = ["dark", "light"] | ||
| 37 | + | ||
| 38 | +PNG_1PX = ( | ||
| 39 | + b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01" | ||
| 40 | + b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00\x01" | ||
| 41 | + b"\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82" | ||
| 42 | +) | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +class Handler(http.server.BaseHTTPRequestHandler): | ||
| 46 | + root_dir = "" | ||
| 47 | + | ||
| 48 | + def _run(self, method): | ||
| 49 | + u = urlparse(self.path) | ||
| 50 | + length = int(self.headers.get("Content-Length") or 0) | ||
| 51 | + body = self.rfile.read(length) if length else b"" | ||
| 52 | + env = dict(os.environ) | ||
| 53 | + env["QUERY_STRING"] = u.query | ||
| 54 | + env["REQUEST_METHOD"] = method | ||
| 55 | + env["FILES_ALLOWED_ROOT"] = self.root_dir | ||
| 56 | + env.pop("BOT_PASSWORD", None) | ||
| 57 | + env["CONTENT_LENGTH"] = str(len(body)) | ||
| 58 | + out = subprocess.run( | ||
| 59 | + [BIN], input=body, capture_output=True, env=env, timeout=60 | ||
| 60 | + ).stdout | ||
| 61 | + sep = out.find(b"\r\n\r\n") | ||
| 62 | + headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" | ||
| 63 | + payload = out[sep + 4:] if sep >= 0 else out | ||
| 64 | + status = 200 | ||
| 65 | + ctype = "application/json; charset=utf-8" | ||
| 66 | + for line in headers.splitlines(): | ||
| 67 | + low = line.lower() | ||
| 68 | + if low.startswith("content-type:"): | ||
| 69 | + ctype = line.split(":", 1)[1].strip() | ||
| 70 | + elif low.startswith("status:"): | ||
| 71 | + try: | ||
| 72 | + status = int(line.split(":", 1)[1].strip().split()[0]) | ||
| 73 | + except (IndexError, ValueError): | ||
| 74 | + status = 200 | ||
| 75 | + self.send_response(status) | ||
| 76 | + self.send_header("Content-Type", ctype) | ||
| 77 | + self.send_header("Cache-Control", "no-store") | ||
| 78 | + self.send_header("Content-Length", str(len(payload))) | ||
| 79 | + self.end_headers() | ||
| 80 | + self.wfile.write(payload) | ||
| 81 | + | ||
| 82 | + def do_GET(self): # noqa: N802 | ||
| 83 | + self._run("GET") | ||
| 84 | + | ||
| 85 | + def do_POST(self): # noqa: N802 | ||
| 86 | + self._run("POST") | ||
| 87 | + | ||
| 88 | + def log_message(self, *_a): | ||
| 89 | + pass | ||
| 90 | + | ||
| 91 | + | ||
| 92 | +def seed(root_dir): | ||
| 93 | + os.makedirs(os.path.join(root_dir, "src"), exist_ok=True) | ||
| 94 | + os.makedirs(os.path.join(root_dir, "docs"), exist_ok=True) | ||
| 95 | + | ||
| 96 | + with open(os.path.join(root_dir, "README.md"), "w", encoding="utf-8") as f: | ||
| 97 | + f.write( | ||
| 98 | + "# Local File Browser\n\n" | ||
| 99 | + "A read-only browser for **SCORPIOX BOT** nodes.\n\n" | ||
| 100 | + "- list directories inside the allowlisted roots\n" | ||
| 101 | + "- preview text with line numbers\n" | ||
| 102 | + "- view images and download files\n\n" | ||
| 103 | + "> Nothing on disk can be modified by this plugin.\n\n" | ||
| 104 | + "```\ncurl 'http://node:8150/plugin_files?action=roots'\n```\n" | ||
| 105 | + ) | ||
| 106 | + with open(os.path.join(root_dir, "src", "main.c"), "w", encoding="utf-8") as f: | ||
| 107 | + f.write("#include <stdio.h>\n\nint main(void)\n{\n puts(\"hi\");\n return 0;\n}\n") | ||
| 108 | + with open(os.path.join(root_dir, "notes.txt"), "w", encoding="utf-8") as f: | ||
| 109 | + f.write("line one\nline two\nline three\n") | ||
| 110 | + with open(os.path.join(root_dir, "blob.bin"), "wb") as f: | ||
| 111 | + f.write(b"PK\x03\x04\x00\x00binary\x00data\x00") | ||
| 112 | + with open(os.path.join(root_dir, "docs", "pixel.png"), "wb") as f: | ||
| 113 | + f.write(PNG_1PX) | ||
| 114 | + with open(os.path.join(root_dir, ".hiddenrc"), "w", encoding="utf-8") as f: | ||
| 115 | + f.write("hidden\n") | ||
| 116 | + | ||
| 117 | + | ||
| 118 | +def main(): | ||
| 119 | + ap = argparse.ArgumentParser() | ||
| 120 | + ap.add_argument("--strict", action="store_true", | ||
| 121 | + help="exit 2 when Playwright is not installed") | ||
| 122 | + args = ap.parse_args() | ||
| 123 | + | ||
| 124 | + try: | ||
| 125 | + from playwright.sync_api import sync_playwright | ||
| 126 | + except Exception: | ||
| 127 | + print("playwright not installed - skipping e2e (offline suite is unaffected)") | ||
| 128 | + return 2 if args.strict else 0 | ||
| 129 | + | ||
| 130 | + if not os.path.exists(BIN): | ||
| 131 | + print("plugin_files not built - run make first") | ||
| 132 | + return 1 | ||
| 133 | + | ||
| 134 | + work = tempfile.mkdtemp(prefix="files-e2e-") | ||
| 135 | + root_dir = os.path.join(work, "root") | ||
| 136 | + os.makedirs(root_dir, exist_ok=True) | ||
| 137 | + seed(root_dir) | ||
| 138 | + Handler.root_dir = root_dir | ||
| 139 | + | ||
| 140 | + httpd = socketserver.TCPServer(("127.0.0.1", 0), Handler) | ||
| 141 | + port = httpd.server_address[1] | ||
| 142 | + threading.Thread(target=httpd.serve_forever, daemon=True).start() | ||
| 143 | + base = "http://127.0.0.1:%d/" % port | ||
| 144 | + | ||
| 145 | + os.makedirs(DOCS, exist_ok=True) | ||
| 146 | + failures = [] | ||
| 147 | + checks = 0 | ||
| 148 | + | ||
| 149 | + def ok(cond, label): | ||
| 150 | + nonlocal checks | ||
| 151 | + checks += 1 | ||
| 152 | + if not cond: | ||
| 153 | + failures.append(label) | ||
| 154 | + print(" FAIL %s" % label) | ||
| 155 | + | ||
| 156 | + try: | ||
| 157 | + with sync_playwright() as pw: | ||
| 158 | + browser = pw.chromium.launch() | ||
| 159 | + for w, h in VIEWPORTS: | ||
| 160 | + for theme in THEMES: | ||
| 161 | + page = browser.new_page(viewport={"width": w, "height": h}, | ||
| 162 | + color_scheme=theme) | ||
| 163 | + errors = [] | ||
| 164 | + page.on("console", lambda m: errors.append(m.text) | ||
| 165 | + if m.type == "error" else None) | ||
| 166 | + page.on("pageerror", lambda e: errors.append(str(e))) | ||
| 167 | + | ||
| 168 | + page.goto(base + "?theme=%s" % theme, wait_until="load") | ||
| 169 | + page.wait_for_selector(".root", timeout=8000) | ||
| 170 | + | ||
| 171 | + ok(page.locator(".root").count() >= 1, | ||
| 172 | + "roots rendered @%dx%d %s" % (w, h, theme)) | ||
| 173 | + # the seeded root is the last one, so pick it by its path | ||
| 174 | + page.evaluate( | ||
| 175 | + "ROOTPATH => Array.from(document.querySelectorAll('.root'))" | ||
| 176 | + ".filter(function(b){return b.textContent.indexOf(ROOTPATH)>=0;})[0]" | ||
| 177 | + ".click()", root_dir) | ||
| 178 | + page.wait_for_function( | ||
| 179 | + "document.querySelectorAll('.row').length >= 4", | ||
| 180 | + timeout=8000) | ||
| 181 | + page.wait_for_selector(".row", timeout=8000) | ||
| 182 | + | ||
| 183 | + ok(page.locator(".row").count() >= 4, | ||
| 184 | + "entries listed @%dx%d %s" % (w, h, theme)) | ||
| 185 | + ok(page.locator(".row.dir").count() >= 2, | ||
| 186 | + "directories first @%dx%d %s" % (w, h, theme)) | ||
| 187 | + ok(".hiddenrc" not in page.inner_text("#entries"), | ||
| 188 | + "hidden files hidden by default @%dx%d %s" % (w, h, theme)) | ||
| 189 | + | ||
| 190 | + sw = page.evaluate("document.documentElement.scrollWidth") | ||
| 191 | + iw = page.evaluate("window.innerWidth") | ||
| 192 | + ok(sw <= iw + 1, "no h-overflow (%d<=%d) @%dx%d %s" | ||
| 193 | + % (sw, iw, w, h, theme)) | ||
| 194 | + | ||
| 195 | + # a real stylesheet, not plain text in the page | ||
| 196 | + ok(page.evaluate( | ||
| 197 | + "document.styleSheets.length>0 && " | ||
| 198 | + "Array.from(document.styleSheets)" | ||
| 199 | + ".reduce(function(n,s){return n+s.cssRules.length;},0)>80"), | ||
| 200 | + "stylesheet parsed @%dx%d %s" % (w, h, theme)) | ||
| 201 | + | ||
| 202 | + # open the markdown file -> rendered headings and bold | ||
| 203 | + page.evaluate( | ||
| 204 | + "Array.from(document.querySelectorAll('.row'))" | ||
| 205 | + ".filter(function(b){return b.textContent.indexOf('README.md')>=0;})[0]" | ||
| 206 | + ".click()") | ||
| 207 | + page.wait_for_selector(".md h1", timeout=8000) | ||
| 208 | + html = page.inner_html(".md") | ||
| 209 | + ok("<h1>Local File Browser</h1>" in html, | ||
| 210 | + "markdown h1 rendered @%dx%d %s" % (w, h, theme)) | ||
| 211 | + ok("<strong>SCORPIOX BOT</strong>" in html, | ||
| 212 | + "markdown bold rendered @%dx%d %s" % (w, h, theme)) | ||
| 213 | + ok("<script>" not in html, | ||
| 214 | + "no raw script tag in preview @%dx%d %s" % (w, h, theme)) | ||
| 215 | + | ||
| 216 | + # text preview has line numbers | ||
| 217 | + page.evaluate( | ||
| 218 | + "Array.from(document.querySelectorAll('.row'))" | ||
| 219 | + ".filter(function(b){return b.textContent.indexOf('notes.txt')>=0;})[0]" | ||
| 220 | + ".click()") | ||
| 221 | + page.wait_for_selector(".codetxt", timeout=8000) | ||
| 222 | + ok(page.inner_text(".codetxt .ln").startswith("1"), | ||
| 223 | + "line numbers start at 1 @%dx%d %s" % (w, h, theme)) | ||
| 224 | + ok("line three" in page.inner_text(".codetxt .tx"), | ||
| 225 | + "text body rendered @%dx%d %s" % (w, h, theme)) | ||
| 226 | + | ||
| 227 | + # binary file degrades to a note, never to mojibake | ||
| 228 | + page.evaluate( | ||
| 229 | + "Array.from(document.querySelectorAll('.row'))" | ||
| 230 | + ".filter(function(b){return b.textContent.indexOf('blob.bin')>=0;})[0]" | ||
| 231 | + ".click()") | ||
| 232 | + page.wait_for_selector(".note", timeout=8000) | ||
| 233 | + ok("Binary file" in page.inner_text(".note"), | ||
| 234 | + "binary file explained @%dx%d %s" % (w, h, theme)) | ||
| 235 | + | ||
| 236 | + # image opens in an <img> | ||
| 237 | + page.evaluate( | ||
| 238 | + "Array.from(document.querySelectorAll('.row.dir'))" | ||
| 239 | + ".filter(function(b){return b.textContent.indexOf('docs')>=0;})[0]" | ||
| 240 | + ".click()") | ||
| 241 | + page.wait_for_function( | ||
| 242 | + "Array.from(document.querySelectorAll('.row'))" | ||
| 243 | + ".some(function(b){return b.textContent.indexOf('pixel.png')>=0;})", | ||
| 244 | + timeout=8000) | ||
| 245 | + page.evaluate( | ||
| 246 | + "Array.from(document.querySelectorAll('.row'))" | ||
| 247 | + ".filter(function(b){return b.textContent.indexOf('pixel.png')>=0;})[0]" | ||
| 248 | + ".click()") | ||
| 249 | + page.wait_for_selector(".imgwrap img", timeout=8000) | ||
| 250 | + ok(page.evaluate( | ||
| 251 | + "document.querySelector('.imgwrap img').naturalWidth > 0"), | ||
| 252 | + "image decoded @%dx%d %s" % (w, h, theme)) | ||
| 253 | + | ||
| 254 | + # hidden toggle reveals the dotfile | ||
| 255 | + # the sidebar is hidden on a phone while a preview is open, | ||
| 256 | + # so drive the toggle the way a user would after Back | ||
| 257 | + page.evaluate("document.getElementById('btnHidden').click()") | ||
| 258 | + page.wait_for_function( | ||
| 259 | + "Array.from(document.querySelectorAll('.row'))" | ||
| 260 | + ".some(function(b){return b.textContent.indexOf('pixel.png')>=0;})", | ||
| 261 | + timeout=8000) | ||
| 262 | + ok(page.evaluate( | ||
| 263 | + "document.documentElement.scrollWidth <= window.innerWidth + 1"), | ||
| 264 | + "no h-overflow after toggle @%dx%d %s" % (w, h, theme)) | ||
| 265 | + | ||
| 266 | + # put the toggle back so the README shot is the default view | ||
| 267 | + page.evaluate("document.getElementById('btnHidden').click()") | ||
| 268 | + page.wait_for_function( | ||
| 269 | + "!Array.from(document.querySelectorAll('.row'))" | ||
| 270 | + ".some(function(b){return b.textContent.indexOf('.hiddenrc')>=0;})", | ||
| 271 | + timeout=8000) | ||
| 272 | + | ||
| 273 | + # screenshot of the browser with a markdown preview open | ||
| 274 | + page.evaluate( | ||
| 275 | + "Array.from(document.querySelectorAll('.crumb'))[0].click()") | ||
| 276 | + page.wait_for_function( | ||
| 277 | + "Array.from(document.querySelectorAll('.row'))" | ||
| 278 | + ".some(function(b){return b.textContent.indexOf('README.md')>=0;})", | ||
| 279 | + timeout=8000) | ||
| 280 | + page.evaluate( | ||
| 281 | + "Array.from(document.querySelectorAll('.row'))" | ||
| 282 | + ".filter(function(b){return b.textContent.indexOf('README.md')>=0;})[0]" | ||
| 283 | + ".click()") | ||
| 284 | + page.wait_for_selector(".md h1", timeout=8000) | ||
| 285 | + page.evaluate("document.querySelector('.prev-body').scrollTop = 0") | ||
| 286 | + shot = os.path.join(DOCS, "ui-%d-%s.png" % (w, theme)) | ||
| 287 | + page.screenshot(path=shot) | ||
| 288 | + | ||
| 289 | + ok(len(errors) == 0, "no console/page errors @%dx%d %s (%s)" | ||
| 290 | + % (w, h, theme, "; ".join(errors[:2]))) | ||
| 291 | + page.close() | ||
| 292 | + | ||
| 293 | + # embed mode hides the theme toggle | ||
| 294 | + page = browser.new_page(viewport={"width": 1024, "height": 768}) | ||
| 295 | + page.goto(base + "?embed=1&theme=dark", wait_until="load") | ||
| 296 | + page.wait_for_selector(".root", timeout=8000) | ||
| 297 | + ok(not page.is_visible("#btnTheme"), "embed hides the theme toggle") | ||
| 298 | + ok(page.evaluate( | ||
| 299 | + "document.documentElement.classList.contains('embedded')"), | ||
| 300 | + "embed marks html.embedded") | ||
| 301 | + page.close() | ||
| 302 | + browser.close() | ||
| 303 | + finally: | ||
| 304 | + httpd.shutdown() | ||
| 305 | + shutil.rmtree(work, ignore_errors=True) | ||
| 306 | + | ||
| 307 | + print("\n%d checks, %d failure(s)" % (checks, len(failures))) | ||
| 308 | + if failures: | ||
| 309 | + for f in failures: | ||
| 310 | + print(" - %s" % f) | ||
| 311 | + return 1 | ||
| 312 | + print("RESULT: OK") | ||
| 313 | + return 0 | ||
| 314 | + | ||
| 315 | + | ||
| 316 | +if __name__ == "__main__": | ||
| 317 | + sys.exit(main()) |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..d8a02de | index 0000000..d8a02de | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/run.sh | +++ b/tests/run.sh | ||
| @@ -0,0 +1,490 @@ | @@ -0,0 +1,490 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/run.sh - offline checks for plugin_files across all 3 modes. | ||
| 3 | +# | ||
| 4 | +# Every check runs against ./plugin_files with FILES_ALLOWED_ROOT pointing at a | ||
| 5 | +# throwaway fixture tree, so the suite never reads anything real. It proves the | ||
| 6 | +# public contract end to end: --meta, node auth on every action, each action's | ||
| 7 | +# JSON shape, the read-only promise, the 1 MiB preview cap, binary detection, | ||
| 8 | +# raw streaming checksums, directory ordering, hidden-file toggle, traversal | ||
| 9 | +# and symlink negatives -> 403/400, the generated UI (no CDN, no <script src=>), | ||
| 10 | +# the MinGW PE header when present, a _FORTIFY_SOURCE=2 build that must run | ||
| 11 | +# clean, and a full-history audit for secrets and LAN addresses. | ||
| 12 | +# | ||
| 13 | +# Exit code 0 = everything passed. | ||
| 14 | + | ||
| 15 | +set -u | ||
| 16 | + | ||
| 17 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | ||
| 18 | +cd "$ROOT" || exit 1 | ||
| 19 | + | ||
| 20 | +BIN=./plugin_files | ||
| 21 | +PASS=0 | ||
| 22 | +FAIL=0 | ||
| 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 400)" | ||
| 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 | + | ||
| 46 | +# strip CGI headers if present, drop CRs, keep the payload | ||
| 47 | +body() { | ||
| 48 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | ||
| 49 | + BEGIN { inhdr = 0 } | ||
| 50 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Content-Security-Policy|Content-Disposition):/) { inhdr = 1; next } | ||
| 51 | + inhdr && $0 == "" { inhdr = 0; next } | ||
| 52 | + inhdr { next } | ||
| 53 | + { print } | ||
| 54 | + ' | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +json_ok() { # json_ok <desc> <json> [python-expression] | ||
| 58 | + expr=${3:-True} | ||
| 59 | + printf '%s' "$2" > "$WORK/j.json" | ||
| 60 | + if python3 -c "import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if ($expr) else 1)" "$WORK/j.json" 2>/dev/null; then | ||
| 61 | + pass "$1" | ||
| 62 | + else | ||
| 63 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | ||
| 64 | + fi | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +api() { body "$(QUERY_STRING="$1" $BIN)"; } | ||
| 68 | + | ||
| 69 | +# raw output including CGI headers, for the Status: assertions | ||
| 70 | +apiraw() { QUERY_STRING="$1" $BIN; } | ||
| 71 | + | ||
| 72 | +status_of() { printf '%s' "$1" | tr -d '\r' | sed -n 's/^Status: \([0-9][0-9][0-9]\).*/\1/p' | head -1; } | ||
| 73 | + | ||
| 74 | +# ---------------------------------------------------------------- build | ||
| 75 | +section "build" | ||
| 76 | +if [ ! -x "$BIN" ]; then | ||
| 77 | + echo " building native binary..." | ||
| 78 | + cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o "$BIN" src/plugin_files.c \ | ||
| 79 | + || { echo " build failed"; exit 1; } | ||
| 80 | + pass "native build" | ||
| 81 | +else | ||
| 82 | + pass "native binary present" | ||
| 83 | +fi | ||
| 84 | + | ||
| 85 | +WORK=$(mktemp -d "${TMPDIR:-/tmp}/files-test.XXXXXX") || exit 1 | ||
| 86 | +trap 'rm -rf "$WORK"' INT TERM EXIT | ||
| 87 | +FX="$WORK/root" | ||
| 88 | +mkdir -p "$FX/sub/deep/deeper" "$FX/emptydir" "$FX/.hiddendir" "$FX/pics" || exit 1 | ||
| 89 | + | ||
| 90 | +printf 'hello world\nsecond line\n' > "$FX/a.txt" | ||
| 91 | +printf '# Title\n\nSome **bold** text and a [link](https://example.com).\n\n- one\n- two\n' > "$FX/readme.md" | ||
| 92 | +printf 'abc\000def\000ghi' > "$FX/bin.dat" | ||
| 93 | +printf 'hidden content\n' > "$FX/.hidden" | ||
| 94 | +: > "$FX/empty.txt" | ||
| 95 | +printf 'deep\n' > "$FX/sub/deep/deeper/leaf.txt" | ||
| 96 | +printf 'in sub\n' > "$FX/sub/inner.txt" | ||
| 97 | +python3 -c "open('$FX/big.txt','w').write('x'*(2*1024*1024))" | ||
| 98 | +python3 -c " | ||
| 99 | +import struct,zlib | ||
| 100 | +def chunk(t,d): | ||
| 101 | + return struct.pack('>I',len(d))+t+d+struct.pack('>I',zlib.crc32(t+d)&0xffffffff) | ||
| 102 | +raw=b'\x00\xff\x00\xff' | ||
| 103 | +idat=zlib.compress(raw) | ||
| 104 | +png=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',2,1,8,2,0,0,0))+chunk(b'IDAT',idat)+chunk(b'IEND',b'') | ||
| 105 | +open('$FX/pics/px.png','wb').write(png) | ||
| 106 | +" | ||
| 107 | +ln -s /etc "$FX/etclink" | ||
| 108 | +ln -s "$FX/a.txt" "$FX/goodlink" | ||
| 109 | + | ||
| 110 | +export FILES_ALLOWED_ROOT="$FX" | ||
| 111 | +unset BOT_PASSWORD | ||
| 112 | + | ||
| 113 | +# ---------------------------------------------------------------- meta | ||
| 114 | +section "--meta / --version" | ||
| 115 | +M=$($BIN --meta) | ||
| 116 | +check "--meta emits name" '"name":"files"' "$M" | ||
| 117 | +check "--meta desc" '"desc":"File browser"' "$M" | ||
| 118 | +json_ok "--meta is valid JSON" "$M" "d['name']=='files' and d['desc']=='File browser'" | ||
| 119 | +M2=$(SX_PLUGIN_META=1 $BIN) | ||
| 120 | +check "SX_PLUGIN_META also emits meta" '"name":"files"' "$M2" | ||
| 121 | +V=$($BIN --version) | ||
| 122 | +check "--version" 'plugin_files 1.0.0' "$V" | ||
| 123 | + | ||
| 124 | +# ---------------------------------------------------------------- auth | ||
| 125 | +section "node auth" | ||
| 126 | +export BOT_PASSWORD=testpw | ||
| 127 | +R=$(apiraw "action=roots") | ||
| 128 | +check "no password -> 401" '401' "$(status_of "$R")" | ||
| 129 | +R=$(apiraw "action=ls&path=$FX") | ||
| 130 | +check "ls without password -> 401" '401' "$(status_of "$R")" | ||
| 131 | +R=$(apiraw "action=read&path=$FX/a.txt") | ||
| 132 | +check "read without password -> 401" '401' "$(status_of "$R")" | ||
| 133 | +R=$(apiraw "action=raw&path=$FX/a.txt") | ||
| 134 | +check "raw without password -> 401" '401' "$(status_of "$R")" | ||
| 135 | +R=$(apiraw "") | ||
| 136 | +check "HTML page without password -> 401" '401' "$(status_of "$R")" | ||
| 137 | +M=$($BIN --meta) | ||
| 138 | +check "--meta stays unauthenticated" '"name":"files"' "$M" | ||
| 139 | +R=$(HTTP_X_BOT_PASSWORD=testpw apiraw "action=roots") | ||
| 140 | +check "X-Bot-Password accepted" '"ok":true' "$(body "$R")" | ||
| 141 | +R=$(HTTP_AUTHORIZATION="Bearer testpw" apiraw "action=roots") | ||
| 142 | +check "Bearer token accepted" '"ok":true' "$(body "$R")" | ||
| 143 | +R=$(apiraw "action=roots&pwd=testpw") | ||
| 144 | +check "?pwd= accepted" '"ok":true' "$(body "$R")" | ||
| 145 | +R=$(apiraw "action=roots&pwd=wrong") | ||
| 146 | +check "wrong ?pwd= -> 401" '401' "$(status_of "$R")" | ||
| 147 | +unset BOT_PASSWORD | ||
| 148 | + | ||
| 149 | +# ---------------------------------------------------------------- roots | ||
| 150 | +section "?action=roots" | ||
| 151 | +R=$(api "action=roots") | ||
| 152 | +json_ok "roots ok" "$R" "d['ok'] is True" | ||
| 153 | +json_ok "roots has a list" "$R" "isinstance(d['roots'],list) and len(d['roots'])>=1" | ||
| 154 | +json_ok "fixture root is present" "$R" "any(r['path']=='$FX' for r in d['roots'])" | ||
| 155 | +json_ok "each root has name+path" "$R" "all('name' in r and 'path' in r for r in d['roots'])" | ||
| 156 | +json_ok "count matches list length" "$R" "d['count']==len(d['roots'])" | ||
| 157 | +json_ok "no /proc root" "$R" "all(r['path']!='/proc' for r in d['roots'])" | ||
| 158 | +json_ok "no /sys root" "$R" "all(r['path']!='/sys' for r in d['roots'])" | ||
| 159 | +json_ok "no /dev root" "$R" "all(r['path']!='/dev' for r in d['roots'])" | ||
| 160 | +R=$(api "format=json") | ||
| 161 | +json_ok "format=json falls back to roots" "$R" "d['ok'] is True and 'roots' in d" | ||
| 162 | + | ||
| 163 | +# ---------------------------------------------------------------- ls | ||
| 164 | +section "?action=ls" | ||
| 165 | +R=$(api "action=ls&path=$FX") | ||
| 166 | +json_ok "ls ok" "$R" "d['ok'] is True" | ||
| 167 | +json_ok "ls path echoed" "$R" "d['path']=='$FX'" | ||
| 168 | +json_ok "ls root is the fixture" "$R" "d['root']=='$FX'" | ||
| 169 | +json_ok "ls parent is null at a root" "$R" "d['parent'] is None" | ||
| 170 | +json_ok "ls count matches entries" "$R" "d['count']==len(d['entries'])" | ||
| 171 | +json_ok "ls not truncated" "$R" "d['truncated'] is False" | ||
| 172 | +json_ok "hidden off by default" "$R" "d['hidden']==0" | ||
| 173 | +json_ok "no dotfiles by default" "$R" "not any(e['name'].startswith('.') for e in d['entries'])" | ||
| 174 | +json_ok "dirs sort before files" "$R" "[e['type'] for e in d['entries']]==sorted([e['type'] for e in d['entries']], key=lambda t:(t!='dir'))" | ||
| 175 | +json_ok "names sorted dirs-first" "$R" "(lambda d:[e['name'] for e in d['entries'] if e['type']=='dir']==sorted([e['name'] for e in d['entries'] if e['type']=='dir'],key=str.lower) and [e['name'] for e in d['entries'] if e['type']!='dir']==sorted([e['name'] for e in d['entries'] if e['type']!='dir'],key=str.lower))(d)" | ||
| 176 | +json_ok "entry has size/mtime/mode" "$R" "all('size' in e and 'mtime' in e and 'mode' in e for e in d['entries'])" | ||
| 177 | +json_ok "dir entry flagged" "$R" "any(e['name']=='sub' and e['type']=='dir' for e in d['entries'])" | ||
| 178 | +json_ok "file entry flagged" "$R" "any(e['name']=='a.txt' and e['type']=='file' for e in d['entries'])" | ||
| 179 | +json_ok "a.txt size is 24" "$R" "any(e['name']=='a.txt' and e['size']==24 for e in d['entries'])" | ||
| 180 | +json_ok "mtime is ISO-8601" "$R" "all(len(e['mtime'])==20 and e['mtime'].endswith('Z') for e in d['entries'] if e['mtime'])" | ||
| 181 | +json_ok "mode is octal string" "$R" "all(e['mode'].isdigit() and len(e['mode'])==4 for e in d['entries'])" | ||
| 182 | +json_ok "empty file listed with size 0" "$R" "any(e['name']=='empty.txt' and e['size']==0 for e in d['entries'])" | ||
| 183 | + | ||
| 184 | +R=$(api "action=ls&path=$FX&hidden=1") | ||
| 185 | +json_ok "hidden=1 flags hidden" "$R" "d['hidden']==1" | ||
| 186 | +json_ok "hidden=1 shows dotfile" "$R" "any(e['name']=='.hidden' for e in d['entries'])" | ||
| 187 | +json_ok "hidden=1 shows dotdir" "$R" "any(e['name']=='.hiddendir' and e['type']=='dir' for e in d['entries'])" | ||
| 188 | + | ||
| 189 | +R=$(api "action=ls&path=$FX&hidden=true") | ||
| 190 | +json_ok "hidden=true also works" "$R" "any(e['name']=='.hidden' for e in d['entries'])" | ||
| 191 | + | ||
| 192 | +R=$(api "action=ls&path=$FX/sub") | ||
| 193 | +json_ok "nested parent is computed" "$R" "d['parent']=='$FX'" | ||
| 194 | +json_ok "nested root is still the fixture" "$R" "d['root']=='$FX'" | ||
| 195 | +json_ok "nested lists its own children" "$R" "any(e['name']=='inner.txt' for e in d['entries'])" | ||
| 196 | + | ||
| 197 | +R=$(api "action=ls&path=$FX/emptydir") | ||
| 198 | +json_ok "empty dir answers count 0" "$R" "d['count']==0 and d['entries']==[]" | ||
| 199 | + | ||
| 200 | +R=$(api "action=ls&path=$FX/goodlink") | ||
| 201 | +json_ok "symlink inside the root is browsable as a file" "$R" "'ok' in d" | ||
| 202 | + | ||
| 203 | +R=$(api "action=ls") | ||
| 204 | +json_ok "ls without path defaults to the first root" "$R" "d['ok'] is True and d['path'].startswith('/')" | ||
| 205 | + | ||
| 206 | +# ---------------------------------------------------------------- read | ||
| 207 | +section "?action=read" | ||
| 208 | +R=$(api "action=read&path=$FX/a.txt") | ||
| 209 | +json_ok "read ok" "$R" "d['ok'] is True" | ||
| 210 | +json_ok "read text" "$R" "d['text']=='hello world\\nsecond line\\n'" | ||
| 211 | +json_ok "read binary false" "$R" "d['binary'] is False" | ||
| 212 | +json_ok "read truncated false" "$R" "d['truncated'] is False" | ||
| 213 | +json_ok "read bytes_read matches file" "$R" "d['bytes_read']==24" | ||
| 214 | +json_ok "read name echoed" "$R" "d['name']=='a.txt'" | ||
| 215 | +json_ok "read size echoed" "$R" "d['size']==24" | ||
| 216 | +json_ok "read mode present" "$R" "len(d['mode'])==4" | ||
| 217 | +json_ok "read has no text key for binary" "$R" "True" | ||
| 218 | + | ||
| 219 | +R=$(api "action=read&path=$FX/bin.dat") | ||
| 220 | +json_ok "binary detected by NUL" "$R" "d['binary'] is True" | ||
| 221 | +json_ok "binary omits text" "$R" "'text' not in d" | ||
| 222 | +json_ok "binary still reports size" "$R" "d['size']==11" | ||
| 223 | + | ||
| 224 | +R=$(api "action=read&path=$FX/big.txt") | ||
| 225 | +json_ok "big file truncated" "$R" "d['truncated'] is True" | ||
| 226 | +json_ok "big file capped at 1 MiB" "$R" "d['bytes_read']==1048576" | ||
| 227 | +json_ok "big file still reports real size" "$R" "d['size']==2097152" | ||
| 228 | + | ||
| 229 | +R=$(api "action=read&path=$FX/empty.txt") | ||
| 230 | +json_ok "empty file reads as empty text" "$R" "d['text']=='' and d['bytes_read']==0" | ||
| 231 | + | ||
| 232 | +R=$(apiraw "action=read&path=$FX") | ||
| 233 | +check "read a directory -> 400" '400' "$(status_of "$R")" | ||
| 234 | + | ||
| 235 | +# ---------------------------------------------------------------- raw | ||
| 236 | +section "?action=raw" | ||
| 237 | +RAWR=$(apiraw "action=raw&path=$FX/a.txt") | ||
| 238 | +HDRS=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p') | ||
| 239 | +check "raw content-type text/plain" 'Content-Type: text/plain; charset=utf-8' "$HDRS" | ||
| 240 | +check "raw attachment for text" 'Content-Disposition: attachment' "$HDRS" | ||
| 241 | +check "raw has no manual Content-Length" '0' "$(printf '%s' "$HDRS" | grep -c 'Content-Length')" | ||
| 242 | +check "raw nosniff" 'X-Content-Type-Options: nosniff' "$HDRS" | ||
| 243 | +check "raw sameorigin" 'X-Frame-Options: SAMEORIGIN' "$HDRS" | ||
| 244 | + | ||
| 245 | +# payload after the blank line must be byte-identical to the file | ||
| 246 | +python3 -c " | ||
| 247 | +import subprocess,sys,os,hashlib | ||
| 248 | +env=dict(os.environ); env['QUERY_STRING']='action=raw&path=$FX/a.txt' | ||
| 249 | +out=subprocess.run(['$BIN'],capture_output=True,env=env).stdout | ||
| 250 | +sep=out.find(b'\r\n\r\n') | ||
| 251 | +payload=out[sep+4:] | ||
| 252 | +want=open('$FX/a.txt','rb').read() | ||
| 253 | +sys.exit(0 if payload==want else 1) | ||
| 254 | +" && pass "raw payload equals the file byte-for-byte" || fail "raw payload equals the file byte-for-byte" | ||
| 255 | + | ||
| 256 | +python3 -c " | ||
| 257 | +import subprocess,sys,os,hashlib | ||
| 258 | +env=dict(os.environ); env['QUERY_STRING']='action=raw&path=$FX/pics/px.png' | ||
| 259 | +out=subprocess.run(['$BIN'],capture_output=True,env=env).stdout | ||
| 260 | +sep=out.find(b'\r\n\r\n') | ||
| 261 | +hdr=out[:sep].decode() | ||
| 262 | +payload=out[sep+4:] | ||
| 263 | +want=open('$FX/pics/px.png','rb').read() | ||
| 264 | +ok = payload==want and 'image/png' in hdr and 'inline' in hdr | ||
| 265 | +sys.exit(0 if ok else 1) | ||
| 266 | +" && pass "raw png is image/png, inline, byte-identical" || fail "raw png is image/png, inline, byte-identical" | ||
| 267 | + | ||
| 268 | +RAWR=$(apiraw "action=raw&path=$FX/pics/px.png&download=1") | ||
| 269 | +HDRS=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p') | ||
| 270 | +check "download=1 forces attachment on an image" 'Content-Disposition: attachment' "$HDRS" | ||
| 271 | + | ||
| 272 | +RAWR=$(apiraw "action=raw&path=$FX/readme.md") | ||
| 273 | +HDRS=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p') | ||
| 274 | +check "markdown served as text/plain (never text/html)" 'Content-Type: text/plain; charset=utf-8' "$HDRS" | ||
| 275 | +HDRS_HTML=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p' | grep -c 'text/html') | ||
| 276 | +check "no text/html on raw markdown" '0' "$HDRS_HTML" | ||
| 277 | + | ||
| 278 | +printf 'PK\003\004xxxx' > "$FX/thing.zip" | ||
| 279 | +RAWR=$(apiraw "action=raw&path=$FX/thing.zip") | ||
| 280 | +HDRS=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p') | ||
| 281 | +check "unknown type is octet-stream" 'application/octet-stream' "$HDRS" | ||
| 282 | +check "unknown type is attachment" 'Content-Disposition: attachment' "$HDRS" | ||
| 283 | + | ||
| 284 | +printf '<html><body><script>alert(1)</script></body></html>' > "$FX/evil.html" | ||
| 285 | +RAWR=$(apiraw "action=raw&path=$FX/evil.html") | ||
| 286 | +HDRS=$(printf '%s' "$RAWR" | tr -d '\r' | sed -n '1,/^$/p') | ||
| 287 | +check "html file is served as plain text" 'text/plain' "$HDRS" | ||
| 288 | + | ||
| 289 | +RAWR=$(apiraw "action=raw&path=$FX/big.txt") | ||
| 290 | +PLEN=$(printf '%s' "$RAWR" | wc -c | tr -d ' ') | ||
| 291 | +if [ "$PLEN" -gt 2000000 ]; then pass "raw streams a 2 MB file whole"; else fail "raw streams a 2 MB file whole ($PLEN)"; fi | ||
| 292 | + | ||
| 293 | +# ---------------------------------------------------------------- security | ||
| 294 | +section "security: traversal, symlink escape, denied roots" | ||
| 295 | +R=$(apiraw "action=ls&path=$FX/../..") | ||
| 296 | +check ".. in a path -> 400" '400' "$(status_of "$R")" | ||
| 297 | +R=$(apiraw "action=ls&path=$FX/sub/../../etc") | ||
| 298 | +check "nested .. -> 400" '400' "$(status_of "$R")" | ||
| 299 | +R=$(apiraw "action=ls&path=../../etc") | ||
| 300 | +check "relative .. path -> 400" '400' "$(status_of "$R")" | ||
| 301 | +R=$(apiraw "action=ls&path=$FX/%2e%2e/%2e%2e/etc") | ||
| 302 | +check "percent-encoded .. -> 400" '400' "$(status_of "$R")" | ||
| 303 | +R=$(apiraw "action=read&path=/etc/passwd") | ||
| 304 | +check "read outside every root -> 403" '403' "$(status_of "$R")" | ||
| 305 | +R=$(apiraw "action=ls&path=/etc") | ||
| 306 | +check "ls outside every root -> 403" '403' "$(status_of "$R")" | ||
| 307 | +R=$(apiraw "action=read&path=$FX/etclink/passwd") | ||
| 308 | +check "symlink pointing outside -> 403" '403' "$(status_of "$R")" | ||
| 309 | +R=$(apiraw "action=ls&path=$FX/etclink") | ||
| 310 | +check "ls a symlink that escapes -> 403" '403' "$(status_of "$R")" | ||
| 311 | +R=$(apiraw "action=raw&path=$FX/etclink/hostname") | ||
| 312 | +check "raw through an escaping symlink -> 403" '403' "$(status_of "$R")" | ||
| 313 | +R=$(apiraw "action=ls&path=/proc") | ||
| 314 | +check "/proc refused" '403' "$(status_of "$R")" | ||
| 315 | +R=$(apiraw "action=ls&path=/proc/self") | ||
| 316 | +check "/proc/self refused" '403' "$(status_of "$R")" | ||
| 317 | +R=$(apiraw "action=ls&path=/sys") | ||
| 318 | +check "/sys refused" '403' "$(status_of "$R")" | ||
| 319 | +R=$(apiraw "action=ls&path=/dev") | ||
| 320 | +check "/dev refused" '403' "$(status_of "$R")" | ||
| 321 | +R=$(apiraw "action=ls&path=") | ||
| 322 | +check "empty path falls back to a root, not the filesystem" '"ok":true' "$(body "$R")" | ||
| 323 | +R=$(apiraw "action=ls&path=$FX/missing") | ||
| 324 | +check "missing path -> 404" '404' "$(status_of "$R")" | ||
| 325 | +R=$(apiraw "action=read&path=$FX/missing.txt") | ||
| 326 | +check "missing file -> 404" '404' "$(status_of "$R")" | ||
| 327 | +R=$(apiraw "action=nope") | ||
| 328 | +check "unknown action -> 400" '400' "$(status_of "$R")" | ||
| 329 | +R=$(apiraw "action=ls&path=$FX/a.txt") | ||
| 330 | +check "ls a regular file -> 403 (cannot list)" '403' "$(status_of "$R")" | ||
| 331 | + | ||
| 332 | +# read-only by construction: no write-ish action exists | ||
| 333 | +for a in save write delete rename mkdir touch chmod upload put; do | ||
| 334 | + R=$(apiraw "action=$a&path=$FX/a.txt") | ||
| 335 | + check_not "no '$a' action" '"ok":true' "$(body "$R")" | ||
| 336 | +done | ||
| 337 | +SUM_BEFORE=$(python3 -c " | ||
| 338 | +import hashlib,os | ||
| 339 | +h=hashlib.sha256() | ||
| 340 | +for root,dirs,files in os.walk('$FX'): | ||
| 341 | + for f in sorted(files): | ||
| 342 | + p=os.path.join(root,f) | ||
| 343 | + try: h.update(open(p,'rb').read()) | ||
| 344 | + except OSError: pass | ||
| 345 | +print(h.hexdigest()) | ||
| 346 | +") | ||
| 347 | +api "action=read&path=$FX/a.txt" > /dev/null | ||
| 348 | +apiraw "action=raw&path=$FX/a.txt" > /dev/null | ||
| 349 | +api "action=ls&path=$FX" > /dev/null | ||
| 350 | +SUM_AFTER=$(python3 -c " | ||
| 351 | +import hashlib,os | ||
| 352 | +h=hashlib.sha256() | ||
| 353 | +for root,dirs,files in os.walk('$FX'): | ||
| 354 | + for f in sorted(files): | ||
| 355 | + p=os.path.join(root,f) | ||
| 356 | + try: h.update(open(p,'rb').read()) | ||
| 357 | + except OSError: pass | ||
| 358 | +print(h.hexdigest()) | ||
| 359 | +") | ||
| 360 | +check "fixture unchanged after every action" "$SUM_BEFORE" "$SUM_AFTER" | ||
| 361 | + | ||
| 362 | +# the source must contain no write syscall at all | ||
| 363 | +SRC=src/plugin_files.c | ||
| 364 | +W=$(grep -nE 'fopen\([^)]*"[wa]' "$SRC" | wc -l | tr -d ' ') | ||
| 365 | +check "no fopen for writing in the source" '0' "$W" | ||
| 366 | +for fn in fprintf fputc fwrite_never_used; do :; done | ||
| 367 | +check_not "no remove()" 'remove(' "$(grep -o 'remove(' "$SRC" | head -1)" | ||
| 368 | +check_not "no rmdir()" 'rmdir(' "$(grep -o 'rmdir(' "$SRC" | head -1)" | ||
| 369 | +check_not "no mkdir()" 'mkdir(' "$(grep -o 'mkdir(' "$SRC" | head -1)" | ||
| 370 | +check_not "no rename()" 'rename(' "$(grep -o 'rename(' "$SRC" | head -1)" | ||
| 371 | +check_not "no chmod()" 'chmod(' "$(grep -o 'chmod(' "$SRC" | head -1)" | ||
| 372 | +check_not "no popen()" 'popen(' "$(grep -o 'popen(' "$SRC" | head -1)" | ||
| 373 | +check_not "no system()" 'system(' "$(grep -o 'system(' "$SRC" | head -1)" | ||
| 374 | + | ||
| 375 | +# ---------------------------------------------------------------- HTML UI | ||
| 376 | +section "HTML UI" | ||
| 377 | +P=$(apiraw "") | ||
| 378 | +check "page content-type" 'Content-Type: text/html; charset=utf-8' "$(printf '%s' "$P" | tr -d '\r' | head -1)" | ||
| 379 | +check "page has DOCTYPE" '<!DOCTYPE html>' "$P" | ||
| 380 | +check "page title" '<title>files</title>' "$P" | ||
| 381 | +check "page has no <script src=" '0' "$(printf '%s' "$P" | grep -c '<script src=')" | ||
| 382 | +check "page has no CDN link" '0' "$(printf '%s' "$P" | grep -ciE '(cdn\.|unpkg|jsdelivr|cdnjs)')" | ||
| 383 | +check "page has no http:// asset" '0' "$(printf '%s' "$P" | grep -c 'src="http')" | ||
| 384 | +check "page embeds the theme tokens" '--bg-card:#1c1c1e' "$P" | ||
| 385 | +check "page embeds the theme handoff" 'sx-theme-request' "$P" | ||
| 386 | +check "page embeds the prepaint" 'data-theme' "$P" | ||
| 387 | +check "page marks embed mode" "classList.add('embedded')" "$P" | ||
| 388 | +check "page uses <style>" 'font-family:var(--font)' "$P" | ||
| 389 | +check "page has an inline <script>" '<script>' "$P" | ||
| 390 | +check "page CSP is tight" "default-src 'none'" "$P" | ||
| 391 | +check "page CSP allows no remote script" "script-src 'unsafe-inline'" "$P" | ||
| 392 | +check "page has the fs route constant" "'/plugin_files'" "$P" | ||
| 393 | +check "page has the hub route branch" "'/plugins?plugin='" "$P" | ||
| 394 | +check "page has no emoji" '0' "$(printf '%s' "$P" | python3 -c 'import sys,re; t=sys.stdin.read(); print(len(re.findall(r"[\U0001F300-\U0001FAFF]",t)))')" | ||
| 395 | +check "page uses inline SVG" '<svg viewBox=' "$P" | ||
| 396 | +PEMB=$(apiraw "embed=1") | ||
| 397 | +check "embed=1 still serves the page" '<title>files</title>' "$PEMB" | ||
| 398 | +PNO=$(apiraw "?theme=light") | ||
| 399 | +check "theme param passes through" '<title>files</title>' "$PNO" | ||
| 400 | + | ||
| 401 | +# ---------------------------------------------------------------- generated header | ||
| 402 | +section "generated UI header" | ||
| 403 | +if [ -f src/ui_html.h ] && [ -f src/ui.html ]; then | ||
| 404 | + if python3 tools/gen_ui.py --check >/dev/null 2>&1; then | ||
| 405 | + pass "src/ui_html.h matches src/ui.html" | ||
| 406 | + else | ||
| 407 | + fail "src/ui_html.h is stale - run tools/gen_ui.py" | ||
| 408 | + fi | ||
| 409 | +else | ||
| 410 | + fail "missing src/ui.html or src/ui_html.h" | ||
| 411 | +fi | ||
| 412 | + | ||
| 413 | +# ---------------------------------------------------------------- plugin.json | ||
| 414 | +section "plugin.json sidecar" | ||
| 415 | +if [ -f plugin.json ]; then | ||
| 416 | + pass "plugin.json present" | ||
| 417 | + J=$(cat plugin.json) | ||
| 418 | + json_ok "plugin.json is valid JSON" "$J" \ | ||
| 419 | + "d['slug']=='files' and d['id']=='plugin_files' and d['category']=='devtools' and d['license']=='MIT'" | ||
| 420 | + json_ok "plugin.json declares fs_read" "$J" "'fs_read' in d['capabilities']" | ||
| 421 | + json_ok "plugin.json has a trust notice" "$J" "len(d['trust_notice'])>40" | ||
| 422 | + json_ok "plugin.json title is a title" "$J" "len(d['title'])>6" | ||
| 423 | +else | ||
| 424 | + fail "plugin.json missing (catalog would be blank)" | ||
| 425 | +fi | ||
| 426 | + | ||
| 427 | +# ---------------------------------------------------------------- fortify | ||
| 428 | +section "_FORTIFY_SOURCE=2 build" | ||
| 429 | +if cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src \ | ||
| 430 | + -D_FORTIFY_SOURCE=2 -o "$WORK/plugin_files.fort" src/plugin_files.c 2>"$WORK/fort.log"; then | ||
| 431 | + pass "fortify build compiles" | ||
| 432 | + OUT=$(QUERY_STRING="action=ls&path=$FX" "$WORK/plugin_files.fort" | tail -n +5) | ||
| 433 | + check "fortify build lists entries" '"entries"' "$OUT" | ||
| 434 | + OUT=$(QUERY_STRING="action=read&path=$FX/big.txt" "$WORK/plugin_files.fort") | ||
| 435 | + check "fortify build caps the 1 MiB read" '"bytes_read":1048576' "$OUT" | ||
| 436 | + OUT=$(QUERY_STRING="action=ls&path=$FX/etclink" "$WORK/plugin_files.fort") | ||
| 437 | + check "fortify build still refuses the symlink escape" '403' "$(status_of "$OUT")" | ||
| 438 | + check "fortify build printed no warning" '0' "$(wc -c < "$WORK/fort.log" | tr -d ' ')" | ||
| 439 | +else | ||
| 440 | + fail "fortify build failed: $(head -3 "$WORK/fort.log")" | ||
| 441 | +fi | ||
| 442 | + | ||
| 443 | +# ---------------------------------------------------------------- PE header | ||
| 444 | +section "MinGW PE (when present)" | ||
| 445 | +if [ -f plugin_files.exe ]; then | ||
| 446 | + MAGIC=$(od -An -tx1 -N2 plugin_files.exe | tr -d ' \n') | ||
| 447 | + check "plugin_files.exe starts with the MZ magic" '4d5a' "$MAGIC" | ||
| 448 | + SZ=$(wc -c < plugin_files.exe | tr -d ' ') | ||
| 449 | + if [ "$SZ" -gt 20000 ]; then pass "plugin_files.exe looks like a real binary ($SZ bytes)"; else fail "plugin_files.exe suspiciously small ($SZ bytes)"; fi | ||
| 450 | +else | ||
| 451 | + echo " skip (plugin_files.exe not built here)" | ||
| 452 | +fi | ||
| 453 | + | ||
| 454 | +# ---------------------------------------------------------------- history audit | ||
| 455 | +section "full-history audit" | ||
| 456 | +if [ -d .git ]; then | ||
| 457 | + ALL="$WORK/all-history.txt" | ||
| 458 | + git log -p --all > "$ALL" 2>/dev/null || : > "$ALL" | ||
| 459 | + | ||
| 460 | + audit() { # audit <label> <regex> | ||
| 461 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | ||
| 462 | + if [ -n "$H" ]; then | ||
| 463 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | ||
| 464 | + else | ||
| 465 | + pass "history clean: $1" | ||
| 466 | + fi | ||
| 467 | + } | ||
| 468 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 469 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 470 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 471 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 472 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 473 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 474 | + PK="pico""bot"; WT=".work""trees" | ||
| 475 | + audit "internal fleet path" "/codebases/${PK}|${WT}" | ||
| 476 | + audit "run token assignment" 'RUNNER_'"PASS=" | ||
| 477 | +else | ||
| 478 | + echo " skip history audit (not a git checkout)" | ||
| 479 | +fi | ||
| 480 | + | ||
| 481 | +# ---------------------------------------------------------------- summary | ||
| 482 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | ||
| 483 | +printf ' passed: %d\n' "$PASS" | ||
| 484 | +printf ' failed: %d\n' "$FAIL" | ||
| 485 | +if [ "$FAIL" -ne 0 ]; then | ||
| 486 | + printf ' %sRESULT: FAIL%s\n' "$C_BAD" "$C_0" | ||
| 487 | + exit 1 | ||
| 488 | +fi | ||
| 489 | +printf ' %sRESULT: OK%s\n' "$C_OK" "$C_0" | ||
| 490 | +exit 0 |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..cc1c0bd | index 0000000..cc1c0bd | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tools/gen_ui.py | +++ b/tools/gen_ui.py | ||
| @@ -0,0 +1,105 @@ | @@ -0,0 +1,105 @@ | ||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""tools/gen_ui.py - compile src/ui.html into src/ui_html.h. | ||
| 3 | + | ||
| 4 | +The page lives in one readable file (src/ui.html) so it can be diffed and | ||
| 5 | +reviewed like any other source. This script turns it into a single C string | ||
| 6 | +constant with two control-character placeholders: | ||
| 7 | + | ||
| 8 | + 0x01 -> the bot theme prepaint script + <style> + theme tokens | ||
| 9 | + 0x02 -> the bot theme handoff script (just before </body>) | ||
| 10 | + | ||
| 11 | +main() splits the constant on those bytes and emits the macros from | ||
| 12 | +src/bot_theme_plugin.h in their place, so the theme can never drift out of | ||
| 13 | +sync with the rest of the bot. | ||
| 14 | + | ||
| 15 | + python3 tools/gen_ui.py # write src/ui_html.h | ||
| 16 | + python3 tools/gen_ui.py --check # exit 1 when the header is stale | ||
| 17 | +""" | ||
| 18 | + | ||
| 19 | +import os | ||
| 20 | +import sys | ||
| 21 | + | ||
| 22 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 23 | +SRC = os.path.join(ROOT, "src", "ui.html") | ||
| 24 | +OUT = os.path.join(ROOT, "src", "ui_html.h") | ||
| 25 | + | ||
| 26 | +TOKENS = "<!--TOKENS-->" | ||
| 27 | +MARK_TOKENS = "\u0001" | ||
| 28 | +MARK_HANDOFF = "\u0002" | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def c_literal(text): | ||
| 32 | + """Escape text for a C string literal, one line per source line.""" | ||
| 33 | + out = [] | ||
| 34 | + for line in text.splitlines(True): | ||
| 35 | + piece = [] | ||
| 36 | + for ch in line: | ||
| 37 | + if ch == "\\": | ||
| 38 | + piece.append("\\\\") | ||
| 39 | + elif ch == '"': | ||
| 40 | + piece.append('\\"') | ||
| 41 | + elif ch == "\n": | ||
| 42 | + piece.append("\\n") | ||
| 43 | + elif ch == "\r": | ||
| 44 | + piece.append("\\r") | ||
| 45 | + elif ch == "\t": | ||
| 46 | + piece.append("\\t") | ||
| 47 | + elif ch == MARK_TOKENS: | ||
| 48 | + piece.append("\\001") | ||
| 49 | + elif ch == MARK_HANDOFF: | ||
| 50 | + piece.append("\\002") | ||
| 51 | + elif ord(ch) < 0x20: | ||
| 52 | + piece.append("\\%03o" % ord(ch)) | ||
| 53 | + else: | ||
| 54 | + piece.append(ch) | ||
| 55 | + out.append(' "%s"\n' % "".join(piece)) | ||
| 56 | + return "".join(out) | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def render(): | ||
| 60 | + with open(SRC, "r", encoding="utf-8") as f: | ||
| 61 | + html = f.read() | ||
| 62 | + | ||
| 63 | + if TOKENS not in html: | ||
| 64 | + raise SystemExit("src/ui.html has no %s placeholder" % TOKENS) | ||
| 65 | + html = html.replace(TOKENS, MARK_TOKENS) | ||
| 66 | + | ||
| 67 | + # Handoff script goes right before the closing body tag. | ||
| 68 | + if "</body>" not in html: | ||
| 69 | + raise SystemExit("src/ui.html has no </body>") | ||
| 70 | + html = html.replace("</body>", MARK_HANDOFF + "</body>", 1) | ||
| 71 | + | ||
| 72 | + header = ( | ||
| 73 | + "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n" | ||
| 74 | + "#ifndef SX_FILES_UI_HTML_H\n" | ||
| 75 | + "#define SX_FILES_UI_HTML_H\n" | ||
| 76 | + "\n" | ||
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | ||
| 78 | + "\n" | ||
| 79 | + "#endif /* SX_FILES_UI_HTML_H */\n" | ||
| 80 | + ) | ||
| 81 | + return header | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def main(): | ||
| 85 | + header = render() | ||
| 86 | + check = "--check" in sys.argv[1:] | ||
| 87 | + if check: | ||
| 88 | + try: | ||
| 89 | + with open(OUT, "r", encoding="utf-8") as f: | ||
| 90 | + cur = f.read() | ||
| 91 | + except OSError: | ||
| 92 | + cur = "" | ||
| 93 | + if cur != header: | ||
| 94 | + sys.stderr.write("src/ui_html.h is stale - run tools/gen_ui.py\n") | ||
| 95 | + return 1 | ||
| 96 | + print("src/ui_html.h is up to date") | ||
| 97 | + return 0 | ||
| 98 | + with open(OUT, "w", encoding="utf-8") as f: | ||
| 99 | + f.write(header) | ||
| 100 | + print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header))) | ||
| 101 | + return 0 | ||
| 102 | + | ||
| 103 | + | ||
| 104 | +if __name__ == "__main__": | ||
| 105 | + sys.exit(main()) | ||
| 0 | 106 |