Files
Panama/config/dot/quickshell/scripts/panama-sharing
T
Gabriel Brown a23b42841a Own user accounts and sharing
Two of the panels this desktop still handed to GNOME Settings.

Users manages the account through accountsservice -- the same daemon
GNOME's panel drives, so a name or picture set here is what the login
screen and lock screen read. Name, picture, account type, password,
automatic login, and adding or removing other accounts. Every change is
authorized by polkit through the agent this session already runs; a
dismissed prompt is a normal outcome and says so.

A new password is read from the helper's stdin, hashed by openssl
reading its own stdin, and handed over D-Bus from inside that process.
It is never an argument: argv is world-readable through /proc, so a
password passed that way is published to every process on the machine.
Removing an account takes two presses and says it destroys their files;
the last administrator cannot be removed or demoted, because a machine
nobody can administer is not a state to offer.

Sharing reports what is actually true, including "the software for this
is not installed" -- the honest answer for Samba here, and the case the
panel it replaces shows as a switch that does nothing. Password sign-in
is reported from sshd's configuration rather than assumed: claiming
"keys only" when the file is silent would state a security property that
cannot be backed up.

The Control Center now draws the account's real picture and name. A
generic glyph sat there while a real avatar was already set, which made
the desktop look like it did not know whose it was.

Also here: the KDE Connect contract no longer requires a phone to be
awake. kdeconnectd drops its device objects for a phone it has not seen
recently while the pairing survives in its config, so demanding one
failed whenever the phone was off.

Claude-Session: https://claude.ai/code/session_01BRvzt4H8XXLPVH5MyYdk9L
2026-08-19 13:05:13 -04:00

189 lines
7.1 KiB
Python
Executable File

