flowstatemcp 2.5.0__py3-none-any.whl
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.
- flowstate/__init__.py +34 -0
- flowstate/__main__.py +7 -0
- flowstate/activity.py +224 -0
- flowstate/agent_guide.py +251 -0
- flowstate/app_keys.py +141 -0
- flowstate/approvals.py +974 -0
- flowstate/approve_page.py +565 -0
- flowstate/ask.py +107 -0
- flowstate/autosession.py +480 -0
- flowstate/backup.py +201 -0
- flowstate/brief.py +420 -0
- flowstate/card_offer.py +208 -0
- flowstate/card_taps.py +165 -0
- flowstate/card_trust.py +127 -0
- flowstate/claims.py +461 -0
- flowstate/cleanup.py +619 -0
- flowstate/cli.py +728 -0
- flowstate/cli_data.py +434 -0
- flowstate/cli_more.py +302 -0
- flowstate/cli_review.py +459 -0
- flowstate/cloudflared_check.py +49 -0
- flowstate/conflict_card_ui.py +286 -0
- flowstate/conflict_cards.py +1193 -0
- flowstate/conflict_reopen.py +320 -0
- flowstate/conflicts.py +420 -0
- flowstate/connections.py +33 -0
- flowstate/database.py +2191 -0
- flowstate/dbconn.py +308 -0
- flowstate/deletes.py +860 -0
- flowstate/embeddings.py +354 -0
- flowstate/erase.py +1047 -0
- flowstate/extras.py +71 -0
- flowstate/git_capture.py +157 -0
- flowstate/guard.py +224 -0
- flowstate/handoffs.py +168 -0
- flowstate/history.py +755 -0
- flowstate/history_page.py +276 -0
- flowstate/http_app.py +204 -0
- flowstate/identity.py +387 -0
- flowstate/install_name.py +140 -0
- flowstate/ledger.py +272 -0
- flowstate/legacy_args.py +65 -0
- flowstate/links.py +609 -0
- flowstate/markdown_io.py +242 -0
- flowstate/meaning.py +398 -0
- flowstate/memory_import.py +92 -0
- flowstate/migrations/001_auto_sessions.sql +16 -0
- flowstate/migrations/002_review_queue.sql +33 -0
- flowstate/migrations/003_links.sql +47 -0
- flowstate/migrations/004_review_mode.sql +24 -0
- flowstate/migrations/005_history.sql +21 -0
- flowstate/migrations/006_activity.sql +26 -0
- flowstate/migrations/007_meaning_index.sql +16 -0
- flowstate/migrations/008_git_capture.sql +12 -0
- flowstate/migrations/009_hard_rules.sql +13 -0
- flowstate/migrations/010_handoffs.sql +14 -0
- flowstate/migrations/011_record_meta.sql +13 -0
- flowstate/migrations/012_accountability.sql +71 -0
- flowstate/migrations/013_todo_claims.sql +36 -0
- flowstate/migrations/014_decision_conflicts.sql +41 -0
- flowstate/migrations/015_session_runs.sql +17 -0
- flowstate/migrations/016_write_receipts.sql +35 -0
- flowstate/migrations/017_run_views.sql +26 -0
- flowstate/migrations/018_run_views_upto.sql +4 -0
- flowstate/migrations/019_approvals.sql +47 -0
- flowstate/migrations/020_source_stamps.sql +10 -0
- flowstate/migrations/021_review_links.sql +11 -0
- flowstate/migrations/022_review_start_tickets.sql +10 -0
- flowstate/migrations/023_conflict_cards.sql +68 -0
- flowstate/migrations/024_rule_confirmations.sql +7 -0
- flowstate/migrations/025_confirmed_hash.sql +7 -0
- flowstate/migrations/__init__.py +149 -0
- flowstate/models.py +307 -0
- flowstate/names.py +157 -0
- flowstate/offsite.py +386 -0
- flowstate/offsite_crypto.py +272 -0
- flowstate/paths.py +265 -0
- flowstate/popup.py +238 -0
- flowstate/priority.py +66 -0
- flowstate/privatefs.py +476 -0
- flowstate/project_history.py +710 -0
- flowstate/provenance.py +696 -0
- flowstate/receipts.py +377 -0
- flowstate/relay/__init__.py +72 -0
- flowstate/relay/acme.py +271 -0
- flowstate/relay/api.py +164 -0
- flowstate/relay/cli.py +344 -0
- flowstate/relay/crypto.py +137 -0
- flowstate/relay/ct.py +118 -0
- flowstate/relay/runner.py +177 -0
- flowstate/relay/store.py +191 -0
- flowstate/relay/tunnel.py +413 -0
- flowstate/release_signers +14 -0
- flowstate/remote_auth.py +1219 -0
- flowstate/review.py +320 -0
- flowstate/review_apply.py +140 -0
- flowstate/review_card_ui.py +241 -0
- flowstate/review_cards.py +564 -0
- flowstate/review_mode.py +274 -0
- flowstate/review_page.py +1361 -0
- flowstate/review_phone.py +465 -0
- flowstate/review_tunnel.py +338 -0
- flowstate/routing.py +392 -0
- flowstate/rules.py +418 -0
- flowstate/safety.py +98 -0
- flowstate/saves.py +83 -0
- flowstate/scheduler.py +160 -0
- flowstate/schema.sql +713 -0
- flowstate/search.py +355 -0
- flowstate/secret_store.py +271 -0
- flowstate/secrets_scan.py +135 -0
- flowstate/selfupdate.py +1020 -0
- flowstate/server.py +1299 -0
- flowstate/session_contents.py +382 -0
- flowstate/session_records.py +629 -0
- flowstate/site_style.py +46 -0
- flowstate/stored.py +158 -0
- flowstate/story.py +442 -0
- flowstate/surface.py +173 -0
- flowstate/tasks.py +231 -0
- flowstate/term.py +40 -0
- flowstate/tool_labels.py +104 -0
- flowstate/tooldefs.py +383 -0
- flowstate/tools/__init__.py +118 -0
- flowstate/tools/core.py +545 -0
- flowstate/tools/files.py +416 -0
- flowstate/tools/git_ops.py +1081 -0
- flowstate/tools/intelligence.py +376 -0
- flowstate/tools/learning.py +282 -0
- flowstate/tools/problems.py +159 -0
- flowstate/tools/sessions.py +266 -0
- flowstate/tools/story.py +48 -0
- flowstate/tools/todos.py +79 -0
- flowstate/tools/utils.py +71 -0
- flowstate/tools/variables.py +345 -0
- flowstate/updates.py +482 -0
- flowstate/urls.py +7 -0
- flowstate/waiting.py +828 -0
- flowstate/who.py +302 -0
- flowstatemcp-2.5.0.dist-info/METADATA +88 -0
- flowstatemcp-2.5.0.dist-info/RECORD +143 -0
- flowstatemcp-2.5.0.dist-info/WHEEL +4 -0
- flowstatemcp-2.5.0.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
"""The tunnel: outbound connections from this computer to the relay.
|
|
2
|
+
|
|
3
|
+
Control connection: TLS to tunnel.fsmcp.com:443 (the relay's own certificate,
|
|
4
|
+
verified normally), one JSON object per line: hello -> welcome, ping/pong heartbeats, and
|
|
5
|
+
`open` when a client connects to <handle>.fsmcp.com. Reconnects with
|
|
6
|
+
exponential backoff and jitter.
|
|
7
|
+
|
|
8
|
+
Data connection (one per client connection): a new TLS connection to the same tunnel
|
|
9
|
+
endpoint, one `attach` line naming the stream, then raw bytes. The relay splices the
|
|
10
|
+
client's TCP bytes into it unchanged (starting with the client's TLS ClientHello). This
|
|
11
|
+
agent then runs the TLS handshake as the SERVER, with the user's own certificate and key, in
|
|
12
|
+
memory (ssl.MemoryBIO), and passes the decrypted HTTP to FlowState's normal public-mode
|
|
13
|
+
HTTP listener on 127.0.0.1. The relay only ever carries ciphertext.
|
|
14
|
+
|
|
15
|
+
Exact wire format: docs/relay-protocol.md.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import asyncio
|
|
19
|
+
import contextlib
|
|
20
|
+
import ipaddress
|
|
21
|
+
import json
|
|
22
|
+
import logging
|
|
23
|
+
import random
|
|
24
|
+
import re
|
|
25
|
+
import ssl
|
|
26
|
+
import time
|
|
27
|
+
from typing import Callable, Optional
|
|
28
|
+
|
|
29
|
+
from . import PROTOCOL, RelayError
|
|
30
|
+
from .api import AGENT
|
|
31
|
+
|
|
32
|
+
log = logging.getLogger("flowstate.relay.tunnel")
|
|
33
|
+
|
|
34
|
+
MAX_LINE = 64 * 1024
|
|
35
|
+
STREAM_RE = re.compile(r"^[A-Za-z0-9_-]{16,128}$")
|
|
36
|
+
CONNECT_TIMEOUT = 15.0
|
|
37
|
+
HANDSHAKE_TIMEOUT = 20.0
|
|
38
|
+
MAX_STREAMS = 64
|
|
39
|
+
CHUNK = 64 * 1024
|
|
40
|
+
DEFAULT_HEARTBEAT = 25.0
|
|
41
|
+
UNAUTHORIZED = {"unauthorized", "revoked", "unknown_device"}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ProtocolError(RelayError):
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class AuthRejected(RelayError):
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def encode(msg: dict) -> bytes:
|
|
53
|
+
return json.dumps(msg, separators=(",", ":")).encode() + b"\n"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def read_msg(reader: asyncio.StreamReader, timeout: Optional[float]) -> dict:
|
|
57
|
+
try:
|
|
58
|
+
line = await asyncio.wait_for(reader.readuntil(b"\n"), timeout)
|
|
59
|
+
except asyncio.LimitOverrunError:
|
|
60
|
+
raise ProtocolError("control line longer than 64 KiB") from None
|
|
61
|
+
except asyncio.IncompleteReadError:
|
|
62
|
+
raise ConnectionError("relay closed the connection") from None
|
|
63
|
+
except asyncio.TimeoutError:
|
|
64
|
+
raise ConnectionError(f"nothing from the relay for {timeout:.0f}s") from None
|
|
65
|
+
try:
|
|
66
|
+
msg = json.loads(line)
|
|
67
|
+
except ValueError:
|
|
68
|
+
raise ProtocolError("control line is not JSON") from None
|
|
69
|
+
if not isinstance(msg, dict) or not isinstance(msg.get("type"), str):
|
|
70
|
+
raise ProtocolError("control message without a type")
|
|
71
|
+
return msg
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class Backoff:
|
|
75
|
+
"""Exponential backoff with equal jitter: attempt n waits between d/2 and d, where
|
|
76
|
+
d = min(cap, base * 2**n)."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, base: float = 1.0, cap: float = 60.0, rand: Callable[[], float] = random.random):
|
|
79
|
+
self.base, self.cap, self.rand, self.attempt = base, cap, rand, 0
|
|
80
|
+
|
|
81
|
+
def next(self) -> float:
|
|
82
|
+
d = min(self.cap, self.base * (2 ** self.attempt))
|
|
83
|
+
self.attempt = min(self.attempt + 1, 32)
|
|
84
|
+
return d / 2 + self.rand() * d / 2
|
|
85
|
+
|
|
86
|
+
def reset(self) -> None:
|
|
87
|
+
self.attempt = 0
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def server_context(cert_file, key_file) -> ssl.SSLContext:
|
|
91
|
+
"""TLS server context with the user's own certificate and key (HTTP/1.1 only)."""
|
|
92
|
+
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
93
|
+
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
94
|
+
ctx.load_cert_chain(str(cert_file), str(key_file))
|
|
95
|
+
ctx.set_alpn_protocols(["http/1.1"])
|
|
96
|
+
ctx.options |= getattr(ssl, "OP_NO_RENEGOTIATION", 0)
|
|
97
|
+
return ctx
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def client_ip(addr: str) -> str:
|
|
101
|
+
"""'203.0.113.5:4431' / '[2001:db8::1]:4431' -> the IP; anything else -> 'relay-unknown'."""
|
|
102
|
+
host = addr.rsplit(":", 1)[0] if addr.count(":") == 1 or addr.startswith("[") else addr
|
|
103
|
+
host = host.strip("[]")
|
|
104
|
+
try:
|
|
105
|
+
return str(ipaddress.ip_address(host))
|
|
106
|
+
except ValueError:
|
|
107
|
+
return "relay-unknown"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class _ServerTLS:
|
|
111
|
+
"""Server-side TLS over a byte pipe, entirely in memory."""
|
|
112
|
+
|
|
113
|
+
def __init__(self, ctx: ssl.SSLContext):
|
|
114
|
+
self.inc, self.out = ssl.MemoryBIO(), ssl.MemoryBIO()
|
|
115
|
+
self.obj = ctx.wrap_bio(self.inc, self.out, server_side=True)
|
|
116
|
+
self.closed = False
|
|
117
|
+
|
|
118
|
+
def flush(self, w: asyncio.StreamWriter) -> None:
|
|
119
|
+
data = self.out.read()
|
|
120
|
+
if data:
|
|
121
|
+
w.write(data)
|
|
122
|
+
|
|
123
|
+
async def handshake(self, r: asyncio.StreamReader, w: asyncio.StreamWriter) -> None:
|
|
124
|
+
while True:
|
|
125
|
+
try:
|
|
126
|
+
self.obj.do_handshake()
|
|
127
|
+
break
|
|
128
|
+
except ssl.SSLWantReadError:
|
|
129
|
+
self.flush(w)
|
|
130
|
+
await w.drain()
|
|
131
|
+
data = await r.read(CHUNK)
|
|
132
|
+
if not data:
|
|
133
|
+
raise EOFError("client went away during the TLS handshake")
|
|
134
|
+
self.inc.write(data)
|
|
135
|
+
self.flush(w)
|
|
136
|
+
await w.drain()
|
|
137
|
+
|
|
138
|
+
def feed(self, data: bytes) -> bytes:
|
|
139
|
+
self.inc.write(data)
|
|
140
|
+
parts = []
|
|
141
|
+
while True:
|
|
142
|
+
try:
|
|
143
|
+
chunk = self.obj.read(CHUNK)
|
|
144
|
+
except ssl.SSLWantReadError:
|
|
145
|
+
break
|
|
146
|
+
except ssl.SSLZeroReturnError:
|
|
147
|
+
self.closed = True
|
|
148
|
+
break
|
|
149
|
+
if not chunk:
|
|
150
|
+
self.closed = True
|
|
151
|
+
break
|
|
152
|
+
parts.append(chunk)
|
|
153
|
+
return b"".join(parts)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _display_name() -> Optional[str]:
|
|
157
|
+
"""The name the user set for this FlowState, or None (never the default "Main FlowState")."""
|
|
158
|
+
from ..install_name import shared
|
|
159
|
+
return shared()
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
_NAME_UNREADABLE = object() # config.json couldn't be read: leave the relay's copy alone
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class TunnelAgent:
|
|
166
|
+
def __init__(self, *, host: str, port: int, sni: str, token: str, handle: str,
|
|
167
|
+
client_ctx: ssl.SSLContext,
|
|
168
|
+
server_ctx: Callable[[], Optional[ssl.SSLContext]],
|
|
169
|
+
local_port: Callable[[], Optional[int]], peer_map: dict,
|
|
170
|
+
on_state: Optional[Callable[[str, str], None]] = None,
|
|
171
|
+
heartbeat: float = DEFAULT_HEARTBEAT, min_heartbeat: float = 5.0,
|
|
172
|
+
backoff: Optional[Backoff] = None, stable_after: float = 30.0,
|
|
173
|
+
display_name: Optional[Callable[[], Optional[str]]] = None):
|
|
174
|
+
self.host, self.port, self.sni = host, port, sni
|
|
175
|
+
# this FlowState's display name (install_name.py), only once the user set one: sent in
|
|
176
|
+
# the hello and again in a "name" message when it changes; null when there is none (so
|
|
177
|
+
# a reset clears the relay's copy). A relay that doesn't know "name" ignores both.
|
|
178
|
+
self.display_name = display_name or _display_name
|
|
179
|
+
self._sent_name = _NAME_UNREADABLE
|
|
180
|
+
self.token, self.handle = token, handle
|
|
181
|
+
self.client_ctx, self.server_ctx, self.local_port = client_ctx, server_ctx, local_port
|
|
182
|
+
self.peer_map, self.on_state = peer_map, on_state
|
|
183
|
+
self.heartbeat, self.min_heartbeat = heartbeat, min_heartbeat
|
|
184
|
+
self.backoff = backoff or Backoff()
|
|
185
|
+
self.stable_after = stable_after
|
|
186
|
+
self.state, self.detail, self.connects = "stopped", "", 0
|
|
187
|
+
self.delays: list = [] # backoff delays used (for status and tests)
|
|
188
|
+
self._welcomed_at: Optional[float] = None
|
|
189
|
+
self._streams: set = set()
|
|
190
|
+
|
|
191
|
+
# ------------------------------------------------------------ state
|
|
192
|
+
def _set(self, state: str, detail: str = "") -> None:
|
|
193
|
+
self.state, self.detail = state, detail
|
|
194
|
+
if self.on_state:
|
|
195
|
+
try:
|
|
196
|
+
self.on_state(state, detail)
|
|
197
|
+
except Exception as e: # noqa: BLE001 - status writing must not kill the tunnel
|
|
198
|
+
log.warning("could not record tunnel state: %s", e)
|
|
199
|
+
|
|
200
|
+
async def _open(self):
|
|
201
|
+
return await asyncio.wait_for(
|
|
202
|
+
asyncio.open_connection(self.host, self.port, ssl=self.client_ctx,
|
|
203
|
+
server_hostname=self.sni, limit=MAX_LINE,
|
|
204
|
+
ssl_handshake_timeout=CONNECT_TIMEOUT),
|
|
205
|
+
CONNECT_TIMEOUT + 5)
|
|
206
|
+
|
|
207
|
+
# ------------------------------------------------------------ control connection
|
|
208
|
+
async def run(self, stop: asyncio.Event) -> None:
|
|
209
|
+
"""Keep a control connection up until `stop` is set or the relay rejects the token."""
|
|
210
|
+
try:
|
|
211
|
+
while not stop.is_set():
|
|
212
|
+
self._set("connecting", f"{self.sni}:{self.port}")
|
|
213
|
+
err = None
|
|
214
|
+
try:
|
|
215
|
+
await self._control(stop)
|
|
216
|
+
except AuthRejected as e:
|
|
217
|
+
log.error("relay rejected this device (%s); run `flowstate relay forget` and "
|
|
218
|
+
"enroll again", e)
|
|
219
|
+
self._set("unauthorized", str(e))
|
|
220
|
+
return
|
|
221
|
+
except (OSError, ssl.SSLError, RelayError, EOFError) as e:
|
|
222
|
+
err = f"{type(e).__name__}: {e}"[:200]
|
|
223
|
+
if stop.is_set():
|
|
224
|
+
break
|
|
225
|
+
if self._welcomed_at and time.monotonic() - self._welcomed_at >= self.stable_after:
|
|
226
|
+
self.backoff.reset()
|
|
227
|
+
delay = self.backoff.next()
|
|
228
|
+
self.delays.append(delay)
|
|
229
|
+
log.info("tunnel down (%s); reconnecting in %.1fs", err or "closed by relay", delay)
|
|
230
|
+
self._set("reconnecting", f"in {delay:.1f}s" + (f" after {err}" if err else ""))
|
|
231
|
+
with contextlib.suppress(asyncio.TimeoutError):
|
|
232
|
+
await asyncio.wait_for(stop.wait(), delay)
|
|
233
|
+
self._set("stopped")
|
|
234
|
+
finally:
|
|
235
|
+
await self.close_streams()
|
|
236
|
+
|
|
237
|
+
@staticmethod
|
|
238
|
+
def _check_error(msg: dict) -> None:
|
|
239
|
+
if msg.get("type") == "error":
|
|
240
|
+
code = str(msg.get("code", "error"))[:40]
|
|
241
|
+
if code in UNAUTHORIZED:
|
|
242
|
+
raise AuthRejected(code)
|
|
243
|
+
raise ProtocolError(f"relay error: {code}")
|
|
244
|
+
|
|
245
|
+
async def _control(self, stop: asyncio.Event) -> None:
|
|
246
|
+
self._welcomed_at = None
|
|
247
|
+
reader, writer = await self._open()
|
|
248
|
+
self.connects += 1
|
|
249
|
+
stop_wait = asyncio.ensure_future(stop.wait())
|
|
250
|
+
pinger = None
|
|
251
|
+
try:
|
|
252
|
+
hello = {"type": "hello", "v": 1, "role": "control", "proto": PROTOCOL,
|
|
253
|
+
"handle": self.handle, "token": self.token, "agent": AGENT}
|
|
254
|
+
name = self._name()
|
|
255
|
+
if name is not _NAME_UNREADABLE:
|
|
256
|
+
hello["name"] = name # None (JSON null): no name set, the relay clears its copy
|
|
257
|
+
self._sent_name = name
|
|
258
|
+
writer.write(encode(hello))
|
|
259
|
+
await writer.drain()
|
|
260
|
+
msg = await read_msg(reader, CONNECT_TIMEOUT)
|
|
261
|
+
self._check_error(msg)
|
|
262
|
+
if msg["type"] != "welcome":
|
|
263
|
+
raise ProtocolError(f"expected welcome, got {msg['type'][:20]}")
|
|
264
|
+
try:
|
|
265
|
+
hb = float(msg.get("heartbeat", self.heartbeat))
|
|
266
|
+
except (TypeError, ValueError):
|
|
267
|
+
hb = self.heartbeat
|
|
268
|
+
hb = min(max(hb, self.min_heartbeat), 120.0)
|
|
269
|
+
self._welcomed_at = time.monotonic()
|
|
270
|
+
log.info("tunnel connected as %s (heartbeat %.0fs)", self.handle, hb)
|
|
271
|
+
self._set("connected", f"heartbeat {hb:.0f}s")
|
|
272
|
+
pinger = asyncio.create_task(self._pinger(writer, hb))
|
|
273
|
+
while True:
|
|
274
|
+
read = asyncio.ensure_future(read_msg(reader, hb * 3))
|
|
275
|
+
done, _ = await asyncio.wait({read, stop_wait}, return_when=asyncio.FIRST_COMPLETED)
|
|
276
|
+
if read not in done:
|
|
277
|
+
read.cancel()
|
|
278
|
+
with contextlib.suppress(Exception):
|
|
279
|
+
writer.write(encode({"type": "bye"}))
|
|
280
|
+
await asyncio.wait_for(writer.drain(), 2)
|
|
281
|
+
return
|
|
282
|
+
msg = read.result()
|
|
283
|
+
t = msg["type"]
|
|
284
|
+
if t == "ping":
|
|
285
|
+
writer.write(encode({"type": "pong", "seq": msg.get("seq")}))
|
|
286
|
+
elif t == "open":
|
|
287
|
+
self._on_open(msg, writer)
|
|
288
|
+
elif t in ("goaway", "bye"):
|
|
289
|
+
return
|
|
290
|
+
elif t == "error":
|
|
291
|
+
self._check_error(msg)
|
|
292
|
+
# "pong" and unknown types: nothing to do (forward compatible)
|
|
293
|
+
finally:
|
|
294
|
+
stop_wait.cancel()
|
|
295
|
+
if pinger:
|
|
296
|
+
pinger.cancel()
|
|
297
|
+
writer.close()
|
|
298
|
+
with contextlib.suppress(Exception):
|
|
299
|
+
await asyncio.wait_for(writer.wait_closed(), 2)
|
|
300
|
+
|
|
301
|
+
async def _pinger(self, writer: asyncio.StreamWriter, hb: float) -> None:
|
|
302
|
+
seq = 0
|
|
303
|
+
with contextlib.suppress(OSError, ConnectionError):
|
|
304
|
+
while True:
|
|
305
|
+
await asyncio.sleep(hb)
|
|
306
|
+
seq += 1
|
|
307
|
+
name = self._name()
|
|
308
|
+
if name is not _NAME_UNREADABLE and name != self._sent_name: # renamed or reset
|
|
309
|
+
writer.write(encode({"type": "name", "name": name}))
|
|
310
|
+
self._sent_name = name
|
|
311
|
+
writer.write(encode({"type": "ping", "seq": seq}))
|
|
312
|
+
await writer.drain()
|
|
313
|
+
|
|
314
|
+
def _name(self):
|
|
315
|
+
"""The set name, None (none set), or _NAME_UNREADABLE."""
|
|
316
|
+
try:
|
|
317
|
+
name = self.display_name()
|
|
318
|
+
except Exception: # noqa: BLE001 - a name problem must not kill the tunnel
|
|
319
|
+
return _NAME_UNREADABLE
|
|
320
|
+
return name if name is None or isinstance(name, str) else _NAME_UNREADABLE
|
|
321
|
+
|
|
322
|
+
# ------------------------------------------------------------ data connections
|
|
323
|
+
def _on_open(self, msg: dict, ctrl: asyncio.StreamWriter) -> None:
|
|
324
|
+
sid = msg.get("stream")
|
|
325
|
+
if not isinstance(sid, str) or not STREAM_RE.match(sid):
|
|
326
|
+
log.warning("relay sent an open with an invalid stream id; ignored")
|
|
327
|
+
return
|
|
328
|
+
reason = None
|
|
329
|
+
if len(self._streams) >= MAX_STREAMS:
|
|
330
|
+
reason = "busy"
|
|
331
|
+
elif self.server_ctx() is None:
|
|
332
|
+
reason = "no_certificate"
|
|
333
|
+
elif not self.local_port():
|
|
334
|
+
reason = "not_ready"
|
|
335
|
+
if reason:
|
|
336
|
+
ctrl.write(encode({"type": "reject", "stream": sid, "reason": reason}))
|
|
337
|
+
return
|
|
338
|
+
t = asyncio.create_task(self._stream(sid, str(msg.get("client") or "")))
|
|
339
|
+
self._streams.add(t)
|
|
340
|
+
t.add_done_callback(self._streams.discard)
|
|
341
|
+
|
|
342
|
+
async def close_streams(self) -> None:
|
|
343
|
+
for t in list(self._streams):
|
|
344
|
+
t.cancel()
|
|
345
|
+
if self._streams:
|
|
346
|
+
await asyncio.gather(*self._streams, return_exceptions=True)
|
|
347
|
+
|
|
348
|
+
async def _stream(self, sid: str, client: str) -> None:
|
|
349
|
+
ctx, port = self.server_ctx(), self.local_port()
|
|
350
|
+
w = lw = None
|
|
351
|
+
key = None
|
|
352
|
+
try:
|
|
353
|
+
r, w = await self._open()
|
|
354
|
+
w.write(encode({"type": "attach", "v": 1, "stream": sid, "token": self.token}))
|
|
355
|
+
await w.drain()
|
|
356
|
+
# From here on the pipe carries the client's own TLS bytes.
|
|
357
|
+
tls = _ServerTLS(ctx)
|
|
358
|
+
await asyncio.wait_for(tls.handshake(r, w), HANDSHAKE_TIMEOUT)
|
|
359
|
+
lr, lw = await asyncio.wait_for(asyncio.open_connection("127.0.0.1", port), CONNECT_TIMEOUT)
|
|
360
|
+
key = lw.get_extra_info("sockname")[1]
|
|
361
|
+
self.peer_map[key] = client_ip(client)
|
|
362
|
+
# the client's first request often arrives with its handshake Finished message
|
|
363
|
+
early = tls.feed(b"")
|
|
364
|
+
tls.flush(w)
|
|
365
|
+
if early:
|
|
366
|
+
lw.write(early)
|
|
367
|
+
up = asyncio.create_task(self._up(tls, r, w, lw))
|
|
368
|
+
down = asyncio.create_task(self._down(tls, lr, w))
|
|
369
|
+
done, pending = await asyncio.wait({up, down}, return_when=asyncio.FIRST_COMPLETED)
|
|
370
|
+
for p in pending:
|
|
371
|
+
p.cancel()
|
|
372
|
+
await asyncio.gather(*pending, return_exceptions=True)
|
|
373
|
+
for d in done:
|
|
374
|
+
if d.exception():
|
|
375
|
+
log.debug("stream %s: %s", sid[:8], d.exception())
|
|
376
|
+
except (OSError, ssl.SSLError, RelayError, EOFError, asyncio.TimeoutError) as e:
|
|
377
|
+
log.info("stream %s ended: %s", sid[:8], type(e).__name__)
|
|
378
|
+
finally:
|
|
379
|
+
if key is not None:
|
|
380
|
+
self.peer_map.pop(key, None)
|
|
381
|
+
for x in (lw, w):
|
|
382
|
+
if x is not None:
|
|
383
|
+
x.close()
|
|
384
|
+
|
|
385
|
+
@staticmethod
|
|
386
|
+
async def _up(tls: _ServerTLS, r, w, lw) -> None:
|
|
387
|
+
"""client (via relay) -> decrypt -> local FlowState listener"""
|
|
388
|
+
while True:
|
|
389
|
+
data = await r.read(CHUNK)
|
|
390
|
+
if not data:
|
|
391
|
+
return
|
|
392
|
+
plain = tls.feed(data)
|
|
393
|
+
tls.flush(w)
|
|
394
|
+
if plain:
|
|
395
|
+
lw.write(plain)
|
|
396
|
+
await lw.drain()
|
|
397
|
+
if tls.closed:
|
|
398
|
+
return
|
|
399
|
+
|
|
400
|
+
@staticmethod
|
|
401
|
+
async def _down(tls: _ServerTLS, lr, w) -> None:
|
|
402
|
+
"""local FlowState listener -> encrypt -> client (via relay)"""
|
|
403
|
+
while True:
|
|
404
|
+
data = await lr.read(CHUNK)
|
|
405
|
+
if not data:
|
|
406
|
+
with contextlib.suppress(ssl.SSLError):
|
|
407
|
+
tls.obj.unwrap() # queue close_notify
|
|
408
|
+
tls.flush(w)
|
|
409
|
+
await w.drain()
|
|
410
|
+
return
|
|
411
|
+
tls.obj.write(data)
|
|
412
|
+
tls.flush(w)
|
|
413
|
+
await w.drain()
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# FlowState release signing keys (SSH allowed-signers format, read by `git verify-tag`).
|
|
2
|
+
#
|
|
3
|
+
# `flowstate update` installs a release only if its git tag is signed by a key listed HERE,
|
|
4
|
+
# in the copy that is already installed (it reads this file before it changes anything; the
|
|
5
|
+
# list inside the new release is not trusted). An empty list means every update is refused
|
|
6
|
+
# with "no release signing key is set up yet".
|
|
7
|
+
#
|
|
8
|
+
# One line per key: <principal> namespaces="git" ssh-ed25519 AAAA... <comment>
|
|
9
|
+
# Public keys only. Never put a private key here. How to make the key and sign a release:
|
|
10
|
+
# docs/RELEASING.md.
|
|
11
|
+
#
|
|
12
|
+
# A new key must arrive in a release signed by a key that is already listed here.
|
|
13
|
+
|
|
14
|
+
flowstate-release namespaces="git" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC5K/vdVxqPUXSmXW842s2NN2uJK7rpDj6/3bq39gmtq DialectForge FlowState release
|