From bc07e1d3e3462b048b818dfa5188b627636185b1 Mon Sep 17 00:00:00 2001 From: David Young Date: Wed, 11 Nov 2026 14:20:47 -0700 Subject: [PATCH] Set up Pop!_OS for a Federated Core, like CoreDesktop's configure A port of CoreDesktop's configure to Pop!_OS 24.04 with COSMIC, in the shape of connector-macos: its own install.sh, update and configure, installed in ~/.local/share/federated-connector/connector. Every configure item is ported: the Core (email, calendars and contacts through GNOME Online Accounts and Evolution, as COSMIC has no accounts of its own; Superpanel; files over davfs2; Element; Tally; the email watcher), Tailscale, backups, AI agents in the sandbox and their sign-ins, languages with mise, AI servers, printers, network storage and the agent sandbox. Folders go in the COSMIC Files sidebar. Each item installs what it needs from apt, Flathub or the tool's own apt repository when you set it up. smoketest/run checks it in Ubuntu 24.04 containers with Docker. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 2 + .shellcheckrc | 7 + LICENSE.md | 9 + Makefile | 16 + README.md | 179 ++++ configure | 169 ++++ configure.d/10-core.sh | 919 ++++++++++++++++++ configure.d/15-tailscale.sh | 93 ++ configure.d/20-backup.sh | 188 ++++ configure.d/30-agents.sh | 260 +++++ configure.d/31-claude.sh | 29 + configure.d/32-opencode.sh | 26 + configure.d/33-hermes.sh | 30 + configure.d/40-languages.sh | 98 ++ configure.d/50-ai-servers.sh | 274 ++++++ configure.d/55-printers.sh | 21 + configure.d/60-storage.sh | 319 ++++++ configure.d/65-sandbox.sh | 83 ++ configure.d/lib/agents.sh | 47 + configure.d/lib/cosmic-favorites | 127 +++ configure.d/lib/goa-account | 263 +++++ configure.d/lib/json.sh | 20 + configure.d/lib/mdns.sh | 48 + configure.d/lib/nextcloud.sh | 48 + configure.d/lib/packages.sh | 60 ++ configure.d/lib/sidebar.sh | 32 + configure.d/lib/tools.sh | 74 ++ install.sh | 256 +++++ sandbox/agent | 145 +++ sandbox/bin/cline-desktop | 1 + sandbox/bin/hermes | 1 + sandbox/bin/hermes-agent | 1 + sandbox/bin/opencode | 1 + sandbox/bin/unsandboxed | 1 + sandbox/config/base.json | 96 ++ sandbox/config/cline-desktop.json | 35 + sandbox/config/hermes.json | 26 + sandbox/config/opencode.json | 21 + sandbox/hermes-bridge | 81 ++ smoketest/Dockerfile | 15 + smoketest/README.md | 61 ++ smoketest/lib/runner.sh | 91 ++ smoketest/run | 111 +++ smoketest/scenarios/05-install.sh | 29 + smoketest/scenarios/10-configure.sh | 24 + smoketest/scenarios/20-goa.sh | 54 + smoketest/scenarios/30-core-local.sh | 81 ++ smoketest/scenarios/40-backup.sh | 45 + smoketest/scenarios/50-sandbox.sh | 48 + smoketest/scenarios/60-packages.sh | 43 + system/backup | 104 ++ system/backup-env.sh | 44 + system/email-watch | 227 +++++ system/run-in-terminal | 27 + system/setup-printers.sh | 406 ++++++++ system/sftp-mount | 34 + .../federated-connector-backup.service | 9 + .../systemd/federated-connector-backup.timer | 11 + .../federated-connector-email-watch.service | 14 + update | 42 + 60 files changed, 5626 insertions(+) create mode 100644 .gitignore create mode 100644 .shellcheckrc create mode 100644 LICENSE.md create mode 100644 Makefile create mode 100644 README.md create mode 100755 configure create mode 100755 configure.d/10-core.sh create mode 100644 configure.d/15-tailscale.sh create mode 100644 configure.d/20-backup.sh create mode 100644 configure.d/30-agents.sh create mode 100644 configure.d/31-claude.sh create mode 100644 configure.d/32-opencode.sh create mode 100644 configure.d/33-hermes.sh create mode 100644 configure.d/40-languages.sh create mode 100644 configure.d/50-ai-servers.sh create mode 100644 configure.d/55-printers.sh create mode 100644 configure.d/60-storage.sh create mode 100644 configure.d/65-sandbox.sh create mode 100644 configure.d/lib/agents.sh create mode 100755 configure.d/lib/cosmic-favorites create mode 100755 configure.d/lib/goa-account create mode 100644 configure.d/lib/json.sh create mode 100644 configure.d/lib/mdns.sh create mode 100644 configure.d/lib/nextcloud.sh create mode 100644 configure.d/lib/packages.sh create mode 100644 configure.d/lib/sidebar.sh create mode 100644 configure.d/lib/tools.sh create mode 100755 install.sh create mode 100755 sandbox/agent create mode 120000 sandbox/bin/cline-desktop create mode 120000 sandbox/bin/hermes create mode 120000 sandbox/bin/hermes-agent create mode 120000 sandbox/bin/opencode create mode 120000 sandbox/bin/unsandboxed create mode 100644 sandbox/config/base.json create mode 100644 sandbox/config/cline-desktop.json create mode 100644 sandbox/config/hermes.json create mode 100644 sandbox/config/opencode.json create mode 100755 sandbox/hermes-bridge create mode 100644 smoketest/Dockerfile create mode 100644 smoketest/README.md create mode 100755 smoketest/lib/runner.sh create mode 100755 smoketest/run create mode 100644 smoketest/scenarios/05-install.sh create mode 100644 smoketest/scenarios/10-configure.sh create mode 100644 smoketest/scenarios/20-goa.sh create mode 100644 smoketest/scenarios/30-core-local.sh create mode 100644 smoketest/scenarios/40-backup.sh create mode 100644 smoketest/scenarios/50-sandbox.sh create mode 100644 smoketest/scenarios/60-packages.sh create mode 100755 system/backup create mode 100644 system/backup-env.sh create mode 100755 system/email-watch create mode 100755 system/run-in-terminal create mode 100755 system/setup-printers.sh create mode 100755 system/sftp-mount create mode 100644 system/systemd/federated-connector-backup.service create mode 100644 system/systemd/federated-connector-backup.timer create mode 100644 system/systemd/federated-connector-email-watch.service create mode 100755 update diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..054b0d6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +smoketest/results/ +.claude/ diff --git a/.shellcheckrc b/.shellcheckrc new file mode 100644 index 0000000..eef8cdc --- /dev/null +++ b/.shellcheckrc @@ -0,0 +1,7 @@ +# Hooks, configure items and config files are sourced from paths only known at +# run time +disable=SC1090 + +# mkdir -p -m only sets the mode of the last directory; every use here makes +# one directory in a parent that already exists +disable=SC2174 diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..c9f32f4 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,9 @@ +MIT License + +Copyright 2026 Federated Computer, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..9289279 --- /dev/null +++ b/Makefile @@ -0,0 +1,16 @@ +# Every tracked file (not symlink) that starts with a bash or sh shebang (\043 is "#", which +# make would otherwise read as the start of a comment) +SCRIPTS := $(shell git ls-files -s | awk '$$1 != 120000 { print $$4 }' | xargs awk 'FNR == 1 && /^#!.*[\/ ](ba)?sh/ { print FILENAME }') + +.PHONY: check lint smoketest + +check: lint smoketest + +# Errors and warnings only; drop --severity to see style notes too +lint: + shellcheck -x --severity=warning $(SCRIPTS) smoketest/scenarios/*.sh + python3 -m py_compile configure.d/lib/goa-account configure.d/lib/cosmic-favorites system/email-watch + find . -name __pycache__ -prune -exec rm -rf {} + + +smoketest: + smoketest/run --tier all diff --git a/README.md b/README.md new file mode 100644 index 0000000..3e65fac --- /dev/null +++ b/README.md @@ -0,0 +1,179 @@ +# Federated Connector for Pop!_OS + +Sets up a Pop!_OS computer for your Federated Core. It's the Pop!_OS counterpart of [CoreDesktop](https://gitea.federated.computer/Federated_Computer/coredesktop)'s `configure`, with the same items, and works the same way: it shows what's set up, sets up the rest, and can test and fix a Core later. + +## Requirements + +- Pop!_OS 24.04 with COSMIC. Most of it works on other Ubuntu 24.04-based systems too; `configure` says so if it's run on one. +- An administrator account (in the `sudo` group): `configure` installs packages and changes system settings such as mounts, printers and Tailscale. + +## Installing + +In a terminal: + +``` +curl -fsSL https://gitea.federated.computer/Federated_Computer/connector-popos/raw/branch/main/install.sh | bash +``` + +That URL points at [install.sh](install.sh) here on Gitea, so you can read what it runs first. It checks the computer first: Linux with apt, not run as root, and an internet connection. It warns if this isn't Pop!_OS, or if your account isn't an administrator. Then it: + +- installs the few packages `configure` itself needs: curl, jq, libsecret-tools, python3-gi, gir1.2-secret-1 and libnotify-bin +- downloads the latest version into `~/.local/share/federated-connector/connector`. Pop!_OS doesn't come with git, so it downloads an archive. +- adds the `configure` and `update` commands to `~/.local/bin` +- makes sure `~/.local/bin` is on your PATH, at the top of `~/.bashrc` +- offers to run `configure` + +Running it again reinstalls the latest version. The logs are in `~/.local/state/federated-connector/`. + +The install's folder never moves. That matters because the backup, email-watch and network storage services point into it. + +## Running it + +``` +configure # show what's set up and choose what to set up +configure core # set up one item +configure --list # show what's set up, and the item names +``` + +## Updating + +``` +update # get the latest version, showing what changed +update --version # the version installed +``` + +`update` downloads the latest version and swaps it in at once, so it's safe while a backup runs. It brings the services `configure` set up up to date too. Your settings, accounts, keyring items and downloaded tools stay as they are. + +Everything `configure` installs from apt (Evolution, davfs2, restic, Tailscale, mise...) is updated by Pop!_OS' own updates, in the COSMIC Store or with `sudo apt upgrade`. Flatpak apps such as Element update there too. + +## What it sets up + +Each item installs what it needs the first time you set it up, after asking. + +- **Your Federated Core.** Give it your Superpanel's address (e.g. https://superpanel.example.com), your Core email, name and password. It sets up: + - **Email, calendars and contacts**, shown in Evolution. COSMIC doesn't have online accounts of its own yet, so `configure` installs GNOME Online Accounts and Evolution and adds the accounts the way GNOME Settings would. GNOME Online Accounts runs on its own, without GNOME. Your passwords are kept in your keyring, which COSMIC unlocks when you log in. + - Email keeps your Core password, because the mail server doesn't take Nextcloud app passwords. Its settings come from the mail server's autoconfig, or the usual ones if the server doesn't publish them. + - Calendars and contacts use a Nextcloud app password, "Pop!_OS on {your computer}", which you can revoke in Nextcloud under Settings > Security. + - **Superpanel** in your applications (the COSMIC launcher and app library), with Superpanel's own icon. + - **Your Nextcloud files**, mounted at /mnt/example.com with davfs2, and shown in the COSMIC Files sidebar as "example.com". `configure` makes `mount.davfs` setuid and adds you to the `davfs2` group, so you can mount it without sudo. It mounts when you log in. + - **Element**, pointed at your Core's Matrix server, for your main Core. If Element isn't installed, it offers to install it from Flathub, as the COSMIC Store would. + - **Tally for Plausible**, if it's installed and your main Core runs Plausible Analytics: it's pointed at plausible.example.com. + - **An email watcher**, a user service that pauses your Core's email if its password stops working (see below). + + You can add more Cores: run `configure core` again and choose "Add a Core". Each gets its own Superpanel, accounts and files. Element, Tailscale and backups use your main Core (the first one, unless you choose another). + + `configure core` also offers: + - **Test a Core**: it checks Superpanel, calendars and contacts, email, your files, Element and backups the way this computer uses them, says which work, and offers to fix those that don't. If a fix needs it, for example a new app password for one that was revoked, it asks for your Core password. Then it tests again. + - **Your Core password changed**: email gets the new password, and signing in to Nextcloud with it turns the app passwords for calendars, contacts, files and backups back on (Nextcloud turns them off when your password changes). Then it checks each of them. + - **Remove a Core**: it removes the accounts, the mount and Superpanel, and revokes the app password. Everything on the Core itself stays as it is. +- **Tailscale**: joins this computer to your Core's Tailscale network through headscale.example.com. If Tailscale isn't installed, it installs it from Tailscale's own apt repository. You can use `tailscale` without sudo afterwards. To leave the network, run `configure tailscale` again. +- **Backup**: backs up your home folder daily to your Nextcloud files, in a `.backup-{computer name}` folder, with restic (from Ubuntu's packages). + - The backup is encrypted with a passphrase that `configure` shows you once. Save it somewhere other than this computer, such as Bitwarden. + - It keeps 7 daily, 4 weekly and 6 monthly backups. It leaves out caches, things that can be reinstalled, and Flatpak apps' caches. To leave out more, list paths in `~/.config/federated-connector/backup-exclude`, one per line. + - restic reaches Nextcloud directly through rclone, with its own Nextcloud app password ("Federated Backup on {your computer}"), so the backup doesn't depend on the /mnt mount. + - A systemd user timer runs it, and catches up at your next login if the computer was off. If a backup fails, you get a notification. To follow one: `journalctl --user -fu federated-connector-backup`. + - To turn backups off, run `configure backup` again. It also offers to delete the backups from your Nextcloud files (they go to Nextcloud's trash bin). +- **AI agents**: offers to install Claude Code, opencode and Hermes Agent with each one's own installer, and runs them in a sandbox (see below). `configure claude`, `configure opencode` and `configure hermes` sign in to them and choose their model providers. +- **Languages**: installs programming languages and tools with [mise](https://mise.jdx.dev), from mise's own apt repository: Ruby on Rails, or any tool mise knows (`mise registry` lists them), such as `node@lts` or `java@21`. To update them: `mise upgrade`. To remove one: `mise unuse -g `. +- **AI servers**: LLM servers on your network, such as Ollama on a Mac. It finds the machines on your network over mDNS and asks each one on the ports LLM servers use (11434 Ollama, 1234 LM Studio, 8080 llama.cpp, 8000 vLLM), since LLM servers don't announce themselves. Or you enter a server's address. For the server you choose, it: + - lets the sandboxed agents reach it (that port only) + - adds it to opencode with its models + - offers to make it Hermes' model + - lets the commands Claude Code runs reach it too + + A server has to accept connections from other machines: in Ollama's settings, turn on "Expose Ollama to the network"; in LM Studio, "Serve on Local Network". +- **Printers** on your network. It lists the printers it finds, whether they're reached directly or shared by another computer, and adds the ones you choose as printers on this computer, without drivers (IPP Everywhere), so they're in every print dialog. A printer another computer shares that can also be reached directly is marked, and not chosen unless you pick it. Printers already added (e.g. by cups-browsed) are left alone. To choose without being asked, set a default printer or print a test page, run `~/.local/share/federated-connector/connector/system/setup-printers.sh --help`. +- **Network storage**: shared folders from other machines on your network, mounted in /mnt and added to the COSMIC Files sidebar. It finds SMB servers (Windows, Samba and NAS boxes, and Macs with File Sharing on) and machines you can ssh to. Or you enter an address (`smb://nas.local/files`, `sftp://me@server.local/srv/data`). + - An SMB share is in /etc/fstab and mounts the first time you open its folder, so a server that's off doesn't hold anything up. Its password is kept in /etc/federated-connector/smb, readable only by root. + - An SFTP folder is mounted by sshfs as you, at login, with the SSH keys in your Bitwarden SSH agent or your keyring's, so the server has to accept one of them (it can't ask for a password). + - "Remove one" unmounts it and takes it back out. +- **Agent sandbox**, if WinBoat is set up: the sandbox hides WinBoat's settings (~/.winboat) from agents, since they include your Windows password. To let agents read them, run `configure sandbox` and switch it; switch it again to hide them. + +### When your Core password changes + +Your email keeps your Core password, so after you change it (e.g. in Superpanel), the mail server starts refusing the old one. Online Accounts tries it again each time your network changes, and Evolution each time it fetches mail. After a few wrong passwords, the mail server blocks this computer for a while. + +So the email watcher watches for it, without ever trying the password on the mail server: + +1. When your password changes, Nextcloud stops accepting the app passwords this computer uses, and Online Accounts notices. +2. The watcher then checks the password your email has with Nextcloud, once. +3. If Nextcloud says it's wrong, the watcher pauses your email: this computer stops trying the old password, and you get a notification. + +Click the notification to open `configure core` in COSMIC Terminal, choose "Your Core password changed" and enter your new password; that ends the pause. + +The Online Accounts that Pop!_OS 24.04 has (3.50) also flags an account when its server just can't be reached. The watcher and "Test a Core" don't take that to mean a wrong password: they check with Nextcloud first, and do nothing if Nextcloud can't be reached either. + +### Restoring from a backup + +To see the backups and get files back: + +``` +source ~/.local/share/federated-connector/connector/system/backup-env.sh +restic snapshots +restic restore latest --target ~/restored --include ~/Documents +``` + +On a new computer, run `configure core` and `configure backup` first. Then name the old computer's folder, and restic asks for the passphrase you saved: + +``` +source ~/.local/share/federated-connector/connector/system/backup-env.sh .backup-{old computer's name} +restic snapshots +``` + +## Sandboxed AI agents + +opencode, Hermes and Cline Desktop run in Anthropic's sandbox runtime (srt), which uses bubblewrap. In the sandbox, an agent: + +- can change files only in the folder you start it in (plus its own settings, /tmp and a few package caches), so start it from a project folder +- can't read your SSH keys, keyrings, password managers, browser profiles, Evolution's mail, calendars and contacts, Thunderbird, Element, cloud and Git credentials, or the other agents' logins +- can reach only AI providers and common developer sites: GitHub, Gitea, npm, PyPI, crates.io, RubyGems, the Go module proxy, and Ubuntu's and Pop!_OS' sites + +Typing `opencode`, `hermes` or `hermes-agent` runs it in the sandbox: `configure agents` adds a block at the end of ~/.bashrc that puts `sandbox/bin` first on PATH. To run one without the sandbox, type `unsandboxed opencode`. Claude Code uses its own built-in sandbox, also on bubblewrap, for every command it runs, which `configure agents` turns on (see `/sandbox` inside Claude). If you had no Claude Code settings, it also adds notifications for when Claude needs you and when it's done. + +If Hermes' gateway is set up as a service, `configure agents` runs it in the sandbox too, and lets it reach the Matrix server in Hermes' settings. If Cline Desktop is installed, its entry in the app library opens it in the sandbox. + +srt needs Node.js 22.12 or later, and Pop!_OS 24.04's is older. Unless a new enough one is installed already, `configure agents` downloads the current LTS from nodejs.org into `~/.local/share/federated-connector/node`, checks it against the SHA-256 sums nodejs.org publishes, and uses it only for srt. + +Ubuntu 24.04 lets only programs AppArmor allows make the user namespaces bubblewrap needs. If that stops the sandbox here, `configure agents` offers to add an AppArmor profile for `/usr/bin/bwrap` (`/etc/apparmor.d/federated-connector-bwrap`), as Ubuntu suggests. + +To allow more, put a file in the same format as `sandbox/config/base.json` in `~/.config/federated-connector/sandbox/`: `base.json` for every agent, or `.json` for one. Lists in it are added to the built-in ones. Domains in `FEDERATED_SANDBOX_DOMAINS` (space-separated) are allowed too. + +## Where things are + +- Your answers: `~/.config/federated-connector/`. That's `cores/.conf`, `core.conf` for the main Core, `tailscale.conf`, `backup.conf`, `storage`, `ai-servers`, `printers`, `languages`, `agents`, and your own `sandbox/` config. +- Accounts: GNOME Online Accounts (`~/.config/goa-1.0/accounts.conf`), with their passwords in your keyring +- The backup's app password and passphrase: your keyring, attributes `federated-connector backup` +- Your files' app password: `~/.davfs2/secrets` +- Services: `~/.config/systemd/user/federated-connector-{backup.service,backup.timer,email-watch.service,sftp-*.service}` +- The Files sidebar: `~/.config/cosmic/com.system76.CosmicFiles/v1/favorites`, and `~/.config/gtk-3.0/bookmarks` for GTK apps +- Federated Connector itself: `~/.local/share/federated-connector/connector`, with `configure` and `update` linked in `~/.local/bin` +- Downloaded tools: `~/.local/share/federated-connector` (`node`, `srt`) + +## Adding an item + +Each file in `configure.d/` is one item. It sets `TITLE` and `DESCRIPTION` and defines `is_configured` and `run_configure`. It can also define `is_installed`, and the item is left out when that fails. Items get `CONNECTOR`, `CONF_DIR`, `confirm` and `confirm_yes` from `configure`, and `pkg_ensure` to install what they need. Libraries are in `configure.d/lib/`: + +- `packages.sh`: apt packages and Flatpak apps +- `goa-account`: accounts in GNOME Online Accounts +- `nextcloud.sh`: app passwords +- `sidebar.sh` and `cosmic-favorites`: the Files sidebar +- `json.sh`: editing JSON settings files +- `mdns.sh`: finding things on the network with Avahi +- `agents.sh`: the agents' real commands and srt +- `tools.sh`: Node.js and srt + +`system/` has what runs in the background (`backup`, `email-watch`, `sftp-mount`) and their systemd units, and `sandbox/` has the sandbox wrapper and its config. + +## Testing + +`make lint` runs shellcheck. `smoketest/run` runs the scenarios in `smoketest/`, each in a fresh Ubuntu 24.04 container with Docker. See [smoketest/README.md](smoketest/README.md). + +## Differences from CoreDesktop + +- Email, calendars and contacts are shown in Evolution, as COSMIC has no Online Accounts of its own. CoreDesktop adds them to GNOME's Settings. +- What each item needs is installed when you set it up, from apt, Flathub or the tool's own apt repository, rather than all at install time. +- The Files sidebar is COSMIC Files'; folders are added to GTK's bookmarks too. +- davfs2 mounts need Ubuntu's setuid `mount.davfs` and the `davfs2` group, where Arch uses the `network` group. +- Languages come from mise's apt repository, and nothing is installed with it up front. CoreDesktop's `update` upgrades them; here, run `mise upgrade`. +- The agents are installed by `configure agents`, and srt runs on its own Node.js. On Ubuntu, bubblewrap may need an AppArmor profile. +- `update` updates only Federated Connector; Pop!_OS updates the rest. diff --git a/configure b/configure new file mode 100755 index 0000000..d4fd6fb --- /dev/null +++ b/configure @@ -0,0 +1,169 @@ +#!/bin/bash +# +# Purpose : Set up this Pop!_OS computer for your Federated Core (email, +# calendars, contacts, Superpanel, files, Element, Tailscale, +# backups) and its network (printers, shared folders, AI servers), +# and AI agents in a sandbox. What Pop!_OS doesn't come with is +# offered for install as each item needs it. +# +# Each file in configure.d/ is one item. It sets TITLE and DESCRIPTION and +# defines is_configured and run_configure. It can also define is_installed; +# the item is left out when that fails. To add an item, add a file there. + +# Wrapped in { ...; exit; } so bash reads the whole script up front; update +# replaces this file while it runs. +{ + +if [ "$(id -u)" -eq 0 ]; then + echo "Run configure as yourself, not as root. It asks for your password when it needs it." + exit 1 +fi + +# The directory this script is in, following the link in ~/.local/bin +CONNECTOR="$(cd "$(dirname "$(realpath "$0")")" && pwd)" +CONF_DIR="$HOME/.config/federated-connector" +PATH="$HOME/.local/bin:$PATH" +export CONNECTOR CONF_DIR + +source "$CONNECTOR/configure.d/lib/agents.sh" +source "$CONNECTOR/configure.d/lib/packages.sh" + +# Ask a yes/no question; the default is no +confirm() { + local answer + read -rp "$1 [y/N] " answer + [[ "$answer" == [yY]* ]] +} + +# Ask a yes/no question; the default is yes +confirm_yes() { + local answer + read -rp "$1 [Y/n] " answer + [[ "$answer" != [nN]* ]] +} + +usage() { + cat << EOF +Usage: configure [item] + + configure Show what's set up and choose what to set up + configure Set up one item + configure --list Show what's set up, and the item names + +EOF +} + +# configure.d/31-claude.sh -> claude +item_name() { + local name + name="$(basename "$1" .sh)" + echo "${name#[0-9][0-9]-}" +} + +# Prints "||<description>"; state is done, todo or absent +item_info() { + ( + source "$1" + if declare -f is_installed > /dev/null && ! is_installed &> /dev/null; then + echo "absent||" + elif is_configured &> /dev/null; then + echo "done|$TITLE|$DESCRIPTION" + else + echo "todo|$TITLE|$DESCRIPTION" + fi + ) +} + +configure_item() { + ( + source "$1" + echo + echo -e "\e[1m$TITLE\e[0m" + run_configure + ) + local status=$? + if [ $status -ne 0 ]; then + echo -e "\e[31m$(item_name "$1") was not set up.\e[0m" + fi + return $status +} + +# Fill ITEMS, STATES, TITLES and DESCRIPTIONS with the installed items +load_items() { + local file state title description + ITEMS=() STATES=() TITLES=() DESCRIPTIONS=() + for file in "$CONNECTOR"/configure.d/*.sh; do + [ -f "$file" ] || continue + IFS='|' read -r state title description < <(item_info "$file") + [ "$state" = absent ] && continue + ITEMS+=("$file") STATES+=("$state") TITLES+=("$title") DESCRIPTIONS+=("$description") + done +} + +show_items() { + local i mark + for i in "${!ITEMS[@]}"; do + if [ "${STATES[$i]}" = "done" ]; then + mark="\e[32mdone\e[0m " + else + mark="\e[33mto do\e[0m" + fi + printf " %2d) $mark %-22s %s\n" $((i + 1)) "${TITLES[$i]}" "${DESCRIPTIONS[$i]}" + done +} + +case "$1" in + "") ;; + -h|--help) + usage + exit 0 ;; + -l|--list) + load_items + for i in "${!ITEMS[@]}"; do + printf '%-6s %-14s %s\n' "${STATES[$i]/todo/to do}" "$(item_name "${ITEMS[$i]}")" "${TITLES[$i]}" + done + exit 0 ;; + *) + for file in "$CONNECTOR"/configure.d/*.sh; do + if [ "$(item_name "$file")" = "$1" ]; then + configure_item "$file" + exit + fi + done + echo "No item named $1. These are: configure --list" + exit 2 ;; +esac + +if ! is_pop; then + echo -e "\e[33mThis is made for Pop!_OS with COSMIC; this computer runs $(os_name).\e[0m" + echo "Most of it works on other Ubuntu-based systems too." +fi + +while true; do + load_items + echo + echo "Federated Core on this computer" + echo + show_items + echo + echo " a) Set up everything still to do" + echo " q) Quit" + echo + read -rp "Choose: " choice || exit 0 + + case "$choice" in + q|Q|"") + exit 0 ;; + a|A) + for i in "${!ITEMS[@]}"; do + [ "${STATES[$i]}" = todo ] && configure_item "${ITEMS[$i]}" + done ;; + *) + if [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= ${#ITEMS[@]} )); then + configure_item "${ITEMS[$((choice - 1))]}" + else + echo "Choose a number from the list, a or q." + fi ;; + esac +done +} diff --git a/configure.d/10-core.sh b/configure.d/10-core.sh new file mode 100755 index 0000000..83eda8f --- /dev/null +++ b/configure.d/10-core.sh @@ -0,0 +1,919 @@ +#!/bin/bash + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="Federated Core" +# shellcheck disable=SC2034 +DESCRIPTION="Email, calendars, contacts, Superpanel, files and Element" + +# Each Core is in cores/<domain>.conf, with what you entered last time, so +# running this again only does what's missing. core.conf is a copy of the main +# Core's: Element, Tailscale and Backup use that one. +CORE_CONF="$CONF_DIR/core.conf" +CORES_DIR="$CONF_DIR/cores" +TAILSCALE_CONF="$CONF_DIR/tailscale.conf" +BACKUP_CONF="$CONF_DIR/backup.conf" +GOA_ACCOUNT="$CONNECTOR/configure.d/lib/goa-account" +EMAIL_WATCH="$CONNECTOR/system/email-watch" +UNITS="$HOME/.config/systemd/user" +source "$CONNECTOR/configure.d/lib/nextcloud.sh" +source "$CONNECTOR/configure.d/lib/sidebar.sh" +[ -f "$CORE_CONF" ] && source "$CORE_CONF" +MAIN_DOMAIN="$CORE_DOMAIN" + +core_domains() { + local file + for file in "$CORES_DIR"/*.conf; do + [ -f "$file" ] && basename "$file" .conf + done +} + +load_core() { + CORE_DOMAIN="" CORE_EMAIL="" CORE_NAME="" + [ -n "$1" ] && source "$CORES_DIR/$1.conf" + core_names +} + +# CORE_DOMAIN, CORE_EMAIL and CORE_NAME come from core.conf; the rest follow +core_names() { + CORE_USER="${CORE_EMAIL%@*}" + NEXTCLOUD="https://nextcloud.$CORE_DOMAIN" + WEBDAV="$NEXTCLOUD/remote.php/dav/files/$CORE_USER" + MOUNT="/mnt/$CORE_DOMAIN" + SUPERPANEL_DESKTOP="$HOME/.local/share/applications/core-$CORE_DOMAIN-superpanel.desktop" + MATRIX="https://matrix.$CORE_DOMAIN" + ELEMENT_CONFIG="$(element_config)" + PLAUSIBLE="plausible.$CORE_DOMAIN" +} + +superpanel_done() { + [ -f "$SUPERPANEL_DESKTOP" ] +} + +nextcloud_done() { + "$GOA_ACCOUNT" exists owncloud "$CORE_USER@nextcloud.$CORE_DOMAIN" 2> /dev/null +} + +email_done() { + "$GOA_ACCOUNT" exists imap_smtp "$CORE_EMAIL" 2> /dev/null +} + +files_done() { + grep -qs " $MOUNT davfs " /etc/fstab && grep -qs "^$MOUNT " "$HOME/.davfs2/secrets" +} + +# Element from Flathub (as the COSMIC Store installs it), or the deb from +# packages.element.io +ELEMENT_FLATPAK=im.riot.Riot + +element_installed() { + flatpak_installed "$ELEMENT_FLATPAK" || command -v element-desktop > /dev/null +} + +# Element reads config.json in its own settings folder, which Flatpak keeps +# in the app's folder under ~/.var/app +element_config() { + if flatpak_installed "$ELEMENT_FLATPAK"; then + echo "$HOME/.var/app/$ELEMENT_FLATPAK/config/Element/config.json" + else + echo "$HOME/.config/Element/config.json" + fi +} + +# Done when Element isn't installed, as there's nothing to set up +element_done() { + element_installed || return 0 + jq -e --arg url "$MATRIX" \ + '.default_server_config["m.homeserver"].base_url | rtrimstr("/") == $url' \ + "$ELEMENT_CONFIG" &> /dev/null +} + +# Tally for Plausible, a Flatpak, shows one Plausible Analytics. It follows the +# main Core, if that runs Plausible. +TALLY=com.cassidyjames.plausible + +tally_installed() { + flatpak info "$TALLY" &> /dev/null +} + +tally_setting() { + flatpak run --command=gsettings "$TALLY" "$@" 2> /dev/null +} + +tally_done() { + [ "$(tally_setting get "$TALLY" domain)" = "'$PLAUSIBLE'" ] +} + +plausible_on_core() { + curl -sf -o /dev/null --max-time 15 "https://$PLAUSIBLE/api/health" +} + +# Element only follows the main Core +core_done() { + superpanel_done && nextcloud_done && email_done && files_done \ + && { [ "$CORE_DOMAIN" != "$MAIN_DOMAIN" ] || element_done; } +} + +# Done when every Core is +is_configured() { + local domain domains + domains="$(core_domains)" + [ -n "$domains" ] || return 1 + for domain in $domains; do + (load_core "$domain" && core_done) || return 1 + done +} + +# The first Core you set up is the main one +save_conf() { + mkdir -p "$CORES_DIR" + { + printf 'CORE_DOMAIN=%q\n' "$CORE_DOMAIN" + printf 'CORE_EMAIL=%q\n' "$CORE_EMAIL" + printf 'CORE_NAME=%q\n' "$CORE_NAME" + } > "$CORES_DIR/$CORE_DOMAIN.conf" + if [ -z "$MAIN_DOMAIN" ] || [ "$MAIN_DOMAIN" = "$CORE_DOMAIN" ]; then + make_main "$CORE_DOMAIN" + fi +} + +make_main() { + cp "$CORES_DIR/$1.conf" "$CORE_CONF" && MAIN_DOMAIN="$1" +} + +desktop_entry() { + local file="$1" name="$2" comment="$3" url="$4" icon="$5" + mkdir -p "$(dirname "$file")" + cat > "$file" << EOF +[Desktop Entry] +Type=Application +Name=$name +Comment=$comment +Exec=xdg-open $url +Icon=$icon +Categories=Network; +EOF +} + +setup_superpanel() { + local url="https://superpanel.$CORE_DOMAIN" + local icon="$HOME/.local/share/icons/core-$CORE_DOMAIN-superpanel.png" + + # The login page carries Superpanel's icon inline + mkdir -p "$(dirname "$icon")" + if ! curl -s "$url/" | grep -o 'rel="icon"[^>]*base64,[^"]*' | head -n 1 \ + | sed 's/.*base64,//' | base64 -d > "$icon" 2> /dev/null || [ ! -s "$icon" ]; then + rm -f "$icon" + icon="applications-internet" + fi + desktop_entry "$SUPERPANEL_DESKTOP" "Superpanel" "Manage your Federated Core ($CORE_DOMAIN)" "$url" "$icon" + echo "Added Superpanel to your applications." +} + +# COSMIC has no Online Accounts of its own, so GNOME's is used: it keeps the +# accounts and their passwords (in your keyring, as COSMIC does), and +# Evolution shows your email, calendars and contacts from it. goa-account adds +# accounts through it the way GNOME Settings does. +goa_ready() { + pkg_ensure "Email, calendars and contacts" gnome-online-accounts evolution \ + python3-gi gir1.2-secret-1 +} + +setup_nextcloud() { + [ -n "$APP_PASSWORD" ] || { echo "This needs your Core password, and Nextcloud didn't accept it."; return 1; } + goa_ready || return 1 + "$GOA_ACCOUNT" add << EOF || return 1 +$(jq -n --arg user "$CORE_USER" --arg host "nextcloud.$CORE_DOMAIN" --arg url "$NEXTCLOUD" \ + --arg password "$APP_PASSWORD" '{ + provider: "owncloud", + identity: $user, + presentation_identity: "\($user)@\($host)", + credentials: {password: $password}, + details: { + Uri: "\($url)/remote.php/webdav", + FilesEnabled: "true", + CalendarEnabled: "true", + CalDavUri: "\($url)/remote.php/dav", + ContactsEnabled: "true", + CardDavUri: "\($url)/remote.php/dav", + AcceptSslErrors: "false" + }}') +EOF + echo "Added Nextcloud's calendars and contacts; Evolution shows them." +} + +# The mail server publishes its settings (Thunderbird's autoconfig format). +# Prints: imap_host imap_port imap_socket smtp_host smtp_port smtp_socket username +mail_settings() { + curl -sf --max-time 15 \ + "https://autoconfig.$CORE_DOMAIN/mail/config-v1.1.xml?emailaddress=$CORE_EMAIL" \ + | python3 -I -c ' +import sys, xml.etree.ElementTree as ET +provider = ET.parse(sys.stdin).getroot().find("emailProvider") +imap = provider.find("incomingServer[@type=\"imap\"]") +smtp = provider.find("outgoingServer[@type=\"smtp\"]") +print(*(s.findtext(f) for s in (imap, smtp) for f in ("hostname", "port", "socketType")), + imap.findtext("username"))' +} + +# Online Accounts takes host:port, and only the host for the usual port +host_port() { + if [ "$2" = "$3" ]; then echo "$1"; else echo "$1:$2"; fi +} + +setup_email() { + [ -n "$PASSWORD" ] || { echo "This needs your Core password."; return 1; } + goa_ready || return 1 + local imap_host imap_port imap_socket smtp_host smtp_port smtp_socket username + if ! read -r imap_host imap_port imap_socket smtp_host smtp_port smtp_socket username < <(mail_settings) \ + || [ -z "$smtp_socket" ]; then + echo "The mail server didn't give its settings; using mail.$CORE_DOMAIN with the usual ports." + imap_host="mail.$CORE_DOMAIN" imap_port=993 imap_socket=SSL + smtp_host="mail.$CORE_DOMAIN" smtp_port=587 smtp_socket=STARTTLS + username="%EMAILADDRESS%" + fi + case "$username" in + %EMAILLOCALPART%) username="$CORE_USER" ;; + *) username="$CORE_EMAIL" ;; + esac + [ "$imap_socket" = SSL ] && imap_std=993 || imap_std=143 + [ "$smtp_socket" = SSL ] && smtp_std=465 || smtp_std=587 + + "$GOA_ACCOUNT" add << EOF || return 1 +$(jq -n --arg email "$CORE_EMAIL" --arg name "$CORE_NAME" --arg user "$username" \ + --arg password "$PASSWORD" \ + --arg imap "$(host_port "$imap_host" "$imap_port" "$imap_std")" --arg imap_socket "$imap_socket" \ + --arg smtp "$(host_port "$smtp_host" "$smtp_port" "$smtp_std")" --arg smtp_socket "$smtp_socket" '{ + provider: "imap_smtp", + identity: $email, + presentation_identity: $email, + credentials: {"imap-password": $password, "smtp-password": $password}, + details: { + Enabled: "true", + EmailAddress: $email, + Name: $name, + ImapHost: $imap, + ImapUserName: $user, + ImapUseSsl: (if $imap_socket == "SSL" then "true" else "false" end), + ImapUseTls: (if $imap_socket == "STARTTLS" then "true" else "false" end), + ImapAcceptSslErrors: "false", + SmtpHost: $smtp, + SmtpUseAuth: "true", + SmtpUserName: $user, + SmtpAuthLogin: "false", + SmtpAuthPlain: "true", + SmtpUseSsl: (if $smtp_socket == "SSL" then "true" else "false" end), + SmtpUseTls: (if $smtp_socket == "STARTTLS" then "true" else "false" end), + SmtpAcceptSslErrors: "false" + }}') +EOF + echo "Added $CORE_EMAIL; Evolution shows it." +} + +# Save APP_PASSWORD for davfs2 to mount your files with. davfs2 only reads +# this file if no one else can. +save_files_secret() { + local secret + mkdir -p -m 700 "$HOME/.davfs2" + touch "$HOME/.davfs2/secrets" + chmod 600 "$HOME/.davfs2/secrets" + secret="${APP_PASSWORD//\\/\\\\}" + secret="${secret//\"/\\\"}" + sed -i "\\#^$MOUNT #d" "$HOME/.davfs2/secrets" + printf '%s %s "%s"\n' "$MOUNT" "$CORE_USER" "$secret" >> "$HOME/.davfs2/secrets" +} + +# davfs2 lets you mount without sudo only if mount.davfs is setuid root, which +# Ubuntu's package asks about when it's installed (no, by default) +davfs2_ready() { + if ! pkg_installed davfs2; then + echo "Mounting your files needs davfs2." + confirm_yes "Install it now (with apt; asks for your password)?" || return 1 + echo "davfs2 davfs2/suid_file boolean true" | sudo debconf-set-selections || return 1 + pkg_install davfs2 || return 1 + fi + if [ ! -u /usr/sbin/mount.davfs ]; then + echo "davfs2 davfs2/suid_file boolean true" | sudo debconf-set-selections \ + && sudo dpkg-reconfigure -f noninteractive davfs2 || return 1 + fi +} + +# Mount your Nextcloud files at /mnt/<domain> with davfs2. You can mount it +# without sudo once it's in /etc/fstab with "user" and you're in Ubuntu's +# davfs2 group. It's mounted now and each time you log in. +setup_files() { + [ -n "$APP_PASSWORD" ] || { echo "This needs your Core password, and Nextcloud didn't accept it."; return 1; } + davfs2_ready || return 1 + sudo install -d -o "$USER" -g "$(id -gn)" "$MOUNT" || return 1 + if ! grep -qs " $MOUNT davfs " /etc/fstab; then + echo "$WEBDAV $MOUNT davfs rw,user,noauto,uid=$USER,_netdev 0 0" | sudo tee -a /etc/fstab > /dev/null || return 1 + # Otherwise mount warns that systemd is still using the old fstab + sudo systemctl daemon-reload + fi + if ! id -nG "$USER" | grep -qw davfs2; then + sudo usermod -aG davfs2 "$USER" || return 1 + fi + save_files_secret || return 1 + + mkdir -p "$HOME/.config/autostart" + cat > "$HOME/.config/autostart/core-$CORE_DOMAIN-files.desktop" << EOF +[Desktop Entry] +Type=Application +Name=Nextcloud files ($CORE_DOMAIN) +Comment=Mount your Nextcloud files at $MOUNT +Exec=sh -c 'mountpoint -q $MOUNT || mount $MOUNT' +X-GNOME-Autostart-enabled=true +NoDisplay=true +EOF + + # Shown in the Files sidebar as the domain + sidebar_add "$MOUNT" "$CORE_DOMAIN" + + # A new session through sudo picks up the davfs2 group now, without + # logging out and in again + if ! mountpoint -q "$MOUNT"; then + sudo -u "$USER" mount "$MOUNT" || return 1 + fi + echo "Your Nextcloud files are at $MOUNT (\"$CORE_DOMAIN\" in the Files sidebar)." +} + +# Element Desktop reads config.json in its settings folder (element_config) +# over its built-in settings. Pointing it at the Core's Matrix server means you only choose +# "Sign in" (the Core offers single sign-on through Authelia). The Core's Matrix +# server is named after its address, matrix.<domain>, and says where its API is. +setup_element() { + local base_url config + base_url="$(curl -sf --max-time 15 "$MATRIX/.well-known/matrix/client" \ + | jq -r '.["m.homeserver"].base_url // empty' 2> /dev/null)" + base_url="${base_url:-$MATRIX}" + + mkdir -p "$(dirname "$ELEMENT_CONFIG")" + config="$(cat "$ELEMENT_CONFIG" 2> /dev/null)" + [ -n "$config" ] || config='{}' + jq --arg url "${base_url%/}" --arg name "matrix.$CORE_DOMAIN" \ + '.default_server_config = {"m.homeserver": {base_url: $url, server_name: $name}}' \ + <<< "$config" > "$ELEMENT_CONFIG.tmp" && mv -f "$ELEMENT_CONFIG.tmp" "$ELEMENT_CONFIG" || return 1 + echo "Element will use $MATRIX the next time it starts." +} + +# Tally opens the page it showed last, so forget that one too +setup_tally() { + tally_setting set "$TALLY" domain "$PLAUSIBLE" || return 1 + tally_setting set "$TALLY" current-url "" || return 1 + echo "Tally for Plausible will show https://$PLAUSIBLE the next time it starts. Sign in there." +} + +# Pauses email if the mail server stops taking its password (system/email-watch) +email_watch_on() { + mkdir -p "$UNITS" \ + && cp "$CONNECTOR/system/systemd/federated-connector-email-watch.service" "$UNITS/" \ + && systemctl --user daemon-reload \ + && systemctl --user enable -q federated-connector-email-watch.service 2> /dev/null \ + && systemctl --user restart federated-connector-email-watch.service 2> /dev/null +} + +# Offer to install Element for the main Core, as the app for its chat +element_offer() { + element_installed && return 0 + flatpak_ensure "$ELEMENT_FLATPAK" Element "It's the app for your Core's chat (Matrix)." || return 0 + ELEMENT_CONFIG="$(element_config)" +} + +# Run a step unless it's done; a failed step doesn't stop the ones after it +core_step() { + local name="$1" title="$2" + if "${name}_done"; then + echo " $title: already set up" + return 0 + fi + if ! confirm_yes "Set up $title?"; then + return 0 + fi + "setup_$name" || { echo -e "\e[31m$title was not set up.\e[0m"; STATUS=1; } +} + +# Ask for your Core password until Nextcloud takes it, and with a name ($1), +# create an app password by that name (APP_PASSWORD). PASSWORD is left empty +# if Nextcloud says it's wrong three times, and kept, unchecked, if Nextcloud +# can't be reached. +ask_password() { + local tries + for _ in 1 2 3; do + read -rsp "Your Core password: " PASSWORD + echo + if [ -n "$1" ]; then nextcloud_app_password "$1"; else nextcloud_sign_in; fi + case $? in + 0) return 0 ;; + 2) echo "Nextcloud says that password is wrong."; PASSWORD="" ;; + *) echo "Couldn't reach Nextcloud at $NEXTCLOUD; trying the password for email anyway."; return 1 ;; + esac + done + return 1 +} + +# Set up the Core loaded with load_core, or a new one +setup_core() { + local url + STATUS=0 + + read -erp "Your Superpanel's address (e.g. https://superpanel.example.com): " \ + -i "${CORE_DOMAIN:+https://superpanel.$CORE_DOMAIN}" url + url="${url#*://}" + url="${url%%/*}" + CORE_DOMAIN="${url#superpanel.}" + if [ -z "$CORE_DOMAIN" ] || ! curl -s -o /dev/null --max-time 15 "https://superpanel.$CORE_DOMAIN/"; then + echo "Couldn't reach https://superpanel.$CORE_DOMAIN." + return 1 + fi + + read -erp "Your Core email: " -i "${CORE_EMAIL:-$USER@$CORE_DOMAIN}" CORE_EMAIL + read -erp "Your name, as shown on email you send: " \ + -i "${CORE_NAME:-$(getent passwd "$USER" | cut -d: -f5 | cut -d, -f1)}" CORE_NAME + [[ "$CORE_EMAIL" == *@* ]] || { echo "That isn't an email address."; return 1; } + core_names + save_conf + + # Nextcloud, email and files need your Core password; Nextcloud checks it + if ! nextcloud_done || ! email_done || ! files_done; then + ask_password "Pop!_OS on $HOSTNAME" + fi + + echo + core_step superpanel "Superpanel in your applications" + core_step nextcloud "Nextcloud calendars and contacts" + core_step email "Email" + core_step files "Nextcloud files at $MOUNT" + [ "$CORE_DOMAIN" = "$MAIN_DOMAIN" ] && element_offer && element_installed \ + && core_step element "Element with your Core's Matrix server" + [ "$CORE_DOMAIN" = "$MAIN_DOMAIN" ] && tally_installed && plausible_on_core \ + && core_step tally "Tally for Plausible with your Core's Plausible" + unset PASSWORD APP_PASSWORD + + email_done && email_watch_on + return $STATUS +} + +# Check an app password this computer keeps for the Core +app_password_works() { + local title="$1" app_password="$2" + [ -n "$app_password" ] || return 0 + case "$(nextcloud_sign_in "$app_password"; echo $?)" in + 0) echo " $title: working" ;; + 2) echo -e " \e[31m$title: Nextcloud doesn't accept its app password.\e[0m" + echo " It may have been revoked in Nextcloud under Settings > Security." + return 1 ;; + *) echo " $title: couldn't reach Nextcloud to check" ;; + esac +} + +# After your Core password changes, e.g. in Superpanel. Email keeps your Core +# password, so it gets the new one. Nextcloud, files and backups use app +# passwords, which stay the same; Nextcloud turns them off until you sign in +# with the new password, and checking the password here does that. +change_password() { + local tries reached=1 + load_core "$1" + STATUS=0 + for _ in 1 2 3; do + read -rsp "Your new Core password: " PASSWORD + echo + nextcloud_sign_in + case $? in + 0) break ;; + 2) echo "Nextcloud says that password is wrong."; PASSWORD="" ;; + *) echo "Couldn't reach Nextcloud at $NEXTCLOUD; trying the password for email anyway." + reached=0; break ;; + esac + done + [ -n "$PASSWORD" ] || return 1 + + echo + if email_done; then + local was_paused="" + "$GOA_ACCOUNT" paused imap_smtp "$CORE_EMAIL" 2> /dev/null && was_paused=", and isn't paused any more" + jq -n --arg password "$PASSWORD" '{"imap-password": $password, "smtp-password": $password}' \ + | "$GOA_ACCOUNT" update imap_smtp "$CORE_EMAIL" 2> /dev/null + case $? in + 0) echo " Email: has your new password$was_paused" ;; + 3) echo -e " \e[31mEmail: saved your new password, but the mail server didn't accept it.\e[0m" + STATUS=1 ;; + *) echo -e " \e[31mEmail: couldn't save your new password.\e[0m"; STATUS=1 ;; + esac + fi + unset PASSWORD + [ $reached = 1 ] || return 1 + + if nextcloud_done; then + if "$GOA_ACCOUNT" check owncloud "$CORE_USER@nextcloud.$CORE_DOMAIN" 2> /dev/null; then + echo " Nextcloud calendars and contacts: working" + else + echo -e " \e[31mNextcloud calendars and contacts: can't sign in.\e[0m" + echo " To fix it: configure core, then choose t) Test a Core" + STATUS=1 + fi + fi + files_done && { app_password_works "Files at $MOUNT" "$(files_app_password)" || STATUS=1; } + app_password_works "Backups" \ + "$(secret-tool lookup federated-connector backup item nextcloud url "$WEBDAV" 2> /dev/null)" || STATUS=1 + return $STATUS +} + +# Tailscale and Backup point at one Core, which can't be removed while they do +tailscale_on() { + [ "$(source "$TAILSCALE_CONF" 2> /dev/null && echo "$TAILSCALE_DOMAIN")" = "$1" ] \ + && tailscale status --json 2> /dev/null | jq -e '.BackendState == "Running"' > /dev/null +} + +backup_on() { + [[ "$(source "$BACKUP_CONF" 2> /dev/null && echo "$BACKUP_WEBDAV")" == "https://nextcloud.$1/"* ]] \ + && systemctl --user is-enabled -q federated-connector-backup.timer 2> /dev/null +} + +# Choose one of DOMAINS, other than $2 if given; sets PICKED +pick_core() { + local choices=() domain choice i + for domain in "${DOMAINS[@]}"; do + [ "$domain" != "$2" ] && choices+=("$domain") + done + if [ ${#choices[@]} -eq 1 ]; then + PICKED="${choices[0]}" + return 0 + fi + for i in "${!choices[@]}"; do + printf ' %d) %s\n' $((i + 1)) "${choices[$i]}" + done + read -rp "$1 " choice + [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= ${#choices[@]} )) || return 1 + PICKED="${choices[$((choice - 1))]}" +} + +# Point Element at the main Core, and say what else follows it +main_changed() { + load_core "$MAIN_DOMAIN" + echo "$MAIN_DOMAIN is now your main Core." + if element_installed && ! element_done && confirm_yes "Point Element at $MATRIX?"; then + setup_element + fi + if tally_installed && ! tally_done && plausible_on_core \ + && confirm_yes "Point Tally for Plausible at https://$PLAUSIBLE?"; then + setup_tally + fi + [ -f "$TAILSCALE_CONF" ] && echo "To move this computer to its Tailscale network: configure tailscale" + [ -f "$BACKUP_CONF" ] && echo "To back up to it instead: configure backup" + return 0 +} + +# The app password this computer uses for the Core, from davfs2's secrets +files_app_password() { + grep -s "^$MOUNT " "$HOME/.davfs2/secrets" \ + | python3 -I -c 'import shlex, sys; print(shlex.split(sys.stdin.read())[2])' 2> /dev/null +} + +# Undo what setup_core did. Nothing on the Core itself changes. +remove_core() { + local domain="$1" new_main="" app_password mount_re + if tailscale_on "$domain"; then + echo "This computer is on $domain's Tailscale network. Leave it first: configure tailscale" + return 1 + fi + if backup_on "$domain"; then + echo "Your backups go to $domain. Turn them off first: configure backup" + return 1 + fi + if [ "$domain" = "$MAIN_DOMAIN" ] && [ ${#DOMAINS[@]} -gt 1 ]; then + echo "$domain is your main Core. Which Core should be the main one instead?" + pick_core "Choose:" "$domain" || { echo "Choose a number from the list."; return 1; } + new_main="$PICKED" + fi + echo "This removes $domain's Superpanel, Nextcloud, email and files from this computer." + echo "Your files, email and everything else stay on the Core." + confirm "Remove $domain?" || return 0 + + load_core "$domain" + app_password="$(files_app_password)" + [ -n "$app_password" ] && nextcloud_revoke_app_password "$app_password" + + mountpoint -q "$MOUNT" && { umount "$MOUNT" 2> /dev/null || sudo umount "$MOUNT"; } + mount_re="${MOUNT//./\\.}" + if grep -qs " $MOUNT davfs " /etc/fstab; then + sudo sed -i "\\# $mount_re davfs #d" /etc/fstab && sudo systemctl daemon-reload + fi + [ -d "$MOUNT" ] && sudo rmdir "$MOUNT" 2> /dev/null + sed -i "\\#^$mount_re #d" "$HOME/.davfs2/secrets" 2> /dev/null + sidebar_remove "$MOUNT" + rm -f "$HOME/.config/autostart/core-$CORE_DOMAIN-files.desktop" + + "$GOA_ACCOUNT" remove owncloud "$CORE_USER@nextcloud.$CORE_DOMAIN" + "$GOA_ACCOUNT" remove imap_smtp "$CORE_EMAIL" + rm -f "$SUPERPANEL_DESKTOP" "$HOME/.local/share/icons/core-$CORE_DOMAIN-superpanel.png" + + # Element keeps its default server, unless that was this Core + if [ "$domain" = "$MAIN_DOMAIN" ] && [ -z "$new_main" ] && [ -f "$ELEMENT_CONFIG" ] \ + && jq -e --arg name "matrix.$domain" '.default_server_config["m.homeserver"].server_name == $name' \ + "$ELEMENT_CONFIG" &> /dev/null; then + jq 'del(.default_server_config)' "$ELEMENT_CONFIG" > "$ELEMENT_CONFIG.tmp" \ + && mv -f "$ELEMENT_CONFIG.tmp" "$ELEMENT_CONFIG" + fi + + rm -f "$CORES_DIR/$domain.conf" + echo "Removed $domain from this computer." + if [ -n "$new_main" ]; then + make_main "$new_main" && main_changed + elif [ "$domain" = "$MAIN_DOMAIN" ]; then + rm -f "$CORE_CONF" + fi +} + +# Testing a Core checks each part this computer set up for it against the +# Core itself, then offers to fix what doesn't work. A test that fails adds a +# fix, if there is one, to FIXES (with its title in FIX_TITLES). + +passed() { + echo -e " $1: \e[32mworking\e[0m" +} + +# failed <title> <problem> [fix] [more] +failed() { + echo -e " \e[31m$1: $2\e[0m" + [ -n "$4" ] && echo " $4" + PROBLEMS=$((PROBLEMS + 1)) + [ -n "$3" ] && FIXES+=("$3") FIX_TITLES+=("$1") +} + +# Test an Online Accounts account, and that none of what this set it up +# for is turned off (e.g. with GNOME Settings, if it was ever installed): +# <title> <provider> <identity> <setup> <fix> <enable> +# Email's password is checked with Nextcloud before it's tried on the mail +# server: each wrong password counts towards the mail server blocking this +# computer. Online Accounts 3.50, which Pop!_OS 24.04 has, marks an account +# as needing attention when the server can't be reached too, so that isn't +# taken to mean a wrong password. +test_account() { + local error off works=1 + if ! "$GOA_ACCOUNT" exists "$2" "$3" 2> /dev/null; then + failed "$1" "not set up" "$4" + return + fi + if "$GOA_ACCOUNT" paused "$2" "$3" 2> /dev/null; then + failed "$1" "paused, as the server stopped taking its password" "$5" \ + "So this computer doesn't keep trying it. Did your Core password change?" + works=0 + elif [ "$2" = imap_smtp ] && { "$EMAIL_WATCH" --check-password "$3"; [ $? -eq 2 ]; }; then + failed "$1" "has an old password: Nextcloud doesn't take it" "$5" "Did your Core password change?" + works=0 + elif ! error="$("$GOA_ACCOUNT" check "$2" "$3" 2>&1)"; then + failed "$1" "can't sign in" "$5" "$error" + works=0 + fi + off="$("$GOA_ACCOUNT" disabled "$2" "$3" 2> /dev/null)" + if [ -n "$off" ]; then + failed "$1" "turned off: $off" "$6" + elif [ $works -eq 1 ]; then + passed "$1" + fi +} + +test_files() { + local title="Nextcloud files at $MOUNT" + files_done || { failed "$title" "not set up" setup_files; return; } + nextcloud_sign_in "$(files_app_password)" + case $? in + 0) if mountpoint -q "$MOUNT" && timeout 15 ls "$MOUNT" &> /dev/null; then + passed "$title" + else + failed "$title" "not mounted" remount_files + fi ;; + 2) failed "$title" "Nextcloud doesn't accept its app password" fix_files \ + "It may have been revoked in Nextcloud under Settings > Security." ;; + *) failed "$title" "couldn't check its app password" ;; + esac +} + +test_element() { + local title="Element with your Core's Matrix server" + if ! element_done; then + failed "$title" "Element uses another server" setup_element + elif curl -sf -o /dev/null --max-time 15 "$MATRIX/_matrix/client/versions"; then + passed "$title" + else + failed "$title" "can't reach $MATRIX" + fi +} + +test_tally() { + local title="Tally for Plausible with your Core's Plausible" + plausible_on_core || return 0 + if tally_done; then + passed "$title" + else + failed "$title" "Tally shows another Plausible" setup_tally + fi +} + +test_backups() { + local webdav + webdav="$(source "$BACKUP_CONF" && echo "$BACKUP_WEBDAV")" + nextcloud_sign_in "$(secret-tool lookup federated-connector backup item nextcloud url "$webdav" 2> /dev/null)" + case $? in + 0) passed "Backups" ;; + 2) failed "Backups" "Nextcloud doesn't accept their app password" fix_backups ;; + *) failed "Backups" "couldn't check their app password" ;; + esac +} + +# Test the Core loaded with load_core. Fails if Nextcloud can't be reached, +# as then nothing else can be tested. +test_core() { + local status + FIXES=() FIX_TITLES=() PROBLEMS=0 + status="$(curl -sf --max-time 15 "$NEXTCLOUD/status.php")" + if [ -z "$status" ]; then + echo -e " \e[31mCouldn't reach Nextcloud at $NEXTCLOUD.\e[0m" + echo " Check this computer's internet connection, or whether your Core is down." + return 1 + fi + if jq -e '.maintenance' <<< "$status" > /dev/null 2>&1; then + echo " Nextcloud is being updated (maintenance mode). Test again when it's done." + return 1 + fi + + if ! superpanel_done; then + failed "Superpanel in your applications" "not set up" setup_superpanel + elif curl -s -o /dev/null --max-time 15 "https://superpanel.$CORE_DOMAIN/"; then + passed "Superpanel" + else + failed "Superpanel" "can't reach https://superpanel.$CORE_DOMAIN" + fi + test_account "Nextcloud calendars and contacts" owncloud "$CORE_USER@nextcloud.$CORE_DOMAIN" \ + setup_nextcloud fix_nextcloud enable_nextcloud + test_account "Email" imap_smtp "$CORE_EMAIL" setup_email fix_email enable_email + test_files + [ "$CORE_DOMAIN" = "$MAIN_DOMAIN" ] && element_installed && test_element + [ "$CORE_DOMAIN" = "$MAIN_DOMAIN" ] && tally_installed && test_tally + backup_on "$CORE_DOMAIN" && test_backups + return 0 +} + +# Calendars and contacts get a new app password +fix_nextcloud() { + [ -n "$APP_PASSWORD" ] || { echo "This needs your Core password, and Nextcloud didn't accept it."; return 1; } + jq -n --arg password "$APP_PASSWORD" '{password: $password}' \ + | "$GOA_ACCOUNT" update owncloud "$CORE_USER@nextcloud.$CORE_DOMAIN" || return 1 + echo "Nextcloud calendars and contacts have a new app password." +} + +enable_nextcloud() { + "$GOA_ACCOUNT" enable owncloud "$CORE_USER@nextcloud.$CORE_DOMAIN" || return 1 + echo "Turned Nextcloud's calendar, contacts and files back on." +} + +enable_email() { + "$GOA_ACCOUNT" enable imap_smtp "$CORE_EMAIL" || return 1 + echo "Turned email back on." +} + +# Email gets your Core password. If the mail server still says no, its +# settings may have changed, so add it again with the server's settings now. +fix_email() { + [ -n "$PASSWORD" ] || { echo "This needs your Core password."; return 1; } + jq -n --arg password "$PASSWORD" '{"imap-password": $password, "smtp-password": $password}' \ + | "$GOA_ACCOUNT" update imap_smtp "$CORE_EMAIL" 2> /dev/null + case $? in + 0) echo "Email has your Core password." ;; + 3) echo "The mail server still says no; adding your email again with its current settings." + "$GOA_ACCOUNT" remove imap_smtp "$CORE_EMAIL" && setup_email ;; + *) return 1 ;; + esac +} + +# Unmount if it's stuck, then mount +remount_files() { + if mountpoint -q "$MOUNT"; then + umount "$MOUNT" 2> /dev/null || sudo umount "$MOUNT" || return 1 + fi + mount "$MOUNT" 2> /dev/null || sudo -u "$USER" mount "$MOUNT" || return 1 + echo "Your Nextcloud files are at $MOUNT." +} + +# davfs2 gets a new app password +fix_files() { + [ -n "$APP_PASSWORD" ] || { echo "This needs your Core password, and Nextcloud didn't accept it."; return 1; } + save_files_secret && remount_files +} + +# Backups get their own new app password, as configure backup gives them +fix_backups() { + local APP_PASSWORD webdav + [ -n "$PASSWORD" ] || { echo "This needs your Core password."; return 1; } + webdav="$(source "$BACKUP_CONF" && echo "$BACKUP_WEBDAV")" + nextcloud_app_password "Federated Backup on $HOSTNAME" || return 1 + printf '%s' "$APP_PASSWORD" | secret-tool store --label "Federated Connector backup nextcloud ($webdav)" \ + federated-connector backup item nextcloud url "$webdav" || return 1 + echo "Backups have a new app password." +} + +# Run the fixes test_core found, asking for your Core password once if they +# need it +fix_core() { + local fix i needs="" + for fix in "${FIXES[@]}"; do + case "$fix" in + setup_nextcloud|fix_nextcloud|setup_files|fix_files) needs=app ;; + setup_email|fix_email|fix_backups) needs="${needs:-password}" ;; + esac + done + case "$needs" in + app) ask_password "Pop!_OS on $HOSTNAME" ;; + password) ask_password ;; + esac + + STATUS=0 + for i in "${!FIXES[@]}"; do + echo + echo "${FIX_TITLES[$i]}:" + "${FIXES[$i]}" || { echo -e "\e[31m${FIX_TITLES[$i]} was not fixed.\e[0m"; STATUS=1; } + done + unset PASSWORD APP_PASSWORD + return $STATUS +} + +check_core() { + load_core "$1" + echo "Testing $CORE_DOMAIN..." + test_core || return 1 + if [ $PROBLEMS -eq 0 ]; then + echo "Everything works." + return 0 + fi + echo + if [ ${#FIXES[@]} -eq 0 ]; then + echo "This computer can't fix that; it's on the Core's side, or the network's." + return 1 + fi + confirm_yes "Fix what doesn't work?" || return 1 + fix_core + + echo + echo "Testing $CORE_DOMAIN again..." + test_core || return 1 + if [ $PROBLEMS -eq 0 ]; then + echo "Everything works now." + else + echo "Some of it still doesn't work." + return 1 + fi +} + +run_configure() { + local choice i state + mapfile -t DOMAINS < <(core_domains) + if [ ${#DOMAINS[@]} -eq 0 ]; then + load_core "" + setup_core + return + fi + + echo "Your Cores:" + for i in "${!DOMAINS[@]}"; do + if (load_core "${DOMAINS[$i]}" && core_done); then + state="\e[32mdone\e[0m " + else + state="\e[33mto do\e[0m" + fi + printf " %d) $state %s%s\n" $((i + 1)) "${DOMAINS[$i]}" \ + "$([ "${DOMAINS[$i]}" = "$MAIN_DOMAIN" ] && echo " (main)")" + done + echo + echo " Choose a number to finish or change its setup, or:" + echo " a) Add a Core" + [ ${#DOMAINS[@]} -gt 1 ] && echo " m) Make another Core the main one" + echo " t) Test a Core, and fix what doesn't work" + echo " p) Your Core password changed" + echo " r) Remove a Core" + echo " q) Leave it as it is" + echo + read -rp "Choose: " choice + case "$choice" in + a|A) + load_core "" + setup_core ;; + m|M) + [ ${#DOMAINS[@]} -gt 1 ] || return 0 + pick_core "Which should be the main one?" "$MAIN_DOMAIN" || { echo "Choose a number from the list."; return 1; } + make_main "$PICKED" && main_changed ;; + p|P) + pick_core "Which Core's password changed?" || { echo "Choose a number from the list."; return 1; } + change_password "$PICKED" ;; + t|T) + pick_core "Which Core should be tested?" || { echo "Choose a number from the list."; return 1; } + check_core "$PICKED" ;; + r|R) + pick_core "Which Core should be removed?" || { echo "Choose a number from the list."; return 1; } + remove_core "$PICKED" ;; + *) + if [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= ${#DOMAINS[@]} )); then + load_core "${DOMAINS[$((choice - 1))]}" + setup_core + fi ;; + esac +} diff --git a/configure.d/15-tailscale.sh b/configure.d/15-tailscale.sh new file mode 100644 index 0000000..09dc7a1 --- /dev/null +++ b/configure.d/15-tailscale.sh @@ -0,0 +1,93 @@ +#!/bin/bash + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="Tailscale" +# shellcheck disable=SC2034 +DESCRIPTION="Join your Core's Tailscale network" + +CORE_CONF="$CONF_DIR/core.conf" +TAILSCALE_CONF="$CONF_DIR/tailscale.conf" +[ -f "$CORE_CONF" ] && source "$CORE_CONF" +[ -f "$TAILSCALE_CONF" ] && source "$TAILSCALE_CONF" + +# Tailscale's own installer adds its apt repository (pkgs.tailscale.com), so +# Pop!_OS' updates keep it up to date. It's downloaded, then run, rather than +# piped into a shell. +install_tailscale() { + local tmp status + echo "Tailscale isn't installed. It comes from Tailscale's own apt repository." + confirm_yes "Install it?" || return 1 + tmp="$(mktemp -d)" || return 1 + if curl -fsSL --max-time 60 -o "$tmp/install.sh" https://tailscale.com/install.sh; then + sh "$tmp/install.sh" + status=$? + else + echo "Couldn't download Tailscale's installer." + status=1 + fi + rm -rf "$tmp" + return $status +} + +# Tailscale has no status field naming its login server, so tailscale.conf +# records which Core it was set up for +joined() { + [ -n "$TAILSCALE_DOMAIN" ] \ + && tailscale status --json 2> /dev/null | jq -e '.BackendState == "Running"' > /dev/null +} + +# Done when on the main Core's network +is_configured() { + [ -n "$CORE_DOMAIN" ] && [ "$TAILSCALE_DOMAIN" = "$CORE_DOMAIN" ] && joined +} + +# Log out rather than only go down, so this computer's key is expired on +# headscale and it's off the network until it joins again +leave_network() { + sudo tailscale logout || return 1 + rm -f "$TAILSCALE_CONF" + echo "This computer has left your Core's Tailscale network. To join again: configure tailscale" +} + +run_configure() { + local choice + if joined &> /dev/null; then + echo "This computer is on $TAILSCALE_DOMAIN's Tailscale network (headscale.$TAILSCALE_DOMAIN)." + echo + if [ "$TAILSCALE_DOMAIN" = "$CORE_DOMAIN" ]; then + echo " 1) Join it again" + else + echo " 1) Join your main Core's network instead (headscale.$CORE_DOMAIN)" + fi + echo " 2) Leave the network" + echo " q) Leave it as it is" + echo + read -rp "Choose: " choice + case "$choice" in + 1) ;; + 2) leave_network; return ;; + *) return 0 ;; + esac + fi + + if [ -z "$CORE_DOMAIN" ]; then + echo "This joins your Core's Tailscale network, so set up your Core first: configure core" + return 1 + fi + + command -v tailscale > /dev/null || install_tailscale || return 1 + + # --reset and --force-reauth move the machine from any other tailnet; + # --operator lets you use it without sudo + if ! systemctl is-active -q tailscaled; then + sudo systemctl enable --now tailscaled || return 1 + fi + echo "Open the link below to sign in to your Core's Tailscale network (headscale.$CORE_DOMAIN)." + sudo tailscale up --reset --force-reauth --login-server "https://headscale.$CORE_DOMAIN" \ + --accept-routes --operator="$USER" || return 1 + + mkdir -p "$(dirname "$TAILSCALE_CONF")" + printf 'TAILSCALE_DOMAIN=%q\n' "$CORE_DOMAIN" > "$TAILSCALE_CONF" + echo "This computer is on your Core's Tailscale network." +} diff --git a/configure.d/20-backup.sh b/configure.d/20-backup.sh new file mode 100644 index 0000000..54bd681 --- /dev/null +++ b/configure.d/20-backup.sh @@ -0,0 +1,188 @@ +#!/bin/bash + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="Backup" +# shellcheck disable=SC2034 +DESCRIPTION="Back up your home folder daily to your Nextcloud files" + +CORE_CONF="$CONF_DIR/core.conf" +BACKUP_CONF="$CONF_DIR/backup.conf" +UNITS="$HOME/.config/systemd/user" +source "$CONNECTOR/configure.d/lib/nextcloud.sh" +[ -f "$CORE_CONF" ] && source "$CORE_CONF" + +backups_on() { + source "$CONNECTOR/system/backup-env.sh" > /dev/null || return 1 + [ -n "$RESTIC_PASSWORD_COMMAND" ] && systemctl --user is-enabled -q federated-connector-backup.timer +} + +# Done when backing up to the main Core +is_configured() { + backups_on && [ "$BACKUP_WEBDAV" = "https://nextcloud.$CORE_DOMAIN/remote.php/dav/files/${CORE_EMAIL%@*}" ] +} + +save_secret() { + printf '%s' "$3" | secret-tool store --label "Federated Connector backup $1 ($2)" \ + federated-connector backup item "$1" url "$2" +} + +# The backup gets its own app password, so revoking it stops only backups +nextcloud_login() { + local tries + [ -n "$(backup_secret nextcloud "$WEBDAV")" ] \ + && rclone lsf --max-depth 1 ":webdav:" > /dev/null 2>&1 && return 0 + for _ in 1 2 3; do + read -rsp "Your Core password: " PASSWORD + echo + nextcloud_app_password "Federated Backup on $HOSTNAME" + case $? in + 0) break ;; + 2) echo "Nextcloud says that password is wrong." ;; + *) echo "Couldn't reach Nextcloud at $NEXTCLOUD."; return 1 ;; + esac + done + unset PASSWORD + [ -n "$APP_PASSWORD" ] || return 1 + save_secret nextcloud "$WEBDAV" "$APP_PASSWORD" || return 1 + unset APP_PASSWORD + RCLONE_WEBDAV_PASS="$(backup_secret nextcloud "$WEBDAV" | rclone obscure -)" +} + +new_passphrase() { + local pass + pass="$(head -c 24 /dev/urandom | base64)" + echo "Your backup is encrypted with this passphrase:" + echo + echo " $pass" + echo + echo "Save it somewhere other than this computer, such as Bitwarden. Without it, the" + echo "backup can't be read if this computer is lost. It's kept in your keyring so the" + echo "daily backup can run." + until confirm "Have you saved it?"; do :; done + save_secret passphrase "$WEBDAV/$BACKUP_DIR" "$pass" +} + +# Stop the daily backup and any running now, and remove its units +stop_backups() { + systemctl --user disable --now federated-connector-backup.timer 2> /dev/null + systemctl --user stop federated-connector-backup.service 2> /dev/null + rm -f "$UNITS"/federated-connector-backup.{service,timer} + systemctl --user daemon-reload +} + +# Delete the backup from Nextcloud, then what's on this computer for it: +# without the backup, the passphrase and app password are no use +delete_backups() { + local app_password + nextcloud_login || { echo "Couldn't sign in to Nextcloud."; return 1; } + echo "Deleting $BACKUP_DIR from your Nextcloud files..." + rclone purge ":webdav:$BACKUP_DIR" \ + || { echo "rclone couldn't delete $BACKUP_DIR."; return 1; } + echo "Deleted. Nextcloud keeps it in its trash bin, where it still uses space, until you empty it." + + app_password="$(backup_secret nextcloud "$WEBDAV")" + [ -n "$app_password" ] && nextcloud_revoke_app_password "$app_password" + secret-tool clear federated-connector backup item nextcloud url "$WEBDAV" + secret-tool clear federated-connector backup item passphrase url "$WEBDAV/$BACKUP_DIR" + rm -f "$BACKUP_CONF" +} + +turn_off() { + local answer + WEBDAV="$BACKUP_WEBDAV" + CORE_USER="$BACKUP_USER" + NEXTCLOUD="${BACKUP_WEBDAV%%/remote.php/*}" + + stop_backups + echo "Backups are off." + + echo + echo "The backups made so far are still in $BACKUP_DIR in your Nextcloud files." + if ! confirm "Delete them? They can't be restored from after that."; then + echo "Kept them. To turn backups back on: configure backup" + return 0 + fi + read -rp "To delete them, type the folder name ($BACKUP_DIR): " answer + if [ "$answer" != "$BACKUP_DIR" ]; then + echo "That's not the folder name, so the backups were kept." + return 0 + fi + delete_backups +} + +run_configure() { + local pass choice + if backups_on &> /dev/null; then + if is_configured &> /dev/null; then + echo "Your home folder is backed up daily to $BACKUP_DIR in your Nextcloud files." + echo + echo " 1) Set it up again" + else + echo "Your home folder is backed up daily to $BACKUP_DIR on ${BACKUP_WEBDAV%%/remote.php/*}," + echo "which isn't your main Core." + echo + echo " 1) Back up to your main Core ($CORE_DOMAIN) instead; the backups so far stay where they are" + fi + echo " 2) Turn backups off" + echo " q) Leave it as it is" + echo + read -rp "Choose: " choice + case "$choice" in + 1) ;; + 2) turn_off; return ;; + *) return 0 ;; + esac + fi + + if [ -z "$CORE_DOMAIN" ] || [ -z "$CORE_EMAIL" ]; then + echo "Backups go to your Nextcloud files, so set up your Core first: configure core" + return 1 + fi + # Ubuntu's restic and rclone are recent enough: restic reaches rclone's + # WebDAV backend since 0.8, and rclone obscure reads stdin since 1.52 + pkg_ensure "Backups" restic rclone libsecret-tools || return 1 + CORE_USER="${CORE_EMAIL%@*}" + NEXTCLOUD="https://nextcloud.$CORE_DOMAIN" + WEBDAV="$NEXTCLOUD/remote.php/dav/files/$CORE_USER" + BACKUP_DIR=".backup-$HOSTNAME" + + mkdir -p "$(dirname "$BACKUP_CONF")" + { + printf 'BACKUP_WEBDAV=%q\n' "$WEBDAV" + printf 'BACKUP_USER=%q\n' "$CORE_USER" + printf 'BACKUP_DIR=%q\n' "$BACKUP_DIR" + } > "$BACKUP_CONF" + source "$CONNECTOR/system/backup-env.sh" + + nextcloud_login || { echo "Couldn't sign in to Nextcloud."; return 1; } + + if rclone lsf --files-only ":webdav:$BACKUP_DIR" 2> /dev/null | grep -qx config; then + # Already there, e.g. after reinstalling: it needs the passphrase from then + if [ -z "$RESTIC_PASSWORD_COMMAND" ] || ! restic cat config &> /dev/null; then + echo "There's already a backup in $BACKUP_DIR in your Nextcloud files." + read -rsp "Its passphrase: " pass + echo + RESTIC_PASSWORD_COMMAND='' RESTIC_PASSWORD="$pass" restic cat config > /dev/null \ + || { echo "restic couldn't open it with that passphrase."; return 1; } + save_secret passphrase "$WEBDAV/$BACKUP_DIR" "$pass" || return 1 + fi + echo "Using the backup in $BACKUP_DIR." + else + new_passphrase || return 1 + source "$CONNECTOR/system/backup-env.sh" + echo "Creating the backup in $BACKUP_DIR in your Nextcloud files..." + restic init || return 1 + fi + + mkdir -p "$UNITS" + cp "$CONNECTOR"/system/systemd/federated-connector-backup.{service,timer} "$UNITS/" || return 1 + systemctl --user daemon-reload + systemctl --user enable --now federated-connector-backup.timer || return 1 + echo "Your home folder will be backed up daily to $BACKUP_DIR in your Nextcloud files." + + if confirm_yes "Start the first backup now? It runs in the background and can take hours."; then + systemctl --user start --no-block federated-connector-backup.service + echo "Started. To follow it: journalctl --user -fu federated-connector-backup" + fi +} diff --git a/configure.d/30-agents.sh b/configure.d/30-agents.sh new file mode 100644 index 0000000..a950b9f --- /dev/null +++ b/configure.d/30-agents.sh @@ -0,0 +1,260 @@ +#!/bin/bash + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="AI agents" +# shellcheck disable=SC2034 +DESCRIPTION="Install Claude Code, opencode and Hermes, sandboxed" + +# Exists once you've run this, even if you installed no agents +AGENTS_CONF="$CONF_DIR/agents" +CLAUDE_SETTINGS="$HOME/.claude/settings.json" +BASE_CONFIG="$CONNECTOR/sandbox/config/base.json" +BASHRC="$HOME/.bashrc" +BLOCK_START="# >>> Federated Connector: agents >>>" +BLOCK_END="# <<< Federated Connector: agents <<<" +APPARMOR_PROFILE="/etc/apparmor.d/federated-connector-bwrap" +source "$CONNECTOR/configure.d/lib/json.sh" +source "$CONNECTOR/configure.d/lib/tools.sh" + +# name|title|installer|installer's arguments. Each agent's own installer, from +# its makers. --non-interactive skips Hermes' setup questions and its gateway +# service; configure hermes chooses a model provider afterwards. +AGENTS=( + "claude|Claude Code (Anthropic)|https://claude.ai/install.sh|" + "opencode|opencode|https://opencode.ai/install|" + "hermes|Hermes Agent (Nous Research)|https://hermes-agent.nousresearch.com/install.sh|--non-interactive" +) + +# srt (and Claude Code's own sandbox) use bubblewrap for the files an agent +# can see, socat to link it to the network proxy, and ripgrep to find the +# files it must not change. Node.js' own builds need libatomic. +SANDBOX_PACKAGES=(bubblewrap socat ripgrep libatomic1) + +# --- Typing an agent's name runs it in the sandbox ------------------------------- + +# The block goes last in ~/.bashrc, so agents' installers adding their own +# folders to PATH don't come before it +path_block() { + cat << EOF +$BLOCK_START +# Typing an AI agent's name runs it in the sandbox: configure agents +export PATH="$SANDBOX_BIN:\$PATH" +$BLOCK_END +EOF +} + +on_path() { + [ -f "$BASHRC" ] && [ "$(grep -v '^[[:space:]]*$' "$BASHRC" | tail -n 4)" = "$(path_block)" ] +} + +put_on_path() { + local tmp + touch "$BASHRC" || return 1 + tmp="$(mktemp)" || return 1 + awk -v start="$BLOCK_START" -v end="$BLOCK_END" \ + '$0 == start { skip = 1 } !skip { print } $0 == end { skip = 0 }' "$BASHRC" > "$tmp" + { cat "$tmp"; echo; path_block; } > "$BASHRC" + rm -f "$tmp" + echo "Agents run in the sandbox in new terminals. To run one without it: unsandboxed <agent>" +} + +# --- bubblewrap and Ubuntu's AppArmor --------------------------------------------- + +# Ubuntu 24.04 lets only programs AppArmor allows make the user namespaces +# bubblewrap needs, and has no rule for bubblewrap itself +bwrap_works() { + bwrap --ro-bind / / --unshare-user --unshare-net true 2> /dev/null +} + +allow_bwrap() { + echo "Ubuntu's AppArmor doesn't let bubblewrap, which the sandbox is built on, make" + echo "user namespaces. A profile for /usr/bin/bwrap allows it, as Ubuntu suggests." + confirm_yes "Add it ($APPARMOR_PROFILE)?" || return 1 + sudo tee "$APPARMOR_PROFILE" > /dev/null << 'EOF' || return 1 +# Written by Federated Connector (configure agents): let bubblewrap, which the +# AI agent sandbox uses, make user namespaces +abi <abi/4.0>, +include <tunables/global> + +profile federated-connector-bwrap /usr/bin/bwrap flags=(unconfined) { + userns, + include if exists <local/federated-connector-bwrap> +} +EOF + sudo apparmor_parser -r "$APPARMOR_PROFILE" || return 1 + bwrap_works || { echo "bubblewrap still can't make user namespaces."; return 1; } +} + +# --- Claude Code ------------------------------------------------------------------- + +# Claude Code runs every command it starts in its own sandbox, also built on +# bubblewrap and socat; it can't run inside srt because bubblewrap can't be +# nested. Anything already in the sandbox section of your settings wins over +# these defaults. +claude_sandbox_on() { + jq -e '.sandbox.enabled == true' "$CLAUDE_SETTINGS" &> /dev/null +} + +turn_on_claude_sandbox() { + local domains + domains="$(jq '.network.allowedDomains' "$BASE_CONFIG")" || return 1 + edit_json "$CLAUDE_SETTINGS" '{}' --argjson domains "$domains" \ + '.sandbox = ({enabled: true, network: {allowedDomains: $domains}} * (.sandbox // {}))' || return 1 + echo "Claude Code runs the commands it starts in its own sandbox." +} + +# A desktop notification when Claude Code needs you or is done, if you have no +# settings of your own yet +claude_notifications() { + [ -f "$CLAUDE_SETTINGS" ] && return 0 + edit_json "$CLAUDE_SETTINGS" '{}' \ + --arg needs "notify-send 'Claude Code' 'Needs your input'" \ + --arg finished "notify-send 'Claude Code' 'Task completed'" \ + '.hooks = { + Notification: [{matcher: "", hooks: [{type: "command", command: $needs}]}], + Stop: [{matcher: "", hooks: [{type: "command", command: $finished}]}] + }' || return 1 + echo "Claude Code shows a notification when it needs you and when it's done." +} + +# --- Hermes' gateway and Cline Desktop ----------------------------------------------- + +# Hermes' gateway acts on messages from outside this machine, so it runs in +# the sandbox too: a systemd drop-in starts it through sandbox/bin/hermes. It +# also needs to reach the Matrix server in Hermes' settings, which differs on +# each machine; for other messaging services, add their domains to +# ~/.config/federated-connector/sandbox/hermes.json. +GATEWAY_UNIT="$HOME/.config/systemd/user/hermes-gateway.service" +GATEWAY_DROPIN="$GATEWAY_UNIT.d/federated-connector-sandbox.conf" + +gateway_dropin() { + local homeserver + homeserver="$(sed -nE "s#^MATRIX_HOMESERVER=[\"']?https?://([^/:\"']+).*#\1#p" "$HOME/.hermes/.env" 2> /dev/null | head -n 1)" + cat << EOF +# Written by Federated Connector (configure agents): run Hermes' gateway in the sandbox +[Service] +Environment="FEDERATED_SANDBOX_DOMAINS=$homeserver" +ExecStart= +ExecStart=$SANDBOX_BIN/hermes gateway run +EOF +} + +gateway_ok() { + [ ! -f "$GATEWAY_UNIT" ] || [ "$(cat "$GATEWAY_DROPIN" 2> /dev/null)" = "$(gateway_dropin)" ] +} + +sandbox_gateway() { + gateway_ok && return 0 + mkdir -p "$(dirname "$GATEWAY_DROPIN")" && gateway_dropin > "$GATEWAY_DROPIN" \ + && systemctl --user daemon-reload || return 1 + echo "Hermes' gateway runs in the sandbox (from its next start)." +} + +# Cline Desktop is opened from the app menu, so an entry of the same name in +# ~/.local/share/applications, which wins over the package's, runs it in the +# sandbox. It's removed when the package is. +CLINE_DESKTOP="/usr/share/applications/cline-desktop.desktop" +CLINE_ENTRY="$HOME/.local/share/applications/cline-desktop.desktop" + +cline_entry() { + sed "s#^Exec=.*#Exec=$SANDBOX_BIN/cline-desktop %U#" "$CLINE_DESKTOP" +} + +cline_ok() { + if [ -f "$CLINE_DESKTOP" ]; then + [ "$(cat "$CLINE_ENTRY" 2> /dev/null)" = "$(cline_entry)" ] + else + [ ! -f "$CLINE_ENTRY" ] + fi +} + +sandbox_cline() { + cline_ok && return 0 + if [ -f "$CLINE_DESKTOP" ]; then + mkdir -p "$(dirname "$CLINE_ENTRY")" && cline_entry > "$CLINE_ENTRY" || return 1 + echo "Cline Desktop runs in the sandbox." + else + rm -f "$CLINE_ENTRY" + fi +} + +# --- The item ------------------------------------------------------------------------- + +sandbox_ready() { + srt_path > /dev/null && on_path && pkg_installed "${SANDBOX_PACKAGES[@]}" && bwrap_works \ + && { ! agent_installed claude || claude_sandbox_on; } && gateway_ok && cline_ok +} + +is_configured() { + [ -f "$AGENTS_CONF" ] && sandbox_ready +} + +# Download the installer, then run it, rather than piping it into bash +install_agent() { + local title="$1" url="$2" args="$3" tmp status + tmp="$(mktemp -d)" || return 1 + echo "Downloading $title's installer from $url" + if curl -fsSL --max-time 120 -o "$tmp/install.sh" "$url"; then + # shellcheck disable=SC2086 + (cd "$tmp" && bash ./install.sh $args) + status=$? + else + echo "Couldn't download it." + status=1 + fi + rm -rf "$tmp" + return $status +} + +run_configure() { + local entry name title url args status=0 + mkdir -p "$CONF_DIR" && touch "$AGENTS_CONF" || return 1 + echo "AI coding agents, run in a sandbox: an agent can change files only in the folder" + echo "you start it in, can't read your keys, passwords, browsers, mail or messages, and" + echo "reaches only AI providers and developer sites." + echo + + for entry in "${AGENTS[@]}"; do + IFS='|' read -r name title url args <<< "$entry" + if agent_installed "$name"; then + echo " $title: installed" + elif confirm_yes "Install $title?"; then + if ! install_agent "$title" "$url" "$args" || ! agent_installed "$name"; then + echo -e "\e[31m$title was not installed.\e[0m" + status=1 + fi + fi + done + + echo + pkg_ensure "The sandbox" "${SANDBOX_PACKAGES[@]}" || return 1 + if ! bwrap_works; then + if [ "$(sysctl -n kernel.apparmor_restrict_unprivileged_userns 2> /dev/null)" = 1 ]; then + allow_bwrap || { echo -e "\e[31mWithout it, the agents can't run in the sandbox.\e[0m"; return 1; } + else + echo -e "\e[31mbubblewrap can't make user namespaces on this computer, so the sandbox can't run.\e[0m" + return 1 + fi + fi + srt_ensure || { echo -e "\e[31mWithout srt, opencode and Hermes can't run in the sandbox.\e[0m"; return 1; } + if ! on_path; then + echo "Typing opencode or hermes should run it in the sandbox. That takes a line at the" + echo "end of ~/.bashrc." + if confirm_yes "Add it?"; then + put_on_path || status=1 + else + echo "Then run them sandboxed as $SANDBOX_BIN/<agent>." + fi + fi + if agent_installed claude; then + claude_notifications || status=1 + claude_sandbox_on || turn_on_claude_sandbox || status=1 + fi + sandbox_gateway || status=1 + sandbox_cline || status=1 + + echo + echo "To sign in to them: configure claude, configure opencode, configure hermes" + return $status +} diff --git a/configure.d/31-claude.sh b/configure.d/31-claude.sh new file mode 100644 index 0000000..0586b6c --- /dev/null +++ b/configure.d/31-claude.sh @@ -0,0 +1,29 @@ +#!/bin/bash + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="Claude Code" +# shellcheck disable=SC2034 +DESCRIPTION="Sign in to Anthropic" + +source "$CONNECTOR/configure.d/lib/agents.sh" + +is_installed() { + agent_installed claude +} + +is_configured() { + unsandboxed claude auth status +} + +run_configure() { + echo " 1) Claude subscription (Pro, Max, Team or Enterprise)" + echo " 2) Anthropic Console (pay for API usage)" + local choice + read -rp "How do you pay for Claude? [1] " choice + case "$choice" in + ""|1) unsandboxed claude auth login ;; + 2) unsandboxed claude auth login --console ;; + *) echo "Choose 1 or 2."; return 1 ;; + esac +} diff --git a/configure.d/32-opencode.sh b/configure.d/32-opencode.sh new file mode 100644 index 0000000..34cf329 --- /dev/null +++ b/configure.d/32-opencode.sh @@ -0,0 +1,26 @@ +#!/bin/bash + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="opencode" +# shellcheck disable=SC2034 +DESCRIPTION="Sign in to AI providers" + +source "$CONNECTOR/configure.d/lib/agents.sh" + +is_installed() { + agent_installed opencode +} + +# Signed in to at least one provider +is_configured() { + jq -e 'length > 0' "$HOME/.local/share/opencode/auth.json" +} + +run_configure() { + echo "Choose a provider and sign in or paste its API key. You can pick the model inside opencode with /models." + unsandboxed opencode auth login || return 1 + while confirm "Sign in to another provider?"; do + unsandboxed opencode auth login || return 1 + done +} diff --git a/configure.d/33-hermes.sh b/configure.d/33-hermes.sh new file mode 100644 index 0000000..c33f92b --- /dev/null +++ b/configure.d/33-hermes.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="Hermes Agent" +# shellcheck disable=SC2034 +DESCRIPTION="Choose a model provider and tools" + +source "$CONNECTOR/configure.d/lib/agents.sh" + +is_installed() { + agent_installed hermes +} + +# Signed in with OAuth (e.g. Nous Portal), or an API key is set +is_configured() { + [ -s "$HOME/.hermes/auth.json" ] || grep -qE '^[A-Z_]*API_KEY=.+' "$HOME/.hermes/.env" +} + +run_configure() { + echo " 1) Nous Portal (one sign-in covers the model, web search, images and more)" + echo " 2) Another provider (OpenRouter, OpenAI, Anthropic or your own endpoint)" + local choice + read -rp "Which provider? [1] " choice + case "$choice" in + ""|1) unsandboxed hermes setup --portal ;; + 2) unsandboxed hermes setup ;; + *) echo "Choose 1 or 2."; return 1 ;; + esac +} diff --git a/configure.d/40-languages.sh b/configure.d/40-languages.sh new file mode 100644 index 0000000..4cf3d05 --- /dev/null +++ b/configure.d/40-languages.sh @@ -0,0 +1,98 @@ +#!/bin/bash + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="Languages" +# shellcheck disable=SC2034 +DESCRIPTION="Install programming languages with mise, e.g. Ruby on Rails" + +# Records that you've chosen, even if you chose nothing, so this isn't "to do" +LANGUAGES_CONF="$CONF_DIR/languages" + +# mise installs these gems into each Ruby it installs, so Rails is still there +# after mise upgrade moves to a new Ruby +DEFAULT_GEMS="$HOME/.default-gems" + +# mise's activation line goes in ~/.bashrc, so the languages it installs are +# on PATH in new terminals +BASHRC="$HOME/.bashrc" +BLOCK_START="# >>> Federated Connector: mise >>>" +BLOCK_END="# <<< Federated Connector: mise <<<" + +# Ruby is built from source, which needs these (from ruby-build's wiki) +RUBY_BUILD_DEPS=(build-essential autoconf patch rustc libssl-dev libyaml-dev libreadline-dev + zlib1g-dev libgmp-dev libncurses-dev libffi-dev libgdbm-dev libdb-dev uuid-dev) + +is_configured() { + [ -f "$LANGUAGES_CONF" ] +} + +# Add a gem to ~/.default-gems unless it's there +add_default_gem() { + grep -qsx "$1" "$DEFAULT_GEMS" || echo "$1" >> "$DEFAULT_GEMS" +} + +# From mise's own apt repository, so Pop!_OS' updates keep mise up to date +install_mise() { + echo "mise isn't installed. It comes from mise's own apt repository (mise.jdx.dev)." + confirm_yes "Install it?" || return 1 + sudo install -dm 755 /etc/apt/keyrings || return 1 + curl -fsSL --max-time 60 https://mise.jdx.dev/gpg-key.pub \ + | sudo tee /etc/apt/keyrings/mise-archive-keyring.asc > /dev/null || return 1 + echo "deb [signed-by=/etc/apt/keyrings/mise-archive-keyring.asc] https://mise.jdx.dev/deb stable main" \ + | sudo tee /etc/apt/sources.list.d/mise.list > /dev/null || return 1 + sudo apt-get update && sudo apt-get install -y mise +} + +activated() { + grep -qsxF "$BLOCK_START" "$BASHRC" +} + +activate() { + { + echo + echo "$BLOCK_START" + echo "# The languages configure languages installs: see mise ls" + echo 'eval "$(mise activate bash)"' + echo "$BLOCK_END" + } >> "$BASHRC" || return 1 + echo "Added mise to ~/.bashrc; the languages it installs work in new terminals." +} + +install_rails() { + pkg_ensure "Building Ruby" "${RUBY_BUILD_DEPS[@]}" || return 1 + echo "Installing Ruby and Rails..." + add_default_gem bundler || return 1 + add_default_gem rails || return 1 + mise use -g ruby@latest || return 1 + # Ruby may already have been installed before ~/.default-gems listed these + mise exec -- gem install --conservative bundler rails || return 1 + grep -qsx rails "$LANGUAGES_CONF" || echo rails >> "$LANGUAGES_CONF" +} + +run_configure() { + local tools tool + export MISE_YES=1 + # From home, so a project's mise.toml in the current directory doesn't count + cd "$HOME" || return 1 + + echo "mise installs programming languages and tools for you, and the version a" + echo "project asks for in its mise.toml." + command -v mise > /dev/null || install_mise || return 1 + activated || activate || return 1 + mkdir -p "$(dirname "$LANGUAGES_CONF")" + touch "$LANGUAGES_CONF" || return 1 + + if confirm "Install Ruby on Rails?"; then + install_rails || return 1 + fi + + echo "Anything else? Name tools mise knows (mise registry lists them), with a version," + read -rp "e.g. node@lts python@3.13 go@latest, or press Enter for none: " tools + for tool in $tools; do + echo "Installing $tool..." + mise use -g "$tool" || return 1 + done + + echo "To update them: mise upgrade. To remove one later: mise unuse -g <tool>" +} diff --git a/configure.d/50-ai-servers.sh b/configure.d/50-ai-servers.sh new file mode 100644 index 0000000..b577fac --- /dev/null +++ b/configure.d/50-ai-servers.sh @@ -0,0 +1,274 @@ +#!/bin/bash + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="AI servers" +# shellcheck disable=SC2034 +DESCRIPTION="Use LLM servers on your network, e.g. Ollama" + +# The servers you've added, one host:port per line. It exists once you've run +# this, even if you added none, so this isn't "to do" on machines without one. +AI_SERVERS_CONF="$CONF_DIR/ai-servers" +# The sandbox config every sandboxed agent reads (see sandbox/agent) +SANDBOX_CONF="$CONF_DIR/sandbox/base.json" +CLAUDE_SETTINGS="$HOME/.claude/settings.json" +OPENCODE_CONF="$HOME/.config/opencode/opencode.json" +source "$CONNECTOR/configure.d/lib/mdns.sh" +source "$CONNECTOR/configure.d/lib/json.sh" + +# Ports LLM servers listen on by default, and who uses each. All of them answer +# OpenAI's API at /v1, which is how every agent here talks to them. +LLM_PORTS=(11434 1234 8080 8000) +declare -A LLM_PORT_NAMES=([11434]=Ollama [1234]="LM Studio" [8080]=llama.cpp [8000]=vLLM) + + +is_configured() { + [ -f "$AI_SERVERS_CONF" ] +} + +# The models a server at host:port offers, one per line; fails if it doesn't +# answer like an LLM server +server_models() { + curl -sf -m 3 "http://$1/v1/models" | jq -er '.data[].id' 2> /dev/null +} + +# What the server is, e.g. Ollama, for its name in the agents' settings +server_kind() { + local port="${1##*:}" + if curl -sf -m 3 "http://$1/api/version" > /dev/null; then + echo Ollama + else + echo "${LLM_PORT_NAMES[$port]:-LLM server}" + fi +} + +# The LLM servers on the network: "host:port|models" per line. mDNS finds the +# machines, but LLM servers don't announce themselves on it, so each machine +# is asked on the usual ports. +find_servers() { + local dir host port + dir="$(mktemp -d)" || return 1 + for host in $(mdns_hosts); do + for port in "${LLM_PORTS[@]}"; do + (server_models "$host:$port" | wc -l > "$dir/$host:$port") & + done + done + wait + for host in "$dir"/*; do + [ -f "$host" ] && [ "$(cat "$host")" -gt 0 ] && echo "$(basename "$host")|$(cat "$host")" + done + rm -rf "$dir" +} + +# Let every sandboxed agent (opencode, Hermes, Cline) reach host:port, and +# only that port +sandbox_allow() { + edit_json "$SANDBOX_CONF" '{}' --arg server "$1" \ + '.network.allowedDomains = ((.network.allowedDomains // []) - [$server] + [$server])' +} + +sandbox_disallow() { + [ -f "$SANDBOX_CONF" ] || return 0 + edit_json "$SANDBOX_CONF" '{}' --arg server "$1" \ + '.network.allowedDomains -= [$server]' +} + +# Claude Code's sandbox only covers the commands it runs, e.g. curl, not its +# own connection to Anthropic. Its list replaces the defaults sandbox/setup.sh +# gives it, so if it has none yet, it starts from those. +claude_allow() { + local defaults + [ -f "$CLAUDE_SETTINGS" ] || return 0 + defaults="$(jq '.network.allowedDomains' "$CONNECTOR/sandbox/config/base.json")" || return 1 + edit_json "$CLAUDE_SETTINGS" '{}' --arg server "$1" --argjson defaults "$defaults" \ + '.sandbox.network.allowedDomains = ((.sandbox.network.allowedDomains // $defaults) - [$server] + [$server])' +} + +claude_disallow() { + [ -f "$CLAUDE_SETTINGS" ] || return 0 + edit_json "$CLAUDE_SETTINGS" '{}' --arg server "$1" \ + 'if .sandbox.network.allowedDomains then .sandbox.network.allowedDomains -= [$server] else . end' +} + +# opencode's name for the server: llm.local:11434 -> llm-11434 +opencode_provider() { + local id="${1%%:*}" + id="${id%.local}-${1##*:}" + echo "${id//[^a-zA-Z0-9-]/-}" | tr '[:upper:]' '[:lower:]' +} + +# Add the server to opencode as a provider with its models, and make $3 the +# model opencode starts with if you say so +opencode_add() { + local server="$1" kind="$2" model="$3" id models + id="$(opencode_provider "$server")" + models="$(server_models "$server" | jq -R '{(.): {name: .}}' | jq -s 'add')" || return 1 + edit_json "$OPENCODE_CONF" '{"$schema": "https://opencode.ai/config.json"}' \ + --arg id "$id" --arg name "$kind on ${server%%:*}" --arg url "http://$server/v1" \ + --argjson models "$models" \ + '.provider[$id] = {npm: "@ai-sdk/openai-compatible", name: $name, options: {baseURL: $url}, models: $models}' \ + || return 1 + echo "opencode: added $kind on ${server%%:*} (choose its models with /models)." + if confirm_yes "Start opencode with $model?"; then + edit_json "$OPENCODE_CONF" '{}' --arg model "$id/$model" '.model = $model' || return 1 + fi +} + +opencode_remove() { + local id + [ -f "$OPENCODE_CONF" ] || return 0 + id="$(opencode_provider "$1")" + edit_json "$OPENCODE_CONF" '{}' --arg id "$id" \ + 'del(.provider[$id]) | if (.model // "") | startswith($id + "/") then del(.model) else . end' +} + +# Hermes uses one model at a time, so ask before replacing the one it has +hermes_use() { + local server="$1" model="$2" + confirm_yes "Use $model on ${server%%:*} for Hermes?" || return 0 + unsandboxed hermes config set model.provider custom > /dev/null \ + && unsandboxed hermes config set model.base_url "http://$server/v1" > /dev/null \ + && unsandboxed hermes config set model.default "$model" > /dev/null || return 1 + echo "Hermes: now uses $model." +} + +# Hermes' gateway reads the sandbox config when it starts, so it can't reach a +# new server until it restarts. (A sandboxed opencode starts its own server +# each time, so it reads the config again then.) +restart_gateway() { + if systemctl --user is-active -q hermes-gateway 2> /dev/null \ + && confirm_yes "Restart Hermes' gateway so it can reach the server?"; then + systemctl --user restart hermes-gateway || return 1 + fi +} + +saved_servers() { + grep -v '^$' "$AI_SERVERS_CONF" 2> /dev/null +} + +# Choose a model from the server and set the agents up to use it +add_server() { + local server="$1" kind models model choice i + mapfile -t models < <(server_models "$server") + if [ ${#models[@]} -eq 0 ]; then + echo "$server doesn't answer like an LLM server (http://$server/v1/models)." + return 1 + fi + kind="$(server_kind "$server")" + + echo + echo "$kind on $server has these models:" + for i in "${!models[@]}"; do + printf ' %2d) %s\n' $((i + 1)) "${models[$i]}" + done + read -rp "Which should the agents use? [1] " choice + choice="${choice:-1}" + if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#models[@]} )); then + echo "Choose a number from the list." + return 1 + fi + model="${models[$((choice - 1))]}" + + sandbox_allow "$server" || return 1 + claude_allow "$server" || return 1 + grep -qsxF "$server" "$AI_SERVERS_CONF" || echo "$server" >> "$AI_SERVERS_CONF" + echo "The sandbox lets the agents reach $server." + + if agent_installed opencode; then + opencode_add "$server" "$kind" "$model" || return 1 + fi + if agent_installed hermes; then + hermes_use "$server" "$model" || return 1 + fi + restart_gateway +} + +remove_server() { + local server="$1" tmp + sandbox_disallow "$server" || return 1 + claude_disallow "$server" || return 1 + opencode_remove "$server" || return 1 + tmp="$(mktemp)" || return 1 + grep -vxF "$server" "$AI_SERVERS_CONF" > "$tmp" + mv -f "$tmp" "$AI_SERVERS_CONF" + echo "The agents can no longer reach $server." + if grep -qsF "$server" "$HOME/.hermes/config.yaml"; then + echo "Hermes still uses it; choose another model provider with: configure hermes" + fi +} + +# Find servers on the network and add the one you choose +find_and_add() { + local servers server models choice i + echo "Looking for LLM servers on your network..." + mapfile -t servers < <(find_servers) + if [ ${#servers[@]} -eq 0 ]; then + echo "No LLM servers found. A server has to accept connections from other machines:" + echo "in Ollama's settings, turn on \"Expose Ollama to the network\" (or set OLLAMA_HOST=0.0.0.0);" + echo "in LM Studio, turn on \"Serve on Local Network\". Or enter its address instead." + return 0 + fi + for i in "${!servers[@]}"; do + IFS='|' read -r server models <<< "${servers[$i]}" + printf ' %2d) %-28s %s, %s models\n' $((i + 1)) "$server" "$(server_kind "$server")" "$models" + done + read -rp "Which server? " choice + if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#servers[@]} )); then + echo "Choose a number from the list." + return 1 + fi + add_server "${servers[$((choice - 1))]%%|*}" +} + +# host, host:port or a URL such as http://host:port/v1 -> host:port +enter_and_add() { + local address + read -rp "The server's address, e.g. llm.local or llm.local:11434: " address + address="${address#*://}" + address="${address%%/*}" + [ -n "$address" ] || return 0 + [[ "$address" == *:* ]] || address="$address:11434" + add_server "$address" +} + +choose_and_remove() { + local servers choice i + mapfile -t servers < <(saved_servers) + for i in "${!servers[@]}"; do + printf ' %2d) %s\n' $((i + 1)) "${servers[$i]}" + done + read -rp "Which server? " choice + if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#servers[@]} )); then + echo "Choose a number from the list." + return 1 + fi + remove_server "${servers[$((choice - 1))]}" +} + +run_configure() { + local choice + pkg_ensure "Finding servers on your network" avahi-utils || return 1 + mkdir -p "$(dirname "$AI_SERVERS_CONF")" && touch "$AI_SERVERS_CONF" || return 1 + echo "Agents run in a sandbox that only lets them reach the servers you allow. This finds" + echo "LLM servers on your network, such as Ollama on a Mac, allows them and sets up the agents." + + while true; do + echo + if [ -s "$AI_SERVERS_CONF" ]; then + echo "The agents can reach: $(saved_servers | paste -sd' ')" + echo + fi + echo " 1) Find servers on your network" + echo " 2) Enter a server's address" + [ -s "$AI_SERVERS_CONF" ] && echo " 3) Remove a server" + echo " q) Done" + echo + read -rp "Choose: " choice || return 0 + case "$choice" in + 1) find_and_add ;; + 2) enter_and_add ;; + 3) [ -s "$AI_SERVERS_CONF" ] && choose_and_remove ;; + *) return 0 ;; + esac + done +} diff --git a/configure.d/55-printers.sh b/configure.d/55-printers.sh new file mode 100644 index 0000000..a9fdfae --- /dev/null +++ b/configure.d/55-printers.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="Printers" +# shellcheck disable=SC2034 +DESCRIPTION="Add your network's printers to every print dialog" + +# Exists once you've run this, even if you added none, so this isn't "to do" +# on machines without a printer +PRINTERS_CONF="$CONF_DIR/printers" + +# Set up here, or a network printer was already added some other way +is_configured() { + [ -f "$PRINTERS_CONF" ] || LC_ALL=C lpstat -v 2> /dev/null | grep -qE ': (ipps?|dnssd)://' +} + +run_configure() { + bash "$CONNECTOR/system/setup-printers.sh" || return 1 + mkdir -p "$(dirname "$PRINTERS_CONF")" && touch "$PRINTERS_CONF" +} diff --git a/configure.d/60-storage.sh b/configure.d/60-storage.sh new file mode 100644 index 0000000..ceb1aa1 --- /dev/null +++ b/configure.d/60-storage.sh @@ -0,0 +1,319 @@ +#!/bin/bash + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="Network storage" +# shellcheck disable=SC2034 +DESCRIPTION="Mount shared folders from your network in /mnt" + +# What's mounted, one "kind|source|mount point" per line, e.g. +# smb|//pi-star.local/files|/mnt/pi-star-files. It exists once you've run +# this, even if you mounted nothing, so this isn't "to do" without a server. +STORAGE_CONF="$CONF_DIR/storage" +# Passwords for SMB shares, readable only by root, which mounts them +SMB_CREDENTIALS="/etc/federated-connector/smb" +source "$CONNECTOR/configure.d/lib/mdns.sh" +source "$CONNECTOR/configure.d/lib/sidebar.sh" + +is_configured() { + [ -f "$STORAGE_CONF" ] +} + +# A name usable in a path: "Pi-Star Files" -> pi-star-files +slug() { + local s + s="$(tr '[:upper:]' '[:lower:]' <<< "$1" | sed -E 's/[^a-z0-9._-]+/-/g; s/^-+//; s/-+$//')" + echo "${s:-share}" +} + +# /mnt/<host>[-<name>], with -2, -3... if that's taken +mount_point() { + local base n=2 point + base="/mnt/$(slug "${1%.local}")" + [ -n "$2" ] && base="$base-$(slug "$2")" + point="$base" + while [ -e "$point" ] || grep -qsF "|$point" "$STORAGE_CONF"; do + point="$base-$n" + n=$((n + 1)) + done + echo "$point" +} + +# --- SMB: Windows, Samba (e.g. a NAS) and Mac file sharing -------------------- + +# The disk shares on an SMB server, one per line, leaving out admin shares +# like C$. smbclient reads the password from PASSWD, not the command line. +smb_shares() { + local host="$1" user="$2" password="$3" auth=(-N) + [ -n "$user" ] && auth=(-U "$user") + PASSWD="$password" timeout 20 smbclient -L "//$host" "${auth[@]}" -g 2> /dev/null \ + | awk -F'|' '$1 == "Disk" && $2 !~ /\$$/ { print $2 }' +} + +# The /etc/fstab line: root mounts the share the first time something opens +# the folder (x-systemd.automount), as you, and unmounts it after 10 idle +# minutes. nofail and the timeout keep a missing server from holding up boot +# or hanging whatever opened the folder. Spaces are \040 in fstab. +smb_fstab_line() { + local source="${1// /\\040}" point="$2" credentials="$3" auth + if [ -n "$credentials" ]; then auth="credentials=$credentials"; else auth="guest"; fi + echo "$source $point cifs $auth,uid=$(id -u),gid=$(id -g),iocharset=utf8,nofail,_netdev,x-systemd.automount,x-systemd.idle-timeout=600,x-systemd.mount-timeout=20 0 0" +} + +add_smb() { + local host="$1" share="$2" user password shares point source credentials="" choice i + pkg_ensure "SMB shared folders" smbclient cifs-utils || return 1 + echo "Sign in to $host. Leave the user name empty for a share anyone can open." + read -rp "User name: " user + password="" + if [ -n "$user" ]; then + read -rsp "Password: " password + echo + fi + + if [ -z "$share" ]; then + mapfile -t shares < <(smb_shares "$host" "$user" "$password") + if [ ${#shares[@]} -eq 0 ]; then + echo "$host didn't list any shares for ${user:-guests} (wrong password, or it doesn't list them)." + read -rp "The share's name, if you know it (Enter to stop): " share + [ -n "$share" ] || return 1 + else + for i in "${!shares[@]}"; do + printf ' %2d) %s\n' $((i + 1)) "${shares[$i]}" + done + read -rp "Which share? " choice + if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#shares[@]} )); then + echo "Choose a number from the list." + return 1 + fi + share="${shares[$((choice - 1))]}" + fi + fi + + source="//$host/$share" + point="$(mount_point "$host" "$share")" + if [ -n "$user" ]; then + credentials="$SMB_CREDENTIALS/$(basename "$point")" + printf 'username=%s\npassword=%s\n' "$user" "$password" \ + | sudo install -D -m 600 -o root -g root /dev/stdin "$credentials" || return 1 + fi + sudo install -d "$point" || return 1 + smb_fstab_line "$source" "$point" "$credentials" | sudo tee -a /etc/fstab > /dev/null || return 1 + sudo systemctl daemon-reload || return 1 + sudo systemctl restart "$(systemd-escape -p --suffix=automount "$point")" || return 1 + finish_add smb "$source" "$point" "$share on ${host%.local}" +} + +remove_smb() { + local point="$1" tmp + sudo systemctl stop "$(systemd-escape -p --suffix=automount "$point")" \ + "$(systemd-escape -p --suffix=mount "$point")" 2> /dev/null + tmp="$(mktemp)" || return 1 + awk -v point="$point" '!($2 == point && $3 == "cifs")' /etc/fstab > "$tmp" + sudo cp /etc/fstab /etc/fstab.bak && sudo install -m 644 "$tmp" /etc/fstab || { rm -f "$tmp"; return 1; } + rm -f "$tmp" + sudo systemctl daemon-reload + sudo rm -f "$SMB_CREDENTIALS/$(basename "$point")" + sudo rmdir "$point" 2> /dev/null + return 0 +} + +# --- SFTP: any machine you can ssh to -------------------------------------------- + +sftp_unit_name() { + echo "federated-connector-sftp-$(basename "$1").service" +} + +# systemd would expand $ and % in the unit's ExecStart +sftp_unit() { + local source="$1" point="$2" + cat << EOF +# Written by Federated Connector (configure storage) +[Unit] +Description=Mount $source at $point +After=network-online.target + +[Service] +ExecStart=%h/.local/share/federated-connector/connector/system/sftp-mount "$source" "$point" +ExecStop=/usr/bin/fusermount3 -u "$point" +Restart=on-failure +RestartSec=30 + +[Install] +WantedBy=default.target +EOF +} + +add_sftp() { + local host="$1" user="${2:-$USER}" path="$3" source point name unit + pkg_ensure "SFTP folders" sshfs || return 1 + read -rp "User name on $host [$user]: " name + user="${name:-$user}" + if [ -z "$path" ]; then + read -rp "Folder on $host (Enter for your home folder): " path + fi + if [[ "$user$host$path" == *[\$%\"\\]* ]]; then + echo "The user name and folder can't contain \$, %, \" or \\." + return 1 + fi + source="$user@$host:$path" + + # Accepts the server's key the first time; the mount can't ask + echo "Checking that $host accepts one of your SSH keys..." + if [ -S "$HOME/.bitwarden-ssh-agent.sock" ]; then + export SSH_AUTH_SOCK="$HOME/.bitwarden-ssh-agent.sock" + fi + ssh -o ConnectTimeout=10 -o PasswordAuthentication=no -o KbdInteractiveAuthentication=no \ + "$user@$host" true || { + echo "$host didn't accept any of your SSH keys, and the mount can't ask for a password." + echo "Add your key to $host first (e.g. ssh-copy-id $user@$host), then try again." + return 1 + } + + point="$(mount_point "$host" "$(basename "${path:-}")")" + unit="$(sftp_unit_name "$point")" + sudo install -d -o "$USER" -g "$(id -gn)" "$point" || return 1 + mkdir -p "$HOME/.config/systemd/user" + sftp_unit "$source" "$point" > "$HOME/.config/systemd/user/$unit" || return 1 + systemctl --user daemon-reload + systemctl --user enable --now "$unit" || return 1 + finish_add sftp "$source" "$point" "${host%.local}${path:+ $(basename "$path")}" +} + +remove_sftp() { + local point="$1" unit + unit="$(sftp_unit_name "$point")" + systemctl --user disable --now "$unit" 2> /dev/null + rm -f "$HOME/.config/systemd/user/$unit" + systemctl --user daemon-reload + sudo rmdir "$point" 2> /dev/null + return 0 +} + +# --- Both ------------------------------------------------------------------------ + +# Record it, add it to the Files sidebar and check it opens +finish_add() { + local kind="$1" source="$2" point="$3" label="$4" + echo "$kind|$source|$point" >> "$STORAGE_CONF" + sidebar_add "$point" "$label" + if timeout 30 ls "$point" > /dev/null 2>&1 && mountpoint -q "$point"; then + echo "$source is at $point (\"$label\" in the Files sidebar)." + else + echo "$source was added at $point, but didn't open yet. If it doesn't, see:" + if [ "$kind" = smb ]; then + echo " journalctl -b -u '$(systemd-escape -p --suffix=mount "$point")'" + else + echo " journalctl --user -u $(sftp_unit_name "$point")" + fi + fi +} + +remove_storage() { + local kind="$1" point="$3" tmp + "remove_$kind" "$point" || return 1 + tmp="$(mktemp)" || return 1 + grep -vF "|$point" "$STORAGE_CONF" > "$tmp" + mv -f "$tmp" "$STORAGE_CONF" + sidebar_remove "$point" + echo "$point is no longer mounted." +} + +# The file servers on the network: "kind|host|name" per line +find_storage() { + local own name type host + own="$(mdns_own_host)" + mdns_services | while IFS='|' read -r name type host _; do + [[ "${host,,}" == "${own,,}" ]] && continue + case "$type" in + _smb._tcp) echo "smb|$host|$name" ;; + _sftp-ssh._tcp) echo "sftp|$host|$name" ;; + esac + done | sort -u +} + +find_and_add() { + local found kind host name choice i + echo "Looking for shared folders on your network..." + mapfile -t found < <(find_storage) + if [ ${#found[@]} -eq 0 ]; then + echo "Nothing found. A Mac shares folders over SMB once File Sharing is on (System Settings >" + echo "General > Sharing). Or enter the address instead." + return 0 + fi + for i in "${!found[@]}"; do + IFS='|' read -r kind host name <<< "${found[$i]}" + printf ' %2d) %-26s %s\n' $((i + 1)) "$host" "$( [ "$kind" = smb ] && echo "SMB shared folders" || echo "SFTP (over SSH)")" + done + read -rp "Which? " choice + if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#found[@]} )); then + echo "Choose a number from the list." + return 1 + fi + IFS='|' read -r kind host _ <<< "${found[$((choice - 1))]}" + "add_$kind" "$host" +} + +# smb://host/share or sftp://[user@]host[/path] +enter_and_add() { + local address rest host user="" path + read -rp "Address, e.g. smb://nas.local/files or sftp://me@server.local/srv/data: " address + rest="${address#*://}" + case "$address" in + smb://*/?*) add_smb "${rest%%/*}" "${rest#*/}" ;; + sftp://*) + [[ "$rest" == *@* ]] && { user="${rest%%@*}"; rest="${rest#*@}"; } + host="${rest%%/*}" + path="" + [[ "$rest" == */* ]] && path="/${rest#*/}" + add_sftp "$host" "$user" "$path" ;; + "") return 0 ;; + *) echo "Start it with smb:// (and include the share) or sftp://."; return 1 ;; + esac +} + +choose_and_remove() { + local entries choice i + mapfile -t entries < <(grep -v '^$' "$STORAGE_CONF") + for i in "${!entries[@]}"; do + IFS='|' read -r _ source point <<< "${entries[$i]}" + printf ' %2d) %-30s %s\n' $((i + 1)) "$point" "$source" + done + read -rp "Which? " choice + if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#entries[@]} )); then + echo "Choose a number from the list." + return 1 + fi + IFS='|' read -r -a entry <<< "${entries[$((choice - 1))]}" + remove_storage "${entry[@]}" +} + +run_configure() { + local choice source point + pkg_ensure "Finding shared folders" avahi-utils || return 1 + mkdir -p "$(dirname "$STORAGE_CONF")" && touch "$STORAGE_CONF" || return 1 + echo "This mounts shared folders from other machines on your network in /mnt: SMB shares" + echo "(Windows, a NAS, a Mac with File Sharing on) and, over SSH, any machine you can ssh to." + + while true; do + echo + if [ -s "$STORAGE_CONF" ]; then + while IFS='|' read -r _ source point; do + echo " $point <- $source" + done < "$STORAGE_CONF" + echo + fi + echo " 1) Find shared folders on your network" + echo " 2) Enter an address" + [ -s "$STORAGE_CONF" ] && echo " 3) Remove one" + echo " q) Done" + echo + read -rp "Choose: " choice || return 0 + case "$choice" in + 1) find_and_add ;; + 2) enter_and_add ;; + 3) [ -s "$STORAGE_CONF" ] && choose_and_remove ;; + *) return 0 ;; + esac + done +} diff --git a/configure.d/65-sandbox.sh b/configure.d/65-sandbox.sh new file mode 100644 index 0000000..2056558 --- /dev/null +++ b/configure.d/65-sandbox.sh @@ -0,0 +1,83 @@ +#!/bin/bash + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="Agent sandbox" +# shellcheck disable=SC2034 +DESCRIPTION="Choose what agents may read, e.g. WinBoat's settings" + +# The sandbox config every sandboxed agent reads (see sandbox/agent) +SANDBOX_CONF="$CONF_DIR/sandbox/base.json" +source "$CONNECTOR/configure.d/lib/json.sh" + +# Folders the sandbox hides from agents (sandbox/config/base.json) that you +# may let them read: "path|what it is". Your SSH keys, password stores, +# browsers and the like aren't here; they're always hidden. A path in +# allowRead can be read even inside one in denyRead, so letting agents read +# one is adding it to allowRead in your own config. +# The paths are written as in sandbox/config/base.json, with ~ for srt to expand +# shellcheck disable=SC2088 +OPTIONAL_HIDDEN=( + "~/.winboat|WinBoat's settings, which include your Windows password" +) + +# Offered only when one of the folders is on this machine +is_installed() { + local entry path + for entry in "${OPTIONAL_HIDDEN[@]}"; do + path="${entry%%|*}" + [ -e "${path/#\~/$HOME}" ] && return 0 + done + return 1 +} + +# Hiding them is the default, so there's nothing you need to do +is_configured() { + true +} + +# True if agents may read $1 (it's in your config's allowRead) +readable() { + jq -e --arg path "$1" '.filesystem.allowRead // [] | index($path)' "$SANDBOX_CONF" &> /dev/null +} + +let_read() { + edit_json "$SANDBOX_CONF" '{}' --arg path "$1" \ + '.filesystem.allowRead = ((.filesystem.allowRead // []) - [$path] + [$path])' +} + +hide() { + [ -f "$SANDBOX_CONF" ] || return 0 + edit_json "$SANDBOX_CONF" '{}' --arg path "$1" \ + 'if .filesystem.allowRead then .filesystem.allowRead -= [$path] else . end' +} + +run_configure() { + local choice i path what state + echo "Agents in the sandbox can't read these unless you let them. Changes apply the next" + echo "time you start an agent (restart Hermes' gateway with: systemctl --user restart hermes-gateway)." + echo "Claude Code's own sandbox doesn't use this list." + + while true; do + echo + for i in "${!OPTIONAL_HIDDEN[@]}"; do + IFS='|' read -r path what <<< "${OPTIONAL_HIDDEN[$i]}" + if readable "$path"; then state="\e[33magents can read it\e[0m"; else state="\e[32mhidden\e[0m"; fi + printf " %d) %-12s $state %s\n" $((i + 1)) "$path" "$what" + done + echo " q) Done" + echo + read -rp "Choose one to switch: " choice || return 0 + if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#OPTIONAL_HIDDEN[@]} )); then + return 0 + fi + IFS='|' read -r path what <<< "${OPTIONAL_HIDDEN[$((choice - 1))]}" + if readable "$path"; then + hide "$path" || return 1 + echo "$path is hidden from agents again." + elif confirm "Let agents read $path ($what)?"; then + let_read "$path" || return 1 + echo "Agents can read $path." + fi + done +} diff --git a/configure.d/lib/agents.sh b/configure.d/lib/agents.sh new file mode 100644 index 0000000..dd08475 --- /dev/null +++ b/configure.d/lib/agents.sh @@ -0,0 +1,47 @@ +#!/bin/bash +# +# Purpose : Find the AI agents' real commands, outside the sandbox's own +# (sandbox/bin), and the sandbox runtime. Sourced by configure and +# sandbox/agent. Needs CONNECTOR. + +SANDBOX_BIN="$CONNECTOR/sandbox/bin" +FC_TOOLS="$HOME/.local/share/federated-connector" + +# Where the agents' installers put them, in case your shell's PATH doesn't +# have them yet (e.g. right after installing) +AGENT_DIRS="$HOME/.local/bin:$HOME/.opencode/bin:$HOME/.hermes/bin:/usr/local/bin:/usr/bin" + +# The real command for an agent: the first on PATH, or in AGENT_DIRS, that +# isn't in sandbox/bin +agent_path() { + local dir bin_dir IFS=: + bin_dir="$(realpath "$SANDBOX_BIN" 2> /dev/null)" + for dir in $PATH:$AGENT_DIRS; do + [ -n "$dir" ] && [ -d "$dir" ] || continue + [ "$(realpath "$dir")" = "$bin_dir" ] && continue + if [ -x "$dir/$1" ] && [ ! -d "$dir/$1" ]; then + echo "$dir/$1" + return 0 + fi + done + return 1 +} + +agent_installed() { + agent_path "$1" > /dev/null +} + +# Run an agent's real command rather than its sandboxed one: setting an agent +# up writes outside its sandbox +unsandboxed() { + local agent="$1" real + shift + real="$(agent_path "$agent")" || { echo "$agent isn't installed."; return 127; } + "$real" "$@" +} + +# srt, and the Node.js it runs with: Federated Connector's own, or one +# already installed +srt_path() { + PATH="$FC_TOOLS/srt/bin:$FC_TOOLS/node/bin:$PATH" command -v srt +} diff --git a/configure.d/lib/cosmic-favorites b/configure.d/lib/cosmic-favorites new file mode 100755 index 0000000..c4f01a6 --- /dev/null +++ b/configure.d/lib/cosmic-favorites @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Add or remove a folder in the COSMIC Files sidebar. + +COSMIC Files keeps the sidebar's places in its cosmic-config setting +"favorites": ~/.config/cosmic/com.system76.CosmicFiles/v1/favorites, a RON +list such as [Home, Documents, Path("/mnt/x"), Named(path: "/mnt/y", name: "y")]. +COSMIC Files watches the file, so a change shows at once. This adds a folder +as Named (a path with the name to show), which COSMIC Files has had since +epoch 1.7, and leaves the rest of the list as it is. Without the file, COSMIC +Files uses its defaults, so those are written first. + +Usage: + cosmic-favorites has <path> + cosmic-favorites add <path> <name> + cosmic-favorites remove <path> +""" + +import os +import sys + +CONFIG = os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"), + "cosmic/com.system76.CosmicFiles/v1/favorites") +DEFAULTS = ["Home", "Documents", "Downloads", "Music", "Pictures", "Videos"] + + +def split_items(text): + """The top-level items of a RON list, as text.""" + text = text.strip() + if not (text.startswith("[") and text.endswith("]")): + raise ValueError("not a RON list") + items, depth, start, quoted, escaped = [], 0, 1, False, False + for i, ch in enumerate(text[1:-1], 1): + if quoted: + if escaped: + escaped = False + elif ch == "\\": + escaped = True + elif ch == '"': + quoted = False + elif ch == '"': + quoted = True + elif ch in "([{": + depth += 1 + elif ch in ")]}": + depth -= 1 + elif ch == "," and depth == 0: + items.append(text[start:i].strip()) + start = i + 1 + last = text[start:-1].strip() + if last: + items.append(last) + return [item for item in items if item] + + +def ron_string(value): + return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"' + + +def unquote(value): + out, escaped = [], False + for ch in value[1:-1]: + if escaped: + out.append(ch) + escaped = False + elif ch == "\\": + escaped = True + else: + out.append(ch) + return "".join(out) + + +def item_path(item): + """The path of a Path, Named or Network item, or None.""" + for prefix in ("Path(", "Named(", "Network("): + if not item.startswith(prefix): + continue + body = item[len(prefix):-1].strip().rstrip(",") + if prefix == "Path(": + return unquote(body.strip()) + for field in split_items("[" + body + "]"): + key, _, value = field.partition(":") + if key.strip() == "path": + return unquote(value.strip()) + return None + + +def load(): + try: + with open(CONFIG, encoding="utf-8") as f: + return split_items(f.read()) + except FileNotFoundError: + return list(DEFAULTS) + + +def save(items): + os.makedirs(os.path.dirname(CONFIG), exist_ok=True) + tmp = CONFIG + ".tmp" + with open(tmp, "w", encoding="utf-8") as f: + f.write("[\n" + "".join(f" {item},\n" for item in items) + "]") + os.replace(tmp, CONFIG) + + +def main(): + args = sys.argv[1:] + if len(args) == 2 and args[0] == "has": + return 0 if any(item_path(i) == args[1] for i in load()) else 1 + if len(args) == 3 and args[0] == "add": + items = [i for i in load() if item_path(i) != args[1]] + items.append(f"Named(path: {ron_string(args[1])}, name: {ron_string(args[2])})") + save(items) + return 0 + if len(args) == 2 and args[0] == "remove": + items = load() + kept = [i for i in items if item_path(i) != args[1]] + if kept != items: + save(kept) + return 0 + print(__doc__.strip().split("\n\n")[-1], file=sys.stderr) + return 2 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except (OSError, ValueError) as error: + print(f"COSMIC Files sidebar: {error}", file=sys.stderr) + sys.exit(1) diff --git a/configure.d/lib/goa-account b/configure.d/lib/goa-account new file mode 100755 index 0000000..d479e8d --- /dev/null +++ b/configure.d/lib/goa-account @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""Add, change or remove an account in GNOME Online Accounts, the way GNOME Settings does. + +COSMIC has no accounts of its own, so configure keeps your Core's email, +calendars and contacts in GNOME Online Accounts, which runs as a D-Bus +service without GNOME, and Evolution shows them. + +Settings adds accounts by calling AddAccount on the Online Accounts service, +which saves the account and keeps its password in the GNOME keyring. This +calls the same method. The service can't change a password, so when you sign +in again, Settings saves the new one in the keyring itself and asks the +service to check it (EnsureCredentials); update does the same. Passwords come +on stdin rather than as arguments, so they don't show up in the process list. + +Usage: + goa-account exists <provider> <presentation-identity> + goa-account add < account.json + goa-account update <provider> <presentation-identity> < credentials.json + goa-account check <provider> <presentation-identity> + goa-account disabled <provider> <presentation-identity> + goa-account enable <provider> <presentation-identity> + goa-account attention <provider> <presentation-identity> + goa-account pause <provider> <presentation-identity> + goa-account paused <provider> <presentation-identity> + goa-account remove <provider> <presentation-identity> + +account.json: + {"provider": "owncloud", "identity": "...", "presentation_identity": "...", + "credentials": {"password": "..."}, "details": {"Uri": "...", ...}} + +credentials.json is the account's "credentials", e.g. {"password": "..."}. +check signs in with what's saved, and fails if the server says no. update +exits with 3 if it saved the password but the server didn't accept it. +disabled prints the features configure uses that are turned off (e.g. in +GNOME Settings), such as "Calendar, Files", and enable turns them back on. + +attention exits 0 if Online Accounts marked the account as needing +attention. It doesn't sign in, so it doesn't add to the server's count of +failed logins. Online Accounts 3.50, which Pop!_OS 24.04 has, marks it for +any failure, including a server it couldn't reach, so it's only a hint that +the password may be wrong (see system/email-watch). + +pause empties the account's saved password, keeping its place in the keyring. +Online Accounts signs in again whenever the network changes, and Evolution +whenever it fetches mail; with no password neither tries, so a mail server +with fail2ban doesn't block this computer for repeated wrong passwords. +update puts a password back, which ends the pause. paused exits 0 if paused. +""" + +import json +import sys + +import gi + +gi.require_version("Gio", "2.0") +gi.require_version("Secret", "1") +from gi.repository import Gio, GLib, Secret # noqa: E402 + +BUS_NAME = "org.gnome.OnlineAccounts" + +# How Online Accounts keeps passwords in the keyring: the credentials printed +# as a GVariant, under "<provider>:gen<N>:<account id>" +SCHEMA = Secret.Schema.new("org.gnome.OnlineAccounts", Secret.SchemaFlags.DONT_MATCH_NAME, + {"goa-identity": Secret.SchemaAttributeType.STRING}) + +# The features configure sets each kind of account up for. Every account has +# a <feature>Disabled property for each feature, used or not. +FEATURES = {"owncloud": ["Calendar", "Contacts", "Files"], "imap_smtp": ["Mail"]} + + +def call(bus, path, interface, method, parameters, reply_type): + return bus.call_sync(BUS_NAME, path, interface, method, parameters, + GLib.VariantType(reply_type), Gio.DBusCallFlags.NONE, + -1, None).unpack() + + +def accounts(bus): + (objects,) = call(bus, "/org/gnome/OnlineAccounts", + "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", + None, "(a{oa{sa{sv}}})") + for path, interfaces in objects.items(): + account = interfaces.get("org.gnome.OnlineAccounts.Account") + if account: + yield path, account + + +def find_accounts(bus, provider, presentation_identity): + return [(path, account) for path, account in accounts(bus) + if account.get("ProviderType") == provider + and account.get("PresentationIdentity") == presentation_identity] + + +def find(bus, provider, presentation_identity): + return [path for path, _ in find_accounts(bus, provider, presentation_identity)] + + +def exists(bus, provider, presentation_identity): + return bool(find(bus, provider, presentation_identity)) + + +def add(bus, account): + credentials = {key: GLib.Variant("s", value) + for key, value in account["credentials"].items()} + parameters = GLib.Variant("(sssa{sv}a{ss})", ( + account["provider"], account["identity"], + account["presentation_identity"], credentials, account["details"])) + call(bus, "/org/gnome/OnlineAccounts/Manager", + "org.gnome.OnlineAccounts.Manager", "AddAccount", parameters, "(o)") + + +def ensure_credentials(bus, path): + call(bus, path, "org.gnome.OnlineAccounts.Account", "EnsureCredentials", None, "(i)") + + +# N in the keyring's name comes from the provider, so this saves over the +# account's own item rather than making one +def store_credentials(provider, account_id, credentials): + items = Secret.password_search_sync( + None, {"xdg:schema": "org.gnome.OnlineAccounts"}, + Secret.SearchFlags.ALL | Secret.SearchFlags.UNLOCK, None) + identities = [item.get_attributes().get("goa-identity", "") for item in items] + identities = [identity for identity in identities + if identity.startswith(f"{provider}:gen") and identity.endswith(f":{account_id}")] + if not identities: + raise LookupError(f"there's no saved password for {account_id} in the keyring") + secret = GLib.Variant("a{sv}", {key: GLib.Variant("s", value) + for key, value in credentials.items()}).print_(True) + for identity in identities: + Secret.password_store_sync(SCHEMA, {"goa-identity": identity}, Secret.COLLECTION_DEFAULT, + f"GOA {provider} credentials for identity {account_id}", + secret, None) + + +# The account's saved credentials, e.g. {"imap-password": "..."} +def lookup_credentials(provider, account_id): + items = Secret.password_search_sync( + None, {"xdg:schema": "org.gnome.OnlineAccounts"}, + Secret.SearchFlags.ALL | Secret.SearchFlags.UNLOCK | Secret.SearchFlags.LOAD_SECRETS, None) + for item in items: + identity = item.get_attributes().get("goa-identity", "") + if identity.startswith(f"{provider}:gen") and identity.endswith(f":{account_id}"): + return GLib.Variant.parse(None, item.get_secret().get_text(), None, None).unpack() + raise LookupError(f"there's no saved password for {account_id} in the keyring") + + +# The credential each kind of account signs in with +PASSWORD_KEYS = {"owncloud": "password", "imap_smtp": "imap-password"} + + +def attention(bus, provider, presentation_identity): + found = find_accounts(bus, provider, presentation_identity) + if not found: + raise LookupError(f"there's no {provider} account for {presentation_identity}") + return any(account.get("AttentionNeeded") for _, account in found) + + +def pause(bus, provider, presentation_identity): + found = find_accounts(bus, provider, presentation_identity) + if not found: + raise LookupError(f"there's no {provider} account for {presentation_identity}") + for _, account in found: + store_credentials(provider, account["Id"], {}) + + +def paused(bus, provider, presentation_identity): + found = find_accounts(bus, provider, presentation_identity) + if not found: + raise LookupError(f"there's no {provider} account for {presentation_identity}") + return any(PASSWORD_KEYS[provider] not in lookup_credentials(provider, account["Id"]) + for _, account in found) + + +def update(bus, provider, presentation_identity, credentials): + found = find_accounts(bus, provider, presentation_identity) + if not found: + raise LookupError(f"there's no {provider} account for {presentation_identity}") + for path, account in found: + store_credentials(provider, account["Id"], credentials) + try: + for path, _ in found: + ensure_credentials(bus, path) + except GLib.Error as error: + print(f"GNOME Online Accounts: {error.message}", file=sys.stderr) + return 3 + return 0 + + +def check(bus, provider, presentation_identity): + found = find(bus, provider, presentation_identity) + if not found: + raise LookupError(f"there's no {provider} account for {presentation_identity}") + for path in found: + ensure_credentials(bus, path) + + +def disabled(bus, provider, presentation_identity): + found = find_accounts(bus, provider, presentation_identity) + if not found: + raise LookupError(f"there's no {provider} account for {presentation_identity}") + return [feature for feature in FEATURES.get(provider, []) + if any(account.get(f"{feature}Disabled") for _, account in found)] + + +# Settings turns a feature off or on by setting its property +def enable(bus, provider, presentation_identity): + for path, account in find_accounts(bus, provider, presentation_identity): + for feature in FEATURES.get(provider, []): + if account.get(f"{feature}Disabled"): + call(bus, path, "org.freedesktop.DBus.Properties", "Set", + GLib.Variant("(ssv)", ("org.gnome.OnlineAccounts.Account", + f"{feature}Disabled", GLib.Variant("b", False))), + "()") + + +def remove(bus, provider, presentation_identity): + for path in find(bus, provider, presentation_identity): + call(bus, path, "org.gnome.OnlineAccounts.Account", "Remove", None, "()") + + +def main(): + bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) + if len(sys.argv) == 4 and sys.argv[1] == "exists": + return 0 if exists(bus, sys.argv[2], sys.argv[3]) else 1 + if len(sys.argv) == 2 and sys.argv[1] == "add": + account = json.load(sys.stdin) + if exists(bus, account["provider"], account["presentation_identity"]): + return 0 + add(bus, account) + return 0 + if len(sys.argv) == 4 and sys.argv[1] == "update": + return update(bus, sys.argv[2], sys.argv[3], json.load(sys.stdin)) + if len(sys.argv) == 4 and sys.argv[1] == "check": + check(bus, sys.argv[2], sys.argv[3]) + return 0 + if len(sys.argv) == 4 and sys.argv[1] == "disabled": + print(", ".join(disabled(bus, sys.argv[2], sys.argv[3]))) + return 0 + if len(sys.argv) == 4 and sys.argv[1] == "enable": + enable(bus, sys.argv[2], sys.argv[3]) + return 0 + if len(sys.argv) == 4 and sys.argv[1] == "attention": + return 0 if attention(bus, sys.argv[2], sys.argv[3]) else 1 + if len(sys.argv) == 4 and sys.argv[1] == "pause": + pause(bus, sys.argv[2], sys.argv[3]) + return 0 + if len(sys.argv) == 4 and sys.argv[1] == "paused": + return 0 if paused(bus, sys.argv[2], sys.argv[3]) else 1 + if len(sys.argv) == 4 and sys.argv[1] == "remove": + remove(bus, sys.argv[2], sys.argv[3]) + return 0 + print(__doc__.strip().split("\n\n")[2], file=sys.stderr) + return 2 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except GLib.Error as error: + print(f"GNOME Online Accounts: {error.message}", file=sys.stderr) + sys.exit(1) + except LookupError as error: + print(f"GNOME Online Accounts: {error}", file=sys.stderr) + sys.exit(1) diff --git a/configure.d/lib/json.sh b/configure.d/lib/json.sh new file mode 100644 index 0000000..6a15c10 --- /dev/null +++ b/configure.d/lib/json.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# +# Purpose : Edit JSON settings files for configure.d items. Source this file. + +# Edit a JSON file in place with jq, creating it from $2 if it's missing. +# Leaves the file alone if it isn't valid JSON or jq fails. +edit_json() { + local file="$1" empty="$2" tmp + shift 2 + mkdir -p "$(dirname "$file")" || return 1 + [ -f "$file" ] || echo "$empty" > "$file" + tmp="$(mktemp "$file.XXXXXX")" || return 1 + if jq "$@" "$file" > "$tmp"; then + mv -f "$tmp" "$file" + else + echo "Couldn't change $file; is it valid JSON?" + rm -f "$tmp" + return 1 + fi +} diff --git a/configure.d/lib/mdns.sh b/configure.d/lib/mdns.sh new file mode 100644 index 0000000..41a2952 --- /dev/null +++ b/configure.d/lib/mdns.sh @@ -0,0 +1,48 @@ +#!/bin/bash +# +# Purpose : Find what's on the local network over mDNS (Avahi), for the +# configure.d items that set up servers, printers and storage on it. +# Source this file. + +# Every service Avahi can see, or only those of type $1 (e.g. _ipp._tcp), one +# per line after waiting a few seconds for answers: +# "name|type|host|address|port|txt". IPv4 only, so a machine isn't listed once +# per address family. The name has Avahi's escapes decoded. +mdns_services() { + local name type host address port txt + timeout 15 avahi-browse "${1:---all}" --resolve --terminate --parsable --no-db-lookup 2> /dev/null \ + | awk -F';' '$1 == "=" && $3 == "IPv4"' \ + | while IFS=';' read -r _ _ _ name type _ host address port txt; do + printf '%s|%s|%s|%s|%s|%s\n' "$(mdns_unescape "$name")" "$type" "$host" "$address" "$port" "$txt" + done | sort -u +} + +# Avahi writes a space as \032 and a dot in a name as \. (decimal escapes) +mdns_unescape() { + local s="$1" out="" ch code escape='^([^\\]*)\\([0-9][0-9][0-9]|.)(.*)$' + while [[ "$s" =~ $escape ]]; do + out+="${BASH_REMATCH[1]}" + code="${BASH_REMATCH[2]}" + s="${BASH_REMATCH[3]}" + if [[ "$code" == [0-9][0-9][0-9] ]]; then + # shellcheck disable=SC2059 + printf -v ch "\\$(printf %03o "$((10#$code))")" + out+="$ch" + else + out+="$code" + fi + done + echo "$out$s" +} + +# This machine's own .local name, which mdns_hosts leaves out +mdns_own_host() { + echo "$(hostnamectl hostname 2> /dev/null || cat /etc/hostname).local" +} + +# The other machines on the network: one .local name per line +mdns_hosts() { + local own + own="$(mdns_own_host)" + mdns_services | cut -d'|' -f3 | grep -vixF "$own" | sort -u +} diff --git a/configure.d/lib/nextcloud.sh b/configure.d/lib/nextcloud.sh new file mode 100644 index 0000000..52d5f5d --- /dev/null +++ b/configure.d/lib/nextcloud.sh @@ -0,0 +1,48 @@ +#!/bin/bash +# +# Purpose : Nextcloud app passwords for configure.d items. Source this file. + +# Basic auth header for curl, read from stdin (-H @-) so the password isn't +# in the process list +auth_header() { + printf 'Authorization: Basic %s\n' "$(printf '%s:%s' "$1" "$2" | base64 -w0)" +} + +# Create a Nextcloud app password, so what configure sets up doesn't keep +# your Core password. It shows in Nextcloud under Settings > Security with the +# name given, where it can be revoked. Uses CORE_USER, PASSWORD and NEXTCLOUD; +# sets APP_PASSWORD. Returns 2 if Nextcloud says the password is wrong. +nextcloud_app_password() { + local name="$1" response code + response="$(auth_header "$CORE_USER" "$PASSWORD" | curl -s -w '\n%{http_code}' -H @- \ + -H 'OCS-APIRequest: true' -A "$name" \ + "$NEXTCLOUD/ocs/v2.php/core/getapppassword?format=json")" + code="${response##*$'\n'}" + case "$code" in + 200) APP_PASSWORD="$(jq -r '.ocs.data.apppassword // empty' <<< "${response%$'\n'*}")" + [ -n "$APP_PASSWORD" ] ;; + 401) return 2 ;; + *) return 1 ;; + esac +} + +# Revoke an app password, signing in with it. Uses CORE_USER and NEXTCLOUD. +nextcloud_revoke_app_password() { + auth_header "$CORE_USER" "$1" | curl -sf -o /dev/null -X DELETE -H @- \ + -H 'OCS-APIRequest: true' "$NEXTCLOUD/ocs/v2.php/core/apppassword" +} + +# Sign in to Nextcloud as CORE_USER with a password ($1), or PASSWORD if not +# given. Signing in with your Core password (not an app password) also turns +# back on the app passwords Nextcloud turned off when the Core password +# changed. Uses NEXTCLOUD. Returns 2 if Nextcloud says the password is wrong. +nextcloud_sign_in() { + local code + code="$(auth_header "$CORE_USER" "${1:-$PASSWORD}" | curl -s -o /dev/null -w '%{http_code}' -H @- \ + -H 'OCS-APIRequest: true' "$NEXTCLOUD/ocs/v2.php/cloud/user?format=json")" + case "$code" in + 200) return 0 ;; + 401) return 2 ;; + *) return 1 ;; + esac +} diff --git a/configure.d/lib/packages.sh b/configure.d/lib/packages.sh new file mode 100644 index 0000000..cfed643 --- /dev/null +++ b/configure.d/lib/packages.sh @@ -0,0 +1,60 @@ +#!/bin/bash +# +# Purpose : Install what an item needs from Pop!_OS' and Ubuntu's apt +# repositories, and from Flathub. Source this file; it uses +# confirm_yes from configure. +# +# Pop!_OS comes with less than CoreDesktop installs up front, so each item +# installs what it needs the first time you set it up, after asking. + +is_pop() { + [ "$(. /etc/os-release 2> /dev/null && echo "$ID")" = pop ] +} + +os_name() { + (. /etc/os-release 2> /dev/null && echo "${PRETTY_NAME:-$ID}") || uname -s +} + +# True if every package named is installed +pkg_installed() { + local pkg + for pkg in "$@"; do + [ "$(dpkg-query -W -f '${db:Status-Status}' "$pkg" 2> /dev/null)" = installed ] || return 1 + done +} + +# pkg_ensure <what they're for> <package>...: offer to install the packages +# that are missing. Fails if any is still missing. +pkg_ensure() { + local why="$1" pkg missing=() + shift + for pkg in "$@"; do + pkg_installed "$pkg" || missing+=("$pkg") + done + [ ${#missing[@]} -eq 0 ] && return 0 + echo "$why needs: ${missing[*]}" + confirm_yes "Install them now (with apt; asks for your password)?" || return 1 + pkg_install "${missing[@]}" +} + +# Install packages without asking. apt's lists may be old on a new install, +# so they're refreshed once per run if the install fails. +pkg_install() { + sudo apt-get install -y "$@" && return 0 + [ -n "$PKG_UPDATED" ] && return 1 + PKG_UPDATED=1 + sudo apt-get update && sudo apt-get install -y "$@" +} + +# Flatpak apps come from Flathub, as in the COSMIC Store +flatpak_installed() { + flatpak info "$1" &> /dev/null +} + +# flatpak_ensure <app id> <name> <what it's for> +flatpak_ensure() { + flatpak_installed "$1" && return 0 + echo "$2 isn't installed. $3" + confirm_yes "Install $2 from Flathub?" || return 1 + flatpak install -y --noninteractive flathub "$1" +} diff --git a/configure.d/lib/sidebar.sh b/configure.d/lib/sidebar.sh new file mode 100644 index 0000000..3bf7b7d --- /dev/null +++ b/configure.d/lib/sidebar.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# +# Purpose : Show a folder in the Files sidebar. Source this file; needs +# CONNECTOR. +# +# COSMIC Files has its own list (see lib/cosmic-favorites). GTK apps, such +# as Evolution's file chooser, read ~/.config/gtk-3.0/bookmarks, so the folder +# goes in both. + +GTK_BOOKMARKS="$HOME/.config/gtk-3.0/bookmarks" +COSMIC_FAVORITES="$CONNECTOR/configure.d/lib/cosmic-favorites" + +# sidebar_add <folder> <name> +sidebar_add() { + mkdir -p "$(dirname "$GTK_BOOKMARKS")" + grep -qs "^file://$1 " "$GTK_BOOKMARKS" || echo "file://$1 $2" >> "$GTK_BOOKMARKS" + "$COSMIC_FAVORITES" add "$1" "$2" +} + +sidebar_remove() { + local tmp + if [ -f "$GTK_BOOKMARKS" ]; then + tmp="$(mktemp)" || return 1 + grep -vF "file://$1 " "$GTK_BOOKMARKS" > "$tmp" + mv -f "$tmp" "$GTK_BOOKMARKS" + fi + "$COSMIC_FAVORITES" remove "$1" +} + +sidebar_has() { + "$COSMIC_FAVORITES" has "$1" 2> /dev/null +} diff --git a/configure.d/lib/tools.sh b/configure.d/lib/tools.sh new file mode 100644 index 0000000..a06b999 --- /dev/null +++ b/configure.d/lib/tools.sh @@ -0,0 +1,74 @@ +#!/bin/bash +# +# Purpose : Node.js and Anthropic's sandbox runtime (srt) for the agent +# sandbox. Source this file after lib/agents.sh; it uses +# confirm_yes from configure. +# +# srt needs Node.js 22.12 or later, and Pop!_OS 24.04's is 18. So unless a +# new enough one is installed already, the current long-term support release +# is downloaded from nodejs.org into FC_TOOLS/node, checked against the +# SHA-256 sums it publishes, and used only for srt: nothing in /usr or your +# shell changes. + +# srt needs Node.js 22.12 or later +node_ok() { + local node version + node="$(PATH="$FC_TOOLS/node/bin:$PATH" command -v node)" || return 1 + version="$("$node" -p 'process.versions.node' 2> /dev/null)" || return 1 + [ "$(printf '%s\n' 22.12.0 "$version" | sort -V | head -n 1)" = 22.12.0 ] +} + +# download_checked <url> <sums url> <file name in sums> <destination> +download_checked() { + local url="$1" sums_url="$2" name="$3" dest="$4" expected actual + echo "Downloading $url" + curl -fL --progress-bar --max-time 1800 -o "$dest" "$url" || return 1 + expected="$(curl -fsL --max-time 30 "$sums_url" | awk -v f="$name" '$2 == f || $2 == "*" f { print $1; exit }')" + actual="$(sha256sum "$dest" | cut -d' ' -f1)" + if [ -z "$expected" ] || [ "$expected" != "$actual" ]; then + echo -e "\e[31mThe download doesn't match the checksum its release publishes. Not installing it.\e[0m" + rm -f "$dest" + return 1 + fi +} + +install_node() { + local tmp version arch name status=1 + version="$(curl -fsL --max-time 30 https://nodejs.org/dist/index.json \ + | jq -r '[.[] | select(.lts)][0].version // empty')" + [ -n "$version" ] || { echo "Couldn't find Node.js' current release."; return 1; } + case "$(uname -m)" in + aarch64|arm64) arch=arm64 ;; + *) arch=x64 ;; + esac + name="node-$version-linux-$arch.tar.xz" + tmp="$(mktemp -d)" || return 1 + if download_checked "https://nodejs.org/dist/$version/$name" \ + "https://nodejs.org/dist/$version/SHASUMS256.txt" "$name" "$tmp/$name" \ + && tar -xJf "$tmp/$name" -C "$tmp" && mkdir -p "$FC_TOOLS"; then + rm -rf "$FC_TOOLS/node" && mv "$tmp/${name%.tar.xz}" "$FC_TOOLS/node" && status=0 + fi + rm -rf "$tmp" + return $status +} + +# srt from npm, into FC_TOOLS/srt. It has no install scripts of its own; the +# ones npm would warn it blocked belong to a Windows-only package it +# optionally depends on. +install_srt() { + local node_dir + node_ok || install_node || return 1 + node_dir="$(dirname "$(PATH="$FC_TOOLS/node/bin:$PATH" command -v node)")" + echo "Installing the sandbox runtime (srt) from npm..." + PATH="$node_dir:$PATH" "$node_dir/npm" install --global --prefix "$FC_TOOLS/srt" \ + --no-fund --no-audit --ignore-scripts @anthropic-ai/sandbox-runtime > /dev/null +} + +# Updating srt is installing it again +srt_ensure() { + srt_path > /dev/null && return 0 + echo "The sandbox is Anthropic's sandbox runtime (srt), which runs on Node.js." + node_ok || echo "This computer's Node.js is older than srt needs, so it gets its own, from nodejs.org." + confirm_yes "Install it (into $FC_TOOLS)?" || return 1 + install_srt +} diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..0a74688 --- /dev/null +++ b/install.sh @@ -0,0 +1,256 @@ +#!/bin/bash +# +# Purpose : Install Federated Connector for Pop!_OS, or update it (`update` +# runs this with --update). +# +# curl -fsSL https://gitea.federated.computer/Federated_Computer/connector-popos/raw/branch/main/install.sh | bash +# +# Pop!_OS doesn't come with git, so this downloads an archive of the latest +# commit from Gitea, puts it in ~/.local/share/federated-connector/connector, +# and records the commit. The place never changes, which matters: the +# backup, email and network storage services point into it. An update swaps +# the new files in at once. +# +# It also installs the few packages configure itself needs, puts `configure` +# and `update` in ~/.local/bin, and that on your PATH, then offers to run +# configure. +# +# Usage: install.sh [--update] +# +# FEDERATED_CONNECTOR_SOURCE=<folder> installs from that folder instead of +# Gitea (the smoketest uses it to install the working copy). + +# Piped into bash, the script is read as it runs; main at the end runs it +# only once bash has read it all. Questions are read from the terminal, as +# stdin is the script. +set -o pipefail + +REPO_URL="https://gitea.federated.computer/Federated_Computer/connector-popos" +API_URL="https://gitea.federated.computer/api/v1/repos/Federated_Computer/connector-popos" +BRANCH=main +BASE="$HOME/.local/share/federated-connector" +CONNECTOR="$BASE/connector" +VERSION_FILE="$CONNECTOR/.version" +BIN="$HOME/.local/bin" +LOG_DIR="$HOME/.local/state/federated-connector" +UNITS="$HOME/.config/systemd/user" +BASHRC="$HOME/.bashrc" +BLOCK_START="# >>> Federated Connector commands >>>" +BLOCK_END="# <<< Federated Connector commands <<<" +# What configure needs before any item: JSON, the keyring, Python's GObject +# bindings (Online Accounts, the email watcher) and notifications +PACKAGES=(curl jq libsecret-tools python3-gi gir1.2-secret-1 libnotify-bin) +RED=$'\033[31m' GREEN=$'\033[32m' YELLOW=$'\033[33m' BOLD=$'\033[1m' RESET=$'\033[0m' + +say() { + echo "$BOLD$*$RESET" +} + +fail() { + echo "$RED$*$RESET" + exit 1 +} + +# Questions come from the terminal; without one (e.g. in a script), the +# answer is no +has_tty() { + { : < /dev/tty; } 2> /dev/null +} + +confirm_yes() { + local answer + has_tty || return 1 + read -rp "$1 [Y/n] " answer < /dev/tty + [[ "$answer" != [nN]* ]] +} + +os_field() { + (. /etc/os-release 2> /dev/null && eval "echo \"\${$1}\"") +} + +# What can't be fixed from here, checked before anything changes +preflight() { + [ "$(uname -s)" = Linux ] || fail "This is for Pop!_OS. On a Mac, use Federated Connector for macOS." + [ "$(id -u)" -ne 0 ] || fail "Run this as yourself, not as root. It asks for your password when it needs it." + command -v apt-get > /dev/null || fail "This is for Pop!_OS (or another Ubuntu-based system); this one has no apt." + if [ "$(os_field ID)" != pop ]; then + echo "${YELLOW}This is made for Pop!_OS with COSMIC; this computer runs $(os_field PRETTY_NAME)." + echo "Most of it works on other Ubuntu-based systems too.$RESET" + fi + if ! id -Gn | tr ' ' '\n' | grep -qxE 'sudo|admin'; then + echo "${YELLOW}Your account isn't an administrator, so configure can't install what it needs" + echo "or change system settings (mounts, printers, Tailscale).$RESET" + fi + if [ -z "$FEDERATED_CONNECTOR_SOURCE" ] && ! curl -fsS --max-time 15 -o /dev/null "$API_URL"; then + fail "Couldn't reach Gitea ($REPO_URL). Connect to the internet and run this again." + fi +} + +installed_version() { + cat "$VERSION_FILE" 2> /dev/null +} + +# The commit main is at now +latest_version() { + if [ -n "$FEDERATED_CONNECTOR_SOURCE" ]; then + echo local + else + curl -fsS --max-time 30 "$API_URL/branches/$BRANCH" \ + | python3 -I -c 'import json, sys; print(json.load(sys.stdin)["commit"]["id"])' 2> /dev/null + fi +} + +# The commits between the installed version and the new one: "short subject" +changes_since() { + [ -n "$1" ] && [ "$1" != local ] && [ "$2" != local ] || return 0 + curl -fsS --max-time 30 "$API_URL/commits?sha=$2&limit=50&stat=false&verification=false&files=false" \ + | python3 -I -c ' +import json, sys +for commit in json.load(sys.stdin): + if commit["sha"] == sys.argv[1]: + break + print(commit["sha"][:7], commit["commit"]["message"].split("\n")[0])' "$1" 2> /dev/null +} + +# The packages configure needs, if any are missing +install_packages() { + local pkg missing=() + for pkg in "${PACKAGES[@]}"; do + [ "$(dpkg-query -W -f '${db:Status-Status}' "$pkg" 2> /dev/null)" = installed ] || missing+=("$pkg") + done + [ ${#missing[@]} -eq 0 ] && return 0 + echo "configure needs: ${missing[*]}" + if ! has_tty && ! sudo -n true 2> /dev/null; then + echo "${YELLOW}Install them with: sudo apt install ${missing[*]}$RESET" + return 1 + fi + # sudo asks for your password on the terminal itself; stdin is this script + sudo apt-get install -y "${missing[@]}" < /dev/null \ + || { sudo apt-get update < /dev/null && sudo apt-get install -y "${missing[@]}" < /dev/null; } +} + +# Put version $1 in a new folder next to CONNECTOR, then swap it in. A folder +# next to it is on the same disk, so the swap is two renames. +fetch_and_swap() { + local version="$1" staging="$BASE/.connector-new-$$" old="$BASE/.connector-old-$$" + mkdir -p "$BASE" || return 1 + rm -rf "$staging" + mkdir "$staging" || return 1 + if [ -n "$FEDERATED_CONNECTOR_SOURCE" ]; then + (cd "$FEDERATED_CONNECTOR_SOURCE" && tar --exclude ./.git --exclude .claude \ + --exclude ./smoketest/results -cf - .) | tar -xf - -C "$staging" || { rm -rf "$staging"; return 1; } + else + echo "Downloading ${version:0:7} from $REPO_URL" + curl -fsSL --max-time 300 "$REPO_URL/archive/$version.tar.gz" \ + | tar -xzf - -C "$staging" --strip-components 1 || { rm -rf "$staging"; return 1; } + fi + [ -x "$staging/configure" ] || { echo "The download doesn't look right (no configure in it)."; rm -rf "$staging"; return 1; } + echo "$version" > "$staging/.version" + if [ -d "$CONNECTOR" ]; then + mv "$CONNECTOR" "$old" || { rm -rf "$staging"; return 1; } + fi + if ! mv "$staging" "$CONNECTOR"; then + [ -d "$old" ] && mv "$old" "$CONNECTOR" + rm -rf "$staging" + return 1 + fi + rm -rf "$old" +} + +# configure and update in ~/.local/bin, linked so they follow updates +link_commands() { + local name + mkdir -p "$BIN" || return 1 + for name in configure update; do + ln -sfn "$CONNECTOR/$name" "$BIN/$name" || return 1 + done +} + +path_block() { + cat << EOF +$BLOCK_START +# configure and update: see $REPO_URL +case ":\$PATH:" in *":\$HOME/.local/bin:"*) ;; *) export PATH="\$HOME/.local/bin:\$PATH" ;; esac +$BLOCK_END +EOF +} + +# Ubuntu's ~/.profile puts ~/.local/bin on PATH at login, but only if it was +# there already, so on a new computer the commands wouldn't be found until +# you log in again. The block goes at the top of ~/.bashrc, so what comes +# later in it, e.g. the agent sandbox's line that configure agents adds, +# still comes first on PATH. +put_on_path() { + local tmp + grep -qxF "$BLOCK_START" "$BASHRC" 2> /dev/null && return 0 + tmp="$(mktemp)" || return 1 + { path_block; echo; cat "$BASHRC" 2> /dev/null || true; } > "$tmp" && cat "$tmp" > "$BASHRC" + rm -f "$tmp" + echo "Added ~/.local/bin to your PATH (in ~/.bashrc)." +} + +# The services configure set up run from copies of system/systemd's units; +# bring those up to date, and restart the email watcher on the new version +refresh_units() { + local unit changed=0 + for unit in "$CONNECTOR"/system/systemd/*; do + [ -f "$UNITS/$(basename "$unit")" ] || continue + cmp -s "$unit" "$UNITS/$(basename "$unit")" && continue + cp "$unit" "$UNITS/" && changed=1 + done + [ $changed -eq 1 ] && systemctl --user daemon-reload 2> /dev/null + if systemctl --user is-active -q federated-connector-email-watch.service 2> /dev/null; then + systemctl --user restart federated-connector-email-watch.service 2> /dev/null + fi + return 0 +} + +main() { + local update=0 installed latest log + [ "$1" = --update ] && update=1 + + mkdir -p "$LOG_DIR" && log="$LOG_DIR/$([ $update -eq 1 ] && echo update || echo install)-$(date +%Y-%m-%d-%H%M%S).log" + [ -n "$log" ] && exec > >(tee -a "$log") 2>&1 + + if [ $update -eq 0 ]; then + echo + say "Federated Connector for Pop!_OS" + echo "Sets up this computer for your Federated Core: email, calendars, contacts," + echo "files, backups, printers, shared folders and AI agents." + echo + fi + preflight + + installed="$(installed_version)" + latest="$(latest_version)" || fail "Couldn't find the latest version on Gitea." + [ -n "$latest" ] || fail "Couldn't find the latest version on Gitea." + + if [ $update -eq 1 ] && [ "$installed" = "$latest" ] && [ "$latest" != local ]; then + echo "Federated Connector is up to date (${latest:0:7})." + return 0 + fi + if [ $update -eq 1 ] && [ -n "$installed" ]; then + say "Updating Federated Connector from ${installed:0:7} to ${latest:0:7}" + changes_since "$installed" "$latest" | sed 's/^/ /' + fi + + install_packages || echo "${YELLOW}Some of configure won't work until they're installed.$RESET" + fetch_and_swap "$latest" || fail "Couldn't install Federated Connector." + link_commands || fail "Couldn't put configure and update in $BIN." + put_on_path + refresh_units + + echo + if [ $update -eq 1 ]; then + echo "${GREEN}Federated Connector is up to date (${latest:0:7}).$RESET" + return 0 + fi + echo "${GREEN}Federated Connector is installed in $CONNECTOR.$RESET" + echo "In a new terminal, run: configure (and later, to get new versions: update)" + if confirm_yes "Run configure now?"; then + "$CONNECTOR/configure" < /dev/tty + fi +} + +main "$@" +exit diff --git a/sandbox/agent b/sandbox/agent new file mode 100755 index 0000000..dccb162 --- /dev/null +++ b/sandbox/agent @@ -0,0 +1,145 @@ +#!/bin/bash +# +# Purpose : Run an AI agent inside Anthropic's sandbox runtime (srt). srt uses +# bubblewrap to limit which files the agent can read and write, and +# removes its network; socat links it to a proxy outside the sandbox +# that only lets through the domains in its config. +# +# sandbox/bin/<agent> links here and `configure agents` puts sandbox/bin first +# on PATH (in ~/.bashrc), so typing an agent's name runs it sandboxed. +# `unsandboxed <agent>` runs the agent's real command instead. +# +# The config is sandbox/config/base.json, then sandbox/config/<agent>.json, +# then your own ~/.config/federated-connector/sandbox/base.json and +# <agent>.json, in the same format. Later files add to the lists in earlier +# ones. Domains in FEDERATED_SANDBOX_DOMAINS (space-separated) are allowed too; +# `configure agents` uses it for Hermes' gateway, whose messaging server +# differs on each machine. + +# Wrapped in { ...; exit; } so bash reads the whole script up front; update +# replaces this file (git pull) while agents are running. +{ + +SANDBOX="$(dirname "$(realpath "$0")")" +CONNECTOR="$(dirname "$SANDBOX")" +USER_CONFIG="$HOME/.config/federated-connector/sandbox" +name="$(basename "$0")" +source "$CONNECTOR/configure.d/lib/agents.sh" + +# The agent's real command: the first one on PATH outside sandbox/bin +real_command() { + agent_path "$1" +} + +if [ "$name" = "unsandboxed" ]; then + if [ $# -eq 0 ]; then + echo "Usage: unsandboxed <agent> [arguments]" + exit 2 + fi + agent="$1" + shift + real="$(real_command "$agent")" || { echo "$agent isn't installed."; exit 127; } + exec "$real" "$@" +fi + +agent="$name" +real="$(real_command "$agent")" || { echo "$agent isn't installed."; exit 127; } + +# Commands that share another agent's sandbox config +case "$agent" in + hermes-agent) profile=hermes ;; + *) profile="$agent" ;; +esac + +# Cline Desktop is a window, usually opened from the app menu in your home +# directory, so it always starts in ~/Projects and can change projects there. +# Its profile hides /run/user, where your session's D-Bus and keyring sockets +# are, except the Wayland socket it draws through. The sandbox has no GPU, and +# WebKit can't start its own sandbox (bubblewrap) inside this one. +gui_socket="" +case "$profile" in + cline-desktop) + mkdir -p "$HOME/Projects" && cd "$HOME/Projects" || exit 1 + gui_socket="$XDG_RUNTIME_DIR/${WAYLAND_DISPLAY:-wayland-0}" + export GDK_BACKEND=wayland WEBKIT_DISABLE_DMABUF_RENDERER=1 WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS=1 ;; +esac + +if ! srt="$(srt_path)"; then + echo "The sandbox (srt) isn't installed; run: configure agents. To run $agent without it: unsandboxed $agent" + exit 1 +fi +# srt runs on the Node.js configure agents found or installed for it +PATH="$FC_TOOLS/srt/bin:$FC_TOOLS/node/bin:$PATH" + +# The agent can change anything in the directory it starts in +case "$PWD" in + "$HOME"|/) + echo "Start $agent from a project directory. In the sandbox it can change anything in the directory it starts in, and this is $PWD." + exit 1 ;; +esac + +configs=("$SANDBOX/config/base.json") +[ -f "$SANDBOX/config/$profile.json" ] && configs+=("$SANDBOX/config/$profile.json") +ours=("${configs[@]}") +for file in "$USER_CONFIG/base.json" "$USER_CONFIG/$profile.json"; do + [ -f "$file" ] && configs+=("$file") +done + +# Objects are merged and lists joined, so later files only add to earlier ones +MERGE=' +def merge(a; b): + reduce (b | to_entries[]) as $e (a; + .[$e.key] |= ( + if type == "object" and ($e.value | type) == "object" then merge(.; $e.value) + elif type == "array" and ($e.value | type) == "array" then . + $e.value | unique + else $e.value end)); +reduce .[] as $config ({}; merge(.; $config))' + +# srt runs in place of this script (exec below), so a stop signal, e.g. from +# systemd, reaches it and it passes it on to the agent. That leaves nothing to +# remove the settings file afterwards, so it's named after this process, and +# files whose process has ended are removed here. +SETTINGS_DIR="${XDG_RUNTIME_DIR:-/tmp}/federated-sandbox" +mkdir -p -m 700 "$SETTINGS_DIR" || exit 1 +for old in "$SETTINGS_DIR"/*.json; do + pid="${old%.json}" + pid="${pid##*.}" + [[ "$pid" =~ ^[0-9]+$ ]] && ! kill -0 "$pid" 2> /dev/null && rm -f "$old" +done + +# Outside the sandbox's writable paths, so the agent can't change its own rules +settings="$SETTINGS_DIR/$agent.$$.json" +if ! jq -s --arg domains "$FEDERATED_SANDBOX_DOMAINS" --arg socket "$gui_socket" \ + "$MERGE"' | .network.allowedDomains += ($domains | split(" ") | map(select(. != ""))) + | if $socket != "" then .filesystem.allowRead += [$socket] else . end' \ + "${configs[@]}" > "$settings"; then + echo "Couldn't read the sandbox config: ${configs[*]}" + exit 1 +fi + +# Bubblewrap can only make writable a directory that exists, and the agent +# can't create one itself in a parent it may not write to +while IFS= read -r path; do + path="${path/#\~/$HOME}" + case "$path" in "$HOME"/*) mkdir -p "$path" ;; esac +done < <(jq -rs "$MERGE | .filesystem.allowWrite[]? | strings" "${ours[@]}") + +# srt sets TMPDIR to /tmp/claude, which nothing creates, unless told otherwise; +# temp files then fail, and GTK aborts. /tmp is writable in every profile. +export CLAUDE_CODE_TMPDIR=/tmp + +# srt tells the agent to connect directly to private addresses (192.168.x.x +# and so on), but the sandbox has no network to do it with, so a server on +# your local network that the config allows by IP, e.g. an Ollama server from +# `configure ai-servers`, couldn't be reached. Only loopback is direct here; +# everything else goes through the proxy, which still allows only the config's +# domains and addresses. +NO_PROXY_DIRECT=localhost,127.0.0.1,::1 +direct=(env "NO_PROXY=$NO_PROXY_DIRECT" "no_proxy=$NO_PROXY_DIRECT") + +# Hermes' terminal reaches its gateway, in another sandbox, through a relay +case "$profile" in + hermes) exec "$srt" --settings "$settings" -- "${direct[@]}" bash "$SANDBOX/hermes-bridge" "$real" "$@" ;; +esac +exec "$srt" --settings "$settings" -- "${direct[@]}" "$real" "$@" +} diff --git a/sandbox/bin/cline-desktop b/sandbox/bin/cline-desktop new file mode 120000 index 0000000..b1d7999 --- /dev/null +++ b/sandbox/bin/cline-desktop @@ -0,0 +1 @@ +../agent \ No newline at end of file diff --git a/sandbox/bin/hermes b/sandbox/bin/hermes new file mode 120000 index 0000000..b1d7999 --- /dev/null +++ b/sandbox/bin/hermes @@ -0,0 +1 @@ +../agent \ No newline at end of file diff --git a/sandbox/bin/hermes-agent b/sandbox/bin/hermes-agent new file mode 120000 index 0000000..b1d7999 --- /dev/null +++ b/sandbox/bin/hermes-agent @@ -0,0 +1 @@ +../agent \ No newline at end of file diff --git a/sandbox/bin/opencode b/sandbox/bin/opencode new file mode 120000 index 0000000..b1d7999 --- /dev/null +++ b/sandbox/bin/opencode @@ -0,0 +1 @@ +../agent \ No newline at end of file diff --git a/sandbox/bin/unsandboxed b/sandbox/bin/unsandboxed new file mode 120000 index 0000000..b1d7999 --- /dev/null +++ b/sandbox/bin/unsandboxed @@ -0,0 +1 @@ +../agent \ No newline at end of file diff --git a/sandbox/config/base.json b/sandbox/config/base.json new file mode 100644 index 0000000..d148ca8 --- /dev/null +++ b/sandbox/config/base.json @@ -0,0 +1,96 @@ +{ + "network": { + "allowedDomains": [ + "anthropic.com", + "*.anthropic.com", + "openai.com", + "*.openai.com", + "chatgpt.com", + "*.chatgpt.com", + "openrouter.ai", + "*.openrouter.ai", + "nousresearch.com", + "*.nousresearch.com", + "generativelanguage.googleapis.com", + "api.mistral.ai", + "api.deepseek.com", + "api.x.ai", + "api.groq.com", + "api.together.xyz", + "*.githubcopilot.com", + "github.com", + "*.github.com", + "*.githubusercontent.com", + "gitea.federated.computer", + "registry.npmjs.org", + "registry.yarnpkg.com", + "pypi.org", + "files.pythonhosted.org", + "crates.io", + "*.crates.io", + "rubygems.org", + "*.rubygems.org", + "proxy.golang.org", + "sum.golang.org", + "ubuntu.com", + "*.ubuntu.com", + "pop-os.org", + "*.pop-os.org", + "system76.com", + "*.system76.com" + ], + "deniedDomains": [] + }, + "filesystem": { + "denyRead": [ + "~/.ssh", + "~/.gnupg", + "~/.password-store", + "~/.local/share/keyrings", + "~/.netrc", + "~/.git-credentials", + "~/.aws", + "~/.azure", + "~/.config/gcloud", + "~/.kube", + "~/.docker", + "~/.config/gh", + "~/.config/tea", + "~/.config/borg", + "~/.config/Bitwarden", + "~/.config/Element", + "~/.mozilla", + "~/.config/chromium", + "~/.config/google-chrome", + "~/.config/BraveSoftware", + "~/.config/net.imput.helium", + "~/.var/app", + "~/.davfs2", + "~/.winboat", + "~/.claude", + "~/.claude.json", + "~/.hermes", + "~/.config/opencode", + "~/.local/share/opencode", + "~/.cline", + "~/.config/bot.cline.app", + "~/.local/share/bot.cline.app", + "~/.config/evolution", + "~/.local/share/evolution", + "~/.cache/evolution", + "~/.config/goa-1.0", + "~/.thunderbird" + ], + "allowRead": [], + "allowWrite": [ + ".", + "/tmp", + "~/.npm", + "~/.cache/pip", + "~/.cargo/registry", + "~/.cargo/git", + "~/go/pkg/mod" + ], + "denyWrite": [] + } +} diff --git a/sandbox/config/cline-desktop.json b/sandbox/config/cline-desktop.json new file mode 100644 index 0000000..08a4147 --- /dev/null +++ b/sandbox/config/cline-desktop.json @@ -0,0 +1,35 @@ +{ + "network": { + "allowedDomains": [ + "cline.bot", + "*.cline.bot" + ], + "allowAllUnixSockets": true + }, + "filesystem": { + "denyRead": [ + "/run/user", + "/run/dbus", + "/run/docker.sock", + "/run/podman", + "/run/tailscale", + "/run/ssh-unix-local", + "/tmp/.X11-unix", + "/tmp/tmux-*", + "/tmp/ssh-*", + "/tmp/*/SingletonSocket" + ], + "allowRead": [ + "~/.cline", + "~/.config/bot.cline.app", + "~/.local/share/bot.cline.app", + "~/.cache/bot.cline.app" + ], + "allowWrite": [ + "~/.cline", + "~/.config/bot.cline.app", + "~/.local/share/bot.cline.app", + "~/.cache/bot.cline.app" + ] + } +} diff --git a/sandbox/config/hermes.json b/sandbox/config/hermes.json new file mode 100644 index 0000000..b541e2a --- /dev/null +++ b/sandbox/config/hermes.json @@ -0,0 +1,26 @@ +{ + "network": { + "allowedDomains": [], + "allowAllUnixSockets": true + }, + "filesystem": { + "denyRead": [ + "/run/user", + "/run/dbus", + "/run/docker.sock", + "/run/podman", + "/run/tailscale", + "/run/ssh-unix-local", + "/tmp/.X11-unix", + "/tmp/tmux-*", + "/tmp/ssh-*", + "/tmp/*/SingletonSocket" + ], + "allowRead": [ + "~/.hermes" + ], + "allowWrite": [ + "~/.hermes" + ] + } +} diff --git a/sandbox/config/opencode.json b/sandbox/config/opencode.json new file mode 100644 index 0000000..d976b2a --- /dev/null +++ b/sandbox/config/opencode.json @@ -0,0 +1,21 @@ +{ + "network": { + "allowedDomains": [ + "opencode.ai", + "*.opencode.ai", + "models.dev" + ] + }, + "filesystem": { + "allowRead": [ + "~/.config/opencode", + "~/.local/share/opencode" + ], + "allowWrite": [ + "~/.config/opencode", + "~/.local/share/opencode", + "~/.local/state/opencode", + "~/.cache/opencode" + ] + } +} diff --git a/sandbox/hermes-bridge b/sandbox/hermes-bridge new file mode 100755 index 0000000..5104c0d --- /dev/null +++ b/sandbox/hermes-bridge @@ -0,0 +1,81 @@ +#!/bin/bash +# +# Purpose : Run Hermes inside its sandbox (sandbox/agent runs this there) and +# connect its terminal to its gateway. +# +# Hermes' gateway runs the agent; `hermes` in a terminal only talks to it, over +# the gateway's control socket and then a WebSocket on 127.0.0.1:<port>. Each +# sandbox has its own network, so that port can't be reached from another one. +# The gateway's sandbox relays the port to API_SOCKET, and a terminal's sandbox +# listens on the same port and relays to API_SOCKET, so `hermes` reaches the +# gateway as if they shared a network. +# +# Usage: hermes-bridge <hermes command> [arguments] + +real="$1" +shift +HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}" +API_SOCKET="$HERMES_HOME/federated-api.sock" + +# The gateway's answer to `identify` on its control socket, or nothing if no +# gateway is running +identify() { + local control="$HERMES_HOME/gateway.sock" + [ -S "$control" ] || control="$(cat "$HERMES_HOME/gateway.sock.path" 2> /dev/null)" + [ -S "$control" ] || return 1 + printf '{"protocol":1,"verb":"identify","id":1}\n' \ + | socat -t 5 - "UNIX-CONNECT:$control" 2> /dev/null | grep . +} + +# The port the gateway's API listens on, once the gateway is ready. Only an +# IPv4 loopback origin is relayed, which is what Hermes uses by default. +api_port() { + local origin + origin="$(identify | jq -r 'select(.result.state == "ready") | .result.api_origin // empty' 2> /dev/null)" + [[ "$origin" =~ ^http://127\.0\.0\.1:([0-9]+)$ ]] || return 1 + echo "${BASH_REMATCH[1]}" +} + +if [ "$1" = "gateway" ] && [ "$2" = "run" ]; then + # A terminal finds no relay, rather than the last gateway's, until this one + # is up + rm -f "$API_SOCKET" + # The relay waits for the gateway, which runs in this process once exec'd; + # the sandbox ends both together + ( + for _ in $(seq 480); do + if port="$(api_port)"; then + exec socat "UNIX-LISTEN:$API_SOCKET,unlink-early,mode=600,fork" "TCP:127.0.0.1:$port" + fi + sleep 0.25 + done + echo "hermes-bridge: the gateway's API didn't come up; terminals can't reach it" >&2 + ) & + exec "$real" "$@" +fi + +# A terminal: relay the gateway's port, if a gateway is running or its service +# is turned on, waiting for one that is still starting. Without one, hermes +# starts its own gateway inside this sandbox, which needs no relay. +if [ -e "$HOME/.config/systemd/user/default.target.wants/hermes-gateway.service" ] \ + || identify > /dev/null; then + [ -S "$API_SOCKET" ] && api_port > /dev/null || echo "Waiting for Hermes' gateway..." >&2 + for _ in $(seq 240); do + [ -S "$API_SOCKET" ] && port="$(api_port)" && break + port="" + sleep 0.25 + done + if [ -n "$port" ]; then + socat "TCP-LISTEN:$port,bind=127.0.0.1,reuseaddr,fork" "UNIX-CONNECT:$API_SOCKET" & + # Wait for the listener (state 0A, LISTEN, in /proc/net/tcp) so hermes' + # first connection doesn't fail + hex="$(printf ':%04X ' "$port")" + for _ in $(seq 50); do + grep -q "$hex.* 0A " /proc/net/tcp && break + sleep 0.05 + done + else + echo "hermes-bridge: Hermes' gateway is running but its API isn't reachable; try: systemctl --user restart hermes-gateway" >&2 + fi +fi +exec "$real" "$@" diff --git a/smoketest/Dockerfile b/smoketest/Dockerfile new file mode 100644 index 0000000..c67a1ca --- /dev/null +++ b/smoketest/Dockerfile @@ -0,0 +1,15 @@ +# Ubuntu 24.04, which Pop!_OS 24.04 is built on: the same apt packages, +# except COSMIC's own. A user "pop" with passwordless sudo, as configure +# expects an administrator. configure's own packages (install.sh's PACKAGES) +# are already in, to keep each scenario quick; 05-install takes one out. +FROM ubuntu:24.04 +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update \ + && apt-get install -y --no-install-recommends sudo ca-certificates curl dbus-x11 gnome-keyring \ + xz-utils procps iproute2 \ + jq libsecret-tools python3-gi gir1.2-secret-1 libnotify-bin avahi-utils \ + && rm -rf /var/lib/apt/lists/* +RUN useradd -m -s /bin/bash pop && echo 'pop ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/pop \ + && printf 'ID=pop\nNAME="Pop!_OS"\nPRETTY_NAME="Pop!_OS 24.04 LTS (smoketest)"\nVERSION_ID="24.04"\nID_LIKE="ubuntu debian"\nUBUNTU_CODENAME=noble\nVERSION_CODENAME=noble\n' > /etc/os-release +USER pop +WORKDIR /home/pop diff --git a/smoketest/README.md b/smoketest/README.md new file mode 100644 index 0000000..285bd19 --- /dev/null +++ b/smoketest/README.md @@ -0,0 +1,61 @@ +# Smoketest + +These tests run `configure`'s pieces on Ubuntu 24.04, which Pop!_OS 24.04 is built on, in throwaway Docker containers. A container has the same apt packages as Pop!_OS, except COSMIC's own, and `/etc/os-release` says Pop!_OS. Each scenario starts a session D-Bus and an unlocked gnome-keyring, as COSMIC does at login. + +They check what lint can't: + +- GNOME Online Accounts 3.50 without GNOME +- Ubuntu's restic, rclone, davfs2 and sshfs +- mise's apt repository +- the sandbox, with real downloads + +## Running it + +``` +smoketest/run --list # scenarios and their tier +smoketest/run # the quick scenarios +smoketest/run --tier all # everything, including the downloads +smoketest/run 40-backup # one scenario (or: smoketest/run 40) +smoketest/run --keep 20 # keep the container afterwards, to look around +``` + +It tests the working copy as it is, including uncommitted changes. The first run builds the image. Each scenario takes a few seconds plus its own apt installs; `50-sandbox` downloads Node.js and srt, and runs with `--privileged` so bubblewrap can make user namespaces. + +Each run writes its logs to `smoketest/results/<time>/`, one per scenario, and prints which scenarios passed. + +## Scenarios + +| Scenario | Checks | +|----------|--------| +| `05-install` | `install.sh` piped into bash, as `curl \| bash` runs it, with the working copy. It installs a missing package again, links the commands, puts `~/.local/bin` on PATH for a new bash, and doesn't ask to run `configure` without a terminal. `update` swaps in a fresh copy without leaving staging folders behind. | +| `10-configure` | `--help`, `--list` (nothing on stderr; agent sign-ins and the sandbox item hidden until they apply), the menu, an unknown item, the Core item's first question, and refusing to run as root | +| `20-goa` | `goa-account` with Online Accounts 3.50. It adds Nextcloud and email (quoting a name), adding again changes nothing, and it pauses email and ends the pause. Test a Core takes an unreachable mail server as a sign-in failure, not a wrong password. Removing leaves nothing in the keyring. | +| `30-core-local` | Superpanel's entry, Element's config (in ~/.config, or the Flatpak's folder), and the COSMIC Files sidebar. The sidebar check reads and writes ron's pretty format with network places and escaped names, keeps COSMIC Files' defaults, and leaves a file it can't read alone. Then davfs2's secret, read back. | +| `40-backup` | restic and rclone from apt, with `rclone serve webdav` standing in for Nextcloud and the secrets in the keyring. `system/backup` makes a snapshot that leaves out caches and the install, a file restores from it, and without the passphrase it fails. | +| `50-sandbox` *(all)* | Node.js and srt download and install. A stand-in agent can't read `~/.ssh` or write outside its project, reaches allowed sites only, and won't start in your home folder. A new bash finds the sandboxed command first. | +| `60-packages` *(all)* | davfs2 installs with `mount.davfs` setuid, and `davfs2_ready` fixes one installed without. sshfs' `fusermount3` and smbclient are where `configure storage` expects them, and so is GTK's CUPS print backend. mise installs from its apt repository and a new bash has it. | + +## What still needs Pop!_OS + +A container has no COSMIC session, systemd user manager, FUSE mounts or AppArmor, so check these by hand on Pop!_OS 24.04: + +- **COSMIC Files** shows a folder added to its sidebar, with its name. +- **Evolution** shows the email, calendars and contacts that `configure core` adds, against a real Core. +- **Mounting your files** with davfs2 after `configure core`, and again after logging out and in. +- **The services**: the backup timer, the email watcher's notification, and that clicking it opens `configure core` in COSMIC Terminal. +- **The AppArmor profile** for bubblewrap, if Pop!_OS restricts user namespaces. +- **Tailscale** joining a Core's headscale, and **SMB and SFTP mounts** of real servers. + +## Writing a scenario + +A scenario is a bash file in `scenarios/` that sets `DESCRIPTION` and `TIER`, either `quick` or `all`, and defines `scenario`. `PRIVILEGED=1` runs its container with `--privileged`. It runs with what `configure` gives items: `CONNECTOR`, `CONF_DIR`, and `confirm` and `confirm_yes`, which always answer yes. So it can source an item and call its functions. The user `pop` has passwordless sudo. Checks, from `lib/runner.sh`: + +| Check | | +|-------|---| +| `check "what" cmd...` | ok if the command succeeds; otherwise FAIL, with its output | +| `check_not "what" cmd...` | ok if the command fails | +| `check_eq "what" expected actual` | ok if they're the same | +| `skip "why"` | Note something not checked | +| `step "what"` | A heading | + +`check` runs its command in a subshell, so variables it sets don't last. Set those before the check. diff --git a/smoketest/lib/runner.sh b/smoketest/lib/runner.sh new file mode 100755 index 0000000..513e097 --- /dev/null +++ b/smoketest/lib/runner.sh @@ -0,0 +1,91 @@ +#!/bin/bash +# +# Purpose : Run one smoketest scenario inside the container (smoketest/run +# starts this). Prints ok, FAIL or skip for each check, and exits 1 +# if any failed. +# +# Usage: runner.sh <scenario file> +# +# A scenario sets DESCRIPTION and TIER and defines `scenario`, which calls the +# checks below. It runs with what configure gives items (CONNECTOR, CONF_DIR, +# confirm...), answering yes to every question, so it can source items and +# call their functions. A desktop session's D-Bus and an unlocked keyring are +# started first, as COSMIC starts them at login. + +CONNECTOR="$HOME/connector" +CONF_DIR="$HOME/.config/federated-connector" +export CONNECTOR CONF_DIR +RED=$'\033[31m' GREEN=$'\033[32m' YELLOW=$'\033[33m' RESET=$'\033[0m' +FAILURES=0 + +# configure's questions, answered yes +confirm() { echo "$1 [y/N] y"; return 0; } +confirm_yes() { echo "$1 [Y/n] y"; return 0; } + +# check <description> <command...>: ok if the command succeeds +check() { + local description="$1" output + shift + if output="$("$@" 2>&1)"; then + echo "${GREEN}ok$RESET $description" + else + echo "${RED}FAIL$RESET $description" + [ -n "$output" ] && printf '%s\n' "$output" | tail -n 15 | sed 's/^/ /' + FAILURES=$((FAILURES + 1)) + fi +} + +# check_not <description> <command...>: ok if the command fails +check_not() { + local description="$1" + shift + if "$@" > /dev/null 2>&1; then + echo "${RED}FAIL$RESET $description (it succeeded)" + FAILURES=$((FAILURES + 1)) + else + echo "${GREEN}ok$RESET $description" + fi +} + +# check_eq <description> <expected> <actual> +check_eq() { + if [ "$2" = "$3" ]; then + echo "${GREEN}ok$RESET $1" + else + echo "${RED}FAIL$RESET $1" + echo " expected: $2" + echo " got: $3" + FAILURES=$((FAILURES + 1)) + fi +} + +skip() { + echo "${YELLOW}skip$RESET $1" +} + +step() { + echo "-- $*" +} + +# The session D-Bus and keyring +export XDG_RUNTIME_DIR="/tmp/runtime-$UID" +mkdir -p -m 700 "$XDG_RUNTIME_DIR" +eval "$(dbus-launch --sh-syntax)" +echo -n smoketest | gnome-keyring-daemon --unlock --components=secrets > /dev/null +export PATH="$HOME/.local/bin:$PATH" + +cd "$HOME" || exit 1 +source "$CONNECTOR/configure.d/lib/packages.sh" +source "$CONNECTOR/configure.d/lib/agents.sh" +# shellcheck disable=SC1090 +source "$1" || { echo "Couldn't read $1"; exit 1; } +echo "$DESCRIPTION" +echo "($(. /etc/os-release && echo "$PRETTY_NAME"), $(uname -m))" +scenario +echo +if [ $FAILURES -eq 0 ]; then + echo "${GREEN}All checks passed.$RESET" +else + echo "${RED}$FAILURES check(s) failed.$RESET" + exit 1 +fi diff --git a/smoketest/run b/smoketest/run new file mode 100755 index 0000000..2646a74 --- /dev/null +++ b/smoketest/run @@ -0,0 +1,111 @@ +#!/bin/bash +# +# Purpose : Run the smoketest scenarios, each in a fresh Ubuntu 24.04 +# container (Pop!_OS 24.04's base) with Docker. See README.md. +# +# Usage: smoketest/run [--tier quick|all] [--keep] [scenario...] +# smoketest/run --list + +# Wrapped in { ...; exit; } so bash reads the whole script up front +{ + +SMOKETEST="$(cd "$(dirname "$0")" && pwd)" +REPO="$(dirname "$SMOKETEST")" +IMAGE="federated-connector-popos-smoketest" +TIER=quick +KEEP=0 +SCENARIOS=() + +usage() { + cat << EOF +Usage: smoketest/run [options] [scenario...] + + --tier quick|all quick leaves out the slow scenarios (default: quick) + --keep Leave each container afterwards, to look around in it + --list List the scenarios and their tier + +Scenarios are named by file name or number, e.g. 40-backup or 40. +EOF +} + +scenario_var() { + sed -nE "s/^$2=\"?([^\"]*)\"?.*/\\1/p" "$1" | head -n 1 +} + +list() { + local file + for file in "$SMOKETEST"/scenarios/*.sh; do + printf '%-20s %-6s %s\n' "$(basename "$file" .sh)" "$(scenario_var "$file" TIER)" \ + "$(scenario_var "$file" DESCRIPTION)" + done +} + +while [ $# -gt 0 ]; do + case "$1" in + --tier) TIER="$2"; shift 2 ;; + --keep) KEEP=1; shift ;; + --list) list; exit 0 ;; + -h|--help) usage; exit 0 ;; + -*) usage; exit 2 ;; + *) SCENARIOS+=("$1"); shift ;; + esac +done + +command -v docker > /dev/null || { echo "Docker isn't installed."; exit 1; } + +# The scenario files to run +pick() { + local file name want + for file in "$SMOKETEST"/scenarios/*.sh; do + name="$(basename "$file" .sh)" + if [ ${#SCENARIOS[@]} -eq 0 ]; then + [ "$TIER" = all ] || [ "$(scenario_var "$file" TIER)" = quick ] || continue + echo "$file" + else + for want in "${SCENARIOS[@]}"; do + case "$name" in "$want"|"$want"-*) echo "$file" ;; esac + done + fi + done +} + +mapfile -t FILES < <(pick) +if [ ${#FILES[@]} -eq 0 ]; then + echo "No scenarios to run. smoketest/run --list shows them." + exit 2 +fi + +echo "Building the image..." +docker build -q -t "$IMAGE" "$SMOKETEST" > /dev/null || exit 1 + +RESULTS="$SMOKETEST/results/$(date +%Y%m%d-%H%M%S)" +mkdir -p "$RESULTS" +PASSED=() FAILED=() + +for file in "${FILES[@]}"; do + scenario="$(basename "$file" .sh)" + log="$RESULTS/$scenario.log" + echo + echo "== $scenario: $(scenario_var "$file" DESCRIPTION)" + # The sandbox needs to make user namespaces, which Docker's defaults forbid + extra=() + [ "$(scenario_var "$file" PRIVILEGED)" = 1 ] && extra=(--privileged) + rm_flag=(--rm) + [ $KEEP -eq 1 ] && rm_flag=(--name "fc-smoke-$scenario-$$") + # The working copy, as it is now, read-only at /src and copied to ~/connector + docker run "${rm_flag[@]}" "${extra[@]}" -v "$REPO:/src:ro" "$IMAGE" bash -c ' + mkdir ~/connector && tar -C /src --exclude ./.git --exclude .claude --exclude ./smoketest/results -cf - . \ + | tar -xf - -C ~/connector && bash ~/connector/smoketest/lib/runner.sh ~/connector/smoketest/scenarios/'"$scenario"'.sh' \ + 2>&1 | tee "$log" + status=${PIPESTATUS[0]} + [ $KEEP -eq 1 ] && echo " Kept the container: docker start -ai fc-smoke-$scenario-$$ (docker rm it afterwards)" + if [ "$status" -eq 0 ]; then PASSED+=("$scenario"); else FAILED+=("$scenario"); fi +done + +echo +echo "Passed: ${PASSED[*]:-none}" +echo "Failed: ${FAILED[*]:-none}" +echo "Logs: $RESULTS" +[ ${#FAILED[@]} -eq 0 ] +exit +} diff --git a/smoketest/scenarios/05-install.sh b/smoketest/scenarios/05-install.sh new file mode 100644 index 0000000..596b86c --- /dev/null +++ b/smoketest/scenarios/05-install.sh @@ -0,0 +1,29 @@ +# shellcheck shell=bash +# Scenarios set what the runner and items read +# shellcheck disable=SC2034 +DESCRIPTION="install.sh piped into bash, as curl | bash runs it, then update" +TIER=quick + +scenario() { + step "Install the working copy, with jq missing" + sudo apt-get remove -y jq > /dev/null 2>&1 + export FEDERATED_CONNECTOR_SOURCE="$CONNECTOR" + bash < "$CONNECTOR/install.sh" > "$HOME/install.log" 2>&1 + check_eq "install.sh succeeds" 0 $? + check "it installed jq again" pkg_installed jq + check "configure is linked in ~/.local/bin" test -L "$HOME/.local/bin/configure" + check "update is linked in ~/.local/bin" test -L "$HOME/.local/bin/update" + check "the install is in place" test -x "$HOME/.local/share/federated-connector/connector/configure" + check_eq "it records the version" local "$(cat "$HOME/.local/share/federated-connector/connector/.version")" + check "configure is on PATH in a new bash" bash -ic 'command -v configure' < /dev/null + check "it didn't ask to run configure without a terminal" grep -q "In a new terminal, run: configure" "$HOME/install.log" + check "it wrote a log" compgen -G "$HOME/.local/state/federated-connector/install-*.log" + + step "update" + check "update --version" "$HOME/.local/bin/update" --version + "$HOME/.local/bin/update" > "$HOME/update.log" 2>&1 + check_eq "update succeeds" 0 $? + check "no staging folders are left" bash -c '! compgen -G "$HOME/.local/share/federated-connector/.connector-*"' + check_eq "the PATH block is in ~/.bashrc once" 1 "$(grep -c '>>> Federated Connector commands >>>' "$HOME/.bashrc")" + check "the installed configure runs" "$HOME/.local/bin/configure" --help +} diff --git a/smoketest/scenarios/10-configure.sh b/smoketest/scenarios/10-configure.sh new file mode 100644 index 0000000..27b84dc --- /dev/null +++ b/smoketest/scenarios/10-configure.sh @@ -0,0 +1,24 @@ +# shellcheck shell=bash +# Scenarios set what the runner and items read +# shellcheck disable=SC2034 +DESCRIPTION="configure --help, --list, the menu, and an item's first question" +TIER=quick + +scenario() { + local out err + check "--help" "$CONNECTOR/configure" --help + out="$("$CONNECTOR/configure" --list 2> "$HOME/err")" + err="$(cat "$HOME/err")" + check_eq "--list writes nothing on stderr" "" "$err" + for item in core tailscale backup agents languages ai-servers printers storage; do + check "--list has $item" grep -qE "^(done|to do) +$item " <<< "$out" + done + check_not "--list leaves out sign-ins for agents that aren't installed" grep -qE ' (claude|opencode|hermes) ' <<< "$out" + check_not "--list leaves out the sandbox item without WinBoat" grep -q ' sandbox ' <<< "$out" + check "the menu quits on q" bash -c "echo q | '$CONNECTOR/configure' | grep -q 'Federated Core on this computer'" + check_not "it doesn't warn that this isn't Pop!_OS" bash -c "echo q | '$CONNECTOR/configure' | grep -q 'made for Pop'" + check_eq "an unknown item exits 2" 2 "$("$CONNECTOR/configure" nonsense > /dev/null; echo $?)" + check "configure core gives up on a Superpanel it can't reach" \ + bash -c "printf 'https://superpanel.smoke.invalid\n' | '$CONNECTOR/configure' core | grep -q \"Couldn't reach https://superpanel.smoke.invalid\"" + check_not "it doesn't run as root" sudo "$CONNECTOR/configure" --list +} diff --git a/smoketest/scenarios/20-goa.sh b/smoketest/scenarios/20-goa.sh new file mode 100644 index 0000000..2c4e8e7 --- /dev/null +++ b/smoketest/scenarios/20-goa.sh @@ -0,0 +1,54 @@ +# shellcheck shell=bash +# Scenarios set what the runner and items read +# shellcheck disable=SC2034 +DESCRIPTION="Email, calendars and contacts in GNOME Online Accounts 3.50, without GNOME" +TIER=quick + +scenario() { + local G="$CONNECTOR/configure.d/lib/goa-account" out + step "Installing GNOME Online Accounts and Evolution's data server" + # Evolution itself is large and only shows what's here; its data server is + # what reads Online Accounts + sudo apt-get update > /dev/null && sudo apt-get install -y gnome-online-accounts evolution-data-server > /dev/null 2>&1 + check "gnome-online-accounts is installed" pkg_installed gnome-online-accounts + + source "$CONNECTOR/configure.d/10-core.sh" + goa_ready() { return 0; } + CORE_DOMAIN=smoke.invalid CORE_EMAIL=jo@smoke.invalid CORE_NAME='Jo "Q" Tester' + core_names + PASSWORD='p\ss "word"' APP_PASSWORD=app-password-1 + + step "Adding the accounts" + check "setup_nextcloud" setup_nextcloud + check "setup_email, with the usual servers when the domain has no autoconfig" setup_email + check "nextcloud_done" nextcloud_done + check "email_done" email_done + check "adding again changes nothing" setup_email + check_eq "there's one email account" 1 "$(grep -c '^Provider=imap_smtp' "$HOME/.config/goa-1.0/accounts.conf")" + check "IMAP is mail.smoke.invalid over SSL" grep -qx 'ImapHost=mail.smoke.invalid' "$HOME/.config/goa-1.0/accounts.conf" + check "SMTP uses STARTTLS on 587" grep -qx 'SmtpUseTls=true' "$HOME/.config/goa-1.0/accounts.conf" + check "the name survives quoting" grep -qxF 'Name=Jo "Q" Tester' "$HOME/.config/goa-1.0/accounts.conf" + check_eq "nothing is turned off" "" "$("$G" disabled owncloud "$CORE_USER@nextcloud.$CORE_DOMAIN")" + + step "Pausing email, as email-watch does" + check_not "not paused at first" "$G" paused imap_smtp "$CORE_EMAIL" + check "pause" "$G" pause imap_smtp "$CORE_EMAIL" + check "paused" "$G" paused imap_smtp "$CORE_EMAIL" + jq -n '{"imap-password": "new", "smtp-password": "new"}' | "$G" update imap_smtp "$CORE_EMAIL" 2> /dev/null + check_eq "update saves the password; the server can't be reached, so it exits 3" 3 $? + check_not "update ends the pause" "$G" paused imap_smtp "$CORE_EMAIL" + + step "Test a Core's account checks" + "$CONNECTOR/system/email-watch" --check-password "$CORE_EMAIL" + check_eq "email-watch can't tell without Nextcloud (1)" 1 $? + FIXES=() FIX_TITLES=() PROBLEMS=0 + out="$(test_account "Email" imap_smtp "$CORE_EMAIL" setup_email fix_email enable_email)" + check "an unreachable mail server is a sign-in failure, not a wrong password" grep -q "can't sign in" <<< "$out" + check_not "...and isn't taken as an old password" grep -q "old password" <<< "$out" + + step "Removing" + check "remove owncloud" "$G" remove owncloud "$CORE_USER@nextcloud.$CORE_DOMAIN" + check "remove imap_smtp" "$G" remove imap_smtp "$CORE_EMAIL" + check_not "nothing left" email_done + check "no passwords left in the keyring" bash -c '! secret-tool search --all xdg:schema org.gnome.OnlineAccounts 2>&1 | grep -q goa-identity' +} diff --git a/smoketest/scenarios/30-core-local.sh b/smoketest/scenarios/30-core-local.sh new file mode 100644 index 0000000..8e6b768 --- /dev/null +++ b/smoketest/scenarios/30-core-local.sh @@ -0,0 +1,81 @@ +# shellcheck shell=bash +# Scenarios set what the runner and items read +# shellcheck disable=SC2034 +DESCRIPTION="The Core item's local parts: Superpanel, Element, the Files sidebar, davfs2's secret" +TIER=quick + +scenario() { + local fav="$HOME/.config/cosmic/com.system76.CosmicFiles/v1/favorites" F="$CONNECTOR/configure.d/lib/cosmic-favorites" + source "$CONNECTOR/configure.d/10-core.sh" + CORE_DOMAIN=smoke.invalid CORE_EMAIL=jo@smoke.invalid CORE_NAME=Jo + core_names + + step "Superpanel" + check "setup_superpanel without its icon" setup_superpanel + check "superpanel_done" superpanel_done + check "it opens Superpanel" grep -qx 'Exec=xdg-open https://superpanel.smoke.invalid' "$SUPERPANEL_DESKTOP" + check "it falls back to a theme icon" grep -qx 'Icon=applications-internet' "$SUPERPANEL_DESKTOP" + + step "Element" + check_eq "without Flatpak, Element's config is in ~/.config" "$HOME/.config/Element/config.json" "$ELEMENT_CONFIG" + mkdir -p "$HOME/.config/Element" && echo '{"brand": "Element"}' > "$ELEMENT_CONFIG" + check "setup_element" setup_element + check_eq "it points at the Core's Matrix server" "https://matrix.smoke.invalid" \ + "$(jq -r '.default_server_config["m.homeserver"].base_url' "$ELEMENT_CONFIG")" + check_eq "it keeps the rest" Element "$(jq -r .brand "$ELEMENT_CONFIG")" + flatpak_installed() { [ "$1" = im.riot.Riot ]; } + check_eq "with the Flatpak, it's in the app's folder" \ + "$HOME/.var/app/im.riot.Riot/config/Element/config.json" "$(element_config)" + unset -f flatpak_installed + source "$CONNECTOR/configure.d/lib/packages.sh" + + step "The COSMIC Files sidebar" + check_not "no favorites file yet" test -f "$fav" + check "sidebar_add" sidebar_add /mnt/smoke.invalid smoke.invalid + check "COSMIC Files' defaults are kept" grep -q '^ Home,$' "$fav" + check "it's added as Named" grep -qF 'Named(path: "/mnt/smoke.invalid", name: "smoke.invalid")' "$fav" + check "sidebar_has" sidebar_has /mnt/smoke.invalid + check "it's in GTK's bookmarks" grep -qx 'file:///mnt/smoke.invalid smoke.invalid' "$HOME/.config/gtk-3.0/bookmarks" + # As COSMIC Files writes it (ron's pretty printer), with a network place + # and a name that needs escaping + cat > "$fav" << 'RON' +[ + Home, + Documents, + Network( + uri: "sftp://nas.local/", + name: "NAS, \"main\"", + path: "/run/user/1000/gvfs/sftp:host=nas.local", + ), + Path("/mnt/a (b)"), + Named( + path: "/mnt/smoke.invalid", + name: "old name", + ), +] +RON + check "adding again replaces the old entry" "$F" add /mnt/smoke.invalid 'smoke "q" \ x' + check_eq "...once" 1 "$(grep -c '/mnt/smoke.invalid' "$fav")" + check "a name with quotes and backslashes is escaped" grep -qF 'name: "smoke \"q\" \\ x")' "$fav" + check "the network place survives" grep -qF 'Network(' "$fav" + check "a Path(...) is found" "$F" has '/mnt/a (b)' + check "remove" "$F" remove '/mnt/a (b)' + check_not "it's gone" "$F" has '/mnt/a (b)' + check "sidebar_remove" sidebar_remove /mnt/smoke.invalid + check_not "removed from COSMIC Files" sidebar_has /mnt/smoke.invalid + check_not "removed from GTK's bookmarks" grep -q smoke.invalid "$HOME/.config/gtk-3.0/bookmarks" + check_eq "three places are left" 3 "$(python3 -c " +import importlib.machinery, importlib.util, sys +loader = importlib.machinery.SourceFileLoader('f', '$F') +m = importlib.util.module_from_spec(importlib.util.spec_from_loader('f', loader)); loader.exec_module(m) +print(len(m.load()))")" + echo 'not ron' > "$fav" + check_not "a file that isn't a RON list is left alone" "$F" add /mnt/x x + check_eq "...unchanged" "not ron" "$(cat "$fav")" + + step "davfs2's secret" + APP_PASSWORD='a"b\c d' + check "save_files_secret" save_files_secret + check_eq "only you can read it" 600 "$(stat -c %a "$HOME/.davfs2/secrets")" + check_eq "the app password reads back" 'a"b\c d' "$(files_app_password)" +} diff --git a/smoketest/scenarios/40-backup.sh b/smoketest/scenarios/40-backup.sh new file mode 100644 index 0000000..2aac7a9 --- /dev/null +++ b/smoketest/scenarios/40-backup.sh @@ -0,0 +1,45 @@ +# shellcheck shell=bash +# Scenarios set what the runner and items read +# shellcheck disable=SC2034 +DESCRIPTION="A backup with Ubuntu's restic and rclone to a local WebDAV server standing in for Nextcloud" +TIER=quick + +scenario() { + local served="$HOME/served" webdav="http://127.0.0.1:8080/remote.php/dav/files/jo" + step "Installing restic and rclone" + sudo apt-get update > /dev/null && sudo apt-get install -y restic rclone > /dev/null 2>&1 + check "restic and rclone are installed" pkg_installed restic rclone + echo "restic $(restic version | cut -d' ' -f2), $(rclone version | head -n 1)" + + # Nextcloud's WebDAV, and status.php, which the backup waits for + mkdir -p "$served/remote.php/dav/files/jo" + echo '{"installed":true,"maintenance":false}' > "$served/status.php" + rclone serve webdav "$served" --addr 127.0.0.1:8080 --user jo --pass app-password > "$HOME/serve.log" 2>&1 & + sleep 2 + + step "Setting up, as configure backup does" + mkdir -p "$CONF_DIR" + printf 'BACKUP_WEBDAV=%q\nBACKUP_USER=jo\nBACKUP_DIR=.backup-smoke\n' "$webdav" > "$CONF_DIR/backup.conf" + printf app-password | secret-tool store --label test federated-connector backup item nextcloud url "$webdav" + printf 'pass phrase' | secret-tool store --label test federated-connector backup item passphrase url "$webdav/.backup-smoke" + source "$CONNECTOR/system/backup-env.sh" + check_eq "restic uses rclone's WebDAV" "rclone::webdav:.backup-smoke" "$RESTIC_REPOSITORY" + check "the passphrase comes from the keyring" test -n "$RESTIC_PASSWORD_COMMAND" + check "rclone reaches the server with the app password" rclone lsf ":webdav:" + check "restic init" restic init + + step "A backup" + mkdir -p "$HOME/Documents" "$HOME/.cache/big" + echo "keep me" > "$HOME/Documents/note.txt" + echo "leave me out" > "$HOME/.cache/big/file" + check "system/backup" "$CONNECTOR/system/backup" + check_eq "there's one snapshot" 1 "$(restic snapshots --json | jq length)" + check "a file restores from it" restic restore latest --target "$HOME/restored" --include "$HOME/Documents" + check_eq "...as it was" "keep me" "$(cat "$HOME/restored$HOME/Documents/note.txt")" + check_not "caches are left out" bash -c "restic ls latest | grep -q '/.cache/big'" + check_not "the install is left out" bash -c "restic ls latest | grep -q '/.local/share/federated-connector/'" + + step "Without the passphrase in the keyring" + secret-tool clear federated-connector backup item passphrase url "$webdav/.backup-smoke" + check_not "system/backup fails" "$CONNECTOR/system/backup" +} diff --git a/smoketest/scenarios/50-sandbox.sh b/smoketest/scenarios/50-sandbox.sh new file mode 100644 index 0000000..9219ed8 --- /dev/null +++ b/smoketest/scenarios/50-sandbox.sh @@ -0,0 +1,48 @@ +# shellcheck shell=bash +# Scenarios set what the runner and items read +# shellcheck disable=SC2034 +DESCRIPTION="Node.js and srt download; a stand-in agent in the sandbox" +TIER=all +PRIVILEGED=1 + +scenario() { + local project="$HOME/Projects/demo" out + source "$CONNECTOR/configure.d/30-agents.sh" + sudo apt-get update > /dev/null && sudo apt-get install -y "${SANDBOX_PACKAGES[@]}" > /dev/null 2>&1 + check "bubblewrap works" bwrap_works + + step "Node.js and srt" + check_not "Ubuntu's Node.js, if any, isn't new enough or isn't there" node_ok + check "install_srt" install_srt + check "Node.js is in ~/.local/share/federated-connector/node" test -x "$FC_TOOLS/node/bin/node" + check "srt is found" srt_path + + step "A stand-in agent" + mkdir -p "$HOME/.local/bin" "$HOME/.ssh" "$project" + echo secret > "$HOME/.ssh/id_test" + cat > "$HOME/.local/bin/opencode" << 'AGENT' +#!/bin/bash +case "$1" in + read-ssh) cat ~/.ssh/id_test ;; + write-home) echo x > ~/outside ;; + write-here) echo x > ./inside ;; + fetch) curl -sf -o /dev/null --max-time 20 "$2" ;; +esac +AGENT + chmod +x "$HOME/.local/bin/opencode" + cd "$project" || return + check_not "it can't read ~/.ssh" "$SANDBOX_BIN/opencode" read-ssh + check_not "it can't write outside its project" "$SANDBOX_BIN/opencode" write-home + check "it can write in its project" "$SANDBOX_BIN/opencode" write-here + check "it reaches an allowed site" "$SANDBOX_BIN/opencode" fetch https://registry.npmjs.org/ + check_not "it doesn't reach others" "$SANDBOX_BIN/opencode" fetch https://example.com/ + check "unsandboxed runs it directly" "$SANDBOX_BIN/unsandboxed" opencode write-home + cd "$HOME" || return + out="$("$SANDBOX_BIN/opencode" write-here 2>&1)" + check "it won't start in your home folder" grep -q "Start opencode from a project directory" <<< "$out" + + step "Typing its name runs it in the sandbox" + check "put_on_path" put_on_path + check "on_path" on_path + check_eq "a new bash finds the sandboxed one first" "$SANDBOX_BIN/opencode" "$(bash -ic 'command -v opencode' < /dev/null 2> /dev/null)" +} diff --git a/smoketest/scenarios/60-packages.sh b/smoketest/scenarios/60-packages.sh new file mode 100644 index 0000000..5f88f34 --- /dev/null +++ b/smoketest/scenarios/60-packages.sh @@ -0,0 +1,43 @@ +# shellcheck shell=bash +# Scenarios set what the runner and items read +# shellcheck disable=SC2034 +DESCRIPTION="What configure expects of Ubuntu's packages: davfs2, sshfs, GTK's print backend, mise" +TIER=all + +scenario() { + sudo apt-get update > /dev/null + + step "davfs2, set up as configure core does" + echo "davfs2 davfs2/suid_file boolean true" | sudo debconf-set-selections + sudo apt-get install -y davfs2 > /dev/null 2>&1 + check "mount.davfs is setuid, so you can mount without sudo" test -u /usr/sbin/mount.davfs + check "the davfs2 group exists" getent group davfs2 + check "davfs2.conf names that group" grep -qE '^#?[[:space:]]*dav_group[[:space:]]+davfs2' /etc/davfs2/davfs2.conf + + step "davfs2 installed first, without setuid" + sudo apt-get purge -y davfs2 > /dev/null 2>&1 + echo "davfs2 davfs2/suid_file boolean false" | sudo debconf-set-selections + sudo apt-get install -y davfs2 > /dev/null 2>&1 + check_not "not setuid" test -u /usr/sbin/mount.davfs + source "$CONNECTOR/configure.d/10-core.sh" + check "davfs2_ready makes it setuid" davfs2_ready + check "...it is" test -u /usr/sbin/mount.davfs + + step "sshfs and SMB" + sudo apt-get install -y sshfs smbclient cifs-utils > /dev/null 2>&1 + check "fusermount3 is where the SFTP unit expects it" test -x /usr/bin/fusermount3 + check "smbclient lists shares with -g" bash -c "smbclient --help 2>&1 | grep -q -- '--grepable'" + + step "Printing" + sudo apt-get install -y libgtk-3-0t64 > /dev/null 2>&1 + check "GTK's CUPS backend is where setup-printers.sh looks" \ + compgen -G '/usr/lib/*/gtk-3.0/*/printbackends/libprintbackend-cups.so' + check "libnss-mdns is a package" apt-cache show libnss-mdns + + step "mise's apt repository" + source "$CONNECTOR/configure.d/40-languages.sh" + check "install_mise" install_mise + check "mise runs" mise --version + check "activate" activate + check "a new bash has mise" bash -ic 'command -v mise' < /dev/null +} diff --git a/system/backup b/system/backup new file mode 100755 index 0000000..c30e055 --- /dev/null +++ b/system/backup @@ -0,0 +1,104 @@ +#!/bin/bash +# +# Purpose : Back up your home folder with restic to your Nextcloud files, in +# .backup-<hostname>. Run daily by federated-connector-backup.timer; +# `configure backup` sets it up. +# +# Keeps 7 daily, 4 weekly and 6 monthly backups. To leave out more, list +# paths or patterns in ~/.config/federated-connector/backup-exclude, one per line. + +# Wrapped in { ...; exit; } so bash reads the whole script up front; update +# replaces this file while a backup may be running. +{ + +CONNECTOR="$(cd "$(dirname "$(realpath "$0")")/.." && pwd)" +USER_EXCLUDE="$HOME/.config/federated-connector/backup-exclude" +LOG_HINT="See: journalctl --user -u federated-connector-backup" + +# Tell the desktop when a backup fails, as no one watches the timer +fail() { + echo "$1" >&2 + notify-send --app-name="Federated Connector" --icon=dialog-error "Backup failed" "$1" 2> /dev/null + exit 1 +} + +source "$CONNECTOR/system/backup-env.sh" || exit 1 +[ -n "$RESTIC_REPOSITORY" ] || fail "Backups aren't set up. Run: configure backup" +[ -n "$RESTIC_PASSWORD_COMMAND" ] || fail "The backup's passphrase isn't in your keyring. Run: configure backup" + +# Run at login, perhaps before the network is up; give it a few minutes +for _ in {1..10}; do + curl -sf --max-time 10 -o /dev/null "${BACKUP_WEBDAV%%/remote.php/*}/status.php" && break + sleep 30 +done + +# Rebuilt by restic, or by reinstalling, so not worth the space +excludes=( + "$HOME/.cache" + "$HOME/.davfs2/cache" + "$HOME/.local/share/Trash" + "$HOME/.local/share/containers" + "$HOME/.local/share/flatpak" + "$HOME/.local/share/federated-connector" + "$HOME/.var/app/*/cache" + "$HOME/.nv" + # Package caches and tool installs + "$HOME/.npm" + "$HOME/.bun/install/cache" + "$HOME/.cargo/registry" + "$HOME/.cargo/git" + "$HOME/go/pkg" + "$HOME/.local/share/mise/installs" + "$HOME/.local/share/mise/downloads" + "$HOME/.local/share/uv" + "$HOME/.local/share/pipx" + "$HOME/.local/share/claude" + "$HOME/.local/share/nvim/lazy" + "$HOME/.local/share/nvim/mason" + # The agents' own installs and downloads; their settings, memories and + # sessions are kept + "$HOME/.hermes/hermes-agent" + "$HOME/.hermes/tools" + "$HOME/.hermes/installs" + "$HOME/.hermes/bin" + "$HOME/.hermes/cache" + "$HOME/.hermes/audio_cache" + "$HOME/.hermes/image_cache" + # LM Studio's models and engines can be downloaded again + "$HOME/.lmstudio/models" + "$HOME/.lmstudio/extensions" + "$HOME/.lmstudio/bin" + # Electron and Chromium apps (Element, browsers, editors) keep caches here + "$HOME/.config/*/Cache" + "$HOME/.config/**/Code Cache" + "$HOME/.config/**/GPUCache" + "$HOME/.config/**/GrShaderCache" + "$HOME/.config/**/GPUPersistentCache" + "$HOME/.config/**/DawnGraphiteCache" + "$HOME/.config/**/DawnWebGPUCache" + "$HOME/.config/**/Service Worker/CacheStorage" + # Element's search index for encrypted messages, which it rebuilds + "$HOME/.config/Element/EventStore" + # WinBoat's Windows VM: its disk is large, and changes whenever Windows runs + "$HOME/winboat" +) +exclude_args=(--exclude-caches) +for path in "${excludes[@]}"; do + exclude_args+=(--exclude "$path") +done +[ -f "$USER_EXCLUDE" ] && exclude_args+=(--exclude-file "$USER_EXCLUDE") + +echo "Backing up $HOME to $BACKUP_DIR in your Nextcloud files..." +# --one-file-system leaves out other mounts and btrfs subvolumes inside home +restic backup --one-file-system --host "$HOSTNAME" "${exclude_args[@]}" "$HOME" +status=$? +# 3 means some files couldn't be read; the rest were backed up +(( status == 0 || status == 3 )) || fail "restic couldn't back up $HOME (exit $status). $LOG_HINT" + +echo "Removing old backups..." +restic forget --host "$HOSTNAME" --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --prune \ + || fail "restic couldn't remove old backups. $LOG_HINT" + +echo "Backup finished." +exit 0 +} diff --git a/system/backup-env.sh b/system/backup-env.sh new file mode 100644 index 0000000..9eade70 --- /dev/null +++ b/system/backup-env.sh @@ -0,0 +1,44 @@ +#!/bin/bash +# +# Purpose : Point restic at your backup in your Nextcloud files. Sourced by +# system/backup and configure.d/20-backup.sh, and by you to look at +# or restore from a backup: +# +# source ~/.local/share/federated-connector/connector/system/backup-env.sh +# restic snapshots +# +# To use another computer's backup, name its folder: +# +# source ~/.local/share/federated-connector/connector/system/backup-env.sh .backup-<name> +# +# restic reaches Nextcloud over WebDAV through rclone, not the davfs2 mount, +# which can't safely replace files. The Nextcloud app password and the +# backup's passphrase are kept in your keyring. + +BACKUP_CONF="$HOME/.config/federated-connector/backup.conf" + +# A secret from the keyring: nextcloud (app password) or passphrase +backup_secret() { + secret-tool lookup federated-connector backup item "$1" url "$2" +} + +if [ -f "$BACKUP_CONF" ]; then + source "$BACKUP_CONF" + BACKUP_DIR="${1:-$BACKUP_DIR}" + + export RCLONE_WEBDAV_URL="$BACKUP_WEBDAV" + export RCLONE_WEBDAV_VENDOR=nextcloud + export RCLONE_WEBDAV_USER="$BACKUP_USER" + RCLONE_WEBDAV_PASS="$(backup_secret nextcloud "$BACKUP_WEBDAV" | rclone obscure -)" + export RCLONE_WEBDAV_PASS + export RESTIC_REPOSITORY="rclone::webdav:$BACKUP_DIR" + + # Without a passphrase in the keyring, e.g. for another computer's backup, + # restic asks for it + unset RESTIC_PASSWORD_COMMAND + if [ -n "$(backup_secret passphrase "$BACKUP_WEBDAV/$BACKUP_DIR")" ]; then + export RESTIC_PASSWORD_COMMAND="secret-tool lookup federated-connector backup item passphrase url $BACKUP_WEBDAV/$BACKUP_DIR" + fi +else + echo "Backups aren't set up. Run: configure backup" >&2 +fi diff --git a/system/email-watch b/system/email-watch new file mode 100755 index 0000000..e3991af --- /dev/null +++ b/system/email-watch @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +"""Pause a Core's email in Online Accounts when its password stops working. + +When your Core password changes (e.g. in Superpanel), email in Online Accounts +still has the old one. Online Accounts signs in with it each time the network +changes, and Evolution each time it fetches mail, and after a few wrong +passwords the mail server's fail2ban blocks this computer. + +Online Accounts doesn't reliably say when a mail server refuses a password: +3.50, which Pop!_OS 24.04 has, marks an account as needing attention for any +failure, including a server it can't reach, and 3.58 reports a refused mail +password as a general failure. It does say when Nextcloud refuses one, and Nextcloud +turns off its app passwords when your Core password changes. So when the +Core's Nextcloud in Online Accounts needs attention, this signs in to Nextcloud, +once, with the password email has (your Core password). If Nextcloud says it's +wrong, the mail server will too, so this pauses email +(configure.d/lib/goa-account pause): nothing signs in with the old password +again. It shows a notification; clicking it runs configure core, where "Your +Core password changed" saves the new password and ends the pause. It never +signs in to the mail server itself. + +Run by federated-connector-email-watch.service, which configure core installs. + +email-watch --check-password <email> checks the password email has with +Nextcloud, as above, for configure core's tests: it exits 0 if it works, 2 if +Nextcloud says it's wrong, 1 if it couldn't tell. +""" + +import base64 +import glob +import importlib.machinery +import importlib.util +import os +import subprocess +import sys +import threading +import urllib.error +import urllib.request + +import gi + +gi.require_version("Gio", "2.0") +from gi.repository import Gio, GLib # noqa: E402 + +CONNECTOR = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) +RUN_IN_TERMINAL = os.path.join(CONNECTOR, "system/run-in-terminal") +CORES = os.path.expanduser("~/.config/federated-connector/cores/*.conf") + + +def load_goa_account(): + # No __pycache__ in the installed copy, which update replaces + sys.dont_write_bytecode = True + path = os.path.join(CONNECTOR, "configure.d/lib/goa-account") + loader = importlib.machinery.SourceFileLoader("goa_account", path) + module = importlib.util.module_from_spec(importlib.util.spec_from_loader("goa_account", loader)) + loader.exec_module(module) + return module + + +goa = load_goa_account() + + +# Each Core's email and domain, from configure core's cores/<domain>.conf +def cores(): + found = {} + for conf in glob.glob(CORES): + result = subprocess.run( + ["bash", "-c", 'source "$1" && printf "%s\\n%s\\n" "$CORE_EMAIL" "$CORE_DOMAIN"', "-", conf], + capture_output=True, text=True) + lines = result.stdout.split("\n") + if result.returncode == 0 and len(lines) >= 2 and lines[0] and lines[1]: + found[lines[0]] = lines[1] + return found + + +def nextcloud_url(domain): + return f"https://nextcloud.{domain}" + + +# Sign in to the Core's Nextcloud with the password email has, the way +# configure core checks a password (configure.d/lib/nextcloud.sh). True if it +# works, False if Nextcloud says it's wrong, None if it couldn't tell. +def nextcloud_takes(email, domain, password): + user = email.rsplit("@", 1)[0] + auth = base64.b64encode(f"{user}:{password}".encode()).decode() + request = urllib.request.Request( + f"{nextcloud_url(domain)}/ocs/v2.php/cloud/user?format=json", + headers={"Authorization": f"Basic {auth}", "OCS-APIRequest": "true"}) + try: + with urllib.request.urlopen(request, timeout=15): + return True + except urllib.error.HTTPError as error: + return False if error.code == 401 else None + except OSError: + return None + + +def email_password(bus, email): + for _, account in goa.find_accounts(bus, "imap_smtp", email): + return goa.lookup_credentials("imap_smtp", account["Id"]).get("imap-password") + return None + + +def check_password(bus, email): + domain = cores().get(email) + if domain is None: + return None + password = email_password(bus, email) + if not password: + return None + return nextcloud_takes(email, domain, password) + + +# Waits for a click in its own thread, so the watching goes on meanwhile +def notify(email, domain, paused_now): + def run(): + if paused_now: + body = (f"Your Core password seems to have changed: {email} has the old one. " + "So the mail server doesn't block this computer for trying it, it's " + "paused. Click to enter your new password.") + else: + body = (f"{email} is paused because it has an old password. " + "Click to enter your new Core password.") + result = subprocess.run( + ["notify-send", "--wait", "--app-name=Federated Connector", "--icon=mail-unread", + "--action=default=Fix", "--action=fix=Enter new password", + f"Email for {domain} is paused", body], + capture_output=True, text=True) + if result.stdout.strip() in ("default", "fix"): + subprocess.run([RUN_IN_TERMINAL, "configure core"]) + + threading.Thread(target=run, daemon=True).start() + + +# Emails already dealt with since they started failing, so each is checked and +# notified about once until it works again +handled = set() + + +def check(bus): + try: + accounts = {(account.get("ProviderType"), account.get("PresentationIdentity")): account + for _, account in goa.accounts(bus)} + except GLib.Error: + return + for email, domain in cores().items(): + mail = accounts.get(("imap_smtp", email)) + if mail is None: + continue + nextcloud = accounts.get(("owncloud", f"{email.rsplit('@', 1)[0]}@nextcloud.{domain}")) + mail_failing = bool(mail.get("AttentionNeeded")) + nextcloud_failing = bool(nextcloud and nextcloud.get("AttentionNeeded")) + if not mail_failing and not nextcloud_failing: + handled.discard(email) + continue + if email in handled: + continue + + try: + if goa.paused(bus, "imap_smtp", email): + handled.add(email) + notify(email, domain, False) + continue + # Nextcloud may only have had an app password revoked, and email may + # still be marked from a pause whose new password hasn't been + # checked yet, so check the password email has before pausing it + password = email_password(bus, email) + if not password: + continue # e.g. the keyring is locked; try again later + works = nextcloud_takes(email, domain, password) + if works is None: + continue # try again when the network changes + if works: + handled.add(email) + continue + goa.pause(bus, "imap_smtp", email) + except (GLib.Error, LookupError): + continue + handled.add(email) + notify(email, domain, True) + + +def watch(): + bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) + pending = [] + + # Signals come in bursts; check once they've settled + def queue_check(*_): + if not pending: + pending.append(GLib.timeout_add_seconds(2, run_check)) + + def run_check(): + pending.clear() + check(bus) + return GLib.SOURCE_REMOVE + + account = "org.gnome.OnlineAccounts.Account" + bus.signal_subscribe(goa.BUS_NAME, "org.freedesktop.DBus.Properties", "PropertiesChanged", + None, account, Gio.DBusSignalFlags.NONE, queue_check) + bus.signal_subscribe(goa.BUS_NAME, "org.freedesktop.DBus.ObjectManager", "InterfacesAdded", + None, None, Gio.DBusSignalFlags.NONE, queue_check) + # Online Accounts checks every account when it starts, e.g. at login, and + # when the network changes + bus.signal_subscribe("org.freedesktop.DBus", "org.freedesktop.DBus", "NameOwnerChanged", + "/org/freedesktop/DBus", goa.BUS_NAME, Gio.DBusSignalFlags.NONE, queue_check) + Gio.NetworkMonitor.get_default().connect("network-changed", queue_check) + queue_check() + GLib.MainLoop().run() + + +def main(): + if len(sys.argv) == 3 and sys.argv[1] == "--check-password": + bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) + try: + works = check_password(bus, sys.argv[2]) + except (GLib.Error, LookupError): + works = None + return {True: 0, False: 2, None: 1}[works] + if len(sys.argv) == 1: + watch() + return 0 + print(__doc__.strip().split("\n\n")[-1], file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/system/run-in-terminal b/system/run-in-terminal new file mode 100755 index 0000000..3b268f8 --- /dev/null +++ b/system/run-in-terminal @@ -0,0 +1,27 @@ +#!/bin/bash +# +# Purpose : Run a command in a new terminal window, for notifications that +# start something when clicked (system/email-watch). +# +# run-in-terminal <command>, e.g. run-in-terminal "configure core" +# +# bash -i reads ~/.bashrc, as if you had typed the command yourself, and the +# window stays open to show how it went. + +run=(bash -ic "$1; echo; read -rp \"Press Enter to close this window.\"") +if command -v cosmic-term &> /dev/null; then + terminal=(cosmic-term -e) +elif command -v xdg-terminal-exec &> /dev/null; then + terminal=(xdg-terminal-exec) +elif command -v gnome-terminal &> /dev/null; then + terminal=(gnome-terminal --) +elif command -v x-terminal-emulator &> /dev/null; then + terminal=(x-terminal-emulator -e) +else + notify-send --app-name="Federated Connector" "No terminal found" "Open a terminal and run $1." + exit 1 +fi + +# Run the terminal as its own unit: when the service that called this exits, +# systemd stops everything still running in it, which would close the terminal +exec systemd-run --user --quiet --collect -- "${terminal[@]}" "${run[@]}" diff --git a/system/setup-printers.sh b/system/setup-printers.sh new file mode 100755 index 0000000..53be9c6 --- /dev/null +++ b/system/setup-printers.sh @@ -0,0 +1,406 @@ +#!/usr/bin/env bash +# +# Purpose : Find the printers on the network and add them as permanent CUPS +# queues, so they show up in every print dialog. `configure printers` +# runs this; run it yourself for the options below (--help). +# +# Printers announce themselves over mDNS, and CUPS prints to them through +# temporary queues that only exist while in use. Chromium browsers list +# those, but the GTK print dialog ("Print using system dialog...") often lists +# only permanent queues, so a printer can show up in the browser but not +# there. `lpstat -v` then says "No +# destinations added" while `lpstat -e` lists the printers. A permanent queue +# made with `lpadmin -m everywhere` (driverless IPP Everywhere) fixes that. + +set -euo pipefail + +CONNECTOR="$(cd "$(dirname "$(realpath "${BASH_SOURCE[0]}")")/.." && pwd)" +source "$CONNECTOR/configure.d/lib/mdns.sh" + +TEST_PAGE=/usr/share/cups/data/default-testpage.pdf + +usage() { + cat << 'EOF' +Usage: setup-printers.sh [options] + +Finds the printers on your network and adds the ones you choose as permanent +CUPS queues, so they show up in every print dialog. + + --all Add every printer found, without asking (a printer another + computer shares is left out when it can be reached directly) + --default NAME Make queue NAME the default printer afterwards + --dry-run Show the commands that would change the system; run none + --no-deps Don't install packages or turn on services + --test-page Print a test page on each queue added + -h, --help Show this help + +If a printer is still missing from a print dialog: + - Quit the app completely (browsers especially) and open it again; print + dialogs read the list of printers when they start. + - GTK needs its CUPS print backend: + ls /usr/lib/*/gtk-3.0/*/printbackends /usr/lib/*/gtk-4.0/*/printbackends + If only the "file" backend is there: sudo apt install --reinstall libgtk-3-0t64 + - Flatpak apps print through the portal (xdg-desktop-portal); the app may + also need: flatpak override --user --socket=cups <app id> + - $CUPS_SERVER or ~/.cups/client.conf can point apps at another CUPS server + than this computer's. + - To see what the dialog does: GTK_DEBUG=printing <app>, while watching + journalctl -fu cups + - cups-browsed can add queues for the printers it finds by itself, instead + of this script; this one adds only the queues you choose. +EOF +} + +DRY_RUN=false ALL=false NO_DEPS=false PRINT_TEST=false DEFAULT="" +while [ $# -gt 0 ]; do + case "$1" in + --all) ALL=true ;; + --default) + [ $# -ge 2 ] || { echo "--default needs a queue name." >&2; exit 2; } + DEFAULT="$2" + shift ;; + --dry-run) DRY_RUN=true ;; + --no-deps) NO_DEPS=true ;; + --test-page) PRINT_TEST=true ;; + -h|--help) usage; exit 0 ;; + *) echo "Unknown option: $1 (see --help)" >&2; exit 2 ;; + esac + shift +done + +# Run a command that changes the system, or with --dry-run only show it +run() { + if $DRY_RUN; then + printf ' would run:' + printf ' %q' "$@" + echo + else + "$@" + fi +} + +# --- Step 1: packages and services ------------------------------------------ + +setup_dependencies() { + local pkg service line new backup missing=() stopped=() + + for pkg in cups avahi-daemon avahi-utils libnss-mdns; do + [ "$(dpkg-query -W -f '${db:Status-Status}' "$pkg" 2> /dev/null)" = installed ] || missing+=("$pkg") + done + if [ ${#missing[@]} -gt 0 ]; then + echo "Installing ${missing[*]}..." + run sudo apt-get install -y "${missing[@]}" + fi + + for service in cups.service avahi-daemon.service; do + if ! systemctl is-enabled -q "$service" 2> /dev/null || ! systemctl is-active -q "$service"; then + stopped+=("$service") + fi + done + if [ ${#stopped[@]} -gt 0 ]; then + echo "Turning on ${stopped[*]}..." + run sudo systemctl enable --now "${stopped[@]}" + fi + + # Without mdns_minimal (Ubuntu's libnss-mdns adds mdns4_minimal, IPv4 + # only), the .local names in printers' addresses don't resolve + line="$(grep -m1 '^hosts:' /etc/nsswitch.conf || true)" + if [[ "$line" != *"mdns_minimal [NOTFOUND=return]"* && "$line" != *"mdns4_minimal [NOTFOUND=return]"* ]]; then + if [[ "$line" == *" resolve"* ]]; then + new="${line/ resolve/ mdns_minimal [NOTFOUND=return] resolve}" + elif [[ "$line" == *" dns"* ]]; then + new="${line/ dns/ mdns_minimal [NOTFOUND=return] dns}" + else + new="${line:-hosts:} mdns_minimal [NOTFOUND=return]" + fi + backup="/etc/nsswitch.conf.bak.$(date +%Y%m%d%H%M%S)" + echo "Letting .local names resolve, in /etc/nsswitch.conf (a copy is kept in $backup):" + echo " before: $line" + echo " after: $new" + run sudo cp -p /etc/nsswitch.conf "$backup" + if [ -n "$line" ]; then + run sudo sed -i "s|^hosts:.*|$new|" /etc/nsswitch.conf + else + echo "$new" | run sudo tee -a /etc/nsswitch.conf > /dev/null + fi + fi +} + +$NO_DEPS || setup_dependencies + +if ! LC_ALL=C lpstat -r 2> /dev/null | grep -q "scheduler is running"; then + echo "CUPS isn't running, so printers can't be found or added." >&2 + echo "Start it with: sudo systemctl enable --now cups.service" >&2 + exit 1 +fi + +# --- Step 2: find printers ---------------------------------------------------- + +# %20 -> space, %40 -> @ and any other percent escape +url_decode() { + local s="${1//\\/\\\\}" + printf '%b' "${s//%/\\x}" +} + +# Printers can take a few seconds to answer +echo "Looking for printers..." +found="" +for attempt in 1 2 3; do + found="$(LC_ALL=C lpinfo --include-schemes dnssd -v 2> /dev/null | grep '^network dnssd://' || true)" + [ -n "$found" ] && break + [ "$attempt" -lt 3 ] && sleep 3 +done +if [ -z "$found" ]; then + echo "No printers found on the network. Is the printer on, and on the same network?" + exit 0 +fi + +# What Avahi knows about each printer, by name: its host, address, port and +# path, for spotting queues that already reach it and for the ipp:// fallback +declare -A AVAHI_HOST=() AVAHI_ADDR=() AVAHI_PORT=() AVAHI_RP=() +while IFS='|' read -r name _ host address port txt; do + [ -n "$name" ] || continue + AVAHI_HOST["$name"]="$host" AVAHI_ADDR["$name"]="$address" AVAHI_PORT["$name"]="$port" + if [[ "$txt" =~ \"rp=([^\"]*)\" ]]; then + AVAHI_RP["$name"]="${BASH_REMATCH[1]}" + fi +done < <(mdns_services _ipp._tcp || true) + +# One entry per printer found: P_NAME is its name as shown, P_BASE the name +# without the "@ host" of a shared printer, P_SHARER that host +P_NAME=() P_BASE=() P_URI=() P_SHARER=() +dnssd='^dnssd://([^/]+)\._ipps?\._tcp\.[^/]*(/[^?]*)' +while read -r _ uri; do + [[ "$uri" =~ $dnssd ]] || continue + name="$(url_decode "${BASH_REMATCH[1]}")" + path="${BASH_REMATCH[2]}" + sharer="" + # Another computer's CUPS shares it, as "<printer> @ <computer>" + if [[ "$path" == /cups* && "$name" == *" @ "* ]]; then + sharer="${name##* @ }" + fi + P_NAME+=("$name") P_BASE+=("${name% @ *}") P_URI+=("$uri") P_SHARER+=("$sharer") +done <<< "$found" +[ "${#P_NAME[@]}" -gt 0 ] || { echo "No printers found on the network."; exit 0; } + +# A shared printer that can also be reached directly: the direct one is used, +# so printing doesn't depend on the other computer being on +P_DUP=() +for i in "${!P_NAME[@]}"; do + P_DUP[i]="" + [ -n "${P_SHARER[i]}" ] || continue + for j in "${!P_NAME[@]}"; do + if [ -z "${P_SHARER[j]}" ] && [ "${P_NAME[j]}" = "${P_BASE[i]}" ]; then + P_DUP[i]="$j" + fi + done +done + +# --- Step 3: queue names ------------------------------------------------------ + +# The queues there are now: name -> device URI +declare -A QUEUE_URI=() +while read -r _ _ queue uri; do + QUEUE_URI["${queue%:}"]="$uri" +done < <(LC_ALL=C lpstat -v 2> /dev/null | grep '^device for ' || true) + +lower() { + tr '[:upper:]' '[:lower:]' <<< "${1%.}" +} + +# The queue that already prints to printer $1, if any: one with the same URI, +# or one made some other way (e.g. cups-browsed or system-config-printer) that reaches the same host +# and path, like ipp://NPI3BE90A.local:631/ipp/print +existing_queue() { + local i="$1" name="${P_NAME[$1]}" queue uri host rp + host="$(lower "${AVAHI_HOST[$name]:-}")" + rp="${AVAHI_RP[$name]:-}" + for queue in "${!QUEUE_URI[@]}"; do + uri="${QUEUE_URI[$queue]}" + if [ "$uri" = "${P_URI[i]}" ]; then + echo "$queue" + return 0 + fi + if [ -n "$host" ] && [[ "$uri" =~ ^ipps?://([^/:]+)(:[0-9]+)?/(.*)$ ]]; then + local uri_host uri_path="${BASH_REMATCH[3]}" + uri_host="$(lower "${BASH_REMATCH[1]}")" + if { [ "$uri_host" = "$host" ] || [ "$uri_host" = "${AVAHI_ADDR[$name]:-}" ]; } \ + && [ "$uri_path" = "$rp" ]; then + echo "$queue" + return 0 + fi + fi + done + return 1 +} + +# "HP LaserJet MFP M234dw (3BE90A) @ lab" -> HP_LaserJet_MFP_M234dw_3BE90A_lab +queue_name() { + local q="${1// @ /_}" + q="$(sed -E 's/[^A-Za-z0-9_-]/_/g; s/_+/_/g; s/^_+//; s/_+$//' <<< "$q")" + echo "${q:0:127}" +} + +# A name no other queue has, adding _2, _3... if needed +declare -A TAKEN=() +for queue in "${!QUEUE_URI[@]}"; do TAKEN["$queue"]=1; done +unique_queue_name() { + local base n=2 name + base="$(queue_name "$1")" + name="$base" + while [ -n "${TAKEN[$name]:-}" ]; do + name="${base:0:120}_$n" + n=$((n + 1)) + done + TAKEN["$name"]=1 + echo "$name" +} + +P_EXISTING=() +for i in "${!P_NAME[@]}"; do + P_EXISTING[i]="$(existing_queue "$i" || true)" +done + +# --- Choose --------------------------------------------------------------------- + +# Chosen unless told otherwise: printers without a queue that aren't a shared +# copy of a direct one +defaults=() +for i in "${!P_NAME[@]}"; do + if [ -z "${P_EXISTING[i]}" ] && [ -z "${P_DUP[i]}" ]; then + defaults+=("$((i + 1))") + fi +done + +echo +echo "Printers on your network:" +for i in "${!P_NAME[@]}"; do + if [ -n "${P_SHARER[i]}" ]; then how="shared by ${P_SHARER[i]}"; else how="direct"; fi + note="" + if [ -n "${P_EXISTING[i]}" ]; then + note="already set up as ${P_EXISTING[i]}" + elif [ -n "${P_DUP[i]}" ]; then + note="same printer as $((P_DUP[i] + 1)), reached directly" + fi + printf ' %2d) %-46s %-20s %s\n' "$((i + 1))" "${P_NAME[i]}" "$how" "$note" +done +echo + +chosen=() +if $ALL; then + chosen=("${defaults[@]}") +else + answer="" + if [ ${#defaults[@]} -gt 0 ]; then + read -rp "Add which printers? Numbers separated by spaces [${defaults[*]}], or n for none: " answer || answer=n + answer="${answer:-${defaults[*]}}" + else + read -rp "Every printer is already set up. Add one anyway? Number, or Enter for none: " answer || answer="" + fi + for n in ${answer//,/ }; do + [[ "$n" == [nN]* ]] && { chosen=(); break; } + if [[ "$n" =~ ^[0-9]+$ ]] && (( n >= 1 && n <= ${#P_NAME[@]} )); then + chosen+=("$n") + else + echo "Skipping \"$n\": not a number from the list." + fi + done +fi + +# --- Step 4: add queues --------------------------------------------------------- + +ADDED=() SKIPPED=() FAILED=() + +add_queue() { + local i="$1" name="${P_NAME[$1]}" queue out fallback="" + if [ -n "${P_EXISTING[i]}" ]; then + SKIPPED+=("$name (already set up as ${P_EXISTING[i]})") + return 0 + fi + queue="$(unique_queue_name "$name")" + echo "Adding $name as $queue..." + if $DRY_RUN; then + run sudo lpadmin -p "$queue" -E -v "${P_URI[i]}" -m everywhere + ADDED+=("$queue") + return 0 + fi + + # lpadmin warns that printer drivers are deprecated; only its status counts + if out="$(sudo lpadmin -p "$queue" -E -v "${P_URI[i]}" -m everywhere 2>&1)"; then + ADDED+=("$queue") + return 0 + fi + + # The printer's address and path from Avahi instead of its mDNS name + if [ -n "${AVAHI_ADDR[$name]:-}" ]; then + fallback="ipp://${AVAHI_ADDR[$name]}:${AVAHI_PORT[$name]:-631}/${AVAHI_RP[$name]:-ipp/print}" + echo " That didn't work; trying $fallback" + if out="$(sudo lpadmin -p "$queue" -E -v "$fallback" -m everywhere 2>&1)"; then + ADDED+=("$queue") + return 0 + fi + fi + unset 'TAKEN[$queue]' + FAILED+=("$name: $(tail -n1 <<< "$out")") +} + +for n in "${chosen[@]}"; do + add_queue "$((n - 1))" +done + +# --- Step 5: default, check and summary --------------------------------------- + +if [ -z "$DEFAULT" ] && ! $ALL && ! $DRY_RUN && [ ${#ADDED[@]} -gt 0 ]; then + current="$(LC_ALL=C lpstat -d 2> /dev/null | sed -n 's/^system default destination: //p')" + read -rp "Make one of the new printers the default? ${ADDED[*]} (Enter to leave it${current:+ as $current}): " DEFAULT || DEFAULT="" +fi +if [ -n "$DEFAULT" ]; then + if [ -n "${QUEUE_URI[$DEFAULT]:-}" ] || [[ " ${ADDED[*]} " == *" $DEFAULT "* ]]; then + run sudo lpadmin -d "$DEFAULT" + else + FAILED+=("default printer: there's no queue named $DEFAULT") + DEFAULT="" + fi +fi + +if ! $DRY_RUN; then + ready=() + for queue in "${ADDED[@]}"; do + if LC_ALL=C lpstat -a "$queue" 2> /dev/null | grep -q "accepting requests"; then + ready+=("$queue") + if $PRINT_TEST; then + lp -d "$queue" "$TEST_PAGE" > /dev/null || FAILED+=("$queue: the test page wasn't sent") + fi + else + FAILED+=("$queue: added, but it isn't accepting jobs (see lpstat -t)") + fi + done + ADDED=("${ready[@]}") +fi + +echo +if $DRY_RUN; then echo "Would add:"; else echo "Added:"; fi +[ ${#ADDED[@]} -gt 0 ] && printf ' %s\n' "${ADDED[@]}" || echo " none" +if [ ${#SKIPPED[@]} -gt 0 ]; then + echo "Skipped:" + printf ' %s\n' "${SKIPPED[@]}" +fi +if [ ${#FAILED[@]} -gt 0 ]; then + echo "Failed:" + printf ' %s\n' "${FAILED[@]}" + echo "A printer that can't be added without a driver needs its maker's: hplip for HP," + echo "printer-driver-brlaser for Brother lasers. This script doesn't install drivers." +fi +[ -n "$DEFAULT" ] && echo "Default printer: $DEFAULT" +if [ ${#ADDED[@]} -gt 0 ] && ! $DRY_RUN; then + $PRINT_TEST && echo "A test page was sent to each new printer." + echo "Quit and reopen apps that are open (browsers especially) to see the new printers." +fi + +# Without its CUPS backend, the GTK dialog can't list printers at all +if compgen -G '/usr/lib/*/gtk-3.0/*/printbackends' > /dev/null \ + && ! compgen -G '/usr/lib/*/gtk-3.0/*/printbackends/libprintbackend-cups.so' > /dev/null; then + echo "GTK's CUPS print backend is missing; reinstall it: sudo apt install --reinstall libgtk-3-0t64" +fi + +[ ${#FAILED[@]} -eq 0 ] diff --git a/system/sftp-mount b/system/sftp-mount new file mode 100755 index 0000000..e0fe090 --- /dev/null +++ b/system/sftp-mount @@ -0,0 +1,34 @@ +#!/bin/bash +# +# Purpose : Mount a folder from another machine over SFTP (sshfs) and stay in +# the foreground until it's unmounted. A systemd user service that +# `configure storage` writes runs it at login. +# +# It runs as you, not root, so it can use your SSH keys: Bitwarden's SSH agent +# while Bitwarden is running it, otherwise the keyring's, which Pop!_OS starts +# with your session. It never asks for a password, so the server has to +# accept one of those keys. +# +# Usage: sftp-mount <user@host:path> <mount point> + +if [ $# -ne 2 ]; then + echo "Usage: sftp-mount <user@host:path> <mount point>" >&2 + exit 2 +fi + +if [ -S "$HOME/.bitwarden-ssh-agent.sock" ]; then + export SSH_AUTH_SOCK="$HOME/.bitwarden-ssh-agent.sock" +elif [ -S "${XDG_RUNTIME_DIR:-/run/user/$UID}/keyring/ssh" ]; then + export SSH_AUTH_SOCK="${XDG_RUNTIME_DIR:-/run/user/$UID}/keyring/ssh" +elif [ -S "${XDG_RUNTIME_DIR:-/run/user/$UID}/gcr/ssh" ]; then + export SSH_AUTH_SOCK="${XDG_RUNTIME_DIR:-/run/user/$UID}/gcr/ssh" +fi + +# A mount left behind by a crash would make sshfs fail +mountpoint -q "$2" && fusermount3 -u "$2" + +# reconnect and ServerAlive* bring it back after the network drops (e.g. +# suspend); idmap=user shows your files on the server as yours here +exec sshfs -f "$1" "$2" \ + -o reconnect,ServerAliveInterval=15,ServerAliveCountMax=3 \ + -o BatchMode=yes,ConnectTimeout=15,idmap=user diff --git a/system/systemd/federated-connector-backup.service b/system/systemd/federated-connector-backup.service new file mode 100644 index 0000000..0a2f3ae --- /dev/null +++ b/system/systemd/federated-connector-backup.service @@ -0,0 +1,9 @@ +[Unit] +Description=Back up your home folder to your Nextcloud files + +[Service] +Type=oneshot +ExecStart=%h/.local/share/federated-connector/connector/system/backup +# Stay out of the way of whatever you're doing +Nice=19 +IOSchedulingClass=idle diff --git a/system/systemd/federated-connector-backup.timer b/system/systemd/federated-connector-backup.timer new file mode 100644 index 0000000..153cc52 --- /dev/null +++ b/system/systemd/federated-connector-backup.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Back up your home folder daily + +[Timer] +OnCalendar=daily +RandomizedDelaySec=1h +# Catch up at the next login if the computer was off or you weren't logged in +Persistent=true + +[Install] +WantedBy=timers.target diff --git a/system/systemd/federated-connector-email-watch.service b/system/systemd/federated-connector-email-watch.service new file mode 100644 index 0000000..e2b8e8d --- /dev/null +++ b/system/systemd/federated-connector-email-watch.service @@ -0,0 +1,14 @@ +[Unit] +Description=Pause a Core's email when the mail server stops taking its password +PartOf=graphical-session.target +After=graphical-session.target +# Only for those who've set up a Core (configure core starts it then) +ConditionPathExistsGlob=%h/.config/federated-connector/cores/*.conf + +[Service] +ExecStart=%h/.local/share/federated-connector/connector/system/email-watch +Restart=on-failure +RestartSec=30 + +[Install] +WantedBy=graphical-session.target diff --git a/update b/update new file mode 100755 index 0000000..3b70649 --- /dev/null +++ b/update @@ -0,0 +1,42 @@ +#!/bin/bash +# +# Purpose : Update Federated Connector to the latest version on Gitea. +# +# Usage: update Update, showing what changed +# update --version Show the version installed +# +# The installer does the work (install.sh --update): it downloads the new +# version and swaps it in, so the services keep pointing at the same place. +# Your settings, accounts, keyring items and downloaded tools are left as they +# are. Pop!_OS' own updates (COSMIC Store, or apt) update everything else, +# including what configure installed from apt. + +# Wrapped in { ...; exit; } so bash reads the whole script up front; the +# update replaces this file while it runs. +{ + +CONNECTOR="$(cd "$(dirname "$(realpath "$0")")" && pwd)" + +case "$1" in + --version|-v) + echo "Federated Connector $(cut -c1-7 "$CONNECTOR/.version" 2> /dev/null || echo "(not installed with install.sh)")" + exit 0 ;; + -h|--help) + sed -n '4,6p' "$(realpath "$0")" | sed 's/^# \{0,1\}//' + exit 0 ;; +esac + +if [ ! -f "$CONNECTOR/.version" ]; then + echo "This copy wasn't installed with install.sh, so update can't replace it. Install with:" + echo " curl -fsSL https://gitea.federated.computer/Federated_Computer/connector-popos/raw/branch/main/install.sh | bash" + exit 1 +fi + +# Run from a copy: the update replaces install.sh along with everything else +copy="$(mktemp)" || exit 1 +cp "$CONNECTOR/install.sh" "$copy" || exit 1 +bash "$copy" --update +status=$? +rm -f "$copy" +exit $status +}