#!/usr/bin/env python3
"""What this machine offers to other machines, and switches for it.
Every row reports what is actually true, including "the software for this is not
installed". GNOME's Sharing panel shows switches for services that are absent,
which is how a switch ends up doing nothing at all.
Enabling remote login is a system-wide change and goes through pkexec, which
prompts with the polkit agent this desktop already runs. Remote desktop is a
user service and needs no privilege.
panama-sharing snapshot
panama-sharing set-remote-login true|false
panama-sharing set-remote-desktop true|false
panama-sharing set-hostname NAME
"""
from __future__ import annotations
import json
import re
import shutil
import subprocess
import sys
from pathlib import Path
HOSTNAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9-]{0,62}$")
class BoundaryError(RuntimeError):
"""A user-visible validation or permission failure."""
def run(command: list[str], timeout: float = 25.0) -> subprocess.CompletedProcess:
try:
return subprocess.run(command, capture_output=True, text=True,
timeout=timeout, check=False)
except (OSError, subprocess.TimeoutExpired) as error:
raise BoundaryError(f"{command[0]} did not answer.") from error
def unit_state(unit: str, user: bool = False) -> dict:
scope = ["--user"] if user else []
active = run(["systemctl", *scope, "is-active", unit]).stdout.strip()
enabled = run(["systemctl", *scope, "is-enabled", unit]).stdout.strip()
return {
"installed": enabled not in ("", "not-found"),
"active": active == "active",
"enabled": enabled == "enabled",
}
def ssh_setting(name: str) -> str:
"""What sshd's own configuration says, or "" when it says nothing.
`sshd -T` would be authoritative but needs root. Reading the files means
reporting "not configured" rather than guessing a default -- which matters,
because claiming "keys only" on a machine that actually accepts passwords
would be a security claim this cannot back up.
"""
paths = [Path("/etc/ssh/sshd_config")]
paths.extend(sorted(Path("/etc/ssh/sshd_config.d").glob("*.conf"))
if Path("/etc/ssh/sshd_config.d").is_dir() else [])
pattern = re.compile(rf"^\s*{name}\s+(\S+)", re.IGNORECASE)
for path in paths:
try:
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
found = pattern.match(line)
if found:
return found.group(1)
except OSError:
continue
return ""
def remote_desktop() -> dict:
state = unit_state("gnome-remote-desktop.service", user=True)
state["available"] = bool(shutil.which("grdctl"))
state["rdpEnabled"] = False
state["port"] = ""
state["hasCredentials"] = False
if not state["available"]:
return state
status = run(["grdctl", "status"]).stdout
section = status.split("RDP:", 1)
if len(section) > 1:
block = section[1].split("VNC:", 1)[0]
state["rdpEnabled"] = re.search(r"Status:\s*enabled", block) is not None
port = re.search(r"Port:\s*(\d+)", block)
state["port"] = port.group(1) if port else ""
# grdctl prints "(hidden)" when a credential is stored and nothing when
# it is not, so this reads presence without ever reading the value.
state["hasCredentials"] = "(hidden)" in block
return state
def snapshot() -> dict:
static_name = run(["hostnamectl", "--static"]).stdout.strip()
pretty_name = run(["hostnamectl", "--pretty"]).stdout.strip()
login = unit_state("sshd.service")
login["port"] = ssh_setting("Port") or "22"
login["passwordAuthentication"] = ssh_setting("PasswordAuthentication")
login["rootLogin"] = ssh_setting("PermitRootLogin")
return {
"hostname": static_name,
"prettyHostname": pretty_name,
"remoteLogin": login,
"remoteDesktop": remote_desktop(),
# Reported as absent rather than offered as a switch that would do
# nothing. Installing software is not this page's job.
"fileSharing": {"installed": bool(shutil.which("smbd")), "package": "samba"},
"mediaSharing": {"installed": bool(shutil.which("rygel")), "package": "rygel"},
"error": "",
}
def set_remote_login(enabled: bool) -> None:
if not unit_state("sshd.service")["installed"]:
raise BoundaryError("OpenSSH server is not installed.")
action = ["enable", "--now"] if enabled else ["disable", "--now"]
result = run(["pkexec", "systemctl", *action, "sshd.service"], timeout=120)
if result.returncode != 0:
raise BoundaryError(_refusal(result, "Remote login could not be changed."))
def set_remote_desktop(enabled: bool) -> None:
state = remote_desktop()
if not state["available"]:
raise BoundaryError("Remote desktop support is not installed.")
if enabled and not state["hasCredentials"]:
raise BoundaryError("Set a remote desktop username and password first.")
toggle = run(["grdctl", "rdp", "enable" if enabled else "disable"])
if toggle.returncode != 0:
raise BoundaryError(_refusal(toggle, "Remote desktop could not be changed."))
action = ["enable", "--now"] if enabled else ["disable", "--now"]
result = run(["systemctl", "--user", *action, "gnome-remote-desktop.service"], timeout=60)
if result.returncode != 0:
raise BoundaryError(_refusal(result, "The remote desktop service could not be changed."))
def set_hostname(name: str) -> None:
if not HOSTNAME.fullmatch(name or ""):
raise BoundaryError("A name may use letters, digits and hyphens.")
result = run(["hostnamectl", "set-hostname", name], timeout=60)
if result.returncode != 0:
raise BoundaryError(_refusal(result, "The name could not be changed."))
def _refusal(result: subprocess.CompletedProcess, fallback: str) -> str:
text = (result.stderr or "").strip().splitlines()
if text and ("not authorized" in text[-1].lower() or "dismissed" in text[-1].lower()):
return "That change was not authorized."
return text[-1][:200] if text else fallback
def main(arguments: list[str]) -> int:
try:
if arguments == ["snapshot"]:
print(json.dumps(snapshot(), separators=(",", ":")))
return 0
if len(arguments) == 2 and arguments[0] == "set-remote-login":
set_remote_login(arguments[1] == "true")
elif len(arguments) == 2 and arguments[0] == "set-remote-desktop":
set_remote_desktop(arguments[1] == "true")
elif len(arguments) == 2 and arguments[0] == "set-hostname":
set_hostname(arguments[1])
else:
raise BoundaryError(
"Usage: panama-sharing snapshot | set-remote-login true|false | "
"set-remote-desktop true|false | set-hostname NAME")
except BoundaryError as error:
state = snapshot()
state["error"] = str(error)
print(json.dumps(state, separators=(",", ":")))
return 0
print(json.dumps(snapshot(), separators=(",", ":")))
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))