devdoor 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.
@@ -0,0 +1,209 @@
1
+ """Shared OS platform adapter protocol, hosts-file helpers, and runner utilities."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import subprocess
7
+ from collections.abc import Callable, Sequence
8
+ from pathlib import Path
9
+ from typing import Protocol
10
+
11
+ from devdoor.core.router import normalize_host
12
+
13
+ HOST_TAG = "# devdoor"
14
+
15
+ CommandRunner = Callable[[Sequence[str], bytes | None], subprocess.CompletedProcess[str]]
16
+
17
+
18
+ class PlatformAdapterError(RuntimeError):
19
+ """Raised when an OS trust, hosts, or port-forwarding operation fails."""
20
+
21
+
22
+ def default_command_runner(
23
+ cmd: Sequence[str],
24
+ stdin_bytes: bytes | None = None,
25
+ ) -> subprocess.CompletedProcess[str]:
26
+ """Execute ``cmd`` cleanly without invoking a shell."""
27
+ stdin_text = stdin_bytes.decode("utf-8") if stdin_bytes is not None else None
28
+ return subprocess.run(
29
+ list(cmd),
30
+ input=stdin_text,
31
+ capture_output=True,
32
+ text=True,
33
+ check=False,
34
+ )
35
+
36
+
37
+ def run_checked(
38
+ runner: CommandRunner,
39
+ cmd: Sequence[str],
40
+ *,
41
+ stdin_bytes: bytes | None = None,
42
+ error_prefix: str = "Command failed",
43
+ ) -> subprocess.CompletedProcess[str]:
44
+ """Run ``cmd`` via ``runner`` and raise ``PlatformAdapterError`` on non-zero exit."""
45
+ result = runner(cmd, stdin_bytes)
46
+ if result.returncode != 0:
47
+ detail = (result.stderr or result.stdout or "").strip()
48
+ raise PlatformAdapterError(f"{error_prefix} ({' '.join(cmd)}): {detail}")
49
+ return result
50
+
51
+
52
+ class OSPlatformAdapter(Protocol):
53
+ """Cross-platform interface implemented by Darwin, Linux, and Windows adapters."""
54
+
55
+ default_tld: str
56
+
57
+ def is_ca_trusted(self, cert_path: str | None = None) -> bool: ...
58
+
59
+ def trust_ca(self, cert_path: str) -> None: ...
60
+
61
+ def untrust_ca(self, cert_path: str) -> None: ...
62
+
63
+ def add_host(self, hostname: str) -> None: ...
64
+
65
+ def remove_host(self, hostname: str) -> None: ...
66
+
67
+ def remove_all_hosts(self) -> None: ...
68
+
69
+ def list_hosts(self) -> tuple[str, ...]: ...
70
+
71
+ def enable_port_forwarding(self, http_port: int, https_port: int) -> None: ...
72
+
73
+ def disable_port_forwarding(self) -> None: ...
74
+
75
+ def is_port_forwarding_active(self) -> bool: ...
76
+
77
+
78
+ def _parse_devdoor_host_line(line: str) -> str | None:
79
+ if HOST_TAG not in line:
80
+ return None
81
+ before_comment = line.split("#", 1)[0].strip()
82
+ parts = before_comment.split()
83
+ if len(parts) < 2:
84
+ return None
85
+ return normalize_host(parts[1])
86
+
87
+
88
+ def list_managed_hosts(hosts_text: str) -> tuple[str, ...]:
89
+ """Extract all ``# devdoor`` hostnames currently declared in a hosts file."""
90
+ found: list[str] = []
91
+ for line in hosts_text.splitlines():
92
+ host = _parse_devdoor_host_line(line)
93
+ if host and host not in found:
94
+ found.append(host)
95
+ return tuple(found)
96
+
97
+
98
+ def render_hosts_with_added(hosts_text: str, hostname: str) -> str:
99
+ """Return hosts-file contents with ``127.0.0.1 <hostname> # devdoor`` idempotently added."""
100
+ host = normalize_host(hostname)
101
+ if not host:
102
+ raise ValueError(f"Invalid hostname: {hostname!r}")
103
+ if host in list_managed_hosts(hosts_text):
104
+ return hosts_text
105
+
106
+ entry = f"127.0.0.1 {host} {HOST_TAG}"
107
+ if not hosts_text:
108
+ return f"{entry}\n"
109
+ separator = "" if hosts_text.endswith("\n") else "\n"
110
+ return f"{hosts_text}{separator}{entry}\n"
111
+
112
+
113
+ def render_hosts_without_host(hosts_text: str, hostname: str) -> str:
114
+ """Remove ``# devdoor`` lines matching ``hostname``, preserving all unrelated lines."""
115
+ target = normalize_host(hostname)
116
+ kept = [line for line in hosts_text.splitlines() if _parse_devdoor_host_line(line) != target]
117
+ return "\n".join(kept) + ("\n" if kept else "")
118
+
119
+
120
+ def render_hosts_without_all_devdoor(hosts_text: str) -> str:
121
+ """Remove all ``# devdoor``-managed entries while keeping unrelated lines untouched."""
122
+ kept = [line for line in hosts_text.splitlines() if _parse_devdoor_host_line(line) is None]
123
+ return "\n".join(kept) + ("\n" if kept else "")
124
+
125
+
126
+ def _can_write_path_directly(path: Path) -> bool:
127
+ if path.exists():
128
+ return os.access(path, os.W_OK)
129
+ return path.parent.exists() and os.access(path.parent, os.W_OK)
130
+
131
+
132
+ def write_system_text(
133
+ path: Path,
134
+ content: str,
135
+ *,
136
+ runner: CommandRunner,
137
+ use_sudo: bool = True,
138
+ ) -> None:
139
+ """Write text directly if permitted, else pipe via ``sudo tee``."""
140
+ if _can_write_path_directly(path):
141
+ path.parent.mkdir(parents=True, exist_ok=True)
142
+ path.write_text(content, encoding="utf-8")
143
+ return
144
+ cmd = ["sudo", "tee", str(path)] if use_sudo else ["tee", str(path)]
145
+ run_checked(runner, cmd, stdin_bytes=content.encode("utf-8"), error_prefix="Write failed")
146
+
147
+
148
+ def remove_system_file(
149
+ path: Path,
150
+ *,
151
+ runner: CommandRunner,
152
+ use_sudo: bool = True,
153
+ ) -> None:
154
+ """Remove a system-managed file directly or via ``sudo rm -f``."""
155
+ if not path.exists():
156
+ return
157
+ if _can_write_path_directly(path):
158
+ path.unlink(missing_ok=True)
159
+ return
160
+ cmd = ["sudo", "rm", "-f", str(path)] if use_sudo else ["rm", "-f", str(path)]
161
+ run_checked(runner, cmd, error_prefix="Remove failed")
162
+
163
+
164
+ def mutate_hosts_file(
165
+ hosts_path: Path,
166
+ transform: Callable[[str], str],
167
+ *,
168
+ runner: CommandRunner,
169
+ use_sudo: bool = True,
170
+ ) -> None:
171
+ """Apply ``transform`` to ``hosts_path`` only rewriting when text actually changes."""
172
+ existing = hosts_path.read_text(encoding="utf-8") if hosts_path.is_file() else ""
173
+ updated = transform(existing)
174
+ if updated == existing:
175
+ return
176
+ write_system_text(hosts_path, updated, runner=runner, use_sudo=use_sudo)
177
+
178
+
179
+ class PosixHostsMixin:
180
+ """Shared POSIX ``/etc/hosts`` adapter methods backed by ``_runner`` and ``_hosts_path``."""
181
+
182
+ _runner: CommandRunner
183
+ _hosts_path: Path
184
+
185
+ def add_host(self, hostname: str) -> None:
186
+ mutate_hosts_file(
187
+ self._hosts_path,
188
+ lambda text: render_hosts_with_added(text, hostname),
189
+ runner=self._runner,
190
+ )
191
+
192
+ def remove_host(self, hostname: str) -> None:
193
+ mutate_hosts_file(
194
+ self._hosts_path,
195
+ lambda text: render_hosts_without_host(text, hostname),
196
+ runner=self._runner,
197
+ )
198
+
199
+ def remove_all_hosts(self) -> None:
200
+ mutate_hosts_file(
201
+ self._hosts_path,
202
+ render_hosts_without_all_devdoor,
203
+ runner=self._runner,
204
+ )
205
+
206
+ def list_hosts(self) -> tuple[str, ...]:
207
+ if not self._hosts_path.is_file():
208
+ return ()
209
+ return list_managed_hosts(self._hosts_path.read_text(encoding="utf-8"))
@@ -0,0 +1,194 @@
1
+ """macOS platform adapter (System Keychain CA, ``/etc/hosts``, and ``pfctl``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import subprocess
8
+ from pathlib import Path
9
+
10
+ from devdoor.core.config import DevDoorPaths, resolve_paths
11
+ from devdoor.platform.base import (
12
+ CommandRunner,
13
+ PosixHostsMixin,
14
+ default_command_runner,
15
+ remove_system_file,
16
+ run_checked,
17
+ write_system_text,
18
+ )
19
+ from devdoor.proxy.certs import ROOT_CA_CN
20
+
21
+ SYSTEM_KEYCHAIN = "/Library/Keychains/System.keychain"
22
+ PF_ANCHOR_NAME = "com.devdoor"
23
+ _TOKEN_RE = re.compile(r"Token\s*:\s*(\S+)")
24
+
25
+
26
+ def _render_pf_anchor(http_port: int, https_port: int) -> str:
27
+ return "".join(
28
+ f"rdr pass on lo0 inet proto tcp from any to 127.0.0.1 port {src} -> 127.0.0.1 port {dst}\n"
29
+ for src, dst in ((80, http_port), (443, https_port))
30
+ )
31
+
32
+
33
+ def _combined_output(proc: subprocess.CompletedProcess[str]) -> str:
34
+ return f"{proc.stdout or ''}\n{proc.stderr or ''}"
35
+
36
+
37
+ def _insert_pf_anchor_lines(pf_conf_text: str, anchor_path: Path) -> str:
38
+ rdr_line = f'rdr-anchor "{PF_ANCHOR_NAME}"'
39
+ load_line = f'load anchor "{PF_ANCHOR_NAME}" from "{anchor_path}"'
40
+ lines = pf_conf_text.splitlines()
41
+ has_rdr = any(line.strip() == rdr_line for line in lines)
42
+ has_load = any(line.strip() == load_line for line in lines)
43
+ if has_rdr and has_load:
44
+ return pf_conf_text
45
+
46
+ cleaned = [line for line in lines if PF_ANCHOR_NAME not in line]
47
+ new_lines: list[str] = []
48
+ inserted_rdr = False
49
+ for line in cleaned:
50
+ new_lines.append(line)
51
+ if not inserted_rdr and line.strip().startswith("rdr-anchor"):
52
+ new_lines.append(rdr_line)
53
+ inserted_rdr = True
54
+ if not inserted_rdr:
55
+ new_lines.append(rdr_line)
56
+ new_lines.append(load_line)
57
+ return "\n".join(new_lines) + "\n"
58
+
59
+
60
+ def _remove_pf_anchor_lines(pf_conf_text: str) -> str:
61
+ kept = [line for line in pf_conf_text.splitlines() if PF_ANCHOR_NAME not in line]
62
+ return "\n".join(kept) + ("\n" if kept else "")
63
+
64
+
65
+ class DarwinAdapter(PosixHostsMixin):
66
+ """macOS privilege adapter wrapping ``security``, ``/etc/hosts``, and ``pfctl``."""
67
+
68
+ default_tld = ".test"
69
+
70
+ def __init__(
71
+ self,
72
+ *,
73
+ runner: CommandRunner = default_command_runner,
74
+ paths: DevDoorPaths | None = None,
75
+ hosts_path: Path = Path("/etc/hosts"),
76
+ pf_conf_path: Path = Path("/etc/pf.conf"),
77
+ pf_anchor_path: Path = Path(f"/etc/pf.anchors/{PF_ANCHOR_NAME}"),
78
+ pf_token_path: Path | None = None,
79
+ ) -> None:
80
+ self._runner = runner
81
+ self._paths = paths or resolve_paths()
82
+ self._hosts_path = hosts_path
83
+ self._pf_conf_path = pf_conf_path
84
+ self._pf_anchor_path = pf_anchor_path
85
+ self._pf_token_path = pf_token_path or (self._paths.home / "pf-token")
86
+
87
+ def is_ca_trusted(self, cert_path: str | None = None) -> bool:
88
+ result = self._runner(
89
+ ("security", "find-certificate", "-c", ROOT_CA_CN, SYSTEM_KEYCHAIN),
90
+ None,
91
+ )
92
+ if result.returncode != 0:
93
+ return False
94
+ if cert_path is not None and Path(cert_path).is_file():
95
+ verify = self._runner(("security", "verify-cert", "-c", cert_path), None)
96
+ if verify.returncode != 0:
97
+ return False
98
+ return True
99
+
100
+ def trust_ca(self, cert_path: str) -> None:
101
+ run_checked(
102
+ self._runner,
103
+ (
104
+ "sudo",
105
+ "security",
106
+ "add-trusted-cert",
107
+ "-d",
108
+ "-r",
109
+ "trustRoot",
110
+ "-k",
111
+ SYSTEM_KEYCHAIN,
112
+ cert_path,
113
+ ),
114
+ error_prefix="Failed to trust DevDoor Root CA",
115
+ )
116
+
117
+ def untrust_ca(self, cert_path: str) -> None:
118
+ self._runner(
119
+ ("sudo", "security", "remove-trusted-cert", "-d", cert_path),
120
+ None,
121
+ )
122
+
123
+ def enable_port_forwarding(self, http_port: int, https_port: int) -> None:
124
+ write_system_text(
125
+ self._pf_anchor_path,
126
+ _render_pf_anchor(http_port, https_port),
127
+ runner=self._runner,
128
+ )
129
+ existing_conf = (
130
+ self._pf_conf_path.read_text(encoding="utf-8") if self._pf_conf_path.is_file() else ""
131
+ )
132
+ updated_conf = _insert_pf_anchor_lines(existing_conf, self._pf_anchor_path)
133
+ if updated_conf != existing_conf:
134
+ write_system_text(self._pf_conf_path, updated_conf, runner=self._runner)
135
+
136
+ run_checked(
137
+ self._runner,
138
+ ("sudo", "pfctl", "-f", str(self._pf_conf_path)),
139
+ error_prefix="Failed to load pf.conf",
140
+ )
141
+ self._ensure_pf_enabled_with_token()
142
+
143
+ def _is_pf_token_active(self, token: str) -> bool:
144
+ if not token:
145
+ return False
146
+ refs = self._runner(("sudo", "pfctl", "-s", "References"), None)
147
+ return refs.returncode == 0 and token in _combined_output(refs)
148
+
149
+ def _ensure_pf_enabled_with_token(self) -> None:
150
+ existing_token = (
151
+ self._pf_token_path.read_text(encoding="utf-8").strip()
152
+ if self._pf_token_path.is_file()
153
+ else ""
154
+ )
155
+ if existing_token and self._is_pf_token_active(existing_token):
156
+ self._runner(("sudo", "pfctl", "-e"), None)
157
+ return
158
+
159
+ enable_res = self._runner(("sudo", "pfctl", "-E"), None)
160
+ combined = _combined_output(enable_res)
161
+ if enable_res.returncode == 0:
162
+ match = _TOKEN_RE.search(combined)
163
+ if match:
164
+ self._pf_token_path.parent.mkdir(parents=True, exist_ok=True)
165
+ self._pf_token_path.write_text(match.group(1), encoding="utf-8")
166
+ if os.name == "posix":
167
+ os.chmod(self._pf_token_path, 0o600)
168
+ return
169
+ self._runner(("sudo", "pfctl", "-e"), None)
170
+
171
+ def disable_port_forwarding(self) -> None:
172
+ if self._pf_conf_path.is_file():
173
+ existing_conf = self._pf_conf_path.read_text(encoding="utf-8")
174
+ updated_conf = _remove_pf_anchor_lines(existing_conf)
175
+ if updated_conf != existing_conf:
176
+ write_system_text(self._pf_conf_path, updated_conf, runner=self._runner)
177
+
178
+ remove_system_file(self._pf_anchor_path, runner=self._runner)
179
+ self._runner(("sudo", "pfctl", "-a", PF_ANCHOR_NAME, "-F", "all"), None)
180
+ if self._pf_conf_path.is_file():
181
+ self._runner(("sudo", "pfctl", "-f", str(self._pf_conf_path)), None)
182
+
183
+ if self._pf_token_path.is_file():
184
+ token = self._pf_token_path.read_text(encoding="utf-8").strip()
185
+ if token:
186
+ self._runner(("sudo", "pfctl", "-X", token), None)
187
+ self._pf_token_path.unlink(missing_ok=True)
188
+
189
+ def is_port_forwarding_active(self) -> bool:
190
+ info = self._runner(("sudo", "pfctl", "-s", "info"), None)
191
+ if info.returncode != 0 or "status: enabled" not in _combined_output(info).lower():
192
+ return False
193
+ res = self._runner(("sudo", "pfctl", "-a", PF_ANCHOR_NAME, "-s", "nat"), None)
194
+ return res.returncode == 0 and "rdr" in _combined_output(res)
@@ -0,0 +1,185 @@
1
+ """Linux platform adapter (CA trust stores, ``/etc/hosts``, ``iptables``/``nft``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ from collections.abc import Callable, Sequence
7
+ from pathlib import Path
8
+
9
+ from devdoor.platform.base import (
10
+ CommandRunner,
11
+ PlatformAdapterError,
12
+ PosixHostsMixin,
13
+ default_command_runner,
14
+ remove_system_file,
15
+ run_checked,
16
+ write_system_text,
17
+ )
18
+
19
+ DEFAULT_CA_ANCHOR_DIRS: tuple[tuple[Path, tuple[str, ...], tuple[str, ...]], ...] = (
20
+ (
21
+ Path("/usr/local/share/ca-certificates"),
22
+ ("update-ca-certificates",),
23
+ ("update-ca-certificates", "--fresh"),
24
+ ),
25
+ (
26
+ Path("/etc/pki/ca-trust/source/anchors"),
27
+ ("update-ca-trust", "extract"),
28
+ ("update-ca-trust", "extract"),
29
+ ),
30
+ (
31
+ Path("/etc/ca-certificates/trust-source/anchors"),
32
+ ("trust", "extract-compat"),
33
+ ("trust", "extract-compat"),
34
+ ),
35
+ )
36
+
37
+ IPTABLES_CHAIN = "DEVDOOR"
38
+ _OUTPUT_JUMP_SPEC = ("-o", "lo", "-d", "127.0.0.1/32", "-j", IPTABLES_CHAIN)
39
+ _MAX_JUMP_CLEANUP = 32
40
+
41
+
42
+ class LinuxAdapter(PosixHostsMixin):
43
+ """Linux privilege adapter handling distro CA stores, hosts, and NAT port redirection."""
44
+
45
+ default_tld = ".test"
46
+
47
+ def __init__(
48
+ self,
49
+ *,
50
+ runner: CommandRunner = default_command_runner,
51
+ hosts_path: Path = Path("/etc/hosts"),
52
+ ca_anchor_dirs: Sequence[
53
+ tuple[Path, tuple[str, ...], tuple[str, ...]]
54
+ ] = DEFAULT_CA_ANCHOR_DIRS,
55
+ which_fn: Callable[[str], str | None] = shutil.which,
56
+ ) -> None:
57
+ self._runner = runner
58
+ self._hosts_path = hosts_path
59
+ self._ca_anchor_dirs = tuple(ca_anchor_dirs)
60
+ self._which = which_fn
61
+
62
+ def _detect_ca_store(self) -> tuple[Path, tuple[str, ...], tuple[str, ...]]:
63
+ for anchor_dir, install_cmd, refresh_cmd in self._ca_anchor_dirs:
64
+ if anchor_dir.is_dir():
65
+ return anchor_dir, install_cmd, refresh_cmd
66
+ raise PlatformAdapterError("No supported Linux CA trust anchor directory found.")
67
+
68
+ def is_ca_trusted(self, cert_path: str | None = None) -> bool:
69
+ try:
70
+ anchor_dir, _, _ = self._detect_ca_store()
71
+ except PlatformAdapterError:
72
+ return False
73
+ target = anchor_dir / "devdoor.crt"
74
+ if not target.is_file():
75
+ return False
76
+ if cert_path is not None and Path(cert_path).is_file():
77
+ return target.read_text(encoding="utf-8") == Path(cert_path).read_text(encoding="utf-8")
78
+ return True
79
+
80
+ def trust_ca(self, cert_path: str) -> None:
81
+ anchor_dir, install_cmd, _ = self._detect_ca_store()
82
+ pem = Path(cert_path).read_text(encoding="utf-8")
83
+ write_system_text(anchor_dir / "devdoor.crt", pem, runner=self._runner)
84
+ run_checked(
85
+ self._runner,
86
+ ("sudo", *install_cmd),
87
+ error_prefix="Failed to update Linux CA trust store",
88
+ )
89
+
90
+ def untrust_ca(self, cert_path: str) -> None:
91
+ del cert_path
92
+ anchor_dir, _, refresh_cmd = self._detect_ca_store()
93
+ remove_system_file(anchor_dir / "devdoor.crt", runner=self._runner)
94
+ self._runner(("sudo", *refresh_cmd), None)
95
+
96
+ def enable_port_forwarding(self, http_port: int, https_port: int) -> None:
97
+ if self._which("iptables") is not None:
98
+ self._runner(("sudo", "iptables", "-t", "nat", "-N", IPTABLES_CHAIN), None)
99
+ run_checked(self._runner, ("sudo", "iptables", "-t", "nat", "-F", IPTABLES_CHAIN))
100
+ for src_port, dst_port in ((80, http_port), (443, https_port)):
101
+ run_checked(
102
+ self._runner,
103
+ (
104
+ "sudo",
105
+ "iptables",
106
+ "-t",
107
+ "nat",
108
+ "-A",
109
+ IPTABLES_CHAIN,
110
+ "-p",
111
+ "tcp",
112
+ "--dport",
113
+ str(src_port),
114
+ "-j",
115
+ "REDIRECT",
116
+ "--to-ports",
117
+ str(dst_port),
118
+ ),
119
+ )
120
+ check = self._runner(
121
+ ("sudo", "iptables", "-t", "nat", "-C", "OUTPUT", *_OUTPUT_JUMP_SPEC),
122
+ None,
123
+ )
124
+ if check.returncode != 0:
125
+ run_checked(
126
+ self._runner,
127
+ ("sudo", "iptables", "-t", "nat", "-I", "OUTPUT", "1", *_OUTPUT_JUMP_SPEC),
128
+ )
129
+ return
130
+
131
+ if self._which("nft") is not None:
132
+ rules = (
133
+ "table ip devdoor {\n"
134
+ " chain output {\n"
135
+ " type nat hook output priority -100; policy accept;\n"
136
+ f' oifname "lo" ip daddr 127.0.0.1 tcp dport 80 redirect to :{http_port}\n'
137
+ f' oifname "lo" ip daddr 127.0.0.1 tcp dport 443 redirect to :{https_port}\n'
138
+ " }\n"
139
+ "}\n"
140
+ )
141
+ run_checked(
142
+ self._runner,
143
+ ("sudo", "nft", "-f", "-"),
144
+ stdin_bytes=rules.encode("utf-8"),
145
+ error_prefix="Failed to apply nftables rules",
146
+ )
147
+ return
148
+
149
+ raise PlatformAdapterError("Neither iptables nor nft binary found on PATH.")
150
+
151
+ def disable_port_forwarding(self) -> None:
152
+ if self._which("iptables") is not None:
153
+ for _ in range(_MAX_JUMP_CLEANUP):
154
+ exists = self._runner(
155
+ ("sudo", "iptables", "-t", "nat", "-C", "OUTPUT", *_OUTPUT_JUMP_SPEC),
156
+ None,
157
+ )
158
+ if exists.returncode != 0:
159
+ break
160
+ del_res = self._runner(
161
+ ("sudo", "iptables", "-t", "nat", "-D", "OUTPUT", *_OUTPUT_JUMP_SPEC),
162
+ None,
163
+ )
164
+ if del_res.returncode != 0:
165
+ break
166
+ self._runner(("sudo", "iptables", "-t", "nat", "-F", IPTABLES_CHAIN), None)
167
+ self._runner(("sudo", "iptables", "-t", "nat", "-X", IPTABLES_CHAIN), None)
168
+ return
169
+ if self._which("nft") is not None:
170
+ self._runner(("sudo", "nft", "delete", "table", "ip", "devdoor"), None)
171
+
172
+ def is_port_forwarding_active(self) -> bool:
173
+ if self._which("iptables") is not None:
174
+ chain_res = self._runner(("iptables", "-t", "nat", "-S", IPTABLES_CHAIN), None)
175
+ if chain_res.returncode != 0 or "REDIRECT" not in (chain_res.stdout or ""):
176
+ return False
177
+ jump_res = self._runner(
178
+ ("iptables", "-t", "nat", "-C", "OUTPUT", *_OUTPUT_JUMP_SPEC),
179
+ None,
180
+ )
181
+ return jump_res.returncode == 0
182
+ if self._which("nft") is not None:
183
+ res = self._runner(("nft", "list", "table", "ip", "devdoor"), None)
184
+ return res.returncode == 0 and "redirect" in (res.stdout or "")
185
+ return False