#!/usr/bin/env -S python3 -X utf8
# summary: Read and change firewall settings.
"""starchaser firewall: check your firewall and save its settings.

Common commands
  starchaser firewall apps                list accepted app IDs; paths such as /usr/bin/curl also work
  starchaser firewall summary             explain the firewall's status in plain words
  starchaser firewall state               show all firewall details as JSON
  starchaser firewall log [N]             show recent connection records as JSON; [] = none yet (default: 200)
  starchaser firewall ruleset [--save]    show saved rules, or save a copy in Documents
  starchaser firewall export              save firewall settings in Documents
  starchaser firewall import-check <file> check a settings file without changing anything
  starchaser firewall allow|block <app> [--incoming] [--network ID] [--zone KIND]
  starchaser firewall allow <app> --network ID --for 15m|2h|network
  starchaser firewall trust <network ID>  trust a saved network, using the same Apply and Keep
  starchaser firewall keep|revert         answer the current Keep countdown
  starchaser firewall activity            outgoing observations on this account
  starchaser firewall public-pause on|end  mark networks Public and pause, or restore both

What the fields mean and more commands
Everything Settings > Firewall shows, read without root.

    starchaser firewall [state]        JSON: policy, "reach" (per network zone: what other computers there can
                                       connect to here, from firewall.py), "fleetAccess" (whether a network this
                                       computer is on keeps your fleet out, from the same answer), zones + networks, interfaces (kernel adapters,
                                       including virtual devices and those outside the network list), hit counters, pending commit, history
                                       (each entry: id, time, summary, rules, enabled; undid = the entry a
                                       change that wasn't kept put back over),
                                       apps (the catalog of apps the rules can mention), users, whether the outgoing checker is installed, "live" (whether the
                                       rules are running: loaded, matches the saved policy ("unknown": loaded but not read back), checked = when,
                                       fresh = checked in the last 150 s; outbound = whether the outgoing checker,
                                       which checks outgoing rules, is needed, installed, running, checking connections
                                       and running Starchaser's rules as written: outbound.matches; outbound.paused =
                                       "restart" or "failures" when the checker cannot start, so the app firewall is
                                       paused and nothing is held; stale = the saved
                                       rules came from an older version and are compiled again after an update;
                                       others = other firewall tables that can also turn connections away),
                                       "allowedOnce" (the "Allow for 15 minutes" answers still running: addr,
                                       proto, port, iface (empty = every network), until), "publicPause" (on, networks, ifaces, connections), "asker" (whether the outgoing question can be
                                       shown: serving, error; connected = the outgoing checker pinged it in the last
                                       15 seconds), "newPorts" (ports an app rule's program listens on
                                       now that the loaded rules don't cover), "baseline" (what every
                                       Starchaser firewall allows by default (expert rules can override some defaults)), "baselineTech" (the
                                       interface patterns behind those defaults, for experts), "fleet" (the fleet's networks:
                                       tailscale, vpn, zones, apps), "keepHelper" (Keep / Go
                                       back can be answered without a second password), "forwarding" (this
                                       computer passes traffic on for others, IPv4 or IPv6: virtual machines,
                                       containers), "forwardFiltered" (the saved rules block traffic passing
                                       through, except this computer's own guest networks and hotspot); each app
                                       carries "installed" (one of its programs is on this computer) and
                                       "software" (the id of the Software page's app that installs it, "" when
                                       Software has none: Settings offers "Get it in Software" only then),
                                       "extra" (the hand-written rules file: path, exists, lines, error,
                                       inSaved = the saved rules have those same lines)
    starchaser firewall log [N]        JSON: the last N incoming connections in the log over the last 24 hours,
                                       newest first, N from 1 to 5000 (default 200; reading the log needs an
                                       administrator account; an account that can't read it gets [] and exit
                                       code 3, so "nothing turned away" is never claimed): ones the firewall
                                       turned away, and ones a rule with "Log matches" logged. Each row has:
                                         rule        the rule's id ("" when no rule matched: the default)
                                         action      what was done, as recorded in the line when it was
                                                     written: allow, block or reject; "" for an older line
                                                     that didn't record it
                                         turnedAway  true when the packet was dropped or refused, false when
                                                     it was let in, null when an older line can't tell
                                         actionNow   what today's rule (or default) would do, for older lines
                                                     only; never the same as a recorded fact
                                         ruleName    the rule's name in the applied policy; ruleGone: true when
                                                     the rule has been deleted since
                                         zone        the network kind it came in on, as recorded then
                                                     (trusted, public, vpn, tailscale, other; "" when older)
                                         group       the address group the source is in
                                         currentAllow saved permission covering this attempt now (rule id,
                                                     current zone, policy revision, limited = rate, source-port
                                                     or uncertain match); {} when no saved Allow covers it
    starchaser firewall ruleset        the saved firewall rules, as text, with a first line saying whether
                                       the firewall is on
    starchaser firewall ruleset --save the same, saved to a new file in your Documents folder; JSON {ok, path}
    starchaser firewall export         the saved firewall settings (policy.json), to a new file in your Documents
                                       folder, for importing on this or another computer; JSON {ok, path, warning}.
                                       Includes the hand-written rules file for manual review and restore; import never loads it.
    starchaser firewall import-files   JSON: firewall settings files found in Documents, Downloads and your
                                       home folder, newest first ({path, name, time})
    starchaser firewall import-check <file>
                                       JSON {ok, errors, policy}: the file's settings, checked the way an Apply
                                       checks them (nothing changes; Settings puts them in the page to review)
    starchaser firewall status         same as state
    starchaser firewall summary        the same in a few plain sentences, for a person to read
    starchaser firewall help           this text
Changes ask for your computer password.
Public pause starts immediately. Undo may ask for your password. Add --json for a structured result.
"""
import hashlib
import ipaddress
import json
import os
import pwd
import grp
import re
import shlex
import socket
import errno
import shutil
import subprocess
import sys
import time
import tempfile
import copy
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import safe_streams
from starchaser_firewall_activity import Activity
safe_streams()

POLICY = Path("/etc/starchaser/policy.json")
EXTRA = Path("/etc/starchaser/firewall-extra.nft")
ZONES = Path("/run/starchaser/firewall-zones.json")
STATS = Path("/run/starchaser/firewall-stats.json")
STATS_FRESH = 150                     # seconds a root-side check counts as current (the timer runs every 60)
PENDING = Path("/run/starchaser-firewall.pending")
HISTORY = Path("/var/lib/starchaser/firewall-history")
CATALOG = Path("/usr/local/share/starchaser/firewall-apps.json")
CATALOG_REPO = next((p for p in (Path(__file__).resolve().parent.parent / "config/firewall/apps.json",
                                 Path.home() / ".local/share/starchaser/repo/config/firewall/apps.json",
                                 Path("/usr/share/starchaser/firewall-apps.json")) if p.exists()),
                    Path.home() / ".local/share/starchaser/repo/config/firewall/apps.json")
NFT = Path("/etc/starchaser/firewall.nft")
NFT_OFF = Path("/etc/starchaser/firewall.nft.off")      # the firewall is off: its last rules

