hostdev 0.2.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.
hostdev/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Serve local applications at https://<name>.localhost and on the LAN through Caddy."""
hostdev/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Run the command line of hostdev: ``python -m hostdev``."""
2
+ import sys
3
+
4
+ from hostdev.cli import main
5
+
6
+ sys.exit(main())
hostdev/airdrop.swift ADDED
@@ -0,0 +1,16 @@
1
+ import AppKit
2
+
3
+ class Delegate: NSObject, NSSharingServiceDelegate {
4
+ func sharingService(_ s: NSSharingService, didShareItems items: [Any]) { print("shared"); exit(0) }
5
+ func sharingService(_ s: NSSharingService, didFailToShareItems items: [Any], error: Error) { print("failed: \(error.localizedDescription)"); exit(1) }
6
+ }
7
+ let app = NSApplication.shared
8
+ app.setActivationPolicy(.accessory)
9
+ let url = URL(fileURLWithPath: CommandLine.arguments[1])
10
+ guard let service = NSSharingService(named: .sendViaAirDrop), service.canPerform(withItems: [url]) else { print("airdrop not available"); exit(2) }
11
+ let delegate = Delegate()
12
+ service.delegate = delegate
13
+ service.perform(withItems: [url])
14
+ app.activate(ignoringOtherApps: true)
15
+ DispatchQueue.main.asyncAfter(deadline: .now() + 300) { print("timeout"); exit(3) }
16
+ app.run()
hostdev/cli.py ADDED
@@ -0,0 +1,85 @@
1
+ """The command line of hostdev.
2
+
3
+ hostdev the interactive menu
4
+ hostdev start [--cwd DIR] [--name NAME] [--instance INSTANCE] [--config CONFIG] [--lan]
5
+ hostdev start [...] --port PORT [--path PATH] -- COMMAND [ARG ...]
6
+ hostdev stop HOST
7
+ hostdev lan HOST on|off
8
+ hostdev list
9
+ hostdev ca
10
+ hostdev check
11
+ hostdev setup
12
+ hostdev publish ALIAS internal: keep ALIAS.local on the LAN
13
+
14
+ Each command, but the menu and ``publish``, writes one JSON line. The exit code is 1 when
15
+ the JSON has an ``error`` key.
16
+ """
17
+
18
+ import argparse
19
+ import json
20
+ import sys
21
+
22
+ from hostdev.core import HostDev
23
+ from hostdev.interactive import Menu
24
+ from hostdev.mdns import CnamePublisher, local_host_name
25
+
26
+
27
+ def say(data):
28
+ sys.stdout.write(json.dumps(data, ensure_ascii=False) + "\n")
29
+
30
+
31
+ def parser():
32
+ result = argparse.ArgumentParser(prog="hostdev")
33
+ commands = result.add_subparsers(dest="command", required=True)
34
+ start = commands.add_parser("start")
35
+ start.add_argument("--cwd", default=".")
36
+ start.add_argument("--name")
37
+ start.add_argument("--instance")
38
+ start.add_argument("--config")
39
+ start.add_argument("--lan", action="store_true")
40
+ start.add_argument("--port", type=int)
41
+ start.add_argument("--path", default="/")
42
+ stop = commands.add_parser("stop")
43
+ stop.add_argument("host")
44
+ lan = commands.add_parser("lan")
45
+ lan.add_argument("host")
46
+ lan.add_argument("state", choices=["on", "off"])
47
+ publish = commands.add_parser("publish")
48
+ publish.add_argument("alias")
49
+ for name in ("list", "ca", "check", "setup"):
50
+ commands.add_parser(name)
51
+ return result
52
+
53
+
54
+ def run(hostdev, args, command):
55
+ """The result of one command, as JSON data."""
56
+ if args.command == "start":
57
+ if command and args.port is None:
58
+ return {"error": "A command after `--` needs --port: the port in the command."}
59
+ return hostdev.start(cwd=args.cwd, name=args.name, instance=args.instance,
60
+ config=args.config, lan=args.lan, command=command,
61
+ port=args.port, path=args.path)
62
+ if args.command == "stop":
63
+ return hostdev.stop(args.host)
64
+ if args.command == "lan":
65
+ return hostdev.lan(args.host, args.state == "on")
66
+ return {"list": hostdev.list, "ca": hostdev.ca, "check": hostdev.check,
67
+ "setup": hostdev.setup}[args.command]()
68
+
69
+
70
+ def main(argv=None):
71
+ argv = sys.argv[1:] if argv is None else argv
72
+ if sys.platform != "darwin":
73
+ sys.stderr.write("hostdev runs on macOS only.\n")
74
+ return 2
75
+ if not argv:
76
+ return Menu(HostDev()).run()
77
+ command = argv[argv.index("--") + 1:] if "--" in argv else []
78
+ args = parser().parse_args(argv[: argv.index("--")] if "--" in argv else argv)
79
+ if args.command == "publish":
80
+ error = CnamePublisher(args.alias, local_host_name()).run()
81
+ sys.stderr.write(f"dns_sd error {error} for {args.alias}\n")
82
+ return 1
83
+ result = run(HostDev(), args, command)
84
+ say(result)
85
+ return 1 if isinstance(result, dict) and "error" in result else 0
hostdev/core.py ADDED
@@ -0,0 +1,345 @@
1
+ """Start local applications and serve them through Caddy.
2
+
3
+ ``HostDev.start`` chooses a free port in PORT_RANGE and starts the command of the
4
+ application with that port. Then it writes one Caddy site file for the host and reloads
5
+ Caddy. The host is ``<instance>.<name>.localhost``, or ``<name>.localhost`` with no
6
+ instance.
7
+
8
+ With ``lan``, the host gets a second name for the devices of the local network:
9
+ ``<instance>-<name>.local``. One ``hostdev publish`` process for each host keeps that name
10
+ on the network (see ``mdns``). The certificate comes from the local CA of Caddy. A phone
11
+ accepts it after ``HostDev.ca`` sends the root certificate and the user trusts it.
12
+
13
+ State: ``<state_dir>/instances.json``, ``<state_dir>/sites/<host>.caddy`` and
14
+ ``<state_dir>/logs/``. The Caddyfile of Homebrew imports ``<state_dir>/sites/*.caddy``.
15
+ """
16
+
17
+ import json
18
+ import os
19
+ import shutil
20
+ import signal
21
+ import socket
22
+ import subprocess
23
+ import sys
24
+ import time
25
+ from pathlib import Path
26
+
27
+ DEFAULT_STATE_DIR = Path.home() / ".local" / "state" / "hostdev"
28
+ PORT_RANGE = range(8100, 8200)
29
+ START_TIMEOUT = 90 # seconds until the port must listen
30
+ CADDY_ADMIN_PORT = 2019
31
+ SITE = "{names} {{\n\ttls internal\n\treverse_proxy 127.0.0.1:{port}\n}}\n"
32
+ IMPORT_COMMENT = "# Local sites of hostdev: one file per host, written by hostdev.\n"
33
+ AIRDROP_SCRIPT = Path(__file__).with_name("airdrop.swift")
34
+ TRUST_COMMAND = "caddy trust"
35
+ IPHONE_STEPS = [
36
+ "On the Mac: select the iPhone in the AirDrop panel.",
37
+ "On the iPhone: Settings > Profile Downloaded > Install.",
38
+ "On the iPhone: Settings > General > About > Certificate Trust Settings. "
39
+ "Enable 'Caddy Local Authority'.",
40
+ ]
41
+
42
+
43
+ def label(text):
44
+ """A DNS label: lower case, letters, digits and hyphens."""
45
+ result = "".join(c if c.isalnum() else "-" for c in text.lower()).strip("-")
46
+ if not result:
47
+ raise ValueError(f"{text!r} gives an empty host name.")
48
+ return result
49
+
50
+
51
+ def host_name(name, instance=None):
52
+ """``<instance>.<name>.localhost``, or ``<name>.localhost`` with no instance."""
53
+ if instance:
54
+ return f"{label(instance)}.{label(name)}.localhost"
55
+ return f"{label(name)}.localhost"
56
+
57
+
58
+ def lan_name(host):
59
+ """The LAN name of a host: its labels in one label, then ``.local``.
60
+
61
+ The LAN name has one label: ``v1.myapp.localhost`` gives ``v1-myapp.local``.
62
+ """
63
+ return host[: -len(".localhost")].replace(".", "-") + ".local"
64
+
65
+
66
+ def command_line(launch, port):
67
+ """The command of a launch configuration, with its port replaced by ``port``."""
68
+ return [launch["runtimeExecutable"],
69
+ *(str(port) if str(arg) == str(launch.get("port")) else arg
70
+ for arg in launch.get("runtimeArgs", []))]
71
+
72
+
73
+ def alive(pid):
74
+ try:
75
+ os.kill(pid, 0)
76
+ except OSError:
77
+ return False
78
+ return True
79
+
80
+
81
+ def listening(port):
82
+ with socket.socket() as sock:
83
+ return sock.connect_ex(("127.0.0.1", port)) == 0
84
+
85
+
86
+ class HostDev:
87
+ """The local applications of one state folder."""
88
+
89
+ def __init__(self, state_dir=None, caddyfile=None):
90
+ self._state_dir = Path(state_dir) if state_dir else DEFAULT_STATE_DIR
91
+ self._caddyfile = Path(caddyfile) if caddyfile else None
92
+
93
+ @property
94
+ def state_dir(self):
95
+ return self._state_dir
96
+
97
+ @property
98
+ def sites_dir(self):
99
+ return self.state_dir / "sites"
100
+
101
+ @property
102
+ def logs_dir(self):
103
+ return self.state_dir / "logs"
104
+
105
+ @property
106
+ def instances_path(self):
107
+ return self.state_dir / "instances.json"
108
+
109
+ @property
110
+ def import_line(self):
111
+ return f"import {self.sites_dir}/*.caddy"
112
+
113
+ @property
114
+ def brew_prefix(self):
115
+ done = subprocess.run(["brew", "--prefix"], capture_output=True, text=True, check=True)
116
+ return Path(done.stdout.strip())
117
+
118
+ @property
119
+ def caddyfile(self):
120
+ """The Caddyfile of the Homebrew service of Caddy."""
121
+ return self._caddyfile or self.brew_prefix / "etc" / "Caddyfile"
122
+
123
+ @property
124
+ def root_ca(self):
125
+ """The root certificate of the local CA of the Homebrew service of Caddy."""
126
+ return (self.brew_prefix / "var" / "lib" / "caddy" / "pki" / "authorities" / "local"
127
+ / "root.crt")
128
+
129
+ # ----------------------------------------------------------------- state
130
+
131
+ def read_instances(self):
132
+ if self.instances_path.exists():
133
+ return json.loads(self.instances_path.read_text())
134
+ return {}
135
+
136
+ def write_instances(self, instances):
137
+ self.state_dir.mkdir(parents=True, exist_ok=True)
138
+ self.instances_path.write_text(json.dumps(instances, indent=1, ensure_ascii=False))
139
+
140
+ def free_port(self, instances):
141
+ used = {entry["port"] for entry in instances.values()}
142
+ for port in PORT_RANGE:
143
+ if port not in used and not listening(port):
144
+ return port
145
+ raise RuntimeError(f"No free port in {PORT_RANGE.start}-{PORT_RANGE.stop - 1}.")
146
+
147
+ def lan_alive(self, entry):
148
+ return entry["lan_pid"] is not None and alive(entry["lan_pid"])
149
+
150
+ def describe(self, host, entry):
151
+ """The public data of one instance."""
152
+ lan_url = f"https://{lan_name(host)}{entry['path']}" if self.lan_alive(entry) else None
153
+ return {"host": host, "url": f"https://{host}{entry['path']}", "lan_url": lan_url,
154
+ "port": entry["port"], "pid": entry["pid"], "alive": alive(entry["pid"]),
155
+ "cwd": entry["cwd"], "log": entry["log"]}
156
+
157
+ # ------------------------------------------------------- launch.json
158
+
159
+ def launch_path(self, cwd):
160
+ return Path(cwd) / ".claude" / "launch.json"
161
+
162
+ def configuration(self, cwd, name=None):
163
+ """One configuration of ``<cwd>/.claude/launch.json``: the first one, or by name."""
164
+ launch = self.launch_path(cwd)
165
+ if not launch.exists():
166
+ raise LookupError(f"{launch} does not exist.")
167
+ configurations = json.loads(launch.read_text())["configurations"]
168
+ if name is None:
169
+ return configurations[0]
170
+ for entry in configurations:
171
+ if entry["name"] == name:
172
+ return entry
173
+ raise LookupError(f"No configuration {name!r} in {launch}.")
174
+
175
+ def write_launch(self, cwd, name, command, port, path):
176
+ """Create ``<cwd>/.claude/launch.json`` with one configuration."""
177
+ launch = self.launch_path(cwd)
178
+ launch.parent.mkdir(parents=True, exist_ok=True)
179
+ configuration = {"name": name, "runtimeExecutable": command[0],
180
+ "runtimeArgs": command[1:], "port": port, "path": path}
181
+ launch.write_text(json.dumps({"version": "0.0.1", "configurations": [configuration]},
182
+ indent=2) + "\n")
183
+ return launch
184
+
185
+ # ----------------------------------------------------------------- Caddy
186
+
187
+ def caddy_reload(self):
188
+ """Reload Caddy with the main Caddyfile. Returns an error text, or None."""
189
+ path = self.caddyfile
190
+ if not path.exists():
191
+ return f"{path} does not exist: run `hostdev setup`."
192
+ done = subprocess.run(["caddy", "reload", "--config", str(path)],
193
+ capture_output=True, text=True, check=False)
194
+ return done.stderr.strip()[-500:] if done.returncode else None
195
+
196
+ def site_text(self, host, entry):
197
+ names = host if entry["lan_pid"] is None else f"{host}, {lan_name(host)}"
198
+ return SITE.format(names=names, port=entry["port"])
199
+
200
+ def write_site(self, host, entry):
201
+ self.sites_dir.mkdir(parents=True, exist_ok=True)
202
+ (self.sites_dir / f"{host}.caddy").write_text(self.site_text(host, entry))
203
+
204
+ # ------------------------------------------------------------------- LAN
205
+
206
+ def publish(self, host):
207
+ """Start the process that keeps the LAN name of ``host`` on the network."""
208
+ self.logs_dir.mkdir(parents=True, exist_ok=True)
209
+ package_parent = str(Path(__file__).resolve().parents[1])
210
+ with (self.logs_dir / f"{host}.lan.log").open("w") as output:
211
+ process = subprocess.Popen(
212
+ [sys.executable, "-m", "hostdev", "publish", lan_name(host)],
213
+ stdout=output, stderr=subprocess.STDOUT, start_new_session=True,
214
+ env={**os.environ, "PYTHONPATH": package_parent})
215
+ return process.pid
216
+
217
+ def lan(self, host, on):
218
+ """Put the LAN name of a running host on the network, or remove it."""
219
+ instances = self.read_instances()
220
+ entry = instances.get(host)
221
+ if entry is None:
222
+ return {"error": f"No instance {host!r}.", "hosts": sorted(instances)}
223
+ if on and not self.lan_alive(entry):
224
+ entry["lan_pid"] = self.publish(host)
225
+ if not on:
226
+ if self.lan_alive(entry):
227
+ os.kill(entry["lan_pid"], signal.SIGTERM)
228
+ entry["lan_pid"] = None
229
+ self.write_site(host, entry)
230
+ self.write_instances(instances)
231
+ return {**self.describe(host, entry), "caddy_error": self.caddy_reload()}
232
+
233
+ def ca(self):
234
+ """Open the AirDrop panel with the root certificate of the local CA of Caddy."""
235
+ root_ca = self.root_ca
236
+ if not root_ca.exists():
237
+ return {"error": f"{root_ca} does not exist: start one application first."}
238
+ done = subprocess.run(["swift", str(AIRDROP_SCRIPT), str(root_ca)],
239
+ capture_output=True, text=True, check=False)
240
+ return {"root_ca": str(root_ca), "shared": done.returncode == 0,
241
+ "airdrop": (done.stdout + done.stderr).strip()[-500:], "steps": IPHONE_STEPS}
242
+
243
+ # ---------------------------------------------------------- start / stop
244
+
245
+ def start(self, cwd=".", name=None, instance=None, config=None, lan=False,
246
+ command=None, port=None, path="/"):
247
+ """Start one application. ``command`` with ``port`` replaces launch.json."""
248
+ cwd = str(Path(cwd).resolve())
249
+ if command:
250
+ launch = {"runtimeExecutable": command[0], "runtimeArgs": command[1:],
251
+ "port": port, "path": path}
252
+ else:
253
+ launch = self.configuration(cwd, config)
254
+ host = host_name(name or Path(cwd).name, instance)
255
+ instances = self.read_instances()
256
+ current = instances.get(host)
257
+ if current and alive(current["pid"]):
258
+ if lan and not self.lan_alive(current):
259
+ return {**self.lan(host, True), "already_running": True}
260
+ return {**self.describe(host, current), "already_running": True}
261
+ chosen = self.free_port(instances)
262
+ argv = command_line(launch, chosen)
263
+ self.logs_dir.mkdir(parents=True, exist_ok=True)
264
+ log = self.logs_dir / f"{host}.log"
265
+ with log.open("w") as output:
266
+ process = subprocess.Popen(argv, cwd=cwd, stdout=output, stderr=subprocess.STDOUT,
267
+ env={**os.environ, "PORT": str(chosen)},
268
+ start_new_session=True)
269
+ deadline = time.monotonic() + START_TIMEOUT
270
+ while not listening(chosen):
271
+ if process.poll() is not None or time.monotonic() > deadline:
272
+ if process.poll() is None:
273
+ os.killpg(process.pid, signal.SIGTERM)
274
+ return {"error": "The application did not start.", "log": str(log),
275
+ "tail": log.read_text()[-1500:]}
276
+ time.sleep(0.5)
277
+ entry = {"port": chosen, "pid": process.pid, "cwd": cwd, "log": str(log),
278
+ "command": argv, "path": launch.get("path", "/"),
279
+ "lan_pid": self.publish(host) if lan else None}
280
+ self.write_site(host, entry)
281
+ instances[host] = entry
282
+ self.write_instances(instances)
283
+ return {**self.describe(host, entry), "caddy_error": self.caddy_reload()}
284
+
285
+ def stop(self, host):
286
+ instances = self.read_instances()
287
+ entry = instances.pop(host, None)
288
+ if entry is None:
289
+ return {"error": f"No instance {host!r}.", "hosts": sorted(instances)}
290
+ if alive(entry["pid"]):
291
+ os.killpg(entry["pid"], signal.SIGTERM)
292
+ if self.lan_alive(entry):
293
+ os.kill(entry["lan_pid"], signal.SIGTERM)
294
+ (self.sites_dir / f"{host}.caddy").unlink(missing_ok=True)
295
+ self.write_instances(instances)
296
+ return {"stopped": host, "caddy_error": self.caddy_reload()}
297
+
298
+ def list(self):
299
+ return [self.describe(host, entry) for host, entry in self.read_instances().items()]
300
+
301
+ # ----------------------------------------------------------------- setup
302
+
303
+ def pending_steps(self):
304
+ """The setup steps that are not done, in the order to do them."""
305
+ path = self.caddyfile
306
+ steps = []
307
+ if shutil.which("caddy") is None:
308
+ steps.append("install_caddy")
309
+ if not path.exists() or self.import_line not in path.read_text():
310
+ steps.append("import_line")
311
+ if not listening(CADDY_ADMIN_PORT):
312
+ steps.append("start_service")
313
+ return steps
314
+
315
+ def check(self):
316
+ """The state of the setup."""
317
+ return {"caddy": shutil.which("caddy"), "caddyfile": str(self.caddyfile),
318
+ "expected_import": self.import_line, "pending": self.pending_steps(),
319
+ "trust": TRUST_COMMAND}
320
+
321
+ def install_caddy(self):
322
+ subprocess.run(["brew", "install", "caddy"], check=True)
323
+
324
+ def add_import_line(self):
325
+ """Add the import line to the Caddyfile, or create the Caddyfile with it."""
326
+ path = self.caddyfile
327
+ self.sites_dir.mkdir(parents=True, exist_ok=True)
328
+ text = path.read_text() if path.exists() else ""
329
+ separator = "\n" if text and not text.endswith("\n") else ""
330
+ path.write_text(text + separator + IMPORT_COMMENT + self.import_line + "\n")
331
+
332
+ def start_service(self):
333
+ subprocess.run(["brew", "services", "start", "caddy"], check=True)
334
+
335
+ def setup_step(self, step):
336
+ {"install_caddy": self.install_caddy, "import_line": self.add_import_line,
337
+ "start_service": self.start_service}[step]()
338
+
339
+ def setup(self):
340
+ """Do each pending setup step. The user runs ``caddy trust`` after the first start."""
341
+ done = self.pending_steps()
342
+ for step in done:
343
+ self.setup_step(step)
344
+ reload_error = self.caddy_reload() if done and "start_service" not in done else None
345
+ return {"done": done, "caddy_error": reload_error, "trust": TRUST_COMMAND}
hostdev/interactive.py ADDED
@@ -0,0 +1,129 @@
1
+ """The interactive menu of hostdev: ``hostdev`` with no argument."""
2
+
3
+ import os
4
+ import shlex
5
+ from pathlib import Path
6
+
7
+ ACTIONS = """
8
+ [s] start the project of this folder
9
+ [l] put on the LAN, or remove from it (number)
10
+ [x] stop (number)
11
+ [c] send the CA to the iPhone (AirDrop)
12
+ [q] quit"""
13
+ SETUP_STEPS = {
14
+ "install_caddy": "Install Caddy with Homebrew (brew install caddy)",
15
+ "import_line": "Add the import line of hostdev to the Caddyfile of Homebrew",
16
+ "start_service": "Start the Caddy service (brew services start caddy)",
17
+ }
18
+
19
+
20
+ class Menu:
21
+ """A menu on the terminal. ``ask`` reads one line, ``show`` writes one text."""
22
+
23
+ def __init__(self, hostdev, ask=input, show=print):
24
+ self._hostdev = hostdev
25
+ self._ask = ask
26
+ self._show = show
27
+
28
+ @property
29
+ def hostdev(self):
30
+ return self._hostdev
31
+
32
+ def ask(self, prompt):
33
+ return self._ask(prompt).strip()
34
+
35
+ def show(self, text=""):
36
+ self._show(text)
37
+
38
+ def confirm(self, question):
39
+ return self.ask(f"{question} [y/N] ").lower() == "y"
40
+
41
+ def run(self):
42
+ """Show the menu until the user quits. Returns the exit code."""
43
+ self.setup()
44
+ actions = {"s": self.start, "l": self.lan, "x": self.stop, "c": self.ca}
45
+ while True:
46
+ rows = self.hostdev.list()
47
+ self.screen(rows)
48
+ try:
49
+ choice = self.ask("> ").lower()
50
+ except EOFError:
51
+ return 0
52
+ if choice == "q":
53
+ return 0
54
+ if choice in actions:
55
+ actions[choice](rows)
56
+
57
+ def setup(self):
58
+ """Ask before each pending setup step, then do it."""
59
+ for step in self.hostdev.pending_steps():
60
+ if not self.confirm(SETUP_STEPS[step] + "?"):
61
+ self.show("Setup is not complete: the links do not work.")
62
+ return
63
+ self.hostdev.setup_step(step)
64
+ self.hostdev.caddy_reload()
65
+
66
+ def screen(self, rows):
67
+ self.show()
68
+ self.show("hostdev")
69
+ self.show()
70
+ if not rows:
71
+ self.show(" No application is running.")
72
+ for number, row in enumerate(rows, 1):
73
+ state = "" if row["alive"] else " (not running)"
74
+ self.show(f" {number} {row['url']} LAN: {row['lan_url'] or 'no'}{state}")
75
+ self.show(ACTIONS)
76
+
77
+ def pick(self, rows):
78
+ """The row of the number that the user gives, or None."""
79
+ answer = self.ask("Number: ")
80
+ if answer.isdigit() and 1 <= int(answer) <= len(rows):
81
+ return rows[int(answer) - 1]
82
+ self.show("No such number.")
83
+ return None
84
+
85
+ def report(self, result):
86
+ """Show the result of one operation."""
87
+ if "error" in result:
88
+ self.show(result["error"])
89
+ self.show(result.get("tail", ""))
90
+ return
91
+ self.show(result["url"])
92
+ if result["lan_url"]:
93
+ self.show(result["lan_url"])
94
+ if result["caddy_error"]:
95
+ self.show(f"Caddy: {result['caddy_error']}")
96
+
97
+ def start(self, rows):
98
+ cwd = os.getcwd()
99
+ if not self.hostdev.launch_path(cwd).exists():
100
+ self.show("This folder has no .claude/launch.json. Give the start command.")
101
+ command = shlex.split(self.ask("Command, with its port (app --port 8000): "))
102
+ port = int(self.ask("Port in the command: "))
103
+ path = self.ask("Page to open [/]: ") or "/"
104
+ self.hostdev.write_launch(cwd, Path(cwd).name, command, port, path)
105
+ instance = self.ask("Instance (empty for none): ") or None
106
+ lan = self.confirm("Put it on the LAN?")
107
+ self.show("Starting...")
108
+ self.report({"caddy_error": None,
109
+ **self.hostdev.start(cwd=cwd, instance=instance, lan=lan)})
110
+
111
+ def lan(self, rows):
112
+ row = self.pick(rows)
113
+ if row:
114
+ self.report(self.hostdev.lan(row["host"], row["lan_url"] is None))
115
+
116
+ def stop(self, rows):
117
+ row = self.pick(rows)
118
+ if row:
119
+ self.hostdev.stop(row["host"])
120
+ self.show(f"Stopped {row['host']}.")
121
+
122
+ def ca(self, rows):
123
+ self.show("The AirDrop panel opens on the Mac.")
124
+ result = self.hostdev.ca()
125
+ if "error" in result:
126
+ self.show(result["error"])
127
+ return
128
+ for step in result["steps"]:
129
+ self.show(f" - {step}")
hostdev/mdns.py ADDED
@@ -0,0 +1,71 @@
1
+ """Publish a ``.local`` name on the LAN as an mDNS CNAME of the name of this Mac.
2
+
3
+ macOS keeps the address of the name of the Mac up to date on each network. The CNAME
4
+ record holds no address, thus the alias follows the Mac when the network changes.
5
+ The record stays published while the process runs.
6
+ """
7
+ import ctypes
8
+ import subprocess
9
+
10
+ DNS_SD_LIBRARY = "/usr/lib/libSystem.B.dylib"
11
+ FLAG_UNIQUE = 0x20 # kDNSServiceFlagsUnique: a second owner of the name is a conflict
12
+ TYPE_CNAME = 5
13
+ CLASS_IN = 1
14
+ TTL = 120
15
+ CALLBACK = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint32,
16
+ ctypes.c_int32, ctypes.c_void_p)
17
+
18
+
19
+ def wire(name):
20
+ """The DNS wire format of a name: each label with its length, then a zero byte."""
21
+ return b"".join(bytes([len(part)]) + part.encode() for part in name.split(".")) + b"\0"
22
+
23
+
24
+ def local_host_name():
25
+ """The mDNS name of this Mac, for example ``my-mac.local``."""
26
+ done = subprocess.run(["scutil", "--get", "LocalHostName"], capture_output=True,
27
+ text=True, check=True)
28
+ return done.stdout.strip() + ".local"
29
+
30
+
31
+ class CnamePublisher:
32
+ """One CNAME record: ``alias`` points to ``target``."""
33
+
34
+ def __init__(self, alias, target):
35
+ self._alias = alias
36
+ self._target = target
37
+ self._error = 0
38
+ self._callback = CALLBACK(self.registered)
39
+
40
+ @property
41
+ def alias(self):
42
+ return self._alias
43
+
44
+ @property
45
+ def target(self):
46
+ return self._target
47
+
48
+ @property
49
+ def error(self):
50
+ return self._error
51
+
52
+ def registered(self, connection, record, flags, error, context):
53
+ """The answer of mDNSResponder to the registration."""
54
+ self._error = error
55
+
56
+ def run(self):
57
+ """Register the record and keep it. Return the dns_sd error code when one occurs."""
58
+ library = ctypes.CDLL(DNS_SD_LIBRARY)
59
+ connection = ctypes.c_void_p()
60
+ error = library.DNSServiceCreateConnection(ctypes.byref(connection))
61
+ if error:
62
+ return error
63
+ record = ctypes.c_void_p()
64
+ data = wire(self.target)
65
+ error = library.DNSServiceRegisterRecord(
66
+ connection, ctypes.byref(record), ctypes.c_uint32(FLAG_UNIQUE), ctypes.c_uint32(0),
67
+ self.alias.encode(), ctypes.c_uint16(TYPE_CNAME), ctypes.c_uint16(CLASS_IN),
68
+ ctypes.c_uint16(len(data)), data, ctypes.c_uint32(TTL), self._callback, None)
69
+ while not error:
70
+ error = library.DNSServiceProcessResult(connection) or self.error
71
+ return error
hostdev/py.typed ADDED
File without changes
@@ -0,0 +1,170 @@
1
+ Metadata-Version: 2.5
2
+ Name: hostdev
3
+ Version: 0.2.0
4
+ Summary: Serve local development servers at https://<name>.localhost and on the LAN, through Caddy.
5
+ Project-URL: Repository, https://github.com/genro/hostdev
6
+ Author: Giovanni Porcari
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: caddy,development,https,localhost,mdns
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Software Development
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+
20
+ # hostdev
21
+
22
+ Serve local development servers at `https://<name>.localhost`, and on the local network at
23
+ `https://<name>.local`.
24
+
25
+ Start a project and get a link such as `https://myapp.localhost/app/`. You never choose or
26
+ remember a port. Several instances of the same project get their own host:
27
+ `https://v1.myapp.localhost/`. With `--lan`, a phone on the same Wi-Fi opens
28
+ `https://myapp.local/app/`.
29
+
30
+ hostdev is a command for the terminal and a plugin for Claude Code.
31
+
32
+ Requirements: macOS, Homebrew, Python 3.9 or later.
33
+
34
+ ## How it works
35
+
36
+ - The start command of a project is in its `.claude/launch.json`: `runtimeExecutable`,
37
+ `runtimeArgs`, `port` and `path` (the page to open). You can also give the command on
38
+ the command line.
39
+ - `hostdev start` chooses a free port in 8100-8199. It replaces the port of the command
40
+ with the chosen port, sets `PORT` and starts the command.
41
+ - When the port listens, it writes one Caddy site file for the host and reloads Caddy.
42
+ Caddy serves the host with a certificate of its local CA (`tls internal`).
43
+ - macOS resolves every `*.localhost` name to localhost. No DNS setup is necessary.
44
+ - A start of a host that is already running returns the running one.
45
+
46
+ ### On the local network
47
+
48
+ - With `--lan`, the host gets a second name, `<name>.local`. An instance joins the name
49
+ with a hyphen: `v1-myapp.local`.
50
+ - One process for each host publishes the name through mDNS (Bonjour), as an alias of the
51
+ name of the Mac. The record holds no address: the name follows the Mac when the network
52
+ changes.
53
+ - Each device of the same network can open the application. Use `--lan` only on a network
54
+ that you trust.
55
+ - A phone accepts the certificate after you install the local CA of Caddy on it, once for
56
+ each Mac. `hostdev ca` sends the certificate with AirDrop.
57
+
58
+ ## Install
59
+
60
+ As a command:
61
+
62
+ ```bash
63
+ uv tool install git+https://github.com/genro/hostdev
64
+ ```
65
+
66
+ As a Claude Code plugin:
67
+
68
+ ```bash
69
+ claude plugin marketplace add genro/hostdev
70
+ ```
71
+
72
+ ```bash
73
+ claude plugin install hostdev@hostdev
74
+ ```
75
+
76
+ The plugin needs no other installation: it runs the package from its own folder.
77
+
78
+ ## Setup, once for each Mac
79
+
80
+ ```bash
81
+ hostdev setup
82
+ ```
83
+
84
+ `setup` installs Caddy with Homebrew, adds one import line to the Caddyfile of Homebrew
85
+ and starts the Caddy service. Then start one application and run:
86
+
87
+ ```bash
88
+ caddy trust
89
+ ```
90
+
91
+ `caddy trust` installs the local CA in the Keychain. macOS asks for your password.
92
+
93
+ ## Use from the terminal
94
+
95
+ `hostdev` with no argument opens a menu: start the project of the folder, put a host on
96
+ the LAN, stop a host, send the CA to the iPhone. On a new Mac the menu asks before each
97
+ setup step.
98
+
99
+ The commands:
100
+
101
+ ```
102
+ hostdev start [--cwd DIR] [--name NAME] [--instance INSTANCE] [--config CONFIG] [--lan]
103
+ hostdev start [...] --port PORT [--path PATH] -- COMMAND [ARG ...]
104
+ hostdev stop HOST
105
+ hostdev lan HOST on|off
106
+ hostdev list
107
+ hostdev ca
108
+ hostdev check
109
+ hostdev setup
110
+ ```
111
+
112
+ Each command writes one JSON line. An example with no `launch.json`:
113
+
114
+ ```bash
115
+ hostdev start --lan --port 8000 -- uvicorn app:application --port 8000
116
+ ```
117
+
118
+ ## Use from Claude
119
+
120
+ - "start it" / "avvialo" — start the project of the working directory.
121
+ - "start it as v1" — start an instance at `v1.<name>.localhost`.
122
+ - "open it on my phone" / "aprilo sul telefono" — put it on the LAN.
123
+ - "stop it" / "fermalo"
124
+ - "what is running" / "cosa gira"
125
+
126
+ ## The iPhone, once for each Mac
127
+
128
+ 1. Run `hostdev ca`. The AirDrop panel opens on the Mac. Select the iPhone.
129
+ 2. On the iPhone: Settings > Profile Downloaded > Install.
130
+ 3. On the iPhone: Settings > General > About > Certificate Trust Settings. Enable
131
+ "Caddy Local Authority".
132
+
133
+ After that, each `https://<name>.local` host of that Mac is valid on the iPhone.
134
+
135
+ ## Example launch.json
136
+
137
+ ```json
138
+ {
139
+ "version": "0.0.1",
140
+ "configurations": [
141
+ {
142
+ "name": "myapp",
143
+ "runtimeExecutable": "env",
144
+ "runtimeArgs": ["DEBUG=1", "op", "run", "--env-file", "keys.env", "--",
145
+ ".venv/bin/python", "-m", "myapp", "--port", "8000"],
146
+ "port": 8000,
147
+ "path": "/app/"
148
+ }
149
+ ]
150
+ }
151
+ ```
152
+
153
+ ## Files written on your Mac
154
+
155
+ - `<brew prefix>/etc/Caddyfile`: one import line.
156
+ - `~/.local/state/hostdev/`: `instances.json`, `sites/<host>.caddy`, `logs/<host>.log`.
157
+ - `<project>/.claude/launch.json`: only when the menu asks you for the start command.
158
+
159
+ ## Development
160
+
161
+ ```bash
162
+ uv run --group dev pytest
163
+ ```
164
+
165
+ The tests start real processes. They do not reload Caddy and do not publish names on the
166
+ network.
167
+
168
+ ## License
169
+
170
+ Apache-2.0
@@ -0,0 +1,13 @@
1
+ hostdev/__init__.py,sha256=iTdiN_UtMtX6sf2ktKMep16H6qVFYWI5W_GLy4YlaTk,89
2
+ hostdev/__main__.py,sha256=nKqPCjXdmNIrEF7XYEFjhtxe21Vq9zRfQaHYtfJCPAQ,121
3
+ hostdev/airdrop.swift,sha256=Mv98b83iDkuAfin8JTSmUm82XbpLx8St-RbccH--9ms,821
4
+ hostdev/cli.py,sha256=OpALjsR9Rwd8FkBzA-u8KiAuGF0LwByJk8fBBi4nlK8,3126
5
+ hostdev/core.py,sha256=nQbd35hI1ekxYlo2Cgk4HWqR5I34lH-UILr2_UgPZSI,14522
6
+ hostdev/interactive.py,sha256=jzRP0Df01Xmc_Kb496BbxEPVeAseQVgeILWtd2BzXso,4416
7
+ hostdev/mdns.py,sha256=AGwIAQ-sAbr6vIMF6bHZ-9yGzRgMnTE-bX39v4ftCJ8,2564
8
+ hostdev/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ hostdev-0.2.0.dist-info/METADATA,sha256=6aNu3-6DWiNggxme1zlFhNjwLbQVF6jFLPJngkJRXCE,5185
10
+ hostdev-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ hostdev-0.2.0.dist-info/entry_points.txt,sha256=4iUHoUm0irBjEhnsOywuKmisTvLEqeCJ_dRN2QSsTGQ,45
12
+ hostdev-0.2.0.dist-info/licenses/LICENSE,sha256=cXHchnnJ1eh89mx5Q2bNPTJ0r9Mr3vpJNzUtOw59yPE,11339
13
+ hostdev-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ hostdev = hostdev.cli:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Support. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Giovanni Porcari
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.