Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion relay/herdr_relay.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,25 @@ async def process_request(connection, request):
from websockets.http11 import Response
from websockets.datastructures import Headers

path = (request.path or "/").split("?")[0]
static_files = {
"/HackNerdFont-Regular.woff2": ("HackNerdFont-Regular.woff2", "font/woff2"),
"/HackNerdFont-LICENSE.txt": ("HackNerdFont-LICENSE.txt", "text/plain; charset=utf-8"),
}
if path in static_files:
filename, content_type = static_files[path]
asset_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "..", "web", filename
)
if os.path.isfile(asset_path):
with open(asset_path, "rb") as f:
body = f.read()
headers = Headers([
("Content-Type", content_type),
("Cache-Control", "public, max-age=3600, must-revalidate"),
])
return Response(200, "OK", headers, body)

# Token auth (if configured)
if AUTH_TOKEN:
token = None
Expand Down Expand Up @@ -480,8 +499,15 @@ async def handle_client(ws):
await ws.send(json.dumps({"type": "error", "message": "unknown pane_id"}))
continue
lines = msg.get("lines", "30")
read_format = msg.get("format", "text")
if read_format not in {"text", "ansi"}:
await ws.send(json.dumps({"type": "error", "message": "invalid pane read format"}))
continue
remote = pane_remote_map.get(pane_id)
content = run_herdr("pane", "read", pane_id, "--lines", str(lines), "--source", "recent", remote=remote)
content = run_herdr(
"pane", "read", pane_id, "--lines", str(lines), "--source", "recent",
"--format", read_format, remote=remote
)
await ws.send(json.dumps({"type": "pane_content", "pane_id": pane_id, "content": content}))
elif msg_type == "send_keys":
pane_id = msg["pane_id"]
Expand Down
21 changes: 17 additions & 4 deletions tests/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@
PASS=0; FAIL=0
DIR="$(cd "$(dirname "$0")/.." && pwd)"

if command -v python3 >/dev/null 2>&1 && python3 -c "pass" >/dev/null 2>&1; then
PYTHON=python3
elif command -v python >/dev/null 2>&1 && python -c "pass" >/dev/null 2>&1; then
PYTHON=python
else
echo "Python 3 is required"
exit 1
fi

