Skip to main content
Glama
Tethergate
by peva3
README.md
# Tethergate

[![npm](https://img.shields.io/npm/v/opencode-tethergate.svg)](https://www.npmjs.com/package/opencode-tethergate)
[![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![MCP](https://img.shields.io/badge/MCP-compatible-6f42c1.svg)](https://modelcontextprotocol.io)

Tethergate is an OpenCode MCP server plus a systemd node agent for running allow-listed
root commands on enrolled LAN or Tailscale machines over mutual TLS. Nodes connect
outbound to the server, so there is no SSH daemon, inbound node port, or shared VPN
credential to manage.

The server exposes these MCP tools to OpenCode:

| Tool | Purpose |
| --- | --- |
| `remote_list_nodes` | List granted nodes, labels, and inventory facts |
| `remote_node_exec` | Run a command on a node as root |
| `remote_bulk_exec` | Run one command on up to 20 nodes or a label group (grants resolve labels when created) |
| `remote_get_file` | Read an allowlisted file with a SHA-256 checksum (agent 0.5.0+) |
| `remote_put_file` | Atomically write an allowlisted file (agent 0.5.0+) |
| `remote_policy_check` | Check a command against the safety floor without running it |
| `remote_audit_tail` | Read recent encrypted audit entries |
| `remote_audit_search` | Filter the audit log by node, action, outcome, or time |

Every tool carries MCP annotations for read-only, destructive, idempotent, and
open-world behavior so clients can choose the right approval UX.

Commands run as root on the node. Tethergate is for machines you own and control,
not for untrusted multi-tenant hosts.

## Get started right now

Paste this into your OpenCode session on the Linux machine that will host
Tethergate:

```text
Read https://github.com/peva3/tethergate/blob/main/STARTUP.md and follow it to set up Tethergate on this machine. Ask me for the node details it requires.
```

The full agent checklist is in [STARTUP.md](STARTUP.md). Prefer to run the setup
yourself? Use the manual steps below.

## Security at a glance

- **No inbound node ports.** The agent opens an outbound TLS connection to the
  server and stays connected.
- **Mutual TLS.** A local EC P-256 CA issues node certificates that rotate automatically. A node
  is authenticated by its certificate, not a shared password.
- **One-command enrollment.** The server prints a curl one-liner with a
  short-lived, single-use or fleet token.
- **Deny by default.** A new OpenCode session has access to no nodes until an
  operator grants it through `/tethergate` or the admin web UI.
- **Human approval.** Access changes require an OpenCode permission prompt. A model
  cannot silently grant itself a node.
- **Hard command floor.** The node refuses destructive patterns such as
  `rm -rf /` even if the server or model asks for them.
- **Encrypted state.** The CA key and audit payloads are encrypted with
  `TETHER_MASTER_KEY`; enrollment tokens are stored as hashes.
- **Private binds only.** Wildcard and public bind addresses are refused.
- **Audited.** Node access, policy decisions, lifecycle changes, and certificate
  renewals are recorded in a hash-chained audit log.

See [SECURITY.md](SECURITY.md) for the full trust model and residual limitations.

## Architecture

```text
┌──────────────┐   stdio    ┌────────────────────┐
│   OpenCode   ├───────────►│ tethergate mcp      │
└──────────────┘            └─────────┬──────────┘
                                      │ mcp.sock
                            ┌─────────▼──────────┐
                            │ Tethergate server  │
                            │  Docker, host net  │
                            ├────────────────────┤
                            │ control.sock admin │
                            │ HTTPS :8787        │
                            │ mTLS  :8788 agent  │
                            │ HTTP  :8789 web UI │
                            └─────────┬──────────┘
                                      │ outbound TLS
                       ┌──────────────┴──────────────┐
                       │                             │
                 ┌─────▼─────┐                 ┌─────▼─────┐
                 │  node A   │                 │  node B   │
                 │  systemd  │                 │  systemd  │
                 └───────────┘                 └───────────┘
```

The server stores its CA, node records, and audit log under `/data`. The OpenCode
plugin only talks to the server's local Unix sockets; it never connects to a node
directly.

## Quick start

### 1. Start the server

You need a Linux host with Docker, a private LAN address or Tailscale address, and
outbound access from the nodes to that address.

```sh
git clone https://github.com/peva3/tethergate.git
cd tethergate
cp .env.example .env
chmod 600 .env
```

Set these in `.env`:

```sh
TETHER_BIND=<private-lan-or-tailscale-ip>
TETHER_PUBLIC_HOST=<same-address-nodes-use>
TETHER_MASTER_KEY=<base64url 32-byte key>
TETHER_CONTROL_CAPABILITY=<random hex capability>
```

Generate the two secrets without reusing them:

```sh
python3 -c 'import base64,secrets; print(base64.urlsafe_b64encode(secrets.token_bytes(32)).decode())'
openssl rand -hex 32
```

Start the server:

```sh
docker compose up -d --build
set -a; . ./.env; set +a
curl -k "https://$TETHER_PUBLIC_HOST:8787/healthz"
```

The install and enrollment endpoints use HTTPS with the local CA. Use `-k` only
while verifying a fresh install, or install the server CA certificate and use normal
verification.

### 2. Install the OpenCode plugin

```sh
opencode plugin add opencode-tethergate@latest
```

Or add it manually to `opencode.json`:

```json
{
  "plugins": ["opencode-tethergate@latest"],
  "mcp": {
    "servers": {
      "tethergate": {
        "type": "local",
        "command": ["docker", "exec", "-i", "tethergate", "tethergate", "mcp"]
      }
    }
  }
}
```

`@latest` follows new releases. A bare `opencode-tethergate` installs the
current release once and does not auto-update. To pin the admin surface, use an
exact version such as `opencode-tethergate@0.5.0` and update it deliberately
after reviewing `CHANGELOG.md`.

### 3. Enroll a node

In OpenCode:

```text
/tethergate node add worker-1
```

The command prints a complete `curl … | sudo bash` one-liner. Run it as root on the
target machine. The installer:

1. Pins the server public-key fingerprint embedded in the installer URL (not a public CA chain).
2. Installs the agent under `/opt/tethergate-agent/releases/<version>`.
3. Writes `/etc/tethergate-agent/agent.json` with mode `0600`.
4. Enrolls the node and starts `tethergate-agent.service`.

For a reusable fleet installer:

```text
/tethergate fleet add tailnet
```

Run the printed one-liner on each machine. Fleet tokens have a use limit and an
expiry and can be revoked from `/tethergate`, the web UI, or the CLI.

### 4. Grant the session access

```text
/tethergate grant worker-1
```

Or open `/tethergate` and choose nodes. A grant is scoped to the current OpenCode
session; it is not a global permission.

### 5. Use it

Ask OpenCode to run a command through the Tethergate MCP tool. For example:

```text
Use remote_node_exec on worker-1 to run `uname -a`.
```

## Admin surfaces

- **TUI menu** — `/tethergate` in the OpenCode TUI.
- **Slash command** — `/tethergate …` for TUI, web, and desktop clients.
- **Standalone web UI** — optional, disabled by default. Set `TETHER_WEB_PORT=8789`,
  `TETHER_WEB_BIND` to a private LAN/Tailscale address, and a long random
  `TETHER_WEB_TOKEN`. Open `http://<address>:8789/` and log in with the token.
  Prefer Tailscale or an SSH tunnel; never expose it publicly.
- **CLI** — `docker exec -it tethergate tethergate …` for break-glass server work.
  Normal access changes should go through `/tethergate` so they are permission-gated
  and audited.

The web UI supports overview/health, node inventory and lifecycle actions, fleet
installers, session grants, and audit verification.

## OpenCode slash commands

These work as `/tethergate …` in the TUI and as a server-side slash command in the
OpenCode web and desktop clients. Access changes and node lifecycle actions trigger
the Tethergate permission prompt.

| Command | Action |
| --- | --- |
| `/tethergate` or `/tethergate help` | Show the command list |
| `/tethergate status` | Show this session's access and nodes |
| `/tethergate grant all` | Grant this session every enrolled node |
| `/tethergate grant NODE[,NODE]` | Grant this session specific nodes |
| `/tethergate grant KEY=VALUE` | Grant active nodes matching a label |
| `/tethergate revoke` | Revoke this session's node access |
| `/tethergate default deny` | New sessions get no node access |
| `/tethergate default all --yes` | New sessions get every node |
| `/tethergate node list` | List enrolled nodes |
| `/tethergate node labels NAME K=V` | Set node labels used by groups |
| `/tethergate node add NAME` | Create a one-command enrollment token |
| `/tethergate node revoke NAME` | Revoke a node |
| `/tethergate node reset NAME` | Clear quarantine and re-enable a node |
| `/tethergate node rename OLD NEW` | Rename a node |
| `/tethergate node retire NAME` | Retire a node and free its name |
| `/tethergate node update NAME` | Update a node agent to this server version |
| `/tethergate node rollback NAME` | Roll back a node agent |
| `/tethergate node uninstall NAME` | Remove the agent from a node |
| `/tethergate auto status` | Show automatic agent update state |
| `/tethergate auto pause [REASON]` | Stop future automatic agent updates |
| `/tethergate auto resume` | Resume automatic agent updates |
| `/tethergate auto run` | Skip the delay and start the rollout now |
| `/tethergate freeze on [REASON]` | Stop all remote execution |
| `/tethergate freeze off` | Reopen remote execution |
| `/tethergate freeze status` | Show the global freeze state |
| `/tethergate fleet add [LABEL]` | Create a reusable fleet installer |
| `/tethergate fleet list` | List fleet installers |
| `/tethergate fleet revoke ID` | Revoke a fleet installer |

`node add` and `fleet add` print the complete installer one-liner. `default all`
requires `--yes`; the default is deny. `auto run` skips the configured rollout
delay, so use it only after reviewing the target version.

### Web and Desktop GUI

The `/tethergate` slash command works in the OpenCode web and desktop clients today.
We are targeting native Web and Desktop GUI panels as soon as OpenCode exposes a
stable GUI plugin surface in those clients. Until then, the standalone web UI
provides the full operator surface outside OpenCode.

## Node lifecycle

Node lifecycle commands are listed in the slash-command table above.

- **Update/rollback** pushes a checksum-verified, versioned agent release over the
  existing mutual-TLS connection.
- **Rename** changes the node label without re-enrollment.
- **Retire** keeps an audited tombstone and frees the original name for a
  replacement.
- **Uninstall** removes the unit and agent files remotely.
- **Revoke** disables the certificate immediately.

Agent updates can also roll out automatically. The server waits
`TETHER_AUTO_UPDATE_DELAY_SECONDS`, updates one canary node, and proceeds only if
that node reconnects with the new version. Set `TETHER_AUTO_UPDATE=off` for a manual
lockout window.

## Certificates

Node certificates are valid for 180 days. The agent checks every six hours and, in
the final 30 days, generates a new P-256 key and CSR, sends it over the authenticated
mTLS connection, and atomically installs the signed certificate and key. The old
certificate remains accepted until the node presents the new one, so a lost renewal
response cannot lock out a node.

Existing nodes that predate key rotation continue to renew with the same key until
they receive a `node update`.

## Backups and audit

Create an encrypted backup of the CA, TLS material, state database, and master key:

```sh
./scripts/backup.sh
```

Restore with `./scripts/restore.sh <archive>` while the container is stopped. Keep
backups off the data volume. The archive contains the CA private key and the master
key, so treat it as a secret.

Audit retention defaults to 90 days and keeps the newest 1,000 entries. Pruning is
anchored with an HMAC so truncation is detectable. Verify the chain from the web UI
or:

```sh
docker exec tethergate tethergate audit verify
docker exec tethergate tethergate audit search --node NODE --outcome denied
docker exec tethergate tethergate audit export --format csv > audit.csv
```

Prometheus metrics are available at `https://<server>:8787/metrics` when
`TETHER_METRICS_TOKEN` is set; send it as `Authorization: Bearer <token>`. Set
`TETHER_AUDIT_SINK_URL` to an HTTPS collector to stream each new audit entry to an
append-only external sink; delivery is asynchronous and never blocks execution.
`TETHER_AUDIT_SINK_TOKEN` adds a bearer token to sink requests. Audit payloads
include command output, so protect the collector like the local audit database.

Use `tethergate freeze on --reason "maintenance"` to stop every remote command,
bulk job, and file transfer. The freeze survives restarts and is shown in
`/healthz`, `status`, and the web UI.

## Common operations

```sh
# Health
curl -k "https://<server>:8787/healthz"

# Logs
docker compose logs -f tethergate

# Stop / start
docker compose down
docker compose up -d

# Rebuild after an upgrade
git pull
docker compose up -d --build
```

The server keeps state in the `tethergate-data` volume and sockets in
`tethergate-run`. `docker compose down -v` deletes the CA, node records, and audit
history; do not use it unless you intend a full reset.

## Development

```sh
python3 -m pytest -q
python3 -m ruff check tethergate tests
python3 -m compileall -q tethergate

cd opencode-plugin
node --check *.js
node --test
```

## Documentation

- [STARTUP.md](STARTUP.md) — copy-paste agent setup checklist
- [SECURITY.md](SECURITY.md) — trust boundaries and residual risks
- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) — components and protocol
- [docs/FLEET.md](docs/FLEET.md) — fleet deployment, backup, upgrades, renewal
- [docs/OPENCODE.md](docs/OPENCODE.md) — OpenCode integration details
- [docs/SESSION-RISK.md](docs/SESSION-RISK.md) — design idea for session risk telemetry (not implemented)
- [CHANGELOG.md](CHANGELOG.md) — release history
- [CONTRIBUTING.md](CONTRIBUTING.md) — development and contribution guide
- [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) — community standards
- [SUPPORT.md](SUPPORT.md) — where to ask for help
- [AGENTS.md](AGENTS.md) — guidance for AI-assisted contributions

## License

MIT. See [LICENSE](LICENSE).