anemones 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
anemones-0.1.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 wispsy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: anemones
3
+ Version: 0.1.1
4
+ Summary: First-party multi-mode remote access over serve-gateway.
5
+ Author: ellainng
6
+ Author-email: ellainng <299958882+ellainng@users.noreply.github.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Dist: serve-asgi>=1.0.0
10
+ Requires-Dist: serve-gateway>=1.0.0
11
+ Requires-Python: >=3.14
12
+ Project-URL: Repository, https://github.com/wispsy/anemones
13
+ Project-URL: Issues, https://github.com/wispsy/anemones/issues
14
+ Project-URL: Documentation, https://github.com/wispsy/anemones/tree/main/docs
15
+ Description-Content-Type: text/markdown
16
+
17
+ # anemones
18
+
19
+ [![CI](https://github.com/wispsy/anemones/actions/workflows/ci.yaml/badge.svg)](https://github.com/wispsy/anemones/actions/workflows/ci.yaml)
20
+ [![Python 3.14+](https://img.shields.io/badge/python-3.14%2B-blue.svg)](https://www.python.org/downloads/)
21
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
22
+ [![Zero Third-Party Deps](https://img.shields.io/badge/third--party%20deps-none-brightgreen.svg)](pyproject.toml)
23
+
24
+ First-party, self-hosted, peer-authenticated remote access and resource connectivity for Python, built on [serve-gateway](https://github.com/wispsy/serve-gateway) and [serve-asgi](https://github.com/wispsy/serve-asgi).
25
+
26
+ Requires Python >=3.14. Runtime dependencies are strictly first-party Wispsy packages (`serve-gateway`, `serve-asgi`) and Python's standard library / platform TLS (`ssl.SSLObject` + `MemoryBIO`), with **zero third-party runtime dependencies**.
27
+
28
+ ## Current Slice (v0.1.1)
29
+
30
+ - **First-party `SGW1` WebSocket client** (`anemones.gateway_client.SGW1Client`): RFC 6455 client requiring `wss://` by default (explicit `allow_insecure_ws=True` opt-in for plaintext dev `ws://`), negotiating `serve-gateway.v1.binary`.
31
+ - **Pre-TLS readiness & consumption-coupled carrier** (`anemones.tls_channel.PairedChannelCarrier`): paired directional channels (`anem.<session>.c2h`, `anem.<session>.h2c`), explicit `READY` synchronization before TLS handshake bytes, sequence verification, carrier credits replenished on consumption, and fail-closed teardown on overflow/timeout/disconnect.
32
+ - **Mutual TLS 1.3 with device fingerprint pinning** (`anemones.identity`, `anemones.tls_channel.TLSChannel`): `ssl.SSLObject` + `MemoryBIO` verifying pre-provisioned peer certificates via SHA-256 of DER `getpeercert(binary_form=True)`.
33
+ - **Host-authorized named TCP forward** (`anemones.stream`, `anemones.agent.HostAgent`, `anemones.client.ForwardListener`, `anemones.server.GatewayServer`): receive-window-enforced single-stream TCP forwarding over `serve-asgi` WSS with bounded half-close deadlines and both one-shot (`--once`) and persistent (`--persist`) CLI modes.
34
+
35
+ ## Install & Development
36
+
37
+ ```sh
38
+ python -m pip install anemones==0.1.1
39
+ ```
40
+
41
+ For source development:
42
+
43
+ ```sh
44
+ uv sync --locked
45
+ uv run --locked anemones --help
46
+ uv run --locked python -W error -m unittest discover -s tests -v
47
+ ```
48
+
49
+ ## Roadmap
50
+
51
+ - **0.1.x — Protocol hardening:** WSS default, consumption-coupled credits, receive-window validation, half-close deadlines, protected token inputs, WebSocket conformance.
52
+ - **0.2.0 — Persistent remote access:** Multi-stream multiplexing, concurrent local connections, heartbeats, reconnection handling.
53
+ - **0.3.0 — Device & resource management:** Persistent device registry, enrollment/rotation, revocation, named resource discovery, audit records.
54
+ - **0.4.0 — Multi-mode connectivity:** Direct connections, TURN relay fallback, WebRTC/ICE (`SignalingApp` + `TurnServer`), optional authorized SOCKS5.
55
+ - **0.5.0 — Native Wispsy integrations:** `clownfish` remote terminals, `hidden-moves` capability access, `serve-runner` supervision, `hypnosis` workers.
56
+ - **1.0.0 — Qualified platform:** Stable protocol specification, compatibility guarantees, independent security review, cross-platform benchmarks.
57
+
58
+ ## Documentation
59
+
60
+ - [Overview and Usage](docs/README.md)
61
+ - [Architecture and Security Boundaries](docs/architecture.md)
@@ -0,0 +1,45 @@
1
+ # anemones
2
+
3
+ [![CI](https://github.com/wispsy/anemones/actions/workflows/ci.yaml/badge.svg)](https://github.com/wispsy/anemones/actions/workflows/ci.yaml)
4
+ [![Python 3.14+](https://img.shields.io/badge/python-3.14%2B-blue.svg)](https://www.python.org/downloads/)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
6
+ [![Zero Third-Party Deps](https://img.shields.io/badge/third--party%20deps-none-brightgreen.svg)](pyproject.toml)
7
+
8
+ First-party, self-hosted, peer-authenticated remote access and resource connectivity for Python, built on [serve-gateway](https://github.com/wispsy/serve-gateway) and [serve-asgi](https://github.com/wispsy/serve-asgi).
9
+
10
+ Requires Python >=3.14. Runtime dependencies are strictly first-party Wispsy packages (`serve-gateway`, `serve-asgi`) and Python's standard library / platform TLS (`ssl.SSLObject` + `MemoryBIO`), with **zero third-party runtime dependencies**.
11
+
12
+ ## Current Slice (v0.1.1)
13
+
14
+ - **First-party `SGW1` WebSocket client** (`anemones.gateway_client.SGW1Client`): RFC 6455 client requiring `wss://` by default (explicit `allow_insecure_ws=True` opt-in for plaintext dev `ws://`), negotiating `serve-gateway.v1.binary`.
15
+ - **Pre-TLS readiness & consumption-coupled carrier** (`anemones.tls_channel.PairedChannelCarrier`): paired directional channels (`anem.<session>.c2h`, `anem.<session>.h2c`), explicit `READY` synchronization before TLS handshake bytes, sequence verification, carrier credits replenished on consumption, and fail-closed teardown on overflow/timeout/disconnect.
16
+ - **Mutual TLS 1.3 with device fingerprint pinning** (`anemones.identity`, `anemones.tls_channel.TLSChannel`): `ssl.SSLObject` + `MemoryBIO` verifying pre-provisioned peer certificates via SHA-256 of DER `getpeercert(binary_form=True)`.
17
+ - **Host-authorized named TCP forward** (`anemones.stream`, `anemones.agent.HostAgent`, `anemones.client.ForwardListener`, `anemones.server.GatewayServer`): receive-window-enforced single-stream TCP forwarding over `serve-asgi` WSS with bounded half-close deadlines and both one-shot (`--once`) and persistent (`--persist`) CLI modes.
18
+
19
+ ## Install & Development
20
+
21
+ ```sh
22
+ python -m pip install anemones==0.1.1
23
+ ```
24
+
25
+ For source development:
26
+
27
+ ```sh
28
+ uv sync --locked
29
+ uv run --locked anemones --help
30
+ uv run --locked python -W error -m unittest discover -s tests -v
31
+ ```
32
+
33
+ ## Roadmap
34
+
35
+ - **0.1.x — Protocol hardening:** WSS default, consumption-coupled credits, receive-window validation, half-close deadlines, protected token inputs, WebSocket conformance.
36
+ - **0.2.0 — Persistent remote access:** Multi-stream multiplexing, concurrent local connections, heartbeats, reconnection handling.
37
+ - **0.3.0 — Device & resource management:** Persistent device registry, enrollment/rotation, revocation, named resource discovery, audit records.
38
+ - **0.4.0 — Multi-mode connectivity:** Direct connections, TURN relay fallback, WebRTC/ICE (`SignalingApp` + `TurnServer`), optional authorized SOCKS5.
39
+ - **0.5.0 — Native Wispsy integrations:** `clownfish` remote terminals, `hidden-moves` capability access, `serve-runner` supervision, `hypnosis` workers.
40
+ - **1.0.0 — Qualified platform:** Stable protocol specification, compatibility guarantees, independent security review, cross-platform benchmarks.
41
+
42
+ ## Documentation
43
+
44
+ - [Overview and Usage](docs/README.md)
45
+ - [Architecture and Security Boundaries](docs/architecture.md)
@@ -0,0 +1,62 @@
1
+ # Anemones Documentation
2
+
3
+ Anemones layers peer-authenticated, end-to-end encrypted remote access on top of `serve-gateway` and `serve-asgi`.
4
+
5
+ ## CLI Quickstart
6
+
7
+ Compute a pre-provisioned device certificate fingerprint (`SHA-256` of DER):
8
+
9
+ ```sh
10
+ anemones fingerprint device.crt
11
+ ```
12
+
13
+ Create `0600` secret files instead of passing Bearer tokens directly in shell commands (or set `ANEMONES_GATEWAY_TOKEN` for `agent` and `forward`):
14
+
15
+ ```sh
16
+ install -m 600 /dev/null gateway-tokens.txt
17
+ printf 'token-host=host-a\ntoken-client=client-a\n' > gateway-tokens.txt
18
+
19
+ install -m 600 /dev/null host-token.txt
20
+ printf 'token-host\n' > host-token.txt
21
+
22
+ install -m 600 /dev/null client-token.txt
23
+ printf 'token-client\n' > client-token.txt
24
+ ```
25
+
26
+ Run the reference `serve-asgi` WSS gateway (requires `--cert` and `--key` unless `--allow-insecure-ws` is passed for local dev):
27
+
28
+ ```sh
29
+ anemones server \
30
+ --host 127.0.0.1 --port 8443 \
31
+ --cert server.crt --key server.key \
32
+ --tokens-file gateway-tokens.txt \
33
+ --session s1:client-a:host-a
34
+ ```
35
+
36
+ Run a host agent exporting a single named local TCP target (defaults to `--once`; pass `--persist` to keep serving sequential sessions):
37
+
38
+ ```sh
39
+ anemones agent \
40
+ --gateway wss://127.0.0.1:8443/ --gateway-ca server.crt \
41
+ --token-file host-token.txt --session s1 \
42
+ --cert host.crt --key host.key \
43
+ --client-id client-a --client-cert client.crt \
44
+ --export-name echo --target 127.0.0.1:9001 \
45
+ --persist
46
+ ```
47
+
48
+ Forward a local client port to that named export (`--once` exits after the connection finishes; pass `--persist` for sequential re-connections):
49
+
50
+ ```sh
51
+ anemones forward \
52
+ --gateway wss://127.0.0.1:8443/ --gateway-ca server.crt \
53
+ --token-file client-token.txt --session s1 \
54
+ --cert client.crt --key client.key \
55
+ --host-id host-a --host-cert host.crt \
56
+ --export-name echo --listen-port 19001 \
57
+ --once
58
+ ```
59
+
60
+ ## Further Reading
61
+
62
+ - [Architecture and Security Boundaries](architecture.md)
@@ -0,0 +1,37 @@
1
+ # Architecture & Security Boundaries
2
+
3
+ ## Layered Design
4
+
5
+ ```text
6
+ Local TCP Socket <--> ForwardListener / HostAgent (Named Export Grant)
7
+ │
8
+ FrameCodec + bridge_tcp_over_tls
9
+ (OPEN, OPEN_OK/ERR, DATA, CREDIT, CLOSE;
10
+ recv_window enforcement & half-close deadlines)
11
+ │
12
+ TLSChannel (TLS 1.3 mTLS via ssl.SSLObject + MemoryBIO)
13
+ │
14
+ PairedChannelCarrier
15
+ (READY barrier, seq, consumption-coupled credits)
16
+ │
17
+ SGW1Client (RFC 6455 WSS-by-default + serve-gateway.v1.binary)
18
+ │
19
+ GatewayServer (serve-asgi Server + serve-gateway.GatewayApp)
20
+ ```
21
+
22
+ ## Key Invariants
23
+
24
+ 1. **Three independent authorization checks:**
25
+ - *Gateway transport admission:* Bearer token in `authenticate(scope)` plus directional channel authorization (`c2h` vs `h2c`) in `GatewayApp.authorize`.
26
+ - *Peer mTLS identity:* TLS 1.3 `CERT_REQUIRED` verified against pre-provisioned peer certificates and pinned by SHA-256 of `getpeercert(binary_form=True)`.
27
+ - *Host export grant:* `HostPolicy.authorize_export(device_id, export_name)` resolves an explicit local `(host, port)` target only when `device_id` is granted `export_name`.
28
+
29
+ 2. **Transport security defaults:**
30
+ `SGW1Client.connect` and `anemones server` require TLS (`wss://` / `--cert` + `--key`) by default. Plaintext `ws://` requires an explicit `allow_insecure_ws=True` / `--allow-insecure-ws` development opt-in.
31
+
32
+ 3. **Pre-TLS readiness & fail-closed carrier:**
33
+ `GatewayApp` reports `published` with `overflow: false` even when no subscriber is attached yet. `PairedChannelCarrier.wait_ready()` confirms both subscriptions and exchanges `READY` beacons before feeding TLS handshake bytes. Any sequence gap, carrier overflow, uncredited frame overrun, pump error/timeout, or WebSocket disconnect fails closed and wakes all blocked readers and writers.
34
+
35
+ 4. **Two-level backpressure & half-close bounds:**
36
+ - *Carrier credits* are replenished only when `recv_tls()` actually consumes ciphertext from the bounded inbox (`window_frames = 6`), keeping `Gateway` queue pressure well below `queue_size = 16`.
37
+ - *Stream byte credits* (`CREDIT` frames) enforce both sender-side windows and receiver-side `recv_window` validation (`StreamProtocolError` on overrun), while `half_close_timeout` bounds half-closed TCP teardown.
@@ -0,0 +1,35 @@
1
+ [project]
2
+ name = "anemones"
3
+ version = "0.1.1"
4
+ description = "First-party multi-mode remote access over serve-gateway."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.14"
9
+ dependencies = [
10
+ "serve-asgi>=1.0.0",
11
+ "serve-gateway>=1.0.0",
12
+ ]
13
+
14
+ [[project.authors]]
15
+ name = "ellainng"
16
+ email = "299958882+ellainng@users.noreply.github.com"
17
+
18
+ [project.scripts]
19
+ anemones = "anemones:main"
20
+
21
+ [project.urls]
22
+ Repository = "https://github.com/wispsy/anemones"
23
+ Issues = "https://github.com/wispsy/anemones/issues"
24
+ Documentation = "https://github.com/wispsy/anemones/tree/main/docs"
25
+
26
+ [build-system]
27
+ requires = ["uv_build>=0.13.9,<0.14.0"]
28
+ build-backend = "uv_build"
29
+
30
+ [tool.uv.build-backend]
31
+ source-include = [
32
+ "tests/**",
33
+ "docs/**",
34
+ "scripts/**",
35
+ ]
@@ -0,0 +1,30 @@
1
+ [project]
2
+ name = "anemones"
3
+ version = "0.1.1"
4
+ description = "First-party multi-mode remote access over serve-gateway."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [
9
+ { name = "ellainng", email = "299958882+ellainng@users.noreply.github.com" },
10
+ ]
11
+ requires-python = ">=3.14"
12
+ dependencies = [
13
+ "serve-asgi>=1.0.0",
14
+ "serve-gateway>=1.0.0",
15
+ ]
16
+
17
+ [project.scripts]
18
+ anemones = "anemones:main"
19
+
20
+ [build-system]
21
+ requires = ["uv_build>=0.13.9,<0.14.0"]
22
+ build-backend = "uv_build"
23
+
24
+ [project.urls]
25
+ Repository = "https://github.com/wispsy/anemones"
26
+ Issues = "https://github.com/wispsy/anemones/issues"
27
+ Documentation = "https://github.com/wispsy/anemones/tree/main/docs"
28
+
29
+ [tool.uv.build-backend]
30
+ source-include = ["tests/**", "docs/**", "scripts/**"]
@@ -0,0 +1,71 @@
1
+ """Validate built distribution metadata, then exercise isolated wheel and source installs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import email
6
+ import os
7
+ from pathlib import Path
8
+ import subprocess
9
+ import sys
10
+ import tarfile
11
+ import tempfile
12
+ import tomllib
13
+ import zipfile
14
+
15
+ root = Path(__file__).resolve().parents[1]
16
+ project = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))["project"]
17
+ artifacts = sorted([*(root / "dist").glob("*.whl"), *(root / "dist").glob("*.tar.gz")])
18
+ assert len(artifacts) == 2, f"Expected exactly one wheel and one sdist, found {artifacts}"
19
+ assert sum(p.suffix == ".whl" for p in artifacts) == 1
20
+ assert sum(p.name.endswith(".tar.gz") for p in artifacts) == 1
21
+
22
+ for artifact in artifacts:
23
+ if artifact.suffix == ".whl":
24
+ with zipfile.ZipFile(artifact) as archive:
25
+ metadata = archive.read(next(n for n in archive.namelist() if n.endswith(".dist-info/METADATA")))
26
+ else:
27
+ with tarfile.open(artifact) as archive:
28
+ names = archive.getnames()
29
+ assert any(n.endswith("/LICENSE") for n in names)
30
+ assert any("/tests/" in n for n in names)
31
+ metadata = archive.extractfile(next(n for n in names if n.endswith("/PKG-INFO"))).read()
32
+
33
+ parsed = email.message_from_bytes(metadata)
34
+ assert parsed["Name"] == project["name"]
35
+ assert parsed["Version"] == project["version"]
36
+ assert parsed["Requires-Python"] == project["requires-python"]
37
+ assert parsed["License-Expression"] == "MIT"
38
+ requires = parsed.get_all("Requires-Dist") or []
39
+ assert any(r.startswith("serve-gateway") for r in requires), f"Missing serve-gateway in {requires}"
40
+ assert any(r.startswith("serve-asgi") for r in requires), f"Missing serve-asgi in {requires}"
41
+ assert parsed.get_payload().strip(), "Long description is empty"
42
+
43
+ with tempfile.TemporaryDirectory(prefix="anemones-installed-") as directory:
44
+ env = Path(directory) / "env"
45
+ python = env / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
46
+ subprocess.run(["uv", "venv", str(env), "--python", sys.executable], check=True)
47
+ subprocess.run(["uv", "pip", "install", "--python", str(python), str(artifact)], check=True)
48
+ subprocess.run(["uv", "pip", "check", "--python", str(python)], check=True)
49
+ subprocess.run([str(python), "-I", str(root / "scripts/smoke_installed.py")], cwd=directory, check=True)
50
+ subprocess.run(
51
+ [
52
+ str(python),
53
+ "-I",
54
+ "-W",
55
+ "error",
56
+ "-m",
57
+ "unittest",
58
+ "discover",
59
+ "-s",
60
+ str(root / "tests"),
61
+ "-p",
62
+ "test_*.py",
63
+ "-v",
64
+ ],
65
+ cwd=directory,
66
+ check=True,
67
+ env={k: v for k, v in os.environ.items() if k != "PYTHONPATH"},
68
+ )
69
+ executable = env / ("Scripts" if os.name == "nt" else "bin") / project["name"]
70
+ subprocess.run([str(executable), "--help"], cwd=directory, check=True, stdout=subprocess.DEVNULL)
71
+ print(f"Verified installed {artifact.name}", flush=True)
@@ -0,0 +1,12 @@
1
+ """Smoke test verifying an isolated installation of anemones."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import anemones
6
+
7
+ assert hasattr(anemones, "SGW1Client")
8
+ assert hasattr(anemones, "TLSChannel")
9
+ assert hasattr(anemones, "HostAgent")
10
+ assert hasattr(anemones, "ForwardListener")
11
+ assert hasattr(anemones, "GatewayServer")
12
+ print("anemones installed smoke OK")
@@ -0,0 +1,61 @@
1
+ """First-party multi-mode remote access over serve-gateway."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .agent import HostAgent
6
+ from .cli import main
7
+ from .client import ForwardListener, ForwardTunnel, open_forward_tunnel
8
+ from .gateway_client import (
9
+ GatewayClientError,
10
+ GatewayClosedError,
11
+ GatewayCommandError,
12
+ GatewayProtocolError,
13
+ SGW1Client,
14
+ SGWMessage,
15
+ )
16
+ from .identity import (
17
+ AuthenticationError,
18
+ ExportTarget,
19
+ HostPolicy,
20
+ PeerIdentity,
21
+ build_mtls_context,
22
+ cert_fingerprint,
23
+ load_cert_fingerprint,
24
+ pem_cert_fingerprint,
25
+ )
26
+ from .server import GatewayServer, GatewayServerConfig, SessionGrant, create_gateway_app
27
+ from .stream import ExportDeniedError, FrameCodec, StreamProtocolError, bridge_tcp_over_tls
28
+ from .tls_channel import CarrierError, PairedChannelCarrier, TLSChannel
29
+
30
+ __all__ = [
31
+ "AuthenticationError",
32
+ "CarrierError",
33
+ "ExportDeniedError",
34
+ "ExportTarget",
35
+ "ForwardListener",
36
+ "ForwardTunnel",
37
+ "FrameCodec",
38
+ "GatewayClientError",
39
+ "GatewayClosedError",
40
+ "GatewayCommandError",
41
+ "GatewayProtocolError",
42
+ "GatewayServer",
43
+ "GatewayServerConfig",
44
+ "HostAgent",
45
+ "HostPolicy",
46
+ "PairedChannelCarrier",
47
+ "PeerIdentity",
48
+ "SGW1Client",
49
+ "SGWMessage",
50
+ "SessionGrant",
51
+ "StreamProtocolError",
52
+ "TLSChannel",
53
+ "bridge_tcp_over_tls",
54
+ "build_mtls_context",
55
+ "cert_fingerprint",
56
+ "create_gateway_app",
57
+ "load_cert_fingerprint",
58
+ "main",
59
+ "open_forward_tunnel",
60
+ "pem_cert_fingerprint",
61
+ ]
@@ -0,0 +1,133 @@
1
+ """Host agent terminating mTLS gateway tunnels onto authorized local TCP exports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from collections.abc import Mapping
7
+ import ssl
8
+
9
+ from .gateway_client import GatewayClosedError, SGW1Client
10
+ from .identity import AuthenticationError, HostPolicy, PeerIdentity
11
+ from .stream import (
12
+ FRAME_OPEN,
13
+ FRAME_OPEN_ERR,
14
+ FRAME_OPEN_OK,
15
+ FrameCodec,
16
+ StreamProtocolError,
17
+ bridge_tcp_over_tls,
18
+ )
19
+ from .tls_channel import PairedChannelCarrier, TLSChannel
20
+
21
+
22
+ class HostAgent:
23
+ """Serves a single paired gateway session and bridges one authorized local TCP export."""
24
+
25
+ def __init__(
26
+ self,
27
+ *,
28
+ gateway_url: str,
29
+ gateway_token: str,
30
+ host_ssl_context: ssl.SSLContext,
31
+ trusted_clients: Mapping[str, PeerIdentity],
32
+ policy: HostPolicy,
33
+ gateway_ssl_context: ssl.SSLContext | None = None,
34
+ allow_insecure_ws: bool = False,
35
+ ) -> None:
36
+ self._gateway_url = gateway_url
37
+ self._gateway_token = gateway_token
38
+ self._host_ssl_context = host_ssl_context
39
+ self._trusted_clients = dict(trusted_clients)
40
+ self._policy = policy
41
+ self._gateway_ssl_context = gateway_ssl_context
42
+ self._allow_insecure_ws = allow_insecure_ws
43
+
44
+ async def serve_session(
45
+ self,
46
+ session_id: str,
47
+ *,
48
+ expected_client_id: str | None = None,
49
+ timeout: float = 10.0,
50
+ ) -> None:
51
+ """Connect to the gateway, authenticate client mTLS, authorize export, and bridge TCP."""
52
+ client = await SGW1Client.connect(
53
+ self._gateway_url,
54
+ ssl_context=self._gateway_ssl_context,
55
+ headers={"Authorization": f"Bearer {self._gateway_token}"},
56
+ connect_timeout=timeout,
57
+ allow_insecure_ws=self._allow_insecure_ws,
58
+ )
59
+ carrier = PairedChannelCarrier(
60
+ client,
61
+ send_channel=f"anem.{session_id}.h2c",
62
+ recv_channel=f"anem.{session_id}.c2h",
63
+ )
64
+ tls = TLSChannel(carrier, self._host_ssl_context, server_side=True)
65
+ tcp_writer: asyncio.StreamWriter | None = None
66
+ try:
67
+ peer = await tls.handshake(
68
+ self._trusted_clients,
69
+ expected_device_id=expected_client_id,
70
+ timeout=timeout,
71
+ )
72
+ codec = FrameCodec(tls)
73
+ frame_type, payload = await codec.recv_frame(timeout=timeout)
74
+ if frame_type != FRAME_OPEN:
75
+ raise StreamProtocolError("expected OPEN frame")
76
+ try:
77
+ export_name = payload.decode("utf-8")
78
+ except UnicodeDecodeError as exc:
79
+ raise StreamProtocolError("invalid export name encoding") from exc
80
+
81
+ target = self._policy.authorize_export(peer.device_id, export_name)
82
+ if target is None:
83
+ await codec.send_frame(FRAME_OPEN_ERR, b"forbidden", timeout=timeout)
84
+ return
85
+
86
+ try:
87
+ async with asyncio.timeout(timeout):
88
+ tcp_reader, tcp_writer = await asyncio.open_connection(target.host, target.port)
89
+ except (OSError, TimeoutError):
90
+ await codec.send_frame(FRAME_OPEN_ERR, b"connect_failed", timeout=timeout)
91
+ return
92
+
93
+ await codec.send_frame(FRAME_OPEN_OK, timeout=timeout)
94
+ await bridge_tcp_over_tls(codec, tcp_reader, tcp_writer)
95
+ finally:
96
+ if tcp_writer is not None and not tcp_writer.is_closing():
97
+ tcp_writer.close()
98
+ try:
99
+ async with asyncio.timeout(1.0):
100
+ await tcp_writer.wait_closed()
101
+ except (OSError, TimeoutError):
102
+ pass
103
+ await tls.close(notify_peer=True)
104
+ await client.close()
105
+
106
+ async def serve_forever(
107
+ self,
108
+ session_id: str,
109
+ *,
110
+ expected_client_id: str | None = None,
111
+ timeout: float = 10.0,
112
+ stop_event: asyncio.Event | None = None,
113
+ retry_delay: float = 0.05,
114
+ ) -> None:
115
+ """Repeatedly serve sequential sessions until stop_event is set or cancelled."""
116
+ while stop_event is None or not stop_event.is_set():
117
+ try:
118
+ await self.serve_session(
119
+ session_id,
120
+ expected_client_id=expected_client_id,
121
+ timeout=timeout,
122
+ )
123
+ except (
124
+ OSError,
125
+ EOFError,
126
+ TimeoutError,
127
+ ssl.SSLError,
128
+ AuthenticationError,
129
+ GatewayClosedError,
130
+ ):
131
+ if stop_event is not None and stop_event.is_set():
132
+ break
133
+ await asyncio.sleep(retry_delay)