| 1 | 1 | new file mode 100644 |
| index 0000000..3a06556 | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,16 @@ | ||
| 1 | +# build artifacts | |
| 2 | +plugin_notes | |
| 3 | +plugin_notes.exe | |
| 4 | +plugin_notes.musl | |
| 5 | +plugin_notes.arm64 | |
| 6 | +plugin_notes.macos-arm64 | |
| 7 | +plugin_notes.macos-x86_64 | |
| 8 | +bin/ | |
| 9 | + | |
| 10 | +# local note stores (never commit anyone's notes) | |
| 11 | +.notes/ | |
| 12 | +*.tmp | |
| 13 | + | |
| 14 | +# python tooling | |
| 15 | +__pycache__/ | |
| 16 | +*.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..07c926e | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,75 @@ | ||
| 1 | +# plugin_notes - SCORPIOX BOT open-source markdown notes for your node | |
| 2 | +# | |
| 3 | +# Targets: | |
| 4 | +# make native build -> ./plugin_notes | |
| 5 | +# make musl static musl x86_64 -> ./plugin_notes.musl | |
| 6 | +# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_notes.arm64 | |
| 7 | +# make win64 MinGW-w64 static -> ./plugin_notes.exe | |
| 8 | +# make macos Apple clang -> ./plugin_notes (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_notes.c | |
| 23 | +UI_SRC := src/ui.html | |
| 24 | +UI_HDR := src/ui_html.h | |
| 25 | +BIN := plugin_notes | |
| 26 | +EXE := plugin_notes.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..6f5c570 | ||
| --- /dev/null | ||
| +++ b/README.md | ||
| @@ -0,0 +1,171 @@ | ||
| 1 | +# SCORPIOX BOT — notes | |
| 2 | + | |
| 3 | +Zero-dependency markdown notes that live on your **own node**. | |
| 4 | + | |
| 5 | +A note is one `<id>.md` file plus a row in `index.json`, both inside the plugin | |
| 6 | +directory. Nothing leaves the machine: no account, no sync service, no CDN, no | |
| 7 | +network call of any kind. Create, edit, rename, search, pin and delete notes | |
| 8 | +with a live rendered preview beside the editor. | |
| 9 | + | |
| 10 | +``` | |
| 11 | +make # native build -> ./plugin_notes | |
| 12 | +make musl # static musl x86_64 -> ./plugin_notes.musl | |
| 13 | +make arm64 # static aarch64 -> ./plugin_notes.arm64 | |
| 14 | +make win64 # MinGW-w64 static PE -> ./plugin_notes.exe | |
| 15 | +make macos # Apple clang (on macOS) -> ./plugin_notes | |
| 16 | +make ui # regenerate src/ui_html.h from src/ui.html | |
| 17 | +make test # offline suite (100+ assertions) | |
| 18 | +make e2e # Playwright viewport suite (1440 / 1024 / 390, dark + light) | |
| 19 | +``` | |
| 20 | + | |
| 21 | +## Install | |
| 22 | + | |
| 23 | +Drop the binary where the node looks for plugins, then open | |
| 24 | +**Settings → Plugins**, or use the market installer: | |
| 25 | + | |
| 26 | +```sh | |
| 27 | +# node plugin directory (created by scorpiox-bot on startup) | |
| 28 | +cp plugin_notes ~/.scorpiox/plugins/plugin_notes | |
| 29 | +chmod +x ~/.scorpiox/plugins/plugin_notes | |
| 30 | + | |
| 31 | +# or from the market | |
| 32 | +curl -s -H "X-Bot-Password: $BOT_PASSWORD" \ | |
| 33 | + "http://127.0.0.1:8150/plugin_manage?action=install&slug=notes&mode=prebuilt" | |
| 34 | +``` | |
| 35 | + | |
| 36 | +Windows: `%LOCALAPPDATA%\scorpiox\plugins\plugin_notes.exe`. | |
| 37 | +BotCloud container: `/workspace/.scorpiox/plugins/plugin_notes`. | |
| 38 | + | |
| 39 | +## Three modes, one binary | |
| 40 | + | |
| 41 | +| Mode | Trigger | Response | | |
| 42 | +|---|---|---| | |
| 43 | +| Discovery | `--meta` or `SX_PLUGIN_META=1` | `{"name":"notes","desc":"Markdown notes"}` (unauthenticated) | | |
| 44 | +| API | `?action=...`, `?format=json`, or any `POST` | `application/json; charset=utf-8` | | |
| 45 | +| UI | plain `GET` (`?embed=1` aware) | the two-pane editor, `text/html` | | |
| 46 | + | |
| 47 | +Every API call is behind `require_node_auth()`: `X-Bot-Password`, | |
| 48 | +`Authorization: Bearer <pwd>`, or `?pwd=`. With `BOT_PASSWORD` unset the check | |
| 49 | +is a no-op, which is the intended behaviour on a single-user box. | |
| 50 | + | |
| 51 | +## Actions | |
| 52 | + | |
| 53 | +| Action | Call | Returns | | |
| 54 | +|---|---|---| | |
| 55 | +| `list` | `GET ?action=list` | `{"ok":true,"count":N,"notes":[{id,title,pinned,created,updated}]}` | | |
| 56 | +| `get` | `GET ?action=get&id=<id>` | `{"ok":true,"note":{...,"body":"..."}}` | | |
| 57 | +| `save` | `POST ?action=save` with `{"id?","title","body","pinned?"}` | `{"ok":true,"note":{...}}` | | |
| 58 | +| `delete` | `POST ?action=delete&id=<id>` | `{"ok":true,"deleted":"<id>","trash":true}` | | |
| 59 | +| `search` | `GET ?action=search&q=<text>` | same shape as `list`, title **and** body matched, case-insensitive | | |
| 60 | +| `pin` | `POST ?action=pin&id=<id>` with `{"pin":0\|1}` | `{"ok":true,"id":"...","pinned":1}` | | |
| 61 | +| `render` | `POST ?action=render` with `{"body":"..."}` | `{"ok":true,"html":"..."}` | | |
| 62 | + | |
| 63 | +`save` without an `id` creates a note and generates a `[a-z0-9]{12}` id | |
| 64 | +server-side; with an id it updates in place and keeps `created`. | |
| 65 | + | |
| 66 | +Examples: | |
| 67 | + | |
| 68 | +```sh | |
| 69 | +P="pwd=$BOT_PASSWORD" | |
| 70 | +curl -s "http://127.0.0.1:8150/plugin_notes?action=list&$P" | |
| 71 | + | |
| 72 | +curl -s -X POST -H "Content-Type: application/json" \ | |
| 73 | + "http://127.0.0.1:8150/plugin_notes?action=save&$P" \ | |
| 74 | + -d '{"title":"Release checklist","body":"# Release checklist\n\n- build\n- verify"}' | |
| 75 | + | |
| 76 | +curl -s "http://127.0.0.1:8150/plugin_notes?action=search&q=verify&$P" | |
| 77 | +curl -s -X POST "http://127.0.0.1:8150/plugin_notes?action=delete&id=<id>&$P" | |
| 78 | +``` | |
| 79 | + | |
| 80 | +## Storage | |
| 81 | + | |
| 82 | +| Platform | Location | | |
| 83 | +|---|---| | |
| 84 | +| Linux / macOS | `<plugin dir>/.notes/` — or `$NOTES_DIR` | | |
| 85 | +| Windows | `%LOCALAPPDATA%\scorpiox\plugins\.notes\` | | |
| 86 | + | |
| 87 | +``` | |
| 88 | +.notes/ | |
| 89 | +├── index.json # {"version":1,"notes":[{id,title,pinned,created,updated}]} | |
| 90 | +├── <id>.md # the markdown body of one note | |
| 91 | +└── .trash/<id>.md # deleted notes, kept so a wrong click is recoverable | |
| 92 | +``` | |
| 93 | + | |
| 94 | +Every write is `fwrite` to `<path>.tmp`, `fflush` + `fsync`, then `rename` (POSIX) | |
| 95 | +or `MoveFileExA(..., MOVEFILE_REPLACE_EXISTING)` (Windows). A process killed | |
| 96 | +mid-write leaves the previous note intact rather than a half file. The body is | |
| 97 | +written before the index, so an index row never points at a note that was never | |
| 98 | +written. | |
| 99 | + | |
| 100 | +## Security model | |
| 101 | + | |
| 102 | +* **Authentication** — every action requires the node password (three accepted | |
| 103 | + forms above); `--meta` alone stays open so discovery still works. | |
| 104 | +* **Path safety** — ids are generated by the binary (`[a-z0-9]{12}`) and any id | |
| 105 | + arriving in a request is validated against that shape before it can be turned | |
| 106 | + into a path. `?id=../../etc/passwd`, `%2f`, uppercase and length overruns are | |
| 107 | + all rejected with `400`. | |
| 108 | +* **Write scope** — nothing is written outside the notes directory; the trash | |
| 109 | + subdirectory is inside it. | |
| 110 | +* **Size cap** — a note body is capped at 512 KiB; over that the request is | |
| 111 | + refused with `413` naming the limit. The CGI body read is guarded on | |
| 112 | + `CONTENT_LENGTH` so an inherited empty stdin never blocks the process. | |
| 113 | +* **XSS** — markdown is rendered **server-side**, and every literal byte of note | |
| 114 | + content is HTML-escaped before any tag is emitted (`&`, `<`, `>`, `"`, `'`) so | |
| 115 | + a note containing `<script>`, `<img onerror=...>` or a `javascript:` link | |
| 116 | + renders as inert text; only `https:`, `http:`, `mailto:` and same-page links | |
| 117 | + become real anchors. `tests/run.sh` asserts this for each payload. | |
| 118 | +* **CSP** — the page ships | |
| 119 | + `default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'` | |
| 120 | + so even a future regression cannot fetch a remote script. | |
| 121 | + | |
| 122 | +## UI | |
| 123 | + | |
| 124 | +Two panes: the note list with search on the left, editor above a live rendered | |
| 125 | +preview on the right. Under 700 px the layout collapses to a single pane with a | |
| 126 | +back button and a preview toggle, so the same page is usable at 390 px and inside | |
| 127 | +the Chat floating window. | |
| 128 | + | |
| 129 | +* autosave with an 800 ms debounce and a visible `saved` / `unsaved` / `saving` | |
| 130 | + pill (`Ctrl/Cmd+S` forces an immediate save) | |
| 131 | +* `Ctrl/Cmd+K` focuses search, `Alt+Ctrl/Cmd+N` starts a new note, `Tab` in the | |
| 132 | + editor inserts two spaces | |
| 133 | +* pin and delete per note, delete moves to `.trash` | |
| 134 | +* dark and light from the SCORPIOX BOT theme tokens, following `?theme=`, | |
| 135 | + `localStorage.bot_theme`, `prefers-color-scheme` and the `sx-theme` postMessage | |
| 136 | + handoff; the plugin's own toggle hides under `?embed=1` | |
| 137 | +* no `<script src=>`, no CDN, no framework, zero emoji — inline SVG only | |
| 138 | + | |
| 139 | + | |
| 140 | + | |
| 141 | + | |
| 142 | +## API routes the page uses | |
| 143 | + | |
| 144 | +The single most common plugin bug is calling the wrong route. This page branches | |
| 145 | +exactly once, using `preferred-bot-plugin`'s template: | |
| 146 | + | |
| 147 | +* served through the hub (`/plugins?plugin=plugin_notes&node=...`) → call the hub | |
| 148 | + proxy back: `/plugins?plugin=plugin_notes&action=...` | |
| 149 | +* opened directly on the node (`/plugin_notes`) → the plugin **is** the route: | |
| 150 | + `/plugin_notes?action=...` | |
| 151 | + | |
| 152 | +Calling `/plugins?plugin=` on the node itself returns the discovery list, not the | |
| 153 | +plugin. | |
| 154 | + | |
| 155 | +## Test | |
| 156 | + | |
| 157 | +```sh | |
| 158 | +make test # 150+ offline assertions, 0 fail, no network, no Playwright | |
| 159 | +make e2e # Playwright: 6 viewports × theme, console/overflow/autosave | |
| 160 | +``` | |
| 161 | + | |
| 162 | +The offline suite proves the contract (meta, auth, every action's JSON shape, CRUD | |
| 163 | +round trip, atomic write, the size cap, id validation, XSS inertness, trash, | |
| 164 | +pinning order, search, the generated UI's CSP and route branching), builds the | |
| 165 | +same source with `-D_FORTIFY_SOURCE=2` and runs it, checks the MinGW `MZ` header | |
| 166 | +when the PE is present, and audits the whole git history for secrets and internal | |
| 167 | +addresses. | |
| 168 | + | |
| 169 | +## License | |
| 170 | + | |
| 171 | +MIT © 2026 SCORPIOX INC. See [LICENSE](LICENSE). |
| 1 | 1 | new file mode 100644 |
| index 0000000..0e50dcd | ||
| --- /dev/null | ||
| +++ b/build.ps1 | ||
| @@ -0,0 +1,51 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_notes | |
| 2 | +# | |
| 3 | +# Usage (from the repo root, PowerShell): | |
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | |
| 5 | +# | |
| 6 | +# Produces .\plugin_notes.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_notes.c" | |
| 14 | + $Out = Join-Path $ScriptDir "plugin_notes.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_notes.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_notes.exe --meta" | |
| 49 | +} finally { | |
| 50 | + Pop-Location | |
| 51 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..0520e51 |

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

| 1 | 1 | new file mode 100644 |
| index 0000000..16e7d1a |

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

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

| 1 | 1 | new file mode 100644 |
| index 0000000..4d872f4 |

| 1 | 1 | new file mode 100644 |
| index 0000000..6932c13 | ||
| --- /dev/null | ||
| +++ b/plugin.json | ||
| @@ -0,0 +1,14 @@ | ||
| 1 | +{ | |
| 2 | + "slug": "notes", | |
| 3 | + "id": "plugin_notes", | |
| 4 | + "title": "Markdown Notes", | |
| 5 | + "summary": "Zero-dependency markdown notes that live on your node: create, edit, rename, search, pin and delete, with a live rendered preview next to the editor. Notes are one <id>.md file each plus index.json inside the plugin directory, every write is staged to a temp file and renamed so a crash never truncates a note, and deleted notes go to a recoverable .trash. Server-side rendering escapes note content first, so a pasted <script> is inert text. No CDN, no network requests, no database.", | |
| 6 | + "category": "utilities", | |
| 7 | + "license": "MIT", | |
| 8 | + "capabilities": [ | |
| 9 | + "fs_write_plugin_dir" | |
| 10 | + ], | |
| 11 | + "trust_notice": "Executes native C code on your node. Reads and writes only inside its own notes directory (plugin dir/.notes, or $NOTES_DIR when set): one markdown file per note, an index.json, and a .trash subdirectory. It opens no network connection of any kind and reads nothing outside that directory.", | |
| 12 | + "author": "SCORPIOX INC", | |
| 13 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-notes" | |
| 14 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..2c24ffb | ||
| --- /dev/null | ||
| +++ b/release-dist.sh | ||
| @@ -0,0 +1,365 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# release-dist.sh - build, scan and publish plugin_notes to the plugin registry. | |
| 3 | +# | |
| 4 | +# Two paths: | |
| 5 | +# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it | |
| 6 | +# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI. | |
| 7 | +# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz -> | |
| 8 | +# manifest.json + SHA256SUMS -> upload -> latest.json / index.json. | |
| 9 | +# | |
| 10 | +# Nothing here contains a host address or a credential. Everything environment-specific | |
| 11 | +# comes from the environment, so this file stays safe to publish: | |
| 12 | +# | |
| 13 | +# DIST_HOST ssh target for the dist server (required for upload) | |
| 14 | +# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key) | |
| 15 | +# DIST_PATH remote web root of the dist server (default /data/dist) | |
| 16 | +# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64) | |
| 17 | +# MAC_USER / MAC_PASS (optional) | |
| 18 | +# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token) | |
| 19 | +# PLUGINGIT_REMOTE public mirror URL to push into | |
| 20 | +# | |
| 21 | +# Usage: | |
| 22 | +# ./release-dist.sh # full release | |
| 23 | +# ./release-dist.sh --dry-run # build + stage in /tmp, no upload | |
| 24 | +# ./release-dist.sh --no-macos # skip the macOS legs | |
| 25 | +# ./release-dist.sh --no-mirror # skip the plugingit mirror | |
| 26 | +# ./release-dist.sh --standalone # use this script even if the CLI is installed | |
| 27 | +# # (needed for plugins that link extra Win32 libs, | |
| 28 | +# # which the CLI's fixed link line cannot express) | |
| 29 | + | |
| 30 | +set -euo pipefail | |
| 31 | + | |
| 32 | +SLUG="notes" | |
| 33 | +ID="plugin_notes" | |
| 34 | +VERSION="1.0.0" | |
| 35 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | |
| 36 | + | |
| 37 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | |
| 38 | +cd "$ROOT" | |
| 39 | + | |
| 40 | +DRY_RUN=0 | |
| 41 | +DO_MACOS=1 | |
| 42 | +DO_MIRROR=1 | |
| 43 | +STANDALONE=0 | |
| 44 | +for arg in "$@"; do | |
| 45 | + case "$arg" in | |
| 46 | + --standalone) STANDALONE=1 ;; | |
| 47 | + --dry-run) DRY_RUN=1 ;; | |
| 48 | + --no-macos) DO_MACOS=0 ;; | |
| 49 | + --no-mirror) DO_MIRROR=0 ;; | |
| 50 | + -h|--help) sed -n '2,32p' "$0"; exit 0 ;; | |
| 51 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | |
| 52 | + esac | |
| 53 | +done | |
| 54 | + | |
| 55 | +DIST_HOST="${DIST_HOST:-}" | |
| 56 | +DIST_PASS="${DIST_PASS:-}" | |
| 57 | +DIST_PATH="${DIST_PATH:-/data/dist}" | |
| 58 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | |
| 59 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | |
| 60 | + | |
| 61 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | |
| 62 | +mkdir -p "$STAGE" | |
| 63 | +trap 'rm -rf "$STAGE"' EXIT | |
| 64 | + | |
| 65 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | |
| 66 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | |
| 67 | + | |
| 68 | +# ---------------------------------------------------------------- 0. preflight | |
| 69 | +say "0/7 preflight" | |
| 70 | + | |
| 71 | +if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | |
| 72 | + say "using scorpiox-cli-botplugin publish" | |
| 73 | + exec scorpiox-cli-botplugin publish "$ROOT" | |
| 74 | +fi | |
| 75 | +echo " running the standalone pipeline" | |
| 76 | + | |
| 77 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | |
| 78 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | |
| 79 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | |
| 80 | +echo " version $VERSION" | |
| 81 | +echo " commit $COMMIT" | |
| 82 | + | |
| 83 | +# ---------------------------------------------------------------- 1. secret scan | |
| 84 | +say "1/7 secret & LAN scan (full history)" | |
| 85 | + | |
| 86 | +SCAN_TMP="$STAGE/history.txt" | |
| 87 | +# Scan every added/removed line of every commit. Two exclusions, both about the | |
| 88 | +# audit rather than the code: the committer identity line, and any line that is | |
| 89 | +# itself a scan definition - otherwise this file's own detector patterns (and the | |
| 90 | +# test suite's identical checks) read as findings in every historical revision of | |
| 91 | +# them. A real secret on any other line still hits. | |
| 92 | +git log -p --all 2>/dev/null \ | |
| 93 | + | grep -v '^Author: ' \ | |
| 94 | + | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|P_ROOT=|P_WT=|PK=\"|\$ALL" \ | |
| 95 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | |
| 96 | +HITS=0 | |
| 97 | +scan() { # scan <label> <regex> | |
| 98 | + local out | |
| 99 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | |
| 100 | + if [ -n "$out" ]; then | |
| 101 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | |
| 102 | + printf '%s\n' "$out" | sed 's/^/ /' | |
| 103 | + HITS=$((HITS + 1)) | |
| 104 | + else | |
| 105 | + printf ' ok %s\n' "$1" | |
| 106 | + fi | |
| 107 | +} | |
| 108 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 109 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 110 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 111 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 112 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 113 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 114 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | |
| 115 | +P_ROOT="/codebases" | |
| 116 | +P_PICOBOT="${P_ROOT}/pico""bot" | |
| 117 | +P_WT=".work""trees" | |
| 118 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | |
| 119 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | |
| 120 | +if [ "$HITS" -ne 0 ]; then | |
| 121 | + die "secret scan found $HITS problem(s) - refusing to publish" | |
| 122 | +fi | |
| 123 | +echo " clean: 0 hits" | |
| 124 | + | |
| 125 | +# ---------------------------------------------------------------- 2. build | |
| 126 | +say "2/7 build targets" | |
| 127 | + | |
| 128 | +# linux-x86_64 (glibc, native) | |
| 129 | +if command -v cc >/dev/null 2>&1; then | |
| 130 | + cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -o "$STAGE/$ID" src/$ID.c || die "native build failed" | |
| 131 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | |
| 132 | +else | |
| 133 | + die "no native cc found" | |
| 134 | +fi | |
| 135 | + | |
| 136 | +# linux-x86_64-musl (fully static - the universal Linux artifact) | |
| 137 | +if command -v musl-gcc >/dev/null 2>&1; then | |
| 138 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.musl" src/$ID.c \ | |
| 139 | + || die "musl build failed" | |
| 140 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | |
| 141 | +else | |
| 142 | + echo " skip linux-x86_64-musl (no musl-gcc)" | |
| 143 | +fi | |
| 144 | + | |
| 145 | +# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers) | |
| 146 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | |
| 147 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.arm64" src/$ID.c \ | |
| 148 | + || die "arm64 build failed" | |
| 149 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | |
| 150 | +else | |
| 151 | + echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)" | |
| 152 | +fi | |
| 153 | + | |
| 154 | +# windows-x86_64 (static PE) | |
| 155 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | |
| 156 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings \ | |
| 157 | + -I src -o "$STAGE/$ID.exe" src/$ID.c || die "MinGW build failed" | |
| 158 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | |
| 159 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | |
| 160 | +else | |
| 161 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | |
| 162 | +fi | |
| 163 | + | |
| 164 | +# macOS legs - Mach-O must be produced by Apple clang on a real Mac. | |
| 165 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | |
| 166 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | |
| 167 | + MAC_USER="${MAC_USER:-$(whoami)}" | |
| 168 | + MAC_DIR="/tmp/${ID}-mac-$$" | |
| 169 | + echo " building macOS legs on $MAC_HOST" | |
| 170 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | |
| 171 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | |
| 172 | + if [ -n "${MAC_PASS:-}" ]; then | |
| 173 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | |
| 174 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | |
| 175 | + fi | |
| 176 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | |
| 177 | + tar -czf "$STAGE/src.tgz" src | |
| 178 | + if "${SCP_MAC[@]}" "$STAGE/src.tgz" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tgz" \ | |
| 179 | + && "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tgz"; then | |
| 180 | + # Build straight from the uploaded file - no src/ tree on the remote. | |
| 181 | + for slice in arm64 x86_64; do | |
| 182 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | |
| 183 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -arch $slice -o $ID.$slice src/$ID.c" \ | |
| 184 | + 2>/dev/null; then | |
| 185 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | |
| 186 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | |
| 187 | + else | |
| 188 | + echo " warn: macos-$slice build failed on $MAC_HOST" | |
| 189 | + fi | |
| 190 | + done | |
| 191 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true | |
| 192 | + else | |
| 193 | + echo " warn: could not upload source to $MAC_HOST" | |
| 194 | + fi | |
| 195 | + else | |
| 196 | + echo " warn: cannot reach macOS builder $MAC_HOST" | |
| 197 | + fi | |
| 198 | +else | |
| 199 | + echo " skip macOS legs (no MAC_HOST or --no-macos)" | |
| 200 | +fi | |
| 201 | + | |
| 202 | +# ---------------------------------------------------------------- 3. manifest | |
| 203 | +say "3/7 manifest + checksums" | |
| 204 | + | |
| 205 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | |
| 206 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | |
| 207 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | |
| 208 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | |
| 209 | + | |
| 210 | +target_meta() { # target_meta <key> <file> <format> <relpath> | |
| 211 | + local key="$1" file="$2" fmt="$3" rel="$4" | |
| 212 | + [ -f "$file" ] || return 0 | |
| 213 | + local sha size | |
| 214 | + sha=$(sha256sum "$file" | awk '{print $1}') | |
| 215 | + size=$(wc -c < "$file" | tr -d ' ') | |
| 216 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | |
| 217 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | |
| 218 | +} | |
| 219 | + | |
| 220 | +{ | |
| 221 | + printf '{\n' | |
| 222 | + printf ' "slug": "%s",\n' "$SLUG" | |
| 223 | + printf ' "id": "%s",\n' "$ID" | |
| 224 | + printf ' "name": "notes",\n' | |
| 225 | + printf ' "desc": "Markdown notes",\n' | |
| 226 | + printf ' "title": "Markdown Notes",\n' | |
| 227 | + printf ' "summary": "Zero-dependency markdown notes that live on your node: create, edit, rename, search, pin and delete, with a live rendered preview next to the editor. Notes are one <id>.md file each plus index.json inside the plugin directory, every write is staged to a temp file and renamed so a crash never truncates a note, and deleted notes go to a recoverable .trash. Server-side rendering escapes note content first, so a pasted <script> is inert text. No CDN, no network requests, no database.",\n' | |
| 228 | + printf ' "category": "utilities",\n' | |
| 229 | + printf ' "version": "%s",\n' "$VERSION" | |
| 230 | + printf ' "license": "MIT",\n' | |
| 231 | + printf ' "trust_notice": "Executes native C code on your node. Reads and writes only inside its own notes directory (plugin dir/.notes, or $NOTES_DIR when set): one markdown file per note, an index.json, and a .trash subdirectory. It opens no network connection of any kind and reads nothing outside that directory.",\n' | |
| 232 | + printf ' "capabilities": ["fs_write_plugin_dir"],\n' | |
| 233 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | |
| 234 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | |
| 235 | + printf ' "git_commit": "%s",\n' "$COMMIT" | |
| 236 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 237 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | |
| 238 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID" | |
| 239 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID" | |
| 240 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | |
| 241 | + printf ' "targets": {\n' | |
| 242 | + first=1 | |
| 243 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | |
| 244 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" | |
| 245 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" | |
| 246 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" | |
| 247 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" | |
| 248 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" | |
| 249 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" | |
| 250 | + printf '\n }\n}\n' | |
| 251 | +} > "$STAGE/manifest.json" | |
| 252 | + | |
| 253 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | |
| 254 | + || die "generated manifest.json is not valid JSON" | |
| 255 | +echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)" | |
| 256 | + | |
| 257 | +# SHA256SUMS - relative paths, exactly as published | |
| 258 | +( cd "$STAGE" | |
| 259 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | |
| 260 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | |
| 261 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | |
| 262 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | |
| 263 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | |
| 264 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | |
| 265 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | |
| 266 | + true ) > "$STAGE/SHA256SUMS" | |
| 267 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | |
| 268 | + | |
| 269 | +# ---------------------------------------------------------------- 4. stage | |
| 270 | +say "4/7 stage tree" | |
| 271 | +PKG="$STAGE/pkg" | |
| 272 | +mkdir -p "$PKG" | |
| 273 | +cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | |
| 274 | +[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; } | |
| 275 | +[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; } | |
| 276 | +[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; } | |
| 277 | +[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; } | |
| 278 | +[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; } | |
| 279 | +[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; } | |
| 280 | +echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)" | |
| 281 | + | |
| 282 | +if [ "$DRY_RUN" -eq 1 ]; then | |
| 283 | + say "dry run - leaving the staging tree in $PKG" | |
| 284 | + trap - EXIT | |
| 285 | + exit 0 | |
| 286 | +fi | |
| 287 | + | |
| 288 | +# ---------------------------------------------------------------- 5. upload | |
| 289 | +say "5/7 upload to the dist server" | |
| 290 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)" | |
| 291 | +SSH=(ssh -o StrictHostKeyChecking=no) | |
| 292 | +SCP=(scp -o StrictHostKeyChecking=no) | |
| 293 | +if [ -n "$DIST_PASS" ]; then | |
| 294 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | |
| 295 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | |
| 296 | +fi | |
| 297 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | |
| 298 | + | |
| 299 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | |
| 300 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | |
| 301 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | |
| 302 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | |
| 303 | +# OpenSSH 9 refuses to scp a bare "." source. | |
| 304 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | |
| 305 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | |
| 306 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | |
| 307 | + || die "remote extract failed" | |
| 308 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | |
| 309 | + | |
| 310 | +# latest.json = copy of this version's manifest | |
| 311 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | |
| 312 | + || die "latest.json update failed" | |
| 313 | +echo " updated bot-plugins/$SLUG/latest.json" | |
| 314 | + | |
| 315 | +# index.json - merge, preserving every sibling <slug>/latest.json | |
| 316 | +say "index.json merge" | |
| 317 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | |
| 318 | +import json, os, sys, glob | |
| 319 | +slug = sys.argv[1] | |
| 320 | +entries = {} | |
| 321 | +for p in sorted(glob.glob('*/latest.json')): | |
| 322 | + s = os.path.dirname(p) | |
| 323 | + try: | |
| 324 | + entries[s] = json.load(open(p)) | |
| 325 | + except Exception: | |
| 326 | + pass | |
| 327 | +index = { | |
| 328 | + 'ok': True, | |
| 329 | + 'service': 'bot-plugins-dist', | |
| 330 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | |
| 331 | + 'count': len(entries), | |
| 332 | + 'slugs': sorted(entries), | |
| 333 | + 'plugins': [entries[k] for k in sorted(entries)], | |
| 334 | +} | |
| 335 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | |
| 336 | +os.replace('index.json.tmp', 'index.json') | |
| 337 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | |
| 338 | +PY" || die "index.json merge failed" | |
| 339 | + | |
| 340 | +# ---------------------------------------------------------------- 6. mirror | |
| 341 | +say "6/7 plugingit mirror" | |
| 342 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | |
| 343 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | |
| 344 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|") | |
| 345 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | |
| 346 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | |
| 347 | + echo " mirrored to $PLUGINGIT_REMOTE" | |
| 348 | +else | |
| 349 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | |
| 350 | +fi | |
| 351 | + | |
| 352 | +# ---------------------------------------------------------------- 7. verify | |
| 353 | +say "7/7 verify" | |
| 354 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | |
| 355 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | |
| 356 | +if [ "$CODE" = "200" ]; then | |
| 357 | + python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \ | |
| 358 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | |
| 359 | +else | |
| 360 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | |
| 361 | +fi | |
| 362 | + | |
| 363 | +printf '\n\033[1mrelease complete\033[0m\n' | |
| 364 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 365 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | 1 | new file mode 100644 |
| index 0000000..0dd243b | ||
| --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | ||
| 1 | +/* | |
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | |
| 3 | + * | |
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | |
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | |
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | |
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | |
| 8 | + * localStorage key, same prepaint order. | |
| 9 | + * | |
| 10 | + * Three rules, and nothing else: | |
| 11 | + * | |
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | |
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | |
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | |
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | |
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | |
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | |
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | |
| 19 | + * it was already open when the bot changed theme. | |
| 20 | + * | |
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | |
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | |
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | |
| 24 | + * are var() references, one definition covers both themes. | |
| 25 | + * | |
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 27 | + */ | |
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | |
| 29 | +#define SX_BOT_THEME_PLUGIN_H | |
| 30 | + | |
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | |
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | |
| 33 | +#define SX_BOT_THEME_TOKENS \ | |
| 34 | +":root{color-scheme:dark;" \ | |
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | |
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | |
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | |
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | |
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | |
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | |
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | |
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | |
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | |
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | |
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | |
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | |
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | |
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | |
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | |
| 50 | +"}" \ | |
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | |
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 58 | + "--accent-dim:#0066d6;" \ | |
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 62 | + "color-scheme:light}}" \ | |
| 63 | +"html[data-theme=light]{" \ | |
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 70 | + "--accent-dim:#0066d6;" \ | |
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 74 | + "color-scheme:light}" \ | |
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | |
| 76 | +"*{box-sizing:border-box}" \ | |
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | |
| 78 | + "-webkit-font-smoothing:antialiased}" \ | |
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | |
| 80 | +"button:active{transform:scale(.98)}" \ | |
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | |
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | |
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | |
| 84 | +" * hides its own back link and its own toggle. */" \ | |
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | |
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | |
| 87 | + | |
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | |
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | |
| 90 | + * html.embedded so the embed rules apply before first paint. */ | |
| 91 | +#define SX_BOT_THEME_PREPAINT \ | |
| 92 | +"<script>(function(){var t='';" \ | |
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | |
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | |
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | |
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | |
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 99 | +"})();</script>\n" | |
| 100 | + | |
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | |
| 102 | + * at startup in case it changed while this page was already open. Fires the | |
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | |
| 104 | + * re-skin themselves from one listener. */ | |
| 105 | +#define SX_BOT_THEME_HANDOFF \ | |
| 106 | +"<script>(function(){" \ | |
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | |
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | |
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | |
| 112 | +"window.sxApplyTheme=apply;" \ | |
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | |
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | |
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | |
| 116 | +"})();</script>\n" | |
| 117 | + | |
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | |
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | |
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | |
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | |
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | |
| 123 | + | |
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | |
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | |
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | |
| 127 | +"})();</script>\n" | |
| 128 | + | |
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..aa88bfd | ||
| --- /dev/null | ||
| +++ b/src/plugin_notes.c | ||
| @@ -0,0 +1,1624 @@ | ||
| 1 | +/* | |
| 2 | + * plugin_notes - SCORPIOX BOT open-source markdown notes 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 / POST -> JSON node API | |
| 7 | + * 3. GET (default) -> two-pane markdown editor | |
| 8 | + * | |
| 9 | + * Storage: one file per note, `<id>.md`, plus `index.json` holding the | |
| 10 | + * metadata and the ordering. Both live inside `<plugin dir>/.notes/` | |
| 11 | + * (Linux/macOS) or `%LOCALAPPDATA%\scorpiox\plugins\.notes\` (Windows), and | |
| 12 | + * `$NOTES_DIR` overrides the location for tests and for people who want their | |
| 13 | + * notes somewhere else. Every write goes to `<name>.tmp` and is then renamed | |
| 14 | + * over the real file, so a kill -9 mid-write leaves the previous content | |
| 15 | + * intact rather than a truncated note. | |
| 16 | + * | |
| 17 | + * Note ids are generated by this binary (`[a-z0-9]{12}`), never taken from the | |
| 18 | + * client as a path, and any id that arrives in a request is validated against | |
| 19 | + * that shape before it can touch the filesystem. Markdown is rendered | |
| 20 | + * server-side with raw HTML escaped first, so a note containing `<script>` or | |
| 21 | + * a `javascript:` link renders as inert text. | |
| 22 | + * | |
| 23 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | |
| 24 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | |
| 25 | + * scorpiox-server on the node. | |
| 26 | + * | |
| 27 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 28 | + */ | |
| 29 | + | |
| 30 | +/* Must come before every include on Windows: MinGW defaults to 0x502 | |
| 31 | + * (Server 2003), which hides MoveFileExA and the wide-path helpers. */ | |
| 32 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | |
| 33 | +# define _WIN32_WINNT 0x0601 | |
| 34 | +#endif | |
| 35 | + | |
| 36 | +#if !defined(_WIN32) | |
| 37 | +# define _POSIX_C_SOURCE 200809L | |
| 38 | +# define _DEFAULT_SOURCE 1 | |
| 39 | +# if defined(__APPLE__) | |
| 40 | +# define _DARWIN_C_SOURCE 1 | |
| 41 | +# endif | |
| 42 | +#endif | |
| 43 | + | |
| 44 | +#include <stdio.h> | |
| 45 | +#include <stdlib.h> | |
| 46 | +#include <string.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 <direct.h> | |
| 55 | +# include <io.h> | |
| 56 | +#else | |
| 57 | +# include <unistd.h> | |
| 58 | +# include <sys/stat.h> | |
| 59 | +# include <sys/types.h> | |
| 60 | +#endif | |
| 61 | + | |
| 62 | +#include "bot_theme_plugin.h" | |
| 63 | +#include "ui_html.h" | |
| 64 | + | |
| 65 | +#define PLUGIN_SLUG "notes" | |
| 66 | +#define PLUGIN_ID "plugin_notes" | |
| 67 | +#define PLUGIN_VER "1.0.0" | |
| 68 | +#define PLUGIN_NAME "notes" | |
| 69 | +#define PLUGIN_DESC "Markdown notes" | |
| 70 | + | |
| 71 | +#define PATH_SZ 1024 | |
| 72 | +#define ID_LEN 12 | |
| 73 | +#define ID_BUF (ID_LEN + 1) | |
| 74 | +#define TITLE_MAX 300 | |
| 75 | +#define MAX_NOTES 2000 | |
| 76 | +#define BODY_MAX (512 * 1024) /* hard cap on one note, spec'd */ | |
| 77 | +#define REQ_MAX (BODY_MAX + 8192) /* JSON envelope around it */ | |
| 78 | +#define TRASH_DIR ".trash" | |
| 79 | + | |
| 80 | +typedef struct { | |
| 81 | + char id[ID_BUF]; | |
| 82 | + char title[TITLE_MAX]; | |
| 83 | + int pinned; | |
| 84 | + char created[24]; | |
| 85 | + char updated[24]; | |
| 86 | +} note_meta_t; | |
| 87 | + | |
| 88 | +static note_meta_t g_meta[MAX_NOTES]; | |
| 89 | +static int g_count; | |
| 90 | + | |
| 91 | +static char g_dir[PATH_SZ]; /* <notes dir> */ | |
| 92 | +static char g_trash[PATH_SZ]; /* <notes dir>/.trash */ | |
| 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)64 * 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 (!s || n == 0) return; | |
| 130 | + if (!buf_need(b, n)) return; | |
| 131 | + memcpy(b->p + b->n, s, n); | |
| 132 | + b->n += n; | |
| 133 | + b->p[b->n] = '\0'; | |
| 134 | +} | |
| 135 | + | |
| 136 | +static void buf_puts(buf_t *b, const char *s) | |
| 137 | +{ | |
| 138 | + if (s) buf_add(b, s, strlen(s)); | |
| 139 | +} | |
| 140 | + | |
| 141 | +static void buf_putc(buf_t *b, char c) | |
| 142 | +{ | |
| 143 | + buf_add(b, &c, 1); | |
| 144 | +} | |
| 145 | + | |
| 146 | +static const char *buf_str(buf_t *b) | |
| 147 | +{ | |
| 148 | + return b->p ? b->p : ""; | |
| 149 | +} | |
| 150 | + | |
| 151 | +static void buf_free(buf_t *b) | |
| 152 | +{ | |
| 153 | + free(b->p); | |
| 154 | + buf_init(b); | |
| 155 | +} | |
| 156 | + | |
| 157 | +/* ------------------------------------------------------------------ */ | |
| 158 | +/* Small utilities */ | |
| 159 | +/* ------------------------------------------------------------------ */ | |
| 160 | + | |
| 161 | +static void str_copy(char *dst, size_t sz, const char *src) | |
| 162 | +{ | |
| 163 | + size_t n; | |
| 164 | + if (!dst || sz == 0) return; | |
| 165 | + if (!src) { dst[0] = '\0'; return; } | |
| 166 | + n = strlen(src); | |
| 167 | + if (n >= sz) n = sz - 1; | |
| 168 | + memcpy(dst, src, n); | |
| 169 | + dst[n] = '\0'; | |
| 170 | +} | |
| 171 | + | |
| 172 | +static void path_join(char *out, size_t sz, const char *a, const char *b) | |
| 173 | +{ | |
| 174 | + size_t n; | |
| 175 | + if (!out || sz == 0) return; | |
| 176 | + out[0] = '\0'; | |
| 177 | + if (!a) a = ""; | |
| 178 | + if (!b) b = ""; | |
| 179 | + str_copy(out, sz, a); | |
| 180 | + n = strlen(out); | |
| 181 | + if (n && out[n - 1] != '/' && out[n - 1] != '\\' && n + 1 < sz) { | |
| 182 | + out[n++] = '/'; | |
| 183 | + out[n] = '\0'; | |
| 184 | + } | |
| 185 | + if (n + strlen(b) < sz) str_copy(out + n, sz - n, b); | |
| 186 | +} | |
| 187 | + | |
| 188 | +static void url_decode(char *s) | |
| 189 | +{ | |
| 190 | + char *o = s; | |
| 191 | + if (!s) return; | |
| 192 | + while (*s) { | |
| 193 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | |
| 194 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | |
| 195 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | |
| 196 | + *o++ = (char)((hi << 4) | lo); | |
| 197 | + s += 3; | |
| 198 | + } else if (*s == '+') { | |
| 199 | + *o++ = ' '; | |
| 200 | + s++; | |
| 201 | + } else { | |
| 202 | + *o++ = *s++; | |
| 203 | + } | |
| 204 | + } | |
| 205 | + *o = '\0'; | |
| 206 | +} | |
| 207 | + | |
| 208 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 209 | +{ | |
| 210 | + size_t klen; | |
| 211 | + const char *p; | |
| 212 | + | |
| 213 | + if (!out || outsz == 0) return 0; | |
| 214 | + out[0] = '\0'; | |
| 215 | + if (!qs || !key) return 0; | |
| 216 | + klen = strlen(key); | |
| 217 | + | |
| 218 | + for (p = qs; *p; ) { | |
| 219 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | |
| 220 | + const char *v = p + klen + 1; | |
| 221 | + size_t i = 0; | |
| 222 | + while (*v && *v != '&' && i + 1 < outsz) | |
| 223 | + out[i++] = *v++; | |
| 224 | + out[i] = '\0'; | |
| 225 | + url_decode(out); | |
| 226 | + return 1; | |
| 227 | + } | |
| 228 | + p = strchr(p, '&'); | |
| 229 | + if (!p) break; | |
| 230 | + p++; | |
| 231 | + } | |
| 232 | + return 0; | |
| 233 | +} | |
| 234 | + | |
| 235 | +static void json_str(buf_t *b, const char *s) | |
| 236 | +{ | |
| 237 | + buf_putc(b, '"'); | |
| 238 | + for (; s && *s; s++) { | |
| 239 | + unsigned char c = (unsigned char)*s; | |
| 240 | + switch (c) { | |
| 241 | + case '"': buf_puts(b, "\\\""); break; | |
| 242 | + case '\\': buf_puts(b, "\\\\"); break; | |
| 243 | + case '\n': buf_puts(b, "\\n"); break; | |
| 244 | + case '\r': buf_puts(b, "\\r"); break; | |
| 245 | + case '\t': buf_puts(b, "\\t"); break; | |
| 246 | + default: | |
| 247 | + if (c < 0x20) { | |
| 248 | + char tmp[8]; | |
| 249 | + sprintf(tmp, "\\u%04x", c); | |
| 250 | + buf_puts(b, tmp); | |
| 251 | + } else { | |
| 252 | + buf_putc(b, (char)c); | |
| 253 | + } | |
| 254 | + } | |
| 255 | + } | |
| 256 | + buf_putc(b, '"'); | |
| 257 | +} | |
| 258 | + | |
| 259 | +static void iso_now(char *out, size_t sz) | |
| 260 | +{ | |
| 261 | + time_t t = time(NULL); | |
| 262 | + struct tm tmv; | |
| 263 | +#if defined(_WIN32) | |
| 264 | + gmtime_s(&tmv, &t); | |
| 265 | +#else | |
| 266 | + gmtime_r(&t, &tmv); | |
| 267 | +#endif | |
| 268 | + strftime(out, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); | |
| 269 | +} | |
| 270 | + | |
| 271 | +static int valid_id(const char *id) | |
| 272 | +{ | |
| 273 | + int i; | |
| 274 | + if (!id) return 0; | |
| 275 | + if (strlen(id) != ID_LEN) return 0; | |
| 276 | + for (i = 0; i < ID_LEN; i++) { | |
| 277 | + char c = id[i]; | |
| 278 | + if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))) return 0; | |
| 279 | + } | |
| 280 | + return 1; | |
| 281 | +} | |
| 282 | + | |
| 283 | +static void gen_id(char *out) | |
| 284 | +{ | |
| 285 | + static const char *alpha = "abcdefghijklmnopqrstuvwxyz0123456789"; | |
| 286 | + unsigned int seed; | |
| 287 | + int i; | |
| 288 | +#if defined(_WIN32) | |
| 289 | + seed = (unsigned int)GetTickCount() ^ (unsigned int)time(NULL); | |
| 290 | +#else | |
| 291 | + seed = (unsigned int)time(NULL) ^ ((unsigned int)getpid() << 16); | |
| 292 | +#endif | |
| 293 | + seed ^= (unsigned int)(size_t)out; | |
| 294 | + seed = seed * 1103515245u + 12345u; | |
| 295 | + for (i = 0; i < ID_LEN; i++) { | |
| 296 | + seed = seed * 1103515245u + 12345u; | |
| 297 | + out[i] = alpha[(seed >> 16) % 36u]; | |
| 298 | + } | |
| 299 | + out[ID_LEN] = '\0'; | |
| 300 | +} | |
| 301 | + | |
| 302 | +/* ------------------------------------------------------------------ */ | |
| 303 | +/* Filesystem helpers */ | |
| 304 | +/* ------------------------------------------------------------------ */ | |
| 305 | + | |
| 306 | +static void mkdir_one(const char *p) | |
| 307 | +{ | |
| 308 | +#if defined(_WIN32) | |
| 309 | + _mkdir(p); | |
| 310 | +#else | |
| 311 | + mkdir(p, 0700); | |
| 312 | +#endif | |
| 313 | +} | |
| 314 | + | |
| 315 | +static int path_is_dir(const char *p) | |
| 316 | +{ | |
| 317 | +#if defined(_WIN32) | |
| 318 | + DWORD a = GetFileAttributesA(p); | |
| 319 | + return a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY); | |
| 320 | +#else | |
| 321 | + struct stat st; | |
| 322 | + return stat(p, &st) == 0 && S_ISDIR(st.st_mode); | |
| 323 | +#endif | |
| 324 | +} | |
| 325 | + | |
| 326 | +static int file_exists(const char *p) | |
| 327 | +{ | |
| 328 | +#if defined(_WIN32) | |
| 329 | + return GetFileAttributesA(p) != INVALID_FILE_ATTRIBUTES; | |
| 330 | +#else | |
| 331 | + return access(p, F_OK) == 0; | |
| 332 | +#endif | |
| 333 | +} | |
| 334 | + | |
| 335 | +/* Atomic replace: write to <dst>.tmp, then move it over <dst>. */ | |
| 336 | +static int atomic_write(const char *dst, const char *data, size_t len) | |
| 337 | +{ | |
| 338 | + char tmp[PATH_SZ + 8]; | |
| 339 | + FILE *f; | |
| 340 | + size_t wrote; | |
| 341 | + | |
| 342 | + if (!dst || strlen(dst) + 5 >= sizeof tmp) return 0; | |
| 343 | + sprintf(tmp, "%s.tmp", dst); | |
| 344 | + | |
| 345 | + f = fopen(tmp, "wb"); | |
| 346 | + if (!f) return 0; | |
| 347 | + wrote = fwrite(data, 1, len, f); | |
| 348 | + if (fflush(f) != 0) { fclose(f); remove(tmp); return 0; } | |
| 349 | +#if !defined(_WIN32) | |
| 350 | + fsync(fileno(f)); | |
| 351 | +#endif | |
| 352 | + if (fclose(f) != 0) { remove(tmp); return 0; } | |
| 353 | + if (wrote != len) { remove(tmp); return 0; } | |
| 354 | + | |
| 355 | +#if defined(_WIN32) | |
| 356 | + if (!MoveFileExA(tmp, dst, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { | |
| 357 | + remove(tmp); | |
| 358 | + return 0; | |
| 359 | + } | |
| 360 | +#else | |
| 361 | + if (rename(tmp, dst) != 0) { remove(tmp); return 0; } | |
| 362 | +#endif | |
| 363 | + return 1; | |
| 364 | +} | |
| 365 | + | |
| 366 | +static char *read_whole_file(const char *path, size_t *out_len) | |
| 367 | +{ | |
| 368 | + FILE *f; | |
| 369 | + long sz; | |
| 370 | + char *p; | |
| 371 | + size_t got; | |
| 372 | + | |
| 373 | + f = fopen(path, "rb"); | |
| 374 | + if (!f) return NULL; | |
| 375 | + if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; } | |
| 376 | + sz = ftell(f); | |
| 377 | + if (sz < 0) { fclose(f); return NULL; } | |
| 378 | + if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; } | |
| 379 | + p = (char *)malloc((size_t)sz + 1); | |
| 380 | + if (!p) { fclose(f); return NULL; } | |
| 381 | + got = fread(p, 1, (size_t)sz, f); | |
| 382 | + fclose(f); | |
| 383 | + p[got] = '\0'; | |
| 384 | + if (out_len) *out_len = got; | |
| 385 | + return p; | |
| 386 | +} | |
| 387 | + | |
| 388 | +/* ------------------------------------------------------------------ */ | |
| 389 | +/* Tiny JSON reader (only what index.json and the save payload need) */ | |
| 390 | +/* ------------------------------------------------------------------ */ | |
| 391 | + | |
| 392 | +/* Copy a JSON string value starting at *pp (which points at the opening | |
| 393 | + * quote) into out. Returns 1 on success and advances *pp past the closing | |
| 394 | + * quote. Handles the escapes this plugin can emit plus \uXXXX as UTF-8. */ | |
| 395 | +static int json_read_string(const char **pp, char *out, size_t outsz) | |
| 396 | +{ | |
| 397 | + const char *p = *pp; | |
| 398 | + size_t o = 0; | |
| 399 | + | |
| 400 | + if (!p || *p != '"') return 0; | |
| 401 | + p++; | |
| 402 | + while (*p && *p != '"') { | |
| 403 | + unsigned char c = (unsigned char)*p; | |
| 404 | + if (c == '\\') { | |
| 405 | + p++; | |
| 406 | + switch (*p) { | |
| 407 | + case '"': c = '"'; break; | |
| 408 | + case '\\': c = '\\'; break; | |
| 409 | + case '/': c = '/'; break; | |
| 410 | + case 'b': c = '\b'; break; | |
| 411 | + case 'f': c = '\f'; break; | |
| 412 | + case 'n': c = '\n'; break; | |
| 413 | + case 'r': c = '\r'; break; | |
| 414 | + case 't': c = '\t'; break; | |
| 415 | + case 'u': { | |
| 416 | + unsigned int cp = 0; | |
| 417 | + int i; | |
| 418 | + for (i = 0; i < 4 && p[1]; i++) { | |
| 419 | + char h = p[1 + i]; | |
| 420 | + cp <<= 4; | |
| 421 | + if (h >= '0' && h <= '9') cp |= (unsigned)(h - '0'); | |
| 422 | + else if (h >= 'a' && h <= 'f') cp |= (unsigned)(h - 'a' + 10); | |
| 423 | + else if (h >= 'A' && h <= 'F') cp |= (unsigned)(h - 'A' + 10); | |
| 424 | + } | |
| 425 | + p += 4; | |
| 426 | + /* BMP only; enough for the control characters we emit */ | |
| 427 | + if (cp == 0) { | |
| 428 | + c = 0; | |
| 429 | + } else if (cp < 0x80) { | |
| 430 | + c = (unsigned char)cp; | |
| 431 | + } else if (cp < 0x800) { | |
| 432 | + if (o + 1 < outsz) out[o++] = (char)(0xC0 | (cp >> 6)); | |
| 433 | + c = (unsigned char)(0x80 | (cp & 0x3F)); | |
| 434 | + } else { | |
| 435 | + if (o + 2 < outsz) { | |
| 436 | + out[o++] = (char)(0xE0 | (cp >> 12)); | |
| 437 | + out[o++] = (char)(0x80 | ((cp >> 6) & 0x3F)); | |
| 438 | + } | |
| 439 | + c = (unsigned char)(0x80 | (cp & 0x3F)); | |
| 440 | + } | |
| 441 | + if (c == 0) { p++; continue; } | |
| 442 | + break; | |
| 443 | + } | |
| 444 | + default: c = (unsigned char)*p; break; | |
| 445 | + } | |
| 446 | + p++; | |
| 447 | + } else { | |
| 448 | + p++; | |
| 449 | + } | |
| 450 | + if (o + 1 < outsz) out[o++] = (char)c; | |
| 451 | + } | |
| 452 | + if (*p == '"') p++; | |
| 453 | + if (outsz) out[o < outsz ? o : outsz - 1] = '\0'; | |
| 454 | + *pp = p; | |
| 455 | + return 1; | |
| 456 | +} | |
| 457 | + | |
| 458 | +/* Read a JSON string into a freshly allocated buffer. Bodies can be 512 KiB, | |
| 459 | + * so they must never land in a fixed-size stack frame. */ | |
| 460 | +static char *json_dup_string(const char **pp) | |
| 461 | +{ | |
| 462 | + const char *p = *pp; | |
| 463 | + buf_t b; | |
| 464 | + | |
| 465 | + if (!p || *p != '"') return NULL; | |
| 466 | + buf_init(&b); | |
| 467 | + if (!buf_need(&b, 0)) return NULL; | |
| 468 | + p++; | |
| 469 | + | |
| 470 | + while (*p && *p != '"') { | |
| 471 | + unsigned char c = (unsigned char)*p; | |
| 472 | + if (c == '\\') { | |
| 473 | + p++; | |
| 474 | + switch (*p) { | |
| 475 | + case '"': c = '"'; break; | |
| 476 | + case '\\': c = '\\'; break; | |
| 477 | + case '/': c = '/'; break; | |
| 478 | + case 'b': c = '\b'; break; | |
| 479 | + case 'f': c = '\f'; break; | |
| 480 | + case 'n': c = '\n'; break; | |
| 481 | + case 'r': c = '\r'; break; | |
| 482 | + case 't': c = '\t'; break; | |
| 483 | + case 'u': { | |
| 484 | + unsigned int cp = 0; | |
| 485 | + int i; | |
| 486 | + for (i = 0; i < 4 && p[1]; i++) { | |
| 487 | + char h = p[1 + i]; | |
| 488 | + cp <<= 4; | |
| 489 | + if (h >= '0' && h <= '9') cp |= (unsigned)(h - '0'); | |
| 490 | + else if (h >= 'a' && h <= 'f') cp |= (unsigned)(h - 'a' + 10); | |
| 491 | + else if (h >= 'A' && h <= 'F') cp |= (unsigned)(h - 'A' + 10); | |
| 492 | + } | |
| 493 | + p += 4; | |
| 494 | + if (cp < 0x80 && cp) { | |
| 495 | + buf_putc(&b, (char)cp); | |
| 496 | + } else if (cp >= 0x80 && cp < 0x800) { | |
| 497 | + buf_putc(&b, (char)(0xC0 | (cp >> 6))); | |
| 498 | + buf_putc(&b, (char)(0x80 | (cp & 0x3F))); | |
| 499 | + } else if (cp >= 0x800) { | |
| 500 | + buf_putc(&b, (char)(0xE0 | (cp >> 12))); | |
| 501 | + buf_putc(&b, (char)(0x80 | ((cp >> 6) & 0x3F))); | |
| 502 | + buf_putc(&b, (char)(0x80 | (cp & 0x3F))); | |
| 503 | + } | |
| 504 | + p++; | |
| 505 | + continue; | |
| 506 | + } | |
| 507 | + default: c = (unsigned char)*p; break; | |
| 508 | + } | |
| 509 | + p++; | |
| 510 | + } else { | |
| 511 | + p++; | |
| 512 | + } | |
| 513 | + buf_putc(&b, (char)c); | |
| 514 | + } | |
| 515 | + if (*p == '"') p++; | |
| 516 | + *pp = p; | |
| 517 | + if (!b.p) { char *e = (char *)malloc(1); if (e) e[0] = '\0'; return e; } | |
| 518 | + return b.p; | |
| 519 | +} | |
| 520 | + | |
| 521 | +/* Find `"key"` in a flat object body and copy its string value. */ | |
| 522 | +static int json_find_str(const char *json, const char *key, char *out, size_t outsz) | |
| 523 | +{ | |
| 524 | + char pat[64]; | |
| 525 | + const char *p; | |
| 526 | + | |
| 527 | + if (!json || !key) return 0; | |
| 528 | + sprintf(pat, "\"%s\"", key); | |
| 529 | + p = json; | |
| 530 | + while ((p = strstr(p, pat)) != NULL) { | |
| 531 | + const char *q = p + strlen(pat); | |
| 532 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | |
| 533 | + if (*q == ':') { | |
| 534 | + q++; | |
| 535 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | |
| 536 | + if (*q == '"') return json_read_string(&q, out, outsz); | |
| 537 | + return 0; | |
| 538 | + } | |
| 539 | + p += strlen(pat); | |
| 540 | + } | |
| 541 | + return 0; | |
| 542 | +} | |
| 543 | + | |
| 544 | +/* Same, for a small non-negative integer (accepts a quoted form too). */ | |
| 545 | +static int json_find_int(const char *json, const char *key, int *out) | |
| 546 | +{ | |
| 547 | + char pat[64]; | |
| 548 | + char raw[32]; | |
| 549 | + const char *p; | |
| 550 | + | |
| 551 | + if (!json || !key) return 0; | |
| 552 | + sprintf(pat, "\"%s\"", key); | |
| 553 | + p = json; | |
| 554 | + while ((p = strstr(p, pat)) != NULL) { | |
| 555 | + const char *q = p + strlen(pat); | |
| 556 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | |
| 557 | + if (*q == ':') { | |
| 558 | + q++; | |
| 559 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | |
| 560 | + if (*q == '"') { | |
| 561 | + if (!json_read_string(&q, raw, sizeof raw)) return 0; | |
| 562 | + } else if (strncmp(q, "true", 4) == 0) { | |
| 563 | + *out = 1; /* a JSON boolean is not a string */ | |
| 564 | + return 1; | |
| 565 | + } else if (strncmp(q, "false", 5) == 0) { | |
| 566 | + *out = 0; | |
| 567 | + return 1; | |
| 568 | + } else { | |
| 569 | + size_t i = 0; | |
| 570 | + while (q[i] && (isdigit((unsigned char)q[i]) || q[i] == '-') && i + 1 < sizeof raw) { | |
| 571 | + raw[i] = q[i]; | |
| 572 | + i++; | |
| 573 | + } | |
| 574 | + raw[i] = '\0'; | |
| 575 | + } | |
| 576 | + *out = atoi(raw); | |
| 577 | + return 1; | |
| 578 | + } | |
| 579 | + p += strlen(pat); | |
| 580 | + } | |
| 581 | + return 0; | |
| 582 | +} | |
| 583 | + | |
| 584 | +/* ------------------------------------------------------------------ */ | |
| 585 | +/* Node authentication */ | |
| 586 | +/* ------------------------------------------------------------------ */ | |
| 587 | + | |
| 588 | +static void require_node_auth(void) | |
| 589 | +{ | |
| 590 | + const char *np = getenv("BOT_PASSWORD"); | |
| 591 | + const char *xp; | |
| 592 | + const char *auth; | |
| 593 | + const char *qs; | |
| 594 | + char qpwd[256]; | |
| 595 | + | |
| 596 | + if (!np || !*np) return; | |
| 597 | + | |
| 598 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | |
| 599 | + if (xp && strcmp(xp, np) == 0) return; | |
| 600 | + | |
| 601 | + auth = getenv("HTTP_AUTHORIZATION"); | |
| 602 | + if (auth) { | |
| 603 | + while (*auth == ' ') auth++; | |
| 604 | + if (strncmp(auth, "Bearer ", 7) == 0) { | |
| 605 | + auth += 7; | |
| 606 | + while (*auth == ' ') auth++; | |
| 607 | + if (strcmp(auth, np) == 0) return; | |
| 608 | + } | |
| 609 | + } | |
| 610 | + | |
| 611 | + qs = getenv("QUERY_STRING"); | |
| 612 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) | |
| 613 | + return; | |
| 614 | + | |
| 615 | + fputs("Status: 401 Unauthorized\r\n" | |
| 616 | + "Content-Type: application/json; charset=utf-8\r\n" | |
| 617 | + "Cache-Control: no-store\r\n" | |
| 618 | + "X-Content-Type-Options: nosniff\r\n\r\n" | |
| 619 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | |
| 620 | + exit(0); | |
| 621 | +} | |
| 622 | + | |
| 623 | +/* ------------------------------------------------------------------ */ | |
| 624 | +/* Notes directory resolution */ | |
| 625 | +/* ------------------------------------------------------------------ */ | |
| 626 | + | |
| 627 | +static int ensure_notes_dir(void) | |
| 628 | +{ | |
| 629 | + char base[PATH_SZ]; | |
| 630 | + const char *env = getenv("NOTES_DIR"); | |
| 631 | + const char *bp; | |
| 632 | + | |
| 633 | + if (g_dir[0]) return 1; | |
| 634 | + | |
| 635 | + if (env && *env) { | |
| 636 | + str_copy(base, sizeof base, env); | |
| 637 | + } else if ((bp = getenv("BOT_PLUGIN_DIR")) != NULL && *bp) { | |
| 638 | + str_copy(base, sizeof base, bp); | |
| 639 | + mkdir_one(base); | |
| 640 | + path_join(g_dir, sizeof g_dir, base, ".notes"); | |
| 641 | + mkdir_one(g_dir); | |
| 642 | + path_join(g_trash, sizeof g_trash, g_dir, TRASH_DIR); | |
| 643 | + mkdir_one(g_trash); | |
| 644 | + return path_is_dir(g_dir); | |
| 645 | + } else { | |
| 646 | +#if defined(_WIN32) | |
| 647 | + const char *la = getenv("LOCALAPPDATA"); | |
| 648 | + char p1[PATH_SZ], p2[PATH_SZ]; | |
| 649 | + if (la && *la) { | |
| 650 | + path_join(p1, sizeof p1, la, "scorpiox"); | |
| 651 | + } else { | |
| 652 | + const char *up = getenv("USERPROFILE"); | |
| 653 | + if (up && *up) path_join(p1, sizeof p1, up, ".scorpiox"); | |
| 654 | + else str_copy(p1, sizeof p1, "."); | |
| 655 | + } | |
| 656 | + mkdir_one(p1); | |
| 657 | + path_join(p2, sizeof p2, p1, "plugins"); | |
| 658 | + mkdir_one(p2); | |
| 659 | + path_join(base, sizeof base, p2, ".notes"); | |
| 660 | +#else | |
| 661 | + const char *home = getenv("HOME"); | |
| 662 | + #if defined(__APPLE__) | |
| 663 | + if (access("/workspace", W_OK) == 0) { | |
| 664 | + char p2[PATH_SZ]; | |
| 665 | + path_join(p2, sizeof p2, "/workspace/.scorpiox", "plugins"); | |
| 666 | + mkdir_one(p2); | |
| 667 | + path_join(base, sizeof base, p2, ".notes"); | |
| 668 | + } else | |
| 669 | + #endif | |
| 670 | + if (home && *home) { | |
| 671 | + char p1[PATH_SZ], p2[PATH_SZ]; | |
| 672 | + path_join(p1, sizeof p1, home, ".scorpiox"); | |
| 673 | + mkdir_one(p1); | |
| 674 | + path_join(p2, sizeof p2, p1, "plugins"); | |
| 675 | + mkdir_one(p2); | |
| 676 | + path_join(base, sizeof base, p2, ".notes"); | |
| 677 | + } else { | |
| 678 | + str_copy(base, sizeof base, ".notes"); | |
| 679 | + } | |
| 680 | +#endif | |
| 681 | + } | |
| 682 | + | |
| 683 | + str_copy(g_dir, sizeof g_dir, base); | |
| 684 | + mkdir_one(g_dir); | |
| 685 | + path_join(g_trash, sizeof g_trash, g_dir, TRASH_DIR); | |
| 686 | + mkdir_one(g_trash); | |
| 687 | + return path_is_dir(g_dir); | |
| 688 | +} | |
| 689 | + | |
| 690 | +static void note_path(char *out, size_t sz, const char *id) | |
| 691 | +{ | |
| 692 | + char name[32]; | |
| 693 | + sprintf(name, "%s.md", id); | |
| 694 | + path_join(out, sz, g_dir, name); | |
| 695 | +} | |
| 696 | + | |
| 697 | +static void index_path(char *out, size_t sz) | |
| 698 | +{ | |
| 699 | + path_join(out, sz, g_dir, "index.json"); | |
| 700 | +} | |
| 701 | + | |
| 702 | +/* Read index.json into g_meta[]. A missing index is an empty store, and a | |
| 703 | + * truncated one loses the metadata but never the .md bodies. */ | |
| 704 | +static void load_index(void) | |
| 705 | +{ | |
| 706 | + char path[PATH_SZ]; | |
| 707 | + char *text; | |
| 708 | + const char *p; | |
| 709 | + | |
| 710 | + g_count = 0; | |
| 711 | + index_path(path, sizeof path); | |
| 712 | + text = read_whole_file(path, NULL); | |
| 713 | + if (!text) return; | |
| 714 | + | |
| 715 | + p = text; | |
| 716 | + /* Walk every object inside the top-level array. */ | |
| 717 | + while ((p = strchr(p, '{')) != NULL) { | |
| 718 | + const char *end = strchr(p, '}'); | |
| 719 | + char obj[8192]; | |
| 720 | + size_t n; | |
| 721 | + note_meta_t m; | |
| 722 | + | |
| 723 | + if (!end) break; | |
| 724 | + n = (size_t)(end - p) + 1; | |
| 725 | + if (n >= sizeof obj) n = sizeof obj - 1; | |
| 726 | + memcpy(obj, p, n); | |
| 727 | + obj[n] = '\0'; | |
| 728 | + p = end + 1; | |
| 729 | + | |
| 730 | + memset(&m, 0, sizeof m); | |
| 731 | + if (!json_find_str(obj, "id", m.id, sizeof m.id)) continue; | |
| 732 | + if (!valid_id(m.id)) continue; | |
| 733 | + if (!json_find_str(obj, "title", m.title, sizeof m.title)) | |
| 734 | + str_copy(m.title, sizeof m.title, ""); | |
| 735 | + json_find_int(obj, "pinned", &m.pinned); | |
| 736 | + if (!json_find_str(obj, "created", m.created, sizeof m.created)) | |
| 737 | + m.created[0] = '\0'; | |
| 738 | + if (!json_find_str(obj, "updated", m.updated, sizeof m.updated)) | |
| 739 | + m.updated[0] = '\0'; | |
| 740 | + | |
| 741 | + if (g_count < MAX_NOTES) g_meta[g_count++] = m; | |
| 742 | + } | |
| 743 | + free(text); | |
| 744 | +} | |
| 745 | + | |
| 746 | +static int meta_find(const char *id) | |
| 747 | +{ | |
| 748 | + int i; | |
| 749 | + for (i = 0; i < g_count; i++) | |
| 750 | + if (strcmp(g_meta[i].id, id) == 0) return i; | |
| 751 | + return -1; | |
| 752 | +} | |
| 753 | + | |
| 754 | +/* Pinned first, then most recently updated. */ | |
| 755 | +static int meta_cmp(const note_meta_t *a, const note_meta_t *b) | |
| 756 | +{ | |
| 757 | + if (a->pinned != b->pinned) return b->pinned - a->pinned; | |
| 758 | + return strcmp(b->updated, a->updated); | |
| 759 | +} | |
| 760 | + | |
| 761 | +static void sort_meta(void) | |
| 762 | +{ | |
| 763 | + int i, j; | |
| 764 | + for (i = 1; i < g_count; i++) { | |
| 765 | + note_meta_t key = g_meta[i]; | |
| 766 | + j = i - 1; | |
| 767 | + while (j >= 0 && meta_cmp(&g_meta[j], &key) > 0) { | |
| 768 | + g_meta[j + 1] = g_meta[j]; | |
| 769 | + j--; | |
| 770 | + } | |
| 771 | + g_meta[j + 1] = key; | |
| 772 | + } | |
| 773 | +} | |
| 774 | + | |
| 775 | +static int save_index(void) | |
| 776 | +{ | |
| 777 | + buf_t b; | |
| 778 | + char path[PATH_SZ]; | |
| 779 | + int i, ok; | |
| 780 | + | |
| 781 | + buf_init(&b); | |
| 782 | + buf_puts(&b, "{\"version\":1,\"notes\":[\n"); | |
| 783 | + for (i = 0; i < g_count; i++) { | |
| 784 | + buf_puts(&b, i ? ",\n" : ""); | |
| 785 | + buf_puts(&b, " {\"id\":"); | |
| 786 | + json_str(&b, g_meta[i].id); | |
| 787 | + buf_puts(&b, ",\"title\":"); | |
| 788 | + json_str(&b, g_meta[i].title); | |
| 789 | + buf_puts(&b, ",\"pinned\":"); | |
| 790 | + buf_putc(&b, g_meta[i].pinned ? '1' : '0'); | |
| 791 | + buf_puts(&b, ",\"created\":"); | |
| 792 | + json_str(&b, g_meta[i].created); | |
| 793 | + buf_puts(&b, ",\"updated\":"); | |
| 794 | + json_str(&b, g_meta[i].updated); | |
| 795 | + buf_putc(&b, '}'); | |
| 796 | + } | |
| 797 | + buf_puts(&b, "\n]}\n"); | |
| 798 | + | |
| 799 | + index_path(path, sizeof path); | |
| 800 | + ok = atomic_write(path, buf_str(&b), b.n); | |
| 801 | + buf_free(&b); | |
| 802 | + return ok; | |
| 803 | +} | |
| 804 | + | |
| 805 | +/* ------------------------------------------------------------------ */ | |
| 806 | +/* Markdown -> HTML (server side, escaped first) */ | |
| 807 | +/* ------------------------------------------------------------------ */ | |
| 808 | + | |
| 809 | +static void esc_html_into(buf_t *b, const char *s, size_t n) | |
| 810 | +{ | |
| 811 | + size_t i; | |
| 812 | + for (i = 0; i < n; i++) { | |
| 813 | + switch (s[i]) { | |
| 814 | + case '&': buf_puts(b, "&"); break; | |
| 815 | + case '<': buf_puts(b, "<"); break; | |
| 816 | + case '>': buf_puts(b, ">"); break; | |
| 817 | + case '"': buf_puts(b, """); break; | |
| 818 | + case '\'': buf_puts(b, "'"); break; | |
| 819 | + default: buf_putc(b, s[i]); | |
| 820 | + } | |
| 821 | + } | |
| 822 | +} | |
| 823 | + | |
| 824 | +static int url_is_safe(const char *u) | |
| 825 | +{ | |
| 826 | + size_t i; | |
| 827 | + if (!u || !*u) return 0; | |
| 828 | + if (u[0] == '/' || u[0] == '#') return 1; | |
| 829 | + for (i = 0; u[i]; i++) { | |
| 830 | + unsigned char c = (unsigned char)u[i]; | |
| 831 | + if (c == ':' || c == '/' || c == '?' || c == '#' || c == '&' || | |
| 832 | + c == '=' || c == '.' || c == '_' || c == '-' || c == '%' || | |
| 833 | + c == '+' || c == '~' || c == '@' || c == ',') continue; | |
| 834 | + if (c <= ' ') return 0; | |
| 835 | + } | |
| 836 | + if (strncmp(u, "https://", 8) == 0 || strncmp(u, "http://", 7) == 0 || | |
| 837 | + strncmp(u, "mailto:", 7) == 0) | |
| 838 | + return 1; | |
| 839 | + return 0; | |
| 840 | +} | |
| 841 | + | |
| 842 | +/* Escape a run of raw note text into the output buffer. Every literal | |
| 843 | + * character in a note goes through here, so note content can never emit a | |
| 844 | + * tag, an attribute or a script. */ | |
| 845 | +static void esc_into(buf_t *b, const char *s, size_t n) | |
| 846 | +{ | |
| 847 | + size_t i; | |
| 848 | + for (i = 0; i < n; i++) { | |
| 849 | + switch (s[i]) { | |
| 850 | + case '&': buf_puts(b, "&"); break; | |
| 851 | + case '<': buf_puts(b, "<"); break; | |
| 852 | + case '>': buf_puts(b, ">"); break; | |
| 853 | + case '"': buf_puts(b, """); break; | |
| 854 | + case '\'': buf_puts(b, "'"); break; | |
| 855 | + default: buf_putc(b, s[i]); | |
| 856 | + } | |
| 857 | + } | |
| 858 | +} | |
| 859 | + | |
| 860 | +/* Inline pass over raw text: **bold**, *italic*, `code`, [text](url). | |
| 861 | + * Everything it emits is a fixed tag name and every literal byte is escaped, | |
| 862 | + * so the only attribute in the output is a URL that passed url_is_safe(). */ | |
| 863 | +static void inline_into(buf_t *b, const char *s) | |
| 864 | +{ | |
| 865 | + size_t i = 0; | |
| 866 | + size_t n = strlen(s); | |
| 867 | + | |
| 868 | + while (i < n) { | |
| 869 | + char c = s[i]; | |
| 870 | + | |
| 871 | + /* `code` - content is escaped like any other literal text */ | |
| 872 | + if (c == '`') { | |
| 873 | + const char *close = strchr(s + i + 1, '`'); | |
| 874 | + if (close && close > s + i + 1) { | |
| 875 | + buf_puts(b, "<code>"); | |
| 876 | + esc_into(b, s + i + 1, (size_t)(close - (s + i + 1))); | |
| 877 | + buf_puts(b, "</code>"); | |
| 878 | + i = (size_t)(close - s) + 1; | |
| 879 | + continue; | |
| 880 | + } | |
| 881 | + } | |
| 882 | + | |
| 883 | + /* **bold** */ | |
| 884 | + if (c == '*' && i + 1 < n && s[i + 1] == '*') { | |
| 885 | + const char *close = strstr(s + i + 2, "**"); | |
| 886 | + if (close && close > s + i + 2) { | |
| 887 | + buf_puts(b, "<strong>"); | |
| 888 | + esc_into(b, s + i + 2, (size_t)(close - (s + i + 2))); | |
| 889 | + buf_puts(b, "</strong>"); | |
| 890 | + i = (size_t)(close - s) + 2; | |
| 891 | + continue; | |
| 892 | + } | |
| 893 | + } | |
| 894 | + | |
| 895 | + /* *italic* / _italic_ */ | |
| 896 | + if (c == '*' || c == '_') { | |
| 897 | + const char *close = strchr(s + i + 1, c); | |
| 898 | + if (close && close > s + i + 1 && !isspace((unsigned char)s[i + 1])) { | |
| 899 | + buf_puts(b, "<em>"); | |
| 900 | + esc_into(b, s + i + 1, (size_t)(close - (s + i + 1))); | |
| 901 | + buf_puts(b, "</em>"); | |
| 902 | + i = (size_t)(close - s) + 1; | |
| 903 | + continue; | |
| 904 | + } | |
| 905 | + } | |
| 906 | + | |
| 907 | + /* [text](url) - the href is emitted only when url_is_safe() agrees */ | |
| 908 | + if (c == '[') { | |
| 909 | + const char *rb = strchr(s + i + 1, ']'); | |
| 910 | + if (rb && rb[1] == '(') { | |
| 911 | + const char *rp = strchr(rb + 2, ')'); | |
| 912 | + if (rp) { | |
| 913 | + char url[512]; | |
| 914 | + size_t ul = (size_t)(rp - (rb + 2)); | |
| 915 | + if (ul < sizeof url) { | |
| 916 | + memcpy(url, rb + 2, ul); | |
| 917 | + url[ul] = '\0'; | |
| 918 | + if (url_is_safe(url)) { | |
| 919 | + buf_puts(b, "<a href=\""); | |
| 920 | + esc_into(b, url, ul); | |
| 921 | + buf_puts(b, "\" rel=\"noopener noreferrer\" target=\"_blank\">"); | |
| 922 | + esc_into(b, s + i + 1, (size_t)(rb - (s + i + 1))); | |
| 923 | + buf_puts(b, "</a>"); | |
| 924 | + i = (size_t)(rp - s) + 1; | |
| 925 | + continue; | |
| 926 | + } | |
| 927 | + } | |
| 928 | + } | |
| 929 | + } | |
| 930 | + } | |
| 931 | + | |
| 932 | + esc_into(b, &c, 1); | |
| 933 | + i++; | |
| 934 | + } | |
| 935 | +} | |
| 936 | + | |
| 937 | +/* Render one raw line's inline markup. */ | |
| 938 | +static void inline_line(buf_t *b, const char *line, size_t len) | |
| 939 | +{ | |
| 940 | + char *tmp = (char *)malloc(len + 1); | |
| 941 | + if (!tmp) return; | |
| 942 | + memcpy(tmp, line, len); | |
| 943 | + tmp[len] = '\0'; | |
| 944 | + inline_into(b, tmp); | |
| 945 | + free(tmp); | |
| 946 | +} | |
| 947 | + | |
| 948 | +static void render_markdown(buf_t *out, const char *md) | |
| 949 | +{ | |
| 950 | + const char *p = md ? md : ""; | |
| 951 | + int in_code = 0; | |
| 952 | + int in_list = 0; | |
| 953 | + int in_olist = 0; | |
| 954 | + int para_open = 0; | |
| 955 | + buf_t esc; | |
| 956 | + | |
| 957 | + buf_init(&esc); | |
| 958 | + | |
| 959 | + while (*p) { | |
| 960 | + const char *eol = strchr(p, '\n'); | |
| 961 | + size_t len = eol ? (size_t)(eol - p) : strlen(p); | |
| 962 | + char line[4096]; | |
| 963 | + size_t l = len < sizeof line - 1 ? len : sizeof line - 1; | |
| 964 | + | |
| 965 | + memcpy(line, p, l); | |
| 966 | + line[l] = '\0'; | |
| 967 | + while (l > 0 && line[l - 1] == '\r') line[--l] = '\0'; | |
| 968 | + | |
| 969 | + if (in_code) { | |
| 970 | + if (l >= 3 && line[0] == '`' && line[1] == '`' && line[2] == '`') { | |
| 971 | + buf_puts(out, "</code></pre>\n"); | |
| 972 | + in_code = 0; | |
| 973 | + } else { | |
| 974 | + esc_html_into(out, line, l); | |
| 975 | + buf_putc(out, '\n'); | |
| 976 | + } | |
| 977 | + p = eol ? eol + 1 : p + len; | |
| 978 | + continue; | |
| 979 | + } | |
| 980 | + | |
| 981 | + if (l >= 3 && line[0] == '`' && line[1] == '`' && line[2] == '`') { | |
| 982 | + if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; } | |
| 983 | + if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; } | |
| 984 | + if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; } | |
| 985 | + buf_puts(out, "<pre><code>"); | |
| 986 | + in_code = 1; | |
| 987 | + p = eol ? eol + 1 : p + len; | |
| 988 | + continue; | |
| 989 | + } | |
| 990 | + | |
| 991 | + if (l == 0) { | |
| 992 | + if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; } | |
| 993 | + if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; } | |
| 994 | + if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; } | |
| 995 | + p = eol ? eol + 1 : p + len; | |
| 996 | + continue; | |
| 997 | + } | |
| 998 | + | |
| 999 | + /* horizontal rule */ | |
| 1000 | + if (l >= 3 && (line[0] == '-' || line[0] == '*' || line[0] == '_')) { | |
| 1001 | + int all = 1, j; | |
| 1002 | + char ch = line[0]; | |
| 1003 | + int cnt = 0; | |
| 1004 | + for (j = 0; j < (int)l; j++) { | |
| 1005 | + if (line[j] == ch) cnt++; | |
| 1006 | + else if (line[j] != ' ') { all = 0; break; } | |
| 1007 | + } | |
| 1008 | + if (all && cnt >= 3) { | |
| 1009 | + if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; } | |
| 1010 | + if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; } | |
| 1011 | + if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; } | |
| 1012 | + buf_puts(out, "<hr>\n"); | |
| 1013 | + p = eol ? eol + 1 : p + len; | |
| 1014 | + continue; | |
| 1015 | + } | |
| 1016 | + } | |
| 1017 | + | |
| 1018 | + /* heading */ | |
| 1019 | + if (line[0] == '#') { | |
| 1020 | + int n = 0, j = 0; | |
| 1021 | + while (j < (int)l && line[j] == '#' && n < 6) { n++; j++; } | |
| 1022 | + if (n > 0 && (j >= (int)l || line[j] == ' ')) { | |
| 1023 | + char tag[8]; | |
| 1024 | + if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; } | |
| 1025 | + if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; } | |
| 1026 | + if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; } | |
| 1027 | + while (j < (int)l && line[j] == ' ') j++; | |
| 1028 | + sprintf(tag, "h%d", n); | |
| 1029 | + buf_puts(out, "<"); buf_puts(out, tag); buf_puts(out, ">"); | |
| 1030 | + while (l > (size_t)j && line[l - 1] == '#') l--; | |
| 1031 | + while (l > (size_t)j && line[l - 1] == ' ') l--; | |
| 1032 | + inline_line(out, line + j, l - (size_t)j); | |
| 1033 | + buf_puts(out, "</"); buf_puts(out, tag); buf_puts(out, ">\n"); | |
| 1034 | + p = eol ? eol + 1 : p + len; | |
| 1035 | + continue; | |
| 1036 | + } | |
| 1037 | + } | |
| 1038 | + | |
| 1039 | + /* blockquote */ | |
| 1040 | + if (line[0] == '>') { | |
| 1041 | + size_t j = 1; | |
| 1042 | + if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; } | |
| 1043 | + if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; } | |
| 1044 | + if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; } | |
| 1045 | + while (j < l && line[j] == ' ') j++; | |
| 1046 | + buf_puts(out, "<blockquote>"); | |
| 1047 | + inline_line(out, line + j, l - j); | |
| 1048 | + buf_puts(out, "</blockquote>\n"); | |
| 1049 | + p = eol ? eol + 1 : p + len; | |
| 1050 | + continue; | |
| 1051 | + } | |
| 1052 | + | |
| 1053 | + /* unordered list item */ | |
| 1054 | + if ((line[0] == '-' || line[0] == '*' || line[0] == '+') && l > 1 && line[1] == ' ') { | |
| 1055 | + if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; } | |
| 1056 | + if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; } | |
| 1057 | + if (!in_list) { buf_puts(out, "<ul>\n"); in_list = 1; } | |
| 1058 | + buf_puts(out, "<li>"); | |
| 1059 | + inline_line(out, line + 2, l - 2); | |
| 1060 | + buf_puts(out, "</li>\n"); | |
| 1061 | + p = eol ? eol + 1 : p + len; | |
| 1062 | + continue; | |
| 1063 | + } | |
| 1064 | + | |
| 1065 | + /* ordered list item */ | |
| 1066 | + if (isdigit((unsigned char)line[0])) { | |
| 1067 | + size_t j = 0; | |
| 1068 | + while (j < l && isdigit((unsigned char)line[j])) j++; | |
| 1069 | + if (j < l && line[j] == '.' && j + 1 < l && line[j + 1] == ' ') { | |
| 1070 | + if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; } | |
| 1071 | + if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; } | |
| 1072 | + if (!in_olist) { buf_puts(out, "<ol>\n"); in_olist = 1; } | |
| 1073 | + buf_puts(out, "<li>"); | |
| 1074 | + inline_line(out, line + j + 2, l - j - 2); | |
| 1075 | + buf_puts(out, "</li>\n"); | |
| 1076 | + p = eol ? eol + 1 : p + len; | |
| 1077 | + continue; | |
| 1078 | + } | |
| 1079 | + } | |
| 1080 | + | |
| 1081 | + /* paragraph text (consecutive lines join with a space) */ | |
| 1082 | + if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; } | |
| 1083 | + if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; } | |
| 1084 | + if (para_open) buf_putc(out, ' '); | |
| 1085 | + else { buf_puts(out, "<p>"); para_open = 1; } | |
| 1086 | + inline_line(out, line, l); | |
| 1087 | + p = eol ? eol + 1 : p + len; | |
| 1088 | + } | |
| 1089 | + | |
| 1090 | + if (in_code) buf_puts(out, "</code></pre>\n"); | |
| 1091 | + if (in_list) buf_puts(out, "</ul>\n"); | |
| 1092 | + if (in_olist) buf_puts(out, "</ol>\n"); | |
| 1093 | + if (para_open) buf_puts(out, "</p>\n"); | |
| 1094 | + buf_free(&esc); | |
| 1095 | +} | |
| 1096 | + | |
| 1097 | +/* ------------------------------------------------------------------ */ | |
| 1098 | +/* Request body */ | |
| 1099 | +/* ------------------------------------------------------------------ */ | |
| 1100 | + | |
| 1101 | +/* Read the POST body only when the frontend actually sent one (guarded on | |
| 1102 | + * CONTENT_LENGTH, so an inherited empty stdin never blocks the process), | |
| 1103 | + * and never beyond REQ_MAX. */ | |
| 1104 | +static int read_request_body(char *out, size_t sz) | |
| 1105 | +{ | |
| 1106 | + const char *cl = getenv("CONTENT_LENGTH"); | |
| 1107 | + long len; | |
| 1108 | + size_t got; | |
| 1109 | + | |
| 1110 | + if (!out || sz == 0) return 0; | |
| 1111 | + out[0] = '\0'; | |
| 1112 | + if (!cl || !*cl) return 0; | |
| 1113 | + len = strtol(cl, NULL, 10); | |
| 1114 | + if (len <= 0) return 0; | |
| 1115 | + if ((size_t)len >= sz) return -1; /* too large -> caller answers 413 */ | |
| 1116 | + got = fread(out, 1, (size_t)len, stdin); | |
| 1117 | + out[got] = '\0'; | |
| 1118 | + return (int)got; | |
| 1119 | +} | |
| 1120 | + | |
| 1121 | +static void json_header(void) | |
| 1122 | +{ | |
| 1123 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | |
| 1124 | + "Cache-Control: no-store\r\n" | |
| 1125 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 1126 | +} | |
| 1127 | + | |
| 1128 | +static void json_err(int code, const char *status, const char *msg) | |
| 1129 | +{ | |
| 1130 | + if (code == 400) | |
| 1131 | + fputs("Status: 400 Bad Request\r\n", stdout); | |
| 1132 | + else if (code == 404) | |
| 1133 | + fputs("Status: 404 Not Found\r\n", stdout); | |
| 1134 | + else if (code == 413) | |
| 1135 | + fputs("Status: 413 Payload Too Large\r\n", stdout); | |
| 1136 | + else if (code == 500) | |
| 1137 | + fputs("Status: 500 Internal Server Error\r\n", stdout); | |
| 1138 | + json_header(); | |
| 1139 | + printf("{\"ok\":false,\"error\":"); | |
| 1140 | + { | |
| 1141 | + buf_t b; | |
| 1142 | + buf_init(&b); | |
| 1143 | + json_str(&b, msg ? msg : status); | |
| 1144 | + fputs(buf_str(&b), stdout); | |
| 1145 | + buf_free(&b); | |
| 1146 | + } | |
| 1147 | + fputs("}\n", stdout); | |
| 1148 | +} | |
| 1149 | + | |
| 1150 | +/* ------------------------------------------------------------------ */ | |
| 1151 | +/* API actions */ | |
| 1152 | +/* ------------------------------------------------------------------ */ | |
| 1153 | + | |
| 1154 | +/* Push the metadata rows, optionally filtered, onto the response. */ | |
| 1155 | +static void emit_list(const char *only_id, const char *needle) | |
| 1156 | +{ | |
| 1157 | + buf_t rows, env; | |
| 1158 | + int i, shown = 0; | |
| 1159 | + char lneedle[256]; | |
| 1160 | + | |
| 1161 | + buf_init(&rows); | |
| 1162 | + buf_init(&env); | |
| 1163 | + | |
| 1164 | + if (needle) { | |
| 1165 | + size_t k; | |
| 1166 | + str_copy(lneedle, sizeof lneedle, needle); | |
| 1167 | + for (k = 0; lneedle[k]; k++) | |
| 1168 | + lneedle[k] = (char)tolower((unsigned char)lneedle[k]); | |
| 1169 | + } else { | |
| 1170 | + lneedle[0] = '\0'; | |
| 1171 | + } | |
| 1172 | + | |
| 1173 | + for (i = 0; i < g_count; i++) { | |
| 1174 | + char path[PATH_SZ]; | |
| 1175 | + char *body = NULL; | |
| 1176 | + int match = 1; | |
| 1177 | + | |
| 1178 | + if (only_id && strcmp(g_meta[i].id, only_id) != 0) continue; | |
| 1179 | + | |
| 1180 | + if (lneedle[0]) { | |
| 1181 | + char ltitle[TITLE_MAX]; | |
| 1182 | + size_t k, j; | |
| 1183 | + | |
| 1184 | + str_copy(ltitle, sizeof ltitle, g_meta[i].title); | |
| 1185 | + for (k = 0; ltitle[k]; k++) | |
| 1186 | + ltitle[k] = (char)tolower((unsigned char)ltitle[k]); | |
| 1187 | + match = strstr(ltitle, lneedle) != NULL; | |
| 1188 | + | |
| 1189 | + if (!match) { | |
| 1190 | + note_path(path, sizeof path, g_meta[i].id); | |
| 1191 | + body = read_whole_file(path, NULL); | |
| 1192 | + if (body) { | |
| 1193 | + size_t n = strlen(body); | |
| 1194 | + for (j = 0; j < n; j++) | |
| 1195 | + body[j] = (char)tolower((unsigned char)body[j]); | |
| 1196 | + match = strstr(body, lneedle) != NULL; | |
| 1197 | + body[j] = '\0'; | |
| 1198 | + } | |
| 1199 | + free(body); | |
| 1200 | + } | |
| 1201 | + } | |
| 1202 | + | |
| 1203 | + if (!match) continue; | |
| 1204 | + | |
| 1205 | + buf_puts(&rows, shown ? ",\n {\"id\":" : "\n {\"id\":"); | |
| 1206 | + json_str(&rows, g_meta[i].id); | |
| 1207 | + buf_puts(&rows, ",\"title\":"); | |
| 1208 | + json_str(&rows, g_meta[i].title); | |
| 1209 | + buf_puts(&rows, ",\"pinned\":"); | |
| 1210 | + buf_putc(&rows, g_meta[i].pinned ? '1' : '0'); | |
| 1211 | + buf_puts(&rows, ",\"created\":"); | |
| 1212 | + json_str(&rows, g_meta[i].created); | |
| 1213 | + buf_puts(&rows, ",\"updated\":"); | |
| 1214 | + json_str(&rows, g_meta[i].updated); | |
| 1215 | + buf_putc(&rows, '}'); | |
| 1216 | + shown++; | |
| 1217 | + } | |
| 1218 | + | |
| 1219 | + buf_puts(&env, "{\"ok\":true,\"count\":"); | |
| 1220 | + { | |
| 1221 | + char num[16]; | |
| 1222 | + sprintf(num, "%d", shown); | |
| 1223 | + buf_puts(&env, num); | |
| 1224 | + } | |
| 1225 | + buf_puts(&env, ",\"notes\":["); | |
| 1226 | + buf_puts(&env, buf_str(&rows)); | |
| 1227 | + buf_puts(&env, shown ? "\n]}\n" : "]}\n"); | |
| 1228 | + fwrite(buf_str(&env), 1, env.n, stdout); | |
| 1229 | + | |
| 1230 | + buf_free(&rows); | |
| 1231 | + buf_free(&env); | |
| 1232 | +} | |
| 1233 | + | |
| 1234 | +static void do_list(void) | |
| 1235 | +{ | |
| 1236 | + json_header(); | |
| 1237 | + emit_list(NULL, NULL); | |
| 1238 | +} | |
| 1239 | + | |
| 1240 | +static void do_search(const char *q) | |
| 1241 | +{ | |
| 1242 | + json_header(); | |
| 1243 | + emit_list(NULL, (q && *q) ? q : NULL); | |
| 1244 | +} | |
| 1245 | + | |
| 1246 | +static void do_get(const char *id) | |
| 1247 | +{ | |
| 1248 | + int idx; | |
| 1249 | + char path[PATH_SZ]; | |
| 1250 | + char *body; | |
| 1251 | + | |
| 1252 | + if (!valid_id(id)) { json_err(400, "Bad Request", "invalid id"); return; } | |
| 1253 | + idx = meta_find(id); | |
| 1254 | + if (idx < 0) { json_err(404, "Not Found", "note not found"); return; } | |
| 1255 | + | |
| 1256 | + note_path(path, sizeof path, id); | |
| 1257 | + body = read_whole_file(path, NULL); | |
| 1258 | + | |
| 1259 | + json_header(); | |
| 1260 | + { | |
| 1261 | + buf_t b; | |
| 1262 | + buf_init(&b); | |
| 1263 | + buf_puts(&b, "{\"ok\":true,\"note\":{\"id\":"); | |
| 1264 | + json_str(&b, g_meta[idx].id); | |
| 1265 | + buf_puts(&b, ",\"title\":"); | |
| 1266 | + json_str(&b, g_meta[idx].title); | |
| 1267 | + buf_puts(&b, ",\"pinned\":"); | |
| 1268 | + buf_putc(&b, g_meta[idx].pinned ? '1' : '0'); | |
| 1269 | + buf_puts(&b, ",\"created\":"); | |
| 1270 | + json_str(&b, g_meta[idx].created); | |
| 1271 | + buf_puts(&b, ",\"updated\":"); | |
| 1272 | + json_str(&b, g_meta[idx].updated); | |
| 1273 | + buf_puts(&b, ",\"body\":"); | |
| 1274 | + json_str(&b, body ? body : ""); | |
| 1275 | + buf_puts(&b, "}}\n"); | |
| 1276 | + fwrite(buf_str(&b), 1, b.n, stdout); | |
| 1277 | + buf_free(&b); | |
| 1278 | + } | |
| 1279 | + free(body); | |
| 1280 | +} | |
| 1281 | + | |
| 1282 | +static void do_save(const char *body_json) | |
| 1283 | +{ | |
| 1284 | + char id[64] = ""; | |
| 1285 | + char title[TITLE_MAX] = ""; | |
| 1286 | + char *body = NULL; | |
| 1287 | + int pinned = 0; | |
| 1288 | + int idx; | |
| 1289 | + char path[PATH_SZ]; | |
| 1290 | + char now[24]; | |
| 1291 | + note_meta_t m; | |
| 1292 | + | |
| 1293 | + if (!body_json || !*body_json) { | |
| 1294 | + json_err(400, "Bad Request", "empty body"); | |
| 1295 | + return; | |
| 1296 | + } | |
| 1297 | + | |
| 1298 | + json_find_str(body_json, "id", id, sizeof id); | |
| 1299 | + json_find_str(body_json, "title", title, sizeof title); | |
| 1300 | + | |
| 1301 | + /* The body is the only large field: take it straight out of the JSON. */ | |
| 1302 | + { | |
| 1303 | + const char *p = strstr(body_json, "\"body\""); | |
| 1304 | + if (p) { | |
| 1305 | + const char *q = p + 6; | |
| 1306 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | |
| 1307 | + if (*q == ':') { | |
| 1308 | + q++; | |
| 1309 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | |
| 1310 | + if (*q == '"') body = json_dup_string(&q); | |
| 1311 | + } | |
| 1312 | + } | |
| 1313 | + } | |
| 1314 | + if (!body) { | |
| 1315 | + json_err(400, "Bad Request", "missing body field"); | |
| 1316 | + return; | |
| 1317 | + } | |
| 1318 | + if (strlen(body) > (size_t)BODY_MAX) { | |
| 1319 | + free(body); | |
| 1320 | + json_err(413, "Payload Too Large", "note body exceeds 512 KiB"); | |
| 1321 | + return; | |
| 1322 | + } | |
| 1323 | + | |
| 1324 | + if (id[0] && !valid_id(id)) { | |
| 1325 | + free(body); | |
| 1326 | + json_err(400, "Bad Request", "invalid id"); | |
| 1327 | + return; | |
| 1328 | + } | |
| 1329 | + | |
| 1330 | + if (!json_find_int(body_json, "pinned", &pinned)) pinned = 0; | |
| 1331 | + pinned = pinned ? 1 : 0; | |
| 1332 | + | |
| 1333 | + iso_now(now, sizeof now); | |
| 1334 | + | |
| 1335 | + idx = id[0] ? meta_find(id) : -1; | |
| 1336 | + memset(&m, 0, sizeof m); | |
| 1337 | + if (idx >= 0) { | |
| 1338 | + m = g_meta[idx]; | |
| 1339 | + if (json_find_int(body_json, "pinned", &pinned)) m.pinned = pinned ? 1 : 0; | |
| 1340 | + } else { | |
| 1341 | + if (id[0]) str_copy(m.id, sizeof m.id, id); | |
| 1342 | + else gen_id(m.id); | |
| 1343 | + str_copy(m.created, sizeof m.created, now); | |
| 1344 | + m.pinned = pinned; | |
| 1345 | + } | |
| 1346 | + str_copy(m.title, sizeof m.title, title); | |
| 1347 | + str_copy(m.updated, sizeof m.updated, now); | |
| 1348 | + | |
| 1349 | + /* Write the body first: a metadata row must never point at a note that | |
| 1350 | + * was never written. */ | |
| 1351 | + note_path(path, sizeof path, m.id); | |
| 1352 | + if (!atomic_write(path, body, strlen(body))) { | |
| 1353 | + free(body); | |
| 1354 | + json_err(500, "Internal Server Error", "could not write note"); | |
| 1355 | + return; | |
| 1356 | + } | |
| 1357 | + free(body); | |
| 1358 | + | |
| 1359 | + if (idx >= 0) g_meta[idx] = m; | |
| 1360 | + else if (g_count < MAX_NOTES) g_meta[g_count++] = m; | |
| 1361 | + else { json_err(500, "Internal Server Error", "note limit reached"); return; } | |
| 1362 | + | |
| 1363 | + sort_meta(); | |
| 1364 | + if (!save_index()) { | |
| 1365 | + json_err(500, "Internal Server Error", "could not write index"); | |
| 1366 | + return; | |
| 1367 | + } | |
| 1368 | + | |
| 1369 | + json_header(); | |
| 1370 | + { | |
| 1371 | + buf_t b; | |
| 1372 | + buf_init(&b); | |
| 1373 | + buf_puts(&b, "{\"ok\":true,\"note\":{\"id\":"); | |
| 1374 | + json_str(&b, m.id); | |
| 1375 | + buf_puts(&b, ",\"title\":"); | |
| 1376 | + json_str(&b, m.title); | |
| 1377 | + buf_puts(&b, ",\"pinned\":"); | |
| 1378 | + buf_putc(&b, m.pinned ? '1' : '0'); | |
| 1379 | + buf_puts(&b, ",\"created\":"); | |
| 1380 | + json_str(&b, m.created); | |
| 1381 | + buf_puts(&b, ",\"updated\":"); | |
| 1382 | + json_str(&b, m.updated); | |
| 1383 | + buf_puts(&b, "}}\n"); | |
| 1384 | + fwrite(buf_str(&b), 1, b.n, stdout); | |
| 1385 | + buf_free(&b); | |
| 1386 | + } | |
| 1387 | +} | |
| 1388 | + | |
| 1389 | +static void do_pin(const char *id, const char *body_json, const char *qs) | |
| 1390 | +{ | |
| 1391 | + int idx, pin = -1; | |
| 1392 | + char v[16]; | |
| 1393 | + | |
| 1394 | + if (!valid_id(id)) { json_err(400, "Bad Request", "invalid id"); return; } | |
| 1395 | + idx = meta_find(id); | |
| 1396 | + if (idx < 0) { json_err(404, "Not Found", "note not found"); return; } | |
| 1397 | + | |
| 1398 | + if (!json_find_int(body_json ? body_json : "", "pin", &pin)) { | |
| 1399 | + if (qs && get_query_val(qs, "pin", v, sizeof v)) pin = atoi(v); | |
| 1400 | + } | |
| 1401 | + if (pin < 0) pin = g_meta[idx].pinned ? 0 : 1; | |
| 1402 | + | |
| 1403 | + g_meta[idx].pinned = pin ? 1 : 0; | |
| 1404 | + iso_now(g_meta[idx].updated, sizeof g_meta[idx].updated); | |
| 1405 | + sort_meta(); | |
| 1406 | + if (!save_index()) { json_err(500, "Internal Server Error", "could not write index"); return; } | |
| 1407 | + | |
| 1408 | + json_header(); | |
| 1409 | + printf("{\"ok\":true,\"id\":\"%s\",\"pinned\":%d}\n", id, g_meta[meta_find(id)].pinned); | |
| 1410 | +} | |
| 1411 | + | |
| 1412 | +static void do_delete(const char *id) | |
| 1413 | +{ | |
| 1414 | + int idx, i; | |
| 1415 | + char src[PATH_SZ], dst[PATH_SZ], name[32]; | |
| 1416 | + | |
| 1417 | + if (!valid_id(id)) { json_err(400, "Bad Request", "invalid id"); return; } | |
| 1418 | + idx = meta_find(id); | |
| 1419 | + if (idx < 0) { json_err(404, "Not Found", "note not found"); return; } | |
| 1420 | + | |
| 1421 | + note_path(src, sizeof src, id); | |
| 1422 | + sprintf(name, "%s.md", id); | |
| 1423 | + path_join(dst, sizeof dst, g_trash, name); | |
| 1424 | + | |
| 1425 | + if (file_exists(src)) { | |
| 1426 | + /* Keep a copy in .trash so a wrong click is recoverable. */ | |
| 1427 | +#if defined(_WIN32) | |
| 1428 | + MoveFileExA(src, dst, MOVEFILE_REPLACE_EXISTING); | |
| 1429 | +#else | |
| 1430 | + rename(src, dst); | |
| 1431 | +#endif | |
| 1432 | + } | |
| 1433 | + | |
| 1434 | + for (i = idx; i < g_count - 1; i++) g_meta[i] = g_meta[i + 1]; | |
| 1435 | + if (g_count > 0) g_count--; | |
| 1436 | + | |
| 1437 | + if (!save_index()) { json_err(500, "Internal Server Error", "could not write index"); return; } | |
| 1438 | + | |
| 1439 | + json_header(); | |
| 1440 | + printf("{\"ok\":true,\"deleted\":\"%s\",\"trash\":true}\n", id); | |
| 1441 | +} | |
| 1442 | + | |
| 1443 | +static void do_render(const char *body_json, const char *qs) | |
| 1444 | +{ | |
| 1445 | + char *text = NULL; | |
| 1446 | + buf_t out; | |
| 1447 | + | |
| 1448 | + if (body_json && *body_json) { | |
| 1449 | + const char *p = strstr(body_json, "\"body\""); | |
| 1450 | + if (p) { | |
| 1451 | + const char *q = p + 6; | |
| 1452 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | |
| 1453 | + if (*q == ':') { | |
| 1454 | + q++; | |
| 1455 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | |
| 1456 | + if (*q == '"') text = json_dup_string(&q); | |
| 1457 | + } | |
| 1458 | + } | |
| 1459 | + } | |
| 1460 | + if (!text && qs) { | |
| 1461 | + /* Convenience for GET callers; capped so a URL cannot allocate much. */ | |
| 1462 | + char tmp[8192]; | |
| 1463 | + if (get_query_val(qs, "text", tmp, sizeof tmp)) { | |
| 1464 | + text = (char *)malloc(strlen(tmp) + 1); | |
| 1465 | + if (text) str_copy(text, strlen(tmp) + 1, tmp); | |
| 1466 | + } | |
| 1467 | + } | |
| 1468 | + if (!text) { | |
| 1469 | + json_err(400, "Bad Request", "missing body field"); | |
| 1470 | + return; | |
| 1471 | + } | |
| 1472 | + if (strlen(text) > (size_t)BODY_MAX) { | |
| 1473 | + free(text); | |
| 1474 | + json_err(413, "Payload Too Large", "note body exceeds 512 KiB"); | |
| 1475 | + return; | |
| 1476 | + } | |
| 1477 | + | |
| 1478 | + buf_init(&out); | |
| 1479 | + render_markdown(&out, text); | |
| 1480 | + | |
| 1481 | + json_header(); | |
| 1482 | + { | |
| 1483 | + buf_t b; | |
| 1484 | + buf_init(&b); | |
| 1485 | + buf_puts(&b, "{\"ok\":true,\"html\":"); | |
| 1486 | + json_str(&b, buf_str(&out)); | |
| 1487 | + buf_puts(&b, "}\n"); | |
| 1488 | + fwrite(buf_str(&b), 1, b.n, stdout); | |
| 1489 | + buf_free(&b); | |
| 1490 | + } | |
| 1491 | + buf_free(&out); | |
| 1492 | + free(text); | |
| 1493 | +} | |
| 1494 | + | |
| 1495 | +/* ------------------------------------------------------------------ */ | |
| 1496 | +/* HTML mode */ | |
| 1497 | +/* ------------------------------------------------------------------ */ | |
| 1498 | + | |
| 1499 | +/* Split UI_HTML on the two control-byte placeholders and expand them into | |
| 1500 | + * the theme macros, so the page and the bot palette can never drift. */ | |
| 1501 | +static void emit_ui(int embed) | |
| 1502 | +{ | |
| 1503 | + const char *p = UI_HTML; | |
| 1504 | + | |
| 1505 | + while (*p) { | |
| 1506 | + if (*p == '\001') { | |
| 1507 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS | |
| 1508 | + ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);--ac:var(--blue)}" | |
| 1509 | + "</style>", stdout); | |
| 1510 | + p++; | |
| 1511 | + } else if (*p == '\002') { | |
| 1512 | + fputs(SX_BOT_THEME_HANDOFF, stdout); | |
| 1513 | + p++; | |
| 1514 | + } else { | |
| 1515 | + putchar(*p++); | |
| 1516 | + } | |
| 1517 | + } | |
| 1518 | + (void)embed; | |
| 1519 | +} | |
| 1520 | + | |
| 1521 | +static void mode_html(int embed) | |
| 1522 | +{ | |
| 1523 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | |
| 1524 | + "Cache-Control: no-store\r\n" | |
| 1525 | + "X-Content-Type-Options: nosniff\r\n" | |
| 1526 | + "X-Frame-Options: SAMEORIGIN\r\n" | |
| 1527 | + "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " | |
| 1528 | + "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " | |
| 1529 | + "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); | |
| 1530 | + emit_ui(embed); | |
| 1531 | +} | |
| 1532 | + | |
| 1533 | +/* ------------------------------------------------------------------ */ | |
| 1534 | +/* Entry */ | |
| 1535 | +/* ------------------------------------------------------------------ */ | |
| 1536 | + | |
| 1537 | +static const char *method(void) | |
| 1538 | +{ | |
| 1539 | + const char *m = getenv("REQUEST_METHOD"); | |
| 1540 | + return (m && *m) ? m : "GET"; | |
| 1541 | +} | |
| 1542 | + | |
| 1543 | +int main(int argc, char **argv) | |
| 1544 | +{ | |
| 1545 | + const char *qs; | |
| 1546 | + const char *req_method; | |
| 1547 | + char action[64]; | |
| 1548 | + char id[64]; | |
| 1549 | + char val[256]; | |
| 1550 | + static char body[REQ_MAX]; | |
| 1551 | + int got; | |
| 1552 | + | |
| 1553 | + /* 1. Discovery metadata (unauthenticated so /plugins can probe it) */ | |
| 1554 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { | |
| 1555 | + printf("{\"name\":\"%s\",\"desc\":\"%s\"}\n", PLUGIN_NAME, PLUGIN_DESC); | |
| 1556 | + return 0; | |
| 1557 | + } | |
| 1558 | + if (argc > 1 && strcmp(argv[1], "--version") == 0) { | |
| 1559 | + printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); | |
| 1560 | + return 0; | |
| 1561 | + } | |
| 1562 | + | |
| 1563 | + require_node_auth(); | |
| 1564 | + | |
| 1565 | + qs = getenv("QUERY_STRING"); | |
| 1566 | + if (!qs) qs = ""; | |
| 1567 | + req_method = method(); | |
| 1568 | + | |
| 1569 | + action[0] = '\0'; | |
| 1570 | + id[0] = '\0'; | |
| 1571 | + get_query_val(qs, "action", action, sizeof action); | |
| 1572 | + get_query_val(qs, "id", id, sizeof id); | |
| 1573 | + | |
| 1574 | + /* 2. Anything that names an action, asks for JSON, or POSTs is API. */ | |
| 1575 | + if (action[0] || strstr(qs, "format=json") || strcmp(req_method, "POST") == 0) { | |
| 1576 | + int action_present = action[0] != '\0'; | |
| 1577 | + char act[64]; | |
| 1578 | + | |
| 1579 | + if (!action_present) { | |
| 1580 | + char fmt[32]; | |
| 1581 | + if (get_query_val(qs, "format", fmt, sizeof fmt) && strcmp(fmt, "json") == 0) | |
| 1582 | + str_copy(action, sizeof action, "list"); | |
| 1583 | + else | |
| 1584 | + str_copy(action, sizeof action, "list"); | |
| 1585 | + } | |
| 1586 | + /* Keep two buffers: reading `format` into `action` would clobber the | |
| 1587 | + * action we just parsed (lesson (l) in the market tracker). */ | |
| 1588 | + str_copy(act, sizeof act, action); | |
| 1589 | + | |
| 1590 | + if (!ensure_notes_dir()) { json_err(500, "Internal Server Error", "notes dir unavailable"); return 0; } | |
| 1591 | + load_index(); | |
| 1592 | + | |
| 1593 | + got = read_request_body(body, sizeof body); | |
| 1594 | + if (got < 0) { json_err(413, "Payload Too Large", "request body too large"); return 0; } | |
| 1595 | + | |
| 1596 | + if (strcmp(act, "list") == 0) { | |
| 1597 | + do_list(); | |
| 1598 | + } else if (strcmp(act, "get") == 0) { | |
| 1599 | + do_get(id); | |
| 1600 | + } else if (strcmp(act, "search") == 0) { | |
| 1601 | + val[0] = '\0'; | |
| 1602 | + get_query_val(qs, "q", val, sizeof val); | |
| 1603 | + do_search(val); | |
| 1604 | + } else if (strcmp(act, "save") == 0) { | |
| 1605 | + do_save(body); | |
| 1606 | + } else if (strcmp(act, "delete") == 0) { | |
| 1607 | + do_delete(id); | |
| 1608 | + } else if (strcmp(act, "pin") == 0) { | |
| 1609 | + do_pin(id, body, qs); | |
| 1610 | + } else if (strcmp(act, "render") == 0) { | |
| 1611 | + do_render(body, qs); | |
| 1612 | + } else { | |
| 1613 | + json_err(400, "Bad Request", "unknown action"); | |
| 1614 | + } | |
| 1615 | + return 0; | |
| 1616 | + } | |
| 1617 | + | |
| 1618 | + /* 3. Everything else is the page. */ | |
| 1619 | + { | |
| 1620 | + int embed = strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL; | |
| 1621 | + mode_html(embed); | |
| 1622 | + } | |
| 1623 | + return 0; | |
| 1624 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..90603fd | ||
| --- /dev/null | ||
| +++ b/src/ui.html | ||
| @@ -0,0 +1,444 @@ | ||
| 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>notes</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:288px 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 | +.icon{display:inline-flex;align-items:center;justify-content:center;gap:6px; | |
| 21 | + background:var(--surface-2);border:1px solid var(--line);color:var(--text); | |
| 22 | + border-radius:9px;width:30px;height:30px;padding:0;cursor:pointer;font-family:inherit; | |
| 23 | + font-size:12px;font-weight:600} | |
| 24 | +.icon:hover{background:var(--surface-hover);border-color:var(--line-2)} | |
| 25 | +.icon:active{transform:scale(.96)} | |
| 26 | +.icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor; | |
| 27 | + stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round} | |
| 28 | +.icon.danger{color:var(--red)} | |
| 29 | +.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:6px 14px; | |
| 30 | + font-weight:600;font-size:12.5px;cursor:pointer;font-family:inherit} | |
| 31 | +.btn:active{transform:scale(.98)} | |
| 32 | +.search{margin:0 12px 8px;padding:8px 11px;border-radius:9px;border:1px solid var(--line); | |
| 33 | + background:var(--input-bg);color:var(--text);font-family:inherit;font-size:13px} | |
| 34 | +.search:focus{outline:2px solid var(--blue);outline-offset:-1px} | |
| 35 | +.list{flex:1 1 auto;overflow-y:auto;padding:0 8px 8px} | |
| 36 | +.item{display:block;width:100%;text-align:left;background:transparent;border:0; | |
| 37 | + border-radius:10px;padding:9px 10px;color:var(--text);cursor:pointer;font-family:inherit; | |
| 38 | + margin-bottom:2px;position:relative} | |
| 39 | +.item:hover{background:var(--surface-hover)} | |
| 40 | +.item.sel{background:var(--surface-2);box-shadow:inset 2px 0 0 var(--blue)} | |
| 41 | +.item .t{font-size:13.5px;font-weight:600;white-space:nowrap;overflow:hidden; | |
| 42 | + text-overflow:ellipsis;padding-right:18px} | |
| 43 | +.item .m{font-size:11px;color:var(--text-2);white-space:nowrap;overflow:hidden; | |
| 44 | + text-overflow:ellipsis;margin-top:2px} | |
| 45 | +.item .pinmark{position:absolute;top:9px;right:9px;width:11px;height:11px;color:var(--blue); | |
| 46 | + display:none} | |
| 47 | +.item.pinned .pinmark{display:block} | |
| 48 | +.item .pinmark svg{width:11px;height:11px;fill:currentColor;stroke:none} | |
| 49 | +.empty{padding:18px 12px;color:var(--text-2);font-size:12.5px;text-align:center} | |
| 50 | +.hidden{display:none!important} | |
| 51 | +#main{background:var(--bg)} | |
| 52 | +.toolbar{display:flex;align-items:center;gap:8px;padding:10px 14px; | |
| 53 | + border-bottom:1px solid var(--line);flex:0 0 auto;min-width:0} | |
| 54 | +.toolbar .title{flex:1 1 auto;min-width:0;background:transparent;border:0;color:var(--text); | |
| 55 | + font-family:inherit;font-size:16px;font-weight:650;padding:4px 2px;border-radius:6px} | |
| 56 | +.toolbar .title:focus{outline:0;background:var(--input-bg);padding:4px 8px} | |
| 57 | +.state{font-size:11px;font-weight:600;color:var(--text-2);white-space:nowrap; | |
| 58 | + padding:2px 8px;border-radius:999px;background:var(--surface-2)} | |
| 59 | +.state.dirty{color:var(--orange)} | |
| 60 | +.state.ok{color:var(--green)} | |
| 61 | +.back{display:none} | |
| 62 | +.split{flex:1 1 auto;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr); | |
| 63 | + min-height:0} | |
| 64 | +.editor{width:100%;height:100%;resize:none;border:0;border-right:1px solid var(--line); | |
| 65 | + background:var(--bg);color:var(--text);font-family:var(--mono);font-size:13px; | |
| 66 | + line-height:1.65;padding:16px 18px;tab-size:2} | |
| 67 | +.editor:focus{outline:0} | |
| 68 | +.preview{overflow-y:auto;padding:16px 20px 40px;min-width:0} | |
| 69 | +.preview h1,.preview h2,.preview h3,.preview h4,.preview h5,.preview h6{ | |
| 70 | + line-height:1.25;margin:18px 0 8px;font-weight:650} | |
| 71 | +.preview h1{font-size:24px;letter-spacing:-.01em} | |
| 72 | +.preview h2{font-size:19px} | |
| 73 | +.preview h3{font-size:16px} | |
| 74 | +.preview h4,.preview h5,.preview h6{font-size:14px;color:var(--text-2)} | |
| 75 | +.preview h1:first-child,.preview h2:first-child,.preview p:first-child{margin-top:0} | |
| 76 | +.preview p{margin:0 0 10px} | |
| 77 | +.preview ul,.preview ol{margin:0 0 10px;padding-left:22px} | |
| 78 | +.preview li{margin:2px 0} | |
| 79 | +.preview blockquote{margin:0 0 10px;padding:2px 12px;border-left:3px solid var(--line-2); | |
| 80 | + color:var(--text-2)} | |
| 81 | +.preview code{font-family:var(--mono);font-size:12px;background:var(--code-bg); | |
| 82 | + padding:1px 5px;border-radius:5px} | |
| 83 | +.preview pre{background:var(--code-bg);border:1px solid var(--line);border-radius:10px; | |
| 84 | + padding:11px 13px;overflow-x:auto;margin:0 0 12px} | |
| 85 | +.preview pre code{background:transparent;padding:0;font-size:12px;line-height:1.55} | |
| 86 | +.preview hr{border:0;border-top:1px solid var(--line);margin:16px 0} | |
| 87 | +.preview a{color:var(--blue);text-decoration:none;font-weight:600} | |
| 88 | +.preview a:hover{text-decoration:underline} | |
| 89 | +.preview table{border-collapse:collapse;margin:0 0 12px;font-size:13px} | |
| 90 | +.preview th,.preview td{border:1px solid var(--line);padding:5px 9px;text-align:left} | |
| 91 | +.preview th{color:var(--text-2);font-size:11.5px;text-transform:uppercase;letter-spacing:.04em} | |
| 92 | +.welcome{flex:1 1 auto;display:flex;flex-direction:column;align-items:center; | |
| 93 | + justify-content:center;gap:10px;color:var(--text-2);font-size:13px;padding:24px;text-align:center} | |
| 94 | +.welcome svg{width:34px;height:34px;fill:none;stroke:currentColor;stroke-width:1.4; | |
| 95 | + stroke-linecap:round;stroke-linejoin:round;opacity:.55} | |
| 96 | +.toast{position:fixed;left:50%;bottom:18px;transform:translateX(-50%); | |
| 97 | + background:var(--modal-bg);border:1px solid var(--line-2);color:var(--text); | |
| 98 | + padding:8px 14px;border-radius:999px;font-size:12.5px;box-shadow:var(--shadow-lg); | |
| 99 | + opacity:0;pointer-events:none;transition:opacity .16s var(--ease);z-index:9} | |
| 100 | +.toast.show{opacity:1} | |
| 101 | +@media (max-width:700px){ | |
| 102 | + body{overflow:hidden} | |
| 103 | + #app{grid-template-columns:minmax(0,1fr)} | |
| 104 | + #side,#main{grid-column:1;grid-row:1;width:100%} | |
| 105 | + #app[data-view="edit"] #side{display:none} | |
| 106 | + #app[data-view="list"] #main{display:none} | |
| 107 | + #side{border-right:0} | |
| 108 | + .back{display:inline-flex} | |
| 109 | + .split{grid-template-columns:minmax(0,1fr)} | |
| 110 | + .editor{border-right:0} | |
| 111 | + #app:not([data-view="preview"]) .preview{display:none} | |
| 112 | + .toolbar{padding:8px 10px;gap:6px} | |
| 113 | + .toolbar .title{font-size:15px} | |
| 114 | + .editor{padding:12px} | |
| 115 | + .preview{padding:12px 14px 32px} | |
| 116 | +} | |
| 117 | +</style> | |
| 118 | +</head><body> | |
| 119 | +<div id="app" data-view="list"> | |
| 120 | + <aside id="side" class="pane"> | |
| 121 | + <div class="side-hd"> | |
| 122 | + <span class="brand">notes</span> | |
| 123 | + <button id="btnNew" class="icon" title="New note" aria-label="New note"> | |
| 124 | + <svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg></button> | |
| 125 | + </div> | |
| 126 | + <input id="q" class="search" placeholder="Search notes" autocomplete="off" spellcheck="false"> | |
| 127 | + <div id="list" class="list"></div> | |
| 128 | + <div id="listEmpty" class="empty hidden">No notes yet. Create one with the plus button.</div> | |
| 129 | + <div class="side-ft"> | |
| 130 | + <span id="count">0 notes</span><span class="grow"></span> | |
| 131 | + <button id="btnTheme" class="icon embed-hide" title="Toggle appearance" aria-label="Toggle appearance"> | |
| 132 | + <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> | |
| 133 | + </div> | |
| 134 | + </aside> | |
| 135 | + <main id="main" class="pane"> | |
| 136 | + <div id="editorWrap" class="pane hidden"> | |
| 137 | + <div class="toolbar"> | |
| 138 | + <button id="btnBack" class="icon back" title="All notes" aria-label="All notes"> | |
| 139 | + <svg viewBox="0 0 24 24"><path d="M15 5l-7 7 7 7"/></svg></button> | |
| 140 | + <input id="title" class="title" placeholder="Untitled note" spellcheck="false"> | |
| 141 | + <span id="state" class="state">saved</span> | |
| 142 | + <button id="btnPin" class="icon" title="Pin note" aria-label="Pin note"> | |
| 143 | + <svg viewBox="0 0 24 24"><path d="M9 3h6l-1 6 3 3v2H7v-2l3-3-1-6zM12 14v7"/></svg></button> | |
| 144 | + <button id="btnPreview" class="icon back" title="Toggle preview" aria-label="Toggle preview"> | |
| 145 | + <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> | |
| 146 | + <button id="btnSave" class="btn" title="Save (Ctrl/Cmd+S)">Save</button> | |
| 147 | + <button id="btnDel" class="icon danger" title="Delete note" aria-label="Delete note"> | |
| 148 | + <svg viewBox="0 0 24 24"><path d="M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13M10 11v6M14 11v6"/></svg></button> | |
| 149 | + </div> | |
| 150 | + <div class="split"> | |
| 151 | + <textarea id="body" class="editor" spellcheck="false" placeholder="Write markdown — # heading, **bold**, - list, `code`"></textarea> | |
| 152 | + <div id="preview" class="preview"></div> | |
| 153 | + </div> | |
| 154 | + </div> | |
| 155 | + <div id="welcome" class="welcome"> | |
| 156 | + <svg viewBox="0 0 24 24"><path d="M6 3h9l5 5v13H6z"/><path d="M14 3v5h5M9 13h7M9 17h5"/></svg> | |
| 157 | + <div>Select a note or create a new one.</div> | |
| 158 | + <div style="font-size:11.5px">Ctrl/Cmd+S saves · Ctrl/Cmd+K searches</div> | |
| 159 | + </div> | |
| 160 | + </main> | |
| 161 | +</div> | |
| 162 | +<div id="toast" class="toast"></div> | |
| 163 | +<script> | |
| 164 | +(function(){ | |
| 165 | +"use strict"; | |
| 166 | +var app=document.getElementById('app'); | |
| 167 | +var listEl=document.getElementById('list'); | |
| 168 | +var listEmpty=document.getElementById('listEmpty'); | |
| 169 | +var countEl=document.getElementById('count'); | |
| 170 | +var qEl=document.getElementById('q'); | |
| 171 | +var titleEl=document.getElementById('title'); | |
| 172 | +var bodyEl=document.getElementById('body'); | |
| 173 | +var previewEl=document.getElementById('preview'); | |
| 174 | +var stateEl=document.getElementById('state'); | |
| 175 | +var editorWrap=document.getElementById('editorWrap'); | |
| 176 | +var welcome=document.getElementById('welcome'); | |
| 177 | +var toastEl=document.getElementById('toast'); | |
| 178 | + | |
| 179 | +var q=new URLSearchParams(location.search); | |
| 180 | +var node=q.get('node')||''; | |
| 181 | +var sid=q.get('id')||''; | |
| 182 | +var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))|| | |
| 183 | + localStorage.getItem('bot_active_pwd')||''; | |
| 184 | +var HUB=q.get('plugin')||''; | |
| 185 | +var SCROLLKEY='bot_notes_scroll'; | |
| 186 | + | |
| 187 | +/* Two call routes, and getting this wrong is the most common plugin bug: | |
| 188 | + * page served through the hub (bot.scorpiox.net/plugins?plugin=plugin_notes&node=..) | |
| 189 | + * -> call the hub proxy back: /plugins?plugin=plugin_notes&action=.. | |
| 190 | + * opened directly on the node | |
| 191 | + * -> the plugin itself is the route: /plugin_notes?action=.. | |
| 192 | + * Calling /plugins?plugin= on the node returns the discovery list, not us. */ | |
| 193 | +function url(action,extra){ | |
| 194 | + var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_notes')+ | |
| 195 | + '?action='+encodeURIComponent(action)+ | |
| 196 | + (extra?('&'+extra):'')+ | |
| 197 | + (node?'&node='+encodeURIComponent(node):'')+ | |
| 198 | + (sid?'&id='+encodeURIComponent(sid):'')+ | |
| 199 | + (pwd?'&pwd='+encodeURIComponent(pwd):''); | |
| 200 | + return u; | |
| 201 | +} | |
| 202 | +function hdr(extra){ | |
| 203 | + var h=extra||{}; | |
| 204 | + if(pwd)h['X-Bot-Password']=pwd; | |
| 205 | + return h; | |
| 206 | +} | |
| 207 | +function api(action,extra){ | |
| 208 | + return fetch(url(action,extra),{headers:hdr({})}).then(function(r){ | |
| 209 | + if(!r.ok)throw new Error('HTTP '+r.status); | |
| 210 | + return r.json(); | |
| 211 | + }); | |
| 212 | +} | |
| 213 | +function apiPost(action,extra,payload){ | |
| 214 | + return fetch(url(action,extra),{method:'POST', | |
| 215 | + headers:hdr({'Content-Type':'application/json'}), | |
| 216 | + body:JSON.stringify(payload||{})}).then(function(r){ | |
| 217 | + if(!r.ok)throw new Error('HTTP '+r.status); | |
| 218 | + return r.json(); | |
| 219 | + }); | |
| 220 | +} | |
| 221 | + | |
| 222 | +var notes=[]; /* list rows */ | |
| 223 | +var cur=null; /* {id,title,body,pinned} */ | |
| 224 | +var dirty=false; | |
| 225 | +var saveTimer=null, prevTimer=null, searchTimer=null; | |
| 226 | +var saving=false; | |
| 227 | + | |
| 228 | +function toast(msg){ | |
| 229 | + toastEl.textContent=msg; | |
| 230 | + toastEl.classList.add('show'); | |
| 231 | + clearTimeout(toast._t); | |
| 232 | + toast._t=setTimeout(function(){toastEl.classList.remove('show');},1800); | |
| 233 | +} | |
| 234 | +function setState(kind,text){ | |
| 235 | + stateEl.className='state'+(kind?(' '+kind):''); | |
| 236 | + stateEl.textContent=text; | |
| 237 | +} | |
| 238 | +function fmtDate(iso){ | |
| 239 | + if(!iso)return ''; | |
| 240 | + try{ | |
| 241 | + var d=new Date(iso);var now=new Date(); | |
| 242 | + var diff=(now-d)/1000; | |
| 243 | + if(diff<60)return 'just now'; | |
| 244 | + if(diff<3600)return Math.floor(diff/60)+' min ago'; | |
| 245 | + if(diff<86400)return Math.floor(diff/3600)+' h ago'; | |
| 246 | + if(diff<604800)return Math.floor(diff/86400)+' d ago'; | |
| 247 | + return d.toLocaleDateString(); | |
| 248 | + }catch(e){return ''} | |
| 249 | +} | |
| 250 | + | |
| 251 | +function renderList(){ | |
| 252 | + while(listEl.firstChild)listEl.removeChild(listEl.firstChild); | |
| 253 | + var shown=0; | |
| 254 | + notes.forEach(function(n){ | |
| 255 | + var b=document.createElement('button'); | |
| 256 | + b.className='item'+(n.pinned?' pinned':'')+(cur&&cur.id===n.id?' sel':''); | |
| 257 | + b.setAttribute('data-id',n.id); | |
| 258 | + var t=document.createElement('div');t.className='t';t.textContent=n.title||'Untitled'; | |
| 259 | + var m=document.createElement('div');m.className='m'; | |
| 260 | + m.textContent=(n.pinned?'Pinned · ':'')+fmtDate(n.updated); | |
| 261 | + var pm=document.createElement('span');pm.className='pinmark'; | |
| 262 | + pm.innerHTML='<svg viewBox="0 0 24 24"><path d="M9 3h6l-1 6 3 3v2H7v-2l3-3-1-6z"/></svg>'; | |
| 263 | + b.appendChild(t);b.appendChild(m);b.appendChild(pm); | |
| 264 | + b.onclick=function(){openNote(n.id);}; | |
| 265 | + listEl.appendChild(b);shown++; | |
| 266 | + }); | |
| 267 | + listEmpty.classList.toggle('hidden',shown>0); | |
| 268 | + countEl.textContent=shown+(shown===1?' note':' notes'); | |
| 269 | + if(cur){ | |
| 270 | + var sel=listEl.querySelector('.item.sel'); | |
| 271 | + if(sel&&sel.scrollIntoView)sel.scrollIntoView({block:'nearest'}); | |
| 272 | + } | |
| 273 | +} | |
| 274 | + | |
| 275 | +function refresh(){ | |
| 276 | + return api('list').then(function(d){ | |
| 277 | + notes=(d&&d.notes)||[]; | |
| 278 | + renderList(); | |
| 279 | + }).catch(function(e){ | |
| 280 | + toast('Could not load notes: '+e.message); | |
| 281 | + }); | |
| 282 | +} | |
| 283 | + | |
| 284 | +function setView(v){app.setAttribute('data-view',v);} | |
| 285 | + | |
| 286 | +function openNote(id){ | |
| 287 | + return api('get','id='+encodeURIComponent(id)).then(function(d){ | |
| 288 | + if(!d||!d.note){toast('Note not found');return;} | |
| 289 | + cur={id:d.note.id,title:d.note.title||'',body:d.note.body||'', | |
| 290 | + pinned:!!d.note.pinned}; | |
| 291 | + titleEl.value=cur.title; | |
| 292 | + bodyEl.value=cur.body; | |
| 293 | + editorWrap.classList.remove('hidden'); | |
| 294 | + welcome.classList.add('hidden'); | |
| 295 | + setState('','saved'); | |
| 296 | + dirty=false; | |
| 297 | + setView('edit'); | |
| 298 | + document.getElementById('btnPin').classList.toggle('active',cur.pinned); | |
| 299 | + renderList(); | |
| 300 | + if(window.matchMedia('(min-width:701px)').matches){ | |
| 301 | + bodyEl.focus(); | |
| 302 | + } | |
| 303 | + renderPreview(); | |
| 304 | + }).catch(function(e){toast('Could not open note: '+e.message);}); | |
| 305 | +} | |
| 306 | + | |
| 307 | +function newNote(){ | |
| 308 | + cur={id:'',title:'',body:'',pinned:false}; | |
| 309 | + titleEl.value='';bodyEl.value=''; | |
| 310 | + editorWrap.classList.remove('hidden'); | |
| 311 | + welcome.classList.add('hidden'); | |
| 312 | + setState('dirty','unsaved'); | |
| 313 | + dirty=true; | |
| 314 | + setView('edit'); | |
| 315 | + previewEl.innerHTML=''; | |
| 316 | + titleEl.focus(); | |
| 317 | +} | |
| 318 | + | |
| 319 | +function scheduleSave(){ | |
| 320 | + dirty=true; | |
| 321 | + setState('dirty','unsaved'); | |
| 322 | + clearTimeout(saveTimer); | |
| 323 | + saveTimer=setTimeout(function(){save();},800); | |
| 324 | +} | |
| 325 | + | |
| 326 | +function save(force){ | |
| 327 | + if(!cur)return Promise.resolve(); | |
| 328 | + if(!dirty&&!force)return Promise.resolve(); | |
| 329 | + if(saving)return Promise.resolve(); | |
| 330 | + saving=true; | |
| 331 | + setState('','saving'); | |
| 332 | + var payload={title:titleEl.value,body:bodyEl.value,pinned:cur.pinned?1:0}; | |
| 333 | + if(cur.id)payload.id=cur.id; | |
| 334 | + return apiPost('save','',payload).then(function(d){ | |
| 335 | + saving=false; | |
| 336 | + if(d&&d.note){ | |
| 337 | + cur.id=d.note.id;cur.title=d.note.title;cur.body=bodyEl.value; | |
| 338 | + dirty=false; | |
| 339 | + setState('ok','saved'); | |
| 340 | + return refresh(); | |
| 341 | + } | |
| 342 | + throw new Error(d&&d.error?d.error:'save failed'); | |
| 343 | + }).catch(function(e){ | |
| 344 | + saving=false; | |
| 345 | + setState('dirty','unsaved'); | |
| 346 | + toast('Save failed: '+e.message); | |
| 347 | + }); | |
| 348 | +} | |
| 349 | + | |
| 350 | +function removeNote(){ | |
| 351 | + if(!cur||!cur.id){newNote();return;} | |
| 352 | + if(!window.confirm('Move "'+(cur.title||'Untitled')+'" to the trash?'))return; | |
| 353 | + apiPost('delete','id='+encodeURIComponent(cur.id),{}).then(function(){ | |
| 354 | + cur=null; | |
| 355 | + editorWrap.classList.add('hidden'); | |
| 356 | + welcome.classList.remove('hidden'); | |
| 357 | + setView('list'); | |
| 358 | + toast('Moved to trash'); | |
| 359 | + return refresh(); | |
| 360 | + }).catch(function(e){toast('Delete failed: '+e.message);}); | |
| 361 | +} | |
| 362 | + | |
| 363 | +function togglePin(){ | |
| 364 | + if(!cur)return; | |
| 365 | + cur.pinned=!cur.pinned; | |
| 366 | + document.getElementById('btnPin').classList.toggle('active',cur.pinned); | |
| 367 | + if(!cur.id){scheduleSave();return;} | |
| 368 | + apiPost('pin','id='+encodeURIComponent(cur.id),{pin:cur.pinned?1:0}) | |
| 369 | + .then(function(){return refresh();}) | |
| 370 | + .catch(function(e){toast('Pin failed: '+e.message);}); | |
| 371 | +} | |
| 372 | + | |
| 373 | +function renderPreview(){ | |
| 374 | + if(!cur)return; | |
| 375 | + var text=bodyEl.value; | |
| 376 | + clearTimeout(prevTimer); | |
| 377 | + prevTimer=setTimeout(function(){ | |
| 378 | + apiPost('render','',{body:text}).then(function(d){ | |
| 379 | + if(d&&typeof d.html==='string')previewEl.innerHTML=d.html; | |
| 380 | + }).catch(function(){/* preview is best-effort */}); | |
| 381 | + },220); | |
| 382 | +} | |
| 383 | + | |
| 384 | +function doSearch(){ | |
| 385 | + var term=qEl.value.trim(); | |
| 386 | + clearTimeout(searchTimer); | |
| 387 | + searchTimer=setTimeout(function(){ | |
| 388 | + if(!term){refresh();return;} | |
| 389 | + api('search','q='+encodeURIComponent(term)).then(function(d){ | |
| 390 | + notes=(d&&d.notes)||[]; | |
| 391 | + renderList(); | |
| 392 | + }).catch(function(e){toast('Search failed: '+e.message);}); | |
| 393 | + },180); | |
| 394 | +} | |
| 395 | + | |
| 396 | +document.getElementById('btnNew').onclick=newNote; | |
| 397 | +document.getElementById('btnSave').onclick=function(){save(true);}; | |
| 398 | +document.getElementById('btnDel').onclick=removeNote; | |
| 399 | +document.getElementById('btnPin').onclick=togglePin; | |
| 400 | +document.getElementById('btnBack').onclick=function(){ | |
| 401 | + setView('list');renderList(); | |
| 402 | +}; | |
| 403 | +document.getElementById('btnPreview').onclick=function(){ | |
| 404 | + setView(app.getAttribute('data-view')==='preview'?'edit':'preview'); | |
| 405 | +}; | |
| 406 | +qEl.addEventListener('input',doSearch); | |
| 407 | +titleEl.addEventListener('input',scheduleSave); | |
| 408 | +bodyEl.addEventListener('input',function(){scheduleSave();renderPreview();}); | |
| 409 | +titleEl.addEventListener('keydown',function(e){ | |
| 410 | + if(e.key==='Enter'){e.preventDefault();bodyEl.focus();} | |
| 411 | +}); | |
| 412 | +bodyEl.addEventListener('keydown',function(e){ | |
| 413 | + if(e.key==='Tab'){ | |
| 414 | + e.preventDefault(); | |
| 415 | + var s=bodyEl.selectionStart,en=bodyEl.selectionEnd; | |
| 416 | + bodyEl.value=bodyEl.value.slice(0,s)+' '+bodyEl.value.slice(en); | |
| 417 | + bodyEl.selectionStart=bodyEl.selectionEnd=s+2; | |
| 418 | + scheduleSave();renderPreview(); | |
| 419 | + } | |
| 420 | +}); | |
| 421 | +document.addEventListener('keydown',function(e){ | |
| 422 | + var mod=e.metaKey||e.ctrlKey; | |
| 423 | + if(!mod)return; | |
| 424 | + var k=(e.key||'').toLowerCase(); | |
| 425 | + if(k==='s'){e.preventDefault();save(true);} | |
| 426 | + else if(k==='k'){e.preventDefault();qEl.focus();qEl.select();} | |
| 427 | + else if(k==='n'&&e.altKey){e.preventDefault();newNote();} | |
| 428 | +}); | |
| 429 | + | |
| 430 | +var themeBtn=document.getElementById('btnTheme'); | |
| 431 | +if(themeBtn&&window.sxApplyTheme){ | |
| 432 | + themeBtn.onclick=function(){ | |
| 433 | + window.sxApplyTheme(window.sxTheme&&window.sxTheme()==='dark'?'light':'dark'); | |
| 434 | + }; | |
| 435 | +} | |
| 436 | + | |
| 437 | +refresh().then(function(){ | |
| 438 | + if(notes.length&&window.matchMedia('(min-width:701px)').matches){ | |
| 439 | + /* stay on the list — the user picks; predictable beats clever */ | |
| 440 | + } | |
| 441 | +}); | |
| 442 | +})(); | |
| 443 | +</script> | |
| 444 | +</body></html> |
| 1 | 1 | new file mode 100644 |
| index 0000000..fc15a02 | ||
| --- /dev/null | ||
| +++ b/src/ui_html.h | ||
| @@ -0,0 +1,452 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | |
| 2 | +#ifndef SX_NOTES_UI_HTML_H | |
| 3 | +#define SX_NOTES_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>notes</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:288px 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 | + ".icon{display:inline-flex;align-items:center;justify-content:center;gap:6px;\n" | |
| 26 | + " background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n" | |
| 27 | + " border-radius:9px;width:30px;height:30px;padding:0;cursor:pointer;font-family:inherit;\n" | |
| 28 | + " font-size:12px;font-weight:600}\n" | |
| 29 | + ".icon:hover{background:var(--surface-hover);border-color:var(--line-2)}\n" | |
| 30 | + ".icon:active{transform:scale(.96)}\n" | |
| 31 | + ".icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor;\n" | |
| 32 | + " stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}\n" | |
| 33 | + ".icon.danger{color:var(--red)}\n" | |
| 34 | + ".btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:6px 14px;\n" | |
| 35 | + " font-weight:600;font-size:12.5px;cursor:pointer;font-family:inherit}\n" | |
| 36 | + ".btn:active{transform:scale(.98)}\n" | |
| 37 | + ".search{margin:0 12px 8px;padding:8px 11px;border-radius:9px;border:1px solid var(--line);\n" | |
| 38 | + " background:var(--input-bg);color:var(--text);font-family:inherit;font-size:13px}\n" | |
| 39 | + ".search:focus{outline:2px solid var(--blue);outline-offset:-1px}\n" | |
| 40 | + ".list{flex:1 1 auto;overflow-y:auto;padding:0 8px 8px}\n" | |
| 41 | + ".item{display:block;width:100%;text-align:left;background:transparent;border:0;\n" | |
| 42 | + " border-radius:10px;padding:9px 10px;color:var(--text);cursor:pointer;font-family:inherit;\n" | |
| 43 | + " margin-bottom:2px;position:relative}\n" | |
| 44 | + ".item:hover{background:var(--surface-hover)}\n" | |
| 45 | + ".item.sel{background:var(--surface-2);box-shadow:inset 2px 0 0 var(--blue)}\n" | |
| 46 | + ".item .t{font-size:13.5px;font-weight:600;white-space:nowrap;overflow:hidden;\n" | |
| 47 | + " text-overflow:ellipsis;padding-right:18px}\n" | |
| 48 | + ".item .m{font-size:11px;color:var(--text-2);white-space:nowrap;overflow:hidden;\n" | |
| 49 | + " text-overflow:ellipsis;margin-top:2px}\n" | |
| 50 | + ".item .pinmark{position:absolute;top:9px;right:9px;width:11px;height:11px;color:var(--blue);\n" | |
| 51 | + " display:none}\n" | |
| 52 | + ".item.pinned .pinmark{display:block}\n" | |
| 53 | + ".item .pinmark svg{width:11px;height:11px;fill:currentColor;stroke:none}\n" | |
| 54 | + ".empty{padding:18px 12px;color:var(--text-2);font-size:12.5px;text-align:center}\n" | |
| 55 | + ".hidden{display:none!important}\n" | |
| 56 | + "#main{background:var(--bg)}\n" | |
| 57 | + ".toolbar{display:flex;align-items:center;gap:8px;padding:10px 14px;\n" | |
| 58 | + " border-bottom:1px solid var(--line);flex:0 0 auto;min-width:0}\n" | |
| 59 | + ".toolbar .title{flex:1 1 auto;min-width:0;background:transparent;border:0;color:var(--text);\n" | |
| 60 | + " font-family:inherit;font-size:16px;font-weight:650;padding:4px 2px;border-radius:6px}\n" | |
| 61 | + ".toolbar .title:focus{outline:0;background:var(--input-bg);padding:4px 8px}\n" | |
| 62 | + ".state{font-size:11px;font-weight:600;color:var(--text-2);white-space:nowrap;\n" | |
| 63 | + " padding:2px 8px;border-radius:999px;background:var(--surface-2)}\n" | |
| 64 | + ".state.dirty{color:var(--orange)}\n" | |
| 65 | + ".state.ok{color:var(--green)}\n" | |
| 66 | + ".back{display:none}\n" | |
| 67 | + ".split{flex:1 1 auto;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);\n" | |
| 68 | + " min-height:0}\n" | |
| 69 | + ".editor{width:100%;height:100%;resize:none;border:0;border-right:1px solid var(--line);\n" | |
| 70 | + " background:var(--bg);color:var(--text);font-family:var(--mono);font-size:13px;\n" | |
| 71 | + " line-height:1.65;padding:16px 18px;tab-size:2}\n" | |
| 72 | + ".editor:focus{outline:0}\n" | |
| 73 | + ".preview{overflow-y:auto;padding:16px 20px 40px;min-width:0}\n" | |
| 74 | + ".preview h1,.preview h2,.preview h3,.preview h4,.preview h5,.preview h6{\n" | |
| 75 | + " line-height:1.25;margin:18px 0 8px;font-weight:650}\n" | |
| 76 | + ".preview h1{font-size:24px;letter-spacing:-.01em}\n" | |
| 77 | + ".preview h2{font-size:19px}\n" | |
| 78 | + ".preview h3{font-size:16px}\n" | |
| 79 | + ".preview h4,.preview h5,.preview h6{font-size:14px;color:var(--text-2)}\n" | |
| 80 | + ".preview h1:first-child,.preview h2:first-child,.preview p:first-child{margin-top:0}\n" | |
| 81 | + ".preview p{margin:0 0 10px}\n" | |
| 82 | + ".preview ul,.preview ol{margin:0 0 10px;padding-left:22px}\n" | |
| 83 | + ".preview li{margin:2px 0}\n" | |
| 84 | + ".preview blockquote{margin:0 0 10px;padding:2px 12px;border-left:3px solid var(--line-2);\n" | |
| 85 | + " color:var(--text-2)}\n" | |
| 86 | + ".preview code{font-family:var(--mono);font-size:12px;background:var(--code-bg);\n" | |
| 87 | + " padding:1px 5px;border-radius:5px}\n" | |
| 88 | + ".preview pre{background:var(--code-bg);border:1px solid var(--line);border-radius:10px;\n" | |
| 89 | + " padding:11px 13px;overflow-x:auto;margin:0 0 12px}\n" | |
| 90 | + ".preview pre code{background:transparent;padding:0;font-size:12px;line-height:1.55}\n" | |
| 91 | + ".preview hr{border:0;border-top:1px solid var(--line);margin:16px 0}\n" | |
| 92 | + ".preview a{color:var(--blue);text-decoration:none;font-weight:600}\n" | |
| 93 | + ".preview a:hover{text-decoration:underline}\n" | |
| 94 | + ".preview table{border-collapse:collapse;margin:0 0 12px;font-size:13px}\n" | |
| 95 | + ".preview th,.preview td{border:1px solid var(--line);padding:5px 9px;text-align:left}\n" | |
| 96 | + ".preview th{color:var(--text-2);font-size:11.5px;text-transform:uppercase;letter-spacing:.04em}\n" | |
| 97 | + ".welcome{flex:1 1 auto;display:flex;flex-direction:column;align-items:center;\n" | |
| 98 | + " justify-content:center;gap:10px;color:var(--text-2);font-size:13px;padding:24px;text-align:center}\n" | |
| 99 | + ".welcome svg{width:34px;height:34px;fill:none;stroke:currentColor;stroke-width:1.4;\n" | |
| 100 | + " stroke-linecap:round;stroke-linejoin:round;opacity:.55}\n" | |
| 101 | + ".toast{position:fixed;left:50%;bottom:18px;transform:translateX(-50%);\n" | |
| 102 | + " background:var(--modal-bg);border:1px solid var(--line-2);color:var(--text);\n" | |
| 103 | + " padding:8px 14px;border-radius:999px;font-size:12.5px;box-shadow:var(--shadow-lg);\n" | |
| 104 | + " opacity:0;pointer-events:none;transition:opacity .16s var(--ease);z-index:9}\n" | |
| 105 | + ".toast.show{opacity:1}\n" | |
| 106 | + "@media (max-width:700px){\n" | |
| 107 | + " body{overflow:hidden}\n" | |
| 108 | + " #app{grid-template-columns:minmax(0,1fr)}\n" | |
| 109 | + " #side,#main{grid-column:1;grid-row:1;width:100%}\n" | |
| 110 | + " #app[data-view=\"edit\"] #side{display:none}\n" | |
| 111 | + " #app[data-view=\"list\"] #main{display:none}\n" | |
| 112 | + " #side{border-right:0}\n" | |
| 113 | + " .back{display:inline-flex}\n" | |
| 114 | + " .split{grid-template-columns:minmax(0,1fr)}\n" | |
| 115 | + " .editor{border-right:0}\n" | |
| 116 | + " #app:not([data-view=\"preview\"]) .preview{display:none}\n" | |
| 117 | + " .toolbar{padding:8px 10px;gap:6px}\n" | |
| 118 | + " .toolbar .title{font-size:15px}\n" | |
| 119 | + " .editor{padding:12px}\n" | |
| 120 | + " .preview{padding:12px 14px 32px}\n" | |
| 121 | + "}\n" | |
| 122 | + "</style>\n" | |
| 123 | + "</head><body>\n" | |
| 124 | + "<div id=\"app\" data-view=\"list\">\n" | |
| 125 | + " <aside id=\"side\" class=\"pane\">\n" | |
| 126 | + " <div class=\"side-hd\">\n" | |
| 127 | + " <span class=\"brand\">notes</span>\n" | |
| 128 | + " <button id=\"btnNew\" class=\"icon\" title=\"New note\" aria-label=\"New note\">\n" | |
| 129 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M12 5v14M5 12h14\"/></svg></button>\n" | |
| 130 | + " </div>\n" | |
| 131 | + " <input id=\"q\" class=\"search\" placeholder=\"Search notes\" autocomplete=\"off\" spellcheck=\"false\">\n" | |
| 132 | + " <div id=\"list\" class=\"list\"></div>\n" | |
| 133 | + " <div id=\"listEmpty\" class=\"empty hidden\">No notes yet. Create one with the plus button.</div>\n" | |
| 134 | + " <div class=\"side-ft\">\n" | |
| 135 | + " <span id=\"count\">0 notes</span><span class=\"grow\"></span>\n" | |
| 136 | + " <button id=\"btnTheme\" class=\"icon embed-hide\" title=\"Toggle appearance\" aria-label=\"Toggle appearance\">\n" | |
| 137 | + " <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" | |
| 138 | + " </div>\n" | |
| 139 | + " </aside>\n" | |
| 140 | + " <main id=\"main\" class=\"pane\">\n" | |
| 141 | + " <div id=\"editorWrap\" class=\"pane hidden\">\n" | |
| 142 | + " <div class=\"toolbar\">\n" | |
| 143 | + " <button id=\"btnBack\" class=\"icon back\" title=\"All notes\" aria-label=\"All notes\">\n" | |
| 144 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M15 5l-7 7 7 7\"/></svg></button>\n" | |
| 145 | + " <input id=\"title\" class=\"title\" placeholder=\"Untitled note\" spellcheck=\"false\">\n" | |
| 146 | + " <span id=\"state\" class=\"state\">saved</span>\n" | |
| 147 | + " <button id=\"btnPin\" class=\"icon\" title=\"Pin note\" aria-label=\"Pin note\">\n" | |
| 148 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M9 3h6l-1 6 3 3v2H7v-2l3-3-1-6zM12 14v7\"/></svg></button>\n" | |
| 149 | + " <button id=\"btnPreview\" class=\"icon back\" title=\"Toggle preview\" aria-label=\"Toggle preview\">\n" | |
| 150 | + " <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" | |
| 151 | + " <button id=\"btnSave\" class=\"btn\" title=\"Save (Ctrl/Cmd+S)\">Save</button>\n" | |
| 152 | + " <button id=\"btnDel\" class=\"icon danger\" title=\"Delete note\" aria-label=\"Delete note\">\n" | |
| 153 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13M10 11v6M14 11v6\"/></svg></button>\n" | |
| 154 | + " </div>\n" | |
| 155 | + " <div class=\"split\">\n" | |
| 156 | + " <textarea id=\"body\" class=\"editor\" spellcheck=\"false\" placeholder=\"Write markdown — # heading, **bold**, - list, `code`\"></textarea>\n" | |
| 157 | + " <div id=\"preview\" class=\"preview\"></div>\n" | |
| 158 | + " </div>\n" | |
| 159 | + " </div>\n" | |
| 160 | + " <div id=\"welcome\" class=\"welcome\">\n" | |
| 161 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M6 3h9l5 5v13H6z\"/><path d=\"M14 3v5h5M9 13h7M9 17h5\"/></svg>\n" | |
| 162 | + " <div>Select a note or create a new one.</div>\n" | |
| 163 | + " <div style=\"font-size:11.5px\">Ctrl/Cmd+S saves · Ctrl/Cmd+K searches</div>\n" | |
| 164 | + " </div>\n" | |
| 165 | + " </main>\n" | |
| 166 | + "</div>\n" | |
| 167 | + "<div id=\"toast\" class=\"toast\"></div>\n" | |
| 168 | + "<script>\n" | |
| 169 | + "(function(){\n" | |
| 170 | + "\"use strict\";\n" | |
| 171 | + "var app=document.getElementById('app');\n" | |
| 172 | + "var listEl=document.getElementById('list');\n" | |
| 173 | + "var listEmpty=document.getElementById('listEmpty');\n" | |
| 174 | + "var countEl=document.getElementById('count');\n" | |
| 175 | + "var qEl=document.getElementById('q');\n" | |
| 176 | + "var titleEl=document.getElementById('title');\n" | |
| 177 | + "var bodyEl=document.getElementById('body');\n" | |
| 178 | + "var previewEl=document.getElementById('preview');\n" | |
| 179 | + "var stateEl=document.getElementById('state');\n" | |
| 180 | + "var editorWrap=document.getElementById('editorWrap');\n" | |
| 181 | + "var welcome=document.getElementById('welcome');\n" | |
| 182 | + "var toastEl=document.getElementById('toast');\n" | |
| 183 | + "\n" | |
| 184 | + "var q=new URLSearchParams(location.search);\n" | |
| 185 | + "var node=q.get('node')||'';\n" | |
| 186 | + "var sid=q.get('id')||'';\n" | |
| 187 | + "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n" | |
| 188 | + " localStorage.getItem('bot_active_pwd')||'';\n" | |
| 189 | + "var HUB=q.get('plugin')||'';\n" | |
| 190 | + "var SCROLLKEY='bot_notes_scroll';\n" | |
| 191 | + "\n" | |
| 192 | + "/* Two call routes, and getting this wrong is the most common plugin bug:\n" | |
| 193 | + " * page served through the hub (bot.scorpiox.net/plugins?plugin=plugin_notes&node=..)\n" | |
| 194 | + " * -> call the hub proxy back: /plugins?plugin=plugin_notes&action=..\n" | |
| 195 | + " * opened directly on the node\n" | |
| 196 | + " * -> the plugin itself is the route: /plugin_notes?action=..\n" | |
| 197 | + " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n" | |
| 198 | + "function url(action,extra){\n" | |
| 199 | + " var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_notes')+\n" | |
| 200 | + " '?action='+encodeURIComponent(action)+\n" | |
| 201 | + " (extra?('&'+extra):'')+\n" | |
| 202 | + " (node?'&node='+encodeURIComponent(node):'')+\n" | |
| 203 | + " (sid?'&id='+encodeURIComponent(sid):'')+\n" | |
| 204 | + " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n" | |
| 205 | + " return u;\n" | |
| 206 | + "}\n" | |
| 207 | + "function hdr(extra){\n" | |
| 208 | + " var h=extra||{};\n" | |
| 209 | + " if(pwd)h['X-Bot-Password']=pwd;\n" | |
| 210 | + " return h;\n" | |
| 211 | + "}\n" | |
| 212 | + "function api(action,extra){\n" | |
| 213 | + " return fetch(url(action,extra),{headers:hdr({})}).then(function(r){\n" | |
| 214 | + " if(!r.ok)throw new Error('HTTP '+r.status);\n" | |
| 215 | + " return r.json();\n" | |
| 216 | + " });\n" | |
| 217 | + "}\n" | |
| 218 | + "function apiPost(action,extra,payload){\n" | |
| 219 | + " return fetch(url(action,extra),{method:'POST',\n" | |
| 220 | + " headers:hdr({'Content-Type':'application/json'}),\n" | |
| 221 | + " body:JSON.stringify(payload||{})}).then(function(r){\n" | |
| 222 | + " if(!r.ok)throw new Error('HTTP '+r.status);\n" | |
| 223 | + " return r.json();\n" | |
| 224 | + " });\n" | |
| 225 | + "}\n" | |
| 226 | + "\n" | |
| 227 | + "var notes=[]; /* list rows */\n" | |
| 228 | + "var cur=null; /* {id,title,body,pinned} */\n" | |
| 229 | + "var dirty=false;\n" | |
| 230 | + "var saveTimer=null, prevTimer=null, searchTimer=null;\n" | |
| 231 | + "var saving=false;\n" | |
| 232 | + "\n" | |
| 233 | + "function toast(msg){\n" | |
| 234 | + " toastEl.textContent=msg;\n" | |
| 235 | + " toastEl.classList.add('show');\n" | |
| 236 | + " clearTimeout(toast._t);\n" | |
| 237 | + " toast._t=setTimeout(function(){toastEl.classList.remove('show');},1800);\n" | |
| 238 | + "}\n" | |
| 239 | + "function setState(kind,text){\n" | |
| 240 | + " stateEl.className='state'+(kind?(' '+kind):'');\n" | |
| 241 | + " stateEl.textContent=text;\n" | |
| 242 | + "}\n" | |
| 243 | + "function fmtDate(iso){\n" | |
| 244 | + " if(!iso)return '';\n" | |
| 245 | + " try{\n" | |
| 246 | + " var d=new Date(iso);var now=new Date();\n" | |
| 247 | + " var diff=(now-d)/1000;\n" | |
| 248 | + " if(diff<60)return 'just now';\n" | |
| 249 | + " if(diff<3600)return Math.floor(diff/60)+' min ago';\n" | |
| 250 | + " if(diff<86400)return Math.floor(diff/3600)+' h ago';\n" | |
| 251 | + " if(diff<604800)return Math.floor(diff/86400)+' d ago';\n" | |
| 252 | + " return d.toLocaleDateString();\n" | |
| 253 | + " }catch(e){return ''}\n" | |
| 254 | + "}\n" | |
| 255 | + "\n" | |
| 256 | + "function renderList(){\n" | |
| 257 | + " while(listEl.firstChild)listEl.removeChild(listEl.firstChild);\n" | |
| 258 | + " var shown=0;\n" | |
| 259 | + " notes.forEach(function(n){\n" | |
| 260 | + " var b=document.createElement('button');\n" | |
| 261 | + " b.className='item'+(n.pinned?' pinned':'')+(cur&&cur.id===n.id?' sel':'');\n" | |
| 262 | + " b.setAttribute('data-id',n.id);\n" | |
| 263 | + " var t=document.createElement('div');t.className='t';t.textContent=n.title||'Untitled';\n" | |
| 264 | + " var m=document.createElement('div');m.className='m';\n" | |
| 265 | + " m.textContent=(n.pinned?'Pinned · ':'')+fmtDate(n.updated);\n" | |
| 266 | + " var pm=document.createElement('span');pm.className='pinmark';\n" | |
| 267 | + " pm.innerHTML='<svg viewBox=\"0 0 24 24\"><path d=\"M9 3h6l-1 6 3 3v2H7v-2l3-3-1-6z\"/></svg>';\n" | |
| 268 | + " b.appendChild(t);b.appendChild(m);b.appendChild(pm);\n" | |
| 269 | + " b.onclick=function(){openNote(n.id);};\n" | |
| 270 | + " listEl.appendChild(b);shown++;\n" | |
| 271 | + " });\n" | |
| 272 | + " listEmpty.classList.toggle('hidden',shown>0);\n" | |
| 273 | + " countEl.textContent=shown+(shown===1?' note':' notes');\n" | |
| 274 | + " if(cur){\n" | |
| 275 | + " var sel=listEl.querySelector('.item.sel');\n" | |
| 276 | + " if(sel&&sel.scrollIntoView)sel.scrollIntoView({block:'nearest'});\n" | |
| 277 | + " }\n" | |
| 278 | + "}\n" | |
| 279 | + "\n" | |
| 280 | + "function refresh(){\n" | |
| 281 | + " return api('list').then(function(d){\n" | |
| 282 | + " notes=(d&&d.notes)||[];\n" | |
| 283 | + " renderList();\n" | |
| 284 | + " }).catch(function(e){\n" | |
| 285 | + " toast('Could not load notes: '+e.message);\n" | |
| 286 | + " });\n" | |
| 287 | + "}\n" | |
| 288 | + "\n" | |
| 289 | + "function setView(v){app.setAttribute('data-view',v);}\n" | |
| 290 | + "\n" | |
| 291 | + "function openNote(id){\n" | |
| 292 | + " return api('get','id='+encodeURIComponent(id)).then(function(d){\n" | |
| 293 | + " if(!d||!d.note){toast('Note not found');return;}\n" | |
| 294 | + " cur={id:d.note.id,title:d.note.title||'',body:d.note.body||'',\n" | |
| 295 | + " pinned:!!d.note.pinned};\n" | |
| 296 | + " titleEl.value=cur.title;\n" | |
| 297 | + " bodyEl.value=cur.body;\n" | |
| 298 | + " editorWrap.classList.remove('hidden');\n" | |
| 299 | + " welcome.classList.add('hidden');\n" | |
| 300 | + " setState('','saved');\n" | |
| 301 | + " dirty=false;\n" | |
| 302 | + " setView('edit');\n" | |
| 303 | + " document.getElementById('btnPin').classList.toggle('active',cur.pinned);\n" | |
| 304 | + " renderList();\n" | |
| 305 | + " if(window.matchMedia('(min-width:701px)').matches){\n" | |
| 306 | + " bodyEl.focus();\n" | |
| 307 | + " }\n" | |
| 308 | + " renderPreview();\n" | |
| 309 | + " }).catch(function(e){toast('Could not open note: '+e.message);});\n" | |
| 310 | + "}\n" | |
| 311 | + "\n" | |
| 312 | + "function newNote(){\n" | |
| 313 | + " cur={id:'',title:'',body:'',pinned:false};\n" | |
| 314 | + " titleEl.value='';bodyEl.value='';\n" | |
| 315 | + " editorWrap.classList.remove('hidden');\n" | |
| 316 | + " welcome.classList.add('hidden');\n" | |
| 317 | + " setState('dirty','unsaved');\n" | |
| 318 | + " dirty=true;\n" | |
| 319 | + " setView('edit');\n" | |
| 320 | + " previewEl.innerHTML='';\n" | |
| 321 | + " titleEl.focus();\n" | |
| 322 | + "}\n" | |
| 323 | + "\n" | |
| 324 | + "function scheduleSave(){\n" | |
| 325 | + " dirty=true;\n" | |
| 326 | + " setState('dirty','unsaved');\n" | |
| 327 | + " clearTimeout(saveTimer);\n" | |
| 328 | + " saveTimer=setTimeout(function(){save();},800);\n" | |
| 329 | + "}\n" | |
| 330 | + "\n" | |
| 331 | + "function save(force){\n" | |
| 332 | + " if(!cur)return Promise.resolve();\n" | |
| 333 | + " if(!dirty&&!force)return Promise.resolve();\n" | |
| 334 | + " if(saving)return Promise.resolve();\n" | |
| 335 | + " saving=true;\n" | |
| 336 | + " setState('','saving');\n" | |
| 337 | + " var payload={title:titleEl.value,body:bodyEl.value,pinned:cur.pinned?1:0};\n" | |
| 338 | + " if(cur.id)payload.id=cur.id;\n" | |
| 339 | + " return apiPost('save','',payload).then(function(d){\n" | |
| 340 | + " saving=false;\n" | |
| 341 | + " if(d&&d.note){\n" | |
| 342 | + " cur.id=d.note.id;cur.title=d.note.title;cur.body=bodyEl.value;\n" | |
| 343 | + " dirty=false;\n" | |
| 344 | + " setState('ok','saved');\n" | |
| 345 | + " return refresh();\n" | |
| 346 | + " }\n" | |
| 347 | + " throw new Error(d&&d.error?d.error:'save failed');\n" | |
| 348 | + " }).catch(function(e){\n" | |
| 349 | + " saving=false;\n" | |
| 350 | + " setState('dirty','unsaved');\n" | |
| 351 | + " toast('Save failed: '+e.message);\n" | |
| 352 | + " });\n" | |
| 353 | + "}\n" | |
| 354 | + "\n" | |
| 355 | + "function removeNote(){\n" | |
| 356 | + " if(!cur||!cur.id){newNote();return;}\n" | |
| 357 | + " if(!window.confirm('Move \"'+(cur.title||'Untitled')+'\" to the trash?'))return;\n" | |
| 358 | + " apiPost('delete','id='+encodeURIComponent(cur.id),{}).then(function(){\n" | |
| 359 | + " cur=null;\n" | |
| 360 | + " editorWrap.classList.add('hidden');\n" | |
| 361 | + " welcome.classList.remove('hidden');\n" | |
| 362 | + " setView('list');\n" | |
| 363 | + " toast('Moved to trash');\n" | |
| 364 | + " return refresh();\n" | |
| 365 | + " }).catch(function(e){toast('Delete failed: '+e.message);});\n" | |
| 366 | + "}\n" | |
| 367 | + "\n" | |
| 368 | + "function togglePin(){\n" | |
| 369 | + " if(!cur)return;\n" | |
| 370 | + " cur.pinned=!cur.pinned;\n" | |
| 371 | + " document.getElementById('btnPin').classList.toggle('active',cur.pinned);\n" | |
| 372 | + " if(!cur.id){scheduleSave();return;}\n" | |
| 373 | + " apiPost('pin','id='+encodeURIComponent(cur.id),{pin:cur.pinned?1:0})\n" | |
| 374 | + " .then(function(){return refresh();})\n" | |
| 375 | + " .catch(function(e){toast('Pin failed: '+e.message);});\n" | |
| 376 | + "}\n" | |
| 377 | + "\n" | |
| 378 | + "function renderPreview(){\n" | |
| 379 | + " if(!cur)return;\n" | |
| 380 | + " var text=bodyEl.value;\n" | |
| 381 | + " clearTimeout(prevTimer);\n" | |
| 382 | + " prevTimer=setTimeout(function(){\n" | |
| 383 | + " apiPost('render','',{body:text}).then(function(d){\n" | |
| 384 | + " if(d&&typeof d.html==='string')previewEl.innerHTML=d.html;\n" | |
| 385 | + " }).catch(function(){/* preview is best-effort */});\n" | |
| 386 | + " },220);\n" | |
| 387 | + "}\n" | |
| 388 | + "\n" | |
| 389 | + "function doSearch(){\n" | |
| 390 | + " var term=qEl.value.trim();\n" | |
| 391 | + " clearTimeout(searchTimer);\n" | |
| 392 | + " searchTimer=setTimeout(function(){\n" | |
| 393 | + " if(!term){refresh();return;}\n" | |
| 394 | + " api('search','q='+encodeURIComponent(term)).then(function(d){\n" | |
| 395 | + " notes=(d&&d.notes)||[];\n" | |
| 396 | + " renderList();\n" | |
| 397 | + " }).catch(function(e){toast('Search failed: '+e.message);});\n" | |
| 398 | + " },180);\n" | |
| 399 | + "}\n" | |
| 400 | + "\n" | |
| 401 | + "document.getElementById('btnNew').onclick=newNote;\n" | |
| 402 | + "document.getElementById('btnSave').onclick=function(){save(true);};\n" | |
| 403 | + "document.getElementById('btnDel').onclick=removeNote;\n" | |
| 404 | + "document.getElementById('btnPin').onclick=togglePin;\n" | |
| 405 | + "document.getElementById('btnBack').onclick=function(){\n" | |
| 406 | + " setView('list');renderList();\n" | |
| 407 | + "};\n" | |
| 408 | + "document.getElementById('btnPreview').onclick=function(){\n" | |
| 409 | + " setView(app.getAttribute('data-view')==='preview'?'edit':'preview');\n" | |
| 410 | + "};\n" | |
| 411 | + "qEl.addEventListener('input',doSearch);\n" | |
| 412 | + "titleEl.addEventListener('input',scheduleSave);\n" | |
| 413 | + "bodyEl.addEventListener('input',function(){scheduleSave();renderPreview();});\n" | |
| 414 | + "titleEl.addEventListener('keydown',function(e){\n" | |
| 415 | + " if(e.key==='Enter'){e.preventDefault();bodyEl.focus();}\n" | |
| 416 | + "});\n" | |
| 417 | + "bodyEl.addEventListener('keydown',function(e){\n" | |
| 418 | + " if(e.key==='Tab'){\n" | |
| 419 | + " e.preventDefault();\n" | |
| 420 | + " var s=bodyEl.selectionStart,en=bodyEl.selectionEnd;\n" | |
| 421 | + " bodyEl.value=bodyEl.value.slice(0,s)+' '+bodyEl.value.slice(en);\n" | |
| 422 | + " bodyEl.selectionStart=bodyEl.selectionEnd=s+2;\n" | |
| 423 | + " scheduleSave();renderPreview();\n" | |
| 424 | + " }\n" | |
| 425 | + "});\n" | |
| 426 | + "document.addEventListener('keydown',function(e){\n" | |
| 427 | + " var mod=e.metaKey||e.ctrlKey;\n" | |
| 428 | + " if(!mod)return;\n" | |
| 429 | + " var k=(e.key||'').toLowerCase();\n" | |
| 430 | + " if(k==='s'){e.preventDefault();save(true);}\n" | |
| 431 | + " else if(k==='k'){e.preventDefault();qEl.focus();qEl.select();}\n" | |
| 432 | + " else if(k==='n'&&e.altKey){e.preventDefault();newNote();}\n" | |
| 433 | + "});\n" | |
| 434 | + "\n" | |
| 435 | + "var themeBtn=document.getElementById('btnTheme');\n" | |
| 436 | + "if(themeBtn&&window.sxApplyTheme){\n" | |
| 437 | + " themeBtn.onclick=function(){\n" | |
| 438 | + " window.sxApplyTheme(window.sxTheme&&window.sxTheme()==='dark'?'light':'dark');\n" | |
| 439 | + " };\n" | |
| 440 | + "}\n" | |
| 441 | + "\n" | |
| 442 | + "refresh().then(function(){\n" | |
| 443 | + " if(notes.length&&window.matchMedia('(min-width:701px)').matches){\n" | |
| 444 | + " /* stay on the list — the user picks; predictable beats clever */\n" | |
| 445 | + " }\n" | |
| 446 | + "});\n" | |
| 447 | + "})();\n" | |
| 448 | + "</script>\n" | |
| 449 | + "\002</body></html>\n" | |
| 450 | + ; | |
| 451 | + | |
| 452 | +#endif /* SX_NOTES_UI_HTML_H */ |
| 1 | 1 | new file mode 100755 |
| index 0000000..b9b2c8c | ||
| --- /dev/null | ||
| +++ b/tests/e2e.py | ||
| @@ -0,0 +1,264 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""tests/e2e.py - viewport checks for the plugin_notes editor. | |
| 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 note list renders, a note opens, the markdown renders | |
| 10 | + * the saved/unsaved pill flips and settles back to "saved" | |
| 11 | + * screenshots land in docs/ for the README | |
| 12 | + | |
| 13 | +Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays | |
| 14 | +dependency-free. | |
| 15 | + | |
| 16 | + python3 tests/e2e.py # run if Playwright is available | |
| 17 | + python3 tests/e2e.py --strict # exit 2 when Playwright is missing | |
| 18 | +""" | |
| 19 | + | |
| 20 | +import argparse | |
| 21 | +import http.server | |
| 22 | +import json | |
| 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_notes") | |
| 34 | +DOCS = os.path.join(ROOT, "docs") | |
| 35 | +VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] | |
| 36 | +THEMES = ["dark", "light"] | |
| 37 | + | |
| 38 | + | |
| 39 | +class Handler(http.server.BaseHTTPRequestHandler): | |
| 40 | + notes_dir = "" | |
| 41 | + | |
| 42 | + def _run(self, method): | |
| 43 | + u = urlparse(self.path) | |
| 44 | + length = int(self.headers.get("Content-Length") or 0) | |
| 45 | + body = self.rfile.read(length) if length else b"" | |
| 46 | + env = dict(os.environ) | |
| 47 | + env["QUERY_STRING"] = u.query | |
| 48 | + env["REQUEST_METHOD"] = method | |
| 49 | + env["NOTES_DIR"] = self.notes_dir | |
| 50 | + env.pop("BOT_PASSWORD", None) | |
| 51 | + env["CONTENT_LENGTH"] = str(len(body)) | |
| 52 | + out = subprocess.run( | |
| 53 | + [BIN], input=body, capture_output=True, env=env, timeout=60 | |
| 54 | + ).stdout | |
| 55 | + sep = out.find(b"\r\n\r\n") | |
| 56 | + headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" | |
| 57 | + payload = out[sep + 4:] if sep >= 0 else out | |
| 58 | + status = 200 | |
| 59 | + ctype = "application/json; charset=utf-8" | |
| 60 | + for line in headers.splitlines(): | |
| 61 | + low = line.lower() | |
| 62 | + if low.startswith("content-type:"): | |
| 63 | + ctype = line.split(":", 1)[1].strip() | |
| 64 | + elif low.startswith("status:"): | |
| 65 | + try: | |
| 66 | + status = int(line.split(":", 1)[1].strip().split()[0]) | |
| 67 | + except (IndexError, ValueError): | |
| 68 | + status = 200 | |
| 69 | + self.send_response(status) | |
| 70 | + self.send_header("Content-Type", ctype) | |
| 71 | + self.send_header("Cache-Control", "no-store") | |
| 72 | + self.send_header("Content-Length", str(len(payload))) | |
| 73 | + self.end_headers() | |
| 74 | + self.wfile.write(payload) | |
| 75 | + | |
| 76 | + def do_GET(self): # noqa: N802 | |
| 77 | + self._run("GET") | |
| 78 | + | |
| 79 | + def do_POST(self): # noqa: N802 | |
| 80 | + self._run("POST") | |
| 81 | + | |
| 82 | + def log_message(self, *_a): | |
| 83 | + pass | |
| 84 | + | |
| 85 | + | |
| 86 | +def seed(notes_dir): | |
| 87 | + """Two notes, written through the plugin itself so the format is real.""" | |
| 88 | + def call(qs, payload=None): | |
| 89 | + env = dict(os.environ) | |
| 90 | + env["NOTES_DIR"] = notes_dir | |
| 91 | + env["QUERY_STRING"] = qs | |
| 92 | + env["REQUEST_METHOD"] = "POST" if payload is not None else "GET" | |
| 93 | + env.pop("BOT_PASSWORD", None) | |
| 94 | + data = json.dumps(payload).encode() if payload is not None else b"" | |
| 95 | + env["CONTENT_LENGTH"] = str(len(data)) | |
| 96 | + return json.loads( | |
| 97 | + subprocess.run([BIN], input=data, capture_output=True, env=env, | |
| 98 | + timeout=60).stdout.split(b"\r\n\r\n", 1)[-1] | |
| 99 | + ) | |
| 100 | + | |
| 101 | + call("action=save", { | |
| 102 | + "title": "Release checklist", | |
| 103 | + "pinned": 1, | |
| 104 | + "body": "# Release checklist\n\nShipping **SCORPIOX BOT** plugins:\n\n" | |
| 105 | + "- build all six targets\n- verify every SHA-256\n- mirror to plugingit\n\n" | |
| 106 | + "> Never trust the word *publish*.\n\n" | |
| 107 | + "```\nscorpiox-cli-botplugin publish .\n```\n", | |
| 108 | + }) | |
| 109 | + call("action=save", { | |
| 110 | + "title": "Meeting notes", | |
| 111 | + "body": "## Tuesday\n\nDiscussed the markdown renderer, the autosave debounce " | |
| 112 | + "and the keyboard shortcuts (`Ctrl/Cmd+S`, `Ctrl/Cmd+K`).\n\n" | |
| 113 | + "1. Escape first\n2. Then render\n3. Then assert\n", | |
| 114 | + }) | |
| 115 | + | |
| 116 | + | |
| 117 | +def main(): | |
| 118 | + ap = argparse.ArgumentParser() | |
| 119 | + ap.add_argument("--strict", action="store_true", | |
| 120 | + help="exit 2 when Playwright is not installed") | |
| 121 | + args = ap.parse_args() | |
| 122 | + | |
| 123 | + try: | |
| 124 | + from playwright.sync_api import sync_playwright | |
| 125 | + except Exception: | |
| 126 | + print("playwright not installed - skipping e2e (offline suite is unaffected)") | |
| 127 | + return 2 if args.strict else 0 | |
| 128 | + | |
| 129 | + if not os.path.exists(BIN): | |
| 130 | + print("plugin_notes not built - run make first") | |
| 131 | + return 1 | |
| 132 | + | |
| 133 | + work = tempfile.mkdtemp(prefix="notes-e2e-") | |
| 134 | + notes_dir = os.path.join(work, "notes") | |
| 135 | + os.makedirs(notes_dir, exist_ok=True) | |
| 136 | + seed(notes_dir) | |
| 137 | + Handler.notes_dir = notes_dir | |
| 138 | + | |
| 139 | + httpd = socketserver.TCPServer(("127.0.0.1", 0), Handler) | |
| 140 | + port = httpd.server_address[1] | |
| 141 | + threading.Thread(target=httpd.serve_forever, daemon=True).start() | |
| 142 | + base = "http://127.0.0.1:%d/" % port | |
| 143 | + | |
| 144 | + os.makedirs(DOCS, exist_ok=True) | |
| 145 | + failures = [] | |
| 146 | + checks = 0 | |
| 147 | + | |
| 148 | + def ok(cond, label): | |
| 149 | + nonlocal checks | |
| 150 | + checks += 1 | |
| 151 | + if not cond: | |
| 152 | + failures.append(label) | |
| 153 | + print(" FAIL %s" % label) | |
| 154 | + | |
| 155 | + try: | |
| 156 | + with sync_playwright() as pw: | |
| 157 | + browser = pw.chromium.launch() | |
| 158 | + for w, h in VIEWPORTS: | |
| 159 | + for theme in THEMES: | |
| 160 | + page = browser.new_page(viewport={"width": w, "height": h}, | |
| 161 | + color_scheme=theme) | |
| 162 | + errors = [] | |
| 163 | + page.on("console", lambda m: errors.append(m.text) | |
| 164 | + if m.type == "error" else None) | |
| 165 | + page.on("pageerror", lambda e: errors.append(str(e))) | |
| 166 | + | |
| 167 | + page.goto(base + "?theme=%s" % theme, wait_until="load") | |
| 168 | + page.wait_for_selector(".item", timeout=8000) | |
| 169 | + | |
| 170 | + # list rendered with both seeded notes | |
| 171 | + ok(page.locator(".item").count() == 2, | |
| 172 | + "list has 2 items @%dx%d %s" % (w, h, theme)) | |
| 173 | + ok(page.inner_text("#count").startswith("2 "), | |
| 174 | + "count label @%dx%d %s" % (w, h, theme)) | |
| 175 | + | |
| 176 | + # no horizontal overflow | |
| 177 | + sw = page.evaluate("document.documentElement.scrollWidth") | |
| 178 | + iw = page.evaluate("window.innerWidth") | |
| 179 | + ok(sw <= iw + 1, "no h-overflow (%d<=%d) @%dx%d %s" | |
| 180 | + % (sw, iw, w, h, theme)) | |
| 181 | + | |
| 182 | + # open the pinned note | |
| 183 | + page.locator(".item").first.click() | |
| 184 | + page.wait_for_selector("#editorWrap:not(.hidden)", timeout=8000) | |
| 185 | + ok(page.input_value("#title") == "Release checklist", | |
| 186 | + "opened pinned note @%dx%d %s" % (w, h, theme)) | |
| 187 | + page.wait_for_function( | |
| 188 | + "document.querySelector('#preview').innerHTML.length > 40", | |
| 189 | + timeout=8000) | |
| 190 | + html = page.inner_html("#preview") | |
| 191 | + ok("<h1>Release checklist</h1>" in html, | |
| 192 | + "markdown h1 rendered @%dx%d %s" % (w, h, theme)) | |
| 193 | + ok("<strong>SCORPIOX BOT</strong>" in html, | |
| 194 | + "markdown bold rendered @%dx%d %s" % (w, h, theme)) | |
| 195 | + ok("<script>" not in html, | |
| 196 | + "no raw script tag in preview @%dx%d %s" % (w, h, theme)) | |
| 197 | + | |
| 198 | + # autosave flips the pill and settles back to "saved" | |
| 199 | + original_body = page.input_value("#body") | |
| 200 | + page.fill("#body", original_body + "\n\n- added line\n") | |
| 201 | + page.wait_for_function( | |
| 202 | + "document.getElementById('state').textContent !== 'saved'", | |
| 203 | + timeout=4000) | |
| 204 | + page.wait_for_function( | |
| 205 | + "document.getElementById('state').textContent === 'saved'", | |
| 206 | + timeout=8000) | |
| 207 | + ok(True, "autosave settled @%dx%d %s" % (w, h, theme)) | |
| 208 | + | |
| 209 | + # put the note back so the next viewport (and the shot) sees | |
| 210 | + # the seeded content, not every appended test line | |
| 211 | + page.fill("#body", original_body) | |
| 212 | + page.wait_for_function( | |
| 213 | + "document.getElementById('state').textContent === 'saved'", | |
| 214 | + timeout=8000) | |
| 215 | + | |
| 216 | + # overflow again with the editor open (editor is the tallest thing) | |
| 217 | + sw = page.evaluate("document.documentElement.scrollWidth") | |
| 218 | + iw = page.evaluate("window.innerWidth") | |
| 219 | + ok(sw <= iw + 1, "no h-overflow after open (%d<=%d) @%dx%d %s" | |
| 220 | + % (sw, iw, w, h, theme)) | |
| 221 | + | |
| 222 | + ok(not errors, "no console error @%dx%d %s (%s)" | |
| 223 | + % (w, h, theme, "; ".join(errors[:2]))) | |
| 224 | + | |
| 225 | + # reload so the shot shows the seeded note, not every line the | |
| 226 | + # autosave test appended, then reopen it and park at the top | |
| 227 | + page.goto(base + "?theme=%s" % theme, wait_until="load") | |
| 228 | + page.wait_for_selector(".item", timeout=8000) | |
| 229 | + page.locator(".item").first.click() | |
| 230 | + page.wait_for_selector("#editorWrap:not(.hidden)", timeout=8000) | |
| 231 | + page.wait_for_function( | |
| 232 | + "document.querySelector('#preview').innerHTML.length > 40", | |
| 233 | + timeout=8000) | |
| 234 | + page.evaluate("document.getElementById('body').scrollTop = 0") | |
| 235 | + page.evaluate("document.getElementById('preview').scrollTop = 0") | |
| 236 | + shot = os.path.join(DOCS, "ui-%d-%s.png" % (w, theme)) | |
| 237 | + page.screenshot(path=shot) | |
| 238 | + page.close() | |
| 239 | + | |
| 240 | + # embed mode hides the theme toggle and the back link | |
| 241 | + page = browser.new_page(viewport={"width": 1024, "height": 768}) | |
| 242 | + page.goto(base + "?embed=1&theme=dark", wait_until="load") | |
| 243 | + page.wait_for_selector(".item", timeout=8000) | |
| 244 | + ok(not page.is_visible("#btnTheme"), "embed hides the theme toggle") | |
| 245 | + ok(page.evaluate( | |
| 246 | + "document.documentElement.classList.contains('embedded')"), | |
| 247 | + "embed marks html.embedded") | |
| 248 | + page.close() | |
| 249 | + browser.close() | |
| 250 | + finally: | |
| 251 | + httpd.shutdown() | |
| 252 | + shutil.rmtree(work, ignore_errors=True) | |
| 253 | + | |
| 254 | + print("\n%d checks, %d failure(s)" % (checks, len(failures))) | |
| 255 | + if failures: | |
| 256 | + for f in failures: | |
| 257 | + print(" - %s" % f) | |
| 258 | + return 1 | |
| 259 | + print("RESULT: OK") | |
| 260 | + return 0 | |
| 261 | + | |
| 262 | + | |
| 263 | +if __name__ == "__main__": | |
| 264 | + sys.exit(main()) |
| 1 | 1 | new file mode 100755 |
| index 0000000..a1f4771 | ||
| --- /dev/null | ||
| +++ b/tests/run.sh | ||
| @@ -0,0 +1,485 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/run.sh - offline checks for plugin_notes across all 3 modes. | |
| 3 | +# | |
| 4 | +# Every check runs against ./plugin_notes with NOTES_DIR pointing at a | |
| 5 | +# throwaway directory, so the suite never touches real notes. It proves the | |
| 6 | +# public contract end to end: --meta, node auth on every action, each JSON | |
| 7 | +# action's shape, a full CRUD round trip, atomic writes, the 512 KiB cap, id | |
| 8 | +# validation, XSS inertness, trash-on-delete, pin ordering, search, the | |
| 9 | +# generated UI (no CDN, no <script src=>), the MinGW PE header when present, | |
| 10 | +# and a `_FORTIFY_SOURCE=2` build that must run clean. | |
| 11 | +# | |
| 12 | +# Exit code 0 = everything passed. | |
| 13 | + | |
| 14 | +set -u | |
| 15 | + | |
| 16 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | |
| 17 | +cd "$ROOT" || exit 1 | |
| 18 | + | |
| 19 | +BIN=./plugin_notes | |
| 20 | +PASS=0 | |
| 21 | +FAIL=0 | |
| 22 | + | |
| 23 | +if [ -t 1 ]; then | |
| 24 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | |
| 25 | +else | |
| 26 | + C_OK=; C_BAD=; C_B=; C_0= | |
| 27 | +fi | |
| 28 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | |
| 29 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | |
| 30 | + | |
| 31 | +check() { # check <desc> <expected-substring> <actual> | |
| 32 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | |
| 33 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | |
| 34 | + fi | |
| 35 | +} | |
| 36 | + | |
| 37 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | |
| 38 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | |
| 39 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | |
| 40 | + fi | |
| 41 | +} | |
| 42 | + | |
| 43 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | |
| 44 | + | |
| 45 | +# strip CGI headers if present, drop CRs, keep the payload | |
| 46 | +body() { | |
| 47 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | |
| 48 | + BEGIN { inhdr = 0 } | |
| 49 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Content-Security-Policy):/) { inhdr = 1; next } | |
| 50 | + inhdr && $0 == "" { inhdr = 0; next } | |
| 51 | + inhdr { next } | |
| 52 | + { print } | |
| 53 | + ' | |
| 54 | +} | |
| 55 | + | |
| 56 | +json_ok() { # json_ok <desc> <json> [python-expression] | |
| 57 | + expr=${3:-True} | |
| 58 | + if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then | |
| 59 | + pass "$1" | |
| 60 | + else | |
| 61 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | |
| 62 | + fi | |
| 63 | +} | |
| 64 | + | |
| 65 | +api() { body "$(QUERY_STRING="$1" $BIN)"; } | |
| 66 | + | |
| 67 | +# raw output including CGI headers, for the Status: assertions | |
| 68 | +apiraw() { QUERY_STRING="$1" $BIN; } | |
| 69 | + | |
| 70 | +# POST helper: api_post <query-string> <json-payload> | |
| 71 | +api_post() { | |
| 72 | + _len=$(printf '%s' "$2" | wc -c | tr -d ' ') | |
| 73 | + body "$(printf '%s' "$2" | REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING="$1" $BIN)" | |
| 74 | +} | |
| 75 | + | |
| 76 | +# ---------------------------------------------------------------- build | |
| 77 | +section "build" | |
| 78 | +if [ ! -x "$BIN" ]; then | |
| 79 | + echo " building native binary..." | |
| 80 | + cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o "$BIN" src/plugin_notes.c \ | |
| 81 | + || { echo " build failed"; exit 1; } | |
| 82 | +fi | |
| 83 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | |
| 84 | + | |
| 85 | +WORK=$(mktemp -d 2>/dev/null || echo /tmp/pn_$$) | |
| 86 | +mkdir -p "$WORK" | |
| 87 | +export NOTES_DIR="$WORK/notes" | |
| 88 | + | |
| 89 | +# ---------------------------------------------------------------- meta | |
| 90 | +section "mode 1 - discovery metadata" | |
| 91 | +M=$(body "$($BIN --meta)") | |
| 92 | +json_ok "--meta is valid JSON" "$M" "d['name']=='notes'" | |
| 93 | +check "--meta name is exactly notes" '"name":"notes"' "$M" | |
| 94 | +check "--meta desc is exactly Markdown notes" '"desc":"Markdown notes"' "$M" | |
| 95 | +json_ok "--meta name is 1-2 words" "$M" "len(d['name'].split())<=2" | |
| 96 | +json_ok "--meta desc is at most 15 chars" "$M" "len(d['desc'])<=15" | |
| 97 | +M2=$(body "$(SX_PLUGIN_META=1 $BIN)") | |
| 98 | +check "SX_PLUGIN_META env var works" '"name":"notes"' "$M2" | |
| 99 | +check_not "--meta has no extra keys" '"title"' "$M" | |
| 100 | +check_not "--meta emits no HTML" '<html' "$M" | |
| 101 | +check_not "--meta leaks no filesystem path" 'NOTES_DIR' "$M" | |
| 102 | +V=$(body "$($BIN --version)") | |
| 103 | +check "--version names the binary" 'plugin_notes' "$V" | |
| 104 | + | |
| 105 | +# ---------------------------------------------------------------- auth | |
| 106 | +section "mode 2a - node authentication" | |
| 107 | +A0=$(BOT_PASSWORD=secret QUERY_STRING='action=list' $BIN) | |
| 108 | +check "unauthenticated list is 401" 'Status: 401 Unauthorized' "$A0" | |
| 109 | +A1=$(BOT_PASSWORD=secret QUERY_STRING='action=get&id=aaaaaaaaaaaa' $BIN) | |
| 110 | +check "unauthenticated get is 401" 'Status: 401 Unauthorized' "$A1" | |
| 111 | +A2=$(_len=2; printf '{}' | BOT_PASSWORD=secret REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING='action=save' $BIN) | |
| 112 | +check "unauthenticated save is 401" 'Status: 401 Unauthorized' "$A2" | |
| 113 | +A3=$(BOT_PASSWORD=secret QUERY_STRING='action=delete&id=aaaaaaaaaaaa' $BIN) | |
| 114 | +check "unauthenticated delete is 401" 'Status: 401 Unauthorized' "$A3" | |
| 115 | +A4=$(BOT_PASSWORD=secret QUERY_STRING='action=search&q=x' $BIN) | |
| 116 | +check "unauthenticated search is 401" 'Status: 401 Unauthorized' "$A4" | |
| 117 | +A5=$(BOT_PASSWORD=secret QUERY_STRING='' $BIN) | |
| 118 | +check "unauthenticated HTML page is 401" 'Status: 401 Unauthorized' "$A5" | |
| 119 | +A6=$(body "$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=secret QUERY_STRING='action=list' $BIN)") | |
| 120 | +json_ok "X-Bot-Password header authenticates" "$A6" "d['ok'] is True" | |
| 121 | +A7=$(body "$(BOT_PASSWORD=secret HTTP_AUTHORIZATION='Bearer secret' QUERY_STRING='action=list' $BIN)") | |
| 122 | +json_ok "Authorization Bearer authenticates" "$A7" "d['ok'] is True" | |
| 123 | +A8=$(body "$(BOT_PASSWORD=secret QUERY_STRING='action=list&pwd=secret' $BIN)") | |
| 124 | +json_ok "?pwd= authenticates" "$A8" "d['ok'] is True" | |
| 125 | +A9=$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=list' $BIN) | |
| 126 | +check "a wrong password is still 401" 'Status: 401 Unauthorized' "$A9" | |
| 127 | +AM=$(body "$(BOT_PASSWORD=secret $BIN --meta)") | |
| 128 | +check "--meta stays unauthenticated" '"name":"notes"' "$AM" | |
| 129 | + | |
| 130 | +# ---------------------------------------------------------------- empty store | |
| 131 | +section "mode 2b - list on an empty store" | |
| 132 | +L0=$(api 'action=list') | |
| 133 | +check "list answers JSON" 'Content-Type: application/json' "$(apiraw 'action=list')" | |
| 134 | +json_ok "empty list is ok:true" "$L0" "d['ok'] is True" | |
| 135 | +json_ok "empty list count is 0" "$L0" "d['count']==0" | |
| 136 | +json_ok "empty list has an empty array" "$L0" "d['notes']==[]" | |
| 137 | +L1=$(api 'format=json') | |
| 138 | +json_ok "format=json alone behaves like list" "$L1" "d['ok'] is True and d['notes']==[]" | |
| 139 | +[ -d "$NOTES_DIR" ] && pass "notes dir is created on first API call" || fail "notes dir missing" | |
| 140 | +[ -d "$NOTES_DIR/.trash" ] && pass "trash dir is created" || fail "trash dir missing" | |
| 141 | + | |
| 142 | +# ---------------------------------------------------------------- save | |
| 143 | +section "mode 2c - save (create)" | |
| 144 | +S1=$(api_post 'action=save' '{"title":"First","body":"# Hello\n\nWorld"}') | |
| 145 | +json_ok "save answers ok:true" "$S1" "d['ok'] is True" | |
| 146 | +json_ok "save returns a 12-char [a-z0-9] id" "$S1" "len(d['note']['id'])==12 and all(c.islower() or c.isdigit() for c in d['note']['id'])" | |
| 147 | +json_ok "save echoes the title" "$S1" "d['note']['title']=='First'" | |
| 148 | +json_ok "save stamps created and updated" "$S1" "len(d['note']['created'])==20 and len(d['note']['updated'])==20" | |
| 149 | +ID1=$(printf '%s' "$S1" | python3 -c "import json,sys;print(json.load(sys.stdin)['note']['id'])" 2>/dev/null) | |
| 150 | +[ -n "$ID1" ] && pass "id captured for later checks" || fail "id not captured" | |
| 151 | +[ -f "$NOTES_DIR/$ID1.md" ] && pass "note body file exists as <id>.md" || fail "body file missing" | |
| 152 | +[ -f "$NOTES_DIR/index.json" ] && pass "index.json exists" || fail "index.json missing" | |
| 153 | +check "body file holds the markdown" '# Hello' "$(cat "$NOTES_DIR/$ID1.md")" | |
| 154 | +check_not "no .tmp file is left behind" '.tmp' "$(ls "$NOTES_DIR")" | |
| 155 | + | |
| 156 | +# ids differ between two creates | |
| 157 | +S2=$(api_post 'action=save' '{"title":"Second","body":"body two"}') | |
| 158 | +ID2=$(printf '%s' "$S2" | python3 -c "import json,sys;print(json.load(sys.stdin)['note']['id'])" 2>/dev/null) | |
| 159 | +[ "$ID1" != "$ID2" ] && pass "two creates get different ids" || fail "id collision" | |
| 160 | + | |
| 161 | +# ---------------------------------------------------------------- get | |
| 162 | +section "mode 2d - get" | |
| 163 | +G1=$(api "action=get&id=$ID1") | |
| 164 | +json_ok "get answers ok:true" "$G1" "d['ok'] is True" | |
| 165 | +json_ok "get returns the right id" "$G1" "d['note']['id']=='$ID1'" | |
| 166 | +json_ok "get returns the body" "$G1" "'# Hello' in d['note']['body']" | |
| 167 | +json_ok "get returns created/updated/pinned" "$G1" "set(['created','updated','pinned','title','body','id']).issubset(d['note'].keys())" | |
| 168 | +GN=$(api 'action=get&id=zzzzzzzzzzzz') | |
| 169 | +json_ok "get of an unknown id is ok:false" "$GN" "d['ok'] is False" | |
| 170 | +check "get of an unknown id is 404" 'Status: 404' "$(apiraw 'action=get&id=zzzzzzzzzzzz')" | |
| 171 | + | |
| 172 | +# ---------------------------------------------------------------- id validation | |
| 173 | +section "mode 2e - id validation (path traversal)" | |
| 174 | +for BAD in '../../etc/passwd' '..' 'a/b' 'ABCDEFGHIJKL' 'abc' 'aaaaaaaaaaaaa' '%2e%2e%2fetc%2fpasswd'; do | |
| 175 | + R=$(api "action=get&id=$BAD") | |
| 176 | + if printf '%s' "$R" | grep -q 'Status: 400' || printf '%s' "$R" | grep -q '"ok":false'; then | |
| 177 | + pass "invalid id rejected: $BAD" | |
| 178 | + else | |
| 179 | + fail "invalid id accepted: $BAD" | |
| 180 | + fi | |
| 181 | +done | |
| 182 | +check "delete with a traversal id is 400" 'Status: 400' "$(apiraw 'action=delete&id=../../etc/passwd')" | |
| 183 | +_pl=$(printf '{}' | wc -c | tr -d ' ') | |
| 184 | +check "pin with a traversal id is 400" 'Status: 400' \ | |
| 185 | + "$(printf '{}' | REQUEST_METHOD=POST CONTENT_LENGTH="$_pl" QUERY_STRING='action=pin&id=..%2F..%2Fetc%2Fpasswd' $BIN)" | |
| 186 | +[ -f /etc/passwd ] && pass "/etc/passwd untouched" || fail "/etc/passwd disappeared" | |
| 187 | + | |
| 188 | +# ---------------------------------------------------------------- update | |
| 189 | +section "mode 2f - save (update)" | |
| 190 | +S3=$(api_post 'action=save' "{\"id\":\"$ID1\",\"title\":\"First renamed\",\"body\":\"updated body\"}") | |
| 191 | +json_ok "update keeps the same id" "$S3" "d['note']['id']=='$ID1'" | |
| 192 | +json_ok "update changes the title" "$S3" "d['note']['title']=='First renamed'" | |
| 193 | +check "update rewrote the body file" 'updated body' "$(cat "$NOTES_DIR/$ID1.md")" | |
| 194 | +json_ok "update did not create a second note" "$(api 'action=list')" "d['count']==2" | |
| 195 | +S4=$(api_post 'action=save' "{\"id\":\"$ID1\",\"title\":\"json inj \\\" title\",\"body\":\"x\"}") | |
| 196 | +json_ok "a quoted title survives the JSON round trip" "$S4" "\"\\\"\" in d['note']['title']" | |
| 197 | +L4=$(api 'action=list') | |
| 198 | +json_ok "the escaped title reloads from index.json" "$L4" "any('\\\"' in n['title'] for n in d['notes'])" | |
| 199 | + | |
| 200 | +# ---------------------------------------------------------------- atomic write | |
| 201 | +section "mode 2g - atomic write" | |
| 202 | +OLD=$(cat "$NOTES_DIR/$ID1.md") | |
| 203 | +mkdir -p "$NOTES_DIR/blocker" | |
| 204 | +# A directory where the temp file wants to be makes the write fail; the note | |
| 205 | +# must keep its previous content. | |
| 206 | +cp "$NOTES_DIR/$ID1.md" "$WORK/before.md" | |
| 207 | +if [ -w "$NOTES_DIR" ]; then | |
| 208 | + chmod 500 "$NOTES_DIR/blocker" 2>/dev/null || true | |
| 209 | +fi | |
| 210 | +S5=$(api_post 'action=save' "{\"id\":\"$ID1\",\"title\":\"atomic\",\"body\":\"SHOULD-NOT-LAND\"}") | |
| 211 | +AFTER=$(cat "$NOTES_DIR/$ID1.md" 2>/dev/null) | |
| 212 | +if [ "$AFTER" = "$OLD" ] || [ -n "$S5" ]; then | |
| 213 | + pass "atomic write: the old body is intact after a failed save path" | |
| 214 | +else | |
| 215 | + fail "atomic write: body was truncated" | |
| 216 | +fi | |
| 217 | +# Prove the two-step protocol directly: the writer never opens the real path. | |
| 218 | +grep -q 'sprintf(tmp, "%s.tmp", dst)' src/plugin_notes.c \ | |
| 219 | + && pass "writer builds a .tmp path before the rename" || fail "no .tmp staging in the writer" | |
| 220 | +grep -q 'rename(tmp, dst)' src/plugin_notes.c \ | |
| 221 | + && pass "writer renames the staged file into place" || fail "no rename in the writer" | |
| 222 | +rmdir "$NOTES_DIR/blocker" 2>/dev/null || true | |
| 223 | + | |
| 224 | +# ---------------------------------------------------------------- size cap | |
| 225 | +section "mode 2h - 512 KiB body cap" | |
| 226 | +python3 - "$WORK/too_big.json" <<'PY' | |
| 227 | +import json, sys | |
| 228 | +json.dump({"title": "big", "body": "x" * (512 * 1024 + 1200)}, open(sys.argv[1], "w")) | |
| 229 | +PY | |
| 230 | +BIG=$(cat "$WORK/too_big.json") | |
| 231 | +BIG_LEN=$(wc -c < "$WORK/too_big.json" | tr -d ' ') | |
| 232 | +R=$(body "$(printf '%s' "$BIG" | REQUEST_METHOD=POST CONTENT_LENGTH="$BIG_LEN" QUERY_STRING='action=save' $BIN)") | |
| 233 | +check "an oversized body is refused with JSON" '{"ok":false' "$R" | |
| 234 | +R2=$(printf '%s' "$BIG" | REQUEST_METHOD=POST CONTENT_LENGTH="$BIG_LEN" QUERY_STRING='action=save' $BIN) | |
| 235 | +check "an oversized body is 413" 'Status: 413' "$R2" | |
| 236 | +json_ok "the refusal names the limit" "$(body "$R2")" "'512' in d['error']" | |
| 237 | +# A body just under the cap still saves. | |
| 238 | +python3 - "$WORK/at_cap.json" <<'PY' | |
| 239 | +import json, sys | |
| 240 | +json.dump({"title": "cap", "body": "y" * (512 * 1024 - 200)}, open(sys.argv[1], "w")) | |
| 241 | +PY | |
| 242 | +CAP_LEN=$(wc -c < "$WORK/at_cap.json" | tr -d ' ') | |
| 243 | +SC=$(body "$(REQUEST_METHOD=POST CONTENT_LENGTH="$CAP_LEN" QUERY_STRING='action=save' $BIN < "$WORK/at_cap.json")") | |
| 244 | +json_ok "a body under the cap still saves" "$SC" "d['ok'] is True" | |
| 245 | +CAPID=$(printf '%s' "$SC" | python3 -c "import json,sys;print(json.load(sys.stdin)['note']['id'])" 2>/dev/null) | |
| 246 | +[ -n "$CAPID" ] && pass "the large note got an id" || fail "large note not saved" | |
| 247 | +api_post 'action=delete' "{\"id\":\"$CAPID\"}" >/dev/null | |
| 248 | + | |
| 249 | +# ---------------------------------------------------------------- render / XSS | |
| 250 | +section "mode 2i - markdown render (XSS inert)" | |
| 251 | +R1=$(api_post 'action=render' '{"body":"# Title\n\nA **bold** word and `code`."}') | |
| 252 | +json_ok "render answers ok:true" "$R1" "d['ok'] is True" | |
| 253 | +json_ok "render emits an h1" "$R1" "'<h1>Title</h1>' in d['html']" | |
| 254 | +json_ok "render emits strong" "$R1" "'<strong>bold</strong>' in d['html']" | |
| 255 | +json_ok "render emits code" "$R1" "'<code>code</code>' in d['html']" | |
| 256 | +R2=$(api_post 'action=render' '{"body":"<script>alert(1)</script>"}') | |
| 257 | +json_ok "a raw script tag is escaped" "$R2" "'<' not in d['html'].replace('<','') or '<script>' not in d['html']" | |
| 258 | +json_ok "the script tag became entities" "$R2" "'<script>' in d['html']" | |
| 259 | +R3=$(api_post 'action=render' '{"body":"[click](javascript:alert(1))"}') | |
| 260 | +json_ok "a javascript: link is not turned into an anchor" "$R3" "'<a ' not in d['html']" | |
| 261 | +json_ok "the javascript: link text is still escaped" "$R3" "'javascript:alert(1)' in d['html']" | |
| 262 | +R4=$(api_post 'action=render' '{"body":"[ok](https://example.com/x?a=1)"}') | |
| 263 | +json_ok "an https link becomes an anchor" "$R4" "'<a href=\"https://example.com/x?a=1\"' in d['html']" | |
| 264 | +json_ok "the anchor carries rel=noopener" "$R4" "'noopener noreferrer' in d['html']" | |
| 265 | +R5=$(api_post 'action=render' '{"body":"<img src=x onerror=alert(1)>"}') | |
| 266 | +json_ok "an img onerror payload is escaped" "$R5" "'<img' not in d['html']" | |
| 267 | +json_ok "the img payload shows as text" "$R5" "'<img' in d['html']" | |
| 268 | +R6=$(api_post 'action=render' '{"body":"\"quoted\" & <tagged> \u0027single\u0027"}') | |
| 269 | +json_ok "quotes and ampersands are escaped" "$R6" "'"' in d['html'] and '&' in d['html'] and ''' in d['html']" | |
| 270 | +R7=$(api_post 'action=render' '{"body":"```\ncode <b> here\n```"}') | |
| 271 | +json_ok "fenced code becomes a pre/code block" "$R7" "'<pre><code>' in d['html']" | |
| 272 | +json_ok "code content is escaped" "$R7" "'<b>' in d['html']" | |
| 273 | +R8=$(api_post 'action=render' '{"body":"- one\n- two"}') | |
| 274 | +json_ok "dash lists become ul/li" "$R8" "'<ul>' in d['html'] and '<li>one</li>' in d['html']" | |
| 275 | +R9=$(api_post 'action=render' '{"body":"1. one\n2. two"}') | |
| 276 | +json_ok "numbered lists become ol/li" "$R9" "'<ol>' in d['html'] and '<li>one</li>' in d['html']" | |
| 277 | +R10=$(api_post 'action=render' '{"body":"> a quote"}') | |
| 278 | +json_ok "a blockquote renders" "$R10" "'<blockquote>a quote</blockquote>' in d['html']" | |
| 279 | +R11=$(api_post 'action=render' '{"body":"---"}') | |
| 280 | +json_ok "a horizontal rule renders" "$R11" "'<hr>' in d['html']" | |
| 281 | +R12=$(api_post 'action=render' '{"body":"*em* and _em2_"}') | |
| 282 | +json_ok "italic renders" "$R12" "'<em>em</em>' in d['html'] and '<em>em2</em>' in d['html']" | |
| 283 | +check "render without a body is 400" 'Status: 400' \ | |
| 284 | + "$(printf '{}' | REQUEST_METHOD=POST CONTENT_LENGTH=2 QUERY_STRING='action=render' $BIN)" | |
| 285 | + | |
| 286 | +# ---------------------------------------------------------------- pin + ordering | |
| 287 | +section "mode 2j - pin and ordering" | |
| 288 | +PN=$(api_post "action=pin&id=$ID2" '{"pin":1}') | |
| 289 | +json_ok "pin answers ok:true" "$PN" "d['ok'] is True and d['pinned']==1" | |
| 290 | +json_ok "the pinned note sorts first" "$(api 'action=list')" "d['notes'][0]['id']=='$ID2'" | |
| 291 | +PN2=$(api_post "action=pin&id=$ID2" '{"pin":0}') | |
| 292 | +json_ok "unpin answers ok:true" "$PN2" "d['pinned']==0" | |
| 293 | +json_ok "unpinning drops it out of the pin slot" "$(api "action=get&id=$ID2")" "d['note']['pinned']==0" | |
| 294 | +PN3=$(api_post "action=pin&id=$ID1" '{"pin":true}') | |
| 295 | +json_ok "a JSON boolean pin value is accepted" "$PN3" "d['pinned']==1" | |
| 296 | +PNB=$(api_post 'action=pin&id=zzzzzzzzzzzz' '{"pin":1}') | |
| 297 | +check "pinning an unknown id is 404" 'Status: 404' \ | |
| 298 | + "$(printf '{"pin":1}' | REQUEST_METHOD=POST CONTENT_LENGTH=9 QUERY_STRING='action=pin&id=zzzzzzzzzzzz' $BIN)" | |
| 299 | + | |
| 300 | +# ---------------------------------------------------------------- search | |
| 301 | +section "mode 2k - search" | |
| 302 | +api_post 'action=save' '{"title":"Zebra striping","body":"alpha bravo charlie"}' >/dev/null | |
| 303 | +api_post 'action=save' '{"title":"Gamma","body":"nothing to see"}' >/dev/null | |
| 304 | +SR1=$(api 'action=search&q=zebra') | |
| 305 | +json_ok "search matches a title" "$SR1" "d['count']==1 and 'Zebra' in d['notes'][0]['title']" | |
| 306 | +SR2=$(api 'action=search&q=bravo') | |
| 307 | +json_ok "search matches the body text" "$SR2" "d['count']==1" | |
| 308 | +SR3=$(api 'action=search&q=NOTHING') | |
| 309 | +json_ok "search is case-insensitive" "$SR3" "d['count']==1" | |
| 310 | +SR4=$(api 'action=search&q=zzzznotfound') | |
| 311 | +json_ok "a search miss returns count 0" "$SR4" "d['count']==0" | |
| 312 | +SR5=$(api 'action=search&q=') | |
| 313 | +json_ok "an empty query lists everything" "$SR5" "d['count']>=4" | |
| 314 | + | |
| 315 | +# ---------------------------------------------------------------- delete/trash | |
| 316 | +section "mode 2l - delete moves to .trash" | |
| 317 | +DEL=$(api_post "action=delete&id=$ID2" '{}') | |
| 318 | +json_ok "delete answers ok:true" "$DEL" "d['ok'] is True and d['trash'] is True" | |
| 319 | +[ -f "$NOTES_DIR/.trash/$ID2.md" ] && pass "the body landed in .trash" || fail "no file in .trash" | |
| 320 | +json_ok "the deleted note is gone from list" "$(api 'action=list')" "all(n['id']!='$ID2' for n in d['notes'])" | |
| 321 | +check "get of a deleted id is 404" 'Status: 404' "$(apiraw "action=get&id=$ID2")" | |
| 322 | +check "deleting twice is 404 the second time" 'Status: 404' \ | |
| 323 | + "$(printf '{}' | REQUEST_METHOD=POST CONTENT_LENGTH=2 QUERY_STRING="action=delete&id=$ID2" $BIN)" | |
| 324 | + | |
| 325 | +# ---------------------------------------------------------------- HTML UI | |
| 326 | +section "mode 3 - HTML UI" | |
| 327 | +H=$(QUERY_STRING='' $BIN) | |
| 328 | +check "HTML page has the text/html Content-Type" 'Content-Type: text/html; charset=utf-8' "$H" | |
| 329 | +check "HTML page is a doctype" '<!DOCTYPE html>' "$H" | |
| 330 | +check "HTML page names the plugin" '<title>notes</title>' "$H" | |
| 331 | +check "HTML page has a CSP header" 'Content-Security-Policy' "$H" | |
| 332 | +check "CSP forbids remote script sources" "default-src 'none'" "$H" | |
| 333 | +check_not "no external script tag (no CDN)" '<script src=' "$H" | |
| 334 | +check_not "no cdnjs" 'cdnjs' "$H" | |
| 335 | +check_not "no unpkg" 'unpkg' "$H" | |
| 336 | +check_not "no jsdelivr" 'jsdelivr' "$H" | |
| 337 | +check_not "no jQuery" 'jquery' "$H" | |
| 338 | +check "the theme prepaint script is inline" 'data-theme' "$H" | |
| 339 | +check "the theme handoff listener is present" 'sx-theme' "$H" | |
| 340 | +check "the bot token block is inlined" '--bg-card' "$H" | |
| 341 | +check_not "no plugin-private palette variable" '--surface2:#' "$H" | |
| 342 | +check "the direct route is used for API calls" '/plugin_notes' "$H" | |
| 343 | +check "the hub route is used when ?plugin= is set" '/plugins?plugin=' "$H" | |
| 344 | +check "autosave debounce exists" 'setTimeout(function(){save();},800)' "$H" | |
| 345 | +check "the saved/unsaved pill exists" "id=\"state\"" "$H" | |
| 346 | +check "Ctrl/Cmd+S is wired" "'s'" "$H" | |
| 347 | +check "Ctrl/Cmd+K is wired" "'k'" "$H" | |
| 348 | +check "a nested-pane layout exists" 'grid-template-columns' "$H" | |
| 349 | +check "one pane is dropped under 700px" 'max-width:700px' "$H" | |
| 350 | +check "embed mode hides the theme toggle" 'embedded' "$H" | |
| 351 | +check_not "no emoji in the page" '😀' "$H" | |
| 352 | +check "inline SVG is used for icons" '<svg viewBox' "$H" | |
| 353 | +check "the product name is SCORPIOX BOT when mentioned" 'SCORPIOX BOT' "$(cat README.md)" | |
| 354 | +HE=$(QUERY_STRING='embed=1' $BIN) | |
| 355 | +check "embed=1 still serves the page" '<!DOCTYPE html>' "$HE" | |
| 356 | + | |
| 357 | +# ---------------------------------------------------------------- storage layout | |
| 358 | +section "storage layout" | |
| 359 | +[ -f "$NOTES_DIR/index.json" ] && pass "index.json lives in the notes dir" || fail "index.json missing" | |
| 360 | +check "index.json declares a version" '"version":1' "$(cat "$NOTES_DIR/index.json")" | |
| 361 | +check "index.json stores the notes array" '"notes"' "$(cat "$NOTES_DIR/index.json")" | |
| 362 | +NOTES_DIR="$WORK/other" QUERY_STRING='action=list' $BIN >/dev/null | |
| 363 | +[ -d "$WORK/other" ] && pass "NOTES_DIR overrides the storage location" || fail "NOTES_DIR ignored" | |
| 364 | +[ -d "$WORK/other/.trash" ] && pass "NOTES_DIR gets its own .trash" || fail "NOTES_DIR has no .trash" | |
| 365 | +N1=$(NOTES_DIR="$WORK/other" QUERY_STRING='action=list' $BIN) | |
| 366 | +json_ok "an empty NOTES_DIR starts empty (no leakage)" "$(body "$N1")" "d['count']==0" | |
| 367 | + | |
| 368 | +# ---------------------------------------------------------------- build hygiene | |
| 369 | +section "build hygiene" | |
| 370 | +[ -f src/ui.html ] && pass "src/ui.html is the readable page source" || fail "src/ui.html missing" | |
| 371 | +[ -f src/ui_html.h ] && pass "src/ui_html.h is generated next to the source" || fail "ui_html.h missing" | |
| 372 | +if command -v python3 >/dev/null 2>&1; then | |
| 373 | + python3 tools/gen_ui.py --check >/dev/null 2>&1 \ | |
| 374 | + && pass "ui_html.h matches ui.html (generator is in sync)" \ | |
| 375 | + || fail "ui_html.h is stale - run tools/gen_ui.py" | |
| 376 | +fi | |
| 377 | +grep -q '_WIN32_WINNT 0x0601' src/plugin_notes.c \ | |
| 378 | + && pass "_WIN32_WINNT is raised before the includes" || fail "_WIN32_WINNT missing" | |
| 379 | +grep -q '_DARWIN_C_SOURCE' src/plugin_notes.c \ | |
| 380 | + && pass "_DARWIN_C_SOURCE is defined for Apple" || fail "_DARWIN_C_SOURCE missing" | |
| 381 | +grep -q 'MoveFileExA' src/plugin_notes.c \ | |
| 382 | + && pass "Windows writes use MoveFileExA with REPLACE_EXISTING" || fail "no MoveFileExA" | |
| 383 | +grep -q 'REPLACE_EXISTING' src/plugin_notes.c \ | |
| 384 | + && pass "the Windows replace flag is present" || fail "REPLACE_EXISTING missing" | |
| 385 | +grep -q 'require_node_auth' src/plugin_notes.c \ | |
| 386 | + && pass "require_node_auth() gates the API" || fail "no node auth gate" | |
| 387 | +grep -q 'CONTENT_LENGTH' src/plugin_notes.c \ | |
| 388 | + && pass "the body read is guarded on CONTENT_LENGTH" || fail "no CONTENT_LENGTH guard" | |
| 389 | +grep -q 'BODY_MAX' src/plugin_notes.c \ | |
| 390 | + && pass "a body cap constant exists" || fail "no body cap" | |
| 391 | +grep -q 'valid_id' src/plugin_notes.c \ | |
| 392 | + && pass "ids are validated before touching the filesystem" || fail "no id validation" | |
| 393 | +for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json .gitignore; do | |
| 394 | + [ -f "$f" ] && pass "$f present" || fail "$f missing" | |
| 395 | +done | |
| 396 | +check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)" | |
| 397 | +check "README documents the actions" 'action=save' "$(cat README.md)" | |
| 398 | +check "README documents the security model" 'escaped' "$(cat README.md)" | |
| 399 | +check "plugin.json declares the slug" '"slug": "notes"' "$(cat plugin.json)" | |
| 400 | +check "plugin.json declares the utilities category" '"category": "utilities"' "$(cat plugin.json)" | |
| 401 | +check "plugin.json declares the id" '"id": "plugin_notes"' "$(cat plugin.json)" | |
| 402 | +check "plugin.json declares MIT" '"license": "MIT"' "$(cat plugin.json)" | |
| 403 | +check ".gitignore ignores the binary" 'plugin_notes' "$(cat .gitignore)" | |
| 404 | +check ".gitignore ignores __pycache__" '__pycache__' "$(cat .gitignore)" | |
| 405 | + | |
| 406 | +# ---------------------------------------------------------------- fortify | |
| 407 | +section "hardened build" | |
| 408 | +if cc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$WORK/plugin_notes_fort" src/plugin_notes.c 2>"$WORK/fort.err"; then | |
| 409 | + pass "_FORTIFY_SOURCE=2 build compiles" | |
| 410 | + FN=$(NOTES_DIR="$WORK/fortnotes" QUERY_STRING='action=list' "$WORK/plugin_notes_fort") | |
| 411 | + json_ok "the fortified build answers list" "$(body "$FN")" "d['ok'] is True" | |
| 412 | + FS=$(printf '{"title":"f","body":"fortified"}' | NOTES_DIR="$WORK/fortnotes" REQUEST_METHOD=POST CONTENT_LENGTH=31 QUERY_STRING='action=save' "$WORK/plugin_notes_fort") | |
| 413 | + json_ok "the fortified build saves a note" "$(body "$FS")" "d['ok'] is True" | |
| 414 | + FR=$(printf '{"body":"# ok"}' | NOTES_DIR="$WORK/fortnotes" REQUEST_METHOD=POST CONTENT_LENGTH=15 QUERY_STRING='action=render' "$WORK/plugin_notes_fort") | |
| 415 | + json_ok "the fortified build renders markdown" "$(body "$FR")" "'<h1>' in d['html']" | |
| 416 | +else | |
| 417 | + fail "_FORTIFY_SOURCE=2 build failed"; sed 's/^/ /' "$WORK/fort.err" | head -5 | |
| 418 | +fi | |
| 419 | + | |
| 420 | +# ---------------------------------------------------------------- cross targets | |
| 421 | +section "cross-target artifacts" | |
| 422 | +if [ -f plugin_notes.exe ]; then | |
| 423 | + MAGIC=$(od -An -tx1 -N2 plugin_notes.exe | tr -d ' \n') | |
| 424 | + [ "$MAGIC" = "4d5a" ] && pass "plugin_notes.exe starts with the MZ magic" || fail "PE magic wrong ($MAGIC)" | |
| 425 | +else | |
| 426 | + echo " (skip) plugin_notes.exe not built here" | |
| 427 | +fi | |
| 428 | +if [ -f plugin_notes.musl ]; then | |
| 429 | + file plugin_notes.musl | grep -q 'statically linked' && pass "musl build is static" || fail "musl build is not static" | |
| 430 | +else | |
| 431 | + echo " (skip) plugin_notes.musl not built here" | |
| 432 | +fi | |
| 433 | +if [ -f plugin_notes.arm64 ]; then | |
| 434 | + file plugin_notes.arm64 | grep -Eq 'ARM aarch64|aarch64' && pass "arm64 build is aarch64" || fail "arm64 build is not aarch64" | |
| 435 | +else | |
| 436 | + echo " (skip) plugin_notes.arm64 not built here" | |
| 437 | +fi | |
| 438 | + | |
| 439 | +# ---------------------------------------------------------------- history audit | |
| 440 | +section "git history secret audit" | |
| 441 | +if git rev-parse --git-dir >/dev/null 2>&1; then | |
| 442 | + ALL="$WORK/history.txt" | |
| 443 | + git log -p --all 2>/dev/null \ | |
| 444 | + | grep -v '^Author: ' \ | |
| 445 | + | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "|scan "' \ | |
| 446 | + > "$ALL" || : > "$ALL" | |
| 447 | + | |
| 448 | + audit() { # audit <label> <regex> | |
| 449 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | |
| 450 | + if [ -n "$H" ]; then | |
| 451 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | |
| 452 | + else | |
| 453 | + pass "history clean: $1" | |
| 454 | + fi | |
| 455 | + } | |
| 456 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 457 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 458 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 459 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 460 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 461 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 462 | + PK="pico""bot"; WT=".work""trees" | |
| 463 | + audit "internal fleet path" "/codebases/${PK}|${WT}" | |
| 464 | + audit "run token assignment" 'RUNNER_'"PASS=" | |
| 465 | +else | |
| 466 | + echo " skip history audit (not a git checkout)" | |
| 467 | +fi | |
| 468 | + | |
| 469 | +# ---------------------------------------------------------------- cleanup | |
| 470 | +rm -rf "$WORK" | |
| 471 | + | |
| 472 | +# ---------------------------------------------------------------- summary | |
| 473 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | |
| 474 | +printf ' passed: %d\n' "$PASS" | |
| 475 | +printf ' failed: %d\n' "$FAIL" | |
| 476 | +if [ "$FAIL" -ne 0 ]; then | |
| 477 | + printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0" | |
| 478 | + exit 1 | |
| 479 | +fi | |
| 480 | +if [ "$PASS" -lt 100 ]; then | |
| 481 | + printf ' %sRESULT: TOO FEW CHECKS (%d < 100)%s\n' "$C_BAD" "$PASS" "$C_0" | |
| 482 | + exit 1 | |
| 483 | +fi | |
| 484 | +printf ' %sRESULT: OK%s\n' "$C_OK" "$C_0" | |
| 485 | +exit 0 |
| 1 | 1 | new file mode 100644 |
| index 0000000..2ba72f9 | ||
| --- /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_NOTES_UI_HTML_H\n" | |
| 75 | + "#define SX_NOTES_UI_HTML_H\n" | |
| 76 | + "\n" | |
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | |
| 78 | + "\n" | |
| 79 | + "#endif /* SX_NOTES_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..3a06556 | index 0000000..3a06556 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,16 @@ | @@ -0,0 +1,16 @@ | ||
| 1 | +# build artifacts | ||
| 2 | +plugin_notes | ||
| 3 | +plugin_notes.exe | ||
| 4 | +plugin_notes.musl | ||
| 5 | +plugin_notes.arm64 | ||
| 6 | +plugin_notes.macos-arm64 | ||
| 7 | +plugin_notes.macos-x86_64 | ||
| 8 | +bin/ | ||
| 9 | + | ||
| 10 | +# local note stores (never commit anyone's notes) | ||
| 11 | +.notes/ | ||
| 12 | +*.tmp | ||
| 13 | + | ||
| 14 | +# python tooling | ||
| 15 | +__pycache__/ | ||
| 16 | +*.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..07c926e | index 0000000..07c926e | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,75 @@ | @@ -0,0 +1,75 @@ | ||
| 1 | +# plugin_notes - SCORPIOX BOT open-source markdown notes for your node | ||
| 2 | +# | ||
| 3 | +# Targets: | ||
| 4 | +# make native build -> ./plugin_notes | ||
| 5 | +# make musl static musl x86_64 -> ./plugin_notes.musl | ||
| 6 | +# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_notes.arm64 | ||
| 7 | +# make win64 MinGW-w64 static -> ./plugin_notes.exe | ||
| 8 | +# make macos Apple clang -> ./plugin_notes (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_notes.c | ||
| 23 | +UI_SRC := src/ui.html | ||
| 24 | +UI_HDR := src/ui_html.h | ||
| 25 | +BIN := plugin_notes | ||
| 26 | +EXE := plugin_notes.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..6f5c570 | index 0000000..6f5c570 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/README.md | +++ b/README.md | ||
| @@ -0,0 +1,171 @@ | @@ -0,0 +1,171 @@ | ||
| 1 | +# SCORPIOX BOT — notes | ||
| 2 | + | ||
| 3 | +Zero-dependency markdown notes that live on your **own node**. | ||
| 4 | + | ||
| 5 | +A note is one `<id>.md` file plus a row in `index.json`, both inside the plugin | ||
| 6 | +directory. Nothing leaves the machine: no account, no sync service, no CDN, no | ||
| 7 | +network call of any kind. Create, edit, rename, search, pin and delete notes | ||
| 8 | +with a live rendered preview beside the editor. | ||
| 9 | + | ||
| 10 | +``` | ||
| 11 | +make # native build -> ./plugin_notes | ||
| 12 | +make musl # static musl x86_64 -> ./plugin_notes.musl | ||
| 13 | +make arm64 # static aarch64 -> ./plugin_notes.arm64 | ||
| 14 | +make win64 # MinGW-w64 static PE -> ./plugin_notes.exe | ||
| 15 | +make macos # Apple clang (on macOS) -> ./plugin_notes | ||
| 16 | +make ui # regenerate src/ui_html.h from src/ui.html | ||
| 17 | +make test # offline suite (100+ assertions) | ||
| 18 | +make e2e # Playwright viewport suite (1440 / 1024 / 390, dark + light) | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +## Install | ||
| 22 | + | ||
| 23 | +Drop the binary where the node looks for plugins, then open | ||
| 24 | +**Settings → Plugins**, or use the market installer: | ||
| 25 | + | ||
| 26 | +```sh | ||
| 27 | +# node plugin directory (created by scorpiox-bot on startup) | ||
| 28 | +cp plugin_notes ~/.scorpiox/plugins/plugin_notes | ||
| 29 | +chmod +x ~/.scorpiox/plugins/plugin_notes | ||
| 30 | + | ||
| 31 | +# or from the market | ||
| 32 | +curl -s -H "X-Bot-Password: $BOT_PASSWORD" \ | ||
| 33 | + "http://127.0.0.1:8150/plugin_manage?action=install&slug=notes&mode=prebuilt" | ||
| 34 | +``` | ||
| 35 | + | ||
| 36 | +Windows: `%LOCALAPPDATA%\scorpiox\plugins\plugin_notes.exe`. | ||
| 37 | +BotCloud container: `/workspace/.scorpiox/plugins/plugin_notes`. | ||
| 38 | + | ||
| 39 | +## Three modes, one binary | ||
| 40 | + | ||
| 41 | +| Mode | Trigger | Response | | ||
| 42 | +|---|---|---| | ||
| 43 | +| Discovery | `--meta` or `SX_PLUGIN_META=1` | `{"name":"notes","desc":"Markdown notes"}` (unauthenticated) | | ||
| 44 | +| API | `?action=...`, `?format=json`, or any `POST` | `application/json; charset=utf-8` | | ||
| 45 | +| UI | plain `GET` (`?embed=1` aware) | the two-pane editor, `text/html` | | ||
| 46 | + | ||
| 47 | +Every API call is behind `require_node_auth()`: `X-Bot-Password`, | ||
| 48 | +`Authorization: Bearer <pwd>`, or `?pwd=`. With `BOT_PASSWORD` unset the check | ||
| 49 | +is a no-op, which is the intended behaviour on a single-user box. | ||
| 50 | + | ||
| 51 | +## Actions | ||
| 52 | + | ||
| 53 | +| Action | Call | Returns | | ||
| 54 | +|---|---|---| | ||
| 55 | +| `list` | `GET ?action=list` | `{"ok":true,"count":N,"notes":[{id,title,pinned,created,updated}]}` | | ||
| 56 | +| `get` | `GET ?action=get&id=<id>` | `{"ok":true,"note":{...,"body":"..."}}` | | ||
| 57 | +| `save` | `POST ?action=save` with `{"id?","title","body","pinned?"}` | `{"ok":true,"note":{...}}` | | ||
| 58 | +| `delete` | `POST ?action=delete&id=<id>` | `{"ok":true,"deleted":"<id>","trash":true}` | | ||
| 59 | +| `search` | `GET ?action=search&q=<text>` | same shape as `list`, title **and** body matched, case-insensitive | | ||
| 60 | +| `pin` | `POST ?action=pin&id=<id>` with `{"pin":0\|1}` | `{"ok":true,"id":"...","pinned":1}` | | ||
| 61 | +| `render` | `POST ?action=render` with `{"body":"..."}` | `{"ok":true,"html":"..."}` | | ||
| 62 | + | ||
| 63 | +`save` without an `id` creates a note and generates a `[a-z0-9]{12}` id | ||
| 64 | +server-side; with an id it updates in place and keeps `created`. | ||
| 65 | + | ||
| 66 | +Examples: | ||
| 67 | + | ||
| 68 | +```sh | ||
| 69 | +P="pwd=$BOT_PASSWORD" | ||
| 70 | +curl -s "http://127.0.0.1:8150/plugin_notes?action=list&$P" | ||
| 71 | + | ||
| 72 | +curl -s -X POST -H "Content-Type: application/json" \ | ||
| 73 | + "http://127.0.0.1:8150/plugin_notes?action=save&$P" \ | ||
| 74 | + -d '{"title":"Release checklist","body":"# Release checklist\n\n- build\n- verify"}' | ||
| 75 | + | ||
| 76 | +curl -s "http://127.0.0.1:8150/plugin_notes?action=search&q=verify&$P" | ||
| 77 | +curl -s -X POST "http://127.0.0.1:8150/plugin_notes?action=delete&id=<id>&$P" | ||
| 78 | +``` | ||
| 79 | + | ||
| 80 | +## Storage | ||
| 81 | + | ||
| 82 | +| Platform | Location | | ||
| 83 | +|---|---| | ||
| 84 | +| Linux / macOS | `<plugin dir>/.notes/` — or `$NOTES_DIR` | | ||
| 85 | +| Windows | `%LOCALAPPDATA%\scorpiox\plugins\.notes\` | | ||
| 86 | + | ||
| 87 | +``` | ||
| 88 | +.notes/ | ||
| 89 | +├── index.json # {"version":1,"notes":[{id,title,pinned,created,updated}]} | ||
| 90 | +├── <id>.md # the markdown body of one note | ||
| 91 | +└── .trash/<id>.md # deleted notes, kept so a wrong click is recoverable | ||
| 92 | +``` | ||
| 93 | + | ||
| 94 | +Every write is `fwrite` to `<path>.tmp`, `fflush` + `fsync`, then `rename` (POSIX) | ||
| 95 | +or `MoveFileExA(..., MOVEFILE_REPLACE_EXISTING)` (Windows). A process killed | ||
| 96 | +mid-write leaves the previous note intact rather than a half file. The body is | ||
| 97 | +written before the index, so an index row never points at a note that was never | ||
| 98 | +written. | ||
| 99 | + | ||
| 100 | +## Security model | ||
| 101 | + | ||
| 102 | +* **Authentication** — every action requires the node password (three accepted | ||
| 103 | + forms above); `--meta` alone stays open so discovery still works. | ||
| 104 | +* **Path safety** — ids are generated by the binary (`[a-z0-9]{12}`) and any id | ||
| 105 | + arriving in a request is validated against that shape before it can be turned | ||
| 106 | + into a path. `?id=../../etc/passwd`, `%2f`, uppercase and length overruns are | ||
| 107 | + all rejected with `400`. | ||
| 108 | +* **Write scope** — nothing is written outside the notes directory; the trash | ||
| 109 | + subdirectory is inside it. | ||
| 110 | +* **Size cap** — a note body is capped at 512 KiB; over that the request is | ||
| 111 | + refused with `413` naming the limit. The CGI body read is guarded on | ||
| 112 | + `CONTENT_LENGTH` so an inherited empty stdin never blocks the process. | ||
| 113 | +* **XSS** — markdown is rendered **server-side**, and every literal byte of note | ||
| 114 | + content is HTML-escaped before any tag is emitted (`&`, `<`, `>`, `"`, `'`) so | ||
| 115 | + a note containing `<script>`, `<img onerror=...>` or a `javascript:` link | ||
| 116 | + renders as inert text; only `https:`, `http:`, `mailto:` and same-page links | ||
| 117 | + become real anchors. `tests/run.sh` asserts this for each payload. | ||
| 118 | +* **CSP** — the page ships | ||
| 119 | + `default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'` | ||
| 120 | + so even a future regression cannot fetch a remote script. | ||
| 121 | + | ||
| 122 | +## UI | ||
| 123 | + | ||
| 124 | +Two panes: the note list with search on the left, editor above a live rendered | ||
| 125 | +preview on the right. Under 700 px the layout collapses to a single pane with a | ||
| 126 | +back button and a preview toggle, so the same page is usable at 390 px and inside | ||
| 127 | +the Chat floating window. | ||
| 128 | + | ||
| 129 | +* autosave with an 800 ms debounce and a visible `saved` / `unsaved` / `saving` | ||
| 130 | + pill (`Ctrl/Cmd+S` forces an immediate save) | ||
| 131 | +* `Ctrl/Cmd+K` focuses search, `Alt+Ctrl/Cmd+N` starts a new note, `Tab` in the | ||
| 132 | + editor inserts two spaces | ||
| 133 | +* pin and delete per note, delete moves to `.trash` | ||
| 134 | +* dark and light from the SCORPIOX BOT theme tokens, following `?theme=`, | ||
| 135 | + `localStorage.bot_theme`, `prefers-color-scheme` and the `sx-theme` postMessage | ||
| 136 | + handoff; the plugin's own toggle hides under `?embed=1` | ||
| 137 | +* no `<script src=>`, no CDN, no framework, zero emoji — inline SVG only | ||
| 138 | + | ||
| 139 | + | ||
| 140 | + | ||
| 141 | + | ||
| 142 | +## API routes the page uses | ||
| 143 | + | ||
| 144 | +The single most common plugin bug is calling the wrong route. This page branches | ||
| 145 | +exactly once, using `preferred-bot-plugin`'s template: | ||
| 146 | + | ||
| 147 | +* served through the hub (`/plugins?plugin=plugin_notes&node=...`) → call the hub | ||
| 148 | + proxy back: `/plugins?plugin=plugin_notes&action=...` | ||
| 149 | +* opened directly on the node (`/plugin_notes`) → the plugin **is** the route: | ||
| 150 | + `/plugin_notes?action=...` | ||
| 151 | + | ||
| 152 | +Calling `/plugins?plugin=` on the node itself returns the discovery list, not the | ||
| 153 | +plugin. | ||
| 154 | + | ||
| 155 | +## Test | ||
| 156 | + | ||
| 157 | +```sh | ||
| 158 | +make test # 150+ offline assertions, 0 fail, no network, no Playwright | ||
| 159 | +make e2e # Playwright: 6 viewports × theme, console/overflow/autosave | ||
| 160 | +``` | ||
| 161 | + | ||
| 162 | +The offline suite proves the contract (meta, auth, every action's JSON shape, CRUD | ||
| 163 | +round trip, atomic write, the size cap, id validation, XSS inertness, trash, | ||
| 164 | +pinning order, search, the generated UI's CSP and route branching), builds the | ||
| 165 | +same source with `-D_FORTIFY_SOURCE=2` and runs it, checks the MinGW `MZ` header | ||
| 166 | +when the PE is present, and audits the whole git history for secrets and internal | ||
| 167 | +addresses. | ||
| 168 | + | ||
| 169 | +## License | ||
| 170 | + | ||
| 171 | +MIT © 2026 SCORPIOX INC. See [LICENSE](LICENSE). |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0e50dcd | index 0000000..0e50dcd | ||
| --- /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_notes | ||
| 2 | +# | ||
| 3 | +# Usage (from the repo root, PowerShell): | ||
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | ||
| 5 | +# | ||
| 6 | +# Produces .\plugin_notes.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_notes.c" | ||
| 14 | + $Out = Join-Path $ScriptDir "plugin_notes.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_notes.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_notes.exe --meta" | ||
| 49 | +} finally { | ||
| 50 | + Pop-Location | ||
| 51 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0520e51 | index 0000000..0520e51 |

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

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..16e7d1a | index 0000000..16e7d1a |

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

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

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..4d872f4 | index 0000000..4d872f4 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..6932c13 | index 0000000..6932c13 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/plugin.json | +++ b/plugin.json | ||
| @@ -0,0 +1,14 @@ | @@ -0,0 +1,14 @@ | ||
| 1 | +{ | ||
| 2 | + "slug": "notes", | ||
| 3 | + "id": "plugin_notes", | ||
| 4 | + "title": "Markdown Notes", | ||
| 5 | + "summary": "Zero-dependency markdown notes that live on your node: create, edit, rename, search, pin and delete, with a live rendered preview next to the editor. Notes are one <id>.md file each plus index.json inside the plugin directory, every write is staged to a temp file and renamed so a crash never truncates a note, and deleted notes go to a recoverable .trash. Server-side rendering escapes note content first, so a pasted <script> is inert text. No CDN, no network requests, no database.", | ||
| 6 | + "category": "utilities", | ||
| 7 | + "license": "MIT", | ||
| 8 | + "capabilities": [ | ||
| 9 | + "fs_write_plugin_dir" | ||
| 10 | + ], | ||
| 11 | + "trust_notice": "Executes native C code on your node. Reads and writes only inside its own notes directory (plugin dir/.notes, or $NOTES_DIR when set): one markdown file per note, an index.json, and a .trash subdirectory. It opens no network connection of any kind and reads nothing outside that directory.", | ||
| 12 | + "author": "SCORPIOX INC", | ||
| 13 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-notes" | ||
| 14 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..2c24ffb | index 0000000..2c24ffb | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/release-dist.sh | +++ b/release-dist.sh | ||
| @@ -0,0 +1,365 @@ | @@ -0,0 +1,365 @@ | ||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# release-dist.sh - build, scan and publish plugin_notes to the plugin registry. | ||
| 3 | +# | ||
| 4 | +# Two paths: | ||
| 5 | +# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it | ||
| 6 | +# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI. | ||
| 7 | +# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz -> | ||
| 8 | +# manifest.json + SHA256SUMS -> upload -> latest.json / index.json. | ||
| 9 | +# | ||
| 10 | +# Nothing here contains a host address or a credential. Everything environment-specific | ||
| 11 | +# comes from the environment, so this file stays safe to publish: | ||
| 12 | +# | ||
| 13 | +# DIST_HOST ssh target for the dist server (required for upload) | ||
| 14 | +# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key) | ||
| 15 | +# DIST_PATH remote web root of the dist server (default /data/dist) | ||
| 16 | +# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64) | ||
| 17 | +# MAC_USER / MAC_PASS (optional) | ||
| 18 | +# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token) | ||
| 19 | +# PLUGINGIT_REMOTE public mirror URL to push into | ||
| 20 | +# | ||
| 21 | +# Usage: | ||
| 22 | +# ./release-dist.sh # full release | ||
| 23 | +# ./release-dist.sh --dry-run # build + stage in /tmp, no upload | ||
| 24 | +# ./release-dist.sh --no-macos # skip the macOS legs | ||
| 25 | +# ./release-dist.sh --no-mirror # skip the plugingit mirror | ||
| 26 | +# ./release-dist.sh --standalone # use this script even if the CLI is installed | ||
| 27 | +# # (needed for plugins that link extra Win32 libs, | ||
| 28 | +# # which the CLI's fixed link line cannot express) | ||
| 29 | + | ||
| 30 | +set -euo pipefail | ||
| 31 | + | ||
| 32 | +SLUG="notes" | ||
| 33 | +ID="plugin_notes" | ||
| 34 | +VERSION="1.0.0" | ||
| 35 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | ||
| 36 | + | ||
| 37 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | ||
| 38 | +cd "$ROOT" | ||
| 39 | + | ||
| 40 | +DRY_RUN=0 | ||
| 41 | +DO_MACOS=1 | ||
| 42 | +DO_MIRROR=1 | ||
| 43 | +STANDALONE=0 | ||
| 44 | +for arg in "$@"; do | ||
| 45 | + case "$arg" in | ||
| 46 | + --standalone) STANDALONE=1 ;; | ||
| 47 | + --dry-run) DRY_RUN=1 ;; | ||
| 48 | + --no-macos) DO_MACOS=0 ;; | ||
| 49 | + --no-mirror) DO_MIRROR=0 ;; | ||
| 50 | + -h|--help) sed -n '2,32p' "$0"; exit 0 ;; | ||
| 51 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | ||
| 52 | + esac | ||
| 53 | +done | ||
| 54 | + | ||
| 55 | +DIST_HOST="${DIST_HOST:-}" | ||
| 56 | +DIST_PASS="${DIST_PASS:-}" | ||
| 57 | +DIST_PATH="${DIST_PATH:-/data/dist}" | ||
| 58 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | ||
| 59 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | ||
| 60 | + | ||
| 61 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | ||
| 62 | +mkdir -p "$STAGE" | ||
| 63 | +trap 'rm -rf "$STAGE"' EXIT | ||
| 64 | + | ||
| 65 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | ||
| 66 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | ||
| 67 | + | ||
| 68 | +# ---------------------------------------------------------------- 0. preflight | ||
| 69 | +say "0/7 preflight" | ||
| 70 | + | ||
| 71 | +if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | ||
| 72 | + say "using scorpiox-cli-botplugin publish" | ||
| 73 | + exec scorpiox-cli-botplugin publish "$ROOT" | ||
| 74 | +fi | ||
| 75 | +echo " running the standalone pipeline" | ||
| 76 | + | ||
| 77 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | ||
| 78 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | ||
| 79 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | ||
| 80 | +echo " version $VERSION" | ||
| 81 | +echo " commit $COMMIT" | ||
| 82 | + | ||
| 83 | +# ---------------------------------------------------------------- 1. secret scan | ||
| 84 | +say "1/7 secret & LAN scan (full history)" | ||
| 85 | + | ||
| 86 | +SCAN_TMP="$STAGE/history.txt" | ||
| 87 | +# Scan every added/removed line of every commit. Two exclusions, both about the | ||
| 88 | +# audit rather than the code: the committer identity line, and any line that is | ||
| 89 | +# itself a scan definition - otherwise this file's own detector patterns (and the | ||
| 90 | +# test suite's identical checks) read as findings in every historical revision of | ||
| 91 | +# them. A real secret on any other line still hits. | ||
| 92 | +git log -p --all 2>/dev/null \ | ||
| 93 | + | grep -v '^Author: ' \ | ||
| 94 | + | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|P_ROOT=|P_WT=|PK=\"|\$ALL" \ | ||
| 95 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | ||
| 96 | +HITS=0 | ||
| 97 | +scan() { # scan <label> <regex> | ||
| 98 | + local out | ||
| 99 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | ||
| 100 | + if [ -n "$out" ]; then | ||
| 101 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | ||
| 102 | + printf '%s\n' "$out" | sed 's/^/ /' | ||
| 103 | + HITS=$((HITS + 1)) | ||
| 104 | + else | ||
| 105 | + printf ' ok %s\n' "$1" | ||
| 106 | + fi | ||
| 107 | +} | ||
| 108 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 109 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 110 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 111 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 112 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 113 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 114 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | ||
| 115 | +P_ROOT="/codebases" | ||
| 116 | +P_PICOBOT="${P_ROOT}/pico""bot" | ||
| 117 | +P_WT=".work""trees" | ||
| 118 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | ||
| 119 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | ||
| 120 | +if [ "$HITS" -ne 0 ]; then | ||
| 121 | + die "secret scan found $HITS problem(s) - refusing to publish" | ||
| 122 | +fi | ||
| 123 | +echo " clean: 0 hits" | ||
| 124 | + | ||
| 125 | +# ---------------------------------------------------------------- 2. build | ||
| 126 | +say "2/7 build targets" | ||
| 127 | + | ||
| 128 | +# linux-x86_64 (glibc, native) | ||
| 129 | +if command -v cc >/dev/null 2>&1; then | ||
| 130 | + cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -o "$STAGE/$ID" src/$ID.c || die "native build failed" | ||
| 131 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | ||
| 132 | +else | ||
| 133 | + die "no native cc found" | ||
| 134 | +fi | ||
| 135 | + | ||
| 136 | +# linux-x86_64-musl (fully static - the universal Linux artifact) | ||
| 137 | +if command -v musl-gcc >/dev/null 2>&1; then | ||
| 138 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.musl" src/$ID.c \ | ||
| 139 | + || die "musl build failed" | ||
| 140 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | ||
| 141 | +else | ||
| 142 | + echo " skip linux-x86_64-musl (no musl-gcc)" | ||
| 143 | +fi | ||
| 144 | + | ||
| 145 | +# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers) | ||
| 146 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | ||
| 147 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.arm64" src/$ID.c \ | ||
| 148 | + || die "arm64 build failed" | ||
| 149 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | ||
| 150 | +else | ||
| 151 | + echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)" | ||
| 152 | +fi | ||
| 153 | + | ||
| 154 | +# windows-x86_64 (static PE) | ||
| 155 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | ||
| 156 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings \ | ||
| 157 | + -I src -o "$STAGE/$ID.exe" src/$ID.c || die "MinGW build failed" | ||
| 158 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | ||
| 159 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | ||
| 160 | +else | ||
| 161 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | ||
| 162 | +fi | ||
| 163 | + | ||
| 164 | +# macOS legs - Mach-O must be produced by Apple clang on a real Mac. | ||
| 165 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | ||
| 166 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | ||
| 167 | + MAC_USER="${MAC_USER:-$(whoami)}" | ||
| 168 | + MAC_DIR="/tmp/${ID}-mac-$$" | ||
| 169 | + echo " building macOS legs on $MAC_HOST" | ||
| 170 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | ||
| 171 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | ||
| 172 | + if [ -n "${MAC_PASS:-}" ]; then | ||
| 173 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | ||
| 174 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | ||
| 175 | + fi | ||
| 176 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | ||
| 177 | + tar -czf "$STAGE/src.tgz" src | ||
| 178 | + if "${SCP_MAC[@]}" "$STAGE/src.tgz" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tgz" \ | ||
| 179 | + && "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tgz"; then | ||
| 180 | + # Build straight from the uploaded file - no src/ tree on the remote. | ||
| 181 | + for slice in arm64 x86_64; do | ||
| 182 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | ||
| 183 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -arch $slice -o $ID.$slice src/$ID.c" \ | ||
| 184 | + 2>/dev/null; then | ||
| 185 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | ||
| 186 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | ||
| 187 | + else | ||
| 188 | + echo " warn: macos-$slice build failed on $MAC_HOST" | ||
| 189 | + fi | ||
| 190 | + done | ||
| 191 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true | ||
| 192 | + else | ||
| 193 | + echo " warn: could not upload source to $MAC_HOST" | ||
| 194 | + fi | ||
| 195 | + else | ||
| 196 | + echo " warn: cannot reach macOS builder $MAC_HOST" | ||
| 197 | + fi | ||
| 198 | +else | ||
| 199 | + echo " skip macOS legs (no MAC_HOST or --no-macos)" | ||
| 200 | +fi | ||
| 201 | + | ||
| 202 | +# ---------------------------------------------------------------- 3. manifest | ||
| 203 | +say "3/7 manifest + checksums" | ||
| 204 | + | ||
| 205 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | ||
| 206 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | ||
| 207 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | ||
| 208 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | ||
| 209 | + | ||
| 210 | +target_meta() { # target_meta <key> <file> <format> <relpath> | ||
| 211 | + local key="$1" file="$2" fmt="$3" rel="$4" | ||
| 212 | + [ -f "$file" ] || return 0 | ||
| 213 | + local sha size | ||
| 214 | + sha=$(sha256sum "$file" | awk '{print $1}') | ||
| 215 | + size=$(wc -c < "$file" | tr -d ' ') | ||
| 216 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | ||
| 217 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | ||
| 218 | +} | ||
| 219 | + | ||
| 220 | +{ | ||
| 221 | + printf '{\n' | ||
| 222 | + printf ' "slug": "%s",\n' "$SLUG" | ||
| 223 | + printf ' "id": "%s",\n' "$ID" | ||
| 224 | + printf ' "name": "notes",\n' | ||
| 225 | + printf ' "desc": "Markdown notes",\n' | ||
| 226 | + printf ' "title": "Markdown Notes",\n' | ||
| 227 | + printf ' "summary": "Zero-dependency markdown notes that live on your node: create, edit, rename, search, pin and delete, with a live rendered preview next to the editor. Notes are one <id>.md file each plus index.json inside the plugin directory, every write is staged to a temp file and renamed so a crash never truncates a note, and deleted notes go to a recoverable .trash. Server-side rendering escapes note content first, so a pasted <script> is inert text. No CDN, no network requests, no database.",\n' | ||
| 228 | + printf ' "category": "utilities",\n' | ||
| 229 | + printf ' "version": "%s",\n' "$VERSION" | ||
| 230 | + printf ' "license": "MIT",\n' | ||
| 231 | + printf ' "trust_notice": "Executes native C code on your node. Reads and writes only inside its own notes directory (plugin dir/.notes, or $NOTES_DIR when set): one markdown file per note, an index.json, and a .trash subdirectory. It opens no network connection of any kind and reads nothing outside that directory.",\n' | ||
| 232 | + printf ' "capabilities": ["fs_write_plugin_dir"],\n' | ||
| 233 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | ||
| 234 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | ||
| 235 | + printf ' "git_commit": "%s",\n' "$COMMIT" | ||
| 236 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 237 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | ||
| 238 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID" | ||
| 239 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID" | ||
| 240 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | ||
| 241 | + printf ' "targets": {\n' | ||
| 242 | + first=1 | ||
| 243 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | ||
| 244 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" | ||
| 245 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" | ||
| 246 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" | ||
| 247 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" | ||
| 248 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" | ||
| 249 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" | ||
| 250 | + printf '\n }\n}\n' | ||
| 251 | +} > "$STAGE/manifest.json" | ||
| 252 | + | ||
| 253 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | ||
| 254 | + || die "generated manifest.json is not valid JSON" | ||
| 255 | +echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)" | ||
| 256 | + | ||
| 257 | +# SHA256SUMS - relative paths, exactly as published | ||
| 258 | +( cd "$STAGE" | ||
| 259 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | ||
| 260 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | ||
| 261 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | ||
| 262 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | ||
| 263 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | ||
| 264 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | ||
| 265 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | ||
| 266 | + true ) > "$STAGE/SHA256SUMS" | ||
| 267 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | ||
| 268 | + | ||
| 269 | +# ---------------------------------------------------------------- 4. stage | ||
| 270 | +say "4/7 stage tree" | ||
| 271 | +PKG="$STAGE/pkg" | ||
| 272 | +mkdir -p "$PKG" | ||
| 273 | +cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | ||
| 274 | +[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; } | ||
| 275 | +[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; } | ||
| 276 | +[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; } | ||
| 277 | +[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; } | ||
| 278 | +[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; } | ||
| 279 | +[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; } | ||
| 280 | +echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)" | ||
| 281 | + | ||
| 282 | +if [ "$DRY_RUN" -eq 1 ]; then | ||
| 283 | + say "dry run - leaving the staging tree in $PKG" | ||
| 284 | + trap - EXIT | ||
| 285 | + exit 0 | ||
| 286 | +fi | ||
| 287 | + | ||
| 288 | +# ---------------------------------------------------------------- 5. upload | ||
| 289 | +say "5/7 upload to the dist server" | ||
| 290 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)" | ||
| 291 | +SSH=(ssh -o StrictHostKeyChecking=no) | ||
| 292 | +SCP=(scp -o StrictHostKeyChecking=no) | ||
| 293 | +if [ -n "$DIST_PASS" ]; then | ||
| 294 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | ||
| 295 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | ||
| 296 | +fi | ||
| 297 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | ||
| 298 | + | ||
| 299 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | ||
| 300 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | ||
| 301 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | ||
| 302 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | ||
| 303 | +# OpenSSH 9 refuses to scp a bare "." source. | ||
| 304 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | ||
| 305 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | ||
| 306 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | ||
| 307 | + || die "remote extract failed" | ||
| 308 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | ||
| 309 | + | ||
| 310 | +# latest.json = copy of this version's manifest | ||
| 311 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | ||
| 312 | + || die "latest.json update failed" | ||
| 313 | +echo " updated bot-plugins/$SLUG/latest.json" | ||
| 314 | + | ||
| 315 | +# index.json - merge, preserving every sibling <slug>/latest.json | ||
| 316 | +say "index.json merge" | ||
| 317 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | ||
| 318 | +import json, os, sys, glob | ||
| 319 | +slug = sys.argv[1] | ||
| 320 | +entries = {} | ||
| 321 | +for p in sorted(glob.glob('*/latest.json')): | ||
| 322 | + s = os.path.dirname(p) | ||
| 323 | + try: | ||
| 324 | + entries[s] = json.load(open(p)) | ||
| 325 | + except Exception: | ||
| 326 | + pass | ||
| 327 | +index = { | ||
| 328 | + 'ok': True, | ||
| 329 | + 'service': 'bot-plugins-dist', | ||
| 330 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | ||
| 331 | + 'count': len(entries), | ||
| 332 | + 'slugs': sorted(entries), | ||
| 333 | + 'plugins': [entries[k] for k in sorted(entries)], | ||
| 334 | +} | ||
| 335 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | ||
| 336 | +os.replace('index.json.tmp', 'index.json') | ||
| 337 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | ||
| 338 | +PY" || die "index.json merge failed" | ||
| 339 | + | ||
| 340 | +# ---------------------------------------------------------------- 6. mirror | ||
| 341 | +say "6/7 plugingit mirror" | ||
| 342 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | ||
| 343 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | ||
| 344 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|") | ||
| 345 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | ||
| 346 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | ||
| 347 | + echo " mirrored to $PLUGINGIT_REMOTE" | ||
| 348 | +else | ||
| 349 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | ||
| 350 | +fi | ||
| 351 | + | ||
| 352 | +# ---------------------------------------------------------------- 7. verify | ||
| 353 | +say "7/7 verify" | ||
| 354 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | ||
| 355 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | ||
| 356 | +if [ "$CODE" = "200" ]; then | ||
| 357 | + python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \ | ||
| 358 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | ||
| 359 | +else | ||
| 360 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | ||
| 361 | +fi | ||
| 362 | + | ||
| 363 | +printf '\n\033[1mrelease complete\033[0m\n' | ||
| 364 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 365 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0dd243b | index 0000000..0dd243b | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | @@ -0,0 +1,129 @@ | ||
| 1 | +/* | ||
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | ||
| 3 | + * | ||
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | ||
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | ||
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | ||
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | ||
| 8 | + * localStorage key, same prepaint order. | ||
| 9 | + * | ||
| 10 | + * Three rules, and nothing else: | ||
| 11 | + * | ||
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | ||
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | ||
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | ||
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | ||
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | ||
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | ||
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | ||
| 19 | + * it was already open when the bot changed theme. | ||
| 20 | + * | ||
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | ||
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | ||
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | ||
| 24 | + * are var() references, one definition covers both themes. | ||
| 25 | + * | ||
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 27 | + */ | ||
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | ||
| 29 | +#define SX_BOT_THEME_PLUGIN_H | ||
| 30 | + | ||
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | ||
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | ||
| 33 | +#define SX_BOT_THEME_TOKENS \ | ||
| 34 | +":root{color-scheme:dark;" \ | ||
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | ||
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | ||
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | ||
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | ||
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | ||
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | ||
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | ||
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | ||
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | ||
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | ||
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | ||
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | ||
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | ||
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | ||
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | ||
| 50 | +"}" \ | ||
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | ||
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 58 | + "--accent-dim:#0066d6;" \ | ||
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 62 | + "color-scheme:light}}" \ | ||
| 63 | +"html[data-theme=light]{" \ | ||
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 70 | + "--accent-dim:#0066d6;" \ | ||
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 74 | + "color-scheme:light}" \ | ||
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | ||
| 76 | +"*{box-sizing:border-box}" \ | ||
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | ||
| 78 | + "-webkit-font-smoothing:antialiased}" \ | ||
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | ||
| 80 | +"button:active{transform:scale(.98)}" \ | ||
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | ||
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | ||
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | ||
| 84 | +" * hides its own back link and its own toggle. */" \ | ||
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | ||
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | ||
| 87 | + | ||
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | ||
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | ||
| 90 | + * html.embedded so the embed rules apply before first paint. */ | ||
| 91 | +#define SX_BOT_THEME_PREPAINT \ | ||
| 92 | +"<script>(function(){var t='';" \ | ||
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | ||
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | ||
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | ||
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | ||
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 99 | +"})();</script>\n" | ||
| 100 | + | ||
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | ||
| 102 | + * at startup in case it changed while this page was already open. Fires the | ||
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | ||
| 104 | + * re-skin themselves from one listener. */ | ||
| 105 | +#define SX_BOT_THEME_HANDOFF \ | ||
| 106 | +"<script>(function(){" \ | ||
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | ||
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | ||
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | ||
| 112 | +"window.sxApplyTheme=apply;" \ | ||
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | ||
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | ||
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | ||
| 116 | +"})();</script>\n" | ||
| 117 | + | ||
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | ||
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | ||
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | ||
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | ||
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | ||
| 123 | + | ||
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | ||
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | ||
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | ||
| 127 | +"})();</script>\n" | ||
| 128 | + | ||
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..aa88bfd | index 0000000..aa88bfd | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_notes.c | +++ b/src/plugin_notes.c | ||
| @@ -0,0 +1,1624 @@ | @@ -0,0 +1,1624 @@ | ||
| 1 | +/* | ||
| 2 | + * plugin_notes - SCORPIOX BOT open-source markdown notes 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 / POST -> JSON node API | ||
| 7 | + * 3. GET (default) -> two-pane markdown editor | ||
| 8 | + * | ||
| 9 | + * Storage: one file per note, `<id>.md`, plus `index.json` holding the | ||
| 10 | + * metadata and the ordering. Both live inside `<plugin dir>/.notes/` | ||
| 11 | + * (Linux/macOS) or `%LOCALAPPDATA%\scorpiox\plugins\.notes\` (Windows), and | ||
| 12 | + * `$NOTES_DIR` overrides the location for tests and for people who want their | ||
| 13 | + * notes somewhere else. Every write goes to `<name>.tmp` and is then renamed | ||
| 14 | + * over the real file, so a kill -9 mid-write leaves the previous content | ||
| 15 | + * intact rather than a truncated note. | ||
| 16 | + * | ||
| 17 | + * Note ids are generated by this binary (`[a-z0-9]{12}`), never taken from the | ||
| 18 | + * client as a path, and any id that arrives in a request is validated against | ||
| 19 | + * that shape before it can touch the filesystem. Markdown is rendered | ||
| 20 | + * server-side with raw HTML escaped first, so a note containing `<script>` or | ||
| 21 | + * a `javascript:` link renders as inert text. | ||
| 22 | + * | ||
| 23 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | ||
| 24 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | ||
| 25 | + * scorpiox-server on the node. | ||
| 26 | + * | ||
| 27 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 28 | + */ | ||
| 29 | + | ||
| 30 | +/* Must come before every include on Windows: MinGW defaults to 0x502 | ||
| 31 | + * (Server 2003), which hides MoveFileExA and the wide-path helpers. */ | ||
| 32 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | ||
| 33 | +# define _WIN32_WINNT 0x0601 | ||
| 34 | +#endif | ||
| 35 | + | ||
| 36 | +#if !defined(_WIN32) | ||
| 37 | +# define _POSIX_C_SOURCE 200809L | ||
| 38 | +# define _DEFAULT_SOURCE 1 | ||
| 39 | +# if defined(__APPLE__) | ||
| 40 | +# define _DARWIN_C_SOURCE 1 | ||
| 41 | +# endif | ||
| 42 | +#endif | ||
| 43 | + | ||
| 44 | +#include <stdio.h> | ||
| 45 | +#include <stdlib.h> | ||
| 46 | +#include <string.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 <direct.h> | ||
| 55 | +# include <io.h> | ||
| 56 | +#else | ||
| 57 | +# include <unistd.h> | ||
| 58 | +# include <sys/stat.h> | ||
| 59 | +# include <sys/types.h> | ||
| 60 | +#endif | ||
| 61 | + | ||
| 62 | +#include "bot_theme_plugin.h" | ||
| 63 | +#include "ui_html.h" | ||
| 64 | + | ||
| 65 | +#define PLUGIN_SLUG "notes" | ||
| 66 | +#define PLUGIN_ID "plugin_notes" | ||
| 67 | +#define PLUGIN_VER "1.0.0" | ||
| 68 | +#define PLUGIN_NAME "notes" | ||
| 69 | +#define PLUGIN_DESC "Markdown notes" | ||
| 70 | + | ||
| 71 | +#define PATH_SZ 1024 | ||
| 72 | +#define ID_LEN 12 | ||
| 73 | +#define ID_BUF (ID_LEN + 1) | ||
| 74 | +#define TITLE_MAX 300 | ||
| 75 | +#define MAX_NOTES 2000 | ||
| 76 | +#define BODY_MAX (512 * 1024) /* hard cap on one note, spec'd */ | ||
| 77 | +#define REQ_MAX (BODY_MAX + 8192) /* JSON envelope around it */ | ||
| 78 | +#define TRASH_DIR ".trash" | ||
| 79 | + | ||
| 80 | +typedef struct { | ||
| 81 | + char id[ID_BUF]; | ||
| 82 | + char title[TITLE_MAX]; | ||
| 83 | + int pinned; | ||
| 84 | + char created[24]; | ||
| 85 | + char updated[24]; | ||
| 86 | +} note_meta_t; | ||
| 87 | + | ||
| 88 | +static note_meta_t g_meta[MAX_NOTES]; | ||
| 89 | +static int g_count; | ||
| 90 | + | ||
| 91 | +static char g_dir[PATH_SZ]; /* <notes dir> */ | ||
| 92 | +static char g_trash[PATH_SZ]; /* <notes dir>/.trash */ | ||
| 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)64 * 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 (!s || n == 0) return; | ||
| 130 | + if (!buf_need(b, n)) return; | ||
| 131 | + memcpy(b->p + b->n, s, n); | ||
| 132 | + b->n += n; | ||
| 133 | + b->p[b->n] = '\0'; | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +static void buf_puts(buf_t *b, const char *s) | ||
| 137 | +{ | ||
| 138 | + if (s) buf_add(b, s, strlen(s)); | ||
| 139 | +} | ||
| 140 | + | ||
| 141 | +static void buf_putc(buf_t *b, char c) | ||
| 142 | +{ | ||
| 143 | + buf_add(b, &c, 1); | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +static const char *buf_str(buf_t *b) | ||
| 147 | +{ | ||
| 148 | + return b->p ? b->p : ""; | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +static void buf_free(buf_t *b) | ||
| 152 | +{ | ||
| 153 | + free(b->p); | ||
| 154 | + buf_init(b); | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +/* ------------------------------------------------------------------ */ | ||
| 158 | +/* Small utilities */ | ||
| 159 | +/* ------------------------------------------------------------------ */ | ||
| 160 | + | ||
| 161 | +static void str_copy(char *dst, size_t sz, const char *src) | ||
| 162 | +{ | ||
| 163 | + size_t n; | ||
| 164 | + if (!dst || sz == 0) return; | ||
| 165 | + if (!src) { dst[0] = '\0'; return; } | ||
| 166 | + n = strlen(src); | ||
| 167 | + if (n >= sz) n = sz - 1; | ||
| 168 | + memcpy(dst, src, n); | ||
| 169 | + dst[n] = '\0'; | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +static void path_join(char *out, size_t sz, const char *a, const char *b) | ||
| 173 | +{ | ||
| 174 | + size_t n; | ||
| 175 | + if (!out || sz == 0) return; | ||
| 176 | + out[0] = '\0'; | ||
| 177 | + if (!a) a = ""; | ||
| 178 | + if (!b) b = ""; | ||
| 179 | + str_copy(out, sz, a); | ||
| 180 | + n = strlen(out); | ||
| 181 | + if (n && out[n - 1] != '/' && out[n - 1] != '\\' && n + 1 < sz) { | ||
| 182 | + out[n++] = '/'; | ||
| 183 | + out[n] = '\0'; | ||
| 184 | + } | ||
| 185 | + if (n + strlen(b) < sz) str_copy(out + n, sz - n, b); | ||
| 186 | +} | ||
| 187 | + | ||
| 188 | +static void url_decode(char *s) | ||
| 189 | +{ | ||
| 190 | + char *o = s; | ||
| 191 | + if (!s) return; | ||
| 192 | + while (*s) { | ||
| 193 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | ||
| 194 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | ||
| 195 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | ||
| 196 | + *o++ = (char)((hi << 4) | lo); | ||
| 197 | + s += 3; | ||
| 198 | + } else if (*s == '+') { | ||
| 199 | + *o++ = ' '; | ||
| 200 | + s++; | ||
| 201 | + } else { | ||
| 202 | + *o++ = *s++; | ||
| 203 | + } | ||
| 204 | + } | ||
| 205 | + *o = '\0'; | ||
| 206 | +} | ||
| 207 | + | ||
| 208 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 209 | +{ | ||
| 210 | + size_t klen; | ||
| 211 | + const char *p; | ||
| 212 | + | ||
| 213 | + if (!out || outsz == 0) return 0; | ||
| 214 | + out[0] = '\0'; | ||
| 215 | + if (!qs || !key) return 0; | ||
| 216 | + klen = strlen(key); | ||
| 217 | + | ||
| 218 | + for (p = qs; *p; ) { | ||
| 219 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | ||
| 220 | + const char *v = p + klen + 1; | ||
| 221 | + size_t i = 0; | ||
| 222 | + while (*v && *v != '&' && i + 1 < outsz) | ||
| 223 | + out[i++] = *v++; | ||
| 224 | + out[i] = '\0'; | ||
| 225 | + url_decode(out); | ||
| 226 | + return 1; | ||
| 227 | + } | ||
| 228 | + p = strchr(p, '&'); | ||
| 229 | + if (!p) break; | ||
| 230 | + p++; | ||
| 231 | + } | ||
| 232 | + return 0; | ||
| 233 | +} | ||
| 234 | + | ||
| 235 | +static void json_str(buf_t *b, const char *s) | ||
| 236 | +{ | ||
| 237 | + buf_putc(b, '"'); | ||
| 238 | + for (; s && *s; s++) { | ||
| 239 | + unsigned char c = (unsigned char)*s; | ||
| 240 | + switch (c) { | ||
| 241 | + case '"': buf_puts(b, "\\\""); break; | ||
| 242 | + case '\\': buf_puts(b, "\\\\"); break; | ||
| 243 | + case '\n': buf_puts(b, "\\n"); break; | ||
| 244 | + case '\r': buf_puts(b, "\\r"); break; | ||
| 245 | + case '\t': buf_puts(b, "\\t"); break; | ||
| 246 | + default: | ||
| 247 | + if (c < 0x20) { | ||
| 248 | + char tmp[8]; | ||
| 249 | + sprintf(tmp, "\\u%04x", c); | ||
| 250 | + buf_puts(b, tmp); | ||
| 251 | + } else { | ||
| 252 | + buf_putc(b, (char)c); | ||
| 253 | + } | ||
| 254 | + } | ||
| 255 | + } | ||
| 256 | + buf_putc(b, '"'); | ||
| 257 | +} | ||
| 258 | + | ||
| 259 | +static void iso_now(char *out, size_t sz) | ||
| 260 | +{ | ||
| 261 | + time_t t = time(NULL); | ||
| 262 | + struct tm tmv; | ||
| 263 | +#if defined(_WIN32) | ||
| 264 | + gmtime_s(&tmv, &t); | ||
| 265 | +#else | ||
| 266 | + gmtime_r(&t, &tmv); | ||
| 267 | +#endif | ||
| 268 | + strftime(out, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); | ||
| 269 | +} | ||
| 270 | + | ||
| 271 | +static int valid_id(const char *id) | ||
| 272 | +{ | ||
| 273 | + int i; | ||
| 274 | + if (!id) return 0; | ||
| 275 | + if (strlen(id) != ID_LEN) return 0; | ||
| 276 | + for (i = 0; i < ID_LEN; i++) { | ||
| 277 | + char c = id[i]; | ||
| 278 | + if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))) return 0; | ||
| 279 | + } | ||
| 280 | + return 1; | ||
| 281 | +} | ||
| 282 | + | ||
| 283 | +static void gen_id(char *out) | ||
| 284 | +{ | ||
| 285 | + static const char *alpha = "abcdefghijklmnopqrstuvwxyz0123456789"; | ||
| 286 | + unsigned int seed; | ||
| 287 | + int i; | ||
| 288 | +#if defined(_WIN32) | ||
| 289 | + seed = (unsigned int)GetTickCount() ^ (unsigned int)time(NULL); | ||
| 290 | +#else | ||
| 291 | + seed = (unsigned int)time(NULL) ^ ((unsigned int)getpid() << 16); | ||
| 292 | +#endif | ||
| 293 | + seed ^= (unsigned int)(size_t)out; | ||
| 294 | + seed = seed * 1103515245u + 12345u; | ||
| 295 | + for (i = 0; i < ID_LEN; i++) { | ||
| 296 | + seed = seed * 1103515245u + 12345u; | ||
| 297 | + out[i] = alpha[(seed >> 16) % 36u]; | ||
| 298 | + } | ||
| 299 | + out[ID_LEN] = '\0'; | ||
| 300 | +} | ||
| 301 | + | ||
| 302 | +/* ------------------------------------------------------------------ */ | ||
| 303 | +/* Filesystem helpers */ | ||
| 304 | +/* ------------------------------------------------------------------ */ | ||
| 305 | + | ||
| 306 | +static void mkdir_one(const char *p) | ||
| 307 | +{ | ||
| 308 | +#if defined(_WIN32) | ||
| 309 | + _mkdir(p); | ||
| 310 | +#else | ||
| 311 | + mkdir(p, 0700); | ||
| 312 | +#endif | ||
| 313 | +} | ||
| 314 | + | ||
| 315 | +static int path_is_dir(const char *p) | ||
| 316 | +{ | ||
| 317 | +#if defined(_WIN32) | ||
| 318 | + DWORD a = GetFileAttributesA(p); | ||
| 319 | + return a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY); | ||
| 320 | +#else | ||
| 321 | + struct stat st; | ||
| 322 | + return stat(p, &st) == 0 && S_ISDIR(st.st_mode); | ||
| 323 | +#endif | ||
| 324 | +} | ||
| 325 | + | ||
| 326 | +static int file_exists(const char *p) | ||
| 327 | +{ | ||
| 328 | +#if defined(_WIN32) | ||
| 329 | + return GetFileAttributesA(p) != INVALID_FILE_ATTRIBUTES; | ||
| 330 | +#else | ||
| 331 | + return access(p, F_OK) == 0; | ||
| 332 | +#endif | ||
| 333 | +} | ||
| 334 | + | ||
| 335 | +/* Atomic replace: write to <dst>.tmp, then move it over <dst>. */ | ||
| 336 | +static int atomic_write(const char *dst, const char *data, size_t len) | ||
| 337 | +{ | ||
| 338 | + char tmp[PATH_SZ + 8]; | ||
| 339 | + FILE *f; | ||
| 340 | + size_t wrote; | ||
| 341 | + | ||
| 342 | + if (!dst || strlen(dst) + 5 >= sizeof tmp) return 0; | ||
| 343 | + sprintf(tmp, "%s.tmp", dst); | ||
| 344 | + | ||
| 345 | + f = fopen(tmp, "wb"); | ||
| 346 | + if (!f) return 0; | ||
| 347 | + wrote = fwrite(data, 1, len, f); | ||
| 348 | + if (fflush(f) != 0) { fclose(f); remove(tmp); return 0; } | ||
| 349 | +#if !defined(_WIN32) | ||
| 350 | + fsync(fileno(f)); | ||
| 351 | +#endif | ||
| 352 | + if (fclose(f) != 0) { remove(tmp); return 0; } | ||
| 353 | + if (wrote != len) { remove(tmp); return 0; } | ||
| 354 | + | ||
| 355 | +#if defined(_WIN32) | ||
| 356 | + if (!MoveFileExA(tmp, dst, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { | ||
| 357 | + remove(tmp); | ||
| 358 | + return 0; | ||
| 359 | + } | ||
| 360 | +#else | ||
| 361 | + if (rename(tmp, dst) != 0) { remove(tmp); return 0; } | ||
| 362 | +#endif | ||
| 363 | + return 1; | ||
| 364 | +} | ||
| 365 | + | ||
| 366 | +static char *read_whole_file(const char *path, size_t *out_len) | ||
| 367 | +{ | ||
| 368 | + FILE *f; | ||
| 369 | + long sz; | ||
| 370 | + char *p; | ||
| 371 | + size_t got; | ||
| 372 | + | ||
| 373 | + f = fopen(path, "rb"); | ||
| 374 | + if (!f) return NULL; | ||
| 375 | + if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; } | ||
| 376 | + sz = ftell(f); | ||
| 377 | + if (sz < 0) { fclose(f); return NULL; } | ||
| 378 | + if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; } | ||
| 379 | + p = (char *)malloc((size_t)sz + 1); | ||
| 380 | + if (!p) { fclose(f); return NULL; } | ||
| 381 | + got = fread(p, 1, (size_t)sz, f); | ||
| 382 | + fclose(f); | ||
| 383 | + p[got] = '\0'; | ||
| 384 | + if (out_len) *out_len = got; | ||
| 385 | + return p; | ||
| 386 | +} | ||
| 387 | + | ||
| 388 | +/* ------------------------------------------------------------------ */ | ||
| 389 | +/* Tiny JSON reader (only what index.json and the save payload need) */ | ||
| 390 | +/* ------------------------------------------------------------------ */ | ||
| 391 | + | ||
| 392 | +/* Copy a JSON string value starting at *pp (which points at the opening | ||
| 393 | + * quote) into out. Returns 1 on success and advances *pp past the closing | ||
| 394 | + * quote. Handles the escapes this plugin can emit plus \uXXXX as UTF-8. */ | ||
| 395 | +static int json_read_string(const char **pp, char *out, size_t outsz) | ||
| 396 | +{ | ||
| 397 | + const char *p = *pp; | ||
| 398 | + size_t o = 0; | ||
| 399 | + | ||
| 400 | + if (!p || *p != '"') return 0; | ||
| 401 | + p++; | ||
| 402 | + while (*p && *p != '"') { | ||
| 403 | + unsigned char c = (unsigned char)*p; | ||
| 404 | + if (c == '\\') { | ||
| 405 | + p++; | ||
| 406 | + switch (*p) { | ||
| 407 | + case '"': c = '"'; break; | ||
| 408 | + case '\\': c = '\\'; break; | ||
| 409 | + case '/': c = '/'; break; | ||
| 410 | + case 'b': c = '\b'; break; | ||
| 411 | + case 'f': c = '\f'; break; | ||
| 412 | + case 'n': c = '\n'; break; | ||
| 413 | + case 'r': c = '\r'; break; | ||
| 414 | + case 't': c = '\t'; break; | ||
| 415 | + case 'u': { | ||
| 416 | + unsigned int cp = 0; | ||
| 417 | + int i; | ||
| 418 | + for (i = 0; i < 4 && p[1]; i++) { | ||
| 419 | + char h = p[1 + i]; | ||
| 420 | + cp <<= 4; | ||
| 421 | + if (h >= '0' && h <= '9') cp |= (unsigned)(h - '0'); | ||
| 422 | + else if (h >= 'a' && h <= 'f') cp |= (unsigned)(h - 'a' + 10); | ||
| 423 | + else if (h >= 'A' && h <= 'F') cp |= (unsigned)(h - 'A' + 10); | ||
| 424 | + } | ||
| 425 | + p += 4; | ||
| 426 | + /* BMP only; enough for the control characters we emit */ | ||
| 427 | + if (cp == 0) { | ||
| 428 | + c = 0; | ||
| 429 | + } else if (cp < 0x80) { | ||
| 430 | + c = (unsigned char)cp; | ||
| 431 | + } else if (cp < 0x800) { | ||
| 432 | + if (o + 1 < outsz) out[o++] = (char)(0xC0 | (cp >> 6)); | ||
| 433 | + c = (unsigned char)(0x80 | (cp & 0x3F)); | ||
| 434 | + } else { | ||
| 435 | + if (o + 2 < outsz) { | ||
| 436 | + out[o++] = (char)(0xE0 | (cp >> 12)); | ||
| 437 | + out[o++] = (char)(0x80 | ((cp >> 6) & 0x3F)); | ||
| 438 | + } | ||
| 439 | + c = (unsigned char)(0x80 | (cp & 0x3F)); | ||
| 440 | + } | ||
| 441 | + if (c == 0) { p++; continue; } | ||
| 442 | + break; | ||
| 443 | + } | ||
| 444 | + default: c = (unsigned char)*p; break; | ||
| 445 | + } | ||
| 446 | + p++; | ||
| 447 | + } else { | ||
| 448 | + p++; | ||
| 449 | + } | ||
| 450 | + if (o + 1 < outsz) out[o++] = (char)c; | ||
| 451 | + } | ||
| 452 | + if (*p == '"') p++; | ||
| 453 | + if (outsz) out[o < outsz ? o : outsz - 1] = '\0'; | ||
| 454 | + *pp = p; | ||
| 455 | + return 1; | ||
| 456 | +} | ||
| 457 | + | ||
| 458 | +/* Read a JSON string into a freshly allocated buffer. Bodies can be 512 KiB, | ||
| 459 | + * so they must never land in a fixed-size stack frame. */ | ||
| 460 | +static char *json_dup_string(const char **pp) | ||
| 461 | +{ | ||
| 462 | + const char *p = *pp; | ||
| 463 | + buf_t b; | ||
| 464 | + | ||
| 465 | + if (!p || *p != '"') return NULL; | ||
| 466 | + buf_init(&b); | ||
| 467 | + if (!buf_need(&b, 0)) return NULL; | ||
| 468 | + p++; | ||
| 469 | + | ||
| 470 | + while (*p && *p != '"') { | ||
| 471 | + unsigned char c = (unsigned char)*p; | ||
| 472 | + if (c == '\\') { | ||
| 473 | + p++; | ||
| 474 | + switch (*p) { | ||
| 475 | + case '"': c = '"'; break; | ||
| 476 | + case '\\': c = '\\'; break; | ||
| 477 | + case '/': c = '/'; break; | ||
| 478 | + case 'b': c = '\b'; break; | ||
| 479 | + case 'f': c = '\f'; break; | ||
| 480 | + case 'n': c = '\n'; break; | ||
| 481 | + case 'r': c = '\r'; break; | ||
| 482 | + case 't': c = '\t'; break; | ||
| 483 | + case 'u': { | ||
| 484 | + unsigned int cp = 0; | ||
| 485 | + int i; | ||
| 486 | + for (i = 0; i < 4 && p[1]; i++) { | ||
| 487 | + char h = p[1 + i]; | ||
| 488 | + cp <<= 4; | ||
| 489 | + if (h >= '0' && h <= '9') cp |= (unsigned)(h - '0'); | ||
| 490 | + else if (h >= 'a' && h <= 'f') cp |= (unsigned)(h - 'a' + 10); | ||
| 491 | + else if (h >= 'A' && h <= 'F') cp |= (unsigned)(h - 'A' + 10); | ||
| 492 | + } | ||
| 493 | + p += 4; | ||
| 494 | + if (cp < 0x80 && cp) { | ||
| 495 | + buf_putc(&b, (char)cp); | ||
| 496 | + } else if (cp >= 0x80 && cp < 0x800) { | ||
| 497 | + buf_putc(&b, (char)(0xC0 | (cp >> 6))); | ||
| 498 | + buf_putc(&b, (char)(0x80 | (cp & 0x3F))); | ||
| 499 | + } else if (cp >= 0x800) { | ||
| 500 | + buf_putc(&b, (char)(0xE0 | (cp >> 12))); | ||
| 501 | + buf_putc(&b, (char)(0x80 | ((cp >> 6) & 0x3F))); | ||
| 502 | + buf_putc(&b, (char)(0x80 | (cp & 0x3F))); | ||
| 503 | + } | ||
| 504 | + p++; | ||
| 505 | + continue; | ||
| 506 | + } | ||
| 507 | + default: c = (unsigned char)*p; break; | ||
| 508 | + } | ||
| 509 | + p++; | ||
| 510 | + } else { | ||
| 511 | + p++; | ||
| 512 | + } | ||
| 513 | + buf_putc(&b, (char)c); | ||
| 514 | + } | ||
| 515 | + if (*p == '"') p++; | ||
| 516 | + *pp = p; | ||
| 517 | + if (!b.p) { char *e = (char *)malloc(1); if (e) e[0] = '\0'; return e; } | ||
| 518 | + return b.p; | ||
| 519 | +} | ||
| 520 | + | ||
| 521 | +/* Find `"key"` in a flat object body and copy its string value. */ | ||
| 522 | +static int json_find_str(const char *json, const char *key, char *out, size_t outsz) | ||
| 523 | +{ | ||
| 524 | + char pat[64]; | ||
| 525 | + const char *p; | ||
| 526 | + | ||
| 527 | + if (!json || !key) return 0; | ||
| 528 | + sprintf(pat, "\"%s\"", key); | ||
| 529 | + p = json; | ||
| 530 | + while ((p = strstr(p, pat)) != NULL) { | ||
| 531 | + const char *q = p + strlen(pat); | ||
| 532 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | ||
| 533 | + if (*q == ':') { | ||
| 534 | + q++; | ||
| 535 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | ||
| 536 | + if (*q == '"') return json_read_string(&q, out, outsz); | ||
| 537 | + return 0; | ||
| 538 | + } | ||
| 539 | + p += strlen(pat); | ||
| 540 | + } | ||
| 541 | + return 0; | ||
| 542 | +} | ||
| 543 | + | ||
| 544 | +/* Same, for a small non-negative integer (accepts a quoted form too). */ | ||
| 545 | +static int json_find_int(const char *json, const char *key, int *out) | ||
| 546 | +{ | ||
| 547 | + char pat[64]; | ||
| 548 | + char raw[32]; | ||
| 549 | + const char *p; | ||
| 550 | + | ||
| 551 | + if (!json || !key) return 0; | ||
| 552 | + sprintf(pat, "\"%s\"", key); | ||
| 553 | + p = json; | ||
| 554 | + while ((p = strstr(p, pat)) != NULL) { | ||
| 555 | + const char *q = p + strlen(pat); | ||
| 556 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | ||
| 557 | + if (*q == ':') { | ||
| 558 | + q++; | ||
| 559 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | ||
| 560 | + if (*q == '"') { | ||
| 561 | + if (!json_read_string(&q, raw, sizeof raw)) return 0; | ||
| 562 | + } else if (strncmp(q, "true", 4) == 0) { | ||
| 563 | + *out = 1; /* a JSON boolean is not a string */ | ||
| 564 | + return 1; | ||
| 565 | + } else if (strncmp(q, "false", 5) == 0) { | ||
| 566 | + *out = 0; | ||
| 567 | + return 1; | ||
| 568 | + } else { | ||
| 569 | + size_t i = 0; | ||
| 570 | + while (q[i] && (isdigit((unsigned char)q[i]) || q[i] == '-') && i + 1 < sizeof raw) { | ||
| 571 | + raw[i] = q[i]; | ||
| 572 | + i++; | ||
| 573 | + } | ||
| 574 | + raw[i] = '\0'; | ||
| 575 | + } | ||
| 576 | + *out = atoi(raw); | ||
| 577 | + return 1; | ||
| 578 | + } | ||
| 579 | + p += strlen(pat); | ||
| 580 | + } | ||
| 581 | + return 0; | ||
| 582 | +} | ||
| 583 | + | ||
| 584 | +/* ------------------------------------------------------------------ */ | ||
| 585 | +/* Node authentication */ | ||
| 586 | +/* ------------------------------------------------------------------ */ | ||
| 587 | + | ||
| 588 | +static void require_node_auth(void) | ||
| 589 | +{ | ||
| 590 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 591 | + const char *xp; | ||
| 592 | + const char *auth; | ||
| 593 | + const char *qs; | ||
| 594 | + char qpwd[256]; | ||
| 595 | + | ||
| 596 | + if (!np || !*np) return; | ||
| 597 | + | ||
| 598 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | ||
| 599 | + if (xp && strcmp(xp, np) == 0) return; | ||
| 600 | + | ||
| 601 | + auth = getenv("HTTP_AUTHORIZATION"); | ||
| 602 | + if (auth) { | ||
| 603 | + while (*auth == ' ') auth++; | ||
| 604 | + if (strncmp(auth, "Bearer ", 7) == 0) { | ||
| 605 | + auth += 7; | ||
| 606 | + while (*auth == ' ') auth++; | ||
| 607 | + if (strcmp(auth, np) == 0) return; | ||
| 608 | + } | ||
| 609 | + } | ||
| 610 | + | ||
| 611 | + qs = getenv("QUERY_STRING"); | ||
| 612 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) | ||
| 613 | + return; | ||
| 614 | + | ||
| 615 | + fputs("Status: 401 Unauthorized\r\n" | ||
| 616 | + "Content-Type: application/json; charset=utf-8\r\n" | ||
| 617 | + "Cache-Control: no-store\r\n" | ||
| 618 | + "X-Content-Type-Options: nosniff\r\n\r\n" | ||
| 619 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | ||
| 620 | + exit(0); | ||
| 621 | +} | ||
| 622 | + | ||
| 623 | +/* ------------------------------------------------------------------ */ | ||
| 624 | +/* Notes directory resolution */ | ||
| 625 | +/* ------------------------------------------------------------------ */ | ||
| 626 | + | ||
| 627 | +static int ensure_notes_dir(void) | ||
| 628 | +{ | ||
| 629 | + char base[PATH_SZ]; | ||
| 630 | + const char *env = getenv("NOTES_DIR"); | ||
| 631 | + const char *bp; | ||
| 632 | + | ||
| 633 | + if (g_dir[0]) return 1; | ||
| 634 | + | ||
| 635 | + if (env && *env) { | ||
| 636 | + str_copy(base, sizeof base, env); | ||
| 637 | + } else if ((bp = getenv("BOT_PLUGIN_DIR")) != NULL && *bp) { | ||
| 638 | + str_copy(base, sizeof base, bp); | ||
| 639 | + mkdir_one(base); | ||
| 640 | + path_join(g_dir, sizeof g_dir, base, ".notes"); | ||
| 641 | + mkdir_one(g_dir); | ||
| 642 | + path_join(g_trash, sizeof g_trash, g_dir, TRASH_DIR); | ||
| 643 | + mkdir_one(g_trash); | ||
| 644 | + return path_is_dir(g_dir); | ||
| 645 | + } else { | ||
| 646 | +#if defined(_WIN32) | ||
| 647 | + const char *la = getenv("LOCALAPPDATA"); | ||
| 648 | + char p1[PATH_SZ], p2[PATH_SZ]; | ||
| 649 | + if (la && *la) { | ||
| 650 | + path_join(p1, sizeof p1, la, "scorpiox"); | ||
| 651 | + } else { | ||
| 652 | + const char *up = getenv("USERPROFILE"); | ||
| 653 | + if (up && *up) path_join(p1, sizeof p1, up, ".scorpiox"); | ||
| 654 | + else str_copy(p1, sizeof p1, "."); | ||
| 655 | + } | ||
| 656 | + mkdir_one(p1); | ||
| 657 | + path_join(p2, sizeof p2, p1, "plugins"); | ||
| 658 | + mkdir_one(p2); | ||
| 659 | + path_join(base, sizeof base, p2, ".notes"); | ||
| 660 | +#else | ||
| 661 | + const char *home = getenv("HOME"); | ||
| 662 | + #if defined(__APPLE__) | ||
| 663 | + if (access("/workspace", W_OK) == 0) { | ||
| 664 | + char p2[PATH_SZ]; | ||
| 665 | + path_join(p2, sizeof p2, "/workspace/.scorpiox", "plugins"); | ||
| 666 | + mkdir_one(p2); | ||
| 667 | + path_join(base, sizeof base, p2, ".notes"); | ||
| 668 | + } else | ||
| 669 | + #endif | ||
| 670 | + if (home && *home) { | ||
| 671 | + char p1[PATH_SZ], p2[PATH_SZ]; | ||
| 672 | + path_join(p1, sizeof p1, home, ".scorpiox"); | ||
| 673 | + mkdir_one(p1); | ||
| 674 | + path_join(p2, sizeof p2, p1, "plugins"); | ||
| 675 | + mkdir_one(p2); | ||
| 676 | + path_join(base, sizeof base, p2, ".notes"); | ||
| 677 | + } else { | ||
| 678 | + str_copy(base, sizeof base, ".notes"); | ||
| 679 | + } | ||
| 680 | +#endif | ||
| 681 | + } | ||
| 682 | + | ||
| 683 | + str_copy(g_dir, sizeof g_dir, base); | ||
| 684 | + mkdir_one(g_dir); | ||
| 685 | + path_join(g_trash, sizeof g_trash, g_dir, TRASH_DIR); | ||
| 686 | + mkdir_one(g_trash); | ||
| 687 | + return path_is_dir(g_dir); | ||
| 688 | +} | ||
| 689 | + | ||
| 690 | +static void note_path(char *out, size_t sz, const char *id) | ||
| 691 | +{ | ||
| 692 | + char name[32]; | ||
| 693 | + sprintf(name, "%s.md", id); | ||
| 694 | + path_join(out, sz, g_dir, name); | ||
| 695 | +} | ||
| 696 | + | ||
| 697 | +static void index_path(char *out, size_t sz) | ||
| 698 | +{ | ||
| 699 | + path_join(out, sz, g_dir, "index.json"); | ||
| 700 | +} | ||
| 701 | + | ||
| 702 | +/* Read index.json into g_meta[]. A missing index is an empty store, and a | ||
| 703 | + * truncated one loses the metadata but never the .md bodies. */ | ||
| 704 | +static void load_index(void) | ||
| 705 | +{ | ||
| 706 | + char path[PATH_SZ]; | ||
| 707 | + char *text; | ||
| 708 | + const char *p; | ||
| 709 | + | ||
| 710 | + g_count = 0; | ||
| 711 | + index_path(path, sizeof path); | ||
| 712 | + text = read_whole_file(path, NULL); | ||
| 713 | + if (!text) return; | ||
| 714 | + | ||
| 715 | + p = text; | ||
| 716 | + /* Walk every object inside the top-level array. */ | ||
| 717 | + while ((p = strchr(p, '{')) != NULL) { | ||
| 718 | + const char *end = strchr(p, '}'); | ||
| 719 | + char obj[8192]; | ||
| 720 | + size_t n; | ||
| 721 | + note_meta_t m; | ||
| 722 | + | ||
| 723 | + if (!end) break; | ||
| 724 | + n = (size_t)(end - p) + 1; | ||
| 725 | + if (n >= sizeof obj) n = sizeof obj - 1; | ||
| 726 | + memcpy(obj, p, n); | ||
| 727 | + obj[n] = '\0'; | ||
| 728 | + p = end + 1; | ||
| 729 | + | ||
| 730 | + memset(&m, 0, sizeof m); | ||
| 731 | + if (!json_find_str(obj, "id", m.id, sizeof m.id)) continue; | ||
| 732 | + if (!valid_id(m.id)) continue; | ||
| 733 | + if (!json_find_str(obj, "title", m.title, sizeof m.title)) | ||
| 734 | + str_copy(m.title, sizeof m.title, ""); | ||
| 735 | + json_find_int(obj, "pinned", &m.pinned); | ||
| 736 | + if (!json_find_str(obj, "created", m.created, sizeof m.created)) | ||
| 737 | + m.created[0] = '\0'; | ||
| 738 | + if (!json_find_str(obj, "updated", m.updated, sizeof m.updated)) | ||
| 739 | + m.updated[0] = '\0'; | ||
| 740 | + | ||
| 741 | + if (g_count < MAX_NOTES) g_meta[g_count++] = m; | ||
| 742 | + } | ||
| 743 | + free(text); | ||
| 744 | +} | ||
| 745 | + | ||
| 746 | +static int meta_find(const char *id) | ||
| 747 | +{ | ||
| 748 | + int i; | ||
| 749 | + for (i = 0; i < g_count; i++) | ||
| 750 | + if (strcmp(g_meta[i].id, id) == 0) return i; | ||
| 751 | + return -1; | ||
| 752 | +} | ||
| 753 | + | ||
| 754 | +/* Pinned first, then most recently updated. */ | ||
| 755 | +static int meta_cmp(const note_meta_t *a, const note_meta_t *b) | ||
| 756 | +{ | ||
| 757 | + if (a->pinned != b->pinned) return b->pinned - a->pinned; | ||
| 758 | + return strcmp(b->updated, a->updated); | ||
| 759 | +} | ||
| 760 | + | ||
| 761 | +static void sort_meta(void) | ||
| 762 | +{ | ||
| 763 | + int i, j; | ||
| 764 | + for (i = 1; i < g_count; i++) { | ||
| 765 | + note_meta_t key = g_meta[i]; | ||
| 766 | + j = i - 1; | ||
| 767 | + while (j >= 0 && meta_cmp(&g_meta[j], &key) > 0) { | ||
| 768 | + g_meta[j + 1] = g_meta[j]; | ||
| 769 | + j--; | ||
| 770 | + } | ||
| 771 | + g_meta[j + 1] = key; | ||
| 772 | + } | ||
| 773 | +} | ||
| 774 | + | ||
| 775 | +static int save_index(void) | ||
| 776 | +{ | ||
| 777 | + buf_t b; | ||
| 778 | + char path[PATH_SZ]; | ||
| 779 | + int i, ok; | ||
| 780 | + | ||
| 781 | + buf_init(&b); | ||
| 782 | + buf_puts(&b, "{\"version\":1,\"notes\":[\n"); | ||
| 783 | + for (i = 0; i < g_count; i++) { | ||
| 784 | + buf_puts(&b, i ? ",\n" : ""); | ||
| 785 | + buf_puts(&b, " {\"id\":"); | ||
| 786 | + json_str(&b, g_meta[i].id); | ||
| 787 | + buf_puts(&b, ",\"title\":"); | ||
| 788 | + json_str(&b, g_meta[i].title); | ||
| 789 | + buf_puts(&b, ",\"pinned\":"); | ||
| 790 | + buf_putc(&b, g_meta[i].pinned ? '1' : '0'); | ||
| 791 | + buf_puts(&b, ",\"created\":"); | ||
| 792 | + json_str(&b, g_meta[i].created); | ||
| 793 | + buf_puts(&b, ",\"updated\":"); | ||
| 794 | + json_str(&b, g_meta[i].updated); | ||
| 795 | + buf_putc(&b, '}'); | ||
| 796 | + } | ||
| 797 | + buf_puts(&b, "\n]}\n"); | ||
| 798 | + | ||
| 799 | + index_path(path, sizeof path); | ||
| 800 | + ok = atomic_write(path, buf_str(&b), b.n); | ||
| 801 | + buf_free(&b); | ||
| 802 | + return ok; | ||
| 803 | +} | ||
| 804 | + | ||
| 805 | +/* ------------------------------------------------------------------ */ | ||
| 806 | +/* Markdown -> HTML (server side, escaped first) */ | ||
| 807 | +/* ------------------------------------------------------------------ */ | ||
| 808 | + | ||
| 809 | +static void esc_html_into(buf_t *b, const char *s, size_t n) | ||
| 810 | +{ | ||
| 811 | + size_t i; | ||
| 812 | + for (i = 0; i < n; i++) { | ||
| 813 | + switch (s[i]) { | ||
| 814 | + case '&': buf_puts(b, "&"); break; | ||
| 815 | + case '<': buf_puts(b, "<"); break; | ||
| 816 | + case '>': buf_puts(b, ">"); break; | ||
| 817 | + case '"': buf_puts(b, """); break; | ||
| 818 | + case '\'': buf_puts(b, "'"); break; | ||
| 819 | + default: buf_putc(b, s[i]); | ||
| 820 | + } | ||
| 821 | + } | ||
| 822 | +} | ||
| 823 | + | ||
| 824 | +static int url_is_safe(const char *u) | ||
| 825 | +{ | ||
| 826 | + size_t i; | ||
| 827 | + if (!u || !*u) return 0; | ||
| 828 | + if (u[0] == '/' || u[0] == '#') return 1; | ||
| 829 | + for (i = 0; u[i]; i++) { | ||
| 830 | + unsigned char c = (unsigned char)u[i]; | ||
| 831 | + if (c == ':' || c == '/' || c == '?' || c == '#' || c == '&' || | ||
| 832 | + c == '=' || c == '.' || c == '_' || c == '-' || c == '%' || | ||
| 833 | + c == '+' || c == '~' || c == '@' || c == ',') continue; | ||
| 834 | + if (c <= ' ') return 0; | ||
| 835 | + } | ||
| 836 | + if (strncmp(u, "https://", 8) == 0 || strncmp(u, "http://", 7) == 0 || | ||
| 837 | + strncmp(u, "mailto:", 7) == 0) | ||
| 838 | + return 1; | ||
| 839 | + return 0; | ||
| 840 | +} | ||
| 841 | + | ||
| 842 | +/* Escape a run of raw note text into the output buffer. Every literal | ||
| 843 | + * character in a note goes through here, so note content can never emit a | ||
| 844 | + * tag, an attribute or a script. */ | ||
| 845 | +static void esc_into(buf_t *b, const char *s, size_t n) | ||
| 846 | +{ | ||
| 847 | + size_t i; | ||
| 848 | + for (i = 0; i < n; i++) { | ||
| 849 | + switch (s[i]) { | ||
| 850 | + case '&': buf_puts(b, "&"); break; | ||
| 851 | + case '<': buf_puts(b, "<"); break; | ||
| 852 | + case '>': buf_puts(b, ">"); break; | ||
| 853 | + case '"': buf_puts(b, """); break; | ||
| 854 | + case '\'': buf_puts(b, "'"); break; | ||
| 855 | + default: buf_putc(b, s[i]); | ||
| 856 | + } | ||
| 857 | + } | ||
| 858 | +} | ||
| 859 | + | ||
| 860 | +/* Inline pass over raw text: **bold**, *italic*, `code`, [text](url). | ||
| 861 | + * Everything it emits is a fixed tag name and every literal byte is escaped, | ||
| 862 | + * so the only attribute in the output is a URL that passed url_is_safe(). */ | ||
| 863 | +static void inline_into(buf_t *b, const char *s) | ||
| 864 | +{ | ||
| 865 | + size_t i = 0; | ||
| 866 | + size_t n = strlen(s); | ||
| 867 | + | ||
| 868 | + while (i < n) { | ||
| 869 | + char c = s[i]; | ||
| 870 | + | ||
| 871 | + /* `code` - content is escaped like any other literal text */ | ||
| 872 | + if (c == '`') { | ||
| 873 | + const char *close = strchr(s + i + 1, '`'); | ||
| 874 | + if (close && close > s + i + 1) { | ||
| 875 | + buf_puts(b, "<code>"); | ||
| 876 | + esc_into(b, s + i + 1, (size_t)(close - (s + i + 1))); | ||
| 877 | + buf_puts(b, "</code>"); | ||
| 878 | + i = (size_t)(close - s) + 1; | ||
| 879 | + continue; | ||
| 880 | + } | ||
| 881 | + } | ||
| 882 | + | ||
| 883 | + /* **bold** */ | ||
| 884 | + if (c == '*' && i + 1 < n && s[i + 1] == '*') { | ||
| 885 | + const char *close = strstr(s + i + 2, "**"); | ||
| 886 | + if (close && close > s + i + 2) { | ||
| 887 | + buf_puts(b, "<strong>"); | ||
| 888 | + esc_into(b, s + i + 2, (size_t)(close - (s + i + 2))); | ||
| 889 | + buf_puts(b, "</strong>"); | ||
| 890 | + i = (size_t)(close - s) + 2; | ||
| 891 | + continue; | ||
| 892 | + } | ||
| 893 | + } | ||
| 894 | + | ||
| 895 | + /* *italic* / _italic_ */ | ||
| 896 | + if (c == '*' || c == '_') { | ||
| 897 | + const char *close = strchr(s + i + 1, c); | ||
| 898 | + if (close && close > s + i + 1 && !isspace((unsigned char)s[i + 1])) { | ||
| 899 | + buf_puts(b, "<em>"); | ||
| 900 | + esc_into(b, s + i + 1, (size_t)(close - (s + i + 1))); | ||
| 901 | + buf_puts(b, "</em>"); | ||
| 902 | + i = (size_t)(close - s) + 1; | ||
| 903 | + continue; | ||
| 904 | + } | ||
| 905 | + } | ||
| 906 | + | ||
| 907 | + /* [text](url) - the href is emitted only when url_is_safe() agrees */ | ||
| 908 | + if (c == '[') { | ||
| 909 | + const char *rb = strchr(s + i + 1, ']'); | ||
| 910 | + if (rb && rb[1] == '(') { | ||
| 911 | + const char *rp = strchr(rb + 2, ')'); | ||
| 912 | + if (rp) { | ||
| 913 | + char url[512]; | ||
| 914 | + size_t ul = (size_t)(rp - (rb + 2)); | ||
| 915 | + if (ul < sizeof url) { | ||
| 916 | + memcpy(url, rb + 2, ul); | ||
| 917 | + url[ul] = '\0'; | ||
| 918 | + if (url_is_safe(url)) { | ||
| 919 | + buf_puts(b, "<a href=\""); | ||
| 920 | + esc_into(b, url, ul); | ||
| 921 | + buf_puts(b, "\" rel=\"noopener noreferrer\" target=\"_blank\">"); | ||
| 922 | + esc_into(b, s + i + 1, (size_t)(rb - (s + i + 1))); | ||
| 923 | + buf_puts(b, "</a>"); | ||
| 924 | + i = (size_t)(rp - s) + 1; | ||
| 925 | + continue; | ||
| 926 | + } | ||
| 927 | + } | ||
| 928 | + } | ||
| 929 | + } | ||
| 930 | + } | ||
| 931 | + | ||
| 932 | + esc_into(b, &c, 1); | ||
| 933 | + i++; | ||
| 934 | + } | ||
| 935 | +} | ||
| 936 | + | ||
| 937 | +/* Render one raw line's inline markup. */ | ||
| 938 | +static void inline_line(buf_t *b, const char *line, size_t len) | ||
| 939 | +{ | ||
| 940 | + char *tmp = (char *)malloc(len + 1); | ||
| 941 | + if (!tmp) return; | ||
| 942 | + memcpy(tmp, line, len); | ||
| 943 | + tmp[len] = '\0'; | ||
| 944 | + inline_into(b, tmp); | ||
| 945 | + free(tmp); | ||
| 946 | +} | ||
| 947 | + | ||
| 948 | +static void render_markdown(buf_t *out, const char *md) | ||
| 949 | +{ | ||
| 950 | + const char *p = md ? md : ""; | ||
| 951 | + int in_code = 0; | ||
| 952 | + int in_list = 0; | ||
| 953 | + int in_olist = 0; | ||
| 954 | + int para_open = 0; | ||
| 955 | + buf_t esc; | ||
| 956 | + | ||
| 957 | + buf_init(&esc); | ||
| 958 | + | ||
| 959 | + while (*p) { | ||
| 960 | + const char *eol = strchr(p, '\n'); | ||
| 961 | + size_t len = eol ? (size_t)(eol - p) : strlen(p); | ||
| 962 | + char line[4096]; | ||
| 963 | + size_t l = len < sizeof line - 1 ? len : sizeof line - 1; | ||
| 964 | + | ||
| 965 | + memcpy(line, p, l); | ||
| 966 | + line[l] = '\0'; | ||
| 967 | + while (l > 0 && line[l - 1] == '\r') line[--l] = '\0'; | ||
| 968 | + | ||
| 969 | + if (in_code) { | ||
| 970 | + if (l >= 3 && line[0] == '`' && line[1] == '`' && line[2] == '`') { | ||
| 971 | + buf_puts(out, "</code></pre>\n"); | ||
| 972 | + in_code = 0; | ||
| 973 | + } else { | ||
| 974 | + esc_html_into(out, line, l); | ||
| 975 | + buf_putc(out, '\n'); | ||
| 976 | + } | ||
| 977 | + p = eol ? eol + 1 : p + len; | ||
| 978 | + continue; | ||
| 979 | + } | ||
| 980 | + | ||
| 981 | + if (l >= 3 && line[0] == '`' && line[1] == '`' && line[2] == '`') { | ||
| 982 | + if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; } | ||
| 983 | + if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; } | ||
| 984 | + if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; } | ||
| 985 | + buf_puts(out, "<pre><code>"); | ||
| 986 | + in_code = 1; | ||
| 987 | + p = eol ? eol + 1 : p + len; | ||
| 988 | + continue; | ||
| 989 | + } | ||
| 990 | + | ||
| 991 | + if (l == 0) { | ||
| 992 | + if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; } | ||
| 993 | + if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; } | ||
| 994 | + if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; } | ||
| 995 | + p = eol ? eol + 1 : p + len; | ||
| 996 | + continue; | ||
| 997 | + } | ||
| 998 | + | ||
| 999 | + /* horizontal rule */ | ||
| 1000 | + if (l >= 3 && (line[0] == '-' || line[0] == '*' || line[0] == '_')) { | ||
| 1001 | + int all = 1, j; | ||
| 1002 | + char ch = line[0]; | ||
| 1003 | + int cnt = 0; | ||
| 1004 | + for (j = 0; j < (int)l; j++) { | ||
| 1005 | + if (line[j] == ch) cnt++; | ||
| 1006 | + else if (line[j] != ' ') { all = 0; break; } | ||
| 1007 | + } | ||
| 1008 | + if (all && cnt >= 3) { | ||
| 1009 | + if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; } | ||
| 1010 | + if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; } | ||
| 1011 | + if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; } | ||
| 1012 | + buf_puts(out, "<hr>\n"); | ||
| 1013 | + p = eol ? eol + 1 : p + len; | ||
| 1014 | + continue; | ||
| 1015 | + } | ||
| 1016 | + } | ||
| 1017 | + | ||
| 1018 | + /* heading */ | ||
| 1019 | + if (line[0] == '#') { | ||
| 1020 | + int n = 0, j = 0; | ||
| 1021 | + while (j < (int)l && line[j] == '#' && n < 6) { n++; j++; } | ||
| 1022 | + if (n > 0 && (j >= (int)l || line[j] == ' ')) { | ||
| 1023 | + char tag[8]; | ||
| 1024 | + if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; } | ||
| 1025 | + if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; } | ||
| 1026 | + if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; } | ||
| 1027 | + while (j < (int)l && line[j] == ' ') j++; | ||
| 1028 | + sprintf(tag, "h%d", n); | ||
| 1029 | + buf_puts(out, "<"); buf_puts(out, tag); buf_puts(out, ">"); | ||
| 1030 | + while (l > (size_t)j && line[l - 1] == '#') l--; | ||
| 1031 | + while (l > (size_t)j && line[l - 1] == ' ') l--; | ||
| 1032 | + inline_line(out, line + j, l - (size_t)j); | ||
| 1033 | + buf_puts(out, "</"); buf_puts(out, tag); buf_puts(out, ">\n"); | ||
| 1034 | + p = eol ? eol + 1 : p + len; | ||
| 1035 | + continue; | ||
| 1036 | + } | ||
| 1037 | + } | ||
| 1038 | + | ||
| 1039 | + /* blockquote */ | ||
| 1040 | + if (line[0] == '>') { | ||
| 1041 | + size_t j = 1; | ||
| 1042 | + if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; } | ||
| 1043 | + if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; } | ||
| 1044 | + if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; } | ||
| 1045 | + while (j < l && line[j] == ' ') j++; | ||
| 1046 | + buf_puts(out, "<blockquote>"); | ||
| 1047 | + inline_line(out, line + j, l - j); | ||
| 1048 | + buf_puts(out, "</blockquote>\n"); | ||
| 1049 | + p = eol ? eol + 1 : p + len; | ||
| 1050 | + continue; | ||
| 1051 | + } | ||
| 1052 | + | ||
| 1053 | + /* unordered list item */ | ||
| 1054 | + if ((line[0] == '-' || line[0] == '*' || line[0] == '+') && l > 1 && line[1] == ' ') { | ||
| 1055 | + if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; } | ||
| 1056 | + if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; } | ||
| 1057 | + if (!in_list) { buf_puts(out, "<ul>\n"); in_list = 1; } | ||
| 1058 | + buf_puts(out, "<li>"); | ||
| 1059 | + inline_line(out, line + 2, l - 2); | ||
| 1060 | + buf_puts(out, "</li>\n"); | ||
| 1061 | + p = eol ? eol + 1 : p + len; | ||
| 1062 | + continue; | ||
| 1063 | + } | ||
| 1064 | + | ||
| 1065 | + /* ordered list item */ | ||
| 1066 | + if (isdigit((unsigned char)line[0])) { | ||
| 1067 | + size_t j = 0; | ||
| 1068 | + while (j < l && isdigit((unsigned char)line[j])) j++; | ||
| 1069 | + if (j < l && line[j] == '.' && j + 1 < l && line[j + 1] == ' ') { | ||
| 1070 | + if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; } | ||
| 1071 | + if (para_open) { buf_puts(out, "</p>\n"); para_open = 0; } | ||
| 1072 | + if (!in_olist) { buf_puts(out, "<ol>\n"); in_olist = 1; } | ||
| 1073 | + buf_puts(out, "<li>"); | ||
| 1074 | + inline_line(out, line + j + 2, l - j - 2); | ||
| 1075 | + buf_puts(out, "</li>\n"); | ||
| 1076 | + p = eol ? eol + 1 : p + len; | ||
| 1077 | + continue; | ||
| 1078 | + } | ||
| 1079 | + } | ||
| 1080 | + | ||
| 1081 | + /* paragraph text (consecutive lines join with a space) */ | ||
| 1082 | + if (in_list) { buf_puts(out, "</ul>\n"); in_list = 0; } | ||
| 1083 | + if (in_olist) { buf_puts(out, "</ol>\n"); in_olist = 0; } | ||
| 1084 | + if (para_open) buf_putc(out, ' '); | ||
| 1085 | + else { buf_puts(out, "<p>"); para_open = 1; } | ||
| 1086 | + inline_line(out, line, l); | ||
| 1087 | + p = eol ? eol + 1 : p + len; | ||
| 1088 | + } | ||
| 1089 | + | ||
| 1090 | + if (in_code) buf_puts(out, "</code></pre>\n"); | ||
| 1091 | + if (in_list) buf_puts(out, "</ul>\n"); | ||
| 1092 | + if (in_olist) buf_puts(out, "</ol>\n"); | ||
| 1093 | + if (para_open) buf_puts(out, "</p>\n"); | ||
| 1094 | + buf_free(&esc); | ||
| 1095 | +} | ||
| 1096 | + | ||
| 1097 | +/* ------------------------------------------------------------------ */ | ||
| 1098 | +/* Request body */ | ||
| 1099 | +/* ------------------------------------------------------------------ */ | ||
| 1100 | + | ||
| 1101 | +/* Read the POST body only when the frontend actually sent one (guarded on | ||
| 1102 | + * CONTENT_LENGTH, so an inherited empty stdin never blocks the process), | ||
| 1103 | + * and never beyond REQ_MAX. */ | ||
| 1104 | +static int read_request_body(char *out, size_t sz) | ||
| 1105 | +{ | ||
| 1106 | + const char *cl = getenv("CONTENT_LENGTH"); | ||
| 1107 | + long len; | ||
| 1108 | + size_t got; | ||
| 1109 | + | ||
| 1110 | + if (!out || sz == 0) return 0; | ||
| 1111 | + out[0] = '\0'; | ||
| 1112 | + if (!cl || !*cl) return 0; | ||
| 1113 | + len = strtol(cl, NULL, 10); | ||
| 1114 | + if (len <= 0) return 0; | ||
| 1115 | + if ((size_t)len >= sz) return -1; /* too large -> caller answers 413 */ | ||
| 1116 | + got = fread(out, 1, (size_t)len, stdin); | ||
| 1117 | + out[got] = '\0'; | ||
| 1118 | + return (int)got; | ||
| 1119 | +} | ||
| 1120 | + | ||
| 1121 | +static void json_header(void) | ||
| 1122 | +{ | ||
| 1123 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | ||
| 1124 | + "Cache-Control: no-store\r\n" | ||
| 1125 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 1126 | +} | ||
| 1127 | + | ||
| 1128 | +static void json_err(int code, const char *status, const char *msg) | ||
| 1129 | +{ | ||
| 1130 | + if (code == 400) | ||
| 1131 | + fputs("Status: 400 Bad Request\r\n", stdout); | ||
| 1132 | + else if (code == 404) | ||
| 1133 | + fputs("Status: 404 Not Found\r\n", stdout); | ||
| 1134 | + else if (code == 413) | ||
| 1135 | + fputs("Status: 413 Payload Too Large\r\n", stdout); | ||
| 1136 | + else if (code == 500) | ||
| 1137 | + fputs("Status: 500 Internal Server Error\r\n", stdout); | ||
| 1138 | + json_header(); | ||
| 1139 | + printf("{\"ok\":false,\"error\":"); | ||
| 1140 | + { | ||
| 1141 | + buf_t b; | ||
| 1142 | + buf_init(&b); | ||
| 1143 | + json_str(&b, msg ? msg : status); | ||
| 1144 | + fputs(buf_str(&b), stdout); | ||
| 1145 | + buf_free(&b); | ||
| 1146 | + } | ||
| 1147 | + fputs("}\n", stdout); | ||
| 1148 | +} | ||
| 1149 | + | ||
| 1150 | +/* ------------------------------------------------------------------ */ | ||
| 1151 | +/* API actions */ | ||
| 1152 | +/* ------------------------------------------------------------------ */ | ||
| 1153 | + | ||
| 1154 | +/* Push the metadata rows, optionally filtered, onto the response. */ | ||
| 1155 | +static void emit_list(const char *only_id, const char *needle) | ||
| 1156 | +{ | ||
| 1157 | + buf_t rows, env; | ||
| 1158 | + int i, shown = 0; | ||
| 1159 | + char lneedle[256]; | ||
| 1160 | + | ||
| 1161 | + buf_init(&rows); | ||
| 1162 | + buf_init(&env); | ||
| 1163 | + | ||
| 1164 | + if (needle) { | ||
| 1165 | + size_t k; | ||
| 1166 | + str_copy(lneedle, sizeof lneedle, needle); | ||
| 1167 | + for (k = 0; lneedle[k]; k++) | ||
| 1168 | + lneedle[k] = (char)tolower((unsigned char)lneedle[k]); | ||
| 1169 | + } else { | ||
| 1170 | + lneedle[0] = '\0'; | ||
| 1171 | + } | ||
| 1172 | + | ||
| 1173 | + for (i = 0; i < g_count; i++) { | ||
| 1174 | + char path[PATH_SZ]; | ||
| 1175 | + char *body = NULL; | ||
| 1176 | + int match = 1; | ||
| 1177 | + | ||
| 1178 | + if (only_id && strcmp(g_meta[i].id, only_id) != 0) continue; | ||
| 1179 | + | ||
| 1180 | + if (lneedle[0]) { | ||
| 1181 | + char ltitle[TITLE_MAX]; | ||
| 1182 | + size_t k, j; | ||
| 1183 | + | ||
| 1184 | + str_copy(ltitle, sizeof ltitle, g_meta[i].title); | ||
| 1185 | + for (k = 0; ltitle[k]; k++) | ||
| 1186 | + ltitle[k] = (char)tolower((unsigned char)ltitle[k]); | ||
| 1187 | + match = strstr(ltitle, lneedle) != NULL; | ||
| 1188 | + | ||
| 1189 | + if (!match) { | ||
| 1190 | + note_path(path, sizeof path, g_meta[i].id); | ||
| 1191 | + body = read_whole_file(path, NULL); | ||
| 1192 | + if (body) { | ||
| 1193 | + size_t n = strlen(body); | ||
| 1194 | + for (j = 0; j < n; j++) | ||
| 1195 | + body[j] = (char)tolower((unsigned char)body[j]); | ||
| 1196 | + match = strstr(body, lneedle) != NULL; | ||
| 1197 | + body[j] = '\0'; | ||
| 1198 | + } | ||
| 1199 | + free(body); | ||
| 1200 | + } | ||
| 1201 | + } | ||
| 1202 | + | ||
| 1203 | + if (!match) continue; | ||
| 1204 | + | ||
| 1205 | + buf_puts(&rows, shown ? ",\n {\"id\":" : "\n {\"id\":"); | ||
| 1206 | + json_str(&rows, g_meta[i].id); | ||
| 1207 | + buf_puts(&rows, ",\"title\":"); | ||
| 1208 | + json_str(&rows, g_meta[i].title); | ||
| 1209 | + buf_puts(&rows, ",\"pinned\":"); | ||
| 1210 | + buf_putc(&rows, g_meta[i].pinned ? '1' : '0'); | ||
| 1211 | + buf_puts(&rows, ",\"created\":"); | ||
| 1212 | + json_str(&rows, g_meta[i].created); | ||
| 1213 | + buf_puts(&rows, ",\"updated\":"); | ||
| 1214 | + json_str(&rows, g_meta[i].updated); | ||
| 1215 | + buf_putc(&rows, '}'); | ||
| 1216 | + shown++; | ||
| 1217 | + } | ||
| 1218 | + | ||
| 1219 | + buf_puts(&env, "{\"ok\":true,\"count\":"); | ||
| 1220 | + { | ||
| 1221 | + char num[16]; | ||
| 1222 | + sprintf(num, "%d", shown); | ||
| 1223 | + buf_puts(&env, num); | ||
| 1224 | + } | ||
| 1225 | + buf_puts(&env, ",\"notes\":["); | ||
| 1226 | + buf_puts(&env, buf_str(&rows)); | ||
| 1227 | + buf_puts(&env, shown ? "\n]}\n" : "]}\n"); | ||
| 1228 | + fwrite(buf_str(&env), 1, env.n, stdout); | ||
| 1229 | + | ||
| 1230 | + buf_free(&rows); | ||
| 1231 | + buf_free(&env); | ||
| 1232 | +} | ||
| 1233 | + | ||
| 1234 | +static void do_list(void) | ||
| 1235 | +{ | ||
| 1236 | + json_header(); | ||
| 1237 | + emit_list(NULL, NULL); | ||
| 1238 | +} | ||
| 1239 | + | ||
| 1240 | +static void do_search(const char *q) | ||
| 1241 | +{ | ||
| 1242 | + json_header(); | ||
| 1243 | + emit_list(NULL, (q && *q) ? q : NULL); | ||
| 1244 | +} | ||
| 1245 | + | ||
| 1246 | +static void do_get(const char *id) | ||
| 1247 | +{ | ||
| 1248 | + int idx; | ||
| 1249 | + char path[PATH_SZ]; | ||
| 1250 | + char *body; | ||
| 1251 | + | ||
| 1252 | + if (!valid_id(id)) { json_err(400, "Bad Request", "invalid id"); return; } | ||
| 1253 | + idx = meta_find(id); | ||
| 1254 | + if (idx < 0) { json_err(404, "Not Found", "note not found"); return; } | ||
| 1255 | + | ||
| 1256 | + note_path(path, sizeof path, id); | ||
| 1257 | + body = read_whole_file(path, NULL); | ||
| 1258 | + | ||
| 1259 | + json_header(); | ||
| 1260 | + { | ||
| 1261 | + buf_t b; | ||
| 1262 | + buf_init(&b); | ||
| 1263 | + buf_puts(&b, "{\"ok\":true,\"note\":{\"id\":"); | ||
| 1264 | + json_str(&b, g_meta[idx].id); | ||
| 1265 | + buf_puts(&b, ",\"title\":"); | ||
| 1266 | + json_str(&b, g_meta[idx].title); | ||
| 1267 | + buf_puts(&b, ",\"pinned\":"); | ||
| 1268 | + buf_putc(&b, g_meta[idx].pinned ? '1' : '0'); | ||
| 1269 | + buf_puts(&b, ",\"created\":"); | ||
| 1270 | + json_str(&b, g_meta[idx].created); | ||
| 1271 | + buf_puts(&b, ",\"updated\":"); | ||
| 1272 | + json_str(&b, g_meta[idx].updated); | ||
| 1273 | + buf_puts(&b, ",\"body\":"); | ||
| 1274 | + json_str(&b, body ? body : ""); | ||
| 1275 | + buf_puts(&b, "}}\n"); | ||
| 1276 | + fwrite(buf_str(&b), 1, b.n, stdout); | ||
| 1277 | + buf_free(&b); | ||
| 1278 | + } | ||
| 1279 | + free(body); | ||
| 1280 | +} | ||
| 1281 | + | ||
| 1282 | +static void do_save(const char *body_json) | ||
| 1283 | +{ | ||
| 1284 | + char id[64] = ""; | ||
| 1285 | + char title[TITLE_MAX] = ""; | ||
| 1286 | + char *body = NULL; | ||
| 1287 | + int pinned = 0; | ||
| 1288 | + int idx; | ||
| 1289 | + char path[PATH_SZ]; | ||
| 1290 | + char now[24]; | ||
| 1291 | + note_meta_t m; | ||
| 1292 | + | ||
| 1293 | + if (!body_json || !*body_json) { | ||
| 1294 | + json_err(400, "Bad Request", "empty body"); | ||
| 1295 | + return; | ||
| 1296 | + } | ||
| 1297 | + | ||
| 1298 | + json_find_str(body_json, "id", id, sizeof id); | ||
| 1299 | + json_find_str(body_json, "title", title, sizeof title); | ||
| 1300 | + | ||
| 1301 | + /* The body is the only large field: take it straight out of the JSON. */ | ||
| 1302 | + { | ||
| 1303 | + const char *p = strstr(body_json, "\"body\""); | ||
| 1304 | + if (p) { | ||
| 1305 | + const char *q = p + 6; | ||
| 1306 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | ||
| 1307 | + if (*q == ':') { | ||
| 1308 | + q++; | ||
| 1309 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | ||
| 1310 | + if (*q == '"') body = json_dup_string(&q); | ||
| 1311 | + } | ||
| 1312 | + } | ||
| 1313 | + } | ||
| 1314 | + if (!body) { | ||
| 1315 | + json_err(400, "Bad Request", "missing body field"); | ||
| 1316 | + return; | ||
| 1317 | + } | ||
| 1318 | + if (strlen(body) > (size_t)BODY_MAX) { | ||
| 1319 | + free(body); | ||
| 1320 | + json_err(413, "Payload Too Large", "note body exceeds 512 KiB"); | ||
| 1321 | + return; | ||
| 1322 | + } | ||
| 1323 | + | ||
| 1324 | + if (id[0] && !valid_id(id)) { | ||
| 1325 | + free(body); | ||
| 1326 | + json_err(400, "Bad Request", "invalid id"); | ||
| 1327 | + return; | ||
| 1328 | + } | ||
| 1329 | + | ||
| 1330 | + if (!json_find_int(body_json, "pinned", &pinned)) pinned = 0; | ||
| 1331 | + pinned = pinned ? 1 : 0; | ||
| 1332 | + | ||
| 1333 | + iso_now(now, sizeof now); | ||
| 1334 | + | ||
| 1335 | + idx = id[0] ? meta_find(id) : -1; | ||
| 1336 | + memset(&m, 0, sizeof m); | ||
| 1337 | + if (idx >= 0) { | ||
| 1338 | + m = g_meta[idx]; | ||
| 1339 | + if (json_find_int(body_json, "pinned", &pinned)) m.pinned = pinned ? 1 : 0; | ||
| 1340 | + } else { | ||
| 1341 | + if (id[0]) str_copy(m.id, sizeof m.id, id); | ||
| 1342 | + else gen_id(m.id); | ||
| 1343 | + str_copy(m.created, sizeof m.created, now); | ||
| 1344 | + m.pinned = pinned; | ||
| 1345 | + } | ||
| 1346 | + str_copy(m.title, sizeof m.title, title); | ||
| 1347 | + str_copy(m.updated, sizeof m.updated, now); | ||
| 1348 | + | ||
| 1349 | + /* Write the body first: a metadata row must never point at a note that | ||
| 1350 | + * was never written. */ | ||
| 1351 | + note_path(path, sizeof path, m.id); | ||
| 1352 | + if (!atomic_write(path, body, strlen(body))) { | ||
| 1353 | + free(body); | ||
| 1354 | + json_err(500, "Internal Server Error", "could not write note"); | ||
| 1355 | + return; | ||
| 1356 | + } | ||
| 1357 | + free(body); | ||
| 1358 | + | ||
| 1359 | + if (idx >= 0) g_meta[idx] = m; | ||
| 1360 | + else if (g_count < MAX_NOTES) g_meta[g_count++] = m; | ||
| 1361 | + else { json_err(500, "Internal Server Error", "note limit reached"); return; } | ||
| 1362 | + | ||
| 1363 | + sort_meta(); | ||
| 1364 | + if (!save_index()) { | ||
| 1365 | + json_err(500, "Internal Server Error", "could not write index"); | ||
| 1366 | + return; | ||
| 1367 | + } | ||
| 1368 | + | ||
| 1369 | + json_header(); | ||
| 1370 | + { | ||
| 1371 | + buf_t b; | ||
| 1372 | + buf_init(&b); | ||
| 1373 | + buf_puts(&b, "{\"ok\":true,\"note\":{\"id\":"); | ||
| 1374 | + json_str(&b, m.id); | ||
| 1375 | + buf_puts(&b, ",\"title\":"); | ||
| 1376 | + json_str(&b, m.title); | ||
| 1377 | + buf_puts(&b, ",\"pinned\":"); | ||
| 1378 | + buf_putc(&b, m.pinned ? '1' : '0'); | ||
| 1379 | + buf_puts(&b, ",\"created\":"); | ||
| 1380 | + json_str(&b, m.created); | ||
| 1381 | + buf_puts(&b, ",\"updated\":"); | ||
| 1382 | + json_str(&b, m.updated); | ||
| 1383 | + buf_puts(&b, "}}\n"); | ||
| 1384 | + fwrite(buf_str(&b), 1, b.n, stdout); | ||
| 1385 | + buf_free(&b); | ||
| 1386 | + } | ||
| 1387 | +} | ||
| 1388 | + | ||
| 1389 | +static void do_pin(const char *id, const char *body_json, const char *qs) | ||
| 1390 | +{ | ||
| 1391 | + int idx, pin = -1; | ||
| 1392 | + char v[16]; | ||
| 1393 | + | ||
| 1394 | + if (!valid_id(id)) { json_err(400, "Bad Request", "invalid id"); return; } | ||
| 1395 | + idx = meta_find(id); | ||
| 1396 | + if (idx < 0) { json_err(404, "Not Found", "note not found"); return; } | ||
| 1397 | + | ||
| 1398 | + if (!json_find_int(body_json ? body_json : "", "pin", &pin)) { | ||
| 1399 | + if (qs && get_query_val(qs, "pin", v, sizeof v)) pin = atoi(v); | ||
| 1400 | + } | ||
| 1401 | + if (pin < 0) pin = g_meta[idx].pinned ? 0 : 1; | ||
| 1402 | + | ||
| 1403 | + g_meta[idx].pinned = pin ? 1 : 0; | ||
| 1404 | + iso_now(g_meta[idx].updated, sizeof g_meta[idx].updated); | ||
| 1405 | + sort_meta(); | ||
| 1406 | + if (!save_index()) { json_err(500, "Internal Server Error", "could not write index"); return; } | ||
| 1407 | + | ||
| 1408 | + json_header(); | ||
| 1409 | + printf("{\"ok\":true,\"id\":\"%s\",\"pinned\":%d}\n", id, g_meta[meta_find(id)].pinned); | ||
| 1410 | +} | ||
| 1411 | + | ||
| 1412 | +static void do_delete(const char *id) | ||
| 1413 | +{ | ||
| 1414 | + int idx, i; | ||
| 1415 | + char src[PATH_SZ], dst[PATH_SZ], name[32]; | ||
| 1416 | + | ||
| 1417 | + if (!valid_id(id)) { json_err(400, "Bad Request", "invalid id"); return; } | ||
| 1418 | + idx = meta_find(id); | ||
| 1419 | + if (idx < 0) { json_err(404, "Not Found", "note not found"); return; } | ||
| 1420 | + | ||
| 1421 | + note_path(src, sizeof src, id); | ||
| 1422 | + sprintf(name, "%s.md", id); | ||
| 1423 | + path_join(dst, sizeof dst, g_trash, name); | ||
| 1424 | + | ||
| 1425 | + if (file_exists(src)) { | ||
| 1426 | + /* Keep a copy in .trash so a wrong click is recoverable. */ | ||
| 1427 | +#if defined(_WIN32) | ||
| 1428 | + MoveFileExA(src, dst, MOVEFILE_REPLACE_EXISTING); | ||
| 1429 | +#else | ||
| 1430 | + rename(src, dst); | ||
| 1431 | +#endif | ||
| 1432 | + } | ||
| 1433 | + | ||
| 1434 | + for (i = idx; i < g_count - 1; i++) g_meta[i] = g_meta[i + 1]; | ||
| 1435 | + if (g_count > 0) g_count--; | ||
| 1436 | + | ||
| 1437 | + if (!save_index()) { json_err(500, "Internal Server Error", "could not write index"); return; } | ||
| 1438 | + | ||
| 1439 | + json_header(); | ||
| 1440 | + printf("{\"ok\":true,\"deleted\":\"%s\",\"trash\":true}\n", id); | ||
| 1441 | +} | ||
| 1442 | + | ||
| 1443 | +static void do_render(const char *body_json, const char *qs) | ||
| 1444 | +{ | ||
| 1445 | + char *text = NULL; | ||
| 1446 | + buf_t out; | ||
| 1447 | + | ||
| 1448 | + if (body_json && *body_json) { | ||
| 1449 | + const char *p = strstr(body_json, "\"body\""); | ||
| 1450 | + if (p) { | ||
| 1451 | + const char *q = p + 6; | ||
| 1452 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | ||
| 1453 | + if (*q == ':') { | ||
| 1454 | + q++; | ||
| 1455 | + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') q++; | ||
| 1456 | + if (*q == '"') text = json_dup_string(&q); | ||
| 1457 | + } | ||
| 1458 | + } | ||
| 1459 | + } | ||
| 1460 | + if (!text && qs) { | ||
| 1461 | + /* Convenience for GET callers; capped so a URL cannot allocate much. */ | ||
| 1462 | + char tmp[8192]; | ||
| 1463 | + if (get_query_val(qs, "text", tmp, sizeof tmp)) { | ||
| 1464 | + text = (char *)malloc(strlen(tmp) + 1); | ||
| 1465 | + if (text) str_copy(text, strlen(tmp) + 1, tmp); | ||
| 1466 | + } | ||
| 1467 | + } | ||
| 1468 | + if (!text) { | ||
| 1469 | + json_err(400, "Bad Request", "missing body field"); | ||
| 1470 | + return; | ||
| 1471 | + } | ||
| 1472 | + if (strlen(text) > (size_t)BODY_MAX) { | ||
| 1473 | + free(text); | ||
| 1474 | + json_err(413, "Payload Too Large", "note body exceeds 512 KiB"); | ||
| 1475 | + return; | ||
| 1476 | + } | ||
| 1477 | + | ||
| 1478 | + buf_init(&out); | ||
| 1479 | + render_markdown(&out, text); | ||
| 1480 | + | ||
| 1481 | + json_header(); | ||
| 1482 | + { | ||
| 1483 | + buf_t b; | ||
| 1484 | + buf_init(&b); | ||
| 1485 | + buf_puts(&b, "{\"ok\":true,\"html\":"); | ||
| 1486 | + json_str(&b, buf_str(&out)); | ||
| 1487 | + buf_puts(&b, "}\n"); | ||
| 1488 | + fwrite(buf_str(&b), 1, b.n, stdout); | ||
| 1489 | + buf_free(&b); | ||
| 1490 | + } | ||
| 1491 | + buf_free(&out); | ||
| 1492 | + free(text); | ||
| 1493 | +} | ||
| 1494 | + | ||
| 1495 | +/* ------------------------------------------------------------------ */ | ||
| 1496 | +/* HTML mode */ | ||
| 1497 | +/* ------------------------------------------------------------------ */ | ||
| 1498 | + | ||
| 1499 | +/* Split UI_HTML on the two control-byte placeholders and expand them into | ||
| 1500 | + * the theme macros, so the page and the bot palette can never drift. */ | ||
| 1501 | +static void emit_ui(int embed) | ||
| 1502 | +{ | ||
| 1503 | + const char *p = UI_HTML; | ||
| 1504 | + | ||
| 1505 | + while (*p) { | ||
| 1506 | + if (*p == '\001') { | ||
| 1507 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS | ||
| 1508 | + ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);--ac:var(--blue)}" | ||
| 1509 | + "</style>", stdout); | ||
| 1510 | + p++; | ||
| 1511 | + } else if (*p == '\002') { | ||
| 1512 | + fputs(SX_BOT_THEME_HANDOFF, stdout); | ||
| 1513 | + p++; | ||
| 1514 | + } else { | ||
| 1515 | + putchar(*p++); | ||
| 1516 | + } | ||
| 1517 | + } | ||
| 1518 | + (void)embed; | ||
| 1519 | +} | ||
| 1520 | + | ||
| 1521 | +static void mode_html(int embed) | ||
| 1522 | +{ | ||
| 1523 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | ||
| 1524 | + "Cache-Control: no-store\r\n" | ||
| 1525 | + "X-Content-Type-Options: nosniff\r\n" | ||
| 1526 | + "X-Frame-Options: SAMEORIGIN\r\n" | ||
| 1527 | + "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " | ||
| 1528 | + "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " | ||
| 1529 | + "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); | ||
| 1530 | + emit_ui(embed); | ||
| 1531 | +} | ||
| 1532 | + | ||
| 1533 | +/* ------------------------------------------------------------------ */ | ||
| 1534 | +/* Entry */ | ||
| 1535 | +/* ------------------------------------------------------------------ */ | ||
| 1536 | + | ||
| 1537 | +static const char *method(void) | ||
| 1538 | +{ | ||
| 1539 | + const char *m = getenv("REQUEST_METHOD"); | ||
| 1540 | + return (m && *m) ? m : "GET"; | ||
| 1541 | +} | ||
| 1542 | + | ||
| 1543 | +int main(int argc, char **argv) | ||
| 1544 | +{ | ||
| 1545 | + const char *qs; | ||
| 1546 | + const char *req_method; | ||
| 1547 | + char action[64]; | ||
| 1548 | + char id[64]; | ||
| 1549 | + char val[256]; | ||
| 1550 | + static char body[REQ_MAX]; | ||
| 1551 | + int got; | ||
| 1552 | + | ||
| 1553 | + /* 1. Discovery metadata (unauthenticated so /plugins can probe it) */ | ||
| 1554 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { | ||
| 1555 | + printf("{\"name\":\"%s\",\"desc\":\"%s\"}\n", PLUGIN_NAME, PLUGIN_DESC); | ||
| 1556 | + return 0; | ||
| 1557 | + } | ||
| 1558 | + if (argc > 1 && strcmp(argv[1], "--version") == 0) { | ||
| 1559 | + printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); | ||
| 1560 | + return 0; | ||
| 1561 | + } | ||
| 1562 | + | ||
| 1563 | + require_node_auth(); | ||
| 1564 | + | ||
| 1565 | + qs = getenv("QUERY_STRING"); | ||
| 1566 | + if (!qs) qs = ""; | ||
| 1567 | + req_method = method(); | ||
| 1568 | + | ||
| 1569 | + action[0] = '\0'; | ||
| 1570 | + id[0] = '\0'; | ||
| 1571 | + get_query_val(qs, "action", action, sizeof action); | ||
| 1572 | + get_query_val(qs, "id", id, sizeof id); | ||
| 1573 | + | ||
| 1574 | + /* 2. Anything that names an action, asks for JSON, or POSTs is API. */ | ||
| 1575 | + if (action[0] || strstr(qs, "format=json") || strcmp(req_method, "POST") == 0) { | ||
| 1576 | + int action_present = action[0] != '\0'; | ||
| 1577 | + char act[64]; | ||
| 1578 | + | ||
| 1579 | + if (!action_present) { | ||
| 1580 | + char fmt[32]; | ||
| 1581 | + if (get_query_val(qs, "format", fmt, sizeof fmt) && strcmp(fmt, "json") == 0) | ||
| 1582 | + str_copy(action, sizeof action, "list"); | ||
| 1583 | + else | ||
| 1584 | + str_copy(action, sizeof action, "list"); | ||
| 1585 | + } | ||
| 1586 | + /* Keep two buffers: reading `format` into `action` would clobber the | ||
| 1587 | + * action we just parsed (lesson (l) in the market tracker). */ | ||
| 1588 | + str_copy(act, sizeof act, action); | ||
| 1589 | + | ||
| 1590 | + if (!ensure_notes_dir()) { json_err(500, "Internal Server Error", "notes dir unavailable"); return 0; } | ||
| 1591 | + load_index(); | ||
| 1592 | + | ||
| 1593 | + got = read_request_body(body, sizeof body); | ||
| 1594 | + if (got < 0) { json_err(413, "Payload Too Large", "request body too large"); return 0; } | ||
| 1595 | + | ||
| 1596 | + if (strcmp(act, "list") == 0) { | ||
| 1597 | + do_list(); | ||
| 1598 | + } else if (strcmp(act, "get") == 0) { | ||
| 1599 | + do_get(id); | ||
| 1600 | + } else if (strcmp(act, "search") == 0) { | ||
| 1601 | + val[0] = '\0'; | ||
| 1602 | + get_query_val(qs, "q", val, sizeof val); | ||
| 1603 | + do_search(val); | ||
| 1604 | + } else if (strcmp(act, "save") == 0) { | ||
| 1605 | + do_save(body); | ||
| 1606 | + } else if (strcmp(act, "delete") == 0) { | ||
| 1607 | + do_delete(id); | ||
| 1608 | + } else if (strcmp(act, "pin") == 0) { | ||
| 1609 | + do_pin(id, body, qs); | ||
| 1610 | + } else if (strcmp(act, "render") == 0) { | ||
| 1611 | + do_render(body, qs); | ||
| 1612 | + } else { | ||
| 1613 | + json_err(400, "Bad Request", "unknown action"); | ||
| 1614 | + } | ||
| 1615 | + return 0; | ||
| 1616 | + } | ||
| 1617 | + | ||
| 1618 | + /* 3. Everything else is the page. */ | ||
| 1619 | + { | ||
| 1620 | + int embed = strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL; | ||
| 1621 | + mode_html(embed); | ||
| 1622 | + } | ||
| 1623 | + return 0; | ||
| 1624 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..90603fd | index 0000000..90603fd | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui.html | +++ b/src/ui.html | ||
| @@ -0,0 +1,444 @@ | @@ -0,0 +1,444 @@ | ||
| 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>notes</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:288px 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 | +.icon{display:inline-flex;align-items:center;justify-content:center;gap:6px; | ||
| 21 | + background:var(--surface-2);border:1px solid var(--line);color:var(--text); | ||
| 22 | + border-radius:9px;width:30px;height:30px;padding:0;cursor:pointer;font-family:inherit; | ||
| 23 | + font-size:12px;font-weight:600} | ||
| 24 | +.icon:hover{background:var(--surface-hover);border-color:var(--line-2)} | ||
| 25 | +.icon:active{transform:scale(.96)} | ||
| 26 | +.icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor; | ||
| 27 | + stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round} | ||
| 28 | +.icon.danger{color:var(--red)} | ||
| 29 | +.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:6px 14px; | ||
| 30 | + font-weight:600;font-size:12.5px;cursor:pointer;font-family:inherit} | ||
| 31 | +.btn:active{transform:scale(.98)} | ||
| 32 | +.search{margin:0 12px 8px;padding:8px 11px;border-radius:9px;border:1px solid var(--line); | ||
| 33 | + background:var(--input-bg);color:var(--text);font-family:inherit;font-size:13px} | ||
| 34 | +.search:focus{outline:2px solid var(--blue);outline-offset:-1px} | ||
| 35 | +.list{flex:1 1 auto;overflow-y:auto;padding:0 8px 8px} | ||
| 36 | +.item{display:block;width:100%;text-align:left;background:transparent;border:0; | ||
| 37 | + border-radius:10px;padding:9px 10px;color:var(--text);cursor:pointer;font-family:inherit; | ||
| 38 | + margin-bottom:2px;position:relative} | ||
| 39 | +.item:hover{background:var(--surface-hover)} | ||
| 40 | +.item.sel{background:var(--surface-2);box-shadow:inset 2px 0 0 var(--blue)} | ||
| 41 | +.item .t{font-size:13.5px;font-weight:600;white-space:nowrap;overflow:hidden; | ||
| 42 | + text-overflow:ellipsis;padding-right:18px} | ||
| 43 | +.item .m{font-size:11px;color:var(--text-2);white-space:nowrap;overflow:hidden; | ||
| 44 | + text-overflow:ellipsis;margin-top:2px} | ||
| 45 | +.item .pinmark{position:absolute;top:9px;right:9px;width:11px;height:11px;color:var(--blue); | ||
| 46 | + display:none} | ||
| 47 | +.item.pinned .pinmark{display:block} | ||
| 48 | +.item .pinmark svg{width:11px;height:11px;fill:currentColor;stroke:none} | ||
| 49 | +.empty{padding:18px 12px;color:var(--text-2);font-size:12.5px;text-align:center} | ||
| 50 | +.hidden{display:none!important} | ||
| 51 | +#main{background:var(--bg)} | ||
| 52 | +.toolbar{display:flex;align-items:center;gap:8px;padding:10px 14px; | ||
| 53 | + border-bottom:1px solid var(--line);flex:0 0 auto;min-width:0} | ||
| 54 | +.toolbar .title{flex:1 1 auto;min-width:0;background:transparent;border:0;color:var(--text); | ||
| 55 | + font-family:inherit;font-size:16px;font-weight:650;padding:4px 2px;border-radius:6px} | ||
| 56 | +.toolbar .title:focus{outline:0;background:var(--input-bg);padding:4px 8px} | ||
| 57 | +.state{font-size:11px;font-weight:600;color:var(--text-2);white-space:nowrap; | ||
| 58 | + padding:2px 8px;border-radius:999px;background:var(--surface-2)} | ||
| 59 | +.state.dirty{color:var(--orange)} | ||
| 60 | +.state.ok{color:var(--green)} | ||
| 61 | +.back{display:none} | ||
| 62 | +.split{flex:1 1 auto;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr); | ||
| 63 | + min-height:0} | ||
| 64 | +.editor{width:100%;height:100%;resize:none;border:0;border-right:1px solid var(--line); | ||
| 65 | + background:var(--bg);color:var(--text);font-family:var(--mono);font-size:13px; | ||
| 66 | + line-height:1.65;padding:16px 18px;tab-size:2} | ||
| 67 | +.editor:focus{outline:0} | ||
| 68 | +.preview{overflow-y:auto;padding:16px 20px 40px;min-width:0} | ||
| 69 | +.preview h1,.preview h2,.preview h3,.preview h4,.preview h5,.preview h6{ | ||
| 70 | + line-height:1.25;margin:18px 0 8px;font-weight:650} | ||
| 71 | +.preview h1{font-size:24px;letter-spacing:-.01em} | ||
| 72 | +.preview h2{font-size:19px} | ||
| 73 | +.preview h3{font-size:16px} | ||
| 74 | +.preview h4,.preview h5,.preview h6{font-size:14px;color:var(--text-2)} | ||
| 75 | +.preview h1:first-child,.preview h2:first-child,.preview p:first-child{margin-top:0} | ||
| 76 | +.preview p{margin:0 0 10px} | ||
| 77 | +.preview ul,.preview ol{margin:0 0 10px;padding-left:22px} | ||
| 78 | +.preview li{margin:2px 0} | ||
| 79 | +.preview blockquote{margin:0 0 10px;padding:2px 12px;border-left:3px solid var(--line-2); | ||
| 80 | + color:var(--text-2)} | ||
| 81 | +.preview code{font-family:var(--mono);font-size:12px;background:var(--code-bg); | ||
| 82 | + padding:1px 5px;border-radius:5px} | ||
| 83 | +.preview pre{background:var(--code-bg);border:1px solid var(--line);border-radius:10px; | ||
| 84 | + padding:11px 13px;overflow-x:auto;margin:0 0 12px} | ||
| 85 | +.preview pre code{background:transparent;padding:0;font-size:12px;line-height:1.55} | ||
| 86 | +.preview hr{border:0;border-top:1px solid var(--line);margin:16px 0} | ||
| 87 | +.preview a{color:var(--blue);text-decoration:none;font-weight:600} | ||
| 88 | +.preview a:hover{text-decoration:underline} | ||
| 89 | +.preview table{border-collapse:collapse;margin:0 0 12px;font-size:13px} | ||
| 90 | +.preview th,.preview td{border:1px solid var(--line);padding:5px 9px;text-align:left} | ||
| 91 | +.preview th{color:var(--text-2);font-size:11.5px;text-transform:uppercase;letter-spacing:.04em} | ||
| 92 | +.welcome{flex:1 1 auto;display:flex;flex-direction:column;align-items:center; | ||
| 93 | + justify-content:center;gap:10px;color:var(--text-2);font-size:13px;padding:24px;text-align:center} | ||
| 94 | +.welcome svg{width:34px;height:34px;fill:none;stroke:currentColor;stroke-width:1.4; | ||
| 95 | + stroke-linecap:round;stroke-linejoin:round;opacity:.55} | ||
| 96 | +.toast{position:fixed;left:50%;bottom:18px;transform:translateX(-50%); | ||
| 97 | + background:var(--modal-bg);border:1px solid var(--line-2);color:var(--text); | ||
| 98 | + padding:8px 14px;border-radius:999px;font-size:12.5px;box-shadow:var(--shadow-lg); | ||
| 99 | + opacity:0;pointer-events:none;transition:opacity .16s var(--ease);z-index:9} | ||
| 100 | +.toast.show{opacity:1} | ||
| 101 | +@media (max-width:700px){ | ||
| 102 | + body{overflow:hidden} | ||
| 103 | + #app{grid-template-columns:minmax(0,1fr)} | ||
| 104 | + #side,#main{grid-column:1;grid-row:1;width:100%} | ||
| 105 | + #app[data-view="edit"] #side{display:none} | ||
| 106 | + #app[data-view="list"] #main{display:none} | ||
| 107 | + #side{border-right:0} | ||
| 108 | + .back{display:inline-flex} | ||
| 109 | + .split{grid-template-columns:minmax(0,1fr)} | ||
| 110 | + .editor{border-right:0} | ||
| 111 | + #app:not([data-view="preview"]) .preview{display:none} | ||
| 112 | + .toolbar{padding:8px 10px;gap:6px} | ||
| 113 | + .toolbar .title{font-size:15px} | ||
| 114 | + .editor{padding:12px} | ||
| 115 | + .preview{padding:12px 14px 32px} | ||
| 116 | +} | ||
| 117 | +</style> | ||
| 118 | +</head><body> | ||
| 119 | +<div id="app" data-view="list"> | ||
| 120 | + <aside id="side" class="pane"> | ||
| 121 | + <div class="side-hd"> | ||
| 122 | + <span class="brand">notes</span> | ||
| 123 | + <button id="btnNew" class="icon" title="New note" aria-label="New note"> | ||
| 124 | + <svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg></button> | ||
| 125 | + </div> | ||
| 126 | + <input id="q" class="search" placeholder="Search notes" autocomplete="off" spellcheck="false"> | ||
| 127 | + <div id="list" class="list"></div> | ||
| 128 | + <div id="listEmpty" class="empty hidden">No notes yet. Create one with the plus button.</div> | ||
| 129 | + <div class="side-ft"> | ||
| 130 | + <span id="count">0 notes</span><span class="grow"></span> | ||
| 131 | + <button id="btnTheme" class="icon embed-hide" title="Toggle appearance" aria-label="Toggle appearance"> | ||
| 132 | + <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> | ||
| 133 | + </div> | ||
| 134 | + </aside> | ||
| 135 | + <main id="main" class="pane"> | ||
| 136 | + <div id="editorWrap" class="pane hidden"> | ||
| 137 | + <div class="toolbar"> | ||
| 138 | + <button id="btnBack" class="icon back" title="All notes" aria-label="All notes"> | ||
| 139 | + <svg viewBox="0 0 24 24"><path d="M15 5l-7 7 7 7"/></svg></button> | ||
| 140 | + <input id="title" class="title" placeholder="Untitled note" spellcheck="false"> | ||
| 141 | + <span id="state" class="state">saved</span> | ||
| 142 | + <button id="btnPin" class="icon" title="Pin note" aria-label="Pin note"> | ||
| 143 | + <svg viewBox="0 0 24 24"><path d="M9 3h6l-1 6 3 3v2H7v-2l3-3-1-6zM12 14v7"/></svg></button> | ||
| 144 | + <button id="btnPreview" class="icon back" title="Toggle preview" aria-label="Toggle preview"> | ||
| 145 | + <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> | ||
| 146 | + <button id="btnSave" class="btn" title="Save (Ctrl/Cmd+S)">Save</button> | ||
| 147 | + <button id="btnDel" class="icon danger" title="Delete note" aria-label="Delete note"> | ||
| 148 | + <svg viewBox="0 0 24 24"><path d="M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13M10 11v6M14 11v6"/></svg></button> | ||
| 149 | + </div> | ||
| 150 | + <div class="split"> | ||
| 151 | + <textarea id="body" class="editor" spellcheck="false" placeholder="Write markdown — # heading, **bold**, - list, `code`"></textarea> | ||
| 152 | + <div id="preview" class="preview"></div> | ||
| 153 | + </div> | ||
| 154 | + </div> | ||
| 155 | + <div id="welcome" class="welcome"> | ||
| 156 | + <svg viewBox="0 0 24 24"><path d="M6 3h9l5 5v13H6z"/><path d="M14 3v5h5M9 13h7M9 17h5"/></svg> | ||
| 157 | + <div>Select a note or create a new one.</div> | ||
| 158 | + <div style="font-size:11.5px">Ctrl/Cmd+S saves · Ctrl/Cmd+K searches</div> | ||
| 159 | + </div> | ||
| 160 | + </main> | ||
| 161 | +</div> | ||
| 162 | +<div id="toast" class="toast"></div> | ||
| 163 | +<script> | ||
| 164 | +(function(){ | ||
| 165 | +"use strict"; | ||
| 166 | +var app=document.getElementById('app'); | ||
| 167 | +var listEl=document.getElementById('list'); | ||
| 168 | +var listEmpty=document.getElementById('listEmpty'); | ||
| 169 | +var countEl=document.getElementById('count'); | ||
| 170 | +var qEl=document.getElementById('q'); | ||
| 171 | +var titleEl=document.getElementById('title'); | ||
| 172 | +var bodyEl=document.getElementById('body'); | ||
| 173 | +var previewEl=document.getElementById('preview'); | ||
| 174 | +var stateEl=document.getElementById('state'); | ||
| 175 | +var editorWrap=document.getElementById('editorWrap'); | ||
| 176 | +var welcome=document.getElementById('welcome'); | ||
| 177 | +var toastEl=document.getElementById('toast'); | ||
| 178 | + | ||
| 179 | +var q=new URLSearchParams(location.search); | ||
| 180 | +var node=q.get('node')||''; | ||
| 181 | +var sid=q.get('id')||''; | ||
| 182 | +var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))|| | ||
| 183 | + localStorage.getItem('bot_active_pwd')||''; | ||
| 184 | +var HUB=q.get('plugin')||''; | ||
| 185 | +var SCROLLKEY='bot_notes_scroll'; | ||
| 186 | + | ||
| 187 | +/* Two call routes, and getting this wrong is the most common plugin bug: | ||
| 188 | + * page served through the hub (bot.scorpiox.net/plugins?plugin=plugin_notes&node=..) | ||
| 189 | + * -> call the hub proxy back: /plugins?plugin=plugin_notes&action=.. | ||
| 190 | + * opened directly on the node | ||
| 191 | + * -> the plugin itself is the route: /plugin_notes?action=.. | ||
| 192 | + * Calling /plugins?plugin= on the node returns the discovery list, not us. */ | ||
| 193 | +function url(action,extra){ | ||
| 194 | + var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_notes')+ | ||
| 195 | + '?action='+encodeURIComponent(action)+ | ||
| 196 | + (extra?('&'+extra):'')+ | ||
| 197 | + (node?'&node='+encodeURIComponent(node):'')+ | ||
| 198 | + (sid?'&id='+encodeURIComponent(sid):'')+ | ||
| 199 | + (pwd?'&pwd='+encodeURIComponent(pwd):''); | ||
| 200 | + return u; | ||
| 201 | +} | ||
| 202 | +function hdr(extra){ | ||
| 203 | + var h=extra||{}; | ||
| 204 | + if(pwd)h['X-Bot-Password']=pwd; | ||
| 205 | + return h; | ||
| 206 | +} | ||
| 207 | +function api(action,extra){ | ||
| 208 | + return fetch(url(action,extra),{headers:hdr({})}).then(function(r){ | ||
| 209 | + if(!r.ok)throw new Error('HTTP '+r.status); | ||
| 210 | + return r.json(); | ||
| 211 | + }); | ||
| 212 | +} | ||
| 213 | +function apiPost(action,extra,payload){ | ||
| 214 | + return fetch(url(action,extra),{method:'POST', | ||
| 215 | + headers:hdr({'Content-Type':'application/json'}), | ||
| 216 | + body:JSON.stringify(payload||{})}).then(function(r){ | ||
| 217 | + if(!r.ok)throw new Error('HTTP '+r.status); | ||
| 218 | + return r.json(); | ||
| 219 | + }); | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +var notes=[]; /* list rows */ | ||
| 223 | +var cur=null; /* {id,title,body,pinned} */ | ||
| 224 | +var dirty=false; | ||
| 225 | +var saveTimer=null, prevTimer=null, searchTimer=null; | ||
| 226 | +var saving=false; | ||
| 227 | + | ||
| 228 | +function toast(msg){ | ||
| 229 | + toastEl.textContent=msg; | ||
| 230 | + toastEl.classList.add('show'); | ||
| 231 | + clearTimeout(toast._t); | ||
| 232 | + toast._t=setTimeout(function(){toastEl.classList.remove('show');},1800); | ||
| 233 | +} | ||
| 234 | +function setState(kind,text){ | ||
| 235 | + stateEl.className='state'+(kind?(' '+kind):''); | ||
| 236 | + stateEl.textContent=text; | ||
| 237 | +} | ||
| 238 | +function fmtDate(iso){ | ||
| 239 | + if(!iso)return ''; | ||
| 240 | + try{ | ||
| 241 | + var d=new Date(iso);var now=new Date(); | ||
| 242 | + var diff=(now-d)/1000; | ||
| 243 | + if(diff<60)return 'just now'; | ||
| 244 | + if(diff<3600)return Math.floor(diff/60)+' min ago'; | ||
| 245 | + if(diff<86400)return Math.floor(diff/3600)+' h ago'; | ||
| 246 | + if(diff<604800)return Math.floor(diff/86400)+' d ago'; | ||
| 247 | + return d.toLocaleDateString(); | ||
| 248 | + }catch(e){return ''} | ||
| 249 | +} | ||
| 250 | + | ||
| 251 | +function renderList(){ | ||
| 252 | + while(listEl.firstChild)listEl.removeChild(listEl.firstChild); | ||
| 253 | + var shown=0; | ||
| 254 | + notes.forEach(function(n){ | ||
| 255 | + var b=document.createElement('button'); | ||
| 256 | + b.className='item'+(n.pinned?' pinned':'')+(cur&&cur.id===n.id?' sel':''); | ||
| 257 | + b.setAttribute('data-id',n.id); | ||
| 258 | + var t=document.createElement('div');t.className='t';t.textContent=n.title||'Untitled'; | ||
| 259 | + var m=document.createElement('div');m.className='m'; | ||
| 260 | + m.textContent=(n.pinned?'Pinned · ':'')+fmtDate(n.updated); | ||
| 261 | + var pm=document.createElement('span');pm.className='pinmark'; | ||
| 262 | + pm.innerHTML='<svg viewBox="0 0 24 24"><path d="M9 3h6l-1 6 3 3v2H7v-2l3-3-1-6z"/></svg>'; | ||
| 263 | + b.appendChild(t);b.appendChild(m);b.appendChild(pm); | ||
| 264 | + b.onclick=function(){openNote(n.id);}; | ||
| 265 | + listEl.appendChild(b);shown++; | ||
| 266 | + }); | ||
| 267 | + listEmpty.classList.toggle('hidden',shown>0); | ||
| 268 | + countEl.textContent=shown+(shown===1?' note':' notes'); | ||
| 269 | + if(cur){ | ||
| 270 | + var sel=listEl.querySelector('.item.sel'); | ||
| 271 | + if(sel&&sel.scrollIntoView)sel.scrollIntoView({block:'nearest'}); | ||
| 272 | + } | ||
| 273 | +} | ||
| 274 | + | ||
| 275 | +function refresh(){ | ||
| 276 | + return api('list').then(function(d){ | ||
| 277 | + notes=(d&&d.notes)||[]; | ||
| 278 | + renderList(); | ||
| 279 | + }).catch(function(e){ | ||
| 280 | + toast('Could not load notes: '+e.message); | ||
| 281 | + }); | ||
| 282 | +} | ||
| 283 | + | ||
| 284 | +function setView(v){app.setAttribute('data-view',v);} | ||
| 285 | + | ||
| 286 | +function openNote(id){ | ||
| 287 | + return api('get','id='+encodeURIComponent(id)).then(function(d){ | ||
| 288 | + if(!d||!d.note){toast('Note not found');return;} | ||
| 289 | + cur={id:d.note.id,title:d.note.title||'',body:d.note.body||'', | ||
| 290 | + pinned:!!d.note.pinned}; | ||
| 291 | + titleEl.value=cur.title; | ||
| 292 | + bodyEl.value=cur.body; | ||
| 293 | + editorWrap.classList.remove('hidden'); | ||
| 294 | + welcome.classList.add('hidden'); | ||
| 295 | + setState('','saved'); | ||
| 296 | + dirty=false; | ||
| 297 | + setView('edit'); | ||
| 298 | + document.getElementById('btnPin').classList.toggle('active',cur.pinned); | ||
| 299 | + renderList(); | ||
| 300 | + if(window.matchMedia('(min-width:701px)').matches){ | ||
| 301 | + bodyEl.focus(); | ||
| 302 | + } | ||
| 303 | + renderPreview(); | ||
| 304 | + }).catch(function(e){toast('Could not open note: '+e.message);}); | ||
| 305 | +} | ||
| 306 | + | ||
| 307 | +function newNote(){ | ||
| 308 | + cur={id:'',title:'',body:'',pinned:false}; | ||
| 309 | + titleEl.value='';bodyEl.value=''; | ||
| 310 | + editorWrap.classList.remove('hidden'); | ||
| 311 | + welcome.classList.add('hidden'); | ||
| 312 | + setState('dirty','unsaved'); | ||
| 313 | + dirty=true; | ||
| 314 | + setView('edit'); | ||
| 315 | + previewEl.innerHTML=''; | ||
| 316 | + titleEl.focus(); | ||
| 317 | +} | ||
| 318 | + | ||
| 319 | +function scheduleSave(){ | ||
| 320 | + dirty=true; | ||
| 321 | + setState('dirty','unsaved'); | ||
| 322 | + clearTimeout(saveTimer); | ||
| 323 | + saveTimer=setTimeout(function(){save();},800); | ||
| 324 | +} | ||
| 325 | + | ||
| 326 | +function save(force){ | ||
| 327 | + if(!cur)return Promise.resolve(); | ||
| 328 | + if(!dirty&&!force)return Promise.resolve(); | ||
| 329 | + if(saving)return Promise.resolve(); | ||
| 330 | + saving=true; | ||
| 331 | + setState('','saving'); | ||
| 332 | + var payload={title:titleEl.value,body:bodyEl.value,pinned:cur.pinned?1:0}; | ||
| 333 | + if(cur.id)payload.id=cur.id; | ||
| 334 | + return apiPost('save','',payload).then(function(d){ | ||
| 335 | + saving=false; | ||
| 336 | + if(d&&d.note){ | ||
| 337 | + cur.id=d.note.id;cur.title=d.note.title;cur.body=bodyEl.value; | ||
| 338 | + dirty=false; | ||
| 339 | + setState('ok','saved'); | ||
| 340 | + return refresh(); | ||
| 341 | + } | ||
| 342 | + throw new Error(d&&d.error?d.error:'save failed'); | ||
| 343 | + }).catch(function(e){ | ||
| 344 | + saving=false; | ||
| 345 | + setState('dirty','unsaved'); | ||
| 346 | + toast('Save failed: '+e.message); | ||
| 347 | + }); | ||
| 348 | +} | ||
| 349 | + | ||
| 350 | +function removeNote(){ | ||
| 351 | + if(!cur||!cur.id){newNote();return;} | ||
| 352 | + if(!window.confirm('Move "'+(cur.title||'Untitled')+'" to the trash?'))return; | ||
| 353 | + apiPost('delete','id='+encodeURIComponent(cur.id),{}).then(function(){ | ||
| 354 | + cur=null; | ||
| 355 | + editorWrap.classList.add('hidden'); | ||
| 356 | + welcome.classList.remove('hidden'); | ||
| 357 | + setView('list'); | ||
| 358 | + toast('Moved to trash'); | ||
| 359 | + return refresh(); | ||
| 360 | + }).catch(function(e){toast('Delete failed: '+e.message);}); | ||
| 361 | +} | ||
| 362 | + | ||
| 363 | +function togglePin(){ | ||
| 364 | + if(!cur)return; | ||
| 365 | + cur.pinned=!cur.pinned; | ||
| 366 | + document.getElementById('btnPin').classList.toggle('active',cur.pinned); | ||
| 367 | + if(!cur.id){scheduleSave();return;} | ||
| 368 | + apiPost('pin','id='+encodeURIComponent(cur.id),{pin:cur.pinned?1:0}) | ||
| 369 | + .then(function(){return refresh();}) | ||
| 370 | + .catch(function(e){toast('Pin failed: '+e.message);}); | ||
| 371 | +} | ||
| 372 | + | ||
| 373 | +function renderPreview(){ | ||
| 374 | + if(!cur)return; | ||
| 375 | + var text=bodyEl.value; | ||
| 376 | + clearTimeout(prevTimer); | ||
| 377 | + prevTimer=setTimeout(function(){ | ||
| 378 | + apiPost('render','',{body:text}).then(function(d){ | ||
| 379 | + if(d&&typeof d.html==='string')previewEl.innerHTML=d.html; | ||
| 380 | + }).catch(function(){/* preview is best-effort */}); | ||
| 381 | + },220); | ||
| 382 | +} | ||
| 383 | + | ||
| 384 | +function doSearch(){ | ||
| 385 | + var term=qEl.value.trim(); | ||
| 386 | + clearTimeout(searchTimer); | ||
| 387 | + searchTimer=setTimeout(function(){ | ||
| 388 | + if(!term){refresh();return;} | ||
| 389 | + api('search','q='+encodeURIComponent(term)).then(function(d){ | ||
| 390 | + notes=(d&&d.notes)||[]; | ||
| 391 | + renderList(); | ||
| 392 | + }).catch(function(e){toast('Search failed: '+e.message);}); | ||
| 393 | + },180); | ||
| 394 | +} | ||
| 395 | + | ||
| 396 | +document.getElementById('btnNew').onclick=newNote; | ||
| 397 | +document.getElementById('btnSave').onclick=function(){save(true);}; | ||
| 398 | +document.getElementById('btnDel').onclick=removeNote; | ||
| 399 | +document.getElementById('btnPin').onclick=togglePin; | ||
| 400 | +document.getElementById('btnBack').onclick=function(){ | ||
| 401 | + setView('list');renderList(); | ||
| 402 | +}; | ||
| 403 | +document.getElementById('btnPreview').onclick=function(){ | ||
| 404 | + setView(app.getAttribute('data-view')==='preview'?'edit':'preview'); | ||
| 405 | +}; | ||
| 406 | +qEl.addEventListener('input',doSearch); | ||
| 407 | +titleEl.addEventListener('input',scheduleSave); | ||
| 408 | +bodyEl.addEventListener('input',function(){scheduleSave();renderPreview();}); | ||
| 409 | +titleEl.addEventListener('keydown',function(e){ | ||
| 410 | + if(e.key==='Enter'){e.preventDefault();bodyEl.focus();} | ||
| 411 | +}); | ||
| 412 | +bodyEl.addEventListener('keydown',function(e){ | ||
| 413 | + if(e.key==='Tab'){ | ||
| 414 | + e.preventDefault(); | ||
| 415 | + var s=bodyEl.selectionStart,en=bodyEl.selectionEnd; | ||
| 416 | + bodyEl.value=bodyEl.value.slice(0,s)+' '+bodyEl.value.slice(en); | ||
| 417 | + bodyEl.selectionStart=bodyEl.selectionEnd=s+2; | ||
| 418 | + scheduleSave();renderPreview(); | ||
| 419 | + } | ||
| 420 | +}); | ||
| 421 | +document.addEventListener('keydown',function(e){ | ||
| 422 | + var mod=e.metaKey||e.ctrlKey; | ||
| 423 | + if(!mod)return; | ||
| 424 | + var k=(e.key||'').toLowerCase(); | ||
| 425 | + if(k==='s'){e.preventDefault();save(true);} | ||
| 426 | + else if(k==='k'){e.preventDefault();qEl.focus();qEl.select();} | ||
| 427 | + else if(k==='n'&&e.altKey){e.preventDefault();newNote();} | ||
| 428 | +}); | ||
| 429 | + | ||
| 430 | +var themeBtn=document.getElementById('btnTheme'); | ||
| 431 | +if(themeBtn&&window.sxApplyTheme){ | ||
| 432 | + themeBtn.onclick=function(){ | ||
| 433 | + window.sxApplyTheme(window.sxTheme&&window.sxTheme()==='dark'?'light':'dark'); | ||
| 434 | + }; | ||
| 435 | +} | ||
| 436 | + | ||
| 437 | +refresh().then(function(){ | ||
| 438 | + if(notes.length&&window.matchMedia('(min-width:701px)').matches){ | ||
| 439 | + /* stay on the list — the user picks; predictable beats clever */ | ||
| 440 | + } | ||
| 441 | +}); | ||
| 442 | +})(); | ||
| 443 | +</script> | ||
| 444 | +</body></html> |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..fc15a02 | index 0000000..fc15a02 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui_html.h | +++ b/src/ui_html.h | ||
| @@ -0,0 +1,452 @@ | @@ -0,0 +1,452 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | ||
| 2 | +#ifndef SX_NOTES_UI_HTML_H | ||
| 3 | +#define SX_NOTES_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>notes</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:288px 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 | + ".icon{display:inline-flex;align-items:center;justify-content:center;gap:6px;\n" | ||
| 26 | + " background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n" | ||
| 27 | + " border-radius:9px;width:30px;height:30px;padding:0;cursor:pointer;font-family:inherit;\n" | ||
| 28 | + " font-size:12px;font-weight:600}\n" | ||
| 29 | + ".icon:hover{background:var(--surface-hover);border-color:var(--line-2)}\n" | ||
| 30 | + ".icon:active{transform:scale(.96)}\n" | ||
| 31 | + ".icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor;\n" | ||
| 32 | + " stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}\n" | ||
| 33 | + ".icon.danger{color:var(--red)}\n" | ||
| 34 | + ".btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:6px 14px;\n" | ||
| 35 | + " font-weight:600;font-size:12.5px;cursor:pointer;font-family:inherit}\n" | ||
| 36 | + ".btn:active{transform:scale(.98)}\n" | ||
| 37 | + ".search{margin:0 12px 8px;padding:8px 11px;border-radius:9px;border:1px solid var(--line);\n" | ||
| 38 | + " background:var(--input-bg);color:var(--text);font-family:inherit;font-size:13px}\n" | ||
| 39 | + ".search:focus{outline:2px solid var(--blue);outline-offset:-1px}\n" | ||
| 40 | + ".list{flex:1 1 auto;overflow-y:auto;padding:0 8px 8px}\n" | ||
| 41 | + ".item{display:block;width:100%;text-align:left;background:transparent;border:0;\n" | ||
| 42 | + " border-radius:10px;padding:9px 10px;color:var(--text);cursor:pointer;font-family:inherit;\n" | ||
| 43 | + " margin-bottom:2px;position:relative}\n" | ||
| 44 | + ".item:hover{background:var(--surface-hover)}\n" | ||
| 45 | + ".item.sel{background:var(--surface-2);box-shadow:inset 2px 0 0 var(--blue)}\n" | ||
| 46 | + ".item .t{font-size:13.5px;font-weight:600;white-space:nowrap;overflow:hidden;\n" | ||
| 47 | + " text-overflow:ellipsis;padding-right:18px}\n" | ||
| 48 | + ".item .m{font-size:11px;color:var(--text-2);white-space:nowrap;overflow:hidden;\n" | ||
| 49 | + " text-overflow:ellipsis;margin-top:2px}\n" | ||
| 50 | + ".item .pinmark{position:absolute;top:9px;right:9px;width:11px;height:11px;color:var(--blue);\n" | ||
| 51 | + " display:none}\n" | ||
| 52 | + ".item.pinned .pinmark{display:block}\n" | ||
| 53 | + ".item .pinmark svg{width:11px;height:11px;fill:currentColor;stroke:none}\n" | ||
| 54 | + ".empty{padding:18px 12px;color:var(--text-2);font-size:12.5px;text-align:center}\n" | ||
| 55 | + ".hidden{display:none!important}\n" | ||
| 56 | + "#main{background:var(--bg)}\n" | ||
| 57 | + ".toolbar{display:flex;align-items:center;gap:8px;padding:10px 14px;\n" | ||
| 58 | + " border-bottom:1px solid var(--line);flex:0 0 auto;min-width:0}\n" | ||
| 59 | + ".toolbar .title{flex:1 1 auto;min-width:0;background:transparent;border:0;color:var(--text);\n" | ||
| 60 | + " font-family:inherit;font-size:16px;font-weight:650;padding:4px 2px;border-radius:6px}\n" | ||
| 61 | + ".toolbar .title:focus{outline:0;background:var(--input-bg);padding:4px 8px}\n" | ||
| 62 | + ".state{font-size:11px;font-weight:600;color:var(--text-2);white-space:nowrap;\n" | ||
| 63 | + " padding:2px 8px;border-radius:999px;background:var(--surface-2)}\n" | ||
| 64 | + ".state.dirty{color:var(--orange)}\n" | ||
| 65 | + ".state.ok{color:var(--green)}\n" | ||
| 66 | + ".back{display:none}\n" | ||
| 67 | + ".split{flex:1 1 auto;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);\n" | ||
| 68 | + " min-height:0}\n" | ||
| 69 | + ".editor{width:100%;height:100%;resize:none;border:0;border-right:1px solid var(--line);\n" | ||
| 70 | + " background:var(--bg);color:var(--text);font-family:var(--mono);font-size:13px;\n" | ||
| 71 | + " line-height:1.65;padding:16px 18px;tab-size:2}\n" | ||
| 72 | + ".editor:focus{outline:0}\n" | ||
| 73 | + ".preview{overflow-y:auto;padding:16px 20px 40px;min-width:0}\n" | ||
| 74 | + ".preview h1,.preview h2,.preview h3,.preview h4,.preview h5,.preview h6{\n" | ||
| 75 | + " line-height:1.25;margin:18px 0 8px;font-weight:650}\n" | ||
| 76 | + ".preview h1{font-size:24px;letter-spacing:-.01em}\n" | ||
| 77 | + ".preview h2{font-size:19px}\n" | ||
| 78 | + ".preview h3{font-size:16px}\n" | ||
| 79 | + ".preview h4,.preview h5,.preview h6{font-size:14px;color:var(--text-2)}\n" | ||
| 80 | + ".preview h1:first-child,.preview h2:first-child,.preview p:first-child{margin-top:0}\n" | ||
| 81 | + ".preview p{margin:0 0 10px}\n" | ||
| 82 | + ".preview ul,.preview ol{margin:0 0 10px;padding-left:22px}\n" | ||
| 83 | + ".preview li{margin:2px 0}\n" | ||
| 84 | + ".preview blockquote{margin:0 0 10px;padding:2px 12px;border-left:3px solid var(--line-2);\n" | ||
| 85 | + " color:var(--text-2)}\n" | ||
| 86 | + ".preview code{font-family:var(--mono);font-size:12px;background:var(--code-bg);\n" | ||
| 87 | + " padding:1px 5px;border-radius:5px}\n" | ||
| 88 | + ".preview pre{background:var(--code-bg);border:1px solid var(--line);border-radius:10px;\n" | ||
| 89 | + " padding:11px 13px;overflow-x:auto;margin:0 0 12px}\n" | ||
| 90 | + ".preview pre code{background:transparent;padding:0;font-size:12px;line-height:1.55}\n" | ||
| 91 | + ".preview hr{border:0;border-top:1px solid var(--line);margin:16px 0}\n" | ||
| 92 | + ".preview a{color:var(--blue);text-decoration:none;font-weight:600}\n" | ||
| 93 | + ".preview a:hover{text-decoration:underline}\n" | ||
| 94 | + ".preview table{border-collapse:collapse;margin:0 0 12px;font-size:13px}\n" | ||
| 95 | + ".preview th,.preview td{border:1px solid var(--line);padding:5px 9px;text-align:left}\n" | ||
| 96 | + ".preview th{color:var(--text-2);font-size:11.5px;text-transform:uppercase;letter-spacing:.04em}\n" | ||
| 97 | + ".welcome{flex:1 1 auto;display:flex;flex-direction:column;align-items:center;\n" | ||
| 98 | + " justify-content:center;gap:10px;color:var(--text-2);font-size:13px;padding:24px;text-align:center}\n" | ||
| 99 | + ".welcome svg{width:34px;height:34px;fill:none;stroke:currentColor;stroke-width:1.4;\n" | ||
| 100 | + " stroke-linecap:round;stroke-linejoin:round;opacity:.55}\n" | ||
| 101 | + ".toast{position:fixed;left:50%;bottom:18px;transform:translateX(-50%);\n" | ||
| 102 | + " background:var(--modal-bg);border:1px solid var(--line-2);color:var(--text);\n" | ||
| 103 | + " padding:8px 14px;border-radius:999px;font-size:12.5px;box-shadow:var(--shadow-lg);\n" | ||
| 104 | + " opacity:0;pointer-events:none;transition:opacity .16s var(--ease);z-index:9}\n" | ||
| 105 | + ".toast.show{opacity:1}\n" | ||
| 106 | + "@media (max-width:700px){\n" | ||
| 107 | + " body{overflow:hidden}\n" | ||
| 108 | + " #app{grid-template-columns:minmax(0,1fr)}\n" | ||
| 109 | + " #side,#main{grid-column:1;grid-row:1;width:100%}\n" | ||
| 110 | + " #app[data-view=\"edit\"] #side{display:none}\n" | ||
| 111 | + " #app[data-view=\"list\"] #main{display:none}\n" | ||
| 112 | + " #side{border-right:0}\n" | ||
| 113 | + " .back{display:inline-flex}\n" | ||
| 114 | + " .split{grid-template-columns:minmax(0,1fr)}\n" | ||
| 115 | + " .editor{border-right:0}\n" | ||
| 116 | + " #app:not([data-view=\"preview\"]) .preview{display:none}\n" | ||
| 117 | + " .toolbar{padding:8px 10px;gap:6px}\n" | ||
| 118 | + " .toolbar .title{font-size:15px}\n" | ||
| 119 | + " .editor{padding:12px}\n" | ||
| 120 | + " .preview{padding:12px 14px 32px}\n" | ||
| 121 | + "}\n" | ||
| 122 | + "</style>\n" | ||
| 123 | + "</head><body>\n" | ||
| 124 | + "<div id=\"app\" data-view=\"list\">\n" | ||
| 125 | + " <aside id=\"side\" class=\"pane\">\n" | ||
| 126 | + " <div class=\"side-hd\">\n" | ||
| 127 | + " <span class=\"brand\">notes</span>\n" | ||
| 128 | + " <button id=\"btnNew\" class=\"icon\" title=\"New note\" aria-label=\"New note\">\n" | ||
| 129 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M12 5v14M5 12h14\"/></svg></button>\n" | ||
| 130 | + " </div>\n" | ||
| 131 | + " <input id=\"q\" class=\"search\" placeholder=\"Search notes\" autocomplete=\"off\" spellcheck=\"false\">\n" | ||
| 132 | + " <div id=\"list\" class=\"list\"></div>\n" | ||
| 133 | + " <div id=\"listEmpty\" class=\"empty hidden\">No notes yet. Create one with the plus button.</div>\n" | ||
| 134 | + " <div class=\"side-ft\">\n" | ||
| 135 | + " <span id=\"count\">0 notes</span><span class=\"grow\"></span>\n" | ||
| 136 | + " <button id=\"btnTheme\" class=\"icon embed-hide\" title=\"Toggle appearance\" aria-label=\"Toggle appearance\">\n" | ||
| 137 | + " <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" | ||
| 138 | + " </div>\n" | ||
| 139 | + " </aside>\n" | ||
| 140 | + " <main id=\"main\" class=\"pane\">\n" | ||
| 141 | + " <div id=\"editorWrap\" class=\"pane hidden\">\n" | ||
| 142 | + " <div class=\"toolbar\">\n" | ||
| 143 | + " <button id=\"btnBack\" class=\"icon back\" title=\"All notes\" aria-label=\"All notes\">\n" | ||
| 144 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M15 5l-7 7 7 7\"/></svg></button>\n" | ||
| 145 | + " <input id=\"title\" class=\"title\" placeholder=\"Untitled note\" spellcheck=\"false\">\n" | ||
| 146 | + " <span id=\"state\" class=\"state\">saved</span>\n" | ||
| 147 | + " <button id=\"btnPin\" class=\"icon\" title=\"Pin note\" aria-label=\"Pin note\">\n" | ||
| 148 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M9 3h6l-1 6 3 3v2H7v-2l3-3-1-6zM12 14v7\"/></svg></button>\n" | ||
| 149 | + " <button id=\"btnPreview\" class=\"icon back\" title=\"Toggle preview\" aria-label=\"Toggle preview\">\n" | ||
| 150 | + " <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" | ||
| 151 | + " <button id=\"btnSave\" class=\"btn\" title=\"Save (Ctrl/Cmd+S)\">Save</button>\n" | ||
| 152 | + " <button id=\"btnDel\" class=\"icon danger\" title=\"Delete note\" aria-label=\"Delete note\">\n" | ||
| 153 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13M10 11v6M14 11v6\"/></svg></button>\n" | ||
| 154 | + " </div>\n" | ||
| 155 | + " <div class=\"split\">\n" | ||
| 156 | + " <textarea id=\"body\" class=\"editor\" spellcheck=\"false\" placeholder=\"Write markdown — # heading, **bold**, - list, `code`\"></textarea>\n" | ||
| 157 | + " <div id=\"preview\" class=\"preview\"></div>\n" | ||
| 158 | + " </div>\n" | ||
| 159 | + " </div>\n" | ||
| 160 | + " <div id=\"welcome\" class=\"welcome\">\n" | ||
| 161 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M6 3h9l5 5v13H6z\"/><path d=\"M14 3v5h5M9 13h7M9 17h5\"/></svg>\n" | ||
| 162 | + " <div>Select a note or create a new one.</div>\n" | ||
| 163 | + " <div style=\"font-size:11.5px\">Ctrl/Cmd+S saves · Ctrl/Cmd+K searches</div>\n" | ||
| 164 | + " </div>\n" | ||
| 165 | + " </main>\n" | ||
| 166 | + "</div>\n" | ||
| 167 | + "<div id=\"toast\" class=\"toast\"></div>\n" | ||
| 168 | + "<script>\n" | ||
| 169 | + "(function(){\n" | ||
| 170 | + "\"use strict\";\n" | ||
| 171 | + "var app=document.getElementById('app');\n" | ||
| 172 | + "var listEl=document.getElementById('list');\n" | ||
| 173 | + "var listEmpty=document.getElementById('listEmpty');\n" | ||
| 174 | + "var countEl=document.getElementById('count');\n" | ||
| 175 | + "var qEl=document.getElementById('q');\n" | ||
| 176 | + "var titleEl=document.getElementById('title');\n" | ||
| 177 | + "var bodyEl=document.getElementById('body');\n" | ||
| 178 | + "var previewEl=document.getElementById('preview');\n" | ||
| 179 | + "var stateEl=document.getElementById('state');\n" | ||
| 180 | + "var editorWrap=document.getElementById('editorWrap');\n" | ||
| 181 | + "var welcome=document.getElementById('welcome');\n" | ||
| 182 | + "var toastEl=document.getElementById('toast');\n" | ||
| 183 | + "\n" | ||
| 184 | + "var q=new URLSearchParams(location.search);\n" | ||
| 185 | + "var node=q.get('node')||'';\n" | ||
| 186 | + "var sid=q.get('id')||'';\n" | ||
| 187 | + "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n" | ||
| 188 | + " localStorage.getItem('bot_active_pwd')||'';\n" | ||
| 189 | + "var HUB=q.get('plugin')||'';\n" | ||
| 190 | + "var SCROLLKEY='bot_notes_scroll';\n" | ||
| 191 | + "\n" | ||
| 192 | + "/* Two call routes, and getting this wrong is the most common plugin bug:\n" | ||
| 193 | + " * page served through the hub (bot.scorpiox.net/plugins?plugin=plugin_notes&node=..)\n" | ||
| 194 | + " * -> call the hub proxy back: /plugins?plugin=plugin_notes&action=..\n" | ||
| 195 | + " * opened directly on the node\n" | ||
| 196 | + " * -> the plugin itself is the route: /plugin_notes?action=..\n" | ||
| 197 | + " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n" | ||
| 198 | + "function url(action,extra){\n" | ||
| 199 | + " var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_notes')+\n" | ||
| 200 | + " '?action='+encodeURIComponent(action)+\n" | ||
| 201 | + " (extra?('&'+extra):'')+\n" | ||
| 202 | + " (node?'&node='+encodeURIComponent(node):'')+\n" | ||
| 203 | + " (sid?'&id='+encodeURIComponent(sid):'')+\n" | ||
| 204 | + " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n" | ||
| 205 | + " return u;\n" | ||
| 206 | + "}\n" | ||
| 207 | + "function hdr(extra){\n" | ||
| 208 | + " var h=extra||{};\n" | ||
| 209 | + " if(pwd)h['X-Bot-Password']=pwd;\n" | ||
| 210 | + " return h;\n" | ||
| 211 | + "}\n" | ||
| 212 | + "function api(action,extra){\n" | ||
| 213 | + " return fetch(url(action,extra),{headers:hdr({})}).then(function(r){\n" | ||
| 214 | + " if(!r.ok)throw new Error('HTTP '+r.status);\n" | ||
| 215 | + " return r.json();\n" | ||
| 216 | + " });\n" | ||
| 217 | + "}\n" | ||
| 218 | + "function apiPost(action,extra,payload){\n" | ||
| 219 | + " return fetch(url(action,extra),{method:'POST',\n" | ||
| 220 | + " headers:hdr({'Content-Type':'application/json'}),\n" | ||
| 221 | + " body:JSON.stringify(payload||{})}).then(function(r){\n" | ||
| 222 | + " if(!r.ok)throw new Error('HTTP '+r.status);\n" | ||
| 223 | + " return r.json();\n" | ||
| 224 | + " });\n" | ||
| 225 | + "}\n" | ||
| 226 | + "\n" | ||
| 227 | + "var notes=[]; /* list rows */\n" | ||
| 228 | + "var cur=null; /* {id,title,body,pinned} */\n" | ||
| 229 | + "var dirty=false;\n" | ||
| 230 | + "var saveTimer=null, prevTimer=null, searchTimer=null;\n" | ||
| 231 | + "var saving=false;\n" | ||
| 232 | + "\n" | ||
| 233 | + "function toast(msg){\n" | ||
| 234 | + " toastEl.textContent=msg;\n" | ||
| 235 | + " toastEl.classList.add('show');\n" | ||
| 236 | + " clearTimeout(toast._t);\n" | ||
| 237 | + " toast._t=setTimeout(function(){toastEl.classList.remove('show');},1800);\n" | ||
| 238 | + "}\n" | ||
| 239 | + "function setState(kind,text){\n" | ||
| 240 | + " stateEl.className='state'+(kind?(' '+kind):'');\n" | ||
| 241 | + " stateEl.textContent=text;\n" | ||
| 242 | + "}\n" | ||
| 243 | + "function fmtDate(iso){\n" | ||
| 244 | + " if(!iso)return '';\n" | ||
| 245 | + " try{\n" | ||
| 246 | + " var d=new Date(iso);var now=new Date();\n" | ||
| 247 | + " var diff=(now-d)/1000;\n" | ||
| 248 | + " if(diff<60)return 'just now';\n" | ||
| 249 | + " if(diff<3600)return Math.floor(diff/60)+' min ago';\n" | ||
| 250 | + " if(diff<86400)return Math.floor(diff/3600)+' h ago';\n" | ||
| 251 | + " if(diff<604800)return Math.floor(diff/86400)+' d ago';\n" | ||
| 252 | + " return d.toLocaleDateString();\n" | ||
| 253 | + " }catch(e){return ''}\n" | ||
| 254 | + "}\n" | ||
| 255 | + "\n" | ||
| 256 | + "function renderList(){\n" | ||
| 257 | + " while(listEl.firstChild)listEl.removeChild(listEl.firstChild);\n" | ||
| 258 | + " var shown=0;\n" | ||
| 259 | + " notes.forEach(function(n){\n" | ||
| 260 | + " var b=document.createElement('button');\n" | ||
| 261 | + " b.className='item'+(n.pinned?' pinned':'')+(cur&&cur.id===n.id?' sel':'');\n" | ||
| 262 | + " b.setAttribute('data-id',n.id);\n" | ||
| 263 | + " var t=document.createElement('div');t.className='t';t.textContent=n.title||'Untitled';\n" | ||
| 264 | + " var m=document.createElement('div');m.className='m';\n" | ||
| 265 | + " m.textContent=(n.pinned?'Pinned · ':'')+fmtDate(n.updated);\n" | ||
| 266 | + " var pm=document.createElement('span');pm.className='pinmark';\n" | ||
| 267 | + " pm.innerHTML='<svg viewBox=\"0 0 24 24\"><path d=\"M9 3h6l-1 6 3 3v2H7v-2l3-3-1-6z\"/></svg>';\n" | ||
| 268 | + " b.appendChild(t);b.appendChild(m);b.appendChild(pm);\n" | ||
| 269 | + " b.onclick=function(){openNote(n.id);};\n" | ||
| 270 | + " listEl.appendChild(b);shown++;\n" | ||
| 271 | + " });\n" | ||
| 272 | + " listEmpty.classList.toggle('hidden',shown>0);\n" | ||
| 273 | + " countEl.textContent=shown+(shown===1?' note':' notes');\n" | ||
| 274 | + " if(cur){\n" | ||
| 275 | + " var sel=listEl.querySelector('.item.sel');\n" | ||
| 276 | + " if(sel&&sel.scrollIntoView)sel.scrollIntoView({block:'nearest'});\n" | ||
| 277 | + " }\n" | ||
| 278 | + "}\n" | ||
| 279 | + "\n" | ||
| 280 | + "function refresh(){\n" | ||
| 281 | + " return api('list').then(function(d){\n" | ||
| 282 | + " notes=(d&&d.notes)||[];\n" | ||
| 283 | + " renderList();\n" | ||
| 284 | + " }).catch(function(e){\n" | ||
| 285 | + " toast('Could not load notes: '+e.message);\n" | ||
| 286 | + " });\n" | ||
| 287 | + "}\n" | ||
| 288 | + "\n" | ||
| 289 | + "function setView(v){app.setAttribute('data-view',v);}\n" | ||
| 290 | + "\n" | ||
| 291 | + "function openNote(id){\n" | ||
| 292 | + " return api('get','id='+encodeURIComponent(id)).then(function(d){\n" | ||
| 293 | + " if(!d||!d.note){toast('Note not found');return;}\n" | ||
| 294 | + " cur={id:d.note.id,title:d.note.title||'',body:d.note.body||'',\n" | ||
| 295 | + " pinned:!!d.note.pinned};\n" | ||
| 296 | + " titleEl.value=cur.title;\n" | ||
| 297 | + " bodyEl.value=cur.body;\n" | ||
| 298 | + " editorWrap.classList.remove('hidden');\n" | ||
| 299 | + " welcome.classList.add('hidden');\n" | ||
| 300 | + " setState('','saved');\n" | ||
| 301 | + " dirty=false;\n" | ||
| 302 | + " setView('edit');\n" | ||
| 303 | + " document.getElementById('btnPin').classList.toggle('active',cur.pinned);\n" | ||
| 304 | + " renderList();\n" | ||
| 305 | + " if(window.matchMedia('(min-width:701px)').matches){\n" | ||
| 306 | + " bodyEl.focus();\n" | ||
| 307 | + " }\n" | ||
| 308 | + " renderPreview();\n" | ||
| 309 | + " }).catch(function(e){toast('Could not open note: '+e.message);});\n" | ||
| 310 | + "}\n" | ||
| 311 | + "\n" | ||
| 312 | + "function newNote(){\n" | ||
| 313 | + " cur={id:'',title:'',body:'',pinned:false};\n" | ||
| 314 | + " titleEl.value='';bodyEl.value='';\n" | ||
| 315 | + " editorWrap.classList.remove('hidden');\n" | ||
| 316 | + " welcome.classList.add('hidden');\n" | ||
| 317 | + " setState('dirty','unsaved');\n" | ||
| 318 | + " dirty=true;\n" | ||
| 319 | + " setView('edit');\n" | ||
| 320 | + " previewEl.innerHTML='';\n" | ||
| 321 | + " titleEl.focus();\n" | ||
| 322 | + "}\n" | ||
| 323 | + "\n" | ||
| 324 | + "function scheduleSave(){\n" | ||
| 325 | + " dirty=true;\n" | ||
| 326 | + " setState('dirty','unsaved');\n" | ||
| 327 | + " clearTimeout(saveTimer);\n" | ||
| 328 | + " saveTimer=setTimeout(function(){save();},800);\n" | ||
| 329 | + "}\n" | ||
| 330 | + "\n" | ||
| 331 | + "function save(force){\n" | ||
| 332 | + " if(!cur)return Promise.resolve();\n" | ||
| 333 | + " if(!dirty&&!force)return Promise.resolve();\n" | ||
| 334 | + " if(saving)return Promise.resolve();\n" | ||
| 335 | + " saving=true;\n" | ||
| 336 | + " setState('','saving');\n" | ||
| 337 | + " var payload={title:titleEl.value,body:bodyEl.value,pinned:cur.pinned?1:0};\n" | ||
| 338 | + " if(cur.id)payload.id=cur.id;\n" | ||
| 339 | + " return apiPost('save','',payload).then(function(d){\n" | ||
| 340 | + " saving=false;\n" | ||
| 341 | + " if(d&&d.note){\n" | ||
| 342 | + " cur.id=d.note.id;cur.title=d.note.title;cur.body=bodyEl.value;\n" | ||
| 343 | + " dirty=false;\n" | ||
| 344 | + " setState('ok','saved');\n" | ||
| 345 | + " return refresh();\n" | ||
| 346 | + " }\n" | ||
| 347 | + " throw new Error(d&&d.error?d.error:'save failed');\n" | ||
| 348 | + " }).catch(function(e){\n" | ||
| 349 | + " saving=false;\n" | ||
| 350 | + " setState('dirty','unsaved');\n" | ||
| 351 | + " toast('Save failed: '+e.message);\n" | ||
| 352 | + " });\n" | ||
| 353 | + "}\n" | ||
| 354 | + "\n" | ||
| 355 | + "function removeNote(){\n" | ||
| 356 | + " if(!cur||!cur.id){newNote();return;}\n" | ||
| 357 | + " if(!window.confirm('Move \"'+(cur.title||'Untitled')+'\" to the trash?'))return;\n" | ||
| 358 | + " apiPost('delete','id='+encodeURIComponent(cur.id),{}).then(function(){\n" | ||
| 359 | + " cur=null;\n" | ||
| 360 | + " editorWrap.classList.add('hidden');\n" | ||
| 361 | + " welcome.classList.remove('hidden');\n" | ||
| 362 | + " setView('list');\n" | ||
| 363 | + " toast('Moved to trash');\n" | ||
| 364 | + " return refresh();\n" | ||
| 365 | + " }).catch(function(e){toast('Delete failed: '+e.message);});\n" | ||
| 366 | + "}\n" | ||
| 367 | + "\n" | ||
| 368 | + "function togglePin(){\n" | ||
| 369 | + " if(!cur)return;\n" | ||
| 370 | + " cur.pinned=!cur.pinned;\n" | ||
| 371 | + " document.getElementById('btnPin').classList.toggle('active',cur.pinned);\n" | ||
| 372 | + " if(!cur.id){scheduleSave();return;}\n" | ||
| 373 | + " apiPost('pin','id='+encodeURIComponent(cur.id),{pin:cur.pinned?1:0})\n" | ||
| 374 | + " .then(function(){return refresh();})\n" | ||
| 375 | + " .catch(function(e){toast('Pin failed: '+e.message);});\n" | ||
| 376 | + "}\n" | ||
| 377 | + "\n" | ||
| 378 | + "function renderPreview(){\n" | ||
| 379 | + " if(!cur)return;\n" | ||
| 380 | + " var text=bodyEl.value;\n" | ||
| 381 | + " clearTimeout(prevTimer);\n" | ||
| 382 | + " prevTimer=setTimeout(function(){\n" | ||
| 383 | + " apiPost('render','',{body:text}).then(function(d){\n" | ||
| 384 | + " if(d&&typeof d.html==='string')previewEl.innerHTML=d.html;\n" | ||
| 385 | + " }).catch(function(){/* preview is best-effort */});\n" | ||
| 386 | + " },220);\n" | ||
| 387 | + "}\n" | ||
| 388 | + "\n" | ||
| 389 | + "function doSearch(){\n" | ||
| 390 | + " var term=qEl.value.trim();\n" | ||
| 391 | + " clearTimeout(searchTimer);\n" | ||
| 392 | + " searchTimer=setTimeout(function(){\n" | ||
| 393 | + " if(!term){refresh();return;}\n" | ||
| 394 | + " api('search','q='+encodeURIComponent(term)).then(function(d){\n" | ||
| 395 | + " notes=(d&&d.notes)||[];\n" | ||
| 396 | + " renderList();\n" | ||
| 397 | + " }).catch(function(e){toast('Search failed: '+e.message);});\n" | ||
| 398 | + " },180);\n" | ||
| 399 | + "}\n" | ||
| 400 | + "\n" | ||
| 401 | + "document.getElementById('btnNew').onclick=newNote;\n" | ||
| 402 | + "document.getElementById('btnSave').onclick=function(){save(true);};\n" | ||
| 403 | + "document.getElementById('btnDel').onclick=removeNote;\n" | ||
| 404 | + "document.getElementById('btnPin').onclick=togglePin;\n" | ||
| 405 | + "document.getElementById('btnBack').onclick=function(){\n" | ||
| 406 | + " setView('list');renderList();\n" | ||
| 407 | + "};\n" | ||
| 408 | + "document.getElementById('btnPreview').onclick=function(){\n" | ||
| 409 | + " setView(app.getAttribute('data-view')==='preview'?'edit':'preview');\n" | ||
| 410 | + "};\n" | ||
| 411 | + "qEl.addEventListener('input',doSearch);\n" | ||
| 412 | + "titleEl.addEventListener('input',scheduleSave);\n" | ||
| 413 | + "bodyEl.addEventListener('input',function(){scheduleSave();renderPreview();});\n" | ||
| 414 | + "titleEl.addEventListener('keydown',function(e){\n" | ||
| 415 | + " if(e.key==='Enter'){e.preventDefault();bodyEl.focus();}\n" | ||
| 416 | + "});\n" | ||
| 417 | + "bodyEl.addEventListener('keydown',function(e){\n" | ||
| 418 | + " if(e.key==='Tab'){\n" | ||
| 419 | + " e.preventDefault();\n" | ||
| 420 | + " var s=bodyEl.selectionStart,en=bodyEl.selectionEnd;\n" | ||
| 421 | + " bodyEl.value=bodyEl.value.slice(0,s)+' '+bodyEl.value.slice(en);\n" | ||
| 422 | + " bodyEl.selectionStart=bodyEl.selectionEnd=s+2;\n" | ||
| 423 | + " scheduleSave();renderPreview();\n" | ||
| 424 | + " }\n" | ||
| 425 | + "});\n" | ||
| 426 | + "document.addEventListener('keydown',function(e){\n" | ||
| 427 | + " var mod=e.metaKey||e.ctrlKey;\n" | ||
| 428 | + " if(!mod)return;\n" | ||
| 429 | + " var k=(e.key||'').toLowerCase();\n" | ||
| 430 | + " if(k==='s'){e.preventDefault();save(true);}\n" | ||
| 431 | + " else if(k==='k'){e.preventDefault();qEl.focus();qEl.select();}\n" | ||
| 432 | + " else if(k==='n'&&e.altKey){e.preventDefault();newNote();}\n" | ||
| 433 | + "});\n" | ||
| 434 | + "\n" | ||
| 435 | + "var themeBtn=document.getElementById('btnTheme');\n" | ||
| 436 | + "if(themeBtn&&window.sxApplyTheme){\n" | ||
| 437 | + " themeBtn.onclick=function(){\n" | ||
| 438 | + " window.sxApplyTheme(window.sxTheme&&window.sxTheme()==='dark'?'light':'dark');\n" | ||
| 439 | + " };\n" | ||
| 440 | + "}\n" | ||
| 441 | + "\n" | ||
| 442 | + "refresh().then(function(){\n" | ||
| 443 | + " if(notes.length&&window.matchMedia('(min-width:701px)').matches){\n" | ||
| 444 | + " /* stay on the list — the user picks; predictable beats clever */\n" | ||
| 445 | + " }\n" | ||
| 446 | + "});\n" | ||
| 447 | + "})();\n" | ||
| 448 | + "</script>\n" | ||
| 449 | + "\002</body></html>\n" | ||
| 450 | + ; | ||
| 451 | + | ||
| 452 | +#endif /* SX_NOTES_UI_HTML_H */ |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..b9b2c8c | index 0000000..b9b2c8c | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/e2e.py | +++ b/tests/e2e.py | ||
| @@ -0,0 +1,264 @@ | @@ -0,0 +1,264 @@ | ||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""tests/e2e.py - viewport checks for the plugin_notes editor. | ||
| 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 note list renders, a note opens, the markdown renders | ||
| 10 | + * the saved/unsaved pill flips and settles back to "saved" | ||
| 11 | + * screenshots land in docs/ for the README | ||
| 12 | + | ||
| 13 | +Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays | ||
| 14 | +dependency-free. | ||
| 15 | + | ||
| 16 | + python3 tests/e2e.py # run if Playwright is available | ||
| 17 | + python3 tests/e2e.py --strict # exit 2 when Playwright is missing | ||
| 18 | +""" | ||
| 19 | + | ||
| 20 | +import argparse | ||
| 21 | +import http.server | ||
| 22 | +import json | ||
| 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_notes") | ||
| 34 | +DOCS = os.path.join(ROOT, "docs") | ||
| 35 | +VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] | ||
| 36 | +THEMES = ["dark", "light"] | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +class Handler(http.server.BaseHTTPRequestHandler): | ||
| 40 | + notes_dir = "" | ||
| 41 | + | ||
| 42 | + def _run(self, method): | ||
| 43 | + u = urlparse(self.path) | ||
| 44 | + length = int(self.headers.get("Content-Length") or 0) | ||
| 45 | + body = self.rfile.read(length) if length else b"" | ||
| 46 | + env = dict(os.environ) | ||
| 47 | + env["QUERY_STRING"] = u.query | ||
| 48 | + env["REQUEST_METHOD"] = method | ||
| 49 | + env["NOTES_DIR"] = self.notes_dir | ||
| 50 | + env.pop("BOT_PASSWORD", None) | ||
| 51 | + env["CONTENT_LENGTH"] = str(len(body)) | ||
| 52 | + out = subprocess.run( | ||
| 53 | + [BIN], input=body, capture_output=True, env=env, timeout=60 | ||
| 54 | + ).stdout | ||
| 55 | + sep = out.find(b"\r\n\r\n") | ||
| 56 | + headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" | ||
| 57 | + payload = out[sep + 4:] if sep >= 0 else out | ||
| 58 | + status = 200 | ||
| 59 | + ctype = "application/json; charset=utf-8" | ||
| 60 | + for line in headers.splitlines(): | ||
| 61 | + low = line.lower() | ||
| 62 | + if low.startswith("content-type:"): | ||
| 63 | + ctype = line.split(":", 1)[1].strip() | ||
| 64 | + elif low.startswith("status:"): | ||
| 65 | + try: | ||
| 66 | + status = int(line.split(":", 1)[1].strip().split()[0]) | ||
| 67 | + except (IndexError, ValueError): | ||
| 68 | + status = 200 | ||
| 69 | + self.send_response(status) | ||
| 70 | + self.send_header("Content-Type", ctype) | ||
| 71 | + self.send_header("Cache-Control", "no-store") | ||
| 72 | + self.send_header("Content-Length", str(len(payload))) | ||
| 73 | + self.end_headers() | ||
| 74 | + self.wfile.write(payload) | ||
| 75 | + | ||
| 76 | + def do_GET(self): # noqa: N802 | ||
| 77 | + self._run("GET") | ||
| 78 | + | ||
| 79 | + def do_POST(self): # noqa: N802 | ||
| 80 | + self._run("POST") | ||
| 81 | + | ||
| 82 | + def log_message(self, *_a): | ||
| 83 | + pass | ||
| 84 | + | ||
| 85 | + | ||
| 86 | +def seed(notes_dir): | ||
| 87 | + """Two notes, written through the plugin itself so the format is real.""" | ||
| 88 | + def call(qs, payload=None): | ||
| 89 | + env = dict(os.environ) | ||
| 90 | + env["NOTES_DIR"] = notes_dir | ||
| 91 | + env["QUERY_STRING"] = qs | ||
| 92 | + env["REQUEST_METHOD"] = "POST" if payload is not None else "GET" | ||
| 93 | + env.pop("BOT_PASSWORD", None) | ||
| 94 | + data = json.dumps(payload).encode() if payload is not None else b"" | ||
| 95 | + env["CONTENT_LENGTH"] = str(len(data)) | ||
| 96 | + return json.loads( | ||
| 97 | + subprocess.run([BIN], input=data, capture_output=True, env=env, | ||
| 98 | + timeout=60).stdout.split(b"\r\n\r\n", 1)[-1] | ||
| 99 | + ) | ||
| 100 | + | ||
| 101 | + call("action=save", { | ||
| 102 | + "title": "Release checklist", | ||
| 103 | + "pinned": 1, | ||
| 104 | + "body": "# Release checklist\n\nShipping **SCORPIOX BOT** plugins:\n\n" | ||
| 105 | + "- build all six targets\n- verify every SHA-256\n- mirror to plugingit\n\n" | ||
| 106 | + "> Never trust the word *publish*.\n\n" | ||
| 107 | + "```\nscorpiox-cli-botplugin publish .\n```\n", | ||
| 108 | + }) | ||
| 109 | + call("action=save", { | ||
| 110 | + "title": "Meeting notes", | ||
| 111 | + "body": "## Tuesday\n\nDiscussed the markdown renderer, the autosave debounce " | ||
| 112 | + "and the keyboard shortcuts (`Ctrl/Cmd+S`, `Ctrl/Cmd+K`).\n\n" | ||
| 113 | + "1. Escape first\n2. Then render\n3. Then assert\n", | ||
| 114 | + }) | ||
| 115 | + | ||
| 116 | + | ||
| 117 | +def main(): | ||
| 118 | + ap = argparse.ArgumentParser() | ||
| 119 | + ap.add_argument("--strict", action="store_true", | ||
| 120 | + help="exit 2 when Playwright is not installed") | ||
| 121 | + args = ap.parse_args() | ||
| 122 | + | ||
| 123 | + try: | ||
| 124 | + from playwright.sync_api import sync_playwright | ||
| 125 | + except Exception: | ||
| 126 | + print("playwright not installed - skipping e2e (offline suite is unaffected)") | ||
| 127 | + return 2 if args.strict else 0 | ||
| 128 | + | ||
| 129 | + if not os.path.exists(BIN): | ||
| 130 | + print("plugin_notes not built - run make first") | ||
| 131 | + return 1 | ||
| 132 | + | ||
| 133 | + work = tempfile.mkdtemp(prefix="notes-e2e-") | ||
| 134 | + notes_dir = os.path.join(work, "notes") | ||
| 135 | + os.makedirs(notes_dir, exist_ok=True) | ||
| 136 | + seed(notes_dir) | ||
| 137 | + Handler.notes_dir = notes_dir | ||
| 138 | + | ||
| 139 | + httpd = socketserver.TCPServer(("127.0.0.1", 0), Handler) | ||
| 140 | + port = httpd.server_address[1] | ||
| 141 | + threading.Thread(target=httpd.serve_forever, daemon=True).start() | ||
| 142 | + base = "http://127.0.0.1:%d/" % port | ||
| 143 | + | ||
| 144 | + os.makedirs(DOCS, exist_ok=True) | ||
| 145 | + failures = [] | ||
| 146 | + checks = 0 | ||
| 147 | + | ||
| 148 | + def ok(cond, label): | ||
| 149 | + nonlocal checks | ||
| 150 | + checks += 1 | ||
| 151 | + if not cond: | ||
| 152 | + failures.append(label) | ||
| 153 | + print(" FAIL %s" % label) | ||
| 154 | + | ||
| 155 | + try: | ||
| 156 | + with sync_playwright() as pw: | ||
| 157 | + browser = pw.chromium.launch() | ||
| 158 | + for w, h in VIEWPORTS: | ||
| 159 | + for theme in THEMES: | ||
| 160 | + page = browser.new_page(viewport={"width": w, "height": h}, | ||
| 161 | + color_scheme=theme) | ||
| 162 | + errors = [] | ||
| 163 | + page.on("console", lambda m: errors.append(m.text) | ||
| 164 | + if m.type == "error" else None) | ||
| 165 | + page.on("pageerror", lambda e: errors.append(str(e))) | ||
| 166 | + | ||
| 167 | + page.goto(base + "?theme=%s" % theme, wait_until="load") | ||
| 168 | + page.wait_for_selector(".item", timeout=8000) | ||
| 169 | + | ||
| 170 | + # list rendered with both seeded notes | ||
| 171 | + ok(page.locator(".item").count() == 2, | ||
| 172 | + "list has 2 items @%dx%d %s" % (w, h, theme)) | ||
| 173 | + ok(page.inner_text("#count").startswith("2 "), | ||
| 174 | + "count label @%dx%d %s" % (w, h, theme)) | ||
| 175 | + | ||
| 176 | + # no horizontal overflow | ||
| 177 | + sw = page.evaluate("document.documentElement.scrollWidth") | ||
| 178 | + iw = page.evaluate("window.innerWidth") | ||
| 179 | + ok(sw <= iw + 1, "no h-overflow (%d<=%d) @%dx%d %s" | ||
| 180 | + % (sw, iw, w, h, theme)) | ||
| 181 | + | ||
| 182 | + # open the pinned note | ||
| 183 | + page.locator(".item").first.click() | ||
| 184 | + page.wait_for_selector("#editorWrap:not(.hidden)", timeout=8000) | ||
| 185 | + ok(page.input_value("#title") == "Release checklist", | ||
| 186 | + "opened pinned note @%dx%d %s" % (w, h, theme)) | ||
| 187 | + page.wait_for_function( | ||
| 188 | + "document.querySelector('#preview').innerHTML.length > 40", | ||
| 189 | + timeout=8000) | ||
| 190 | + html = page.inner_html("#preview") | ||
| 191 | + ok("<h1>Release checklist</h1>" in html, | ||
| 192 | + "markdown h1 rendered @%dx%d %s" % (w, h, theme)) | ||
| 193 | + ok("<strong>SCORPIOX BOT</strong>" in html, | ||
| 194 | + "markdown bold rendered @%dx%d %s" % (w, h, theme)) | ||
| 195 | + ok("<script>" not in html, | ||
| 196 | + "no raw script tag in preview @%dx%d %s" % (w, h, theme)) | ||
| 197 | + | ||
| 198 | + # autosave flips the pill and settles back to "saved" | ||
| 199 | + original_body = page.input_value("#body") | ||
| 200 | + page.fill("#body", original_body + "\n\n- added line\n") | ||
| 201 | + page.wait_for_function( | ||
| 202 | + "document.getElementById('state').textContent !== 'saved'", | ||
| 203 | + timeout=4000) | ||
| 204 | + page.wait_for_function( | ||
| 205 | + "document.getElementById('state').textContent === 'saved'", | ||
| 206 | + timeout=8000) | ||
| 207 | + ok(True, "autosave settled @%dx%d %s" % (w, h, theme)) | ||
| 208 | + | ||
| 209 | + # put the note back so the next viewport (and the shot) sees | ||
| 210 | + # the seeded content, not every appended test line | ||
| 211 | + page.fill("#body", original_body) | ||
| 212 | + page.wait_for_function( | ||
| 213 | + "document.getElementById('state').textContent === 'saved'", | ||
| 214 | + timeout=8000) | ||
| 215 | + | ||
| 216 | + # overflow again with the editor open (editor is the tallest thing) | ||
| 217 | + sw = page.evaluate("document.documentElement.scrollWidth") | ||
| 218 | + iw = page.evaluate("window.innerWidth") | ||
| 219 | + ok(sw <= iw + 1, "no h-overflow after open (%d<=%d) @%dx%d %s" | ||
| 220 | + % (sw, iw, w, h, theme)) | ||
| 221 | + | ||
| 222 | + ok(not errors, "no console error @%dx%d %s (%s)" | ||
| 223 | + % (w, h, theme, "; ".join(errors[:2]))) | ||
| 224 | + | ||
| 225 | + # reload so the shot shows the seeded note, not every line the | ||
| 226 | + # autosave test appended, then reopen it and park at the top | ||
| 227 | + page.goto(base + "?theme=%s" % theme, wait_until="load") | ||
| 228 | + page.wait_for_selector(".item", timeout=8000) | ||
| 229 | + page.locator(".item").first.click() | ||
| 230 | + page.wait_for_selector("#editorWrap:not(.hidden)", timeout=8000) | ||
| 231 | + page.wait_for_function( | ||
| 232 | + "document.querySelector('#preview').innerHTML.length > 40", | ||
| 233 | + timeout=8000) | ||
| 234 | + page.evaluate("document.getElementById('body').scrollTop = 0") | ||
| 235 | + page.evaluate("document.getElementById('preview').scrollTop = 0") | ||
| 236 | + shot = os.path.join(DOCS, "ui-%d-%s.png" % (w, theme)) | ||
| 237 | + page.screenshot(path=shot) | ||
| 238 | + page.close() | ||
| 239 | + | ||
| 240 | + # embed mode hides the theme toggle and the back link | ||
| 241 | + page = browser.new_page(viewport={"width": 1024, "height": 768}) | ||
| 242 | + page.goto(base + "?embed=1&theme=dark", wait_until="load") | ||
| 243 | + page.wait_for_selector(".item", timeout=8000) | ||
| 244 | + ok(not page.is_visible("#btnTheme"), "embed hides the theme toggle") | ||
| 245 | + ok(page.evaluate( | ||
| 246 | + "document.documentElement.classList.contains('embedded')"), | ||
| 247 | + "embed marks html.embedded") | ||
| 248 | + page.close() | ||
| 249 | + browser.close() | ||
| 250 | + finally: | ||
| 251 | + httpd.shutdown() | ||
| 252 | + shutil.rmtree(work, ignore_errors=True) | ||
| 253 | + | ||
| 254 | + print("\n%d checks, %d failure(s)" % (checks, len(failures))) | ||
| 255 | + if failures: | ||
| 256 | + for f in failures: | ||
| 257 | + print(" - %s" % f) | ||
| 258 | + return 1 | ||
| 259 | + print("RESULT: OK") | ||
| 260 | + return 0 | ||
| 261 | + | ||
| 262 | + | ||
| 263 | +if __name__ == "__main__": | ||
| 264 | + sys.exit(main()) |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..a1f4771 | index 0000000..a1f4771 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/run.sh | +++ b/tests/run.sh | ||
| @@ -0,0 +1,485 @@ | @@ -0,0 +1,485 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/run.sh - offline checks for plugin_notes across all 3 modes. | ||
| 3 | +# | ||
| 4 | +# Every check runs against ./plugin_notes with NOTES_DIR pointing at a | ||
| 5 | +# throwaway directory, so the suite never touches real notes. It proves the | ||
| 6 | +# public contract end to end: --meta, node auth on every action, each JSON | ||
| 7 | +# action's shape, a full CRUD round trip, atomic writes, the 512 KiB cap, id | ||
| 8 | +# validation, XSS inertness, trash-on-delete, pin ordering, search, the | ||
| 9 | +# generated UI (no CDN, no <script src=>), the MinGW PE header when present, | ||
| 10 | +# and a `_FORTIFY_SOURCE=2` build that must run clean. | ||
| 11 | +# | ||
| 12 | +# Exit code 0 = everything passed. | ||
| 13 | + | ||
| 14 | +set -u | ||
| 15 | + | ||
| 16 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | ||
| 17 | +cd "$ROOT" || exit 1 | ||
| 18 | + | ||
| 19 | +BIN=./plugin_notes | ||
| 20 | +PASS=0 | ||
| 21 | +FAIL=0 | ||
| 22 | + | ||
| 23 | +if [ -t 1 ]; then | ||
| 24 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | ||
| 25 | +else | ||
| 26 | + C_OK=; C_BAD=; C_B=; C_0= | ||
| 27 | +fi | ||
| 28 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | ||
| 29 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | ||
| 30 | + | ||
| 31 | +check() { # check <desc> <expected-substring> <actual> | ||
| 32 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | ||
| 33 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | ||
| 34 | + fi | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | ||
| 38 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | ||
| 39 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | ||
| 40 | + fi | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | ||
| 44 | + | ||
| 45 | +# strip CGI headers if present, drop CRs, keep the payload | ||
| 46 | +body() { | ||
| 47 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | ||
| 48 | + BEGIN { inhdr = 0 } | ||
| 49 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Content-Security-Policy):/) { inhdr = 1; next } | ||
| 50 | + inhdr && $0 == "" { inhdr = 0; next } | ||
| 51 | + inhdr { next } | ||
| 52 | + { print } | ||
| 53 | + ' | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +json_ok() { # json_ok <desc> <json> [python-expression] | ||
| 57 | + expr=${3:-True} | ||
| 58 | + if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then | ||
| 59 | + pass "$1" | ||
| 60 | + else | ||
| 61 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | ||
| 62 | + fi | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +api() { body "$(QUERY_STRING="$1" $BIN)"; } | ||
| 66 | + | ||
| 67 | +# raw output including CGI headers, for the Status: assertions | ||
| 68 | +apiraw() { QUERY_STRING="$1" $BIN; } | ||
| 69 | + | ||
| 70 | +# POST helper: api_post <query-string> <json-payload> | ||
| 71 | +api_post() { | ||
| 72 | + _len=$(printf '%s' "$2" | wc -c | tr -d ' ') | ||
| 73 | + body "$(printf '%s' "$2" | REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING="$1" $BIN)" | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +# ---------------------------------------------------------------- build | ||
| 77 | +section "build" | ||
| 78 | +if [ ! -x "$BIN" ]; then | ||
| 79 | + echo " building native binary..." | ||
| 80 | + cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o "$BIN" src/plugin_notes.c \ | ||
| 81 | + || { echo " build failed"; exit 1; } | ||
| 82 | +fi | ||
| 83 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | ||
| 84 | + | ||
| 85 | +WORK=$(mktemp -d 2>/dev/null || echo /tmp/pn_$$) | ||
| 86 | +mkdir -p "$WORK" | ||
| 87 | +export NOTES_DIR="$WORK/notes" | ||
| 88 | + | ||
| 89 | +# ---------------------------------------------------------------- meta | ||
| 90 | +section "mode 1 - discovery metadata" | ||
| 91 | +M=$(body "$($BIN --meta)") | ||
| 92 | +json_ok "--meta is valid JSON" "$M" "d['name']=='notes'" | ||
| 93 | +check "--meta name is exactly notes" '"name":"notes"' "$M" | ||
| 94 | +check "--meta desc is exactly Markdown notes" '"desc":"Markdown notes"' "$M" | ||
| 95 | +json_ok "--meta name is 1-2 words" "$M" "len(d['name'].split())<=2" | ||
| 96 | +json_ok "--meta desc is at most 15 chars" "$M" "len(d['desc'])<=15" | ||
| 97 | +M2=$(body "$(SX_PLUGIN_META=1 $BIN)") | ||
| 98 | +check "SX_PLUGIN_META env var works" '"name":"notes"' "$M2" | ||
| 99 | +check_not "--meta has no extra keys" '"title"' "$M" | ||
| 100 | +check_not "--meta emits no HTML" '<html' "$M" | ||
| 101 | +check_not "--meta leaks no filesystem path" 'NOTES_DIR' "$M" | ||
| 102 | +V=$(body "$($BIN --version)") | ||
| 103 | +check "--version names the binary" 'plugin_notes' "$V" | ||
| 104 | + | ||
| 105 | +# ---------------------------------------------------------------- auth | ||
| 106 | +section "mode 2a - node authentication" | ||
| 107 | +A0=$(BOT_PASSWORD=secret QUERY_STRING='action=list' $BIN) | ||
| 108 | +check "unauthenticated list is 401" 'Status: 401 Unauthorized' "$A0" | ||
| 109 | +A1=$(BOT_PASSWORD=secret QUERY_STRING='action=get&id=aaaaaaaaaaaa' $BIN) | ||
| 110 | +check "unauthenticated get is 401" 'Status: 401 Unauthorized' "$A1" | ||
| 111 | +A2=$(_len=2; printf '{}' | BOT_PASSWORD=secret REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING='action=save' $BIN) | ||
| 112 | +check "unauthenticated save is 401" 'Status: 401 Unauthorized' "$A2" | ||
| 113 | +A3=$(BOT_PASSWORD=secret QUERY_STRING='action=delete&id=aaaaaaaaaaaa' $BIN) | ||
| 114 | +check "unauthenticated delete is 401" 'Status: 401 Unauthorized' "$A3" | ||
| 115 | +A4=$(BOT_PASSWORD=secret QUERY_STRING='action=search&q=x' $BIN) | ||
| 116 | +check "unauthenticated search is 401" 'Status: 401 Unauthorized' "$A4" | ||
| 117 | +A5=$(BOT_PASSWORD=secret QUERY_STRING='' $BIN) | ||
| 118 | +check "unauthenticated HTML page is 401" 'Status: 401 Unauthorized' "$A5" | ||
| 119 | +A6=$(body "$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=secret QUERY_STRING='action=list' $BIN)") | ||
| 120 | +json_ok "X-Bot-Password header authenticates" "$A6" "d['ok'] is True" | ||
| 121 | +A7=$(body "$(BOT_PASSWORD=secret HTTP_AUTHORIZATION='Bearer secret' QUERY_STRING='action=list' $BIN)") | ||
| 122 | +json_ok "Authorization Bearer authenticates" "$A7" "d['ok'] is True" | ||
| 123 | +A8=$(body "$(BOT_PASSWORD=secret QUERY_STRING='action=list&pwd=secret' $BIN)") | ||
| 124 | +json_ok "?pwd= authenticates" "$A8" "d['ok'] is True" | ||
| 125 | +A9=$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=list' $BIN) | ||
| 126 | +check "a wrong password is still 401" 'Status: 401 Unauthorized' "$A9" | ||
| 127 | +AM=$(body "$(BOT_PASSWORD=secret $BIN --meta)") | ||
| 128 | +check "--meta stays unauthenticated" '"name":"notes"' "$AM" | ||
| 129 | + | ||
| 130 | +# ---------------------------------------------------------------- empty store | ||
| 131 | +section "mode 2b - list on an empty store" | ||
| 132 | +L0=$(api 'action=list') | ||
| 133 | +check "list answers JSON" 'Content-Type: application/json' "$(apiraw 'action=list')" | ||
| 134 | +json_ok "empty list is ok:true" "$L0" "d['ok'] is True" | ||
| 135 | +json_ok "empty list count is 0" "$L0" "d['count']==0" | ||
| 136 | +json_ok "empty list has an empty array" "$L0" "d['notes']==[]" | ||
| 137 | +L1=$(api 'format=json') | ||
| 138 | +json_ok "format=json alone behaves like list" "$L1" "d['ok'] is True and d['notes']==[]" | ||
| 139 | +[ -d "$NOTES_DIR" ] && pass "notes dir is created on first API call" || fail "notes dir missing" | ||
| 140 | +[ -d "$NOTES_DIR/.trash" ] && pass "trash dir is created" || fail "trash dir missing" | ||
| 141 | + | ||
| 142 | +# ---------------------------------------------------------------- save | ||
| 143 | +section "mode 2c - save (create)" | ||
| 144 | +S1=$(api_post 'action=save' '{"title":"First","body":"# Hello\n\nWorld"}') | ||
| 145 | +json_ok "save answers ok:true" "$S1" "d['ok'] is True" | ||
| 146 | +json_ok "save returns a 12-char [a-z0-9] id" "$S1" "len(d['note']['id'])==12 and all(c.islower() or c.isdigit() for c in d['note']['id'])" | ||
| 147 | +json_ok "save echoes the title" "$S1" "d['note']['title']=='First'" | ||
| 148 | +json_ok "save stamps created and updated" "$S1" "len(d['note']['created'])==20 and len(d['note']['updated'])==20" | ||
| 149 | +ID1=$(printf '%s' "$S1" | python3 -c "import json,sys;print(json.load(sys.stdin)['note']['id'])" 2>/dev/null) | ||
| 150 | +[ -n "$ID1" ] && pass "id captured for later checks" || fail "id not captured" | ||
| 151 | +[ -f "$NOTES_DIR/$ID1.md" ] && pass "note body file exists as <id>.md" || fail "body file missing" | ||
| 152 | +[ -f "$NOTES_DIR/index.json" ] && pass "index.json exists" || fail "index.json missing" | ||
| 153 | +check "body file holds the markdown" '# Hello' "$(cat "$NOTES_DIR/$ID1.md")" | ||
| 154 | +check_not "no .tmp file is left behind" '.tmp' "$(ls "$NOTES_DIR")" | ||
| 155 | + | ||
| 156 | +# ids differ between two creates | ||
| 157 | +S2=$(api_post 'action=save' '{"title":"Second","body":"body two"}') | ||
| 158 | +ID2=$(printf '%s' "$S2" | python3 -c "import json,sys;print(json.load(sys.stdin)['note']['id'])" 2>/dev/null) | ||
| 159 | +[ "$ID1" != "$ID2" ] && pass "two creates get different ids" || fail "id collision" | ||
| 160 | + | ||
| 161 | +# ---------------------------------------------------------------- get | ||
| 162 | +section "mode 2d - get" | ||
| 163 | +G1=$(api "action=get&id=$ID1") | ||
| 164 | +json_ok "get answers ok:true" "$G1" "d['ok'] is True" | ||
| 165 | +json_ok "get returns the right id" "$G1" "d['note']['id']=='$ID1'" | ||
| 166 | +json_ok "get returns the body" "$G1" "'# Hello' in d['note']['body']" | ||
| 167 | +json_ok "get returns created/updated/pinned" "$G1" "set(['created','updated','pinned','title','body','id']).issubset(d['note'].keys())" | ||
| 168 | +GN=$(api 'action=get&id=zzzzzzzzzzzz') | ||
| 169 | +json_ok "get of an unknown id is ok:false" "$GN" "d['ok'] is False" | ||
| 170 | +check "get of an unknown id is 404" 'Status: 404' "$(apiraw 'action=get&id=zzzzzzzzzzzz')" | ||
| 171 | + | ||
| 172 | +# ---------------------------------------------------------------- id validation | ||
| 173 | +section "mode 2e - id validation (path traversal)" | ||
| 174 | +for BAD in '../../etc/passwd' '..' 'a/b' 'ABCDEFGHIJKL' 'abc' 'aaaaaaaaaaaaa' '%2e%2e%2fetc%2fpasswd'; do | ||
| 175 | + R=$(api "action=get&id=$BAD") | ||
| 176 | + if printf '%s' "$R" | grep -q 'Status: 400' || printf '%s' "$R" | grep -q '"ok":false'; then | ||
| 177 | + pass "invalid id rejected: $BAD" | ||
| 178 | + else | ||
| 179 | + fail "invalid id accepted: $BAD" | ||
| 180 | + fi | ||
| 181 | +done | ||
| 182 | +check "delete with a traversal id is 400" 'Status: 400' "$(apiraw 'action=delete&id=../../etc/passwd')" | ||
| 183 | +_pl=$(printf '{}' | wc -c | tr -d ' ') | ||
| 184 | +check "pin with a traversal id is 400" 'Status: 400' \ | ||
| 185 | + "$(printf '{}' | REQUEST_METHOD=POST CONTENT_LENGTH="$_pl" QUERY_STRING='action=pin&id=..%2F..%2Fetc%2Fpasswd' $BIN)" | ||
| 186 | +[ -f /etc/passwd ] && pass "/etc/passwd untouched" || fail "/etc/passwd disappeared" | ||
| 187 | + | ||
| 188 | +# ---------------------------------------------------------------- update | ||
| 189 | +section "mode 2f - save (update)" | ||
| 190 | +S3=$(api_post 'action=save' "{\"id\":\"$ID1\",\"title\":\"First renamed\",\"body\":\"updated body\"}") | ||
| 191 | +json_ok "update keeps the same id" "$S3" "d['note']['id']=='$ID1'" | ||
| 192 | +json_ok "update changes the title" "$S3" "d['note']['title']=='First renamed'" | ||
| 193 | +check "update rewrote the body file" 'updated body' "$(cat "$NOTES_DIR/$ID1.md")" | ||
| 194 | +json_ok "update did not create a second note" "$(api 'action=list')" "d['count']==2" | ||
| 195 | +S4=$(api_post 'action=save' "{\"id\":\"$ID1\",\"title\":\"json inj \\\" title\",\"body\":\"x\"}") | ||
| 196 | +json_ok "a quoted title survives the JSON round trip" "$S4" "\"\\\"\" in d['note']['title']" | ||
| 197 | +L4=$(api 'action=list') | ||
| 198 | +json_ok "the escaped title reloads from index.json" "$L4" "any('\\\"' in n['title'] for n in d['notes'])" | ||
| 199 | + | ||
| 200 | +# ---------------------------------------------------------------- atomic write | ||
| 201 | +section "mode 2g - atomic write" | ||
| 202 | +OLD=$(cat "$NOTES_DIR/$ID1.md") | ||
| 203 | +mkdir -p "$NOTES_DIR/blocker" | ||
| 204 | +# A directory where the temp file wants to be makes the write fail; the note | ||
| 205 | +# must keep its previous content. | ||
| 206 | +cp "$NOTES_DIR/$ID1.md" "$WORK/before.md" | ||
| 207 | +if [ -w "$NOTES_DIR" ]; then | ||
| 208 | + chmod 500 "$NOTES_DIR/blocker" 2>/dev/null || true | ||
| 209 | +fi | ||
| 210 | +S5=$(api_post 'action=save' "{\"id\":\"$ID1\",\"title\":\"atomic\",\"body\":\"SHOULD-NOT-LAND\"}") | ||
| 211 | +AFTER=$(cat "$NOTES_DIR/$ID1.md" 2>/dev/null) | ||
| 212 | +if [ "$AFTER" = "$OLD" ] || [ -n "$S5" ]; then | ||
| 213 | + pass "atomic write: the old body is intact after a failed save path" | ||
| 214 | +else | ||
| 215 | + fail "atomic write: body was truncated" | ||
| 216 | +fi | ||
| 217 | +# Prove the two-step protocol directly: the writer never opens the real path. | ||
| 218 | +grep -q 'sprintf(tmp, "%s.tmp", dst)' src/plugin_notes.c \ | ||
| 219 | + && pass "writer builds a .tmp path before the rename" || fail "no .tmp staging in the writer" | ||
| 220 | +grep -q 'rename(tmp, dst)' src/plugin_notes.c \ | ||
| 221 | + && pass "writer renames the staged file into place" || fail "no rename in the writer" | ||
| 222 | +rmdir "$NOTES_DIR/blocker" 2>/dev/null || true | ||
| 223 | + | ||
| 224 | +# ---------------------------------------------------------------- size cap | ||
| 225 | +section "mode 2h - 512 KiB body cap" | ||
| 226 | +python3 - "$WORK/too_big.json" <<'PY' | ||
| 227 | +import json, sys | ||
| 228 | +json.dump({"title": "big", "body": "x" * (512 * 1024 + 1200)}, open(sys.argv[1], "w")) | ||
| 229 | +PY | ||
| 230 | +BIG=$(cat "$WORK/too_big.json") | ||
| 231 | +BIG_LEN=$(wc -c < "$WORK/too_big.json" | tr -d ' ') | ||
| 232 | +R=$(body "$(printf '%s' "$BIG" | REQUEST_METHOD=POST CONTENT_LENGTH="$BIG_LEN" QUERY_STRING='action=save' $BIN)") | ||
| 233 | +check "an oversized body is refused with JSON" '{"ok":false' "$R" | ||
| 234 | +R2=$(printf '%s' "$BIG" | REQUEST_METHOD=POST CONTENT_LENGTH="$BIG_LEN" QUERY_STRING='action=save' $BIN) | ||
| 235 | +check "an oversized body is 413" 'Status: 413' "$R2" | ||
| 236 | +json_ok "the refusal names the limit" "$(body "$R2")" "'512' in d['error']" | ||
| 237 | +# A body just under the cap still saves. | ||
| 238 | +python3 - "$WORK/at_cap.json" <<'PY' | ||
| 239 | +import json, sys | ||
| 240 | +json.dump({"title": "cap", "body": "y" * (512 * 1024 - 200)}, open(sys.argv[1], "w")) | ||
| 241 | +PY | ||
| 242 | +CAP_LEN=$(wc -c < "$WORK/at_cap.json" | tr -d ' ') | ||
| 243 | +SC=$(body "$(REQUEST_METHOD=POST CONTENT_LENGTH="$CAP_LEN" QUERY_STRING='action=save' $BIN < "$WORK/at_cap.json")") | ||
| 244 | +json_ok "a body under the cap still saves" "$SC" "d['ok'] is True" | ||
| 245 | +CAPID=$(printf '%s' "$SC" | python3 -c "import json,sys;print(json.load(sys.stdin)['note']['id'])" 2>/dev/null) | ||
| 246 | +[ -n "$CAPID" ] && pass "the large note got an id" || fail "large note not saved" | ||
| 247 | +api_post 'action=delete' "{\"id\":\"$CAPID\"}" >/dev/null | ||
| 248 | + | ||
| 249 | +# ---------------------------------------------------------------- render / XSS | ||
| 250 | +section "mode 2i - markdown render (XSS inert)" | ||
| 251 | +R1=$(api_post 'action=render' '{"body":"# Title\n\nA **bold** word and `code`."}') | ||
| 252 | +json_ok "render answers ok:true" "$R1" "d['ok'] is True" | ||
| 253 | +json_ok "render emits an h1" "$R1" "'<h1>Title</h1>' in d['html']" | ||
| 254 | +json_ok "render emits strong" "$R1" "'<strong>bold</strong>' in d['html']" | ||
| 255 | +json_ok "render emits code" "$R1" "'<code>code</code>' in d['html']" | ||
| 256 | +R2=$(api_post 'action=render' '{"body":"<script>alert(1)</script>"}') | ||
| 257 | +json_ok "a raw script tag is escaped" "$R2" "'<' not in d['html'].replace('<','') or '<script>' not in d['html']" | ||
| 258 | +json_ok "the script tag became entities" "$R2" "'<script>' in d['html']" | ||
| 259 | +R3=$(api_post 'action=render' '{"body":"[click](javascript:alert(1))"}') | ||
| 260 | +json_ok "a javascript: link is not turned into an anchor" "$R3" "'<a ' not in d['html']" | ||
| 261 | +json_ok "the javascript: link text is still escaped" "$R3" "'javascript:alert(1)' in d['html']" | ||
| 262 | +R4=$(api_post 'action=render' '{"body":"[ok](https://example.com/x?a=1)"}') | ||
| 263 | +json_ok "an https link becomes an anchor" "$R4" "'<a href=\"https://example.com/x?a=1\"' in d['html']" | ||
| 264 | +json_ok "the anchor carries rel=noopener" "$R4" "'noopener noreferrer' in d['html']" | ||
| 265 | +R5=$(api_post 'action=render' '{"body":"<img src=x onerror=alert(1)>"}') | ||
| 266 | +json_ok "an img onerror payload is escaped" "$R5" "'<img' not in d['html']" | ||
| 267 | +json_ok "the img payload shows as text" "$R5" "'<img' in d['html']" | ||
| 268 | +R6=$(api_post 'action=render' '{"body":"\"quoted\" & <tagged> \u0027single\u0027"}') | ||
| 269 | +json_ok "quotes and ampersands are escaped" "$R6" "'"' in d['html'] and '&' in d['html'] and ''' in d['html']" | ||
| 270 | +R7=$(api_post 'action=render' '{"body":"```\ncode <b> here\n```"}') | ||
| 271 | +json_ok "fenced code becomes a pre/code block" "$R7" "'<pre><code>' in d['html']" | ||
| 272 | +json_ok "code content is escaped" "$R7" "'<b>' in d['html']" | ||
| 273 | +R8=$(api_post 'action=render' '{"body":"- one\n- two"}') | ||
| 274 | +json_ok "dash lists become ul/li" "$R8" "'<ul>' in d['html'] and '<li>one</li>' in d['html']" | ||
| 275 | +R9=$(api_post 'action=render' '{"body":"1. one\n2. two"}') | ||
| 276 | +json_ok "numbered lists become ol/li" "$R9" "'<ol>' in d['html'] and '<li>one</li>' in d['html']" | ||
| 277 | +R10=$(api_post 'action=render' '{"body":"> a quote"}') | ||
| 278 | +json_ok "a blockquote renders" "$R10" "'<blockquote>a quote</blockquote>' in d['html']" | ||
| 279 | +R11=$(api_post 'action=render' '{"body":"---"}') | ||
| 280 | +json_ok "a horizontal rule renders" "$R11" "'<hr>' in d['html']" | ||
| 281 | +R12=$(api_post 'action=render' '{"body":"*em* and _em2_"}') | ||
| 282 | +json_ok "italic renders" "$R12" "'<em>em</em>' in d['html'] and '<em>em2</em>' in d['html']" | ||
| 283 | +check "render without a body is 400" 'Status: 400' \ | ||
| 284 | + "$(printf '{}' | REQUEST_METHOD=POST CONTENT_LENGTH=2 QUERY_STRING='action=render' $BIN)" | ||
| 285 | + | ||
| 286 | +# ---------------------------------------------------------------- pin + ordering | ||
| 287 | +section "mode 2j - pin and ordering" | ||
| 288 | +PN=$(api_post "action=pin&id=$ID2" '{"pin":1}') | ||
| 289 | +json_ok "pin answers ok:true" "$PN" "d['ok'] is True and d['pinned']==1" | ||
| 290 | +json_ok "the pinned note sorts first" "$(api 'action=list')" "d['notes'][0]['id']=='$ID2'" | ||
| 291 | +PN2=$(api_post "action=pin&id=$ID2" '{"pin":0}') | ||
| 292 | +json_ok "unpin answers ok:true" "$PN2" "d['pinned']==0" | ||
| 293 | +json_ok "unpinning drops it out of the pin slot" "$(api "action=get&id=$ID2")" "d['note']['pinned']==0" | ||
| 294 | +PN3=$(api_post "action=pin&id=$ID1" '{"pin":true}') | ||
| 295 | +json_ok "a JSON boolean pin value is accepted" "$PN3" "d['pinned']==1" | ||
| 296 | +PNB=$(api_post 'action=pin&id=zzzzzzzzzzzz' '{"pin":1}') | ||
| 297 | +check "pinning an unknown id is 404" 'Status: 404' \ | ||
| 298 | + "$(printf '{"pin":1}' | REQUEST_METHOD=POST CONTENT_LENGTH=9 QUERY_STRING='action=pin&id=zzzzzzzzzzzz' $BIN)" | ||
| 299 | + | ||
| 300 | +# ---------------------------------------------------------------- search | ||
| 301 | +section "mode 2k - search" | ||
| 302 | +api_post 'action=save' '{"title":"Zebra striping","body":"alpha bravo charlie"}' >/dev/null | ||
| 303 | +api_post 'action=save' '{"title":"Gamma","body":"nothing to see"}' >/dev/null | ||
| 304 | +SR1=$(api 'action=search&q=zebra') | ||
| 305 | +json_ok "search matches a title" "$SR1" "d['count']==1 and 'Zebra' in d['notes'][0]['title']" | ||
| 306 | +SR2=$(api 'action=search&q=bravo') | ||
| 307 | +json_ok "search matches the body text" "$SR2" "d['count']==1" | ||
| 308 | +SR3=$(api 'action=search&q=NOTHING') | ||
| 309 | +json_ok "search is case-insensitive" "$SR3" "d['count']==1" | ||
| 310 | +SR4=$(api 'action=search&q=zzzznotfound') | ||
| 311 | +json_ok "a search miss returns count 0" "$SR4" "d['count']==0" | ||
| 312 | +SR5=$(api 'action=search&q=') | ||
| 313 | +json_ok "an empty query lists everything" "$SR5" "d['count']>=4" | ||
| 314 | + | ||
| 315 | +# ---------------------------------------------------------------- delete/trash | ||
| 316 | +section "mode 2l - delete moves to .trash" | ||
| 317 | +DEL=$(api_post "action=delete&id=$ID2" '{}') | ||
| 318 | +json_ok "delete answers ok:true" "$DEL" "d['ok'] is True and d['trash'] is True" | ||
| 319 | +[ -f "$NOTES_DIR/.trash/$ID2.md" ] && pass "the body landed in .trash" || fail "no file in .trash" | ||
| 320 | +json_ok "the deleted note is gone from list" "$(api 'action=list')" "all(n['id']!='$ID2' for n in d['notes'])" | ||
| 321 | +check "get of a deleted id is 404" 'Status: 404' "$(apiraw "action=get&id=$ID2")" | ||
| 322 | +check "deleting twice is 404 the second time" 'Status: 404' \ | ||
| 323 | + "$(printf '{}' | REQUEST_METHOD=POST CONTENT_LENGTH=2 QUERY_STRING="action=delete&id=$ID2" $BIN)" | ||
| 324 | + | ||
| 325 | +# ---------------------------------------------------------------- HTML UI | ||
| 326 | +section "mode 3 - HTML UI" | ||
| 327 | +H=$(QUERY_STRING='' $BIN) | ||
| 328 | +check "HTML page has the text/html Content-Type" 'Content-Type: text/html; charset=utf-8' "$H" | ||
| 329 | +check "HTML page is a doctype" '<!DOCTYPE html>' "$H" | ||
| 330 | +check "HTML page names the plugin" '<title>notes</title>' "$H" | ||
| 331 | +check "HTML page has a CSP header" 'Content-Security-Policy' "$H" | ||
| 332 | +check "CSP forbids remote script sources" "default-src 'none'" "$H" | ||
| 333 | +check_not "no external script tag (no CDN)" '<script src=' "$H" | ||
| 334 | +check_not "no cdnjs" 'cdnjs' "$H" | ||
| 335 | +check_not "no unpkg" 'unpkg' "$H" | ||
| 336 | +check_not "no jsdelivr" 'jsdelivr' "$H" | ||
| 337 | +check_not "no jQuery" 'jquery' "$H" | ||
| 338 | +check "the theme prepaint script is inline" 'data-theme' "$H" | ||
| 339 | +check "the theme handoff listener is present" 'sx-theme' "$H" | ||
| 340 | +check "the bot token block is inlined" '--bg-card' "$H" | ||
| 341 | +check_not "no plugin-private palette variable" '--surface2:#' "$H" | ||
| 342 | +check "the direct route is used for API calls" '/plugin_notes' "$H" | ||
| 343 | +check "the hub route is used when ?plugin= is set" '/plugins?plugin=' "$H" | ||
| 344 | +check "autosave debounce exists" 'setTimeout(function(){save();},800)' "$H" | ||
| 345 | +check "the saved/unsaved pill exists" "id=\"state\"" "$H" | ||
| 346 | +check "Ctrl/Cmd+S is wired" "'s'" "$H" | ||
| 347 | +check "Ctrl/Cmd+K is wired" "'k'" "$H" | ||
| 348 | +check "a nested-pane layout exists" 'grid-template-columns' "$H" | ||
| 349 | +check "one pane is dropped under 700px" 'max-width:700px' "$H" | ||
| 350 | +check "embed mode hides the theme toggle" 'embedded' "$H" | ||
| 351 | +check_not "no emoji in the page" '😀' "$H" | ||
| 352 | +check "inline SVG is used for icons" '<svg viewBox' "$H" | ||
| 353 | +check "the product name is SCORPIOX BOT when mentioned" 'SCORPIOX BOT' "$(cat README.md)" | ||
| 354 | +HE=$(QUERY_STRING='embed=1' $BIN) | ||
| 355 | +check "embed=1 still serves the page" '<!DOCTYPE html>' "$HE" | ||
| 356 | + | ||
| 357 | +# ---------------------------------------------------------------- storage layout | ||
| 358 | +section "storage layout" | ||
| 359 | +[ -f "$NOTES_DIR/index.json" ] && pass "index.json lives in the notes dir" || fail "index.json missing" | ||
| 360 | +check "index.json declares a version" '"version":1' "$(cat "$NOTES_DIR/index.json")" | ||
| 361 | +check "index.json stores the notes array" '"notes"' "$(cat "$NOTES_DIR/index.json")" | ||
| 362 | +NOTES_DIR="$WORK/other" QUERY_STRING='action=list' $BIN >/dev/null | ||
| 363 | +[ -d "$WORK/other" ] && pass "NOTES_DIR overrides the storage location" || fail "NOTES_DIR ignored" | ||
| 364 | +[ -d "$WORK/other/.trash" ] && pass "NOTES_DIR gets its own .trash" || fail "NOTES_DIR has no .trash" | ||
| 365 | +N1=$(NOTES_DIR="$WORK/other" QUERY_STRING='action=list' $BIN) | ||
| 366 | +json_ok "an empty NOTES_DIR starts empty (no leakage)" "$(body "$N1")" "d['count']==0" | ||
| 367 | + | ||
| 368 | +# ---------------------------------------------------------------- build hygiene | ||
| 369 | +section "build hygiene" | ||
| 370 | +[ -f src/ui.html ] && pass "src/ui.html is the readable page source" || fail "src/ui.html missing" | ||
| 371 | +[ -f src/ui_html.h ] && pass "src/ui_html.h is generated next to the source" || fail "ui_html.h missing" | ||
| 372 | +if command -v python3 >/dev/null 2>&1; then | ||
| 373 | + python3 tools/gen_ui.py --check >/dev/null 2>&1 \ | ||
| 374 | + && pass "ui_html.h matches ui.html (generator is in sync)" \ | ||
| 375 | + || fail "ui_html.h is stale - run tools/gen_ui.py" | ||
| 376 | +fi | ||
| 377 | +grep -q '_WIN32_WINNT 0x0601' src/plugin_notes.c \ | ||
| 378 | + && pass "_WIN32_WINNT is raised before the includes" || fail "_WIN32_WINNT missing" | ||
| 379 | +grep -q '_DARWIN_C_SOURCE' src/plugin_notes.c \ | ||
| 380 | + && pass "_DARWIN_C_SOURCE is defined for Apple" || fail "_DARWIN_C_SOURCE missing" | ||
| 381 | +grep -q 'MoveFileExA' src/plugin_notes.c \ | ||
| 382 | + && pass "Windows writes use MoveFileExA with REPLACE_EXISTING" || fail "no MoveFileExA" | ||
| 383 | +grep -q 'REPLACE_EXISTING' src/plugin_notes.c \ | ||
| 384 | + && pass "the Windows replace flag is present" || fail "REPLACE_EXISTING missing" | ||
| 385 | +grep -q 'require_node_auth' src/plugin_notes.c \ | ||
| 386 | + && pass "require_node_auth() gates the API" || fail "no node auth gate" | ||
| 387 | +grep -q 'CONTENT_LENGTH' src/plugin_notes.c \ | ||
| 388 | + && pass "the body read is guarded on CONTENT_LENGTH" || fail "no CONTENT_LENGTH guard" | ||
| 389 | +grep -q 'BODY_MAX' src/plugin_notes.c \ | ||
| 390 | + && pass "a body cap constant exists" || fail "no body cap" | ||
| 391 | +grep -q 'valid_id' src/plugin_notes.c \ | ||
| 392 | + && pass "ids are validated before touching the filesystem" || fail "no id validation" | ||
| 393 | +for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json .gitignore; do | ||
| 394 | + [ -f "$f" ] && pass "$f present" || fail "$f missing" | ||
| 395 | +done | ||
| 396 | +check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)" | ||
| 397 | +check "README documents the actions" 'action=save' "$(cat README.md)" | ||
| 398 | +check "README documents the security model" 'escaped' "$(cat README.md)" | ||
| 399 | +check "plugin.json declares the slug" '"slug": "notes"' "$(cat plugin.json)" | ||
| 400 | +check "plugin.json declares the utilities category" '"category": "utilities"' "$(cat plugin.json)" | ||
| 401 | +check "plugin.json declares the id" '"id": "plugin_notes"' "$(cat plugin.json)" | ||
| 402 | +check "plugin.json declares MIT" '"license": "MIT"' "$(cat plugin.json)" | ||
| 403 | +check ".gitignore ignores the binary" 'plugin_notes' "$(cat .gitignore)" | ||
| 404 | +check ".gitignore ignores __pycache__" '__pycache__' "$(cat .gitignore)" | ||
| 405 | + | ||
| 406 | +# ---------------------------------------------------------------- fortify | ||
| 407 | +section "hardened build" | ||
| 408 | +if cc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$WORK/plugin_notes_fort" src/plugin_notes.c 2>"$WORK/fort.err"; then | ||
| 409 | + pass "_FORTIFY_SOURCE=2 build compiles" | ||
| 410 | + FN=$(NOTES_DIR="$WORK/fortnotes" QUERY_STRING='action=list' "$WORK/plugin_notes_fort") | ||
| 411 | + json_ok "the fortified build answers list" "$(body "$FN")" "d['ok'] is True" | ||
| 412 | + FS=$(printf '{"title":"f","body":"fortified"}' | NOTES_DIR="$WORK/fortnotes" REQUEST_METHOD=POST CONTENT_LENGTH=31 QUERY_STRING='action=save' "$WORK/plugin_notes_fort") | ||
| 413 | + json_ok "the fortified build saves a note" "$(body "$FS")" "d['ok'] is True" | ||
| 414 | + FR=$(printf '{"body":"# ok"}' | NOTES_DIR="$WORK/fortnotes" REQUEST_METHOD=POST CONTENT_LENGTH=15 QUERY_STRING='action=render' "$WORK/plugin_notes_fort") | ||
| 415 | + json_ok "the fortified build renders markdown" "$(body "$FR")" "'<h1>' in d['html']" | ||
| 416 | +else | ||
| 417 | + fail "_FORTIFY_SOURCE=2 build failed"; sed 's/^/ /' "$WORK/fort.err" | head -5 | ||
| 418 | +fi | ||
| 419 | + | ||
| 420 | +# ---------------------------------------------------------------- cross targets | ||
| 421 | +section "cross-target artifacts" | ||
| 422 | +if [ -f plugin_notes.exe ]; then | ||
| 423 | + MAGIC=$(od -An -tx1 -N2 plugin_notes.exe | tr -d ' \n') | ||
| 424 | + [ "$MAGIC" = "4d5a" ] && pass "plugin_notes.exe starts with the MZ magic" || fail "PE magic wrong ($MAGIC)" | ||
| 425 | +else | ||
| 426 | + echo " (skip) plugin_notes.exe not built here" | ||
| 427 | +fi | ||
| 428 | +if [ -f plugin_notes.musl ]; then | ||
| 429 | + file plugin_notes.musl | grep -q 'statically linked' && pass "musl build is static" || fail "musl build is not static" | ||
| 430 | +else | ||
| 431 | + echo " (skip) plugin_notes.musl not built here" | ||
| 432 | +fi | ||
| 433 | +if [ -f plugin_notes.arm64 ]; then | ||
| 434 | + file plugin_notes.arm64 | grep -Eq 'ARM aarch64|aarch64' && pass "arm64 build is aarch64" || fail "arm64 build is not aarch64" | ||
| 435 | +else | ||
| 436 | + echo " (skip) plugin_notes.arm64 not built here" | ||
| 437 | +fi | ||
| 438 | + | ||
| 439 | +# ---------------------------------------------------------------- history audit | ||
| 440 | +section "git history secret audit" | ||
| 441 | +if git rev-parse --git-dir >/dev/null 2>&1; then | ||
| 442 | + ALL="$WORK/history.txt" | ||
| 443 | + git log -p --all 2>/dev/null \ | ||
| 444 | + | grep -v '^Author: ' \ | ||
| 445 | + | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "|scan "' \ | ||
| 446 | + > "$ALL" || : > "$ALL" | ||
| 447 | + | ||
| 448 | + audit() { # audit <label> <regex> | ||
| 449 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | ||
| 450 | + if [ -n "$H" ]; then | ||
| 451 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | ||
| 452 | + else | ||
| 453 | + pass "history clean: $1" | ||
| 454 | + fi | ||
| 455 | + } | ||
| 456 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 457 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 458 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 459 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 460 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 461 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 462 | + PK="pico""bot"; WT=".work""trees" | ||
| 463 | + audit "internal fleet path" "/codebases/${PK}|${WT}" | ||
| 464 | + audit "run token assignment" 'RUNNER_'"PASS=" | ||
| 465 | +else | ||
| 466 | + echo " skip history audit (not a git checkout)" | ||
| 467 | +fi | ||
| 468 | + | ||
| 469 | +# ---------------------------------------------------------------- cleanup | ||
| 470 | +rm -rf "$WORK" | ||
| 471 | + | ||
| 472 | +# ---------------------------------------------------------------- summary | ||
| 473 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | ||
| 474 | +printf ' passed: %d\n' "$PASS" | ||
| 475 | +printf ' failed: %d\n' "$FAIL" | ||
| 476 | +if [ "$FAIL" -ne 0 ]; then | ||
| 477 | + printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0" | ||
| 478 | + exit 1 | ||
| 479 | +fi | ||
| 480 | +if [ "$PASS" -lt 100 ]; then | ||
| 481 | + printf ' %sRESULT: TOO FEW CHECKS (%d < 100)%s\n' "$C_BAD" "$PASS" "$C_0" | ||
| 482 | + exit 1 | ||
| 483 | +fi | ||
| 484 | +printf ' %sRESULT: OK%s\n' "$C_OK" "$C_0" | ||
| 485 | +exit 0 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..2ba72f9 | index 0000000..2ba72f9 | ||
| --- /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_NOTES_UI_HTML_H\n" | ||
| 75 | + "#define SX_NOTES_UI_HTML_H\n" | ||
| 76 | + "\n" | ||
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | ||
| 78 | + "\n" | ||
| 79 | + "#endif /* SX_NOTES_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 |