From a6b3a87d67b6d3c79e64b03fa120d0ddc6d9abca Mon Sep 17 00:00:00 2001 From: teaspoonai Date: Mon, 30 Nov 2026 15:13:57 -0600 Subject: [PATCH] brain: listen on the box alone, and refuse to start without GATEWAY_TOKEN (#477) The brain's port (7861) listened on 0.0.0.0, and an empty GATEWAY_TOKEN opened /talk, /talk/status and the config page to anyone who reached it. - The brain listens where BRAIN_LISTEN says: 127.0.0.1. A NemoClaw install adds the docker bridge's 172.18.0.1, bound with IP_FREEBIND, so the bridge may come up after the brain. --host takes a comma-separated list. A name, a scoped or an IPv4-mapped address is refused at the start. - No GATEWAY_TOKEN: the brain exits 78 (EX_CONFIG), and the unit's RestartPreventExitStatus=78 makes that one failure, not a loop. TEAPORT_ALLOW_NO_AUTH=1 runs a developer's brain open on purpose. A page in the agent's browser reaches 127.0.0.1 too, so loopback alone is no excuse for no token. - settings_access.gateway_token_ok is the one check for /talk, /talk/status and the config page on the port. token_matches("", "") is True, so the empty case is decided before the compare. - install.sh writes BRAIN_LISTEN on every full run. A repair run that can't see the sandbox seeds the bridge address on a NemoClaw box instead, and --only brain seeds it there too, before the new brain starts. - The Discord bridge sends the token now (BRIDGE_GATEWAY_TOKEN in bridge.env, from install.sh). It never did, so the brain refused it on every installed box. - teaport doctor: no token fails; a brain that refused its configuration is named, and --fix doesn't restart it; a port that answers beyond the box, or a NemoClaw BRAIN_LISTEN without the bridge, warns. - Docs: security "The brain's port", troubleshooting "The brain does not start without its token", configuration, architecture and cli; settings reference regenerated; citations moved. - Tests: test_brain_port.py (new); test_settings_access, test_config_ui, test_install_brain_only updated; the two SIP tests that start a brain without a token run it open on purpose; test_local_audio and test_wake_gate poll /talk/status with the token, and test_tts_pacing expects doctor's failure for a missing one. Co-Authored-By: Claude Opus 5.5 --- brain/teaport_brain/config_schema.toml | 33 ++- brain/teaport_brain/config_ui.py | 27 +- brain/teaport_brain/gateway_server.py | 144 +++++++-- brain/teaport_brain/pairing.py | 7 +- brain/teaport_brain/settings_access.py | 26 +- brain/tests/test_brain_port.py | 273 ++++++++++++++++++ brain/tests/test_call_experience.py | 1 + brain/tests/test_config_ui.py | 20 +- brain/tests/test_install_brain_only.py | 21 +- brain/tests/test_local_audio.py | 11 +- brain/tests/test_settings_access.py | 26 +- brain/tests/test_sip_fake_gateway.py | 1 + brain/tests/test_tts_pacing.py | 2 +- brain/tests/test_wake_gate.py | 12 +- bridge/discord/index.js | 4 + cli/teaport | 39 ++- .../docs/getting-started/installation.md | 12 +- docs/src/content/docs/guides/configuration.md | 36 +-- .../src/content/docs/guides/discord-bridge.md | 16 +- docs/src/content/docs/guides/faq.md | 2 +- docs/src/content/docs/guides/local-audio.md | 4 +- docs/src/content/docs/guides/phone-calls.md | 26 +- .../content/docs/guides/troubleshooting.md | 36 ++- docs/src/content/docs/guides/updating.md | 18 +- docs/src/content/docs/guides/wifi-setup.md | 2 +- docs/src/content/docs/index.mdx | 2 +- .../content/docs/reference/architecture.md | 6 +- docs/src/content/docs/reference/cli.md | 67 ++--- docs/src/content/docs/reference/installer.md | 30 +- docs/src/content/docs/reference/licenses.md | 4 +- docs/src/content/docs/reference/security.md | 26 +- docs/src/content/docs/reference/settings.md | 7 +- install.sh | 34 ++- systemd/teaport-brain.service.in | 3 + 34 files changed, 781 insertions(+), 197 deletions(-) create mode 100644 brain/tests/test_brain_port.py diff --git a/brain/teaport_brain/config_schema.toml b/brain/teaport_brain/config_schema.toml index 25877d49e..4648def7e 100644 --- a/brain/teaport_brain/config_schema.toml +++ b/brain/teaport_brain/config_schema.toml @@ -2249,9 +2249,29 @@ type = "secret" default = "" read = "startup" tier = "installer" -help = "Shared secret for /talk. Empty means anyone who can reach the port gets a full agent session and can replace a client's session by claiming its id; the brain warns loudly at startup." +help = "Shared secret for /talk, /talk/status and the configuration page on the brain's port. Without it the brain refuses to start, because anyone who reaches the port gets a full agent session and can replace a client's session by claiming its id." note = "Mirrored into the plugin config by install.sh. Never change one side alone." +[[settings]] +name = "TEAPORT_ALLOW_NO_AUTH" +store = "brain_env" +group = "installer" +type = "flag" +default = false +read = "startup" +tier = "installer" +help = "Let the brain run with no GATEWAY_TOKEN, open to anything that reaches its port. For a developer's brain or a test, never a device: an installed device always has a token." + +[[settings]] +name = "BRAIN_LISTEN" +store = "brain_env" +group = "installer" +type = "string" +default = "127.0.0.1" +read = "startup" +tier = "installer" +help = "The addresses the brain listens on, comma-separated IP addresses. Every client is on the device, so 127.0.0.1 alone; a NemoClaw install adds the docker bridge's 172.18.0.1, which the sandbox reaches the brain by. --host overrides it." + [[settings]] name = "MALLOC_ARENA_MAX" store = "brain_env" @@ -2575,6 +2595,17 @@ tier = "installer" help = "Derived from BRAIN_PORT." source = ["bridge/discord/index.js", "install.sh"] +[[settings]] +name = "BRIDGE_GATEWAY_TOKEN" +store = "bridge_env" +group = "bridge" +type = "secret" +default = "" +tier = "installer" +help = "The brain's GATEWAY_TOKEN, which the bridge sends on /talk. The brain admits no one without it." +note = "Copied from brain.env by install.sh. Never change one side alone." +source = ["bridge/discord/index.js", "install.sh"] + [[settings]] name = "TEAPORT_VOICE" store = "bridge_env" diff --git a/brain/teaport_brain/config_ui.py b/brain/teaport_brain/config_ui.py index d0dc52860..ca7025cf9 100644 --- a/brain/teaport_brain/config_ui.py +++ b/brain/teaport_brain/config_ui.py @@ -17,8 +17,9 @@ GET /api/licenses and GET /api/licenses/{package} (licenses.py) Auth is the same shared secret /talk uses: GATEWAY_TOKEN, as a bearer header -or ?token=. Unset means open, exactly like /talk, and the brain already warns -about that at startup. On the brain's own port, plain HTTP, the page and its routes +or ?token=. Unset opens nothing, exactly like /talk, and the brain won't start +without it (#477) unless it runs open on purpose (TEAPORT_ALLOW_NO_AUTH, a developer's). +On the brain's own port, plain HTTP, the page and its routes answer only the box itself (_on_box_or_settings): over the LAN the token would travel in cleartext. Other devices use the front door: the routes are mounted again under /settings (gateway_server), on the Settings site over HTTPS, where a Settings session @@ -101,10 +102,11 @@ def _on_box_or_settings(request: Request) -> None: """Every route here, on either mount. Under /settings, SettingsGuard has already - let only the Settings site through. On the brain's own port, plain HTTP open to the - LAN, only the box itself (settings_access.on_box): the token would cross the network - in cleartext, and an unset token would open the page to anyone on it. Elsewhere the - answer names the Settings site, where the same token works over HTTPS.""" + let only the Settings site through. On the brain's own port, plain HTTP, only the box + itself (settings_access.on_box): the token would otherwise cross the network in + cleartext. The port listens on the box alone (BRAIN_LISTEN, #477), but a hand-set + --host or the NemoClaw bridge widens it, and this check holds whatever it listens on. + Elsewhere the answer names the Settings site, where the same token works over HTTPS.""" if request.url.path.startswith(settings_access.PREFIX) or settings_access.on_box(request): return where = (f" at {settings_access.origin()}{settings_access.PAGE_PATH}" @@ -130,19 +132,20 @@ def _authorize(request: Request) -> None: url = getattr(request, "url", None) # a bare stand-in (a test's) has none if getattr(url, "path", "").startswith(settings_access.PREFIX): # The front door's mount (gateway_server): the owner's Settings session or the - # operator's token as a bearer header -- an unset token opens the box itself, - # never the front door. + # operator's token as a bearer header -- an unset token never opens the front + # door, even on a brain that runs open on purpose. if not settings_access.authorized(request): raise HTTPException(status_code=401, detail="no Settings session") return want = _token() - if not want: - return got = settings_access.bearer(request) if got is None: got = request.query_params.get("token", "") - if not settings_access.token_matches(got, want): - raise HTTPException(status_code=401, detail="bad or missing token") + # no token set opens nothing (#477): an agent's browser page on the box reaches here too + if not settings_access.gateway_token_ok(got, want): + raise HTTPException(status_code=401, detail=( + "bad or missing token" if want else + "this box has no GATEWAY_TOKEN: run the installer again (teaport doctor)")) # ------------------------------------------------------------------ env files diff --git a/brain/teaport_brain/gateway_server.py b/brain/teaport_brain/gateway_server.py index 9a968f31e..761b05256 100644 --- a/brain/teaport_brain/gateway_server.py +++ b/brain/teaport_brain/gateway_server.py @@ -24,14 +24,17 @@ # session arbiter's (session_arbiter.py). This module is just the OpenClaw WebSocket # transport + FastAPI plumbing around them. # -# Usage: teaport-brain [--host 0.0.0.0] [--port 7861] +# Usage: teaport-brain [--host ADDR[,ADDR...]] [--port 7861] +# --host defaults to BRAIN_LISTEN (127.0.0.1: the box alone, #477). # Requires the engine reachable at TEAPORT_URL (default ws://127.0.0.1:8000). # import argparse import asyncio +import ipaddress import json import logging import re +import socket import sys import time from contextlib import asynccontextmanager @@ -72,14 +75,26 @@ from teaport_brain.settings import setting LISTEN_PORT = setting("GATEWAY_PORT") -# Shared secret for /talk. When set, a client must present it as ?token= on -# the WebSocket URL (the teaport-realtime plugin sends its TEAPORT_GATEWAY_TOKEN -# env / provider-config token); a missing or wrong token is rejected BEFORE the -# pipeline — and before the session arbiter — runs. When unset, anyone who can reach -# this port gets a full agent session (memory read/write tools included) and can -# replace a client's session by claiming its ?client= id, so we log a loud warning at -# startup. +# Shared secret for /talk. A client must present it as ?token= on the WebSocket +# URL (the teaport-realtime plugin sends its TEAPORT_GATEWAY_TOKEN env / provider-config +# token); a missing or wrong token is rejected BEFORE the pipeline — and before the +# session arbiter — runs. Without one, anyone who could reach this port would get a full +# agent session (memory read/write tools included) and could replace a client's session +# by claiming its ?client= id -- a page in the agent's own browser included, which +# reaches 127.0.0.1 -- so the brain refuses to start without it (#477), unless +# TEAPORT_ALLOW_NO_AUTH says it is open on purpose (a developer's). GATEWAY_TOKEN = setting("GATEWAY_TOKEN") +# The exit status of a start refused for its configuration (sysexits EX_CONFIG): the +# unit's RestartPreventExitStatus, so systemd shows one failure, not a restart loop. +EXIT_CONFIG = 78 +# Where the brain listens (#477). Every client is on the box: the room's bridge, the +# plugin, Caddy, the CLI, all at 127.0.0.1. NemoClaw's sandbox is the one exception: it +# reaches the host over the docker bridge (install.sh writes its address here). +LISTEN = setting("BRAIN_LISTEN") +# IP_FREEBIND / IPV6_FREEBIND (Linux; the socket module has no names for them): bind an +# address no interface holds yet. The docker bridge appears after the brain starts, at +# docker's own pace; bound this way the brain needs no order and no retry for it. +_IP_FREEBIND, _IPV6_FREEBIND = 15, 78 # The close codes a /talk session ends with when the session arbiter (session_arbiter.py) # decides; 4000-4999 is the private range. Every other end — the session's own end, the # idle timeout, a brain shutdown — closes with 1000 or drops the socket. Clients that @@ -781,8 +796,9 @@ async def talk(websocket: WebSocket): # Auth BEFORE anything else: an unauthenticated socket must never reach the session # arbiter — otherwise any host that can reach this port can use the agent (and its # memory read/write tools), or claim a client's id and replace its session. - if GATEWAY_TOKEN and not settings_access.token_matches( - websocket.query_params.get("token"), GATEWAY_TOKEN): + # No configured token admits no one (#477): main() refuses to start without one, and + # this holds should that ever be bypassed (a test's app, an import elsewhere). + if not settings_access.gateway_token_ok(websocket.query_params.get("token"), GATEWAY_TOKEN): logger.warning("rejected /talk client: missing or bad token") await websocket.close(code=1008) return @@ -892,39 +908,117 @@ def redact_tokens_in_uvicorn_logs() -> None: access.addFilter(_QuietStatusPolls()) -def serve(host: str, port: int) -> None: - """uvicorn.run(app, host=, port=) with a readiness notification after the bind.""" - config = uvicorn.Config(app, host=host, port=port) +def listen_addresses(text: str | None) -> list[str]: + """BRAIN_LISTEN's (or --host's) addresses: IP literals, comma- or space-separated, + each once. A name is refused: it would be resolved once, at start, to whatever it + said then. ValueError says what is wrong.""" + addrs = list(dict.fromkeys(a for a in re.split(r"[\s,]+", text or "") if a)) + if not addrs: + raise ValueError("no address to listen on") + for a in addrs: + try: + ip = ipaddress.ip_address(a) + except ValueError: + raise ValueError(f"{a!r} is not an IP address") from None + # bound IPv6-only, these two never bind: refused here, not in a restart loop + if ip.version == 6 and (ip.scope_id or ip.ipv4_mapped): + raise ValueError(f"{a!r}: an IPv6 scoped or IPv4-mapped address; give it plainly") + return addrs + + +def listen_sockets(addrs: list[str], port: int) -> list[socket.socket]: + """One bound socket per address (uvicorn listens on them: Server.run(sockets=)). + One that isn't loopback is bound free (_IP_FREEBIND), so the docker bridge's address + may come up after the brain. OSError if any bind fails, none left open.""" + socks: list[socket.socket] = [] + try: + for a in addrs: + ip = ipaddress.ip_address(a) + family = socket.AF_INET6 if ip.version == 6 else socket.AF_INET + sock = socket.socket(family, socket.SOCK_STREAM) + socks.append(sock) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # as uvicorn's own + if family == socket.AF_INET6: + sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) + if not ip.is_loopback: + if family == socket.AF_INET6: + sock.setsockopt(socket.IPPROTO_IPV6, _IPV6_FREEBIND, 1) + else: + sock.setsockopt(socket.IPPROTO_IP, _IP_FREEBIND, 1) + sock.bind((a, port)) + except OSError: + for sock in socks: + sock.close() + raise + return socks + + +def serve(addrs: list[str], port: int) -> None: + """uvicorn.run(app, ...) on these addresses, with a readiness notification after the + bind.""" + # host only names the server in uvicorn's own lines: it listens on the sockets + config = uvicorn.Config(app, host=addrs[0], port=port) redact_tokens_in_uvicorn_logs() server = _ReadyServer(config) try: - server.run() + socks = listen_sockets(addrs, port) + except OSError as e: + logger.error(f"cannot listen on {', '.join(addrs)} port {port}: {e}") + sys.exit(3) # uvicorn.run's own exit status for a server that never started + try: + server.run(sockets=socks) except KeyboardInterrupt: # as uvicorn.run: it re-raises a Ctrl-C after shutting down pass if not server.started: - sys.exit(3) # uvicorn.run's own exit status for a server that never started + sys.exit(3) + + +def refuse_without_token() -> None: + """No GATEWAY_TOKEN: exit EXIT_CONFIG, unless the brain is open on purpose + (TEAPORT_ALLOW_NO_AUTH, a developer's), which is said loudly instead (#477).""" + if GATEWAY_TOKEN: + return + if not settings_access.open_without_token(): + logger.error( + "GATEWAY_TOKEN is not set in brain.env, so the brain will not start: without " + "it anyone who reaches /talk gets a full agent session (memory tools included). " + "Run the installer again: it writes the token for the brain and every client " + "of it ('teaport doctor' says more). A developer's brain can run open on " + "purpose with TEAPORT_ALLOW_NO_AUTH=1.") + sys.exit(EXIT_CONFIG) + logger.warning( + "GATEWAY_TOKEN is not set and TEAPORT_ALLOW_NO_AUTH=1: /talk is OPEN. Anyone who " + "reaches this port can use the agent (and its memory tools) and replace a " + "client's session.") def main(): parser = argparse.ArgumentParser( description="teaport OpenClaw gateway-relay voice server" ) - parser.add_argument("--host", default="0.0.0.0") + parser.add_argument("--host", default=None, + help="address(es) to listen on, comma-separated (default: " + "BRAIN_LISTEN, 127.0.0.1)") parser.add_argument("--port", type=int, default=LISTEN_PORT) args = parser.parse_args() conversation_log.install() - if not GATEWAY_TOKEN: - logger.warning( - "GATEWAY_TOKEN is not set — /talk is UNAUTHENTICATED: anyone who can " - "reach this port can use the agent (and its memory tools) and replace " - "a client's session. Set GATEWAY_TOKEN (server) + TEAPORT_GATEWAY_TOKEN " - "(plugin) except on a trusted network." - ) + refuse_without_token() + try: + addrs = listen_addresses(args.host or LISTEN) + except ValueError as e: + logger.error(f"{'--host' if args.host else 'BRAIN_LISTEN'}: {e}") + sys.exit(EXIT_CONFIG) + wider = [a for a in addrs if not ipaddress.ip_address(a).is_loopback] + if wider: + logger.info(f"listening beyond the box too, on {', '.join(wider)}: /talk takes " + "only GATEWAY_TOKEN there") logger.info(agent_backend.startup_line()) logger.info("Priming TTS service...") make_tts() # warm the engine TTS client once at startup (G2P/synthesis are engine-side) - logger.info(f"teaport OpenClaw relay server on ws://{args.host}:{args.port}/talk") - serve(args.host, args.port) + for a in addrs: + shown = f"[{a}]" if ":" in a else a + logger.info(f"teaport OpenClaw relay server on ws://{shown}:{args.port}/talk") + serve(addrs, args.port) if __name__ == "__main__": diff --git a/brain/teaport_brain/pairing.py b/brain/teaport_brain/pairing.py index 003c0b769..05486f77a 100644 --- a/brain/teaport_brain/pairing.py +++ b/brain/teaport_brain/pairing.py @@ -995,9 +995,10 @@ def _expired() -> HTMLResponse: def via_front_door(request: Request) -> bool: - """Whether the request came through Caddy over HTTPS. The brain listens on every - interface (http://:7861 serves /talk), so without this anyone on the - LAN could reach /p/ in cleartext, or burn a live offer with wrong guesses. uvicorn + """Whether the request came through Caddy over HTTPS. The brain's own port is plain + HTTP; it listens on the box alone (BRAIN_LISTEN, #477), but a hand-set --host or the + NemoClaw bridge widens it, and then without this anyone there could reach /p/ in + cleartext, or burn a live offer with wrong guesses. uvicorn trusts X-Forwarded-* only from 127.0.0.1 (its forwarded_allow_ips default) and then sets the scheme from X-Forwarded-Proto, so "https" here means Caddy said so. Run without that middleware, the same rule is checked by hand: a loopback peer that diff --git a/brain/teaport_brain/settings_access.py b/brain/teaport_brain/settings_access.py index bc2af6745..77c14db88 100644 --- a/brain/teaport_brain/settings_access.py +++ b/brain/teaport_brain/settings_access.py @@ -36,16 +36,18 @@ # # The session is a signed expiry, not a server-side record: an HMAC under a key derived # from GATEWAY_TOKEN (_key), so it outlives a brain restart (the page restarts the -# brain), ends when the token is changed, and is checked in constant time. With no -# token the page is open on the box itself anyway; a per-process random key then signs. +# brain), ends when the token is changed, and is checked in constant time. A brain with +# no token runs only when open on purpose (open_without_token, a developer's); a +# per-process random key then signs. # # What keeps a session to the owner's phone: # - the code: shown on the box's screen or said aloud in the room, five minutes, once; # - only what came through the Settings site over HTTPS is answered here at all # (on_settings_site: Caddy over loopback saying https, for the Settings port; every # /settings route, whoever mounted it, through SettingsGuard): the brain's own port, -# open to the LAN, gets a 404 -- the page shell too -- that is no guess, and a Secure cookie -# is never sent to it in cleartext; +# plain HTTP, gets a 404 -- the page shell too -- that is no guess, and a Secure cookie +# is never sent to it in cleartext. That port listens on the box alone (BRAIN_LISTEN, +# #477), but a page in a browser on the box (the agent's) can still reach it; # - another origin cannot use the cookie: SameSite=Strict keeps the browser from # sending it on any cross-site request; a request that changes anything must carry # the Settings origin itself as its Origin (same_origin), and one a browser marks as @@ -244,6 +246,22 @@ def b(s: str | None) -> bytes: return hmac.compare_digest(b(got), b(want)) +def open_without_token() -> bool: + """TEAPORT_ALLOW_NO_AUTH: a developer's or a test's brain with no GATEWAY_TOKEN, open + on purpose. Off, which every install is, no token means nothing opens (#477).""" + return bool(setting("TEAPORT_ALLOW_NO_AUTH")) + + +def gateway_token_ok(got: str | None, want: str | None) -> bool: + """The brain's own token checks (/talk, /talk/status, the config page on its port): + the configured token, presented. With none configured, nothing passes -- an empty + token matches an empty one (token_matches), so that is decided here, before the + compare -- unless the brain runs open on purpose (open_without_token).""" + if not want: + return open_without_token() + return token_matches(got, want) + + def bearer(request: Request) -> str | None: """The token of an `Authorization: Bearer` header, or None.""" auth = request.headers.get("authorization", "") diff --git a/brain/tests/test_brain_port.py b/brain/tests/test_brain_port.py new file mode 100644 index 000000000..c6470dc40 --- /dev/null +++ b/brain/tests/test_brain_port.py @@ -0,0 +1,273 @@ +# teaport — the brain's own port (#477). It listens on the box alone (BRAIN_LISTEN, +# 127.0.0.1; a NemoClaw install adds the docker bridge's address, bound before docker +# brings it up), and it refuses to start without GATEWAY_TOKEN unless it runs open on +# purpose (TEAPORT_ALLOW_NO_AUTH, a developer's). With no token, /talk admits no one. +# +# Synthetic addresses only: 192.0.2.1 is TEST-NET-1, held by no interface here, as the +# bridge's address is before docker creates it. +import os +import pathlib +import re +import socket +import subprocess +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from pinned_pipecat import require_pinned # noqa: E402 + +require_pinned() + +TOKEN = "t0k3n-" + "5" * 24 +os.environ["GATEWAY_TOKEN"] = TOKEN +os.environ.pop("TEAPORT_ALLOW_NO_AUTH", None) + +from fastapi.testclient import TestClient # noqa: E402 +from starlette.websockets import WebSocketDisconnect # noqa: E402 + +import appliance # noqa: E402 +from tempdirs import tempdir # noqa: E402 +from teaport_brain import gateway_server, settings, settings_access # noqa: E402 + +REPO = pathlib.Path(__file__).resolve().parents[2] + + +def _raises(exc, fn, *a): + try: + fn(*a) + except exc as e: + return e + raise AssertionError(f"{fn.__name__}{a} did not raise {exc.__name__}") + + +def test_the_brain_listens_on_the_box_alone_by_default(): + assert settings.setting("BRAIN_LISTEN", env={}) == "127.0.0.1" + assert gateway_server.listen_addresses("127.0.0.1") == ["127.0.0.1"] + # NemoClaw's: the bridge too; each address once, commas or spaces + assert gateway_server.listen_addresses(" 127.0.0.1, 172.18.0.1 127.0.0.1 ") == [ + "127.0.0.1", "172.18.0.1"] + assert gateway_server.listen_addresses("::1") == ["::1"] + # a name would be resolved once, at start: refused, as is nothing at all + # IPv6 sockets are bound IPv6-only: a scoped or IPv4-mapped address would never bind, + # and a bind failure restarts the unit; refused at the start instead (exit 78) + for bad in ("", " , ", "localhost", "teaport.local", "127.0.0.1,nope", + "fe80::1%lo", "::ffff:127.0.0.1"): + _raises(ValueError, gateway_server.listen_addresses, bad) + + +def test_the_bridge_address_is_bound_before_any_interface_holds_it(): + socks = gateway_server.listen_sockets(["127.0.0.1", "192.0.2.1"], 0) + try: + assert [s.getsockname()[0] for s in socks] == ["127.0.0.1", "192.0.2.1"] + finally: + for s in socks: + s.close() + # the same bind, plain, is refused: what the free bind is for + plain = socket.socket() + try: + e = _raises(OSError, plain.bind, ("192.0.2.1", 0)) + assert e.errno == 99, e # EADDRNOTAVAIL + finally: + plain.close() + + +def test_uvicorn_serves_on_the_sockets_bound_here(): + # serve() hands uvicorn sockets bound but not listening: asyncio listens on them. A + # small app, as the brain's own startup needs the engine. + import threading + import time + import urllib.request + + import uvicorn + from fastapi import FastAPI + + app = FastAPI() + + @app.get("/health") + def health(): + return {"ok": True} + + socks = gateway_server.listen_sockets(["127.0.0.1", "192.0.2.1"], 0) + port = socks[0].getsockname()[1] + server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error")) + t = threading.Thread(target=server.run, kwargs={"sockets": socks}, daemon=True) + t.start() + try: + for _ in range(100): + if server.started: + break + time.sleep(0.05) + assert server.started + with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=5) as r: + assert r.status == 200 + finally: + server.should_exit = True + t.join(10) + + +def test_a_failed_bind_leaves_no_socket_open(): + held = socket.socket() + held.bind(("127.0.0.1", 0)) + held.listen() + made = [] + real = socket.socket + + class Recorded(real): + def __init__(self, *a, **k): + super().__init__(*a, **k) + made.append(self) + + socket.socket = Recorded + try: + port = held.getsockname()[1] + _raises(OSError, gateway_server.listen_sockets, ["192.0.2.1", "127.0.0.1"], port) + finally: + socket.socket = real + held.close() + assert len(made) == 2 and all(s.fileno() == -1 for s in made), made + + +def test_no_token_refuses_to_start_unless_open_on_purpose(): + before = gateway_server.GATEWAY_TOKEN + gateway_server.GATEWAY_TOKEN = "" + try: + e = _raises(SystemExit, gateway_server.refuse_without_token) + assert e.code == gateway_server.EXIT_CONFIG == 78 + os.environ["TEAPORT_ALLOW_NO_AUTH"] = "1" + assert gateway_server.refuse_without_token() is None + os.environ["TEAPORT_ALLOW_NO_AUTH"] = "off" + _raises(SystemExit, gateway_server.refuse_without_token) + finally: + gateway_server.GATEWAY_TOKEN = before + os.environ.pop("TEAPORT_ALLOW_NO_AUTH", None) + assert gateway_server.refuse_without_token() is None # a token: nothing to refuse + + +def test_the_token_check_admits_no_one_when_none_is_set(): + ok = settings_access.gateway_token_ok + assert ok(TOKEN, TOKEN) and not ok("wrong", TOKEN) and not ok(None, TOKEN) + # an empty token matches an empty one (token_matches): never let that through + assert settings_access.token_matches("", "") + assert not ok("", "") and not ok(None, "") and not ok("anything", "") + os.environ["TEAPORT_ALLOW_NO_AUTH"] = "yes" + try: + assert ok(None, "") + assert not ok("wrong", TOKEN) # open on purpose only when no token is set + finally: + os.environ.pop("TEAPORT_ALLOW_NO_AUTH", None) + + +def test_talk_is_closed_to_anyone_without_the_token(): + client = TestClient(gateway_server.app) # no lifespan: only the socket's own check + + def closed(url): + try: + with client.websocket_connect(url) as ws: + ws.receive_text() + except WebSocketDisconnect as e: + return e.code + return None + + assert closed("/talk?token=wrong") == 1008 + assert closed("/talk") == 1008 + before = gateway_server.GATEWAY_TOKEN + gateway_server.GATEWAY_TOKEN = "" # a brain that started without one, somehow + try: + assert closed("/talk") == 1008 + assert closed("/talk?token=") == 1008 + finally: + gateway_server.GATEWAY_TOKEN = before + + +def test_the_unit_takes_a_refused_start_as_final(): + unit = (REPO / "systemd" / "teaport-brain.service.in").read_text() + assert f"\nRestartPreventExitStatus={gateway_server.EXIT_CONFIG}\n" in unit + start = next(line for line in unit.splitlines() if line.startswith("ExecStart=")) + assert "--host" not in start # BRAIN_LISTEN decides + + +def _install_fn(name: str) -> str: + text = (REPO / "install.sh").read_text() + m = re.search(rf"^{name}\(\) {{\n.*?^}}\n", text, re.S | re.M) + assert m, name + return m.group(0) + + +def test_install_writes_the_box_alone_and_for_nemoclaw_the_bridge(): + text = (REPO / "install.sh").read_text() + fn = "BRAIN_BRIDGE_ADDR=172.18.0.1\n" + _install_fn("brain_listen") + # (AGENT_MODE, a sandbox-recover unit on the box) -> the brain.env line + for mode, unit, want in ( + ("", False, "BRAIN_LISTEN=127.0.0.1"), + ("openclaw", False, "BRAIN_LISTEN=127.0.0.1"), + ("nemoclaw", True, "BRAIN_LISTEN=127.0.0.1,172.18.0.1"), + # moved to host OpenClaw, the old recover unit still there: it follows + ("openclaw", True, "BRAIN_LISTEN=127.0.0.1"), + # a repair run that can't see the sandbox (root's home): seeded, so it stays + ("", True, "?BRAIN_LISTEN=127.0.0.1,172.18.0.1")): + stub = f"systemctl() {{ {'true' if unit else 'false'}; }}\n" + out = subprocess.run(["bash", "-c", f"{stub}{fn}AGENT_MODE={mode}; brain_listen"], + capture_output=True, text=True, check=True).stdout.strip() + assert out == want, (mode, unit, out) + assert gateway_server.listen_addresses(out.split("=", 1)[1]) # the brain takes it + assert '"BRAIN_PORT=$BRAIN_PORT" "$(brain_listen)"' in text + assert 'brain_ws="ws://$BRAIN_BRIDGE_ADDR:${BRAIN_PORT}/talk"' in text + assert "\nBRAIN_BRIDGE_ADDR=172.18.0.1\n" in text + # --only brain: a NemoClaw box keeps its sandbox's way in, seeded before the new brain + only = _install_fn("main_brain_only") + calls = [only.index(f"\n {c}") for c in ("brain_listen_seed\n", "brain_deb_keep\n", + "brain_swap \"$BRAIN_DEB_CACHED\"")] + assert calls == sorted(calls), calls + seed = _install_fn("brain_listen_seed") + assert "teaport-sandbox-recover.service" in seed + assert '"?BRAIN_LISTEN=127.0.0.1,$BRAIN_BRIDGE_ADDR"' in seed + + +def test_the_discord_bridge_sends_the_token(): + # /talk admits no one without the token (#477): the bridge gets it from install.sh + bridge = _install_fn("phase_bridge") + assert bridge.index("resolve_gateway_token") < bridge.index('"BRIDGE_GATEWAY_TOKEN=$GATEWAY_TOKEN"') + js = (REPO / "bridge" / "discord" / "index.js").read_text() + assert 'const GATEWAY_TOKEN = setting("BRIDGE_GATEWAY_TOKEN") || "";' in js + url = js[js.index("function brainUrl()"):] + url = url[:url.index("\n}\n")] + assert 'q.push("token=" + encodeURIComponent(GATEWAY_TOKEN))' in url + # and never into a log line: those show BRAIN_URL, not brainUrl() + assert not [ln for ln in js.splitlines() if "log(" in ln and "brainUrl()" in ln] + + +def _doctor_listen(ss_lines: list[str], *, nemoclaw: bool, listen: str) -> list[str]: + """cmd_doctor's brain_listen_check, with ss and systemctl stood in for.""" + text = (REPO / "cli" / "teaport").read_text() + prefix = text[:text.index('cmd="${1:-}"; shift || true')] + etc = pathlib.Path(tempdir("doctor-listen-")) + (etc / "brain.env").write_text(f"BRAIN_LISTEN={listen}\n") + (etc / "ss.out").write_text("".join(line + "\n" for line in ss_lines)) + script = (prefix + f"ETC={etc}; BRAIN_PORT=7861\n" + 'warnc() { echo "WARN $*"; }\n' + f'ss() {{ cat "{etc}/ss.out"; }}\n' + f"systemctl() {{ return {0 if nemoclaw else 1}; }}\n" + "brain_listen_check\n") + p = subprocess.run(["bash", "-c", script], capture_output=True, text=True) + assert p.returncode == 0, p.stderr + return [line for line in p.stdout.splitlines() if line] + + +def test_doctor_says_when_the_port_answers_beyond_the_box(): + box = "LISTEN 0 2048 127.0.0.1:7861 0.0.0.0:*" + bridge = "LISTEN 0 2048 172.18.0.1:7861 0.0.0.0:*" + assert _doctor_listen([box], nemoclaw=False, listen="127.0.0.1") == [] + assert _doctor_listen([box, bridge], nemoclaw=True, listen="127.0.0.1,172.18.0.1") == [] + for wide in ("LISTEN 0 2048 0.0.0.0:7861 0.0.0.0:*", "LISTEN 0 2048 [::]:7861 [::]:*", + "LISTEN 0 2048 192.168.1.50:7861 0.0.0.0:*"): + out = _doctor_listen([wide], nemoclaw=False, listen="127.0.0.1") + assert len(out) == 1 and "beyond the box" in out[0], out + # a NemoClaw box whose brain left the bridge out: its sandbox can't reach it + out = _doctor_listen([box], nemoclaw=True, listen="127.0.0.1") + assert len(out) == 1 and "NemoClaw sandbox cannot reach" in out[0], out + # the two copies of the bridge's address agree + cli = (REPO / "cli" / "teaport").read_text() + assert "\nBRAIN_BRIDGE_ADDR=172.18.0.1\n" in cli + + +if __name__ == "__main__": + appliance.run_tests([fn for name, fn in list(globals().items()) if name.startswith("test_")]) diff --git a/brain/tests/test_call_experience.py b/brain/tests/test_call_experience.py index 1941c4ce9..687c75b97 100644 --- a/brain/tests/test_call_experience.py +++ b/brain/tests/test_call_experience.py @@ -97,6 +97,7 @@ async def __aenter__(self): async def start_brain(self): env = {k: v for k, v in os.environ.items() if k not in ("GATEWAY_TOKEN", "TEAPORT_AUDIO_DUMP")} + env["TEAPORT_ALLOW_NO_AUTH"] = "1" # no token: nothing here uses /talk (#477) env.update(self.engine.env_for()) with socket.socket() as s: s.bind(("127.0.0.1", 0)) diff --git a/brain/tests/test_config_ui.py b/brain/tests/test_config_ui.py index 80f7cf150..26a8e96c9 100644 --- a/brain/tests/test_config_ui.py +++ b/brain/tests/test_config_ui.py @@ -372,12 +372,14 @@ def test_doctor_reads_a_blank_secret_as_not_set(): # `teaport doctor`'s two secret checks (cli/teaport cmd_doctor) by the same rule as the # brain: a blank or whitespace-only llm_key and a GATEWAY_TOKEN=" " are not set. The # CLI's functions as they are (everything above its dispatch, as test_tts_pacing.py - # takes them), then those two lines of cmd_doctor. + # takes them), then the key's line of cmd_doctor and the token's check. No token is a + # failure (the brain will not start, #477) unless it runs open on purpose. import pathlib import subprocess text = (pathlib.Path(__file__).resolve().parents[2] / "cli" / "teaport").read_text() - lines = [l for l in text.splitlines() if 'ok "GATEWAY_TOKEN set"' in l or 'ok "LLM API key present"' in l] - assert len(lines) == 2, lines + lines = ["gateway_token_check"] + [ + l for l in text.splitlines() if 'ok "LLM API key present"' in l] + assert len(lines) == 2 and "\n gateway_token_check\n" in text, lines prefix = text[:text.index('cmd="${1:-}"; shift || true')] def doctor(token_line, key_file, key_env=""): @@ -388,7 +390,8 @@ def doctor(token_line, key_file, key_env=""): with open(os.path.join(secrets, "llm_key"), "w") as f: f.write(key_file) script = (prefix + f"ETC={etc}; SECRETS={secrets}\n" - 'ok() { echo "OK $*"; }; warnc() { echo "WARN $*"; }\n' + "\n".join(lines) + "\n") + 'ok() { echo "OK $*"; }; warnc() { echo "WARN $*"; }; failc() { echo "FAIL $*"; }\n' + + "\n".join(lines) + "\n") env = {k: v for k, v in os.environ.items() if k != "LLM_API_KEY"} if key_env: env["LLM_API_KEY"] = key_env @@ -396,10 +399,13 @@ def doctor(token_line, key_file, key_env=""): return [l.split()[0] for l in p.stdout.splitlines()] assert doctor("GATEWAY_TOKEN=t0k3n", "sk-x\n") == ["OK", "OK"] - assert doctor('GATEWAY_TOKEN=" "', " \n\t\n") == ["WARN", "WARN"] - assert doctor("GATEWAY_TOKEN=", "") == ["WARN", "WARN"] - assert doctor("GATEWAY_TOKEN=''", None, key_env=" ") == ["WARN", "WARN"] + assert doctor('GATEWAY_TOKEN=" "', " \n\t\n") == ["FAIL", "WARN"] + assert doctor("GATEWAY_TOKEN=", "") == ["FAIL", "WARN"] + assert doctor("GATEWAY_TOKEN=''", None, key_env=" ") == ["FAIL", "WARN"] assert doctor('GATEWAY_TOKEN="t0k3n"', None, key_env="sk-x") == ["OK", "OK"] + # open on purpose: said, not failed; an off word is still a failure + assert doctor("GATEWAY_TOKEN=\nTEAPORT_ALLOW_NO_AUTH=Yes", "sk-x") == ["WARN", "OK"] + assert doctor("GATEWAY_TOKEN=\nTEAPORT_ALLOW_NO_AUTH=0", "sk-x") == ["FAIL", "OK"] def test_get_shows_what_other_readers_get_as_written(): diff --git a/brain/tests/test_install_brain_only.py b/brain/tests/test_install_brain_only.py index dda91bf09..ab2e54017 100644 --- a/brain/tests/test_install_brain_only.py +++ b/brain/tests/test_install_brain_only.py @@ -187,7 +187,7 @@ def test_brain_verify_polls_the_port_from_a_root_only_brain_env(): ONLY_BRAIN_STUBS = r''' BRAIN_DEB_CACHED=/cache/x.deb BRAIN_DEB_NEW=2.0 systemctl() { [ "$1" = cat ] && [ "${NO_UNIT:-0}" = 0 ]; } # the brain unit is installed -for f in check_brain_source brain_deb_fetch brain_deb_keep wait_for_idle sip_brain_detach brain_swap sip_brain_retire \ +for f in check_brain_source brain_deb_fetch brain_deb_keep wait_for_idle sip_brain_detach brain_listen_seed brain_swap sip_brain_retire \ brain_retire_old_tools brain_retire_old_venvs install_busy_lamp install_dns_resilience install_arp_multihome \ brain_deb_prune; do eval "$f() { echo STEP $f; }"; done ''' @@ -241,12 +241,29 @@ def test_only_brain_installs_the_package_first_and_the_rest_only_after_the_verif order = [ln.split()[1] for ln in out.splitlines() if ln.startswith("STEP ")] # The wait for nobody talking (teaport update's runs) comes after the download and before # the package is kept: a wait that gives up leaves the cache --rollback brain reads as it was. - assert order == ["check_brain_source", "brain_deb_fetch", "wait_for_idle", "sip_brain_detach", "brain_deb_keep", + assert order == ["check_brain_source", "brain_deb_fetch", "wait_for_idle", "sip_brain_detach", + "brain_listen_seed", "brain_deb_keep", "brain_swap", "sip_brain_retire", "brain_retire_old_tools", "brain_retire_old_venvs", "install_busy_lamp", "install_dns_resilience", "install_arp_multihome", "brain_deb_prune"], order +def test_only_brain_keeps_a_nemoclaw_sandbox_on_the_bridge(): + # --only brain writes no brain.env, and the new brain listens on BRAIN_LISTEN (#477): + # a NemoClaw box (its sandbox-recover unit) gets the bridge too, as a seed; any other + # box nothing. + def seed(nemoclaw): + script = ('BRAIN_BRIDGE_ADDR=172.18.0.1; ETC=/etc/teaport\n' + f'systemctl() {{ [ "$1 $2" = "cat teaport-sandbox-recover.service" ] && {str(nemoclaw).lower()}; }}\n' + 'write_env() { echo "WRITE $*"; }\n' + 'brain_listen_seed') + return _run(tempdir("teaport-only-"), script, ["brain_listen_seed"]) + rc, out = seed(True) + assert rc == 0 and "WRITE /etc/teaport/brain.env ?BRAIN_LISTEN=127.0.0.1,172.18.0.1" in out, out + rc, out = seed(False) + assert rc == 0 and "WRITE" not in out, out + + # --- the resolver's serve-stale drop-in ------------------------------------------------ def _dns(tmp, resolved_active=True, stub=True, systemd=255): diff --git a/brain/tests/test_local_audio.py b/brain/tests/test_local_audio.py index 350ee1469..9f11f9a2a 100644 --- a/brain/tests/test_local_audio.py +++ b/brain/tests/test_local_audio.py @@ -585,8 +585,8 @@ def test_talk_status_carries_the_brains_ask_for_the_room(monkeypatch): from types import SimpleNamespace gs = _gateway() from teaport_brain import first_boot - monkeypatch.delenv("GATEWAY_TOKEN", raising=False) - req = SimpleNamespace(query_params={}, headers={}) + monkeypatch.setenv("GATEWAY_TOKEN", "secret") + req = SimpleNamespace(query_params={}, headers={"authorization": "Bearer secret"}) from teaport_brain import session_arbiter as arb monkeypatch.setattr(arb, "ARBITER", arb.SessionArbiter()) monkeypatch.setattr(first_boot, "_wanted", None) @@ -1058,8 +1058,14 @@ def req(token=None, bearer=None): return SimpleNamespace(query_params={"token": token} if token else {}, headers={"authorization": f"Bearer {bearer}"} if bearer else {}) monkeypatch.delenv("GATEWAY_TOKEN", raising=False) + monkeypatch.delenv("TEAPORT_ALLOW_NO_AUTH", raising=False) a = arb.SessionArbiter() monkeypatch.setattr(arb, "ARBITER", a) + # no token set: closed to everyone (#477), unless the brain runs open on purpose + with pytest.raises(HTTPException) as e: + asyncio.run(gs.talk_status(req())) + assert e.value.status_code == 401 + monkeypatch.setenv("TEAPORT_ALLOW_NO_AUTH", "1") assert asyncio.run(gs.talk_status(req())) == {"active": False, "call": False, "live": False, "holder": None, "asleep": False, "held": None, "wanted": None} @@ -1067,6 +1073,7 @@ def req(token=None, bearer=None): live = {"active": True, "call": False, "live": True, "holder": "talk", "asleep": False, "held": None, "wanted": None} assert asyncio.run(gs.talk_status(req())) == live + monkeypatch.delenv("TEAPORT_ALLOW_NO_AUTH") monkeypatch.setenv("GATEWAY_TOKEN", "secret") for bad in (req(), req(token="nope"), req(bearer="nope")): with pytest.raises(HTTPException) as e: diff --git a/brain/tests/test_settings_access.py b/brain/tests/test_settings_access.py index 103562888..9c40695d8 100644 --- a/brain/tests/test_settings_access.py +++ b/brain/tests/test_settings_access.py @@ -636,8 +636,9 @@ def test_a_settings_code_never_reaches_the_access_log(): def test_no_token_does_not_open_the_front_door(): - """An unset GATEWAY_TOKEN leaves the brain's own port open to the box itself, never - the front door's mount: there only a Settings session counts (#279 review).""" + """An unset GATEWAY_TOKEN never opens the front door's mount: there only a Settings + session counts (#279 review). The brain's own port opens nothing either (#477), unless + the brain runs open on purpose, and then to the box itself alone.""" async def run(): _setup() os.environ["GATEWAY_TOKEN"] = "" @@ -648,7 +649,12 @@ async def run(): assert (await c.post("/settings/api/restart", json={"unit": "teaport-brain"})).status_code == 401 assert (await c.post("/settings/api/wifi/connect", json={"ssid": "x"})).status_code == 401 async with _client(proto=None, origin=None, port=7861, host="127.0.0.1") as c: - assert (await c.get("/api/config")).status_code == 200 # the box itself, open + assert (await c.get("/api/config")).status_code == 401 # not even the box (#477) + os.environ["TEAPORT_ALLOW_NO_AUTH"] = "1" + try: + assert (await c.get("/api/config")).status_code == 200 # open on purpose + finally: + del os.environ["TEAPORT_ALLOW_NO_AUTH"] screen = Screen() await Voice(screen)._heard("open my settings") async with _client() as c: @@ -695,9 +701,9 @@ async def run(): def test_the_operator_page_answers_only_the_box_itself(): """http://:7861/config is plain HTTP: the token it asks for would cross the LAN - in cleartext, and an unset one would open it to the LAN. Only a loopback peer no - proxy forwarded gets it -- with no token set too; /talk/status, which shares the - token check, stays on the LAN for the room bridge.""" + in cleartext. Only a loopback peer no proxy forwarded gets it, and with no token set, + not even that (#477). /talk/status shares the token check but not the loopback rule: + it answers wherever the brain listens (the box alone, unless BRAIN_LISTEN widens it).""" async def run(): _setup() app = gateway_server.app @@ -727,14 +733,20 @@ def peer(host, **headers): assert (await fwd.get("/api/config", headers=auth)).status_code == 403 async with peer("127.0.0.1", **{"X-Forwarded-Proto": "http"}) as fwd: assert (await fwd.get("/api/config", headers=auth)).status_code == 403 - # No token set: open on the box, still nothing for the LAN. + # No token set: nothing opens, the box itself included -- a page in the agent's + # browser is on the box too (#477). Open on purpose: the box alone, never the LAN. os.environ["GATEWAY_TOKEN"] = "" try: async with peer("127.0.0.1") as box, peer("192.168.1.50") as lan: + assert (await box.get("/api/config")).status_code == 401 + assert (await box.get("/talk/status")).status_code == 401 + assert (await lan.get("/api/config")).status_code == 403 + os.environ["TEAPORT_ALLOW_NO_AUTH"] = "1" assert (await box.get("/api/config")).status_code == 200 assert (await lan.get("/api/config")).status_code == 403 finally: os.environ["GATEWAY_TOKEN"] = TOKEN + os.environ.pop("TEAPORT_ALLOW_NO_AUTH", None) asyncio.run(run()) diff --git a/brain/tests/test_sip_fake_gateway.py b/brain/tests/test_sip_fake_gateway.py index 02a22fc7d..e564e140b 100644 --- a/brain/tests/test_sip_fake_gateway.py +++ b/brain/tests/test_sip_fake_gateway.py @@ -92,6 +92,7 @@ async def __aexit__(self, exc_type, *exc): def start_brain(self) -> subprocess.Popen: env = {k: v for k, v in os.environ.items() if k not in ("GATEWAY_TOKEN", "TEAPORT_AUDIO_DUMP")} + env["TEAPORT_ALLOW_NO_AUTH"] = "1" # no token: nothing here uses /talk (#477) env.update(self.engine.env_for()) with socket.socket() as s: # a free port for /talk, which nothing here uses s.bind(("127.0.0.1", 0)) diff --git a/brain/tests/test_tts_pacing.py b/brain/tests/test_tts_pacing.py index cf4abe5e0..e4a65927a 100644 --- a/brain/tests/test_tts_pacing.py +++ b/brain/tests/test_tts_pacing.py @@ -621,7 +621,7 @@ def test_doctor_runs_every_check_on_any_box(): f.write("LLM_BASE_URL=http://llm:8080/v1\nGATEWAY_TOKEN=\n") rc, checks = _doctor_run(health, etc=etc) assert {"OK KOKORO_RESERVE_FPT=6", "OK LLM_BASE_URL set", - "WARN GATEWAY_TOKEN unset — /talk is unauthenticated", + f"FAIL GATEWAY_TOKEN unset in {etc}/brain.env — the brain will not start without it (#477): run install.sh again, which writes it for the brain and every client of it", "OK TTS pacing: greedy"} <= set(checks), checks if os.geteuid() != 0: # root reads a mode-000 file import grp diff --git a/brain/tests/test_wake_gate.py b/brain/tests/test_wake_gate.py index 13b1e9d67..8b96da7cc 100644 --- a/brain/tests/test_wake_gate.py +++ b/brain/tests/test_wake_gate.py @@ -301,7 +301,17 @@ async def test_a_phone_call_closes_the_asleep_mic_session_and_holds_the_room_off assert await call.start("c1") is None assert asleep.task.cancelled and asleep_ws.closed == [(gs.YIELD_CLOSE_CODE, gs.YIELD_CLOSE_REASON)] assert gs.call_live() - status = await gs.talk_status(type("R", (), {"query_params": {}, "headers": {}})()) + # the room bridge's own poll, with the brain's token (#477: none opens nothing) + before = os.environ.get("GATEWAY_TOKEN") + os.environ["GATEWAY_TOKEN"] = "t0k3n" + try: + status = await gs.talk_status(type("R", (), {"query_params": {}, + "headers": {"authorization": "Bearer t0k3n"}})()) + finally: + if before is None: + del os.environ["GATEWAY_TOKEN"] + else: + os.environ["GATEWAY_TOKEN"] = before assert status["call"] is True and status["holder"] == "call" call.end() call.end() # twice: harmless diff --git a/bridge/discord/index.js b/bridge/discord/index.js index 4d062dae8..565fc32a2 100644 --- a/bridge/discord/index.js +++ b/bridge/discord/index.js @@ -56,6 +56,9 @@ if (!GUILD_ID || !FOLLOW_USER_ID) { const BRAIN_URL = setting("BRAIN_URL", "ws_url") || "ws://127.0.0.1:7861/talk"; const FORCE_JOIN_CHANNEL_ID = setting("BRIDGE_JOIN_CHANNEL_ID", "snowflake") || ""; const VOICE = setting("TEAPORT_VOICE") || ""; +// The brain's GATEWAY_TOKEN (install.sh copies it here): /talk admits no one without it. +// Only ever in the URL brainUrl() builds, never in a log line (those show BRAIN_URL). +const GATEWAY_TOKEN = setting("BRIDGE_GATEWAY_TOKEN") || ""; const TOKEN_FILE = setting("DISCORD_BOT_TOKEN_FILE") || `${process.env.HOME}/.config/teaport/discord_bot_token`; @@ -85,6 +88,7 @@ const CLIENT_ID = "discord"; function brainUrl() { const q = ["client=" + CLIENT_ID]; if (VOICE) q.push("voice=" + encodeURIComponent(VOICE)); + if (GATEWAY_TOKEN) q.push("token=" + encodeURIComponent(GATEWAY_TOKEN)); return BRAIN_URL + (BRAIN_URL.includes("?") ? "&" : "?") + q.join("&"); } diff --git a/cli/teaport b/cli/teaport index a8267accf..96b431c9d 100755 --- a/cli/teaport +++ b/cli/teaport @@ -211,6 +211,38 @@ installed() { systemctl cat "$1.service" >/dev/null 2>&1; } # Not `grep -q`: under pipefail, grep leaving at its first match can SIGPIPE ss and # fail the pipeline for a port that IS listening (install.sh's contains() says more). listening() { ss -ltn 2>/dev/null | grep -F ":$1 " >/dev/null; } +# a brain flag's "on" words (settings.FLAG_TRUE) +truthy() { case "${1,,}" in 1|true|yes|y|on) return 0 ;; *) return 1 ;; esac; } +# doctor: the brain will not start without GATEWAY_TOKEN (#477), unless it runs open on +# purpose (TEAPORT_ALLOW_NO_AUTH, a developer's). Blank or whitespace is not set, as the +# brain reads it. ok/warnc/failc are cmd_doctor's. +gateway_token_check() { + if [ -n "$(envval "$ETC/brain.env" GATEWAY_TOKEN | tr -d "\"' \t")" ]; then ok "GATEWAY_TOKEN set" + elif truthy "$(envval "$ETC/brain.env" TEAPORT_ALLOW_NO_AUTH | tr -d "\"' \t")"; then + warnc "GATEWAY_TOKEN unset and TEAPORT_ALLOW_NO_AUTH on — the brain runs open on purpose (a developer's, never a box)" + else failc "GATEWAY_TOKEN unset in $ETC/brain.env — the brain will not start without it (#477): run install.sh again, which writes it for the brain and every client of it"; fi +} +# The brain's port answers only the box (#477): every client of it is there. The one other +# address it may hold is the docker bridge's, for a NemoClaw sandbox (BRAIN_LISTEN). +BRAIN_BRIDGE_ADDR=172.18.0.1 +brain_listen_check() { + local addr wide=() line + while IFS= read -r line; do + addr="$(awk '{print $4}' <<<"$line")"; addr="${addr%:*}" + case "$addr" in + 127.*|'[::1]'|"$BRAIN_BRIDGE_ADDR") ;; + *) wide+=("$addr") ;; + esac + done < <(ss -Hltn "sport = :$BRAIN_PORT" 2>/dev/null || true) + if [ "${#wide[@]}" -gt 0 ]; then + warnc "brain :$BRAIN_PORT answers beyond the box (${wide[*]}): a brain from before #477, or BRAIN_LISTEN / --host set wide — run install.sh again" + fi + # a NemoClaw box: its sandbox reaches the brain only on the bridge + if [ -r "$ETC/brain.env" ] && systemctl cat teaport-sandbox-recover.service >/dev/null 2>&1 \ + && [[ ",$(envval "$ETC/brain.env" BRAIN_LISTEN | tr -d "\"' \t")," != *",$BRAIN_BRIDGE_ADDR,"* ]]; then + warnc "BRAIN_LISTEN lacks $BRAIN_BRIDGE_ADDR: the NemoClaw sandbox cannot reach the brain — run install.sh again" + fi +} # envval — the first KEY= value; "" when unset or the file is unreadable. # One sed, no pipe: `sed | head` failed under pipefail on a missing file, and doctor's # `fpt="$(envval …)"` then ended doctor (set -e) on a box without engine.env. @@ -383,7 +415,7 @@ cmd_doctor() { fi if env_file_check "$ETC/brain.env"; then [ -n "$(envval "$ETC/brain.env" LLM_BASE_URL)" ] && ok "LLM_BASE_URL set" || failc "LLM_BASE_URL unset in $ETC/brain.env" - [ -n "$(envval "$ETC/brain.env" GATEWAY_TOKEN | tr -d "\"' \t")" ] && ok "GATEWAY_TOKEN set" || warnc "GATEWAY_TOKEN unset — /talk is unauthenticated" + gateway_token_check # The owner's Settings site (#279) comes with a full install, not with --only brain. if [ -n "$(envval "$ETC/brain.env" TEAPORT_FRONTDOOR_HOST)" ] && [ -z "$(envval "$ETC/brain.env" TEAPORT_SETTINGS_PORT)" ]; then warnc "no Settings site (TEAPORT_SETTINGS_PORT unset): \"open my settings\" cannot work until install.sh runs without --only" @@ -394,6 +426,10 @@ cmd_doctor() { for u in teaport-engine teaport-brain; do st="$(active "$u")" if [ "$st" = active ]; then ok "$u active" + elif [ "$u" = teaport-brain ] && [ "$(systemctl show -p ExecMainStatus --value teaport-brain.service 2>/dev/null)" = 78 ]; then + # 78: the brain refused its configuration (no GATEWAY_TOKEN, a bad BRAIN_LISTEN): a + # restart would only refuse again (#477) + failc "$u refused to start: its configuration (GATEWAY_TOKEN or BRAIN_LISTEN, above; journalctl -u $u -n 5)" else failc "$u is $st" if [ "$fix" = 1 ]; then warnc " --fix: systemctl restart $u"; SUDO systemctl restart "$u.service" || true; fi @@ -401,6 +437,7 @@ cmd_doctor() { done listening "$ENGINE_PORT" && ok "engine :$ENGINE_PORT listening" || failc "engine :$ENGINE_PORT not listening (allow ~1min after start)" listening "$BRAIN_PORT" && ok "brain :$BRAIN_PORT listening" || failc "brain :$BRAIN_PORT not listening" + brain_listen_check brain_pacing_check answers_check credit_check diff --git a/docs/src/content/docs/getting-started/installation.md b/docs/src/content/docs/getting-started/installation.md index d881349a6..25c3238db 100644 --- a/docs/src/content/docs/getting-started/installation.md +++ b/docs/src/content/docs/getting-started/installation.md @@ -187,7 +187,7 @@ The installer does these tasks: its Wi-Fi address, the same name as its Wi-Fi setup network. - It starts the services and checks the installation. - + ## Optional components @@ -204,7 +204,7 @@ teaport has three optional components. The installer sets up none of them by def and speaks without a phone. Turn it on with `TEAPORT_ENABLE_LOCAL_AUDIO=1`. See [Use a microphone on the device](/guides/local-audio/). - + ## Check the installation @@ -216,7 +216,7 @@ teaport has three optional components. The installer sets up none of them by def All three services show `active`, with the engine and brain ports and the memory use. - + 2. Run the health check: @@ -228,7 +228,7 @@ teaport has three optional components. The installer sets up none of them by def configuration, the services, and the ports. Every check prints `ok`, or a warning that says what to fix. - + 3. Optional: to confirm that speech recognition uses the fast path, read the engine's first messages: @@ -250,7 +250,7 @@ The installer printed a web address at the end, similar to the following: browser: open https://teaport.local/#token=a-long-token from a LAN device (accept the one-time cert). ``` - + Open that address on the phone or laptop. Accept the certificate warning once: the device signs its own certificate, and the browser needs HTTPS before it allows the microphone. @@ -267,7 +267,7 @@ device, run the sandbox command that the installer printed instead. The token is `~/.openclaw/openclaw.json` under `gateway.auth.token`. ::: - + Start a Talk session in the page and speak. The device answers through the phone or the laptop's microphone and speaker. diff --git a/docs/src/content/docs/guides/configuration.md b/docs/src/content/docs/guides/configuration.md index 23ae4da56..681891955 100644 --- a/docs/src/content/docs/guides/configuration.md +++ b/docs/src/content/docs/guides/configuration.md @@ -5,27 +5,27 @@ description: Change teaport settings in the configuration page or in the configu Each teaport service reads its settings once, at startup. To change a setting, edit it, then restart the service that reads it. Nothing hot-reloads. - + You can make the edit in two places: the brain's configuration page, or the configuration files over SSH. The page edits the same files you edit by hand; the two paths differ only in convenience. For every setting, its default, and the file that holds it, see the [Settings reference](/reference/settings/). ## Before you begin - The IP address of the device on your network. The steps call it `DEVICE_IP`. -- The gateway token `GATEWAY_TOKEN`, if you set one: the shared secret that clients use at `/talk`. You enter it on the page once, and the browser remembers it after that. The installer writes the same token into the plugin configuration. +- The gateway token `GATEWAY_TOKEN`: the shared secret that clients use at `/talk`. The installer writes it to `/etc/teaport/brain.env`. You enter it on the page once, and the browser remembers it after that. The installer writes the same token into the plugin configuration. - An SSH connection to the device, for the procedure that edits files. On a device that ships ready to set up, sign in as `teaport`, the login you created during setup; see [Create your login in the settings](#create-your-login-in-the-settings) if you have none yet. - + ## Change a setting in the configuration page The brain serves the page at `https://DEVICE_NAME.local:8443/settings/config`, on the device's settings site (see [Open the settings from your phone](/guides/configuration/#open-the-settings-from-your-phone)). On the device itself it also serves the page at `http://127.0.0.1:7861/config` (port 7861 is the default; if you changed `BRAIN_PORT`, the page moves with it). That plain-HTTP address answers only the device itself, so the token never crosses the network unencrypted; from another computer without the settings site, tunnel to it over SSH, for example `ssh -L 7861:127.0.0.1:7861 DEVICE_IP`, and open `http://127.0.0.1:7861/config`. The page edits the env files and the secret files where the settings live, and shows each value as the running services read it. It never displays a secret: for a secret it shows whether one is set, and it accepts a new value. - + To change a setting there: -1. Open `https://DEVICE_NAME.local:8443/settings/config#token` and enter `GATEWAY_TOKEN`. The browser remembers it. Over the SSH tunnel, open `http://127.0.0.1:7861/config`, which asks for the same token. If you did not set a token, the tunnelled address opens without one, and the brain warns about that at startup; the settings site never opens without a token or a phone session. +1. Open `https://DEVICE_NAME.local:8443/settings/config#token` and enter `GATEWAY_TOKEN`. The browser remembers it. Over the SSH tunnel, open `http://127.0.0.1:7861/config`, which asks for the same token. The installer always writes a token, and the brain does not start without one; the settings site never opens without a token or a phone session. 2. Find the setting: type its name or words from its description in the search field, or open the group that covers it. At first the page shows the settings most devices need. Turn on **Show tuning & diagnostics** to list the rest, along with the groups for parts the device has not set up. The page shows each value as the services read it, which is not always the way the file spells it. @@ -50,25 +50,25 @@ When a model is set up, you can also ask in your own words, for example "I need 2. Tap **Continue**. You can use the code one time, within five minutes. Asking again replaces it. 3. The phone shows the **AI account** step at the top, under a **Create your login** card while the device has no login yet (see [Create your login in the settings](#create-your-login-in-the-settings)): tap **Connect your OpenRouter account**, or paste a key from your OpenRouter account and tap **Test and save**. Tap **Show advanced** for every other setting on the page. - + The settings open at `https://DEVICE_NAME.local:8443/settings/config`: a port of their own, set by `TEAPORT_SETTINGS_PORT`, so that no page the gateway serves on the usual HTTPS port shares an origin with them. The plain address that the device reads out redirects there. Phones on your network must be able to reach TCP port 8443 on the device. The full installer sets this site up; an `install.sh --only brain` update does not touch Caddy, so on a device last fully installed before it, the device says that its settings can't be reached from a phone until you run the installer without `--only`. The phone stays signed in for an hour, in a cookie the browser sends only to that address over HTTPS. Without a session or the token nothing on that port opens, and an unset `GATEWAY_TOKEN` opens nothing there. - + Until the phone trusts the device's certificate, the browser warns that the connection is not private. The pages link to the steps that install the device's certificate on each kind of phone and computer. - + If the device is on no network at all and spoken Wi-Fi setup is on, the device asks you to get it online first: a phone cannot reach it yet. A home network without internet is enough. In setup mode the setup page takes the key too, as [Connect the device to Wi-Fi](/guides/wifi-setup/#connect-your-ai-account) shows. - + ## Create your login in the settings On a device that ships ready to set up, such as a Teaspoon AI device, you create the device's login yourself: an administrator account named `teaport` that signs in with SSH and runs commands with `sudo`. The Wi-Fi setup page offers this step (see [Create your login](/guides/wifi-setup/#create-your-login)). A device that went online another way, over Ethernet or with Wi-Fi setup by voice, never shows that page, so the settings offer the same step instead: a **Create your login** card at the top, until a login exists. A device that you installed yourself never shows the card. - + To create your login in the settings, follow these steps: @@ -102,7 +102,7 @@ The button shows only on the settings site, at the port `TEAPORT_SETTINGS_PORT` Setup mode can't use the sign-in, because neither the phone nor the device has internet there. When Wi-Fi setup ends without a key on the setup page, and the device has no key of your own, the device offers it: it says so out loud and shows the settings QR code on its screen, the same code that "open my settings" shows. A device without a screen that draws it reads out the address and the code instead. - + ## Change a setting in a configuration file @@ -140,19 +140,19 @@ To change a setting this way: The secret files live in `~/.config/teaport/`: `llm_key`, `openclaw_token`, `discord_bot_token`, `persona.md`, and `teaport-sip.conf`. The installer creates the directory with mode 700 and writes each secret with mode 600, and it keeps the secrets out of the units and images. - + You edit `persona.md` whenever you like. A repair writes the starter persona only when the file is missing, so your changes to it survive. - + For every secret, an environment variable that is set wins over the file: every reader checks the environment first. A secret that is also set in an env file is a trap, because a new value in the file changes nothing while the variable is set. If you edit the file, remove the matching line from the env file too, or empty its value. The configuration page does this for you: saving a secret writes the file and drops the env-file copy of the same name. The units that read the secret at startup then show as pending, because their environment holds the old value until the restart. - + A new value in a secret file takes hold on its own schedule. The brain reads the large language model (LLM) key once per session, so the next conversation uses it and no restart is needed; the Discord bridge reads its token once at startup, so a new token there needs the usual restart. - + ## Apply the change @@ -170,7 +170,7 @@ Restart the service that reads the file you changed. The table lists each config A change to `wifi-setup.env` needs no restart: the Wi-Fi setup unit reads the file each time it runs, and the unit runs only on request. To fix a new setup password in it and print it for a card, run `teaport setup-card --new-password`; see [teaport setup-card](/reference/cli/#teaport-setup-card). - + On the configuration page, the restart runs the same command two seconds later. The delay gives the brain time to answer the page before it replaces itself, and the timer survives the brain exiting. @@ -204,7 +204,7 @@ Groq stays second, for when BaseTen does not answer. Write `LLM_EXTRA_BODY` in ` 4. Enter the model name in `LLM_MODEL`, or leave it empty for the default, `gpt-oss-120b`. 5. Save. The page lists the brain as still running the old values; restart it from the page, or as [Apply the change](/guides/configuration/#apply-the-change) describes. - + ### From the command line @@ -216,7 +216,7 @@ teaport key set In a terminal on the device, the command asks for the key without showing it. It also reads the key from standard input, for example `teaport key set < key.txt`; over SSH, use that form, because without a terminal there is no prompt, and your own terminal shows the key as you type it. The next conversation uses the new key; the brain needs no restart. The [teaport key set](/reference/cli/#teaport-key-set) reference lists its options and exit statuses. - + ### In the configuration files diff --git a/docs/src/content/docs/guides/discord-bridge.md b/docs/src/content/docs/guides/discord-bridge.md index f8abffa32..be0ada0a6 100644 --- a/docs/src/content/docs/guides/discord-bridge.md +++ b/docs/src/content/docs/guides/discord-bridge.md @@ -5,7 +5,7 @@ description: Install the optional Discord bridge so teaport joins you in a voice The Discord bridge is an optional host service that carries a Discord voice channel into teaport. When the user it follows joins a voice channel on your server, the teaport bot joins the same channel: you talk to the assistant through Discord, and it answers there. The installer adds the bridge only when you ask for it; a plain install leaves no bridge behind. - + ## How the bridge works @@ -23,7 +23,7 @@ The brain holds one conversation at a time. When the bot joins, a live dashboard - Node.js 22 or later on the host. The installer stops when it is missing. - The ID of your Discord server (the guild ID) and your Discord user ID, both numeric. - + ## Create the Discord bot @@ -41,13 +41,13 @@ The brain holds one conversation at a time. When the bot joins, a live dashboard Replace `DISCORD_BOT_TOKEN` with the token from the application you created. The file now holds the token, and only your user can read it. - + ## Install and enable the bridge The installer does the rest: it copies the bridge, installs its dependencies, writes `/etc/teaport/bridge.env` and the `teaport-discord-bridge` unit, and enables the service. - + - On the Jetson, re-run the installer with the bridge turned on: @@ -65,11 +65,11 @@ The installer writes both values to `/etc/teaport/bridge.env`. Leave the variables out and the installer prompts for the server and the user, and for the token when no token file exists. The installer also accepts the token as `DISCORD_BOT_TOKEN` and writes it to the token file. A repair run keeps the values already in `bridge.env` unless you set the variables again. - + The token itself never lands in the unit or in `bridge.env`: the env file records the token path, `DISCORD_BOT_TOKEN_FILE`, `~/.config/teaport/discord_bot_token` by default. The bridge reads the token from that file at startup, and a `DISCORD_BOT_TOKEN` environment variable wins when set. A new token needs a bridge restart to take effect. - + ## Check the bridge @@ -95,7 +95,7 @@ The token itself never lands in the unit or in `bridge.env`: the env file record The line `bot is not in the configured guild` means you have not added the bot to the server in `BRIDGE_GUILD_ID`. 3. Join a voice channel on the server as the user the bot follows, and speak. The bot joins the channel with you and leaves when you leave; the assistant hears you and answers in the channel. - + ## Turn off the bridge @@ -107,7 +107,7 @@ The token itself never lands in the unit or in `bridge.env`: the env file record The bot leaves the channel, and the unit no longer starts at boot. To use the bridge again, run the same command with `enable`. - + ## What's next diff --git a/docs/src/content/docs/guides/faq.md b/docs/src/content/docs/guides/faq.md index 41de7cd5b..5d8c991c9 100644 --- a/docs/src/content/docs/guides/faq.md +++ b/docs/src/content/docs/guides/faq.md @@ -33,7 +33,7 @@ The brain and the plugin are MIT. The engine is a separate component with its ow Yes. Install without an agent and teaport runs in voice-only mode: the brain offers only the tools that live on the device, and the installer writes `TEAPORT_AGENT=none`. Anything that needs the OpenClaw gateway, such as web search, memory, or the agent consult, is not available in this mode. Running the installer again with `--install-agent`, or installing OpenClaw yourself and running it again, turns the agent on; the choices are in [Install an agent](/getting-started/installation/#install-an-agent). - + ## Can teaport answer phone calls? diff --git a/docs/src/content/docs/guides/local-audio.md b/docs/src/content/docs/guides/local-audio.md index 02a645b29..476e66c95 100644 --- a/docs/src/content/docs/guides/local-audio.md +++ b/docs/src/content/docs/guides/local-audio.md @@ -23,7 +23,7 @@ sudo systemctl disable --now teaport-local-audio A bridge you disabled stays off when the installer runs again without the flag. - + ## Talk to the agent @@ -74,7 +74,7 @@ On an XVF3800, the LED ring shows phone-call state: breathing red while a call r The XVF3800 cancels echo in hardware. The bridge replaces the chip's automatic gain with a fixed gain, and sets the chip's echo suppression to remove the device's own voice from the microphone while still letting your voice through when you talk over it. `LOCAL_AUDIO_ECHO_CONTROL` and `LOCAL_AUDIO_MIC_GAIN_DB` adjust the behavior. - + ## What's next diff --git a/docs/src/content/docs/guides/phone-calls.md b/docs/src/content/docs/guides/phone-calls.md index f151484ef..c2f34fc3c 100644 --- a/docs/src/content/docs/guides/phone-calls.md +++ b/docs/src/content/docs/guides/phone-calls.md @@ -21,7 +21,7 @@ You need: repository, and the service runs `~/teaport-sip/build/teaport-sip`. - Access to the device as the user the teaport services run as. - + ## Turn on telephony @@ -49,13 +49,13 @@ To configure the line, follow these steps: password, and enables the service. If the registration fails, the wizard writes nothing and telephony stays off. - + Run the wizard as the user the services run as. As root, add `sudo -E`: a plain `sudo` resets `HOME`, so the wizard writes a configuration the gateway never reads, and it refuses to. - + ### Turn it on without prompts @@ -73,7 +73,7 @@ Replace the following: - `SIP_USER`: the username the trunk assigns you. - `SIP_PASSWORD`: the trunk password. - + ### Use an existing gateway configuration @@ -92,7 +92,7 @@ the brain answers the call, after a couple of rings. If a gateway or SIP front-end launched by hand is still running, the command refuses and names it: the service it is about to enable needs port 5060 and the socket. - + ### Change the trunk later @@ -105,7 +105,7 @@ does not know. Before the test registration, the wizard lists by name the settings it keeps. To keep nothing and write a fresh template, run `teaport sip configure --fresh`. - + ## Check the line @@ -117,7 +117,7 @@ in it, and the registration from this run: teaport sip status ``` - + To follow the gateway's journal: @@ -127,7 +127,7 @@ teaport logs sip -f The call's own lines are in the brain's journal, `teaport logs brain`. - + ## Keep the line running @@ -149,7 +149,7 @@ teaport sip restart The command waits for the trunk's `200 OK`; the brain reconnects on its own. - + The gateway cancels echo for the caller. `teaport sip aec` prints the current acoustic echo cancellation (AEC) setting: @@ -166,7 +166,7 @@ teaport sip aec off teaport sip aec on ``` - + To turn telephony off: @@ -178,7 +178,7 @@ The command stops and disables the gateway. The configuration stays at `~/.config/teaport/teaport-sip.conf`; add `--purge` to remove it too. Run the wizard again to turn telephony back on. - + The configuration is the gateway's own `key=value` format: `registrar_uri`, `id_uri`, `username`, `password`, `uds_path`, `aec`, `auto_answer`, and more. @@ -188,7 +188,7 @@ confirmed, because the gateway still runs the configuration it started with. Nothing about the line lives in `/tmp`: the configuration is in `~/.config/teaport`, the socket in `/run/teaport`, and the logs in journald. - + ## A call during a conversation @@ -203,7 +203,7 @@ The brain answers the call, not the gateway. The delay is a setting, pipeline and words its greeting during the ring, so the greeting plays as soon as the caller is connected. See [the settings reference](/reference/settings/#sip-front-end). - + While the call rings, the agent asks the live conversation, in the conversation's language: *"Someone's calling me — Ann Smith. Should I step away diff --git a/docs/src/content/docs/guides/troubleshooting.md b/docs/src/content/docs/guides/troubleshooting.md index 243ed62c8..8a35834a2 100644 --- a/docs/src/content/docs/guides/troubleshooting.md +++ b/docs/src/content/docs/guides/troubleshooting.md @@ -26,7 +26,7 @@ teaport logs # what did the brain report? `teaport doctor --fix` runs the same checks and restarts a service whose unit has stopped. It prints the unit that it restarts. - + You can run the installer again at any time. It repairs an installation without making a second one and keeps the settings that you added yourself. @@ -178,7 +178,26 @@ also needs up to a minute before the engine port listens. 3. If the same check fails again, read the log. See [Where the logs are](#where-the-logs-are). - + + +## The brain does not start without its token + +**Cause** `/etc/teaport/brain.env` has no `GATEWAY_TOKEN`. The brain refuses to start +without it, and systemd does not restart it. `teaport doctor` shows +`GATEWAY_TOKEN unset` and `teaport-brain refused to start`. The device doesn't answer in +the room, in Talk, or on phone calls. Every installer run writes a token, so the line was +lost after the install, for example by a hand edit or a restored backup. + +**Fix** + +1. Run the installer again, as for the first install. It writes a new token for the + brain, the agent's plugin, the room microphone, and the Discord bridge, and starts the brain. +2. Run `teaport doctor`. The last line reads `doctor: all good`. + +Don't add a token to `brain.env` by hand. The agent's plugin and the Discord bridge must +have the same token, and the installer writes it to all of them. + + ## The browser cannot open `https://teaport.local` @@ -406,8 +425,7 @@ the dashboard link or the app's setup code. The code is over and the screen clea again; if it keeps failing, check the gateway with `openclaw gateway status`. Pairing links work only through the front door, `https://teaport.local/p/...`. The -same path on the brain's own port, `http://:7861/p/...`, answers -**Not Found**. +brain's own port, 7861, accepts connections only from the device itself. ### The pairing link does not open @@ -419,7 +437,7 @@ door's configuration or `brain.env`. [Install teaport](/getting-started/installation/#install-teaport). A re-run repairs the installation and keeps your settings. You do this one time. - + ## Phone calls go unanswered @@ -428,7 +446,7 @@ the installation and keeps your settings. You do this one time. to it (`TEAPORT_SIP_SOCKET` empty in `/etc/teaport/brain.env`); or the trunk registration is missing, so calls from the provider never arrive. - + **Fix** @@ -487,7 +505,7 @@ read Chinese through the Mandarin dictionary, speak without tones. The other voices are not affected. The installer's checks report `running WITHOUT the Mandarin dict`. - + **Fix** @@ -517,7 +535,7 @@ when `engine.env` sets `VOX_TTS_WATERMARK=0`. If `engine.env` sets watermark, and the installer's checks report `running WITHOUT the AI watermark`. - + **Fix** @@ -720,7 +738,7 @@ run out, and asks you to connect your own account. 3. Ask teaport something. The `answers (brain)` line reads `working`, and the note on the configuration page goes away, after the provider accepts a request. - + ## teaport does not remember anything diff --git a/docs/src/content/docs/guides/updating.md b/docs/src/content/docs/guides/updating.md index 4c4cf387d..99c8cb1ac 100644 --- a/docs/src/content/docs/guides/updating.md +++ b/docs/src/content/docs/guides/updating.md @@ -5,14 +5,14 @@ description: Check a device against its release manifest, install the update wit The `teaport update --check` command compares the device with the release manifest and names the parts that differ; it changes nothing. `teaport update` installs a new brain, engine, or model by itself, through the installer's narrower paths: `install.sh --only brain` installs the brain package alone, and `install.sh --only engine` updates the engine alone. You can run those yourself too. A change to anything else takes a full installer run. `install.sh --rollback brain` and `install.sh --rollback engine` put the previous one back. - + ## Before you begin - An SSH connection to the device: every command on this page runs on it. - A device with teaport installed. `teaport update --check` reads `/opt/teaport/manifest.json`, the manifest the installer wrote, and exits with an error if the file is missing. - + ## Check for updates @@ -43,7 +43,7 @@ To install what the check found: The update runs as the `teaport-update` service, and the command prints its output until it ends. The user that runs the brain can start that service without a password; anyone else is asked for an administrator's password. To install without the question, for example from a script, run `teaport update --yes`. - + The service fetches the installer of the release, at the release tag that the manifest names. It never runs an installer from a branch, or one from before `teaport update` existed. When the engine or the models changed, it runs `install.sh --only engine`; when the brain changed, it then runs `install.sh --only brain`. Each run downloads first. An update never goes back: when the channel you pick names an older brain or an older engine than the device has, `teaport update` installs nothing from it, and `teaport update --check` says so. To go back on purpose, use `install.sh --rollback`. Before it swaps in the new engine or brain, it waits until nobody is talking to the device: no phone call, no Talk session, and no conversation with the device's microphone. After an hour of conversation, the run stops before the swap and keeps what it downloaded, so the next try is quick. Each run puts the previous engine or brain back by itself if the new one doesn't come back healthy, as the next sections describe. @@ -63,7 +63,7 @@ teaport update --status The command prints `running`, `done`, `failed`, or `interrupted`, for a run that a power cut stopped, with the step and the reason. The full output is in `/var/lib/teaport-update/log` and in `journalctl -u teaport-update`. - + ### Update only the brain @@ -145,11 +145,11 @@ The engine takes about a minute to load its models after a restart, and a Talk s `/etc/teaport/engine.env` gains only the keys it lacks. A value that is already in the file stays, so a `KOKORO_RESERVE_FPT` that you tuned survives the update. A full run writes the installer's values over it. - + The run asks you to accept the engine license only when its version differs from the one you accepted. It installs no system packages: it checks that `espeak-ng`, `libopenblas.so.0`, and `libcudnn.so.9` are present, and stops when one is missing. Nothing else changes: no brain build and no other unit. - + If a drop-in changes the engine's unit, for example one that a manual deployment left in `/run`, the run names it and leaves it in place. Remove it if you don't need it, and then run `sudo systemctl daemon-reload`. @@ -179,7 +179,7 @@ To put the previous brain package back, run the rollback on its own: The run installs the newest other package kept in `/var/cache/teaport`, restarts the brain, and checks it comes back. The `teaport` command and the root helpers come with the package, so they go back together with the brain. The package that the run replaces stays kept, so running the rollback again undoes it. - + The installer accepts two components, `brain` and `engine`, and `--only` and `--rollback` do not combine in one run. @@ -201,11 +201,11 @@ To put the previous engine back, run the rollback on its own: The run takes the newest engine kept in `engine.rollback/` in the install root and makes it the live engine again, with the unit it ran under and any model it kept. It keeps the live engine there first, moves the kept files back, restarts the engine, and checks that it comes back. To undo the rollback, run it again. - + The engine-only update rolls back on its own when the engine fails its check. A rollback doesn't: if the engine doesn't come back, the run stops and says so. A full run doesn't roll back either; use the rollback by hand there. - + ## Choose a release channel diff --git a/docs/src/content/docs/guides/wifi-setup.md b/docs/src/content/docs/guides/wifi-setup.md index b5c614436..635fcdd4f 100644 --- a/docs/src/content/docs/guides/wifi-setup.md +++ b/docs/src/content/docs/guides/wifi-setup.md @@ -55,7 +55,7 @@ If you start setup by voice, the screen shows its words in the language that the The setup network uses WPA2. Its password is the one printed on the paper insert, stored on the device as `WIFI_SETUP_PASSWORD` in `/etc/teaport/wifi-setup.env`. Without that stored password, the device makes a fresh random one for each run: twelve characters in three groups of four, for example `k7mq-x4tn-p9wr`, lowercase letters and digits without look-alikes or sound-alikes (no 0 or o, no 1, l or i, no q). The hyphens are part of the password; type it as the screen shows it. The screen shows it, and the device reads it out, character by character with "dash" between the groups, when it has no screen or you say "repeat". A password for the paper insert should use the same grouped form: `teaport setup-card --new-password` makes one, stores it, and prints what goes on the insert (see [teaport setup-card](/reference/cli/#teaport-setup-card)). - + ## Create your login diff --git a/docs/src/content/docs/index.mdx b/docs/src/content/docs/index.mdx index e5a26723c..97129c623 100644 --- a/docs/src/content/docs/index.mdx +++ b/docs/src/content/docs/index.mdx @@ -35,7 +35,7 @@ answers in speech. Your voice does not leave the device. configuration page. A restart applies the change; nothing hot-reloads. See [Configure teaport](/guides/configuration/). - {/* source: install.sh:3009,3040#f9381768; brain/teaport_brain/gateway_server.py:27#8b91144b; brain/teaport_brain/config_ui.py:44-45#433b1e87 */} + {/* source: install.sh:3009,3040#f9381768; brain/teaport_brain/gateway_server.py:27#9973f1cb; brain/teaport_brain/config_ui.py:45-46#433b1e87 */} Answer phone calls on the device over a SIP trunk. `teaport sip configure` diff --git a/docs/src/content/docs/reference/architecture.md b/docs/src/content/docs/reference/architecture.md index 62bb1b6e8..f415dd429 100644 --- a/docs/src/content/docs/reference/architecture.md +++ b/docs/src/content/docs/reference/architecture.md @@ -133,7 +133,7 @@ Client tools run on the client, not in the brain: the client announces its featu Only the plugin's Talk session has a relay for `openclaw_agent_consult`. The plugin announces `relay` in its features when OpenClaw gives the session a tool-call handler. The brain also counts the run-control protocol, which only the plugin speaks, so a brain updated without its plugin keeps the relay. A consult on any other session goes straight to the agent: the brain sends no call to the client and does not wait for the relay to acknowledge one. - + ## Network ports @@ -142,10 +142,10 @@ The table lists each port a teaport service listens on, and the service behind i | Port | Service | What it serves | | --- | --- | --- | | 8000 | `teaport-engine` | speech-to-text and text-to-speech for every front end | -| 7861 | `teaport-brain` | the `/talk` WebSocket and `/health`; the plugin, the Discord bridge, and the room microphone connect here as clients | +| 7861 | `teaport-brain` | the `/talk` WebSocket and `/health`, on the device only (`127.0.0.1`); the plugin, the Discord bridge, and the room microphone connect here as clients | | 80 | `teaport-wifi-setup`, through a redirect | captive-portal probes on the setup network, sent to the setup page while the service runs | - + The `teaport-sip` gateway binds the SIP port that its trunk configuration names, and it binds nothing before `teaport sip configure` writes the credentials file. The gateway talks to the brain over a UNIX domain socket under `/run/teaport`, not TCP. The Discord bridge and the room microphone open no ports; both connect out to the brain's `/talk` WebSocket. diff --git a/docs/src/content/docs/reference/cli.md b/docs/src/content/docs/reference/cli.md index f79a43d95..b41c4ed90 100644 --- a/docs/src/content/docs/reference/cli.md +++ b/docs/src/content/docs/reference/cli.md @@ -12,7 +12,7 @@ and the release manifest, and it reads the layout the installer creates: `/opt/t The `teaport-brain` package installs the command at `/usr/bin/teaport`. Run `teaport` with no arguments, or `teaport help`, to print the command summary. An unknown command or option prints an error and exits 1. - + The paths and ports in this reference are the defaults that the command reads at startup. `TEAPORT_PREFIX`, `TEAPORT_ETC`, `TEAPORT_SECRETS_DIR`, @@ -33,7 +33,7 @@ recent requests for a reply met at the model provider, whether a newer release i load average, and, on a device with OpenClaw, whether OpenClaw uses the brain's key. When the Session Initiation Protocol (SIP) gateway unit is enabled, it also shows the `teaport-sip` service and the brain's SIP front-end. It takes no options. - + Example: @@ -54,7 +54,7 @@ teaport — status load 0.03 0.19 0.20 ``` - + ## teaport doctor @@ -72,10 +72,11 @@ at all, which says `not set up`. On the device's included trial credit, it also what is left: a warning from half used on, and a failure after it has run out. Where OpenClaw shares the brain's key, it warns while OpenClaw waits for a restart to use a new key, and fails when a key change left OpenClaw and the brain on different keys. When telephony is on, it also checks the SIP gateway binary and service, the brain's SIP front-end, the SIP source filter, and the trunk registration. When it finds a NemoClaw sandbox record, it names the configured -sandbox. Each check prints one line: a check mark for pass, `!` for warning, and a cross -for failure. +sandbox. It fails when `brain.env` has no `GATEWAY_TOKEN`, because the brain does not start +without one, and warns when the brain's port answers beyond the device. Each check prints +one line: a check mark for pass, `!` for warning, and a cross for failure. - + Option: @@ -83,13 +84,13 @@ Option: | --- | --- | | `--fix` | Restarts what failed: a service that is not active, the SIP gateway when it is down or has not registered, and the brain when its SIP front-end is not connected. | - + The final line is `doctor: all good` when every check passed, otherwise `doctor: issues above`. The command exits 0 in the first case and 1 in the second; a warning does not change the exit status. - + Example: @@ -126,7 +127,7 @@ device has, or no brain package at all, offers nothing: the check says so, and | `--yes` | Installs without asking. Without it, the command asks first, and when it isn't run in a terminal it stops and names this option. | | `--status` | Prints how the last update went. It changes nothing. | - + Without `--channel`, the command uses the `TEAPORT_UPDATE_CHANNEL` setting in `/etc/teaport/brain.env`. When that is empty, it uses the channel the installed manifest @@ -149,7 +150,7 @@ device's own channel, so `--channel` goes with `--check` only. It exits 0 when t is installed or there is nothing it installs, and 1 when the update fails. [Update teaport](/guides/updating/#apply-an-update) has the details. - + Press Ctrl+C to stop following: the update goes on. `teaport update --status` prints the last run's state, `running`, `done`, `failed`, or `interrupted` for a run that a power cut @@ -157,7 +158,7 @@ stopped, with the step it is on and its message. The full output is in `/var/lib/teaport-update/log`, which the user that runs the brain can read, and in `journalctl -u teaport-update`. - + The brain also does the check by itself every day (the `TEAPORT_UPDATE_CHECK_SECS` setting; `0` turns it off), and `teaport status` shows the result on a `release` line, or @@ -193,7 +194,7 @@ The command runs under the brain's own Python environment, so it reads the same open-source licenses page that the configuration page links to (see [Open-source licenses](/reference/licenses/)). A package's text is the license files in its `.dist-info` directory. A file longer than 256 KB is cut. - + The command exits with 0 when it shows something. It exits with 1, and says why, when the brain has no package of that name, or when `--notices` finds no document. A brain installed from @@ -217,7 +218,7 @@ take the key, the brain keeps the key it had. In the rare case where OpenClaw mi the key before it failed, `teaport status` says that the two might be on different keys until the next save. - + The command runs with the brain's environment: the settings in `/etc/teaport/brain.env`, your user's home directory from the system's user database, and systemd's default `PATH`. @@ -226,7 +227,7 @@ reads that copy first, so the command saves nothing and tells you to remove the command as the user the brain runs as, not as root. A running brain uses the new key from the next conversation, without a restart. - + | Option | Description | | --- | --- | @@ -250,7 +251,7 @@ takes effect when the check ends, after at most about 10 seconds, or 16 with `-- With `--starter`, exit 2 can also mean that the key was saved but couldn't be marked as the trial key. In each of these cases, running the command again finishes the job. - + Example, with the key in a file: @@ -273,7 +274,7 @@ card, and with 1 when it prints none: no password is fixed, setup mode doesn't a fixed one, the device has no Wi-Fi, or `--new-password` couldn't install the new file. Stopped by a signal, it prints no card and exits with another nonzero status. - + The card has no login for the device. On a device that ships ready to set up, the owner creates the login during setup, on the Wi-Fi setup page or in the settings, as @@ -286,7 +287,7 @@ creates the login during setup, on the Wi-Fi setup page or in the settings, as | `--new-password` | Makes a new password, in the same format as the ones setup mode makes, and fixes it in `wifi-setup.env`. The command keeps the file's other setup settings and comments, installs the file owned by root and readable by the group of the user who runs the command (mode 640, like the installer's other settings files), and prints the card only after the file is in place. It uses `sudo`. If the file holds a line that isn't a setup setting (`WIFI_SETUP_...`) or a comment, or a carriage return, the command changes nothing and exits 1; fix the file by hand. | | `--json` | Prints the name, the password, and the QR code text as one JSON object. | - + Example: @@ -315,11 +316,11 @@ unchanged, so `-f`, `-n LINES`, and `--since` work directly. With no further arg passes `-b`, so a bare `teaport logs` shows this boot's entries instead of the whole journal. - + The command exits with the exit status of `journalctl`. - + Example: @@ -332,7 +333,7 @@ teaport logs engine -f `teaport sip` controls the opt-in telephony: phone calls over SIP. Telephony is off on a fresh install; `teaport sip configure` turns it on and `teaport sip disable` turns it off. - + The wizard writes the gateway configuration to `~/.config/teaport/teaport-sip.conf`. The gateway binary is `~/teaport-sip/build/teaport-sip`, and the gateway and the brain's SIP @@ -344,7 +345,7 @@ front-end meet on the `/run/teaport/teaport-sip.sock` socket. The subcommands are `configure`, `status`, `aec`, `restart`, and `disable`. For a walk through of the setup, see [Set up phone calls](/guides/phone-calls/). - + ### teaport sip configure @@ -360,13 +361,13 @@ host. A re-run keeps the settings of the installed configuration that it does no anything: if the registration fails, the configuration is not written and the units are left as they were. - + On success it writes the configuration with mode 600, enables and restarts the gateway, and prints `SIP enabled — telephony is on. Check: teaport sip status`. It then waits up to 20 seconds for the first registration; a missing registration does not fail the command. - + With `--conf FILE` it adopts an existing gateway configuration instead of asking. The file must be readable and must set `id_uri`, `registrar_uri`, `username`, and `password`. The @@ -374,7 +375,7 @@ must be readable and must set `id_uri`, `registrar_uri`, `username`, and `passwo services need, each change prints a note, and the result is test-registered exactly like the wizard. - + | Option | Description | | --- | --- | @@ -387,14 +388,14 @@ the wizard. | `--conf FILE` | Adopt this gateway configuration instead of running the wizard. | | `-h`, `--help` | Print the usage. | - + The command exits 1 and leaves the installed configuration, if any, unchanged when a flag is unknown, an argument is missing, a check refuses the install, the gateway can't finish its check of the configuration, the test registration fails, or the configuration file changes while the test runs. - + Example: @@ -418,7 +419,7 @@ this run's registration outcome. Without a configuration it prints `config` as ` with the configure command, and it still reports the gateway's registration attempt from the journal. It takes no options. - + Example: @@ -438,12 +439,12 @@ rewrite the `aec` key in place, print the old and new value, and restart the gat reads the setting at startup. The restart preconditions are checked before the file is touched. - + The command exits 1 when the argument is none of the accepted values, the telephony preconditions fail, or the rewrite fails; a failed rewrite leaves `aec` as it was. - + Example: @@ -463,7 +464,7 @@ front-end reconnects to the gateway on its own; the brain service, and any Talk is not touched. The command then waits up to 20 seconds for a fresh registration, and a missing one does not fail it. It takes no options. - + Example: @@ -482,17 +483,17 @@ Stops and disables the `teaport-sip` service and prints configuration is kept and the command says where. Afterwards, `teaport status` and `teaport doctor` report telephony as off by choice. - + | Option | Description | | --- | --- | | `--purge` | Also deletes the configuration file and prints its path. | - + A failing `systemctl` call does not fail the command. - + Example: diff --git a/docs/src/content/docs/reference/installer.md b/docs/src/content/docs/reference/installer.md index d39ee9792..418e200d8 100644 --- a/docs/src/content/docs/reference/installer.md +++ b/docs/src/content/docs/reference/installer.md @@ -90,7 +90,7 @@ A full install writes every unit and env file and restarts the engine and the br The installer honors the overrides in this table; the default applies when the variable is unset. `TEAPORT_REPO` and `TEAPORT_REF` belong to the one-line form alone. - + | Variable | Default | Controls | | --- | --- | --- | @@ -235,13 +235,13 @@ A run downloads the engine files and models that differ from the manifest into ` The non-secret configuration. The installer writes `engine.env` and `brain.env` here, group-readable with mode 640. - + **`~/.config/teaport/`** The secrets directory, created with mode 700. The installer seeds `persona.md` when it is absent and never overwrites it, and keeps the `openclaw_token` and `discord_bot_token` files at mode 600. - + **`/var/lib/teaport/`** @@ -263,7 +263,7 @@ The last `teaport update` run: `run.json`, its state, and `log`, its output. The Root-owned helpers that run outside the brain: the Wi-Fi setup helper and its captive DNS configuration. The brain package does not install anything here. - + **`/usr/bin/teaport` and `/usr/lib/teaport/`** @@ -295,7 +295,7 @@ The owner's login marker, `pending`, in a folder only root can open. Neither the Smaller system configuration lands outside these trees: a journald drop-in, a systemd-resolved drop-in, a sysctl drop-in (`/etc/sysctl.d/60-teaport-multihome.conf`) so that Ethernet and Wi-Fi on one subnet each answer ARP only for their own addresses, and the polkit rule that lets the user that runs the brain scan for Wi-Fi networks, and nothing else. - + ## systemd units @@ -307,54 +307,54 @@ The installer renders the templates in `systemd/*.service.in` into `/etc/systemd The speech engine: Voxtral for speech-to-text and Kokoro for text-to-speech. Rendered on every install and enabled. - + **`teaport-brain.service`** The voice pipeline. The brain serves Talk and the phone line's front end. Rendered on every install and enabled. - + **`teaport-sandbox-recover.service`** NemoClaw sandbox recovery at boot. Rendered and enabled only when the install has a NemoClaw sandbox. - + **`teaport-discord-bridge.service`** The Discord voice bridge. It runs on the host, owns the media leg, and pipes audio to the brain's `/talk` endpoint. The installer renders it when `TEAPORT_ENABLE_BRIDGE=1` or a bot token is already present, and enables it; the unit starts only after the guild, followed user, and token are configured. - + **`teaport-sip.service`** The SIP front end for phone calls. Rendered on every run, never enabled by the installer: the unit carries a `ConditionPathExists` on the SIP configuration, and `teaport sip configure` is what registers a trunk and turns it on. A repair re-renders the unit and leaves its enabled state alone. The gateway binary itself comes from the separate teaport-sip repository. While it renders the SIP unit, the installer also removes a leftover `teaport-sip-brain` unit from older installs. - + **`teaport-local-audio.service`** The local microphone and speaker bridge for a USB mic array, piping audio to the brain's `/talk` endpoint. Rendered on every install but inert until `.env` exists. `TEAPORT_ENABLE_LOCAL_AUDIO=1` seeds that file and enables the unit; a repair without it leaves the enabled state alone, so a bridge the operator disabled stays off. - + **`teaport-wifi-setup.service`** The Wi-Fi setup flow: a temporary setup network and a page where a phone enters the password. The brain starts it when the user asks for setup. Rendered when NetworkManager and iptables are present; never enabled by the installer. It runs as the run user. Its changes to the Wi-Fi, such as the setup network and joining your network, go through `wifi_apply.py` under `sudo`. - + **`teaport-wifi-setup-net.service`** The root side of Wi-Fi setup: the rule that sends port 80 on the setup network to the page, and the captive DNS file. It starts before `teaport-wifi-setup.service` and stops after it, however that ends. It loads no settings file: the settings in `/etc/teaport` are written on the run user's behalf, so no command that runs as root takes its environment from them. The brain package installs it in `/usr/lib/systemd/system`, and the installer also renders it into `/etc/systemd/system`. - + Teaspoon AI appliances come with an OLED face; this installer does not install it, and leaves one that is already on the box alone. - + The installer also enables `avahi-daemon` and `caddy`. - + diff --git a/docs/src/content/docs/reference/licenses.md b/docs/src/content/docs/reference/licenses.md index 5db5fed6c..9ab00c50f 100644 --- a/docs/src/content/docs/reference/licenses.md +++ b/docs/src/content/docs/reference/licenses.md @@ -25,13 +25,13 @@ The brain package installs these files. The table lists where each one is and wh | The `.dist-info` directory of each Python package, under `/opt/teaport/brain/lib/python3.12/site-packages/` | That package's own license files. | | `THIRD_PARTY_NOTICES.txt` in the install root, `/opt/teaport` by default | The attributions for the components the engine is built from. The installer downloads it with the engine. | - + ## See the licenses on the device The configuration page has an Open-source licenses link at the bottom. It opens a page with the notices the package installs, including the two font licenses, and the Python packages in the brain with each one's version and license. Select a package to read its license text. The page is `/settings/licenses` on the Settings site and `http://127.0.0.1:7861/licenses` on the device itself. Like the configuration page, it loads its data with the Settings session or the token. - + `teaport licenses` shows the same on the command line. See the [teaport licenses](/reference/cli/#teaport-licenses) reference. diff --git a/docs/src/content/docs/reference/security.md b/docs/src/content/docs/reference/security.md index f148cdef3..12ba88ee4 100644 --- a/docs/src/content/docs/reference/security.md +++ b/docs/src/content/docs/reference/security.md @@ -154,11 +154,7 @@ Anyone who can reach the setup page or the settings can create the login first, - The setup page is plain HTTP over the setup network's WPA2 password. Someone who knows that password and recorded the phone joining the network can read what the phone sends, including the login password. -- On a device without a gateway token (`GATEWAY_TOKEN`), the configuration page on the - device itself, `http://127.0.0.1:7861/config`, needs no token, so any user or program - on the device can create the login there. - - + The setup page makes the step required, so on a device set up through that page the window ends at setup. The exception is a create that fails because of the device, not @@ -171,6 +167,26 @@ whose owner has no login yet; it doesn't prevent it. See +## The brain's port + +The brain listens on port 7861 (`BRAIN_PORT`). Every program that talks to it runs on the +device: the room microphone, the agent's plugin, the front door, the Discord bridge, and +`teaport`. So the brain listens only on the device itself, `127.0.0.1` +(`BRAIN_LISTEN`). With NemoClaw, the installer adds the docker bridge's address, +`172.18.0.1`, which the agent's sandbox reaches the brain on. Other devices on your +network can't connect to the port. Phones reach the device through its front door. + + + +A conversation on the port (`/talk`), its status (`/talk/status`), and the configuration +page there all need the gateway token, `GATEWAY_TOKEN`. The installer writes it for the +brain, the agent's plugin, the room microphone, and the Discord bridge. A page in a browser on the device, such +as the agent's, can reach `127.0.0.1` too, so the token is required there as well. Without +a token the brain does not start; see +[The brain does not start without its token](/guides/troubleshooting/#the-brain-does-not-start-without-its-token). + + + ## Related - [Create your login](/guides/wifi-setup/#create-your-login) diff --git a/docs/src/content/docs/reference/settings.md b/docs/src/content/docs/reference/settings.md index 3ad00ff67..0902c272d 100644 --- a/docs/src/content/docs/reference/settings.md +++ b/docs/src/content/docs/reference/settings.md @@ -5,7 +5,7 @@ description: Every setting teaport reads, the file it lives in, its default, and This page lists every setting teaport reads, the file it lives in, and what it does. See [Configure teaport](/guides/configuration/) for the configuration page, the secret files, and how to apply a change. - + @@ -344,7 +344,9 @@ In `/etc/teaport/brain.env`. Written by install.sh. Shown read-only. |---|---|---| | `BRAIN_PORT` | **7861** port (1–65535) | Passed as --port by the unit, and read by the local audio bridge to find /talk. Changing it means re-rendering the plugin config, bridge.env and Caddy. *Set by the installer.* | | `GATEWAY_PORT` | **7861** port (1–65535) | Code fallback for the listen port when --port is not given. On an installed box BRAIN_PORT is the effective setting. *Set by the installer.* | -| `GATEWAY_TOKEN` | — | Shared secret for /talk. Empty means anyone who can reach the port gets a full agent session and can replace a client's session by claiming its id; the brain warns loudly at startup. Mirrored into the plugin config by install.sh. Never change one side alone. *Set by the installer.* | +| `GATEWAY_TOKEN` | — | Shared secret for /talk, /talk/status and the configuration page on the brain's port. Without it the brain refuses to start, because anyone who reaches the port gets a full agent session and can replace a client's session by claiming its id. Mirrored into the plugin config by install.sh. Never change one side alone. *Set by the installer.* | +| `TEAPORT_ALLOW_NO_AUTH` | **off** | Let the brain run with no GATEWAY_TOKEN, open to anything that reaches its port. For a developer's brain or a test, never a device: an installed device always has a token. *Set by the installer.* | +| `BRAIN_LISTEN` | `127.0.0.1` | The addresses the brain listens on, comma-separated IP addresses. Every client is on the device, so 127.0.0.1 alone; a NemoClaw install adds the docker bridge's 172.18.0.1, which the sandbox reaches the brain by. --host overrides it. *Set by the installer.* | | `MALLOC_ARENA_MAX` | **2** (≥ 1) | glibc arena cap; part of the memory budget. *Set by the installer.* | | `HF_HUB_OFFLINE` | `1` | Never fetch from the Hub on the appliance. Also set by the package at import. One of `1`. *Set by the installer.* | @@ -401,6 +403,7 @@ In `/etc/teaport/bridge.env`. | `BRIDGE_FOLLOW_USER_ID` | **required** | The user whose voice channel the bot follows. | | `BRIDGE_JOIN_CHANNEL_ID` | — | Force a voice channel instead of following the user. | | `BRAIN_URL` | `ws://127.0.0.1:7861/talk` | Derived from BRAIN_PORT. *Set by the installer.* | +| `BRIDGE_GATEWAY_TOKEN` | — | The brain's GATEWAY_TOKEN, which the bridge sends on /talk. The brain admits no one without it. Copied from brain.env by install.sh. Never change one side alone. *Set by the installer.* | | `TEAPORT_VOICE` | — | TTS voice for bridge sessions; unset = the brain's TTS_VOICE. | | `BRIDGE_PRIME_MS` | **40** ms (≥ 0) | Downlink prime. | | `DISCORD_BOT_TOKEN_FILE` | `~/.config/teaport/discord_bot_token` | Where the bot token is read from. *Set by the installer.* | diff --git a/install.sh b/install.sh index 87c8ebbf7..0ef4d4fa6 100755 --- a/install.sh +++ b/install.sh @@ -2918,7 +2918,7 @@ JSON agent_nemoclaw() { resolve_nemoclaw; resolve_gateway_token log "NemoClaw sandbox '$SANDBOX' — installing the plugin + wiring talk.realtime" - local brain_ws="ws://172.18.0.1:${BRAIN_PORT}/talk" # sandbox -> host brain over the docker bridge + local brain_ws="ws://$BRAIN_BRIDGE_ADDR:${BRAIN_PORT}/talk" # sandbox -> host brain over the docker bridge # 1. Plugin into the sandbox. Published -> npm spec; otherwise npm-pack a tgz (honors the # files allowlist), upload it, and `openclaw plugins install ` copies it into @@ -3649,6 +3649,29 @@ set_avahi_hostname() { # stay what an install that never ran this line has. TTS_PACING_SEED=("?TTS_PACING=lead" "?TTS_EAGER=low_lead") +# Where the brain listens (BRAIN_LISTEN, #477): the box alone, since every client of it is +# on the box. NemoClaw's sandbox is the exception: it reaches the host's brain over the +# docker bridge (agent_nemoclaw's brain_ws), so its address too. Written plain every run +# (a box that changes agents follows), but for a repair run that can't see the sandbox. +BRAIN_BRIDGE_ADDR=172.18.0.1 +brain_listen() { + if [ "$AGENT_MODE" = nemoclaw ]; then printf 'BRAIN_LISTEN=127.0.0.1,%s\n' "$BRAIN_BRIDGE_ADDR" + # A repair run as root or another account sees no sandbox (detect_agent looks in its own + # home; see TEAPORT_AGENT below), so a box with one (its recover unit) only SEEDS it: an + # existing value stays, and the sandbox keeps its way to the brain. + elif [ -z "$AGENT_MODE" ] && systemctl cat teaport-sandbox-recover.service >/dev/null 2>&1; then + printf '?BRAIN_LISTEN=127.0.0.1,%s\n' "$BRAIN_BRIDGE_ADDR" + else echo BRAIN_LISTEN=127.0.0.1; fi +} +# --only brain writes no brain.env. A brain from before #477 listened everywhere, so a +# NemoClaw box's sandbox reached it on the bridge with nothing written; the new one listens +# on BRAIN_LISTEN, 127.0.0.1 when unset. Such a box (its sandbox-recover unit says so) +# gets the bridge address too, before the new brain starts. A seed: one already set stays. +brain_listen_seed() { + systemctl cat teaport-sandbox-recover.service >/dev/null 2>&1 || return 0 + write_env "$ETC/brain.env" "?BRAIN_LISTEN=127.0.0.1,$BRAIN_BRIDGE_ADDR" +} + phase_services() { log "systemd units + env files" SUDO mkdir -p "$ETC" @@ -3685,7 +3708,7 @@ phase_services() { "TEAPORT_FRONTDOOR_CA_NAME=$FRONTDOOR_CA_NAME") fi write_env "$ETC/brain.env" \ - "BRAIN_PORT=$BRAIN_PORT" \ + "BRAIN_PORT=$BRAIN_PORT" "$(brain_listen)" \ "${LLM_URL_SEED}LLM_BASE_URL=$LLM_BASE_URL" "${LLM_MODEL_SEED}LLM_MODEL=$LLM_MODEL" \ "TEAPORT_URL=ws://127.0.0.1:$ENGINE_PORT/v1/realtime" \ "${agent[@]}" \ @@ -3893,9 +3916,11 @@ phase_bridge() { # --omit=dev; the host toolchain builds @discordjs/opus from source (JetPack ships gcc/make/python3). run npm install --omit=dev --no-audit --no-fund --prefix "$PREFIX/bridge" + # the brain's token: /talk admits no one without it (#477) + resolve_gateway_token write_env "$ETC/bridge.env" \ "BRIDGE_GUILD_ID=$guild" "BRIDGE_FOLLOW_USER_ID=$follow" \ - "BRAIN_URL=ws://127.0.0.1:$BRAIN_PORT/talk" \ + "BRAIN_URL=ws://127.0.0.1:$BRAIN_PORT/talk" "BRIDGE_GATEWAY_TOKEN=$GATEWAY_TOKEN" \ "DISCORD_BOT_TOKEN_FILE=$tokfile" render_unit teaport-discord-bridge.service.in teaport-discord-bridge.service SUDO systemctl daemon-reload @@ -4488,6 +4513,9 @@ main_brain_only() { # the old SIP brain must not be left running beside it. Its unit goes only once the swap # is verified; a rollback puts it back (see sip_brain_detach). sip_brain_detach + # Before the new brain starts: a NemoClaw box's sandbox keeps its way to it (#477). An + # old brain left in place ignores the line. + brain_listen_seed # Kept right before the swap, nothing in between: a run that stops earlier (a wait that # gives up, a drop-in that cannot move) leaves the cache --rollback brain picks from as it # was, and the download stays in $STATE for the next try. brain_swap takes a package that diff --git a/systemd/teaport-brain.service.in b/systemd/teaport-brain.service.in index 04dde28f5..4d2d498da 100644 --- a/systemd/teaport-brain.service.in +++ b/systemd/teaport-brain.service.in @@ -27,6 +27,9 @@ EnvironmentFile=@ETC@/brain.env ExecStart=@PREFIX@/brain/bin/teaport-brain --port ${BRAIN_PORT} Restart=on-failure RestartSec=5 +# 78 (EX_CONFIG): a start the brain refused for its configuration, no GATEWAY_TOKEN or +# a bad BRAIN_LISTEN (#477). A restart can't fix it: one failure, `teaport doctor` says why +RestartPreventExitStatus=78 # The voice path goes last when memory runs out (see teaport-engine.service). OOMScoreAdjust=-500