assert_eq() {
if [ "$1" = "$2" ]; then PASS=$((PASS+1)); echo " pass: $3"
else FAIL=$((FAIL+1)); echo " FAIL: $3 (expected '$2', got '$1')"; fi
Expand All @@ -14,9 +23,13 @@ echo ""
# --- Relay ---
echo "=== Relay ==="
echo "1. relay syntax"
python3 -c "import ast; ast.parse(open('$DIR/relay/herdr_relay.py').read())" 2>/dev/null
"$PYTHON" -c "import ast, pathlib, sys; ast.parse(pathlib.Path(sys.argv[1]).read_text(encoding='utf-8'))" "$DIR/relay/herdr_relay.py" 2>/dev/null
assert_eq "$?" "0" "herdr_relay.py parses"

echo "1b. relay behavior"
"$PYTHON" -m unittest discover -s "$DIR/tests" -p "test_*.py"
assert_eq "$?" "0" "relay behavior"

echo "2. PEP 723 metadata"
grep -q "requires-python" "$DIR/relay/herdr_relay.py"
assert_eq "$?" "0" "inline deps present"
Expand All @@ -29,11 +42,11 @@ assert_eq "$?" "0" "start.sh +x"
echo ""
echo "=== Telegram bot ==="
echo "4. telegram bot syntax"
python3 -c "import ast; ast.parse(open('$DIR/relay/herdr_telegram.py').read())" 2>/dev/null
"$PYTHON" -c "import ast, pathlib, sys; ast.parse(pathlib.Path(sys.argv[1]).read_text(encoding='utf-8'))" "$DIR/relay/herdr_telegram.py" 2>/dev/null
assert_eq "$?" "0" "herdr_telegram.py parses"

echo "5. telegram demo bot syntax"
python3 -c "import ast; ast.parse(open('$DIR/relay/herdr_telegram_demo.py').read())" 2>/dev/null
"$PYTHON" -c "import ast, pathlib, sys; ast.parse(pathlib.Path(sys.argv[1]).read_text(encoding='utf-8'))" "$DIR/relay/herdr_telegram_demo.py" 2>/dev/null
assert_eq "$?" "0" "herdr_telegram_demo.py parses"

echo "6. telegram bot has all commands"
Expand All @@ -58,7 +71,7 @@ assert_eq "$?" "0" "agent state tests"
echo ""
echo "=== TUI ==="
echo "10. TUI syntax"
python3 -c "import ast; ast.parse(open('$DIR/relay/herdr_tui.py').read())" 2>/dev/null
"$PYTHON" -c "import ast, pathlib, sys; ast.parse(pathlib.Path(sys.argv[1]).read_text(encoding='utf-8'))" "$DIR/relay/herdr_tui.py" 2>/dev/null
assert_eq "$?" "0" "herdr_tui.py parses"

# --- Web app ---
Expand Down
126 changes: 126 additions & 0 deletions tests/test_ansi_terminal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import asyncio
import importlib.util
import json
import logging
import os
from pathlib import Path
import sys
import tempfile
import types
import unittest
from contextlib import contextmanager
from unittest import mock
import uuid


RELAY_PATH = Path(__file__).resolve().parents[1] / "relay" / "herdr_relay.py"
WEB_DIR = Path(__file__).resolve().parents[1] / "web"


class _Closed(Exception):
pass


def _websocket_stubs():
websockets = types.ModuleType("websockets")
websockets.__path__ = []
asyncio_module = types.ModuleType("websockets.asyncio")
asyncio_module.__path__ = []
server = types.ModuleType("websockets.asyncio.server")
server.serve = object()
exceptions = types.ModuleType("websockets.exceptions")
exceptions.ConnectionClosedError = _Closed
exceptions.ConnectionClosedOK = _Closed
return {
"websockets": websockets,
"websockets.asyncio": asyncio_module,
"websockets.asyncio.server": server,
"websockets.exceptions": exceptions,
}


@contextmanager
def loaded_relay():
module_name = f"ansi_relay_test_{uuid.uuid4().hex}"
logger = logging.getLogger("herdr-relay")
original_handlers = tuple(logger.handlers)
relay_dir = str(RELAY_PATH.parent)
added_relay_dir = relay_dir not in sys.path
if added_relay_dir:
sys.path.insert(0, relay_dir)
with tempfile.TemporaryDirectory() as log_dir, mock.patch.dict(
os.environ, {"HERDR_LOG_DIR": log_dir}, clear=False
), mock.patch.dict(sys.modules, _websocket_stubs(), clear=False):
spec = importlib.util.spec_from_file_location(module_name, RELAY_PATH)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
try:
spec.loader.exec_module(module)
logger.disabled = True
yield module
finally:
sys.modules.pop(module_name, None)
if added_relay_dir:
sys.path.remove(relay_dir)
for handler in tuple(logger.handlers):
if handler not in original_handlers:
logger.removeHandler(handler)
handler.close()
audit_logger = logging.getLogger("herdr-audit")
for handler in tuple(audit_logger.handlers):
audit_logger.removeHandler(handler)
handler.close()
logger.disabled = False


class _WebSocket:
remote_address = ("127.0.0.1", 1)
request = types.SimpleNamespace(headers={"User-Agent": "test", "Origin": ""})

def __init__(self, message):
self.messages = iter([json.dumps(message)])
self.sent = []

def __aiter__(self):
return self

async def __anext__(self):
try:
return next(self.messages)
except StopIteration:
raise StopAsyncIteration

async def send(self, value):
self.sent.append(json.loads(value))


class AnsiTransportTests(unittest.TestCase):
def test_bundled_font_and_renderer_assets_are_present(self):
font = WEB_DIR / "HackNerdFont-Regular.woff2"
license_file = WEB_DIR / "HackNerdFont-LICENSE.txt"
page = (WEB_DIR / "index.html").read_text(encoding="utf-8")

self.assertGreater(font.stat().st_size, 100_000)
self.assertIn("Hack", license_file.read_text(encoding="utf-8"))
self.assertIn("HackNerdFont-Regular.woff2", page)
self.assertIn("function ansiFragment", page)
self.assertIn("format:'ansi'", page)

def test_pane_read_defaults_to_text_and_accepts_explicit_ansi(self):
for requested_format in (None, "ansi"):
with self.subTest(requested_format=requested_format), loaded_relay() as relay:
relay.known_panes.add("pane-1")
message = {"type": "read_pane", "pane_id": "pane-1", "lines": 5}
if requested_format:
message["format"] = requested_format
ws = _WebSocket(message)
with mock.patch.object(relay.subprocess, "run") as run:
run.return_value = types.SimpleNamespace(returncode=0, stdout="screen", stderr="")
asyncio.run(relay.handle_client(ws))
command = run.call_args.args[0]
self.assertEqual(command[-2:], ["--format", requested_format or "text"])
self.assertEqual(ws.sent[-1]["type"], "pane_content")


if __name__ == "__main__":
unittest.main()
2 changes: 1 addition & 1 deletion tests/test_telegram.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,7 @@ async def test_send_keys_requires_positive_relay_acknowledgement(self):

def test_relay_allows_numeric_approval_keys_and_acknowledges_them(self):
relay_path = ROOT / "relay" / "herdr_relay.py"
source = relay_path.read_text()
source = relay_path.read_text(encoding="utf-8")
tree = ast.parse(source)
safe_keys = next(
node.value
Expand Down
56 changes: 56 additions & 0 deletions web/HackNerdFont-LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
Hack Nerd Font

The bundled font is a Nerd Fonts patched build of Hack 3.003.
Hack: https://github.com/source-foundry/Hack
Nerd Fonts: https://github.com/ryanoasis/nerd-fonts

Hack licensing
==============

The work in the Hack project is Copyright 2018 Source Foundry Authors and licensed under the MIT License.

The work in the DejaVu project was committed to the public domain.

Bitstream Vera Sans Mono Copyright 2003 Bitstream Inc. and licensed under the Bitstream Vera License with Reserved Font Names "Bitstream" and "Vera".

MIT License
-----------

Copyright (c) 2018 Source Foundry Authors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

BITSTREAM VERA LICENSE
----------------------

Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions:

The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces.

The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Bitstream" or the word "Vera".

This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Bitstream Vera" names.

The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself.

THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.

Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org.
Binary file added web/HackNerdFont-Regular.woff2
Binary file not shown.
Loading