touchop 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.
touchop/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """touchop: Touch ID-gated 1Password CLI bridge for remote machines and agents."""
2
+
3
+ __version__ = "0.1.0"
Binary file
touchop/cli.py ADDED
@@ -0,0 +1,431 @@
1
+ """Unified CLI for touchop: init-host, init-client, serve, allow/revoke, doctor, uninstall."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import pathlib
9
+ import platform
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import urllib.request
14
+
15
+ from . import __version__
16
+ from .config import (
17
+ DEFAULT_PORT,
18
+ LAUNCHD_LABEL,
19
+ SYSTEMD_SERVICE_NAME,
20
+ client_urls_path,
21
+ config_dir,
22
+ detect_op_binary,
23
+ detect_tailscale_ipv4,
24
+ ensure_token,
25
+ host_config_path,
26
+ load_host_config,
27
+ save_host_config,
28
+ token_path,
29
+ write_secret_file,
30
+ )
31
+ from .macos_app import app_bundle_path, build_macos_app_bundle
32
+ from .server import TouchopServer
33
+
34
+
35
+ def _launchd_plist_path() -> pathlib.Path:
36
+ return pathlib.Path.home() / "Library" / "LaunchAgents" / f"{LAUNCHD_LABEL}.plist"
37
+
38
+
39
+ def _systemd_unit_path() -> pathlib.Path:
40
+ return pathlib.Path.home() / ".config" / "systemd" / "user" / SYSTEMD_SERVICE_NAME
41
+
42
+
43
+ def _install_host_service() -> str:
44
+ py_exe = sys.executable
45
+ pkg_parent = str(pathlib.Path(__file__).resolve().parent.parent)
46
+ if platform.system() == "Darwin":
47
+ plist_path = _launchd_plist_path()
48
+ log_dir = pathlib.Path.home() / "Library" / "Logs"
49
+ log_dir.mkdir(parents=True, exist_ok=True)
50
+ bundle_exe = build_macos_app_bundle()
51
+ if bundle_exe:
52
+ prog_args = [str(bundle_exe), py_exe, "-m", "touchop.cli", "serve"]
53
+ else:
54
+ prog_args = [py_exe, "-m", "touchop.cli", "serve"]
55
+ args_xml = "\n".join(f" <string>{a}</string>" for a in prog_args)
56
+ plist = f"""<?xml version="1.0" encoding="UTF-8"?>
57
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
58
+ <plist version="1.0">
59
+ <dict>
60
+ <key>Label</key>
61
+ <string>{LAUNCHD_LABEL}</string>
62
+ <key>ProgramArguments</key>
63
+ <array>
64
+ {args_xml}
65
+ </array>
66
+ <key>EnvironmentVariables</key>
67
+ <dict>
68
+ <key>PYTHONPATH</key>
69
+ <string>{pkg_parent}</string>
70
+ </dict>
71
+ <key>LimitLoadToSessionType</key>
72
+ <string>Aqua</string>
73
+ <key>RunAtLoad</key>
74
+ <true/>
75
+ <key>KeepAlive</key>
76
+ <true/>
77
+ <key>ThrottleInterval</key>
78
+ <integer>5</integer>
79
+ <key>StandardOutPath</key>
80
+ <string>{log_dir / "touchop-bridge.stdout.log"}</string>
81
+ <key>StandardErrorPath</key>
82
+ <string>{log_dir / "touchop-bridge.stderr.log"}</string>
83
+ </dict>
84
+ </plist>
85
+ """
86
+ plist_path.parent.mkdir(parents=True, exist_ok=True)
87
+ plist_path.write_text(plist, encoding="utf-8")
88
+ uid = os.getuid()
89
+ subprocess.run(["launchctl", "bootout", f"gui/{uid}/{LAUNCHD_LABEL}"], capture_output=True)
90
+ res = subprocess.run(["launchctl", "bootstrap", f"gui/{uid}", str(plist_path)], capture_output=True, text=True)
91
+ if res.returncode != 0:
92
+ raise RuntimeError(f"launchctl bootstrap failed: {res.stderr.strip()}")
93
+ bundle_note = f", app bundle {app_bundle_path()}" if bundle_exe else ""
94
+ return f"macOS Aqua LaunchAgent loaded ({plist_path}{bundle_note})"
95
+
96
+ if platform.system() == "Linux":
97
+ unit_path = _systemd_unit_path()
98
+ unit = f"""[Unit]
99
+ Description=touchop biometric 1Password CLI bridge
100
+ After=network-online.target
101
+
102
+ [Service]
103
+ Type=simple
104
+ Environment=PYTHONPATH={pkg_parent}
105
+ ExecStart={py_exe} -m touchop.cli serve
106
+ Restart=always
107
+ RestartSec=5
108
+
109
+ [Install]
110
+ WantedBy=default.target
111
+ """
112
+ unit_path.parent.mkdir(parents=True, exist_ok=True)
113
+ unit_path.write_text(unit, encoding="utf-8")
114
+ subprocess.run(["systemctl", "--user", "daemon-reload"], check=False)
115
+ subprocess.run(["systemctl", "--user", "enable", "--now", SYSTEMD_SERVICE_NAME], check=False)
116
+ return f"Linux systemd user service installed ({unit_path})"
117
+
118
+ return "auto-service not supported on this OS; run `touchop serve` manually"
119
+
120
+
121
+ def _reload_host_service() -> None:
122
+ if platform.system() == "Darwin" and _launchd_plist_path().exists():
123
+ uid = os.getuid()
124
+ subprocess.run(["launchctl", "kickstart", "-k", f"gui/{uid}/{LAUNCHD_LABEL}"], capture_output=True)
125
+ elif platform.system() == "Linux" and _systemd_unit_path().exists():
126
+ subprocess.run(["systemctl", "--user", "restart", SYSTEMD_SERVICE_NAME], capture_output=True)
127
+
128
+
129
+ def cmd_init_host(args: argparse.Namespace) -> int:
130
+ cfg = load_host_config()
131
+
132
+ bind_host = args.bind
133
+ if not bind_host:
134
+ ts_ip = detect_tailscale_ipv4()
135
+ bind_host = ts_ip or "127.0.0.1"
136
+
137
+ cfg["bind_host"] = bind_host
138
+ cfg["port"] = args.port
139
+
140
+ allowed_ips = list(cfg.get("allowed_ips", []))
141
+ for ip in ["127.0.0.1", bind_host, *(args.allow_ip or [])]:
142
+ if ip and ip not in allowed_ips:
143
+ allowed_ips.append(ip)
144
+ cfg["allowed_ips"] = allowed_ips
145
+
146
+ if args.allow_node:
147
+ nodes = list(cfg.get("allowed_tailscale_nodes", []))
148
+ for n in args.allow_node:
149
+ if n not in nodes:
150
+ nodes.append(n)
151
+ cfg["allowed_tailscale_nodes"] = nodes
152
+
153
+ if args.allow_vault:
154
+ vaults = list(cfg.get("allowed_vaults", []))
155
+ for v in args.allow_vault:
156
+ if v not in vaults:
157
+ vaults.append(v)
158
+ cfg["allowed_vaults"] = vaults
159
+
160
+ if args.account is not None:
161
+ cfg["default_account"] = args.account
162
+
163
+ if args.require_confirm:
164
+ cfg["require_confirm"] = True
165
+
166
+ op_bin = args.op_bin or detect_op_binary()
167
+ if not op_bin:
168
+ sys.stderr.write("error: 1Password CLI (`op`) not found. Install it first (e.g. `brew install 1password-cli`).\n")
169
+ return 1
170
+ cfg["op_bin"] = op_bin
171
+
172
+ tok = ensure_token(force=args.rotate_token)
173
+ cfg_file = save_host_config(cfg)
174
+
175
+ print(f"Configured touchop host:")
176
+ print(f" Config: {cfg_file}")
177
+ print(f" Token: {token_path()} (mode 0600)")
178
+ print(f" Bind: http://{cfg['bind_host']}:{cfg['port']}")
179
+ print(f" op binary: {cfg['op_bin']}")
180
+ print(f" Allowed IPs: {', '.join(cfg['allowed_ips'])}")
181
+ if cfg["allowed_vaults"]:
182
+ print(f" Allowed vaults: {', '.join(cfg['allowed_vaults'])}")
183
+ if cfg["require_confirm"]:
184
+ print(f" Host confirm: enabled (per-request dialog)")
185
+
186
+ if not args.no_service:
187
+ status = _install_host_service()
188
+ print(f" Service: {status}")
189
+
190
+ print("\nNext steps on each remote client:")
191
+ print(f" 1. Add the client's Tailscale IP here: touchop allow-ip <CLIENT_TAILSCALE_IP>")
192
+ print(f" 2. Copy {token_path()} securely to the client and run:")
193
+ print(f" touchop init-client --url http://{cfg['bind_host']}:{cfg['port']} --token-file /path/to/token")
194
+ if args.show_token:
195
+ print(f"\nBearer token (--show-token requested):\n {tok}")
196
+ return 0
197
+
198
+
199
+ def cmd_init_client(args: argparse.Namespace) -> int:
200
+ urls = [u.strip().rstrip("/") for u in args.url if u.strip()]
201
+ if not urls:
202
+ sys.stderr.write("error: at least one --url is required.\n")
203
+ return 1
204
+
205
+ if args.token_stdin:
206
+ tok = sys.stdin.read().strip()
207
+ elif args.token_file:
208
+ tok = pathlib.Path(args.token_file).expanduser().read_text(encoding="utf-8").strip()
209
+ else:
210
+ sys.stderr.write("error: pass --token-file <path> or --token-stdin (avoid passing secrets on CLI argv).\n")
211
+ return 1
212
+
213
+ if not tok:
214
+ sys.stderr.write("error: bridge token is empty.\n")
215
+ return 1
216
+
217
+ write_secret_file(token_path(), tok + "\n")
218
+ write_secret_file(client_urls_path(), "\n".join(urls) + "\n")
219
+
220
+ bin_dir = pathlib.Path(args.bin_dir).expanduser()
221
+ bin_dir.mkdir(parents=True, exist_ok=True)
222
+ shim_path = bin_dir / "op"
223
+
224
+ # Generate an executable shim that invokes touchop.shim with this exact Python interpreter.
225
+ py_exe = sys.executable
226
+ pkg_parent = str(pathlib.Path(__file__).resolve().parent.parent)
227
+ shim_code = f"""#!{py_exe}
228
+ # TOUCHOP_SHIM_MARKER
229
+ import sys
230
+ sys.path.insert(0, {pkg_parent!r})
231
+ from touchop.shim import main
232
+ raise SystemExit(main())
233
+ """
234
+ shim_path.write_text(shim_code, encoding="utf-8")
235
+ os.chmod(shim_path, 0o755)
236
+
237
+ print("Configured touchop client:")
238
+ print(f" Shim installed: {shim_path}")
239
+ print(f" Bridge URLs: {', '.join(urls)}")
240
+ print(f" Token file: {token_path()} (mode 0600)")
241
+
242
+ which_op = shutil.which("op")
243
+ if which_op and pathlib.Path(which_op).resolve() != shim_path.resolve():
244
+ print(
245
+ f"\nWARNING: `which op` currently resolves to {which_op} instead of {shim_path}.\n"
246
+ f'Add `export PATH="{bin_dir}:$PATH"` near the end of your shell profile (~/.zshrc or ~/.bashrc).'
247
+ )
248
+ elif not which_op:
249
+ print(f'\nAdd `export PATH="{bin_dir}:$PATH"` to your shell profile so `op` resolves to {shim_path}.')
250
+
251
+ ts_ip = detect_tailscale_ipv4()
252
+ if ts_ip:
253
+ print(f"\nOn your biometric host, ensure this client's Tailscale IP is allowlisted:")
254
+ print(f" touchop allow-ip {ts_ip}")
255
+ return 0
256
+
257
+
258
+ def cmd_serve(_args: argparse.Namespace) -> int:
259
+ server = TouchopServer()
260
+ server.serve_forever(retry_bind=True)
261
+ return 0
262
+
263
+
264
+ def cmd_modify_list(field: str, value: str, add: bool) -> int:
265
+ cfg = load_host_config()
266
+ items = list(cfg.get(field, []))
267
+ if add:
268
+ if value not in items:
269
+ items.append(value)
270
+ else:
271
+ items = [x for x in items if x != value]
272
+ cfg[field] = items
273
+ save_host_config(cfg)
274
+ _reload_host_service()
275
+ action = "Added" if add else "Removed"
276
+ print(f"{action} {value!r} ({field}={items})")
277
+ return 0
278
+
279
+
280
+ def cmd_doctor(_args: argparse.Namespace) -> int:
281
+ ok = True
282
+ print(f"touchop v{__version__} ({platform.system()} / Python {platform.python_version()})")
283
+ print(f"Config dir: {config_dir()}")
284
+
285
+ ts_ip = detect_tailscale_ipv4()
286
+ print(f"Tailscale IPv4: {ts_ip or 'not detected'}")
287
+ print(f"Native op binary: {detect_op_binary() or 'not found'}")
288
+ print(f"PATH `op`: {shutil.which('op') or 'not found'}")
289
+
290
+ if host_config_path().exists():
291
+ cfg = load_host_config()
292
+ print(f"\n[Host] config: {host_config_path()}")
293
+ print(f" Bind: http://{cfg['bind_host']}:{cfg['port']}")
294
+ print(f" Allowed IPs: {cfg.get('allowed_ips')}")
295
+ print(f" Allowed vaults: {cfg.get('allowed_vaults') or '(all)'}")
296
+ if token_path().exists():
297
+ tok = token_path().read_text(encoding="utf-8").strip()
298
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
299
+ url = f"http://{cfg['bind_host']}:{cfg['port']}/health"
300
+ try:
301
+ req = urllib.request.Request(url, headers={"Authorization": f"Bearer {tok}"})
302
+ with opener.open(req, timeout=5) as r:
303
+ print(f" Health check ({url}): OK {r.read().decode()}")
304
+ except Exception as exc:
305
+ print(f" Health check ({url}): FAILED ({exc})")
306
+ ok = False
307
+
308
+ if client_urls_path().exists():
309
+ urls = [ln.strip() for ln in client_urls_path().read_text(encoding="utf-8").splitlines() if ln.strip()]
310
+ print(f"\n[Client] urls: {urls}")
311
+ if token_path().exists():
312
+ tok = token_path().read_text(encoding="utf-8").strip()
313
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
314
+ for u in urls:
315
+ try:
316
+ req = urllib.request.Request(f"{u.rstrip('/')}/health", headers={"Authorization": f"Bearer {tok}"})
317
+ with opener.open(req, timeout=5) as r:
318
+ print(f" Bridge {u}: OK {r.read().decode()}")
319
+ except Exception as exc:
320
+ print(f" Bridge {u}: UNREACHABLE ({exc})")
321
+ ok = False
322
+
323
+ return 0 if ok else 1
324
+
325
+
326
+ def cmd_uninstall(args: argparse.Namespace) -> int:
327
+ if args.mode in {"host", "all"}:
328
+ if platform.system() == "Darwin":
329
+ plist = _launchd_plist_path()
330
+ uid = os.getuid()
331
+ subprocess.run(["launchctl", "bootout", f"gui/{uid}/{LAUNCHD_LABEL}"], capture_output=True)
332
+ if plist.exists():
333
+ plist.unlink()
334
+ print(f"Removed {plist}")
335
+ bundle = app_bundle_path()
336
+ if bundle.exists():
337
+ shutil.rmtree(bundle)
338
+ print(f"Removed {bundle}")
339
+ elif platform.system() == "Linux":
340
+ unit = _systemd_unit_path()
341
+ subprocess.run(["systemctl", "--user", "disable", "--now", SYSTEMD_SERVICE_NAME], capture_output=True)
342
+ if unit.exists():
343
+ unit.unlink()
344
+ print(f"Removed {unit}")
345
+ if host_config_path().exists():
346
+ host_config_path().unlink()
347
+ print(f"Removed {host_config_path()}")
348
+
349
+ if args.mode in {"client", "all"}:
350
+ shim = pathlib.Path(args.bin_dir).expanduser() / "op"
351
+ if shim.exists() and b"TOUCHOP_SHIM_MARKER" in shim.read_bytes()[:256]:
352
+ shim.unlink()
353
+ print(f"Removed shim {shim}")
354
+ if client_urls_path().exists():
355
+ client_urls_path().unlink()
356
+ print(f"Removed {client_urls_path()}")
357
+
358
+ if args.mode == "all" and token_path().exists():
359
+ token_path().unlink()
360
+ print(f"Removed {token_path()}")
361
+
362
+ return 0
363
+
364
+
365
+ def build_parser() -> argparse.ArgumentParser:
366
+ p = argparse.ArgumentParser(
367
+ prog="touchop",
368
+ description="Touch ID-gated 1Password CLI bridge for remote machines and AI agents.",
369
+ )
370
+ p.add_argument("-V", "--version", action="version", version=f"touchop {__version__}")
371
+ sub = p.add_subparsers(dest="command", required=True)
372
+
373
+ ih = sub.add_parser("init-host", help="Initialize biometric host bridge and install LaunchAgent/systemd service")
374
+ ih.add_argument("--bind", help="IP to bind (default: auto-detected Tailscale IPv4, else 127.0.0.1)")
375
+ ih.add_argument("--port", type=int, default=DEFAULT_PORT, help=f"TCP port (default: {DEFAULT_PORT})")
376
+ ih.add_argument("--allow-ip", action="append", help="Client IP or CIDR to allow (repeatable)")
377
+ ih.add_argument("--allow-node", action="append", help="Allowed Tailscale node name via tailscale whois (repeatable)")
378
+ ih.add_argument("--allow-vault", action="append", help="Restrict remote access to specific 1Password vault(s) (repeatable)")
379
+ ih.add_argument("--account", help="Default 1Password account shorthand/URL (e.g. myteam.1password.com)")
380
+ ih.add_argument("--op-bin", help="Explicit path to native 1Password CLI binary")
381
+ ih.add_argument("--require-confirm", action="store_true", help="Prompt a native macOS dialog for every request")
382
+ ih.add_argument("--rotate-token", action="store_true", help="Generate a fresh bearer token")
383
+ ih.add_argument("--show-token", action="store_true", help="Print the bearer token once to stdout")
384
+ ih.add_argument("--no-service", action="store_true", help="Skip installing LaunchAgent / systemd service")
385
+ ih.set_defaults(func=cmd_init_host)
386
+
387
+ ic = sub.add_parser("init-client", help="Install the drop-in `op` shim on a remote VM, container, or secondary Mac")
388
+ ic.add_argument("--url", action="append", required=True, help="Host bridge URL (repeatable for failover)")
389
+ ic.add_argument("--token-file", help="Path to shared bearer token file")
390
+ ic.add_argument("--token-stdin", action="store_true", help="Read shared bearer token from stdin")
391
+ ic.add_argument("--bin-dir", default="~/.local/bin", help="Directory for the `op` shim (default: ~/.local/bin)")
392
+ ic.set_defaults(func=cmd_init_client)
393
+
394
+ sv = sub.add_parser("serve", help="Run the biometric host bridge in the foreground")
395
+ sv.set_defaults(func=cmd_serve)
396
+
397
+ aip = sub.add_parser("allow-ip", help="Allow a client IP or CIDR on the host bridge")
398
+ aip.add_argument("ip", help="IP address or CIDR (e.g. 100.64.0.20)")
399
+ aip.set_defaults(func=lambda a: cmd_modify_list("allowed_ips", a.ip, True))
400
+
401
+ rip = sub.add_parser("revoke-ip", help="Remove a client IP or CIDR from the host bridge")
402
+ rip.add_argument("ip", help="IP address or CIDR")
403
+ rip.set_defaults(func=lambda a: cmd_modify_list("allowed_ips", a.ip, False))
404
+
405
+ av = sub.add_parser("allow-vault", help="Restrict host bridge to include this vault name")
406
+ av.add_argument("vault", help="1Password vault name")
407
+ av.set_defaults(func=lambda a: cmd_modify_list("allowed_vaults", a.vault, True))
408
+
409
+ rv = sub.add_parser("revoke-vault", help="Remove a vault from allowed_vaults")
410
+ rv.add_argument("vault", help="1Password vault name")
411
+ rv.set_defaults(func=lambda a: cmd_modify_list("allowed_vaults", a.vault, False))
412
+
413
+ dr = sub.add_parser("doctor", help="Check host/client configuration, PATH order, and bridge health")
414
+ dr.set_defaults(func=cmd_doctor)
415
+
416
+ un = sub.add_parser("uninstall", help="Uninstall LaunchAgent/systemd service and/or client op shim")
417
+ un.add_argument("--mode", choices=["host", "client", "all"], default="all")
418
+ un.add_argument("--bin-dir", default="~/.local/bin")
419
+ un.set_defaults(func=cmd_uninstall)
420
+
421
+ return p
422
+
423
+
424
+ def main(argv: list[str] | None = None) -> int:
425
+ parser = build_parser()
426
+ args = parser.parse_args(argv)
427
+ return int(args.func(args))
428
+
429
+
430
+ if __name__ == "__main__":
431
+ sys.exit(main())
touchop/config.py ADDED
@@ -0,0 +1,174 @@
1
+ """Configuration, path detection, and secure file I/O for touchop."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import pathlib
8
+ import platform
9
+ import secrets
10
+ import shutil
11
+ import subprocess
12
+ from typing import Any
13
+
14
+ DEFAULT_PORT = 18765
15
+ DEFAULT_TIMEOUT_SECONDS = 120
16
+ DEFAULT_MAX_PAYLOAD_BYTES = 2 * 1024 * 1024
17
+ DEFAULT_RATE_LIMIT_PER_MIN = 60
18
+
19
+ LAUNCHD_LABEL = "dev.touchop.bridge"
20
+ SYSTEMD_SERVICE_NAME = "touchop-bridge.service"
21
+
22
+
23
+ def config_dir() -> pathlib.Path:
24
+ override = os.environ.get("TOUCHOP_CONFIG_DIR")
25
+ if override:
26
+ return pathlib.Path(override).expanduser()
27
+ xdg = os.environ.get("XDG_CONFIG_HOME")
28
+ if xdg:
29
+ return pathlib.Path(xdg).expanduser() / "touchop"
30
+ return pathlib.Path.home() / ".config" / "touchop"
31
+
32
+
33
+ def host_config_path() -> pathlib.Path:
34
+ return config_dir() / "host.json"
35
+
36
+
37
+ def token_path() -> pathlib.Path:
38
+ return config_dir() / "token"
39
+
40
+
41
+ def client_urls_path() -> pathlib.Path:
42
+ return config_dir() / "urls"
43
+
44
+
45
+ def default_log_path() -> pathlib.Path:
46
+ if platform.system() == "Darwin":
47
+ return pathlib.Path.home() / "Library" / "Logs" / "touchop-bridge.log"
48
+ state_home = os.environ.get("XDG_STATE_HOME")
49
+ if state_home:
50
+ return pathlib.Path(state_home).expanduser() / "touchop" / "bridge.log"
51
+ return pathlib.Path.home() / ".local" / "state" / "touchop" / "bridge.log"
52
+
53
+
54
+ def write_secret_file(path: pathlib.Path, content: str) -> None:
55
+ """Create parent dir (0700) and write file strictly with mode 0600."""
56
+ path.parent.mkdir(parents=True, exist_ok=True)
57
+ try:
58
+ os.chmod(path.parent, 0o700)
59
+ except OSError:
60
+ pass
61
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
62
+ fd = os.open(str(path), flags, 0o600)
63
+ try:
64
+ os.write(fd, content.encode("utf-8"))
65
+ finally:
66
+ os.close(fd)
67
+ os.chmod(path, 0o600)
68
+
69
+
70
+ def ensure_token(path: pathlib.Path | None = None, force: bool = False) -> str:
71
+ p = path or token_path()
72
+ if p.exists() and not force:
73
+ existing = p.read_text(encoding="utf-8").strip()
74
+ if existing:
75
+ return existing
76
+ tok = secrets.token_hex(32)
77
+ write_secret_file(p, tok + "\n")
78
+ return tok
79
+
80
+
81
+ def detect_op_binary(exclude: pathlib.Path | None = None) -> str | None:
82
+ """Locate the real native 1Password CLI binary, avoiding our own shim."""
83
+ candidates = [
84
+ "/opt/homebrew/bin/op",
85
+ "/usr/local/bin/op",
86
+ "/usr/bin/op",
87
+ "/bin/op",
88
+ ]
89
+ found = shutil.which("op")
90
+ if found:
91
+ candidates.insert(0, found)
92
+
93
+ excluded_resolved = exclude.resolve() if exclude and exclude.exists() else None
94
+ for cand in candidates:
95
+ p = pathlib.Path(cand)
96
+ if not (p.exists() and os.access(str(p), os.X_OK)):
97
+ continue
98
+ try:
99
+ resolved = p.resolve()
100
+ except OSError:
101
+ resolved = p
102
+ if excluded_resolved and resolved == excluded_resolved:
103
+ continue
104
+ # Avoid selecting a touchop shim script as the real binary
105
+ try:
106
+ head = p.read_bytes()[:256]
107
+ if b"TOUCHOP_SHIM_MARKER" in head:
108
+ continue
109
+ except OSError:
110
+ continue
111
+ return str(p)
112
+ return None
113
+
114
+
115
+ def detect_tailscale_binary() -> str | None:
116
+ for cand in [
117
+ shutil.which("tailscale"),
118
+ "/Applications/Tailscale.app/Contents/MacOS/Tailscale",
119
+ "/opt/homebrew/bin/tailscale",
120
+ "/usr/local/bin/tailscale",
121
+ "/usr/bin/tailscale",
122
+ ]:
123
+ if cand and os.path.exists(cand) and os.access(cand, os.X_OK):
124
+ return cand
125
+ return None
126
+
127
+
128
+ def detect_tailscale_ipv4() -> str | None:
129
+ ts = detect_tailscale_binary()
130
+ if not ts:
131
+ return None
132
+ try:
133
+ proc = subprocess.run([ts, "ip", "-4"], capture_output=True, text=True, timeout=5)
134
+ if proc.returncode == 0:
135
+ lines = [ln.strip() for ln in proc.stdout.splitlines() if ln.strip()]
136
+ if lines:
137
+ return lines[0]
138
+ except Exception:
139
+ return None
140
+ return None
141
+
142
+
143
+ def default_host_config() -> dict[str, Any]:
144
+ return {
145
+ "bind_host": "127.0.0.1",
146
+ "port": DEFAULT_PORT,
147
+ "allowed_ips": ["127.0.0.1"],
148
+ "allowed_tailscale_nodes": [],
149
+ "allowed_vaults": [],
150
+ "default_account": "",
151
+ "require_confirm": False,
152
+ "confirm_timeout_seconds": 30,
153
+ "timeout_seconds": DEFAULT_TIMEOUT_SECONDS,
154
+ "max_payload_bytes": DEFAULT_MAX_PAYLOAD_BYTES,
155
+ "rate_limit_per_minute": DEFAULT_RATE_LIMIT_PER_MIN,
156
+ "op_bin": detect_op_binary() or "/opt/homebrew/bin/op",
157
+ "log_path": str(default_log_path()),
158
+ }
159
+
160
+
161
+ def load_host_config(path: pathlib.Path | None = None) -> dict[str, Any]:
162
+ cfg = default_host_config()
163
+ p = path or host_config_path()
164
+ if p.exists():
165
+ loaded = json.loads(p.read_text(encoding="utf-8"))
166
+ if isinstance(loaded, dict):
167
+ cfg.update(loaded)
168
+ return cfg
169
+
170
+
171
+ def save_host_config(cfg: dict[str, Any], path: pathlib.Path | None = None) -> pathlib.Path:
172
+ p = path or host_config_path()
173
+ write_secret_file(p, json.dumps(cfg, indent=2) + "\n")
174
+ return p