# The engine (firewall.py) answers what's reachable, the same way it builds the rules, so Settings never works it out
# itself. The checkout's copy first, like the catalog: it's the one written for this code. Importing it needs no root
# (standard library only, and nothing runs on import). Settings applies changes through
# `pkexec /usr/local/lib/starchaser/starchaser-admin firewall-commit` (the root side).
fw = None
for _lib in (Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
    if (_lib / "firewall.py").is_file():
        sys.path.insert(0, str(_lib))
        try:
            import firewall as fw
        except Exception:                               # an older or broken copy: Settings shows less, not nothing
            fw = None
        break


def jread(p: Path, default):
    try:
        return json.loads(p.read_text())
    except (OSError, ValueError):
        return default


def nmcli(*args) -> str:
    """NetworkManager's answer, or nothing when it isn't installed (no networks to list)."""
    try:
        return subprocess.run(["nmcli", *args], capture_output=True, text=True).stdout
    except OSError:
        return ""


def networks_now() -> list:
    if fw is None:  # Without the engine, we cannot tell which connections belong in its network list.
        return []
    out = nmcli("-t", "-f", "UUID,NAME,TYPE,DEVICE", "connection", "show", "--active")
    nets = []
    for line in out.splitlines():
        f = [x.replace("\0", ":") for x in line.replace("\\:", "\0").split(":")]
        if len(f) >= 4 and f[2] != "loopback" and f[3] != "lo" and not fw.host_only(f[3], managed=True):
            nets.append({"uuid": f[0], "name": f[1], "type": f[2], "device": f[3]})
    return nets


def vpn_endpoints(network):
    kind = network.get('type', '')
    field = 'wireguard.peers' if kind == 'wireguard' else 'vpn.data'
    text = nmcli('-g', field, 'connection', 'show', network['uuid'])
    text = text.replace('\\:', ':')
    candidates = []
    if kind == 'wireguard':
        for value in re.findall(r'endpoint\s*=\s*([^,; }]+)', text):
            address, _, port = value.rpartition(':')
            candidates.append((address.strip('[]'), port, 'udp'))
    else:
        data = dict(re.findall(r'([a-z0-9-]+)\s*=\s*([^,]+)', text))
        candidates.append((data.get('remote', '').strip(), data.get('port', '1194').strip(), 'tcp' if data.get('proto-tcp', '').strip() == 'yes' else 'udp'))
    rows = []
    for address, port, protocol in candidates:
        try:
            address = str(ipaddress.ip_address(address))
            if port.isdigit() and 1 <= int(port) <= 65535: rows.append(dict(address=address, port=int(port), protocol=protocol))
        except ValueError: continue
    return rows


def interfaces_now(networks: list, root: Path = Path("/sys/class/net")) -> list:
    """Kernel adapters, including devices without a saved network connection. Loopback isn't a choice."""
    managed = {n["device"]: n for n in networks if n.get("device")}
    adapters = []
    for path in sorted(root.glob("*")):
        name = path.name
        if name == "lo" or not re.fullmatch(r"[A-Za-z0-9_.:@-]{1,15}", name):
            continue
        virtual = "/virtual/" in str(path.resolve())
        net = managed.get(name)
        kind = "virtual adapter" if virtual else "Wi-Fi" if (path / "wireless").exists() else "network adapter"
        label = (net["name"] + " (" + name + (", virtual adapter" if virtual else "") + ")") if net else name + " (" + kind + ", outside the network list)"
        adapters.append({"device": name, "label": label, "virtual": virtual, "managed": bool(net)})
    return adapters


def subnets() -> dict:
    """{device: ["192.0.2.0/24", ...]}: the networks this computer is on (for suggesting a "Home network" group)."""
    try:
        data = json.loads(subprocess.run(["ip", "-j", "addr"], capture_output=True, text=True).stdout or "[]")
    except (ValueError, OSError):                      # no ip command (OSError): no networks to list
        return {}
    out = {}
    for d in data:
        for a in d.get("addr_info", []):
            if a.get("scope") != "global":
                continue
            try:
                out.setdefault(d["ifname"], []).append(str(ipaddress.ip_interface(f"{a['local']}/{a['prefixlen']}").network))
            except (KeyError, ValueError):
                pass
    return out


def saved_networks() -> list:
    """Saved Wi-Fi and wired connections, excluding unused automatic wired profiles, for Groups > Networks."""
    out = nmcli("-t", "-f", "UUID,NAME,TYPE,DEVICE,TIMESTAMP", "connection", "show")
    nets = []
    for line in out.splitlines():
        f = [x.replace("\0", ":") for x in line.replace("\\:", "\0").split(":")]
        if len(f) >= 5 and f[2] in ("802-11-wireless", "802-3-ethernet", "wifi", "ethernet") and not f[3].startswith(("virbr", "vnet")):
            if f[2] in ("802-3-ethernet", "ethernet") and f[4] == "0" and re.fullmatch(r"Wired connection \d+", f[1]):
                continue
            nets.append({"uuid": f[0], "name": f[1], "type": f[2], "device": f[3]})
    return nets


# Keep the saved-answer scope in step with starchaser-firewall-ask's INTERPRETERS.
INTERPRETERS = re.compile(r"^(python[0-9.]*|pypy[0-9.]*|node(js)?|bun|deno|perl[0-9.]*|ruby[0-9.]*|php[0-9.]*|java"
                          r"|lua(jit)?[0-9.-]*|tclsh[0-9.]*|wish[0-9.]*|g?awk|mawk|R(script)?|julia"
                          r"|sh|bash|zsh|fish|dash|ksh|mksh|tcsh|csh|busybox)$")


ASKED_ERROR = ''


def asked() -> list:
    """Outgoing answers saved by the asker ("Allow always" / "Never"): OpenSnitch's sc-asked-*.json rules."""
    global ASKED_ERROR
    out, records, unreadable = [], [], False
    ASKED_ERROR = ''
    for f in sorted(Path("/etc/opensnitchd/rules").glob("sc-asked-*.json")):
        r = jread(f, None)
        if not isinstance(r, dict) or r.get('action') not in ('allow', 'deny'):
            unreadable = True
            continue
        op = r.get('operator') or {}
        parts = op.get('list') or [op] if isinstance(op, dict) else []
        user = next((str(p.get('data')) for p in parts if isinstance(p, dict) and p.get('operand') == 'user.id'), 'any')
        if user not in ('any', str(os.getuid())): continue
        records.append((f.name, r))
    if unreadable:
        folder = fw.RUN if fw is not None else Path('/run/starchaser')
        snapshot = jread(folder / 'firewall-answers' / (str(os.getuid()) + '.json'), {})
        if isinstance(snapshot, dict) and snapshot.get('uid') == os.getuid() and isinstance(snapshot.get('time'), (int, float)) and 0 <= time.time() - snapshot['time'] < STATS_FRESH and isinstance(snapshot.get('answers'), list):
            records = [(row['file'], row['rule']) for row in snapshot['answers'] if isinstance(row, dict) and isinstance(row.get('file'), str) and re.fullmatch(r'sc-asked-[A-Za-z0-9_.-]+\.json', row['file']) and isinstance(row.get('rule'), dict)]
            ASKED_ERROR = str(snapshot.get('error') or '')
        else:
            ASKED_ERROR = "Saved app answers couldn't be read. Open Firewall again after the next protection check."
    for filename, r in records:
        op = r.get("operator", {})
        if not isinstance(op, dict) or r.get('action') not in ('allow', 'deny'):
            ASKED_ERROR = "Some saved app answers couldn't be read."
            continue
        parts = op.get("list") or [op]
        if not isinstance(parts, list) or not all(isinstance(p, dict) and isinstance(p.get('data', ''), str) for p in parts):
            ASKED_ERROR = "Some saved app answers couldn't be read."
            continue
        path = next((o.get("data", "") for o in parts if o.get("operand") == "process.path"), "")
        scope = next((o.get("data", "") for o in parts if o.get("operand") == "process.starchaser.scope.v2"), "")
        app = scope[8:] if scope.startswith("flatpak:") else next(
            (o.get("data", "") for o in parts if o.get("operand") == "process.env.FLATPAK_ID"), "")
        script = next((o.get("data", "").replace("\\", "") for o in parts if o.get("operand") == "process.command"), "")
        out.append({"file": filename, "action": r.get("action", ""), "path": path, "script": script,
                    "runner": not script and bool(INTERPRETERS.match(Path(path).name)),
                    "name": app or (Path(script).name if script else Path(path).name), "created": r.get("created", "")})
        if app: out[-1]["app"] = "flatpak:" + app
        site = next((o.get("data", "") for o in parts if o.get("operand") in ("dest.host", "dest.ip")), "")
        if site: out[-1]["site"] = site
    return out


def live(stats=None, changed_after=0) -> dict:
    """Whether the rules are running, from the root-side check (firewall-stats, every 60 seconds once a policy
    exists, on or off; every 10 while Settings > Firewall is open). stale: the saved rules came from an older version of the engine (an update since)."""
    st = jread(STATS, {}) if stats is None else stats
    lv = st.get("live") or {}
    checked = int(st.get("updated") or 0)
    fresh = bool(checked) and time.time() - checked < STATS_FRESH
    ob = st.get("outbound") or {}
    return {"loaded": lv.get("loaded"), "matches": lv.get("matches"), "stale": lv.get("stale") is True, "checked": checked,
            # what differs from the rules Settings loaded, in plain words (firewall.py drift(); only on a mismatch)
            "diff": [str(x) for x in lv.get("diff") or []][:5],
            # 150 s: the check runs every 60 s (plus its timer's slack), so one missed tick still counts as current
            "fresh": fresh,
            # Queue inventory from before a mutation cannot describe what remains afterward.
            "queuesFresh": fresh and checked > changed_after + 1,
            "outbound": {"needed": ob.get("needed"), "installed": ob.get("installed"), "active": ob.get("active"),
                         "intercepting": ob.get("intercepting"), "matches": ob.get("matches"),
                         # Block with OpenSnitch not checking: new outgoing connections are held (firewall.py OUTBLOCK_TABLE)
                         "held": ob.get("held") is True,
                         # the checker cannot start, so the app firewall is paused and nothing is held: "restart" (an
                         # update replaced the running kernel) or "failures" (firewall.py CHECKER_PAUSED)
                         "paused": ob.get("paused") if ob.get("paused") in ("restart", "failures") else ""},
            "others": [str(x) for x in st.get("others") or []],
            "queueHooks": [str(x) for x in st.get("queueHooks") or []],
            "queuesChecked": st.get("queuesChecked"),
            # the start-up fallback (firewall.py boot_load): "emergency" = the strict backup table runs instead of
            # your rules (nothing gets in); "rebuilt" = the saved file wouldn't load, so the rules were compiled
            # again from your settings; "failed" = nothing could be loaded
            "emergency": lv.get("emergency") is True,
            "boot": ({"mode": str((lv.get("boot") or {}).get("mode") or ""),
                      "time": (lv.get("boot") or {}).get("time") or 0,
                      "errors": [str(x) for x in (lv.get("boot") or {}).get("errors") or []][:3]}
                     if isinstance(lv.get("boot"), dict) else None)}


def asker() -> dict:
    """The outgoing question (starchaser firewall ask) reports here whether it can be shown, and when OpenSnitch last
    pinged it (it does every few seconds while it's connected): serving with no ping means questions go nowhere."""
    rt = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
    a = jread(Path(rt) / "starchaser-firewall-ask.json", {})
    if not isinstance(a, dict):                     # a damaged state reads as no asker, never a traceback
        a = {}
    ping = a.get("lastPing") or 0
    if not isinstance(ping, (int, float)):
        ping = 0
    return {"serving": bool(a.get("serving")), "error": str(a.get("error") or ""), "time": a.get("time") or 0,
            "lastPing": ping, "connected": bool(ping) and time.time() - ping < 15, "pendingApps": a.get("pendingApps", []) if isinstance(a.get("pendingApps", []), list) else []}


def installed(app: dict):
    """Whether one of a catalog app's programs is on this computer: True / False, None when the catalog names no
    program (nothing to look for). Looked for on PATH, in ~/.local/bin, and as a folder of its own under /usr/lib or
    /opt (where packages like Plex, Jellyfin and Cockpit keep their daemons). Cheap enough for every state read."""
    progs = [p for p in app.get("programs") or [] if isinstance(p, str) and p]
    if not progs:
        return None
    for p in progs:
        if shutil.which(p) or (Path.home() / ".local/bin" / p).exists():
            return True
    for name in progs + [str(app.get("id") or "")]:
        if name and "/" not in name and any((Path(d) / name).exists() for d in ("/usr/lib", "/opt")):
            return True
    # a sandboxed (Flatpak) copy, for this account or everyone: its launcher in the exports folder
    exports = (Path.home() / ".local/share/flatpak/exports/bin", Path("/var/lib/flatpak/exports/bin"))
    for app_id in app.get("flatpakIds") or []:
        if isinstance(app_id, str) and app_id and "/" not in app_id and any((d / app_id).exists() for d in exports):
            return True
    return False


# Software's catalog, in the order starchaser software reads it (a copy of your own first): an entry with
# "firewall": "<id>" installs that firewall app
SOFTWARE = [Path.home() / ".config/starchaser/software/catalog.json",
            Path(__file__).resolve().parent.parent / "config/software/catalog.json",
            Path("/usr/share/starchaser/software/catalog.json")]


def software_ids() -> dict:
    """{firewall app id: Software app id} for the apps Software can install."""
    for p in SOFTWARE:
        if p.exists():
            d = jread(p, {})
            apps = d.get("apps") if isinstance(d, dict) else None
            if not isinstance(apps, list):
                apps = []
            return {a["firewall"]: a["id"] for a in apps
                    if isinstance(a, dict) and isinstance(a.get("firewall"), str) and isinstance(a.get("id"), str)}
    return {}


def reach(policy: dict, cat: dict, report: dict, networks=None, net_ifaces=None):
    """{zone: [what other computers on a network of that zone can connect to here]} (firewall.py reach(): each item
    says whether any device there can, or only some address groups, and whether an allow added by hand decides it),
    plus "openAll": the zones where a rule lets any device there connect to every port. None when the engine is
    missing or too old, or the policy can't be read."""
    if fw is None or not hasattr(fw, "reach"):
        return None
    try:
        apps = {a["id"]: a for a in cat.get("apps", []) if isinstance(a, dict) and "id" in a}
        live = {}                                   # without root, the compile report has the ports listened on
        out = {z: fw.reach(policy, z, apps, live, report) for z in fw.ZONES}
        out["interfaces"] = {}
        for n in networks or []:
            if not n.get("device"):
                continue
            scoped = policy
            if net_ifaces is not None:
                # Resolve one-network rules against the sets loaded in the firewall. A matching Block is
                # definite here; a rule for another network cannot open anything on this adapter.
                rules = []
                for rule in policy.get("rules", []):
                    r = dict(rule)
                    network = r.pop("network", None)
                    if network and n["device"] not in net_ifaces.get(network, []):
                        r["enabled"] = False
                    rules.append(r)
                scoped = dict(policy, rules=rules)
            out["interfaces"][n["device"]] = {z: fw.reach(scoped, z, apps, live, report, iface=n["device"]) for z in fw.ZONES}
        out["openAll"] = [z for z in fw.ZONES if any(i["everything"] and i["anyDevice"] and not any(i.get(k) for k in ("iface", "network", "rate", "sport")) for i in out[z])]
        return out
    except Exception:                               # a hand-edited policy the engine would refuse: say nothing
        return None


def history_key(h: dict) -> tuple:
    """Newest first: the saved time, then the id's -2, -3... (two changes in one second; by name, -10 would come
    before -2 and the plain id after both)."""
    m = re.fullmatch(r"(\d{8}-\d{6})(?:-(\d+))?", str(h.get("id") or ""))
    return (h.get("time") or 0, m.group(1) if m else "", int(m.group(2) or 1) if m else 0)


def forward_filtered() -> bool:
    """Whether the saved rules have the forward chain (compiler 20+): traffic passing through this computer is
    blocked there, except its own guests' networks and hotspot. Older saved rules don't check it."""
    try:
        return "\n    chain forward {\n" in NFT.read_text()
    except OSError:
        return False


def forwarding() -> bool:
    """Whether the kernel passes traffic on between interfaces (libvirt and Docker turn this on). Rules from before
    the forward chain (forward_filtered) don't check that traffic."""
    for f in ("/proc/sys/net/ipv4/ip_forward", "/proc/sys/net/ipv6/conf/all/forwarding"):
        try:
            if Path(f).read_text().strip() not in ("", "0"):
                return True
        except OSError:
            pass
    return False


ZONE_WORDS = {"trusted": "a Trusted network: your other devices can reach the apps you allowed for Trusted networks",
              "public": "a Public network: other computers can reach only what you allowed on every network",
              "vpn": "a VPN: only rules for VPN networks, or for every network, let anything in",
              "tailscale": "a Tailscale network: your devices can reach the apps you allowed for Trusted + Tailscale"}


def friendly_network(net, networks=(), sentence=False):
    name = net.get('name') or net.get('device') or 'this network'
    def wired(n):
        return bool(re.fullmatch(r'Wired connection \d+', n.get('name', ''))) and not re.match(r'w[lw]', n.get('device', '')) and not re.search(r'wireless|wifi', n.get('type', ''))
    if wired(net):
        names = {n.get('name') for n in networks if wired(n)} | {name}
        name = 'cable (Ethernet) connection ' + name.rsplit(' ', 1)[-1] if len(names) > 1 else 'your cable (Ethernet) connection'
    return name[0].upper() + name[1:] if sentence and re.match(r'your |cable |this network$', name) else name


def protection_facts(st):
    policy = st.get('policy') or {}
    if not policy.get('enabled'): return []
    privacy = policy.get('privacy') or {}
    facts = []
    for key, label in [('harmful', 'harmful sites blocked'), ('trackers', 'common trackers blocked'), ('adult', 'adult sites blocked')]:
        if privacy.get(key) or key == 'adult' and any(c.get('adult') for c in policy.get('children', [])): facts.append(label)
    dns = 'always' if any(c.get('adult') for c in policy.get('children', [])) else privacy.get('dns', 'off')
    if dns != 'off': facts.append('encrypted lookups ' + ('on every network' if dns == 'always' else 'on Public networks'))
    for c in policy.get('children', []):
        person = next((u for u in st.get('users', []) if u['uid'] == c['uid']), {})
        facts.append('child controls for ' + (person.get('fullName') or person.get('name') or 'account ' + str(c['uid'])))
    if privacy.get('quietPublic'): facts.append('new connections stopped on Public networks')
    if privacy.get('vpn', {}).get('enabled'): facts.append('internet traffic held if the VPN drops')
    return facts


# as firewall.py PAUSED_RESTART_WORDS / PAUSED_FAILURES_WORDS (the engine may be an older copy: said here)
PAUSED_WORDS = {"restart": "Restart to finish the update. Until then, the app firewall is paused; your other firewall "
                           "rules still apply.",
                "failures": "The app firewall is paused because the program that checks apps reaching out keeps "
                            "stopping. Your other firewall rules still apply."}


def summary(st: dict) -> str:
    """starchaser firewall summary: state() in plain sentences (status/state stay JSON for scripts)."""
    if st.get("policyUnreadable"):
        return "Couldn't read firewall settings."
    pol = st.get("policy") or {}
    lv = st.get("live") or {}
    boot = lv.get("boot") or {}
    lines = []
    others = lv.get("others") or [] if lv.get("fresh") else []
    if not pol.get("enabled"):
        queues_fresh = lv.get("fresh") and lv.get("queuesFresh") is True
        queues = lv.get("queueHooks") or [] if queues_fresh else []
        lines.append("The firewall is off: other computers can connect to any app on this computer that accepts connections"
                     + (f", unless other firewall rules loaded on this computer ({', '.join(others)}) turn them away."
                        if others else ", unless other connection checks stop them." if queues else
                        ", but other connection checks couldn't be checked." if queues_fresh and lv.get("queuesChecked") is False else
                        "; checking for other connection controls." if not queues_fresh else "."))
        if queues:
            lines.append("Other connection checks are still active (" + ", ".join(queues)
                         + "). They send connections to a program for checking and may still stop incoming or outgoing connections.")
    elif lv.get("emergency") or boot.get("mode") in ("emergency", "failed"):
        # the start-up fallback runs instead of your rules (or nothing could be loaded): said first, plainly
        if lv.get("emergency"):
            lines.append("Your firewall rules didn't load when the firewall last started, so Starchaser is running strict "
                         "backup rules: other computers can't connect to anything on this computer. Outgoing connections may also be held until the rules are restored.")
        else:
            lines.append("Your firewall rules didn't load when the firewall last started, and neither did Starchaser's "
                         "backup rules. The firewall may NOT be protecting this computer.")
        lines += [f"  {e}" for e in boot.get("errors") or []]
        lines.append("Open Settings > Firewall and press Reload saved firewall.")
    elif lv.get("fresh") and lv.get("loaded") is False:
        lines.append("The firewall is set to on, but its rules are NOT running: other computers may be able to connect "
                     "to apps on this computer. Open Settings > Firewall and press Reload saved firewall.")
    elif lv.get("fresh") and lv.get("matches") is False:
        lines.append("The firewall is on, but the running rules were changed outside Settings:")
        lines += [f"  {d}" for d in (lv.get("diff") or [])[:3]]
        lines.append("Settings > Firewall > Reload saved firewall puts your rules back.")
    else:
        lines.append(("The firewall is on and paused: nobody new can connect until you end the pause." if (st.get("publicPause") or {}).get("on") or (st.get("publicPause") or {}).get("ifaces") else "The firewall is on. It blocks incoming connections unless you allowed them.") if lv.get("fresh") and lv.get("matches") != "unknown" else
                     "The firewall is set to on. Starchaser couldn't check just now that its rules are running.")
        if boot.get("mode") == "rebuilt":
            lines.append("The saved rules file wouldn't load when the firewall last started, so Starchaser rebuilt the "
                         "rules from your settings.")
        custom = (st.get("extra") or {}).get("savedLines", 0) > 0
        if custom:
            lines.append("Extra firewall settings added outside this app are active and may change what can connect. This summary describes rules set in Settings.")
        public = (st.get("reach") or {}).get("public") or []
        if public:
            apps = {a["id"]: a.get("plain") or a.get("name") for a in st.get("apps") or []}
            groups = {a["id"]: a for a in pol.get("addresses") or []}
            permissions = []
            for item in public:
                name = "every app and connection number" if item.get("everything") else apps.get(item.get("app")) or item["name"]
                devices = "any device" if item.get("anyDevice") else ", ".join(
                    (groups.get(g) or {}).get("name") or g for g in item.get("groups") or []) or "selected devices"
                limits = ["from " + devices]
                if item.get("partial"):
                    limits.append("some connections are blocked by earlier rules")
                if item.get("except"):
                    limits.append("except " + ", ".join(item["except"]))
                if item.get("iface"):
                    limits.append("only on adapter " + item["iface"])
                if item.get("network"):
                    network = next((n.get("name") for n in pol.get("networks") or [] if n.get("uuid") == item["network"]), None)
                    limits.append("only on " + (network or "its selected network"))
                if item.get("rate") or item.get("sport"):
                    limits.append("with extra limits; see Rules for details")
                permissions.append(name + " (" + "; ".join(limits) + ")")
            lines.append("Permissions on Public networks, including public Wi-Fi: " + "; ".join(permissions) + ".")
            lines.append("Apps must be running to accept these connections. Other connection controls may still block them.")
        where = {i: z for z, ifs in (st.get("zones") or {}).items() for i in ifs or []}
        for n in st.get("networks") or []:
            z = where.get(n.get("device"), "")
            words = ("counted as " + {"trusted": "a network you trust", "public": "a public network", "vpn": "a VPN network", "tailscale": "a Tailscale network"}.get(z, "an unmarked network")) if custom else (ZONE_WORDS.get(z) or "not sorted into a kind of network yet")
            if n.get("device") in (st.get("publicPause") or {}).get("ifaces", []):
                words = "a Public network; Public pause blocks new incoming connections, including saved permissions"
            lines.append(friendly_network(n, st.get("networks", []), True) + " is " + words + ".")
        on = [r for r in pol.get("rules") or [] if r.get("enabled", True)]
        lines.append(f"{len(on)} {'rule is' if len(on) == 1 else 'rules are'} on. See them in Settings > Firewall.")
    facts = protection_facts(st)
    if facts and lines and lv.get('fresh') and lv.get('loaded') is not False and lv.get('matches') is True:
        lines[0] += " On now: " + " · ".join(facts) + "."
    paused = (lv.get("outbound") or {}).get("paused") if pol.get("enabled") and lv.get("fresh") else ""
    if paused and lines:                               # second: Settings > Firewall shows the first line under its own banner
        lines.insert(1, PAUSED_WORDS[paused])
    if st.get("pending"):
        lines.append("A change is waiting: press Keep in Settings > Firewall, or it goes back by itself.")
    return "\n".join(lines)


def fleet() -> dict:
    """The fleet's networks (starchaser-admin fleet-networks): the two switches, the zones the fleet's own switches
    use, and which apps those are. An engine too old to know them: Tailscale on, VPN off, as it always was."""
    if fw is not None and hasattr(fw, "fleet_networks"):
        nets = fw.fleet_networks()
        return {**nets, "zones": fw.fleet_zones(nets), "apps": list(fw.FLEET_APPS)}
    return {"tailscale": True, "vpn": False, "zones": ["trusted", "tailscale"],
            "apps": ["ssh", "tsshd", "starchaser-devices", "mdns", "sunshine", "mission-control"]}


def fleet_access(policy: dict, networks: list, reached) -> dict:
    """Whether a network this computer is on keeps the fleet out (firewall_access.fleet_block(), from the same
    "reach" answer Settings shows). Nothing to say when the engine is missing or couldn't answer."""
    if fw is None or not reached:
        return {"blocked": False}
    try:
        import firewall_access
        return firewall_access.fleet_block(policy, networks, reached)
    except Exception:                               # an older engine: the taskbar says nothing, never something wrong
        return {"blocked": False}


def policy_state() -> dict:
    """Read the files that can change together during Apply, Keep, and restoration."""
    hist = []
    for f in HISTORY.glob("*.json") if HISTORY.is_dir() else []:
        h = jread(f, {})
        hist.append({"id": h.get("id"), "time": h.get("time"), "summary": h.get("summary"), "undid": h.get("undid"),
                     "reloadOnly": h.get("reloadOnly") is True,
                     "runtimeOnly": h.get("runtimeOnly") is True,
                     "event": h.get("event") or {},
                     "rules": len((h.get("policy") or {}).get("rules", [])), "enabled": (h.get("policy") or {}).get("enabled")})
    hist = sorted(hist, key=history_key, reverse=True)[:30]
    # no policy file yet is a firewall that was never set up (off, no rules); a file that is there but can't be read
    # or parsed is said so ("policyUnreadable"), so nothing builds a change on the stand-in (Ask, Software's drafts)
    unreadable = False
    try:
        pol = json.loads(POLICY.read_text())
        unreadable = not isinstance(pol, dict)
    except FileNotFoundError:
        pol = None
    except (OSError, ValueError, RecursionError):
        unreadable = True
    if unreadable or pol is None:
        pol = {"enabled": False, "rules": []}
    return {"policy": pol, "policyUnreadable": unreadable, "history": hist,
            "pending": jread(PENDING, None), "stats": jread(STATS, {}), "zones": jread(ZONES, {})}


def state_once(snapshot: dict) -> dict:
    administrators = set()
    admin_gids = set()
    for group in grp.getgrall():
        if group.gr_name in ('wheel', 'sudo'):
            administrators.update(group.gr_mem); admin_gids.add(group.gr_gid)
    users = [{"uid": u.pw_uid, "name": u.pw_name, "fullName": u.pw_gecos.split(',')[0] or u.pw_name,
              "admin": u.pw_name in administrators or u.pw_gid in admin_gids}
             for u in pwd.getpwall() if 1000 <= u.pw_uid < 60000]
    cat = jread(CATALOG, None) or jread(CATALOG_REPO, {"apps": []})
    sw = software_ids()
    for a in cat.get("apps", []):
        if isinstance(a, dict):
            a["installed"] = installed(a)
            a["software"] = sw.get(a.get("id"), "")
    pol = snapshot["policy"]
    unreadable = snapshot["policyUnreadable"]
    hist = snapshot["history"]
    last_change = max((h.get("time") or 0 for h in hist if not h.get("runtimeOnly")), default=0)
    stats = snapshot["stats"]
    z = snapshot["zones"]
    networks = networks_now()
    for network in networks:
        if re.search(r'vpn|wireguard|tun', network.get('type', '')): network['endpoints'] = vpn_endpoints(network)
    # Use the current identity, not the zone file's last reload: a saved cable profile can now be on another network.
    if fw is not None:
        networks = fw.annotate_networks(pol, networks, z.get("networks", []))
    reached = {} if unreadable else reach(pol, cat, z.get("report", {}), networks, z.get("netIfaces", {}))
    result = {"policy": pol, "policyRevision": "" if unreadable else policy_revision(pol), "policyUnreadable": unreadable, "reach": reached, "zones": z.get("zones", {}),
            "fleetAccess": fleet_access(pol, networks, reached),
            "netIfaces": z.get("netIfaces", {}),
            "report": z.get("report", {}), "networks": networks, "interfaces": interfaces_now(networks),
            "saved": saved_networks(), "subnets": subnets(), "stats": stats.get("rules", {}),
            "pending": snapshot["pending"], "history": hist, "apps": cat.get("apps", []), "users": users,
            "opensnitch": bool(shutil.which("opensnitchd")), "asked": asked(), "askedError": ASKED_ERROR,
            "adminReady": Path("/usr/local/lib/starchaser/firewall.py").exists(), "live": live(stats, last_change), "asker": asker(),
            "keepHelper": Path("/usr/local/lib/starchaser/starchaser-firewall-keep").exists(),
            "baseline": [] if unreadable else baseline(pol),
            "baselineTech": [] if unreadable else baseline_tech(),
            "extra": fw.extra_state(check=True) if fw is not None and hasattr(fw, "extra_state") else None,
            "publicPause": stats.get("publicPause") or {"on": False, "networks": [], "ifaces": [], "connections": []},
            "outgoingChecker": stats.get("outgoingChecker") or "",
            "listeners": stats.get("listeners") or [], "socketPresence": stats.get("socketPresence"),
            "listenersSeen": stats.get("listenersSeen") or [],
            "deviceNames": device_names(),
            "listenerDetails": listener_details(),
            "newPorts": stats.get("newPorts") or {}, "forwarding": forwarding(),
            "forwardFiltered": forward_filtered(), "fleet": fleet(),
            "allowedOnce": [dict(o, iface=o.get("iface") or "") for o in stats.get("allowedOnce") or [] if (o.get("until") or 0) > time.time()]}

    activity = Activity().read()
    result["weekly"] = jread(Path("/var/lib/starchaser/firewall-week.json"), {})
    result["weeklyWords"] = fw.firewall_week.words(result["weekly"]) if fw is not None and hasattr(fw, "firewall_week") else ""
    result["fleetPresent"] = bool((jread(Path.home() / ".config/starchaser/fleet.json", {}).get("fleet") or {}).get("tag"))
    try:
        hotspots = set(fw.hotspot_interfaces()) if fw else set()
        neighbors = subprocess.run(["ip", "-j", "neigh", "show"], capture_output=True, text=True, timeout=3)
        result["hotspotClients"] = [{"address": n["dst"], "mac": n.get("lladdr", "")} for n in json.loads(neighbors.stdout or "[]") if n.get("dev") in hotspots and n.get("dst") and n.get("state") != ["FAILED"]]
    except (OSError, ValueError, subprocess.SubprocessError): result["hotspotClients"] = []
    result["wifiPresent"] = any((Path('/sys/class/net') / n / 'wireless').exists() for n in os.listdir('/sys/class/net'))
    child_status = jread(Path('/run/starchaser/firewall-child-requests') / (str(os.getuid()) + '.json'), {})
    result["childRequestsKnown"] = child_status.get('uid') == os.getuid() and 0 <= time.time() - child_status.get('time', 0) < STATS_FRESH
    result["childRequests"] = child_status.get('requests', []) if result["childRequestsKnown"] else []
    result["activity"] = activity
    result["appRecords"] = app_records(result)
    result["summary"] = summary(result)
    result["uid"] = os.getuid()
    result["signInNetworks"] = fw.portal_networks(networks) if fw else []
    for row in result["signInNetworks"]:
        net = next((n for n in networks if n.get('uuid') == row['network']), row)
        row['name'] = friendly_network(net, networks, True)
    result["privacyStatus"] = {"dnsRunning": nm_service("starchaser-firewall-dns.service"),
                               "settings": pol.get("privacy", {}), "children": pol.get("children", [])}
    return result


def nm_service(unit):
    try:
        return subprocess.run(["systemctl", "is-active", "--quiet", unit], capture_output=True, timeout=3).returncode == 0
    except (OSError, subprocess.TimeoutExpired): return False


def filterable_program(path):
    """A launcher script is not the executable the checker will attribute its child connections to."""
    try:
        with open(path, 'rb') as stream: return stream.read(4) == b'\x7fELF'
    except OSError: return False


def catalog_launcher(path, cat):
    """The program a catalog-named launcher script starts (apps.json "launchers"), when it is installed as a root-owned
    executable in a system folder: Brave Origin's launcher is two scripts deep, too long to read, so the catalog
    names the browser program the outgoing checker sees making each connection."""
    name = Path(path).name
    for item in (cat or {}).values():
        target = (item.get('launchers') or {}).get(name)
        if not target or not re.fullmatch(r'/(?:usr|opt)/[A-Za-z0-9._/+-]+', target): continue
        try:
            real, info = Path(target).resolve(), Path(target).resolve().stat()
        except OSError: continue
        if (str(real).startswith(('/usr/', '/opt/')) and info.st_uid == 0 and not info.st_mode & 0o022
                and os.access(real, os.X_OK) and filterable_program(real)):
            return str(real)
    return ''


def launcher_program(path, cat=None):
    """Resolve only a literal, unconditional exec wrapper or a catalog-named launcher; never execute launcher code
    or guess an interpreter."""
    path = str(Path(path).resolve())
    if filterable_program(path): return path
    known = catalog_launcher(path, cat)
    if known: return known
    try:
        if Path(path).stat().st_size > 16384: return path
        lines = [line.strip() for line in Path(path).read_text().splitlines() if line.strip() and not line.lstrip().startswith('#')]
        if len(lines) != 1 or not lines[0].startswith('exec '): return path
        words = shlex.split(lines[0])
        if len(words) < 2 or re.search(r'[;|&<>`]', lines[0]) or any('$' in w and w != '$@' for w in words): return path
        real = shutil.which(words[1])
        if real and filterable_program(real) and not fw.ASK_INTERPRETERS.fullmatch(Path(real).name):
            return str(Path(real).resolve())
    except (OSError, UnicodeError, ValueError): pass
    return path


def menu_visibility():
    for folder in (Path(__file__).resolve().parent.parent / 'config/keybinds', Path.home() / '.config/keybinds'):
        if (folder / 'app_visibility.py').is_file():
            import importlib.util
            spec = importlib.util.spec_from_file_location('firewall_app_visibility', folder / 'app_visibility.py')
            module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
            return module
    return None


def menu_hidden_apps():
    return getattr(menu_visibility(), 'HIDDEN_APPS', set())


def same_app_fallbacks():
    return getattr(menu_visibility(), 'SAME_APP_FALLBACKS', {})


def installed_desktop_records(cat, folders=None):
    """Launcher metadata discovers apps; only verified executable/sandbox identities can get permissions."""
    folders = folders if folders is not None else [Path('/usr/share/applications'), Path('/var/lib/flatpak/exports/share/applications'),
        Path.home() / '.local/share/flatpak/exports/share/applications', Path.home() / '.local/share/applications',
        Path(os.environ.get('XDG_DATA_HOME', Path.home() / '.local/share')) / 'applications']
    found, entries = {}, {}
    hidden = menu_hidden_apps()
    for directory in folders:
        for file in sorted(directory.glob('*.desktop')): entries[file.name] = file
    # Files has a fallback launcher (Thunar beside Flea): the person knows one app, so the fallback folds into
    # system tools under a name that says what it is, rather than a second "Files" or "File Manager" row.
    fallbacks = {stem for stem, main in same_app_fallbacks().items() if main + '.desktop' in entries}
    for file in entries.values():
        directory = file.parent
        try:
            if file.stat().st_size > 65536: continue
            values, section = {}, ''
            for line in file.read_text(errors='replace').splitlines():
                if line.startswith('['): section = line.strip()
                elif section == '[Desktop Entry]' and '=' in line and not line.startswith('#'):
                    key, value = line.split('=', 1); values[key] = value
            # The privacy broker mediates launchers; use their original metadata just as the Super menu does.
            original = values.get('X-Starchaser-Privacy-Source')
            if original:
                source = Path(original)
                if source.stat().st_size > 65536: continue
                values, section = {}, ''
                for line in source.read_text(errors='replace').splitlines():
                    if line.startswith('['): section = line.strip()
                    elif section == '[Desktop Entry]' and '=' in line and not line.startswith('#'):
                        key, value = line.split('=', 1); values[key] = value
            if values.get('Hidden') == 'true' or values.get('NoDisplay') == 'true' or values.get('Type', 'Application') != 'Application': continue
            argv = shlex.split(values.get('Exec', ''))
            if not argv: continue
            sandbox = 'flatpak/exports/share/applications' in str(directory)
            if sandbox:
                app_id = file.stem
                if not re.fullmatch(r'[A-Za-z0-9_]+(?:\.[A-Za-z0-9_-]+){2,}', app_id): continue
                row = fw.app_record('', 'flatpak:' + app_id, cat)
                row['incoming'] = bool(cat.get(row.get('catalogId'), {}).get('in'))
            else:
                if Path(argv[0]).name == 'env':
                    argv = argv[1:]
                    while argv and re.match(r'^[A-Za-z_][A-Za-z_0-9]*=', argv[0]): argv = argv[1:]
                if not argv or argv[0].startswith('-') or Path(argv[0]).name == 'xdg-open' or re.search(r'starchaser-(?:app-permissions|permissions|firewall|privacy)', Path(argv[0]).name): continue
                exe = shutil.which(argv[0]) if not argv[0].startswith('/') else argv[0]
                if not exe or not os.access(exe, os.X_OK) or not Path(exe).is_file(): continue
                exe = launcher_program(exe, cat)
                if fw.ASK_INTERPRETERS.fullmatch(Path(exe).name) or Path(exe).name == 'flatpak': continue
                row = fw.app_record(exe, 'host', cat)
                row['incoming'] = True
                row['outgoing'] = filterable_program(exe)
            item = cat.get(row.get('catalogId'), {})
            system_tool = file.stem in hidden or file.stem in fallbacks or file.stem in {"org.fcitx.fcitx5-config-qt", "fcitx5-configtool"}
            row.update(installed=True, launcher=not system_tool, ports=item.get('in', []))
            name = 'Files (fallback file manager)' if file.stem in fallbacks else values.get('Name') or row['name']
            if re.search(r'gnome|kde|xfce|hyprland|cachyos|thunar', name, re.I):
                name = values.get('GenericName') or ('Terminal' if 'terminal' in file.stem else 'About' if 'about' in file.stem else row['name'])
            if re.search(r'gnome|kde|xfce|hyprland|cachyos|thunar', name, re.I): name = 'System program'
            row['name'] = fw.clean_name(name, 120)
            row['icon'] = values.get('Icon') or row.get('icon', '')
            found[row['id']] = row
        except (OSError, ValueError): continue
    return found


def app_records(st):
    """One row per executable or sandbox app, with existing catalog permissions attached as shared rules."""
    records, cat = {}, {a['id']: a for a in st.get('apps', [])}
    for item in cat.values():
        if not item.get('installed'): continue
        for prog in item.get('programs', []):
            path = shutil.which(prog)
            if not path: continue
            # Resolve symlinks the same way the checker sees process executables, and a launcher script to the
            # program it starts, as the launcher rows below do (one Brave Origin row, and a switch that works).
            path = launcher_program(path, cat)
            row = fw.app_record(path, 'host', cat) if fw else {'id': 'program:' + path, 'name': prog}
            trusted = row.get('catalogId') == item['id']
            row.update(installed=True, incoming=bool(item.get('in')) if trusted else True,
                       ports=item.get('in', []) if trusted else [], outgoing=filterable_program(path))
            records[row['id']] = row
    for event in st.get('activity', {}).get('events', []):
        key = event['app']
        if key == 'unidentified': continue
        if key not in records:
            records[key] = {'id': key, 'name': event['name'], 'icon': 'application-x-executable',
                            'incoming': key.startswith('program:/'), 'programs': []}
    for answer in st.get('asked', []):
        key = answer.get('app') or 'program:' + answer.get('path', '')
        if key != 'program:' and key not in records:
            records[key] = {'id': key, 'name': answer.get('name') or key, 'icon': 'application-x-executable', 'incoming': key.startswith('program:/'), 'programs': []}
    for rule in st['policy'].get('rules', []):
        key = rule.get('app', 'any')
        # Catalog-family rules appear in each app's details instead of becoming a second aggregate app row.
        if key in cat: continue
        if key != 'any' and key not in records:
            records[key] = {'id': key, 'name': rule.get('name') or key, 'icon': 'application-x-executable',
                            'incoming': not key.startswith('flatpak:'), 'programs': []}
    if fw:
        for key, row in installed_desktop_records(cat).items():
            records[key] = dict(records.get(key, {}), **row)
    active = {e['app'] for e in st.get('activity', {}).get('events', [])}
    active.update(a.get('app') or 'program:' + a.get('path', '') for a in st.get('asked', []))
    rows = [r for r in records.values() if not re.search(r'opensnitch|starchaser-|/xdg-open$', r['id'], re.I)]
    for row in rows:
        if row.get('name') == 'Running app':
            row['name'] = fw.app_record(row['id'][8:], 'host', cat)['name'] if fw and row['id'].startswith('program:') else 'System program'
        if re.search(r'gnome|kde|xfce|hyprland|cachyos|thunar', row.get('name', ''), re.I):
            row['name'] = 'Terminal' if 'terminal' in row['id'].lower() else 'About' if 'about' in row['id'].lower() else 'System program'
    names = {}
    for row in rows: names[row['name']] = names.get(row['name'], 0) + 1
    for row in rows:
        row['system'] = not row.get('launcher')
        row['incoming'] = bool(row.get('ports'))
        if names[row['name']] > 1:
            # Use stable, distinct numbers rather than exposing hidden upstream desktop names.
            siblings = sorted(r['id'] for r in rows if r['name'] == row['name'] or r.get('_baseName') == row['name'])
            row['_baseName'] = row['name']
            row['name'] += ' (' + str(siblings.index(row['id']) + 1) + ')'
    for row in rows: row.pop('_baseName', None)
    return sorted(rows, key=lambda x: (x['system'], x['name'].casefold()))


def listener_details():
    """Current process details readable by this account, for the expanded app chooser and Log only."""
    try:
        result = subprocess.run(["ss", "-H", "-lntup"], capture_output=True, text=True, timeout=3, check=False)
    except (OSError, subprocess.TimeoutExpired):
        return []
    if result.returncode:
        return []
    details = []
    for line in result.stdout.splitlines():
        fields = line.split()
        if len(fields) < 6 or fields[0] not in ("tcp", "udp"):
            continue
        bind, _, port = fields[4].rpartition(":")
        if not port.isdigit():
            continue
        for pid in dict.fromkeys(re.findall(r"pid=(\d+)", line)):
            proc = Path("/proc") / pid
            try:
                executable = os.readlink(proc / "exe")
                user = pwd.getpwuid(proc.stat().st_uid).pw_name
                args = (proc / "cmdline").read_bytes().decode("utf-8", "replace").rstrip("\0").split("\0")
            except (OSError, KeyError):
                continue
            command = shlex.join(args)
            command = "".join(c if c.isprintable() else " " for c in command)[:1000]
            details.append({"proto": fields[0], "port": int(port), "bind": bind.strip("[]"),
                            "text": f"{command}\nProgram: {executable}\nProcess ID: {pid} · User: {user}"})
    return details[:200]


def device_names():
    """Recent DNS claims from the notification helper, never treated as verified device identities."""
    path = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "starchaser-firewall-device-names.json"
    try:
        names = json.loads(path.read_text())
        now = time.time()
        return {ip: value[1] for ip, value in names.items()
                if isinstance(value, list) and len(value) == 2 and isinstance(value[0], (int, float))
                and 0 <= now - value[0] < 600 and isinstance(value[1], str)
                and re.fullmatch(r"[\w.-]{1,40}", value[1])}
    except (OSError, ValueError, AttributeError):
        return {}


def check_now() -> None:
    """Start the root-side check when its result is older than the check's own beat, so `state` after a change made
    from a terminal is not a look back in time. polkit lets the person at the computer start this unit without a
    password; --no-ask-password means any other session just keeps the cached check, never a prompt."""
    try:
        if time.time() - STATS.stat().st_mtime <= 10:
            return
    except OSError:
        pass
    try:
        subprocess.run(["systemctl", "--wait", "--no-ask-password", "start", "starchaser-firewall-stats.service"],
                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=20, check=False)
    except (OSError, subprocess.TimeoutExpired):
        pass


def state() -> dict:
    # A restore can replace these files between reads. Retry once; a second race is explicitly unconfirmed.
    snapshot = policy_state()
    for _ in range(2):
        result = state_once(snapshot)
        after = policy_state()
        if snapshot == after:
            return {**result, "stateCoherent": True}
        snapshot = after
    return {**result, "stateCoherent": False}


LOG_MAX = 5000
unreadable = False                          # set by blocked(): this account can't read the kernel log


def group_of(src: str, groups: list) -> str:
    """The id of the first address group the source is in (addresses, networks and ranges, IPv4 and IPv6)."""
    try:
        ip = ipaddress.ip_address(src)
    except ValueError:
        return ""
    for a in groups:
        for x in a.get("addrs", []):
            try:
                if "-" in x:
                    lo, hi = (ipaddress.ip_address(y.strip()) for y in x.split("-", 1))
                    if lo.version == ip.version and lo <= ip <= hi:
                        return a.get("id", "")
                elif ip in ipaddress.ip_network(x.strip(), strict=False):
                    return a.get("id", "")
            except (ValueError, TypeError):
                continue
    return ""


def policy_revision(policy: dict) -> str:
    """Tie a log annotation to the same saved policy shown by state, even across a refresh."""
    return hashlib.sha256(json.dumps(policy, sort_keys=True).encode()).hexdigest()


def log_permission(policy: dict, incoming: list, zones: dict, iface: str, src: str, proto: str, port, sport,
                   net_ifaces: dict = None) -> dict:
    """A saved Allow covering this attempt now, separate from the recorded outcome.

    Rule order, address groups, adapter, destination and source ports all matter.
    Rate limits cannot be proved from a log line; keep those Allows available to review.
    A rule limited to one network covers the adapter only when the firewall put it in that network's set
    (net_ifaces, the zone file's netIfaces); unknown means it doesn't.
    """
    if fw is None or not policy.get("enabled") or not iface or proto not in ("tcp", "udp"):
        return {}
    try:
        port = int(port)
        if not 1 <= port <= 65535:
            return {}
        groups = fw.peer_groups(policy, src)
    except (ValueError, TypeError):
        return {}
    # Use today's adapter membership, never the zone recorded when the attempt happened.
    zone = next((z for z, adapters in zones.items() if iface in adapters), "other")
    limited = False
    for rule, ports, _ in incoming:
        if not (fw.zone_matches(rule, zone) and fw.peer_matches(rule, groups)
                and fw.interface_matches(rule, iface) and fw.port_matches(ports, proto, port)):
            continue
        sports = rule.get("sport") or []
        if sports and not fw._sport_matches(sports, sport):
            continue
        if rule.get("network") and iface not in ((net_ifaces or {}).get(rule["network"]) or []):
            continue
        uncertain_sport = bool(sports) and not str(sport).isdigit()
        if rule.get("action") == "allow":
            return {"rule": rule["id"], "limited": limited or bool(rule.get("rate")) or bool(sports),
                    "zone": zone, "revision": policy_revision(policy)}
        if rule.get("rate") or uncertain_sport:
            limited = True
            continue
        return {}
    return {}


def blocked(n: int) -> list:
    n = max(1, min(n, LOG_MAX))             # [-0:] would mean "every row", and negatives would drop rows
    # _TRANSPORT=kernel, not -k: -k means this boot only, and the last 24 hours can reach back before a restart.
    # "sc-in-blocked " / "sc-in-paused " = turned away; "sc-in <rule id> " = a rule with "Log matches" on;
    # "sc-fwd-paused " = the pause turned away something passing through (a port forwarded to a guest, VPN routing)
    try:
        r = subprocess.run(["journalctl", "_TRANSPORT=kernel", "--since", "-24h", "-o", "json", "--no-pager",
                            "-g", "^sc-(in[ -]|fwd-paused )", "-n", str(n)], capture_output=True, text=True)
    except OSError:                                    # no journalctl: no rows to show
        return []
    out = r.stdout
    global unreadable
    # an account outside wheel, adm and systemd-journal sees only its own messages (journalctl says so on stderr, and
    # may still exit 0): an empty answer then means "can't see", not "nothing turned away"
    unreadable = not out.strip() and bool(re.search(r"insufficient permissions|No journal files were opened|"
                                                    r"not seeing messages from other users", r.stderr or "", re.I))
    pol = jread(POLICY, {})
    rules = {r.get("id"): r for r in pol.get("rules", []) if isinstance(r, dict)}
    dflt = "reject" if (pol.get("defaults") or {}).get("in") == "reject" else "block"
    verdicts = {"allow": "allow", "block": "block", "reject": "reject", "drop": "block"}
    zone_state = jread(ZONES, {}) or {}
    report = zone_state.get("report", {})
    incoming = []
    if fw is not None:
        try:
            incoming = list(fw.inbound(pol, fw.catalog(), {}, report))
        except (ValueError, TypeError, KeyError, AttributeError):
            pass                                # a malformed or older policy has no current Allow annotation
    permissions = {}
    rate_candidates = {}
    rows = []
    for line in out.splitlines():
        try:
            e = json.loads(line)
        except ValueError:
            continue
        msg = e.get("MESSAGE", "")
        if isinstance(msg, list):
            msg = bytes(msg).decode(errors="replace")
        kv = dict(re.findall(r"(\w+)=(\S*)", msg))
        # "sc-in <rule> <action> z=<zone> " / "sc-in-blocked <drop|reject> z=<zone> " (firewall.py LOG_LIMIT);
        # older lines are "sc-in <rule> " / "sc-in-blocked " with neither
        m = re.match(r"sc-(?:(?P<fwd>fwd)-paused|in(?:-blocked|-(?P<pause>paused)| (?P<rule>\S+))) (?:(?P<act>allow|block|reject|drop) )?(?:z=(?P<zone>[a-z]+) )?", msg)
        if not m:
            continue
        rule, zone = m.group("rule") or "", m.group("zone") or ""
        forwarded = bool(m.group("fwd"))               # on its way to a guest or a VPN, not to this computer
        reason = "pause" if m.group("pause") or forwarded else ""
        action = verdicts.get(m.group("act") or "", "")
        if action:
            turned_away, now = action != "allow", ""
        elif not rule:                                  # an older default line: always a drop or a refusal
            turned_away, now = True, dflt
        else:                                           # an older rule line: today's rule is a guess, not a fact
            turned_away, now = None, (rules.get(rule) or {}).get("action", "")
        src = kv.get("SRC", "")
        try:
            src = ipaddress.ip_address(src).compressed      # the kernel writes IPv6 in full
        except ValueError:
            pass
        dst = kv.get("DST", "")
        try:
            dst = ipaddress.ip_address(dst).compressed
        except ValueError:
            pass
        try:
            usec = int(e.get("__REALTIME_TIMESTAMP", "0"))
        except ValueError:
            usec = 0
        candidates = []
        if not rule and not reason and turned_away and fw is not None and hasattr(fw, "rate_allow_candidates"):
            try:
                key = (kv.get("PROTO", "").lower(), kv.get("DPT", ""), zone, kv.get("IN", ""), src, kv.get("SPT", ""))
                if key not in rate_candidates:
                    rate_candidates[key] = fw.rate_allow_candidates(pol, key[0], key[1], known=report, zone=zone or None,
                                                                    iface=key[3] or None, src=src, sport=key[5])
                candidates = rate_candidates[key]
            except (ValueError, TypeError, KeyError):
                pass                            # malformed saved policy: do not guess an explanation
        permission_key = (kv.get("IN", ""), src, kv.get("PROTO", "").lower(), kv.get("DPT", ""), kv.get("SPT", ""))
        if permission_key not in permissions:
            try:
                permissions[permission_key] = log_permission(pol, incoming, zone_state.get("zones", {}), *permission_key,
                                                                 net_ifaces=zone_state.get("netIfaces") or {})
            except (ValueError, TypeError, KeyError, AttributeError):
                permissions[permission_key] = {}
        rows.append({"usec": usec, "time": usec // 1_000_000, "iface": kv.get("IN", ""),
                     "src": src, "dst": dst, "proto": kv.get("PROTO", "").lower(),
                     "sport": kv.get("SPT", ""), "dport": kv.get("DPT", ""), "rule": rule, "action": action,
                     "turnedAway": turned_away, "actionNow": now, "zone": zone, "reason": reason, "forwarded": forwarded,
                     "ruleName": str((rules.get(rule) or {}).get("name") or "") if rule else "",
                     "ruleGone": bool(rule) and rule not in rules, "rateCandidates": candidates,
                     "currentAllow": permissions[permission_key],
                     "group": group_of(src, pol.get("addresses", []))})
    # newest first, by the time each line was written (journalctl's own order isn't relied on), then the newest n
    rows.sort(key=lambda r: r["usec"], reverse=True)
    for r in rows:
        del r["usec"]
    return rows[:n]


def table_loaded():
    """True/False when nft can tell us whether the starchaser table is loaded; None when it can't (no root)."""
    try:
        r = subprocess.run(["nft", "list", "tables"], capture_output=True, text=True, timeout=5)
    except (OSError, subprocess.SubprocessError):
        return None
    if r.returncode != 0:
        return None
    return any(line.strip() == "table inet starchaser" for line in r.stdout.splitlines())


def baseline_tech() -> list:
    """The interface patterns behind the baseline's plain words (Settings' Technical details)."""
    if fw is None or not hasattr(fw, "guest_baseline_tech"):
        return []
    return fw.guest_baseline_tech()


def baseline(pol: dict) -> list:
    """What every Starchaser firewall allows by default (expert rules can override some defaults) (ping as the policy's Ping choice says)."""
    if fw is None or not hasattr(fw, "baseline_text"):
        return []
    try:
        return fw.baseline_text(pol)
    except TypeError:                                   # an engine from before the Ping choice
        return fw.baseline_text()


def documents() -> Path:
    """Where saved files go: the Documents folder (xdg-user-dir), else the home folder."""
    try:
        d = subprocess.run(["xdg-user-dir", "DOCUMENTS"], capture_output=True, text=True, timeout=5).stdout.strip()
    except (OSError, subprocess.SubprocessError):
        d = ""
    for p in (Path(d) if d else None, Path.home() / "Documents"):
        if p and p.is_dir() and p != Path.home():
            return p
    return Path.home()


def save_new(stem: str, ext: str, text: str) -> dict:
    """Save text to a new file named for now ("Starchaser firewall rules 2026-10-10 14.05.nft"), never over one."""
    folder = documents()
    base = f"{stem} {time.strftime('%Y-%m-%d %H.%M')}"
    path = folder / f"{base}{ext}"
    n = 2
    while path.exists():
        path = folder / f"{base} ({n}){ext}"
        n += 1
    try:
        with open(path, "x") as f:
            f.write(text)
    except OSError as e:
        return {"ok": False, "errors": f"Couldn't save to {folder}: {e.strerror or e}."}
    return {"ok": True, "errors": "", "path": str(path)}


EXPORT_MARK = "starchaserFirewall"        # a settings export's own key
EXTRA_RESTORE = ("The backup includes the hand-written rules file as saved on disk; it may differ from the rules running now. "
                 "Import restores only Settings-managed rules. To restore the hand-written rules, review the text shown after Import, "
                 "save it to /etc/starchaser/firewall-extra.nft with administrator rights, "
                 "then use Reload saved firewall to review and load it.")


def is_firewall_backup(d) -> bool:
    """Recognize an export or a bare policy before permissive normalization fills defaults."""
    if not isinstance(d, dict):
        return False
    if EXPORT_MARK in d and (type(d[EXPORT_MARK]) is not int or d[EXPORT_MARK] not in (1, 2)):
        return False
    if d.get(EXPORT_MARK) == 2:
        extra = d.get("handWrittenRules")
        if not isinstance(extra, dict) or "text" not in extra or (extra["text"] is not None and not isinstance(extra["text"], str)):
            return False
    # Exports carry a version; bare policies may predate it. Reject unsupported versions
    # in either format. Policy versions 1 and 2 remain readable by the version 3 engine.
    if (EXPORT_MARK in d or "version" in d) and (
            type(d.get("version")) is not int or d["version"] not in (1, 2, 3)):
        return False
    return (isinstance(d.get("enabled"), bool)
            and isinstance(d.get("rules"), list)
            and isinstance(d.get("defaults"), dict)
            and all(isinstance(d["defaults"].get(k), str) for k in ("in", "out"))
            and all(isinstance(d[k], list) for k in ("networks", "addresses", "services") if k in d)
            and all(isinstance(x, dict) for k in ("networks", "addresses", "services", "rules")
                    for x in d.get(k, [])))


def export() -> dict:
    try:
        pol = json.loads(POLICY.read_text())
    except FileNotFoundError:
        return {"ok": False, "errors": "There are no firewall settings to save yet: the firewall has never been turned on."}
    except (OSError, ValueError, RecursionError) as e:
        return {"ok": False, "errors": f"The firewall settings couldn't be read ({e})."}
    try:
        # Preserve comments, blank lines and line endings, including an edited or invalid rules file.
        extra = EXTRA.read_bytes().decode("utf-8")
    except FileNotFoundError:
        extra = None
    except (OSError, UnicodeDecodeError):
        return {"ok": False, "errors": "The hand-written rules file couldn't be read as UTF-8. No backup was saved. "
                "Check /etc/starchaser/firewall-extra.nft and its read permissions, then try again."}
    out = {EXPORT_MARK: 2, "saved": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
           "computer": (Path("/etc/hostname").read_text().strip() if Path("/etc/hostname").exists() else ""), **pol,
           "handWrittenRules": {"path": str(EXTRA), "text": extra, "restore": EXTRA_RESTORE}}
    result = save_new("Starchaser firewall settings", ".json", json.dumps(out, indent=2) + "\n")
    if result["ok"]:
        result["warning"] = EXTRA_RESTORE if extra is not None else "No hand-written rules file was present. Import restores only Settings-managed rules."
    return result


def import_files() -> list:
    found = []
    for folder in dict.fromkeys((documents(), Path.home() / "Downloads", Path.home())):
        try:
            files = [f for f in folder.glob("*.json") if f.is_file() and f.stat().st_size < 2_000_000]
        except OSError:
            continue
        for f in files:
            try:
                d = json.loads(f.read_text())
            except (OSError, ValueError, UnicodeDecodeError):
                continue
            if is_firewall_backup(d):
                found.append({"path": str(f), "name": f.name, "folder": folder.name or str(folder), "time": int(f.stat().st_mtime)})
    return sorted(found, key=lambda x: -x["time"])[:30]


def import_check(path: str) -> dict:
    try:
        d = json.loads(Path(path).read_text())
    except FileNotFoundError as e:
        return {"ok": False, "errors": "That file wasn't found. It may have been moved or deleted.", "details": str(e)}
    except PermissionError as e:
        return {"ok": False, "errors": "You don't have permission to open that file.", "details": str(e)}
    except UnicodeDecodeError as e:
        return {"ok": False, "errors": "That file's text encoding couldn't be read. Save it as UTF-8 and try again.", "details": str(e)}
    except json.JSONDecodeError as e:
        return {"ok": False, "errors": f"That settings file has invalid text at line {e.lineno}, column {e.colno}. "
                "Your current firewall hasn't changed. Choose another backup.", "details": str(e)}
    except (ValueError, RecursionError) as e:
        return {"ok": False, "errors": "That file isn't a valid Starchaser firewall settings file.", "details": str(e)}
    except OSError as e:
        return {"ok": False, "errors": "That file couldn't be opened.", "details": str(e)}
    if not is_firewall_backup(d):
        return {"ok": False, "errors": "This isn't a Starchaser firewall backup. Choose a file made with Back up settings."}
    if fw is None:
        return {"ok": False, "errors": "The firewall engine isn't installed, so the file can't be checked."}
    try:
        pol = fw.validate({k: v for k, v in d.items() if k not in (EXPORT_MARK, "saved", "computer", "handWrittenRules")})
    except fw.PolicyError as e:
        return {"ok": False, "errors": f"That file's settings can't be used here: {e}. Your current firewall hasn't changed. Choose another backup."}
    def plain(s) -> str:                         # a file from elsewhere: its names are shown, never as markup
        return fw.clean_name(s).replace("<", "\u2039").replace(">", "\u203a")
    for key in ("networks", "addresses", "services", "rules"):
        for x in pol.get(key) or []:
            if isinstance(x, dict) and "name" in x:
                x["name"] = plain(x["name"])
    source = Path(path)
    return {"ok": True, "errors": "", "policy": pol, "name": plain(source.name),
            "folder": plain(source.parent.name or str(source.parent)),
            "computer": plain(d.get("computer")), "saved": plain(d.get("saved")),
            "handWrittenText": d["handWrittenRules"]["text"] if d.get(EXPORT_MARK) == 2 else None,
            "warning": EXTRA_RESTORE if d.get(EXPORT_MARK) == 2 and d["handWrittenRules"]["text"] is not None else
                "Import leaves this computer's hand-written rules file unchanged."}


def ruleset() -> str:
    """The saved rules file, headed by a comment line that says what it is. Messages go to stdout as
    comment lines because Settings > Firewall > Rules only reads stdout."""
    enabled = bool(jread(POLICY, {}).get("enabled"))
    try:
        # off: the last rules are kept as firewall.nft.off (an older engine left them as firewall.nft)
        text = (NFT_OFF if not enabled and NFT_OFF.exists() else NFT).read_text()
    except FileNotFoundError:
        if enabled:
            return ("# The firewall is set to on, but its rules file is missing. Click Reload saved firewall to rebuild\n"
                    "# it from your settings; the firewall stays on the whole time.")
        return "# The firewall is off, and no rules have been made yet."
    except PermissionError:
        return "# Can't read the saved rules (permission denied)."
    except OSError as e:
        return f"# Can't read the saved rules ({e.strerror or e})."
    loaded = table_loaded()
    lv = live()
    if loaded is None and lv["fresh"]:
        loaded = lv["loaded"]
    # the root-side check counts only when it was made after the last change (the page's rule: a second after the
    # newest History entry); one from before it ("Reload saved firewall" a moment ago) would still describe the old
    # table and say these rules aren't running
    last = max((int(jread(f, {}).get("time") or 0) for f in (HISTORY.glob("*.json") if HISTORY.is_dir() else [])), default=0)
    checked = lv["fresh"] and lv["checked"] > last + 1
    if not enabled:
        head = "# The firewall is off. These are the last rules saved for it; they aren't running."
    elif lv["fresh"] and lv["emergency"]:
        # (first: the strict table turns everything away even beside rules a restart of the unit left loaded, so
        # "the firewall is on, these are the rules it's running" would be wrong whatever else is loaded)
        head = ("# These rules didn't load when the computer started, so strict backup rules are running instead:\n"
                "# nothing gets in. Click Reload saved firewall to try these once more.")
    elif loaded is True and checked and lv["matches"] is False:
        head = ("# The firewall is set to on, but the rules running now aren't these. Click Reload saved firewall to\n"
                "# put these back; the firewall stays on the whole time.")
    elif loaded is True and checked and lv["matches"] is True:
        # The structural check excludes changing set contents and counters; this text comes from the saved file.
        head = ("# The firewall is on. These are saved firewall instructions for incoming connections, plus a backup copy of\n"
                "# outgoing blocks that cover every app; all outgoing rules are listed in Settings > Firewall > Rules.\n"
                "# This saved file does not show current network assignments, temporary permissions or connection counts.")
    elif loaded is True and checked and lv["matches"] == "unknown":
        head = ("# The firewall is on, but Starchaser couldn't confirm that these rules loaded. Click Reload saved\n"
                "# firewall to load them and check.")
    elif loaded is False and lv["fresh"] and lv["emergency"]:
        head = ("# These rules didn't load when the computer started, so strict backup rules are running instead:\n"
                "# nothing gets in. Click Reload saved firewall to try these once more.")
    elif loaded is False:
        head = ("# The firewall is set to on, but these rules are not running right now. Click Reload saved firewall to\n"
                "# load them.")
    else:
        head = "# The firewall is set to on. These are the rules it was last given (this view can't check that they're running)."
    return head + "\n\n" + text.rstrip("\n")


def usage_error(msg: str):
    print(f"starchaser firewall: {msg}", file=sys.stderr)
    print("Run 'starchaser firewall --help' for more help.", file=sys.stderr)
    sys.exit(2)


def public_pause_action(action: str) -> dict:
    """Use the same privileged action as Settings; never save a separate CLI policy."""
    door = "/usr/local/lib/starchaser/starchaser-admin-area"
    if not os.access(door, os.X_OK):
        door = "/usr/local/lib/starchaser/starchaser-admin"
    command = ["pkexec", door, "firewall-public-pause-" + ("on" if action == "on" else "off")]
    if action in ("end", "undo"):
        command.append("--undo")
    try:
        result = subprocess.run(command, capture_output=True, text=True)
        reply = json.loads(result.stdout)
        if isinstance(reply, dict) and isinstance(reply.get("ok"), bool) and (not reply["ok"] or result.returncode == 0):
            return reply
    except (OSError, ValueError):
        pass
    return {"ok": False, "errors": "Public pause didn't finish. Check Settings > Firewall before trying again."}


def copy_permissions(source, target):
    """Portable permissions go after the target's own rules; never copy identities, child users or VPN endpoints."""
    if fw is None: raise ValueError("The firewall engine is unavailable.")
    source = fw.validate(source)
    result = fw.validate(target)
    for policy in (source, result):
        for kind in ("addresses", "services"):
            ids = [item["id"] for item in policy[kind]]
            if len(ids) != len(set(ids)):
                raise ValueError(f"Can't copy permissions with duplicate {kind} IDs.")
    portable = [r for r in source["rules"] if not r.get("network") and not r.get("iface") and r.get("user", "any") == "any"
                and not r.get("app", "").startswith(("program:", "flatpak:"))]
    used_addresses = {a for r in portable for a in r["peers"] if a != "any"}
    used_services = {s for r in portable if isinstance(r["service"], list) for s in r["service"]}
    # Hash the full ID rather than truncating it: repeated copies must never merge distinct groups or rules.
    # The fixed length stays within the engine's 64-character limit at every hop.
    prefix = "copy-" + hashlib.sha256(json.dumps(source, sort_keys=True).encode()).hexdigest()[:10] + "-"
    mappings = {}
    for kind, items in (("addresses", source["addresses"]), ("services", source["services"]), ("rules", portable)):
        mapping = {item["id"]: prefix + hashlib.sha256((kind + ":" + item["id"]).encode()).hexdigest()[:48]
                   for item in items}
        if len(set(mapping.values())) != len(mapping):
            raise ValueError(f"Can't copy permissions: {kind} ID collision.")
        mappings[kind] = mapping

    def append_checked(kind, item):
        existing = next((g for g in result[kind] if g["id"] == item["id"]), None)
        if existing is None:
            result[kind].append(item)
        elif existing != item:
            raise ValueError(f"Can't copy permissions: {kind} ID collision.")

    for kind, used in (("addresses", used_addresses), ("services", used_services)):
        for group in source[kind]:
            if group["id"] in used:
                append_checked(kind, dict(group, id=mappings[kind][group["id"]]))
    for rule in portable:
        r = dict(rule, id=mappings["rules"][rule["id"]])
        r["peers"] = [mappings["addresses"][a] if a != "any" else a for a in r["peers"]]
        if isinstance(r["service"], list): r["service"] = [mappings["services"][x] for x in r["service"]]
        append_checked("rules", r)
    return fw.validate(result)


def probe_ports(address, ports):
    address = str(ipaddress.ip_address(address))
    if len(ports) > 16 or not ports or any(type(p) is not int or not 1 <= p <= 65535 for p in ports):
        raise ValueError("Choose from 1 to 16 TCP ports, each from 1 to 65535.")
    rows = []
    for port in ports:
        try:
            with socket.create_connection((address, port), timeout=1): pass
            result = "reachable"
        except ConnectionRefusedError: result = "no-service"
        except OSError: result = "unknown"
        rows.append({"address": address, "port": port, "result": result})
    return {"ok": True, "ports": rows,
            "message": "This checks only these TCP ports from this computer. A timeout can't prove that the internet can't see you."}


def change_draft(pol, command, app, network="", duration="", incoming=False, uid=None, zone=""):
    """Build exactly the policy the terminal will submit; validation and application stay in the root helper."""
    if fw is None: raise ValueError("The firewall engine is unavailable.")
    if zone and zone not in fw.ZONES: raise ValueError("Choose a valid network kind for --zone.")
    if network and zone: raise ValueError("Choose either --network or --zone.")
    draft = copy.deepcopy(pol)
    if not draft.get("enabled"): raise ValueError("Turn on the firewall before changing app permissions.")
    if command == "trust":
        if not re.fullmatch(r"[0-9a-f-]{36}", app): raise ValueError("trust needs a saved network ID.")
        row = next((n for n in draft.get("networks", []) if n["uuid"] == app), None)
        if row is None:
            net = next((n for n in networks_now() if n["uuid"] == app), None)
            if not net: raise ValueError("That network isn't connected or saved.")
            row = {"uuid": app, "name": net["name"], "zone": "trusted"}
            draft.setdefault("networks", []).append(row)
        row["zone"] = "trusted"
    else:
        if app.startswith("/"): app = "program:" + app
        if not app.startswith(("program:/", "flatpak:")) and app not in fw.catalog():
            raise ValueError("No app is called " + app + ". See the names with: starchaser firewall apps")
        direction = "in" if incoming else "out"
        if network and direction == "out": raise ValueError("Outgoing permissions use --zone; --network is for incoming permissions.")
        ident = "cli-" + hashlib.sha256((direction + app).encode()).hexdigest()[:20]
        rule = dict(id=ident, name=("Allow " if command == "allow" else "Block ") + app, enabled=True,
                    dir=direction, action=command, app=app, service="app-default" if incoming else "any",
                    zones=["any"], peers=["any"], user="any" if incoming else str(os.getuid() if uid is None else uid))
        if network:
            if network in fw.ZONES: rule["zones"] = [network]
            else: rule["network"] = network
        if zone: rule["zones"] = [zone]
        if duration:
            raise ValueError("Use temporary-access for a timed incoming address and port permission.")
        draft["rules"] = [rule] + [r for r in draft.get("rules", []) if r["id"] != ident]
    return fw.validate(draft)


def submit_draft(draft, base, message):
    with tempfile.TemporaryDirectory(prefix="starchaser-firewall-") as folder:
        path, old = Path(folder) / "request.json", Path(folder) / "base.json"
        path.write_text(json.dumps(draft)); old.write_text(json.dumps(base))
        path.chmod(0o600); old.chmod(0o600)
        helper = "/usr/local/lib/starchaser/starchaser-admin-area"
        if not os.access(helper, os.X_OK): helper = "/usr/local/lib/starchaser/starchaser-admin"
        result = subprocess.run(["pkexec", helper, "firewall-commit", str(path), "--base", str(old),
                                 "--timeout", "30", "--summary", message], capture_output=True, text=True)
        try: reply = json.loads(result.stdout)
        except ValueError: return {"ok": False, "errors": "The firewall change didn't finish."}
        if reply.get("ok") and reply.get("timed"):
            reply["next"] = "Run starchaser firewall keep within 30 seconds, or starchaser firewall revert."
        return reply


def change_words(result):
    """Human-facing commands use words; state and privileged helper responses remain machine-readable."""
    if not result.get('ok'): return result.get('errors') or "The change did not finish."
    return (result.get('message') or "Saved your firewall change.") + ("\n" + result['next'] if result.get('next') else "")


def expert_change(words):
    import argparse
    parser = argparse.ArgumentParser(prog="starchaser firewall " + words[0])
    parser.add_argument("app", help="Catalog ID from starchaser firewall apps, executable path, or flatpak:app.id")
    scope = parser.add_mutually_exclusive_group()
    scope.add_argument("--network", default="")
    scope.add_argument("--zone", choices=("trusted", "public", "vpn", "tailscale"), default="")
    parser.add_argument("--for", dest="duration", default="")
    parser.add_argument("--incoming", action="store_true")
    args = parser.parse_args(words[1:])
    snapshot = policy_state()
    if snapshot["policyUnreadable"]: return {"ok": False, "errors": "Couldn't read firewall settings."}
    if args.duration:
        duration = {"15m": 15, "2h": 120, "network": 1440}.get(args.duration)
        if words[0] != "allow" or duration is None or not args.network:
            return {"ok": False, "errors": "Timed app access needs allow, --network <connected network ID>, and --for 15m, 2h, or network."}
        app = "program:" + args.app if args.app.startswith("/") else args.app
        result = subprocess.run(["pkexec", "/usr/local/lib/starchaser/starchaser-admin", "firewall-allow-app-temporary", app, args.network, str(duration)], capture_output=True, text=True)
        try:
            reply = json.loads(result.stdout)
            if reply.get('ok'):
                item = fw.catalog().get(app, {})
                name = item.get('plain') or item.get('name') or args.app
                net = next((n['name'] for n in networks_now() if n['uuid'] == args.network), args.network)
                lasts = 'until you leave this network (up to 24 hours)' if args.duration == 'network' else 'for ' + str(duration) + ' minutes'
                reply['message'] = name + ' is allowed on ' + net + ' ' + lasts + '. Leaving this network ends it.'
            return reply
        except ValueError: return {"ok": False, "errors": "Temporary app access didn't finish."}
    try: draft = change_draft(snapshot["policy"], words[0], args.app, args.network, args.duration, args.incoming, zone=args.zone)
    except (ValueError, fw.PolicyError) as e: return {"ok": False, "errors": str(e)}
    return submit_draft(draft, snapshot["policy"], words[0].capitalize() + " " + args.app + " from the terminal")


if __name__ == "__main__":
    args = sys.argv[1:]
    cmd = args[0] if args else "state"
    if cmd == "status":                               # the name starchaser usb and starchaser security use
        cmd = "state"
    if cmd in ("-h", "--help", "help") or any(a in ("-h", "--help") for a in args[1:]):   # help after the verb too
        print(__doc__.strip())
        sys.exit(0)
    if cmd == "state":
        if len(args) > 1:
            usage_error("state doesn't take anything after it.")
        check_now()
        print(json.dumps(state()))
    elif cmd == "copy-check":
        try:
            source = json.loads(sys.stdin.read(1024 * 1024 + 1))
            snapshot = policy_state()
            if snapshot["policyUnreadable"]: raise ValueError("Couldn't read the target firewall settings.")
            print(json.dumps({"ok": True, "base": snapshot["policy"], "policy": copy_permissions(source, snapshot["policy"])}))
        except (ValueError, fw.PolicyError) as e:
            print(json.dumps({"ok": False, "errors": str(e)})); sys.exit(1)
    elif cmd == "probe":
        try:
            if len(args) != 3: raise ValueError("probe needs an address and comma-separated TCP ports.")
            print(json.dumps(probe_ports(args[1], [int(p) for p in args[2].split(",")])))
        except ValueError as e: usage_error(str(e))
    elif cmd in ("allow", "block", "trust"):
        result = expert_change(args)
        print(change_words(result))
        sys.exit(0 if result.get("ok") else 1)
    elif cmd == "apps":
        for key, item in sorted((fw.catalog() if fw else {}).items()):
            print(key + " — " + (item.get("plain") or item.get("name") or key))
        print("For another app, use its executable path, such as /usr/bin/curl, or flatpak:app.id.")
    elif cmd in ("keep", "revert"):
        trial = jread(PENDING, {}) or {}
        if not trial.get("id"): usage_error("There is no change waiting for Keep.")
        sys.exit(subprocess.run(["pkexec", "/usr/local/lib/starchaser/starchaser-firewall-keep",
                                "firewall-confirm" if cmd == "keep" else "firewall-revert", trial["id"]]).returncode)
    elif cmd == "end-temporary":
        grants = [o for o in jread(STATS, {}).get("allowedOnce", []) if o.get("until", 0) > time.time()]
        for grant in grants:
            command = ["pkexec", "/usr/local/lib/starchaser/starchaser-admin-area", "firewall-revoke-once", grant["addr"], grant["proto"], str(grant["port"])]
            if grant.get("iface"): command += ["--iface", grant["iface"]]
            result = subprocess.run(command, capture_output=True, text=True)
            if result.returncode:
                print(json.dumps({"ok": False, "errors": "Some temporary permissions couldn't be ended. Open Firewall to check."})); sys.exit(1)
        print(json.dumps({"ok": True}))
    elif cmd == "activity":
        print(json.dumps(Activity().read()))
    elif cmd == "summary":
        if len(args) > 1:
            usage_error("summary doesn't take anything after it.")
        check_now()
        print(summary(state()))
    elif cmd == "public-pause":
        words = args[1:]
        structured = len(words) == 2 and words[-1] == "--json"
        if structured:
            words = words[:-1]
        if len(words) != 1 or words[0] not in ("on", "end", "off", "undo"):
            usage_error("public-pause takes on or end, optionally followed by --json.")
        r = public_pause_action(words[0])
        print(json.dumps(r) if structured else ((r.get("message", "") + " " + r.get("warning", "")).strip()
                                               if r["ok"] else r.get("errors", "Public pause failed.")))
        sys.exit(0 if r["ok"] else 1)
    elif cmd == "log":
        if len(args) > 2:
            usage_error("log takes one number at most, like: starchaser firewall log 200")
        n = 200
        if len(args) == 2:
            raw = args[1].strip()
            if not re.fullmatch(r"[0-9]{1,4}", raw) or not 1 <= int(raw) <= LOG_MAX:
                usage_error(f"log: N must be a whole number from 1 to {LOG_MAX}, like 200 (got \"{args[1]}\").")
            n = int(raw)
        print(json.dumps(blocked(n)))
        if unreadable:
            sys.exit(3)
    elif cmd == "ruleset":
        if args[1:] == ["--save"]:
            print(json.dumps(save_new("Starchaser firewall rules", ".nft", ruleset() + "\n")))
            sys.exit(0)
        if len(args) > 1:
            usage_error("ruleset takes only --save after it.")
        print(ruleset())
    elif cmd == "export":
        if len(args) > 1:
            usage_error("export doesn't take anything after it.")
        r = export()
        print(json.dumps(r))
        sys.exit(0 if r["ok"] else 1)
    elif cmd == "import-files":
        if len(args) > 1:
            usage_error("import-files doesn't take anything after it.")
        print(json.dumps(import_files()))
    elif cmd == "analyze":
        if len(args) != 1 or fw is None:
            usage_error("analyze reads firewall policies from its input.")
        import firewall_analysis
        try:
            data = sys.stdin.buffer.read(1024 * 1024 + 1)
            if len(data) > 1024 * 1024:
                raise ValueError("The firewall check is too large.")
            result = firewall_analysis.batch(fw, json.loads(data))
            print(json.dumps({"ok": True, "answers": result}))
        except (OSError, ValueError, TypeError, KeyError) as error:
            print(json.dumps({"ok": False, "errors": str(error)}))
            sys.exit(1)
    elif cmd == "import-check":
        if len(args) != 2:
            usage_error("import-check takes one file, like: starchaser firewall import-check ~/Documents/firewall.json")
        r = import_check(args[1])
        print(json.dumps(r))
        sys.exit(0 if r["ok"] else 1)
    else:
        usage_error(f"unknown command '{cmd}'.")
