caisson-tools 0.1.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.
caisson_tools/serve.py ADDED
@@ -0,0 +1,160 @@
1
+ """Tailnet-only workspace ingress. Mutations run under the Podman lifecycle lock."""
2
+
3
+ from html import escape
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import re
8
+ import subprocess
9
+ import sys
10
+
11
+
12
+ PORTS = range(8400, 8500)
13
+
14
+ PICKER_HEAD = """<!doctype html>
15
+ <html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
16
+ <title>Workspaces · Caisson</title>
17
+ <style>
18
+ :root { color-scheme: light dark; font: 100%/1.5 system-ui, sans-serif; }
19
+ body { margin: 0; background: Canvas; color: CanvasText; }
20
+ main { max-width: 34rem; margin: clamp(2rem, 10vh, 6rem) auto; padding: 0 1.25rem; }
21
+ header small { font-weight: 700; letter-spacing: .12em; text-transform: uppercase; }
22
+ h1 { margin: .25rem 0 1.25rem; line-height: 1.2; }
23
+ ul { list-style: none; padding: 0; }
24
+ li + li { margin-top: .5rem; }
25
+ a { display: flex; justify-content: space-between; gap: 1rem; align-items: center;
26
+ padding: .8rem 1rem; border: 1px solid GrayText; border-radius: .6rem;
27
+ color: inherit; text-decoration: none; font-weight: 600; overflow-wrap: anywhere; }
28
+ a:hover, a:focus-visible { color: LinkText; border-color: currentColor; text-decoration: underline; }
29
+ </style>
30
+ <main><header><small>Caisson</small><h1>Workspaces</h1></header>
31
+ """
32
+
33
+
34
+ def state_dir():
35
+ return Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state") / "caisson"
36
+
37
+
38
+ def assignments():
39
+ try:
40
+ ports = json.loads((state_dir() / "serve-ports.json").read_text())
41
+ except FileNotFoundError:
42
+ return {}
43
+ if not isinstance(ports, dict) or any(
44
+ type(p) is not int or p not in PORTS for p in ports.values()
45
+ ) or len(set(ports.values())) != len(ports):
46
+ raise ValueError("Invalid workspace Serve port assignments")
47
+ return ports
48
+
49
+
50
+ def ts(*args):
51
+ # Publishing a filesystem path requires elevated tailscaled permissions.
52
+ if args[:2] == ("serve", "--bg"):
53
+ command = ["tailscale", *args]
54
+ if os.geteuid():
55
+ command = (["sudo"] if sys.stdin.isatty() else ["sudo", "-n"]) + command
56
+ # Surface Serve enablement instructions without contaminating CLI stdout.
57
+ subprocess.run(command, stdout=sys.stderr, check=True)
58
+ else:
59
+ return subprocess.check_output(["tailscale", *args], text=True)
60
+
61
+
62
+ def atomic_write(path, content):
63
+ # Writers share the host lifecycle lock. Serve reads only the final file.
64
+ temp = path.with_suffix(".tmp")
65
+ temp.write_text(content)
66
+ temp.replace(path)
67
+
68
+
69
+ class Serve:
70
+ def __init__(self, ports):
71
+ status = json.loads(ts("status", "--json", "--peers=false"))
72
+ self.host = ((status.get("Self") or {}).get("DNSName") or "").rstrip(".").lower()
73
+ if status.get("BackendState") != "Running" or not re.fullmatch(
74
+ r"(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9]+", self.host
75
+ ):
76
+ raise ValueError("Tailscale must be running with a MagicDNS hostname")
77
+ self.refresh()
78
+ self.index = state_dir() / "index.html"
79
+ self.ports = ports
80
+
81
+ def allocate(self, name):
82
+ if name not in self.ports:
83
+ for port in PORTS:
84
+ if port not in self.ports.values() and not self.occupied(port):
85
+ self.ports[name] = port
86
+ self.save()
87
+ break
88
+ else:
89
+ raise ValueError("No free Tailscale workspace HTTPS ports")
90
+ return self.url(name)
91
+
92
+ def save(self):
93
+ atomic_write(state_dir() / "serve-ports.json", json.dumps(self.ports, sort_keys=True))
94
+
95
+ def refresh(self):
96
+ self.routes = json.loads(ts("serve", "status", "--json")) or {}
97
+
98
+ def url(self, name):
99
+ if name not in self.ports:
100
+ raise ValueError(f"No Serve port assigned; rebuild {name}")
101
+ return f"https://{self.host}:{self.ports[name]}"
102
+
103
+ def occupied(self, port):
104
+ return any(self.listeners(cfg, port) for cfg in (
105
+ self.routes, *(self.routes.get("Foreground") or {}).values(),
106
+ ))
107
+
108
+ @staticmethod
109
+ def listeners(cfg, port):
110
+ return (
111
+ str(port) in (cfg.get("TCP") or {})
112
+ or any(key.endswith(f":{port}") for key in (cfg.get("Web") or {}))
113
+ or any(on and key.endswith(f":{port}") for key, on in (cfg.get("AllowFunnel") or {}).items())
114
+ )
115
+
116
+ def is_served(self, port):
117
+ """False if unused, True if ours; never modify a conflicting listener."""
118
+ if not self.occupied(port):
119
+ return False
120
+ key = f"{self.host}:{port}"
121
+ cfg = self.routes
122
+ handlers = (cfg.get("Web") or {}).get(key, {}).get("Handlers", {})
123
+ kind, target = self.target(port)
124
+ if (
125
+ (cfg.get("TCP") or {}).get(str(port)) == {"HTTPS": True}
126
+ and handlers == {"/": {kind: target}}
127
+ and not any(k != key and k.endswith(f":{port}") for k in (cfg.get("Web") or {}))
128
+ and not any(v and k.endswith(f":{port}") for k, v in (cfg.get("AllowFunnel") or {}).items())
129
+ and not any(self.listeners(fg, port) for fg in (cfg.get("Foreground") or {}).values())
130
+ ):
131
+ return True
132
+ raise ValueError(f"Tailscale port {port} has a conflicting listener; leaving it unchanged")
133
+
134
+ def target(self, port):
135
+ if port == 443:
136
+ return "Path", str(self.index)
137
+ return "Proxy", f"http://{self.relay(port)}"
138
+
139
+ @staticmethod
140
+ def relay(port):
141
+ return f"127.0.0.1:{10000 + port}"
142
+
143
+ def configure(self, port, enabled):
144
+ if self.is_served(port) == enabled:
145
+ return
146
+ _, target = self.target(port)
147
+ ts("serve", "--bg", "--yes", f"--https={port}", target if enabled else "off")
148
+ self.refresh()
149
+ if self.is_served(port) != enabled:
150
+ raise ValueError(f"Tailscale did not apply the listener change on {port}")
151
+
152
+ def picker(self, states):
153
+ links = []
154
+ for name in sorted(states):
155
+ if states[name] == "running" and name in self.ports and self.is_served(self.ports[name]):
156
+ links.append(f'<li><a href="{escape(self.url(name))}/">{escape(name)}'
157
+ ' <span aria-hidden="true">→</span></a></li>')
158
+ body = "<ul>" + "".join(links) + "</ul>" if links else "<p>No running workspaces.</p>"
159
+ atomic_write(self.index, PICKER_HEAD + body + "</main></html>\n")
160
+ self.configure(443, True)
@@ -0,0 +1,194 @@
1
+ """Interactive-only imports: never loaded by ordinary one-shot commands."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+ import shlex
6
+ import stat
7
+
8
+ import click
9
+ from click.shell_completion import ShellComplete, CompletionItem
10
+ from prompt_toolkit import PromptSession
11
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
12
+ from prompt_toolkit.completion import Completer, Completion, WordCompleter
13
+ from prompt_toolkit.history import FileHistory, InMemoryHistory
14
+ from prompt_toolkit.validation import Validator
15
+
16
+ from .common import console, local_paths, private_directory, prompt_text
17
+
18
+
19
+ class SafeHistory(InMemoryHistory):
20
+ def __init__(self, filename=None):
21
+ super().__init__()
22
+ self.file_history = FileHistory(str(filename)) if filename else None
23
+
24
+ def load_history_strings(self):
25
+ source = self.file_history if self.file_history else super()
26
+ yield from source.load_history_strings()
27
+
28
+ def store_string(self, string):
29
+ target = self.file_history if self.file_history else super()
30
+ target.store_string(string)
31
+
32
+ def append_string(self, string):
33
+ if string.startswith(" "):
34
+ return
35
+ try:
36
+ words = shlex.split(string)
37
+ except ValueError:
38
+ return
39
+ if any(
40
+ word in {"creds", "exec", "--value", "--placeholder"}
41
+ or word.startswith(("--value=", "--placeholder="))
42
+ for word in words
43
+ ):
44
+ return
45
+ super().append_string(string)
46
+
47
+
48
+ def persistent_history(name):
49
+ base = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state")
50
+ directory = private_directory(base / "caisson")
51
+ path = directory / f"{name}.history"
52
+ fd = os.open(path, os.O_CREAT | os.O_APPEND | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
53
+ try:
54
+ info = os.fstat(fd)
55
+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid():
56
+ raise OSError(f"Unsafe history file: {path}")
57
+ os.fchmod(fd, 0o600)
58
+ finally:
59
+ os.close(fd)
60
+ return SafeHistory(path)
61
+
62
+
63
+ class CommandCompleter(Completer):
64
+ def __init__(self, group, state):
65
+ self.group, self.state = group, state
66
+
67
+ def get_completions(self, document, complete_event):
68
+ text = document.text_before_cursor
69
+ start, quote, escaped = 0, None, False
70
+ for index, char in enumerate(text):
71
+ if escaped:
72
+ escaped = False
73
+ elif char == "\\" and quote != "'":
74
+ escaped = True
75
+ elif quote:
76
+ if char == quote:
77
+ quote = None
78
+ elif char in "'\"":
79
+ quote = char
80
+ elif char.isspace():
81
+ start = index + 1
82
+ try:
83
+ previous = shlex.split(text[:start])
84
+ token = text[start:]
85
+ decoded = shlex.split(token + (quote or "") + ("\\" if escaped else ""))
86
+ prefix = decoded[0] if decoded else ""
87
+ except ValueError:
88
+ return
89
+ items = []
90
+ if not previous:
91
+ items += [
92
+ CompletionItem(name, help="REPL")
93
+ for name in ("help", "exit", "quit")
94
+ if name.startswith(prefix)
95
+ ]
96
+ if previous[:1] == ["help"]:
97
+ previous = previous[1:]
98
+ try:
99
+ # Click resolves context without executing callbacks/network calls.
100
+ items += ShellComplete(
101
+ self.group, {"obj": self.state.copy()}, self.group.name or "caisson", "_COMPLETE"
102
+ ).get_completions(previous, prefix)
103
+ except (click.ClickException, ValueError):
104
+ return
105
+ seen = set()
106
+ for item in items:
107
+ expanded = local_paths(item.value) if item.type in {"file", "dir"} else [item]
108
+ for match in expanded:
109
+ if match.value in seen:
110
+ continue
111
+ seen.add(match.value)
112
+ yield Completion(
113
+ shlex.quote(match.value),
114
+ start_position=-len(text[start:]),
115
+ display=match.value,
116
+ display_meta=match.help or "",
117
+ )
118
+
119
+
120
+ def pick_workspace(host, names):
121
+ """Show workspace completions immediately, before the user starts typing."""
122
+ session = PromptSession(
123
+ completer=WordCompleter(names, sentence=True),
124
+ complete_while_typing=True,
125
+ validator=Validator.from_callable(
126
+ lambda text: text in names,
127
+ error_message="Choose a workspace from the list.",
128
+ move_cursor_to_end=True,
129
+ ),
130
+ )
131
+ try:
132
+ return session.prompt(
133
+ f"Workspace on {host}: ",
134
+ pre_run=lambda: session.app.current_buffer.start_completion(select_first=False),
135
+ )
136
+ except (EOFError, KeyboardInterrupt) as exc:
137
+ raise click.Abort() from exc
138
+
139
+
140
+ def context_toolbar(state, name):
141
+ """Render cached values only; never perform IO in a prompt callback."""
142
+ def display(value):
143
+ return "".join(c if c.isprintable() else "?" for c in str(value or "unavailable"))
144
+
145
+ if name == "caisson":
146
+ text = f"Workspace: {display(state.get('workspace') or 'no workspace')}"
147
+ if target := state.get("target"):
148
+ text += f" · Podman: {display(target)}"
149
+ else:
150
+ text += f" · User: {display(state.get('user_context', {}).get('user'))}"
151
+ else:
152
+ context = state.get("ops_context", {})
153
+ text = (
154
+ f"User: {display(context.get('account'))} · "
155
+ f"Project: {display(context.get('PROJECT_ID'))} · "
156
+ f"Region: {display(context.get('REGION'))}"
157
+ )
158
+ return [("class:bottom-toolbar", text)]
159
+
160
+
161
+ def repl(group, state, name):
162
+ state["in_repl"] = True
163
+ session = PromptSession(
164
+ history=persistent_history(name),
165
+ completer=CommandCompleter(group, state),
166
+ auto_suggest=AutoSuggestFromHistory(),
167
+ complete_while_typing=False,
168
+ bottom_toolbar=lambda: context_toolbar(state, name),
169
+ )
170
+ while True:
171
+ try:
172
+ line = session.prompt(prompt_text(state, name))
173
+ words = shlex.split(line)
174
+ if not words:
175
+ continue
176
+ if words[0] in {"exit", "quit"}:
177
+ break
178
+ if words[0] == "help":
179
+ words = words[1:] + ["--help"]
180
+ group.main(words, prog_name=name, obj=state, standalone_mode=False)
181
+ except EOFError:
182
+ break
183
+ except KeyboardInterrupt:
184
+ console.print("Cancelled.")
185
+ except click.ClickException as exc:
186
+ exc.show()
187
+ except click.exceptions.Exit as exc:
188
+ if exc.exit_code:
189
+ console.print(f"Command exited {exc.exit_code}.")
190
+ except click.Abort:
191
+ console.print("Cancelled.")
192
+ except (ValueError, OSError) as exc:
193
+ console.print(str(exc))
194
+ state.pop("in_repl", None)