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,177 @@
|
|
|
1
|
+
"""`flowstate relay run`: everything the relay needs, in one process.
|
|
2
|
+
|
|
3
|
+
- FlowState's normal public-mode HTTP app (OAuth 2.1 + PKCE, passphrase consent, per-app
|
|
4
|
+
revoke, read-only, Host allow-list, rate limits) on 127.0.0.1:<port>, with public URL
|
|
5
|
+
https://<handle>.fsmcp.com. Nothing about sign-in changes.
|
|
6
|
+
- the tunnel agent (tunnel.py), which terminates TLS with the local key and pipes the
|
|
7
|
+
decrypted HTTP to that listener;
|
|
8
|
+
- certificate upkeep: obtain at start if missing, check twice a day, renew 30 days before
|
|
9
|
+
expiry, reload the TLS context after a renewal;
|
|
10
|
+
- the daily Certificate Transparency check;
|
|
11
|
+
- a watcher that stops everything when `flowstate relay disable` / `forget` runs.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
import contextlib
|
|
16
|
+
import logging
|
|
17
|
+
import time
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Callable, Optional
|
|
20
|
+
|
|
21
|
+
from . import RelayError
|
|
22
|
+
from . import acme, ct
|
|
23
|
+
from . import crypto as C
|
|
24
|
+
from .api import client_context
|
|
25
|
+
from .store import CERT, TLS_KEY, TOKEN, RelayStore
|
|
26
|
+
from .tunnel import Backoff, TunnelAgent, server_context
|
|
27
|
+
|
|
28
|
+
log = logging.getLogger("flowstate.relay")
|
|
29
|
+
|
|
30
|
+
DEFAULT_PORT = 8768
|
|
31
|
+
CERT_CHECK_EVERY = 12 * 3600
|
|
32
|
+
WATCH_EVERY = 5.0
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
async def _sleep_or_stop(stop: asyncio.Event, seconds: float) -> None:
|
|
36
|
+
with contextlib.suppress(asyncio.TimeoutError):
|
|
37
|
+
await asyncio.wait_for(stop.wait(), seconds)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _Certs:
|
|
41
|
+
"""The current TLS server context, rebuilt whenever the certificate changes."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, store: RelayStore):
|
|
44
|
+
self.store, self.ctx, self.info = store, None, None
|
|
45
|
+
|
|
46
|
+
def reload(self) -> None:
|
|
47
|
+
why = acme.needs_cert(self.store)
|
|
48
|
+
if why and not why.startswith("certificate expires"):
|
|
49
|
+
self.ctx, self.info = None, None
|
|
50
|
+
return
|
|
51
|
+
self.ctx = server_context(self.store.path(CERT), self.store.path(TLS_KEY))
|
|
52
|
+
self.info = C.cert_info(self.store.read_bytes(CERT))
|
|
53
|
+
|
|
54
|
+
def get(self):
|
|
55
|
+
return self.ctx
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def run(store: Optional[RelayStore] = None, *, db_path: Optional[Path] = None,
|
|
59
|
+
port: int = DEFAULT_PORT, stop: Optional[asyncio.Event] = None,
|
|
60
|
+
ct_fetch=None, acme_sleep: Callable[[float], None] = time.sleep,
|
|
61
|
+
on_ready: Optional[Callable[[int], None]] = None,
|
|
62
|
+
heartbeat_min: float = 5.0, backoff: Optional[Backoff] = None) -> None:
|
|
63
|
+
store = store or RelayStore()
|
|
64
|
+
cfg = store.config()
|
|
65
|
+
if not cfg.get("handle"):
|
|
66
|
+
raise RelayError("the relay is not set up; run: flowstate relay enroll --code <code>")
|
|
67
|
+
if not cfg.get("enabled"):
|
|
68
|
+
raise RelayError("the relay is turned off; turn it on with: flowstate relay enable")
|
|
69
|
+
C._lib() # fail early, plainly, if `cryptography` is missing
|
|
70
|
+
token = store.token()
|
|
71
|
+
host = cfg["hostname"]
|
|
72
|
+
stop = stop or asyncio.Event()
|
|
73
|
+
|
|
74
|
+
import uvicorn
|
|
75
|
+
from .. import remote_auth as RA
|
|
76
|
+
from ..server import create_http_app
|
|
77
|
+
if not RA.AuthStore().has_passphrase():
|
|
78
|
+
log.warning("no owner passphrase set: apps can't be approved until you run "
|
|
79
|
+
"`flowstate remote passphrase`")
|
|
80
|
+
|
|
81
|
+
peer_map: dict = {}
|
|
82
|
+
app = create_http_app(None, db_path=db_path, public_url=f"https://{host}", trust_proxy=False,
|
|
83
|
+
peer_resolver=lambda peer: peer_map.get(peer[1]), relay=True)
|
|
84
|
+
server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="info",
|
|
85
|
+
access_log=False, proxy_headers=False,
|
|
86
|
+
server_header=False))
|
|
87
|
+
status = {"tunnel": "starting", "detail": "", "url": f"https://{host}/mcp"}
|
|
88
|
+
|
|
89
|
+
def save(**kw):
|
|
90
|
+
status.update(kw)
|
|
91
|
+
if store.path(TOKEN).exists(): # after `forget`, leave nothing behind
|
|
92
|
+
store.save_status(status)
|
|
93
|
+
|
|
94
|
+
certs = _Certs(store)
|
|
95
|
+
certs.reload()
|
|
96
|
+
serve = asyncio.create_task(server.serve())
|
|
97
|
+
while not server.started:
|
|
98
|
+
if serve.done():
|
|
99
|
+
serve.result()
|
|
100
|
+
raise RelayError(f"the local listener on 127.0.0.1:{port} did not start")
|
|
101
|
+
await asyncio.sleep(0.05)
|
|
102
|
+
local_port = server.servers[0].sockets[0].getsockname()[1]
|
|
103
|
+
save(port=local_port)
|
|
104
|
+
log.info("relay: FlowState public listener on 127.0.0.1:%s for https://%s", local_port, host)
|
|
105
|
+
|
|
106
|
+
agent = TunnelAgent(
|
|
107
|
+
host=cfg.get("tunnel_host"), port=int(cfg.get("tunnel_port", 443)),
|
|
108
|
+
sni=cfg.get("tunnel_sni") or cfg.get("tunnel_host"), token=token, handle=cfg["handle"],
|
|
109
|
+
client_ctx=client_context(store.ca_file()), server_ctx=certs.get,
|
|
110
|
+
local_port=lambda: local_port, peer_map=peer_map,
|
|
111
|
+
on_state=lambda s, d: save(tunnel=s, detail=d, tunnel_since=int(time.time())),
|
|
112
|
+
min_heartbeat=heartbeat_min, backoff=backoff)
|
|
113
|
+
|
|
114
|
+
async def cert_loop():
|
|
115
|
+
fail = Backoff(base=300, cap=6 * 3600)
|
|
116
|
+
while not stop.is_set():
|
|
117
|
+
try:
|
|
118
|
+
r = await asyncio.to_thread(acme.ensure_cert, store, sleep=acme_sleep)
|
|
119
|
+
if r["renewed"] or certs.ctx is None:
|
|
120
|
+
certs.reload()
|
|
121
|
+
info = certs.info or r["info"]
|
|
122
|
+
save(cert_not_after=info["not_after"].isoformat(), cert_error=None,
|
|
123
|
+
cert_checked=int(time.time()))
|
|
124
|
+
fail.reset()
|
|
125
|
+
wait = CERT_CHECK_EVERY
|
|
126
|
+
except Exception as e: # noqa: BLE001 - keep serving with the old cert, retry later
|
|
127
|
+
wait = fail.next()
|
|
128
|
+
log.error("certificate: %s (retry in %.0f min)", e, wait / 60)
|
|
129
|
+
save(cert_error=str(e)[:200], cert_checked=int(time.time()))
|
|
130
|
+
await _sleep_or_stop(stop, wait)
|
|
131
|
+
|
|
132
|
+
async def ct_loop():
|
|
133
|
+
while not stop.is_set():
|
|
134
|
+
if ct.due(store):
|
|
135
|
+
try:
|
|
136
|
+
r = await asyncio.to_thread(ct.run_check, store, ct_fetch or ct._fetch)
|
|
137
|
+
save(ct_ok=r["ok"], ct_last_check=r.get("last_check"))
|
|
138
|
+
except Exception as e: # noqa: BLE001
|
|
139
|
+
log.warning("CT check failed: %s", e)
|
|
140
|
+
await _sleep_or_stop(stop, 3600)
|
|
141
|
+
|
|
142
|
+
async def watch():
|
|
143
|
+
last = 0.0
|
|
144
|
+
while not stop.is_set():
|
|
145
|
+
c = store.config()
|
|
146
|
+
if not c.get("enabled") or store.read_bytes(TOKEN) is None:
|
|
147
|
+
log.info("relay turned off (flowstate relay disable/forget); stopping")
|
|
148
|
+
stop.set()
|
|
149
|
+
break
|
|
150
|
+
if serve.done():
|
|
151
|
+
stop.set()
|
|
152
|
+
break
|
|
153
|
+
if time.monotonic() - last > 30:
|
|
154
|
+
save() # heartbeat for `flowstate relay status`
|
|
155
|
+
last = time.monotonic()
|
|
156
|
+
await _sleep_or_stop(stop, WATCH_EVERY)
|
|
157
|
+
|
|
158
|
+
tasks = [asyncio.create_task(agent.run(stop)), asyncio.create_task(cert_loop()),
|
|
159
|
+
asyncio.create_task(watch())]
|
|
160
|
+
if ct_fetch is not False:
|
|
161
|
+
tasks.append(asyncio.create_task(ct_loop()))
|
|
162
|
+
if on_ready:
|
|
163
|
+
on_ready(local_port)
|
|
164
|
+
try:
|
|
165
|
+
await asyncio.wait({serve, asyncio.ensure_future(stop.wait())},
|
|
166
|
+
return_when=asyncio.FIRST_COMPLETED)
|
|
167
|
+
finally:
|
|
168
|
+
stop.set()
|
|
169
|
+
server.should_exit = True
|
|
170
|
+
for t in tasks[1:]:
|
|
171
|
+
t.cancel()
|
|
172
|
+
await asyncio.gather(*tasks, return_exceptions=True)
|
|
173
|
+
with contextlib.suppress(Exception):
|
|
174
|
+
await asyncio.wait_for(serve, 10)
|
|
175
|
+
with contextlib.suppress(Exception):
|
|
176
|
+
save(tunnel="stopped", detail="")
|
|
177
|
+
log.info("relay stopped")
|
flowstate/relay/store.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Relay state on disk. Standard library only.
|
|
2
|
+
|
|
3
|
+
Folder: FLOWSTATE_RELAY_DIR, else <FlowState data folder>/relay (Windows
|
|
4
|
+
%LOCALAPPDATA%\\flowstate\\relay, macOS ~/Library/Application Support/flowstate/relay,
|
|
5
|
+
Linux ~/.local/share/flowstate/relay). Created 0700; every file is written 0600 (on Windows
|
|
6
|
+
the per-user AppData ACL is what protects it). Refused inside a git work tree.
|
|
7
|
+
|
|
8
|
+
relay.json settings, no secrets: handle, hostname, api, tunnel, staging, enabled
|
|
9
|
+
device-token the relay device token (secret)
|
|
10
|
+
tls-key.pem ECDSA P-256 key for <handle>.fsmcp.com (secret, never sent)
|
|
11
|
+
acme-account-key.pem ECDSA P-256 Let's Encrypt account key (secret, never sent)
|
|
12
|
+
acme-account.json the ACME account URL per directory
|
|
13
|
+
cert.pem the certificate chain (public)
|
|
14
|
+
status.json written by the running agent: tunnel state, heartbeat time
|
|
15
|
+
ct.json Certificate Transparency results and alerts
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import time
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Optional
|
|
23
|
+
|
|
24
|
+
from .. import paths
|
|
25
|
+
from ..urls import no_trailing_slash
|
|
26
|
+
from . import API_BASE, HOST_SUFFIX, TUNNEL_HOST, TUNNEL_PORT, RelayError
|
|
27
|
+
|
|
28
|
+
CONFIG = "relay.json"
|
|
29
|
+
TOKEN = "device-token"
|
|
30
|
+
TLS_KEY = "tls-key.pem"
|
|
31
|
+
ACCOUNT_KEY = "acme-account-key.pem"
|
|
32
|
+
ACCOUNT = "acme-account.json"
|
|
33
|
+
CERT = "cert.pem"
|
|
34
|
+
STATUS = "status.json"
|
|
35
|
+
CT = "ct.json"
|
|
36
|
+
ALL_FILES = (CONFIG, TOKEN, TLS_KEY, ACCOUNT_KEY, ACCOUNT, CERT, STATUS, CT)
|
|
37
|
+
|
|
38
|
+
# the running agent rewrites status.json at least this often; older means "not running"
|
|
39
|
+
STATUS_FRESH_SECONDS = 90
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def relay_dir() -> Path:
|
|
43
|
+
env = os.environ.get("FLOWSTATE_RELAY_DIR")
|
|
44
|
+
return Path(env).expanduser() if env else paths.data_root() / "relay"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _write_private(p: Path, data: bytes) -> None:
|
|
48
|
+
"""Write `data` to `p` as an owner-only file, atomically."""
|
|
49
|
+
tmp = p.with_name(p.name + ".tmp")
|
|
50
|
+
# O_BINARY: Windows would otherwise write every b"\n" in keys and certificates as \r\n
|
|
51
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_BINARY", 0), 0o600)
|
|
52
|
+
try:
|
|
53
|
+
os.write(fd, data)
|
|
54
|
+
finally:
|
|
55
|
+
os.close(fd)
|
|
56
|
+
os.chmod(tmp, 0o600)
|
|
57
|
+
paths.replace_file(tmp, p)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class RelayStore:
|
|
61
|
+
def __init__(self, root: Optional[Path] = None):
|
|
62
|
+
self.root = Path(root) if root else relay_dir()
|
|
63
|
+
|
|
64
|
+
# ------------------------------------------------------------ files
|
|
65
|
+
def path(self, name: str) -> Path:
|
|
66
|
+
return self.root / name
|
|
67
|
+
|
|
68
|
+
def ensure_dir(self) -> None:
|
|
69
|
+
repo = paths.inside_git_worktree(self.root)
|
|
70
|
+
if repo:
|
|
71
|
+
raise RelayError(f"refusing to keep relay keys inside a git folder ({repo}); "
|
|
72
|
+
"set FLOWSTATE_RELAY_DIR to a private folder")
|
|
73
|
+
self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
74
|
+
os.chmod(self.root, 0o700)
|
|
75
|
+
|
|
76
|
+
def write_secret(self, name: str, data: bytes) -> None:
|
|
77
|
+
self.ensure_dir()
|
|
78
|
+
_write_private(self.path(name), data)
|
|
79
|
+
|
|
80
|
+
def read_bytes(self, name: str) -> Optional[bytes]:
|
|
81
|
+
try:
|
|
82
|
+
return self.path(name).read_bytes()
|
|
83
|
+
except FileNotFoundError:
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
def _read_json(self, name: str) -> dict:
|
|
87
|
+
raw = self.read_bytes(name)
|
|
88
|
+
try:
|
|
89
|
+
data = json.loads(raw) if raw else {}
|
|
90
|
+
except ValueError:
|
|
91
|
+
return {}
|
|
92
|
+
return data if isinstance(data, dict) else {}
|
|
93
|
+
|
|
94
|
+
def _write_json(self, name: str, data: dict) -> None:
|
|
95
|
+
self.write_secret(name, (json.dumps(data, indent=2, sort_keys=True) + "\n").encode())
|
|
96
|
+
|
|
97
|
+
# ------------------------------------------------------------ settings
|
|
98
|
+
def config(self) -> dict:
|
|
99
|
+
return self._read_json(CONFIG)
|
|
100
|
+
|
|
101
|
+
def save_config(self, cfg: dict) -> None:
|
|
102
|
+
for k in ("token", "device_token"): # never in the settings file
|
|
103
|
+
cfg.pop(k, None)
|
|
104
|
+
self._write_json(CONFIG, cfg)
|
|
105
|
+
|
|
106
|
+
def enrolled(self) -> bool:
|
|
107
|
+
return bool(self.config().get("handle")) and self.read_bytes(TOKEN) is not None
|
|
108
|
+
|
|
109
|
+
def token(self) -> str:
|
|
110
|
+
raw = self.read_bytes(TOKEN)
|
|
111
|
+
if not raw:
|
|
112
|
+
raise RelayError("not enrolled (no device token); run: flowstate relay enroll --code <code>")
|
|
113
|
+
return raw.decode().strip()
|
|
114
|
+
|
|
115
|
+
def save_enrollment(self, handle: str, token: str, *, api: str = API_BASE,
|
|
116
|
+
tunnel_host: str = TUNNEL_HOST, tunnel_port: int = TUNNEL_PORT,
|
|
117
|
+
tunnel_sni: str = TUNNEL_HOST, staging: bool = False,
|
|
118
|
+
ca_file: Optional[str] = None) -> dict:
|
|
119
|
+
cfg = {"version": 1, "handle": handle, "hostname": f"{handle}.{HOST_SUFFIX}",
|
|
120
|
+
"api": no_trailing_slash(api), "tunnel_host": tunnel_host, "tunnel_port": int(tunnel_port),
|
|
121
|
+
"tunnel_sni": tunnel_sni, "staging": bool(staging), "enabled": True,
|
|
122
|
+
"enrolled_at": int(time.time()), "known_spki": []}
|
|
123
|
+
if ca_file:
|
|
124
|
+
cfg["ca_file"] = str(ca_file)
|
|
125
|
+
self.write_secret(TOKEN, token.encode() + b"\n")
|
|
126
|
+
self.save_config(cfg)
|
|
127
|
+
return cfg
|
|
128
|
+
|
|
129
|
+
def set_enabled(self, on: bool) -> dict:
|
|
130
|
+
cfg = self.config()
|
|
131
|
+
if not cfg.get("handle"):
|
|
132
|
+
raise RelayError("the relay is not set up (flowstate relay enroll --code <code>)")
|
|
133
|
+
cfg["enabled"] = bool(on)
|
|
134
|
+
self.save_config(cfg)
|
|
135
|
+
return cfg
|
|
136
|
+
|
|
137
|
+
def forget(self) -> list:
|
|
138
|
+
"""Delete token, keys, certificate and state. Returns the names removed."""
|
|
139
|
+
gone = []
|
|
140
|
+
for name in ALL_FILES:
|
|
141
|
+
for p in (self.path(name), self.path(name + ".tmp")):
|
|
142
|
+
if p.exists():
|
|
143
|
+
p.unlink()
|
|
144
|
+
gone.append(p.name)
|
|
145
|
+
try:
|
|
146
|
+
self.root.rmdir()
|
|
147
|
+
except OSError:
|
|
148
|
+
pass
|
|
149
|
+
return gone
|
|
150
|
+
|
|
151
|
+
# ------------------------------------------------------------ agent status / CT
|
|
152
|
+
def status(self) -> dict:
|
|
153
|
+
return self._read_json(STATUS)
|
|
154
|
+
|
|
155
|
+
def save_status(self, st: dict) -> None:
|
|
156
|
+
st = dict(st, pid=os.getpid(), updated=int(time.time()))
|
|
157
|
+
self._write_json(STATUS, st)
|
|
158
|
+
|
|
159
|
+
def ct(self) -> dict:
|
|
160
|
+
return self._read_json(CT)
|
|
161
|
+
|
|
162
|
+
def save_ct(self, data: dict) -> None:
|
|
163
|
+
self._write_json(CT, data)
|
|
164
|
+
|
|
165
|
+
def ca_file(self) -> Optional[str]:
|
|
166
|
+
return os.environ.get("FLOWSTATE_RELAY_CA_FILE") or self.config().get("ca_file")
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def active_alerts(ct: dict) -> list:
|
|
170
|
+
return [a for a in ct.get("alerts") or [] if not a.get("acknowledged")]
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def tool_warning(store: Optional[RelayStore] = None) -> Optional[str]:
|
|
174
|
+
"""One loud line for tool output (start_here) when the CT watch found a certificate for
|
|
175
|
+
this computer's relay hostname that was NOT made with the local key. None otherwise
|
|
176
|
+
(and always None when the relay was never set up). Never raises."""
|
|
177
|
+
try:
|
|
178
|
+
store = store or RelayStore()
|
|
179
|
+
if not store.path(CT).exists():
|
|
180
|
+
return None
|
|
181
|
+
alerts = active_alerts(store.ct())
|
|
182
|
+
except Exception: # noqa: BLE001 - a status line must never break a tool
|
|
183
|
+
return None
|
|
184
|
+
if not alerts:
|
|
185
|
+
return None
|
|
186
|
+
host = store.config().get("hostname", "your relay hostname")
|
|
187
|
+
ids = ", ".join(str(a.get("crtsh_id")) for a in alerts[:5])
|
|
188
|
+
return (f"!! FLOWSTATE RELAY SECURITY WARNING: {len(alerts)} certificate(s) for {host} were "
|
|
189
|
+
f"issued with a key that is NOT this computer's (crt.sh id {ids}). Someone may be "
|
|
190
|
+
f"able to read relay traffic. Tell the user now; they should run "
|
|
191
|
+
f"`flowstate relay disable` and `flowstate relay status`.")
|