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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion brain/teaport_brain/config_schema.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand Down
27 changes: 15 additions & 12 deletions brain/teaport_brain/config_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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}"
Expand All @@ -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
Expand Down
144 changes: 119 additions & 25 deletions brain/teaport_brain/gateway_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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=<value> 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=<value> 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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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__":
Expand Down
7 changes: 4 additions & 3 deletions brain/teaport_brain/pairing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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://<box>: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
Expand Down
26 changes: 22 additions & 4 deletions brain/teaport_brain/settings_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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", "")
Expand Down
Loading
Loading