commit 08e6b2ee4f755fe8b6d4b80a7cb688c8fecb9e51 Author: David Young Date: Wed Nov 11 08:34:42 2026 -0700 Set up a Mac for a Federated Core, like CoreDesktop's configure A macOS counterpart of CoreDesktop's configure, with the same drop-in items in configure.d/: - core: Mail, Calendar and Contacts through a configuration profile, Superpanel as an app, Nextcloud files through the Nextcloud app, and Element; with test-and-fix, password change and removal - tailscale: join the Core's network through headscale - backup: restic to Nextcloud through rclone, run by launchd through an app that can be given Full Disk Access - storage: SMB shares mounted the way Finder does, again at login and on network changes - agents, claude, opencode, hermes, sandbox: install the agents and run them in Anthropic's sandbox runtime (Seatbelt on macOS) - ai-servers: LLM servers on this Mac or the network, for the agents Apps and tools macOS lacks are offered for download, checked against their makers' Team IDs and notarization, or published SHA-256 sums. Everything runs on macOS' bash 3.2 with only built-in tools. smoketest/ runs scenarios in fresh macOS VMs with Tart. Co-Authored-By: Claude Opus 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..60601e6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.claude/ +smoketest/results/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..8423f40 --- /dev/null +++ b/README.md @@ -0,0 +1,140 @@ +# Federated Connector for macOS + +Sets up a Mac for your Federated Core, using the apps macOS comes with: Mail, Calendar and Contacts. It's the macOS counterpart of [CoreDesktop](https://gitea.federated.computer/Federated_Computer/coredesktop)'s `configure`, and works the same way: it shows what's set up, sets up the rest, and can test and fix a Core later. + +## Requirements + +- macOS 13 (Ventura) or later, on Apple silicon or Intel. +- Nothing else. It runs with the bash macOS comes with and only uses tools that are part of macOS. It doesn't need Homebrew, jq, python or the Command Line Tools. + +## 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 +``` + +To run it as just `configure`, link it into a directory on your PATH, e.g. `ln -s "$PWD/configure" /usr/local/bin/configure`. + +## What it sets up + +- **Your Federated Core.** Give it your Superpanel's address (e.g. https://superpanel.example.com), your Core email, name and password. It sets up: + - **Mail, Calendar and Contacts.** It makes one configuration profile with your email account (IMAP and SMTP, with the settings your mail server publishes) and your Nextcloud calendars (CalDAV) and address books (CardDAV). This is how macOS itself sets up these accounts. macOS doesn't let scripts install profiles, so `configure` opens the profile and System Settings, and you double-click "Federated Core (example.com)" under Downloaded and choose Install. To take the accounts off this Mac, remove the profile. + - Mail keeps your Core password, because the mail server doesn't take Nextcloud app passwords. + - Calendar and Contacts use a Nextcloud app password, named "macOS Calendar and Contacts on {your Mac}", which you can revoke in Nextcloud under Settings > Security. A copy is kept in your login keychain, so the profile can be made again without a new app password. + - **Superpanel** as an app in ~/Applications (so it's in Launchpad and Spotlight) that opens Superpanel in your browser. + - **Your Nextcloud files**, kept in sync by the Nextcloud app. It opens with your Core's address filled in, and you sign in in your browser. + - **Element**, pointed at your Core's Matrix server, for your main Core. + + You can add more Cores: run `configure core` again and choose "Add a Core". Each Core gets its own profile, Superpanel and app password. Element, Tailscale and backups use your main Core (the first one, unless you choose another). + + `configure core` also offers: + - **Test a Core**: it checks each part against the Core and offers to fix what doesn't work. + - **Your Core password changed**: signing in with the new password turns Calendar's, Contacts' and the Nextcloud app's app passwords back on (Nextcloud turns them off when your password changes). Mail then gets the new password in a new version of the profile, which replaces the old one and keeps your mail. + - **Remove a Core**: it removes the profile, revokes the app password and deletes the Superpanel app. Everything on the Core itself stays as it is. +- **Tailscale**: joins this Mac to your Core's Tailscale network through headscale.example.com. To leave it, run `configure tailscale` again. +- **Backup**: backs up your home folder daily to your Nextcloud files, in a `.backup-{this Mac's name}` folder, with restic. + - The backup is encrypted with a passphrase that `configure` shows you once. Save it somewhere other than this Mac, such as Bitwarden. + - It keeps 7 daily, 4 weekly and 6 monthly backups. It leaves out caches, things that can be downloaded again, VM disks, and files already in the cloud (iCloud Drive, your Nextcloud folder). To leave out more, list paths in `~/Library/Application Support/Federated Connector/backup-exclude`, one per line. + - restic reaches Nextcloud directly through rclone, with its own Nextcloud app password ("Federated Backup on {your Mac}"). + - launchd starts it hourly and at login, and it backs up once a day, so a Mac that was asleep or off catches up soon after. It's started through a small app, "Federated Backup" in ~/Applications, because macOS only lets apps into Desktop, Documents, Mail and Photos once you give them Full Disk Access. `configure` opens the right place in System Settings and checks that it worked. Without it, backups leave those folders out and you get a notification each time. + - The log is `~/Library/Logs/Federated Connector/backup.log`. Run `configure backup` again to back up now or to turn backups off; turning them off also offers to delete the backups. + - To restore, see "Restoring from a backup" below. +- **Network storage**: shared folders (SMB) from Windows PCs, NAS boxes and Macs with File Sharing on. It finds them on your network, or you enter an address (`smb://nas.local/files`; leave out the share to choose from a list). macOS mounts them in /Volumes and shows them in Finder's sidebar, and its sign-in window can keep the password in your keychain. A launchd job mounts them again at login and when the network changes, skipping servers it can't reach. Folders over SSH (SFTP) need macFUSE, which this doesn't set up. +- **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. +- **Agent sandbox**: iCloud Drive and other cloud drives' files are hidden from agents. Reading a file macOS keeps only in the cloud downloads it. To let agents read one of these, switch it here. +- **AI servers**: LLM servers on this Mac or your network, such as Ollama or LM Studio. It finds the machines on your network over Bonjour and asks each one on the ports LLM servers use (11434 Ollama, 1234 LM Studio, 8080 llama.cpp, 8000 vLLM); or you enter an 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, and lets the commands Claude Code runs reach it too. A server on another machine 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". + +## Sandboxed AI agents + +opencode and Hermes run in Anthropic's sandbox runtime (srt), which on macOS uses Seatbelt, the same mechanism macOS uses to sandbox its own apps. 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, keychains, password managers, browser profiles, Mail, Messages, Calendar and Contacts data, Signal, 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 Homebrew + +Typing `opencode`, `hermes` or `hermes-agent` runs it in the sandbox: `configure agents` adds a line at the end of ~/.zshrc and ~/.bash_profile that puts `sandbox/bin` first on PATH. To run one without the sandbox, type `unsandboxed opencode`. Claude Code uses its own built-in sandbox for every command it runs, which `configure agents` turns on (see `/sandbox` inside Claude). + +srt needs Node.js 22.12 or later. If this Mac doesn't have it, `configure agents` downloads Node.js and srt into `~/.local/share/federated-connector` and uses them only for the sandbox. + +To allow more, put a file in the same format as `sandbox/config/base.json` in `~/Library/Application Support/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. + +## Restoring from a backup + +To see the backups and get files back: + +``` +source system/backup-env.sh +restic snapshots +restic restore latest --target ~/restored --include ~/Documents +``` + +On a new Mac, run `configure core` and `configure backup` first. Then name the old Mac's folder, and restic asks for the passphrase you saved: + +``` +source system/backup-env.sh .backup-{old Mac's name} +restic snapshots +``` + +## Apps it downloads + +If an app a step needs isn't on this Mac, `configure` offers to download and install it from its maker: + +| App | For | From | Team ID | +|-----------|-------------------------|-------------------------------------------|--------------| +| Nextcloud | Your files | github.com/nextcloud-releases/desktop | `NKUJUXUJ3B` | +| Element | Your Core's chat | packages.element.io | `7J4U792NQT` | +| Tailscale | Your Core's network | pkgs.tailscale.com | `W5364U7YZB` | + +An app is installed only if it's signed with its maker's Developer ID (the Team ID above) and Gatekeeper accepts it, which means Apple notarized it. The apps update themselves after that. Installing a .pkg (Nextcloud, Tailscale) asks for your Mac password. + +Command-line tools are used as they are if they're already installed (e.g. with Homebrew). Otherwise they're downloaded into `~/.local/share/federated-connector`, and each download is checked against the SHA-256 checksums its release publishes: + +| Tool | For | From | +|---------|--------------------------------------|-------------------------| +| restic | Backups | github.com/restic | +| rclone | Backups (reaching Nextcloud) | downloads.rclone.org | +| Node.js | Running the sandbox | nodejs.org (current LTS)| +| srt | The agent sandbox | npm (@anthropic-ai/sandbox-runtime) | + +The agents are installed with their makers' own installers: claude.ai/install.sh, opencode.ai/install and hermes-agent.nousresearch.com/install.sh. Each installer is downloaded first and then run, rather than piped straight into bash. + +## Where things are + +- Your answers: `~/Library/Application Support/Federated Connector/` (`cores/.conf`, `core.conf` for the main Core, `tailscale.conf`, `backup.conf`, `storage`, `ai-servers`, and your own `sandbox/` config) +- App passwords and the backup passphrase: login keychain, services "Federated Connector" and "federated-connector-backup" +- Background jobs: `~/Library/LaunchAgents/computer.federated.connector.{backup,storage}.plist` +- Downloaded tools: `~/.local/share/federated-connector` +- The accounts: System Settings > Privacy & Security > Profiles (General > Device Management on some versions) + +## 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. Libraries are in `configure.d/lib/`: + +- `json.sh`: JSON through JavaScript for Automation +- `keychain.sh`: secrets in the login keychain +- `nextcloud.sh`: app passwords +- `apps.sh`: downloading and checking apps +- `tools.sh`: downloading and checking command-line tools +- `profile.sh`: configuration profiles +- `mdns.sh`: finding things on the network with dns-sd +- `smb.sh`: SMB shares +- `agents.sh`: the agents' real commands and srt + +`system/` has what runs in the background (`backup`, `storage-mount`), and `sandbox/` has the sandbox wrapper and its config. + +Keep to bash 3.2: no `mapfile`, `read -i`, associative arrays or `${var,,}`. + +## Testing + +`smoketest/run` runs the scenarios in `smoketest/`, each in a fresh macOS VM, with Tart on an Apple silicon Mac. See [smoketest/README.md](smoketest/README.md). + +## Differences from CoreDesktop + +- Mail, Calendar and Contacts come from a configuration profile, not GNOME Online Accounts. macOS asks you to approve the profile. +- Files sync through the Nextcloud app rather than a davfs2 mount. +- Backups and network storage run from launchd rather than systemd. Backups need Full Disk Access (see above), and network storage uses macOS' own SMB mounting and keychain rather than /etc/fstab. +- Network storage is SMB only; SFTP would need macFUSE. +- The sandbox uses Seatbelt rather than bubblewrap, so sandboxed agents reach everything, including local servers, through srt's proxy. +- Not ported: Cline Desktop (not packaged for macOS here), running Hermes' gateway in the sandbox, printers (AirPrint finds them), languages, Tally and the email watcher. diff --git a/configure b/configure new file mode 100755 index 0000000..8241cea --- /dev/null +++ b/configure @@ -0,0 +1,220 @@ +#!/bin/bash +# +# Purpose : Set up this Mac for your Federated Core (Mail, Calendar, +# Contacts, Superpanel, files, Element, Tailscale, backups) and its +# network (shared folders, AI servers), and AI agents in a sandbox. +# The apps macOS doesn't come with are offered for download. +# +# 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. +# +# This runs with the bash macOS comes with (3.2), so it doesn't use mapfile, +# read -i, associative arrays or ${var,,}, and it uses only tools that are +# part of macOS (plutil, xmllint, osascript, security, profiles), not jq or +# python3, which need the Command Line Tools. + +# Wrapped in { ...; exit; } so bash reads the whole script up front; an update +# can then replace this file while it runs. +{ + +if [ "$(uname -s)" != Darwin ]; then + echo "This is for macOS. On Linux, use CoreDesktop's configure." + exit 1 +fi +MACOS_MAJOR="$(sw_vers -productVersion | cut -d. -f1)" +if [ "$MACOS_MAJOR" -lt 13 ] 2> /dev/null; then + echo "This needs macOS 13 (Ventura) or later." + exit 1 +fi + +# The directory this script is in, following symlinks, so it can be linked +# into a directory on PATH +script_dir() { + local file="$0" link + while [ -L "$file" ]; do + link="$(readlink "$file")" + case "$link" in + /*) file="$link" ;; + *) file="$(dirname "$file")/$link" ;; + esac + done + cd "$(dirname "$file")" && pwd +} + +CONNECTOR="$(script_dir)" +CONF_DIR="$HOME/Library/Application Support/Federated Connector" +COMPUTER="$(scutil --get ComputerName 2> /dev/null || hostname -s)" + +RED=$'\033[31m' GREEN=$'\033[32m' YELLOW=$'\033[33m' BOLD=$'\033[1m' RESET=$'\033[0m' + +# 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]* ]] +} + +# ask [default]: Enter alone keeps the default (bash +# 3.2's read can't put it on the line to edit) +ask() { + local answer + if [ -n "$3" ]; then + read -rp "$2 [$3]: " answer + else + read -rp "$2: " answer + fi + printf -v "$1" '%s' "${answer:-$3}" +} + +# wait_until [args]: run the command every 2 seconds until +# it succeeds, you press Enter, or time runs out. Fails unless it succeeded. +wait_until() { + local seconds="$1" waited=0 key + shift + echo "(Waiting; press Enter to stop waiting.)" + while [ "$waited" -lt "$seconds" ]; do + "$@" && return 0 + if read -r -t 2 key; then + "$@" + return + fi + waited=$((waited + 2)) + done + "$@" +} + +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/10-core.sh -> core +item_name() { + local name + name="$(basename "$1" .sh)" + echo "${name#[0-9][0-9]-}" +} + +# Prints "||<description>"; state is done, todo or absent +# shellcheck disable=SC2153 +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 "$BOLD$TITLE$RESET" + run_configure + ) + local status=$? + if [ $status -ne 0 ]; then + echo "$RED$(item_name "$1") was not set up.$RESET" + 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="${GREEN}done$RESET " + else + mark="${YELLOW}to do$RESET" + fi + printf " %2d) %s %-22s %s\n" $((i + 1)) "$mark" "${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 + +while true; do + load_items + echo + echo "Federated Core on this Mac" + 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" -ge 1 ] && [ "$choice" -le ${#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 100644 index 0000000..0594caf --- /dev/null +++ b/configure.d/10-core.sh @@ -0,0 +1,824 @@ +#!/bin/bash + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="Federated Core" +# shellcheck disable=SC2034 +DESCRIPTION="Mail, Calendar, 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 and Tailscale 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" +BACKUP_KEYCHAIN="federated-connector-backup" +ELEMENT_CONFIG="$HOME/Library/Application Support/Element/config.json" +NEXTCLOUD_CFG="$HOME/Library/Preferences/Nextcloud/nextcloud.cfg" +source "$CONNECTOR/configure.d/lib/json.sh" +source "$CONNECTOR/configure.d/lib/keychain.sh" +source "$CONNECTOR/configure.d/lib/nextcloud.sh" +source "$CONNECTOR/configure.d/lib/apps.sh" +source "$CONNECTOR/configure.d/lib/profile.sh" +[ -f "$CORE_CONF" ] && source "$CORE_CONF" +MAIN_DOMAIN="$CORE_DOMAIN" + +# Mail, Calendar and Contacts are payloads in one profile per Core +SERVICES="mail calendar contacts" + +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="" PROFILE_SERVICES="" PROFILE_UUID="" + [ -n "$1" ] && source "$CORES_DIR/$1.conf" + core_names +} + +# CORE_DOMAIN, CORE_EMAIL and CORE_NAME come from the Core's conf; the rest +# follow +core_names() { + CORE_USER="${CORE_EMAIL%@*}" + NEXTCLOUD="https://nextcloud.$CORE_DOMAIN" + SUPERPANEL="https://superpanel.$CORE_DOMAIN" + SUPERPANEL_APP="$HOME/Applications/Superpanel ($CORE_DOMAIN).app" + MATRIX="https://matrix.$CORE_DOMAIN" + PROFILE_ID="computer.federated.connector.$CORE_DOMAIN" + PROFILE_NAME="Federated Core ($CORE_DOMAIN)" + KEYCHAIN_ACCOUNT="$CORE_USER@nextcloud.$CORE_DOMAIN" +} + +# in_list <word> <list> +in_list() { + [[ " $2 " == *" $1 "* ]] +} + +service_title() { + case "$1" in + mail) echo "Mail for $CORE_EMAIL" ;; + calendar) echo "Calendar with your Nextcloud calendars" ;; + contacts) echo "Contacts with your Nextcloud address books" ;; + esac +} + +superpanel_done() { + [ -d "$SUPERPANEL_APP" ] +} + +# The services in the profile this Mac installed last, if it's still installed +installed_services() { + [ -n "$PROFILE_UUID" ] && profile_installed "$PROFILE_ID" "$PROFILE_UUID" && echo "$PROFILE_SERVICES" +} + +accounts_done() { + local installed svc + installed="$(installed_services)" + for svc in $SERVICES; do + in_list "$svc" "$installed" || return 1 + done +} + +# The Nextcloud app saves each account as "<n>\url=<server>" +files_done() { + grep -qsxE "[0-9]+\\\\url=${NEXTCLOUD//./\\.}/?" "$NEXTCLOUD_CFG" +} + +element_installed() { + app_installed element +} + +# Done when Element isn't installed, as there's nothing to set up; setting up +# the Core offers to install it +element_done() { + element_installed || return 0 + [ -f "$ELEMENT_CONFIG" ] || return 1 + json_get 'd.default_server_config["m.homeserver"].server_name === a[0]' \ + "matrix.$CORE_DOMAIN" < "$ELEMENT_CONFIG" > /dev/null +} + +# Element only follows the main Core +core_done() { + superpanel_done && accounts_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" + printf 'PROFILE_SERVICES=%q\n' "$PROFILE_SERVICES" + printf 'PROFILE_UUID=%q\n' "$PROFILE_UUID" + } > "$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" +} + +# Superpanel as an app in ~/Applications (so in Launchpad and Spotlight) that +# opens it in your browser. The login page carries Superpanel's icon inline. +setup_superpanel() { + local tmp + mkdir -p "$HOME/Applications" + rm -rf "$SUPERPANEL_APP" + osacompile -o "$SUPERPANEL_APP" -e "open location \"$SUPERPANEL/\"" || return 1 + + tmp="$(mktemp -d)" + if curl -s --max-time 15 "$SUPERPANEL/" | grep -o 'rel="icon"[^>]*base64,[^"]*' | head -n 1 \ + | sed 's/.*base64,//' | base64 -D > "$tmp/icon" 2> /dev/null && [ -s "$tmp/icon" ]; then + sips -s format png -z 512 512 "$tmp/icon" --out "$tmp/icon.png" > /dev/null 2>&1 \ + && sips -s format icns "$tmp/icon.png" \ + --out "$SUPERPANEL_APP/Contents/Resources/applet.icns" > /dev/null 2>&1 + fi + rm -rf "$tmp" + # Changing the icon breaks osacompile's ad hoc signature, without which the + # app doesn't open on Apple silicon + codesign --force --sign - "$SUPERPANEL_APP" > /dev/null 2>&1 + touch "$SUPERPANEL_APP" + echo "Added Superpanel to your applications (~/Applications)." +} + +# Ask for your Core password until Nextcloud takes it (PASSWORD). With "app", +# also get an app password for Calendar and Contacts (APP_PASSWORD): the one +# this Mac keeps, if Nextcloud still takes it, or a new one +# (NEW_APP_PASSWORD=1). Asks only once while they're set. +get_passwords() { + local stored + if [ -z "$PASSWORD" ]; then + for _ in 1 2 3; do + read -rsp "${PASSWORD_PROMPT:-Your 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."; PASSWORD=""; return 1 ;; + esac + done + [ -n "$PASSWORD" ] || return 1 + fi + [ "$1" = app ] && [ -z "$APP_PASSWORD" ] || return 0 + stored="$(app_password_load)" + if [ -n "$stored" ] && nextcloud_sign_in "$stored"; then + APP_PASSWORD="$stored" + elif nextcloud_app_password "macOS Calendar and Contacts on $COMPUTER"; then + NEW_APP_PASSWORD=1 + else + echo "Nextcloud didn't make an app password for Calendar and Contacts." + return 1 + fi +} + +forget_passwords() { + unset PASSWORD APP_PASSWORD NEW_APP_PASSWORD +} + +# The mail server publishes its settings (Thunderbird's autoconfig format). +# Sets IMAP_HOST, IMAP_PORT, IMAP_SOCKET, SMTP_HOST, SMTP_PORT, SMTP_SOCKET +# and MAIL_USER, with the usual ones if the server doesn't say. +mail_settings() { + local xml values + xml="$(curl -sf --max-time 15 \ + "https://autoconfig.$CORE_DOMAIN/mail/config-v1.1.xml?emailaddress=$CORE_EMAIL")" + xpath() { + xmllint --xpath "string($1)" - 2> /dev/null <<< "$xml" + } + IMAP_HOST="$(xpath '//incomingServer[@type="imap"][1]/hostname')" + IMAP_PORT="$(xpath '//incomingServer[@type="imap"][1]/port')" + IMAP_SOCKET="$(xpath '//incomingServer[@type="imap"][1]/socketType')" + SMTP_HOST="$(xpath '//outgoingServer[@type="smtp"][1]/hostname')" + SMTP_PORT="$(xpath '//outgoingServer[@type="smtp"][1]/port')" + SMTP_SOCKET="$(xpath '//outgoingServer[@type="smtp"][1]/socketType')" + MAIL_USER="$(xpath '//incomingServer[@type="imap"][1]/username')" + if [ -z "$IMAP_HOST" ] || [ -z "$SMTP_HOST" ] || [ -z "$SMTP_SOCKET" ] \ + || [[ ! "$IMAP_PORT$SMTP_PORT" =~ ^[0-9]+$ ]]; 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 + MAIL_USER="%EMAILADDRESS%" + fi + case "$MAIL_USER" in + %EMAILLOCALPART%) MAIL_USER="$CORE_USER" ;; + *) MAIL_USER="$CORE_EMAIL" ;; + esac +} + +# Mail uses TLS for SSL and STARTTLS alike, and works out which from the port +tls() { + case "$1" in + SSL|STARTTLS) echo "<true/>" ;; + *) echo "<false/>" ;; + esac +} + +payload_header() { + cat << EOF + <dict> + <key>PayloadType</key><string>$1</string> + <key>PayloadVersion</key><integer>1</integer> + <key>PayloadIdentifier</key><string>$PROFILE_ID.$2</string> + <key>PayloadUUID</key><string>$(stable_uuid "$PROFILE_ID.$2")</string> + <key>PayloadDisplayName</key><string>$3</string> +EOF +} + +# Mail keeps your Core password: the mail server doesn't take Nextcloud's app +# passwords +payload_mail() { + payload_header com.apple.mail.managed mail Mail + cat << EOF + <key>EmailAccountDescription</key><string>$(xml_escape "$CORE_EMAIL")</string> + <key>EmailAccountName</key><string>$(xml_escape "$CORE_NAME")</string> + <key>EmailAccountType</key><string>EmailTypeIMAP</string> + <key>EmailAddress</key><string>$(xml_escape "$CORE_EMAIL")</string> + <key>IncomingMailServerAuthentication</key><string>EmailAuthPassword</string> + <key>IncomingMailServerHostName</key><string>$(xml_escape "$IMAP_HOST")</string> + <key>IncomingMailServerPortNumber</key><integer>$IMAP_PORT</integer> + <key>IncomingMailServerUseSSL</key>$(tls "$IMAP_SOCKET") + <key>IncomingMailServerUsername</key><string>$(xml_escape "$MAIL_USER")</string> + <key>IncomingPassword</key><string>$(xml_escape "$PASSWORD")</string> + <key>OutgoingMailServerAuthentication</key><string>EmailAuthPassword</string> + <key>OutgoingMailServerHostName</key><string>$(xml_escape "$SMTP_HOST")</string> + <key>OutgoingMailServerPortNumber</key><integer>$SMTP_PORT</integer> + <key>OutgoingMailServerUseSSL</key>$(tls "$SMTP_SOCKET") + <key>OutgoingMailServerUsername</key><string>$(xml_escape "$MAIL_USER")</string> + <key>OutgoingPassword</key><string>$(xml_escape "$PASSWORD")</string> + </dict> +EOF +} + +# payload_dav <CalDAV|CardDAV> <service> <title> +payload_dav() { + payload_header "com.apple.$(echo "$1" | tr "[:upper:]" "[:lower:]").account" "$2" "$3" + cat << EOF + <key>$1AccountDescription</key><string>$(xml_escape "$3 ($CORE_DOMAIN)")</string> + <key>$1HostName</key><string>nextcloud.$CORE_DOMAIN</string> + <key>$1Port</key><integer>443</integer> + <key>$1PrincipalURL</key><string>$(xml_escape "$NEXTCLOUD/remote.php/dav/principals/users/$CORE_USER/")</string> + <key>$1UseSSL</key><true/> + <key>$1Username</key><string>$(xml_escape "$CORE_USER")</string> + <key>$1Password</key><string>$(xml_escape "$APP_PASSWORD")</string> + </dict> +EOF +} + +payload_calendar() { + payload_dav CalDAV calendar Calendar +} + +payload_contacts() { + payload_dav CardDAV contacts Contacts +} + +# write_profile <file> <services> <uuid> +write_profile() { + local file="$1" services="$2" uuid="$3" svc + { + cat << EOF +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>PayloadContent</key> + <array> +EOF + for svc in $services; do + "payload_$svc" + done + cat << EOF + </array> + <key>PayloadDisplayName</key><string>$(xml_escape "$PROFILE_NAME")</string> + <key>PayloadDescription</key><string>$(xml_escape "Your Federated Core's email, calendars and contacts ($CORE_EMAIL).")</string> + <key>PayloadIdentifier</key><string>$PROFILE_ID</string> + <key>PayloadOrganization</key><string>$(xml_escape "$CORE_DOMAIN")</string> + <key>PayloadRemovalDisallowed</key><false/> + <key>PayloadScope</key><string>User</string> + <key>PayloadType</key><string>Configuration</string> + <key>PayloadUUID</key><string>$uuid</string> + <key>PayloadVersion</key><integer>1</integer> +</dict> +</plist> +EOF + } > "$file" + plutil -lint -s "$file" +} + +# Install the profile with these services, replacing the one installed. The +# profile file has your passwords in it, so only you can read it, and it's +# deleted once macOS has it. +install_accounts() { + local services="$1" dir uuid status=0 + if in_list calendar "$services" || in_list contacts "$services"; then + get_passwords app || return 1 + else + get_passwords || return 1 + fi + in_list mail "$services" && mail_settings + + dir="$(mktemp -d)" || return 1 + uuid="$(uuidgen)" + if ! (umask 077 && write_profile "$dir/$PROFILE_NAME.mobileconfig" "$services" "$uuid"); then + echo "Couldn't make the profile." + status=1 + elif profile_install "$dir/$PROFILE_NAME.mobileconfig" "$PROFILE_ID" "$uuid" "$PROFILE_NAME"; then + PROFILE_SERVICES="$services" PROFILE_UUID="$uuid" + save_conf + if [ -n "$NEW_APP_PASSWORD" ]; then + app_password_save "$APP_PASSWORD" \ + || echo "Couldn't keep Calendar and Contacts' app password in your keychain; it still works." + NEW_APP_PASSWORD="" + fi + else + status=1 + fi + rm -rf "$dir" + # An app password nothing uses + if [ -n "$NEW_APP_PASSWORD" ]; then + nextcloud_revoke_app_password "$APP_PASSWORD" + APP_PASSWORD="" NEW_APP_PASSWORD="" + fi + return $status +} + +# Ask which of Mail, Calendar and Contacts to set up, and install a profile +# with them and the ones already set up +setup_accounts() { + local installed wanted="" svc + installed="$(installed_services)" + for svc in $SERVICES; do + if in_list "$svc" "$installed"; then + echo " $(service_title "$svc"): already set up" + wanted="$wanted $svc" + elif confirm_yes "Set up $(service_title "$svc")?"; then + wanted="$wanted $svc" + fi + done + wanted="${wanted# }" + [ -n "$wanted" ] && [ "$wanted" != "$installed" ] || return 0 + install_accounts "$wanted" +} + +# The Nextcloud app keeps your files in Finder. It signs in through your +# browser and makes its own app password; told the server, it skips asking. +setup_files() { + local app + app_ensure nextcloud "It keeps your Nextcloud files in Finder." || return 1 + app="$(app_path nextcloud)" + if pgrep -x Nextcloud > /dev/null; then + open -a "$app" + echo "Nextcloud is already open. Click the cloud in the menu bar, then your account" + echo "name > Add account, and enter $NEXTCLOUD." + else + open -a "$app" --args --overrideserverurl "$NEXTCLOUD" + echo "Nextcloud opens with $NEXTCLOUD filled in. Choose Log in, then sign in" + echo "in your browser, and choose where your files go (the default is fine)." + fi + if ! wait_until 600 files_done; then + echo "Nextcloud isn't signed in to $NEXTCLOUD yet. Run this again when it is." + return 1 + fi + echo "Nextcloud keeps your files in sync with this Mac." +} + +# Element reads config.json in its folder in Application Support 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 + base_url="$(curl -sf --max-time 15 "$MATRIX/.well-known/matrix/client" \ + | json_get 'd["m.homeserver"].base_url')" + base_url="${base_url:-$MATRIX}" + json_edit "$ELEMENT_CONFIG" \ + 'd.default_server_config = {"m.homeserver": {base_url: a[0], server_name: a[1]}};' \ + "${base_url%/}" "matrix.$CORE_DOMAIN" || return 1 + echo "Element will use $MATRIX the next time it opens." +} + +# Run a step unless it's done; a failed step doesn't stop the ones after it +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 "$RED$title was not set up.$RESET"; STATUS=1; } +} + +# Set up the Core loaded with load_core, or a new one +setup_core() { + local url name + STATUS=0 + + ask url "Your Superpanel's address (e.g. https://superpanel.example.com)" \ + "${CORE_DOMAIN:+https://superpanel.$CORE_DOMAIN}" + url="${url#*://}" + url="${url%%/*}" + CORE_DOMAIN="${url#superpanel.}" + if [[ ! "$CORE_DOMAIN" =~ ^[A-Za-z0-9.-]+$ ]]; then + echo "That isn't a Superpanel address." + return 1 + fi + core_names + if ! curl -s -o /dev/null --max-time 15 "$SUPERPANEL/"; then + echo "Couldn't reach $SUPERPANEL." + return 1 + fi + + ask CORE_EMAIL "Your Core email" "${CORE_EMAIL:-$USER@$CORE_DOMAIN}" + name="$(id -F 2> /dev/null)" + ask CORE_NAME "Your name, as shown on email you send" "${CORE_NAME:-$name}" + [[ "$CORE_EMAIL" == ?*@?* ]] || { echo "That isn't an email address."; return 1; } + core_names + save_conf + + echo + step superpanel "Superpanel in your applications" + if accounts_done; then + echo " Mail, Calendar and Contacts: already set up" + else + setup_accounts || { echo "${RED}Mail, Calendar and Contacts were not set up.$RESET"; STATUS=1; } + fi + step files "Your Nextcloud files in Finder" + if [ "$CORE_DOMAIN" = "$MAIN_DOMAIN" ]; then + if ! element_installed; then + app_ensure element "It's the app for your Core's chat (Matrix)." || true + fi + element_installed && step element "Element with your Core's Matrix server" + fi + forget_passwords + return $STATUS +} + +# After your Core password changes, e.g. in Superpanel. Mail keeps your Core +# password, so it gets the new one, in a new version of the profile. Calendar, +# Contacts and the Nextcloud app 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 installed + load_core "$1" + PASSWORD_PROMPT="Your new Core password" + get_passwords || return 1 + echo "Nextcloud has your new password, and Calendar, Contacts and the Nextcloud app work again." + installed="$(installed_services)" + if in_list mail "$installed"; then + echo "Mail needs it too, in a new version of the \"$PROFILE_NAME\" profile." + install_accounts "$installed" || { forget_passwords; return 1; } + fi + forget_passwords +} + +# Tailscale and Backup point at one Core, which can't be removed while they do +backup_on() { + [[ "$(source "$BACKUP_CONF" 2> /dev/null && echo "$BACKUP_WEBDAV")" == "https://nextcloud.$1/"* ]] \ + && launchctl print "gui/$(id -u)/computer.federated.connector.backup" > /dev/null 2>&1 +} + +tailscale_on() { + [ "$(source "$TAILSCALE_CONF" 2> /dev/null && echo "$TAILSCALE_DOMAIN")" = "$1" ] +} + +# 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" -ge 1 ] && [ "$choice" -le ${#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 + [ -f "$TAILSCALE_CONF" ] && echo "To move this Mac to its Tailscale network: configure tailscale" + return 0 +} + +# Undo what setup_core did. Nothing on the Core itself changes. +remove_core() { + local domain="$1" new_main="" app_password + if tailscale_on "$domain"; then + echo "This Mac 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 Mail, Calendar, Contacts and Superpanel from this Mac." + echo "Your email, calendars, contacts and files stay on the Core." + confirm "Remove $domain?" || return 0 + + load_core "$domain" + if ! profile_remove "$PROFILE_ID" "$PROFILE_NAME"; then + echo "The \"$PROFILE_NAME\" profile is still installed, so $domain wasn't removed." + return 1 + fi + app_password="$(app_password_load)" + [ -n "$app_password" ] && nextcloud_revoke_app_password "$app_password" + app_password_delete + rm -rf "$SUPERPANEL_APP" + + # Element keeps its default server, unless that was this Core + if [ "$domain" = "$MAIN_DOMAIN" ] && [ -z "$new_main" ] && [ -f "$ELEMENT_CONFIG" ] \ + && element_installed && element_done; then + json_edit "$ELEMENT_CONFIG" 'delete d.default_server_config;' + fi + + if files_done; then + echo "The Nextcloud app still syncs your files. To stop, click the cloud in the menu bar," + echo "then your account ($CORE_USER) > Remove account. Your files stay on the Core." + fi + + rm -f "$CORES_DIR/$domain.conf" + echo "Removed $domain from this Mac." + 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 Mac 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 " $1: ${GREEN}working$RESET" +} + +# failed <title> <problem> [fix] [more] +failed() { + echo " $RED$1: $2$RESET" + [ -n "$4" ] && echo " $4" + PROBLEMS=$((PROBLEMS + 1)) + if [ -n "$3" ]; then + FIXES+=("$3") + FIX_TITLES+=("$1") + fi +} + +# The profile, and the app password Calendar and Contacts have. Mail's +# password can't be checked without macOS asking you to let this see it in +# your keychain. +test_accounts() { + local installed svc missing="" app_password + installed="$(installed_services)" + if [ -z "$installed" ]; then + failed "Mail, Calendar and Contacts" "not set up (the profile isn't installed)" fix_accounts + return + fi + for svc in $SERVICES; do + in_list "$svc" "$installed" || missing="$missing $svc" + done + [ -n "$missing" ] && failed "Profile" "doesn't have${missing}" fix_accounts + in_list mail "$installed" && passed "Mail (the profile is installed)" + in_list calendar "$installed" || in_list contacts "$installed" || return 0 + app_password="$(app_password_load)" + if [ -z "$app_password" ]; then + failed "Calendar and Contacts" "this Mac doesn't have their app password" fix_accounts + return + fi + nextcloud_sign_in "$app_password" + case $? in + 0) passed "Calendar and Contacts" ;; + 2) failed "Calendar and Contacts" "Nextcloud doesn't accept their app password" fix_accounts \ + "It may have been revoked in Nextcloud under Settings > Security." ;; + *) failed "Calendar and Contacts" "couldn't check their app password" ;; + esac +} + +test_files() { + local title="Your Nextcloud files" + if ! app_installed nextcloud; then + failed "$title" "the Nextcloud app isn't installed" setup_files + elif ! files_done; then + failed "$title" "the Nextcloud app isn't signed in to $NEXTCLOUD" setup_files + elif ! pgrep -x Nextcloud > /dev/null; then + failed "$title" "the Nextcloud app isn't open" open_nextcloud + else + passed "$title" + fi +} + +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 +} + +# Backups have their own app password, in the keychain +backup_webdav() { + (source "$BACKUP_CONF" && echo "$BACKUP_WEBDAV") +} + +test_backups() { + nextcloud_sign_in "$(keychain_load "$BACKUP_KEYCHAIN" "nextcloud:$(backup_webdav)")" + 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 +} + +# Backups get their own new app password, as configure backup gives them +fix_backups() { + local APP_PASSWORD webdav + get_passwords || return 1 + webdav="$(backup_webdav)" + nextcloud_app_password "Federated Backup on $COMPUTER" || return 1 + keychain_save "$BACKUP_KEYCHAIN" "nextcloud:$webdav" "$APP_PASSWORD" || return 1 + echo "Backups have a new app password." +} + +# 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 " ${RED}Couldn't reach Nextcloud at $NEXTCLOUD.$RESET" + echo " Check this Mac's internet connection, or whether your Core is down." + return 1 + fi + if json_get 'd.maintenance' <<< "$status" > /dev/null; 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 "$SUPERPANEL/"; then + passed "Superpanel" + else + failed "Superpanel" "can't reach $SUPERPANEL" + fi + test_accounts + test_files + [ "$CORE_DOMAIN" = "$MAIN_DOMAIN" ] && element_installed && test_element + backup_on "$CORE_DOMAIN" && test_backups + return 0 +} + +# A new version of the profile with all of Mail, Calendar and Contacts, and +# Calendar and Contacts' app password, or a new one if Nextcloud doesn't take +# it any more +fix_accounts() { + install_accounts "$SERVICES" +} + +open_nextcloud() { + open -a "$(app_path nextcloud)" +} + +# Run the fixes test_core found. Those that need your Core password ask for +# it once. +fix_core() { + local i + STATUS=0 + for i in "${!FIXES[@]}"; do + # Each fix is listed once + [ "$i" -gt 0 ] && in_list "${FIXES[$i]}" "${FIXES[*]:0:$i}" && continue + echo + echo "${FIX_TITLES[$i]}:" + "${FIXES[$i]}" || { echo "$RED${FIX_TITLES[$i]} was not fixed.$RESET"; STATUS=1; } + done + forget_passwords + 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 Mac 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 domain + DOMAINS=() + while IFS= read -r domain; do + DOMAINS+=("$domain") + done < <(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="${GREEN}done$RESET " + else + state="${YELLOW}to do$RESET" + fi + printf " %d) %s %s%s\n" $((i + 1)) "$state" "${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" -ge 1 ] && [ "$choice" -le ${#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..c1b0720 --- /dev/null +++ b/configure.d/15-tailscale.sh @@ -0,0 +1,96 @@ +#!/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" +source "$CONNECTOR/configure.d/lib/json.sh" +source "$CONNECTOR/configure.d/lib/apps.sh" +[ -f "$CORE_CONF" ] && source "$CORE_CONF" +[ -f "$TAILSCALE_CONF" ] && source "$TAILSCALE_CONF" + +# The Tailscale app's own command line, in both the App Store and the +# standalone app +tailscale() { + local app + app="$(app_path tailscale)" || return 1 + "$app/Contents/MacOS/Tailscale" "$@" +} + +running() { + tailscale status --json 2> /dev/null | json_get 'd.BackendState === "Running"' > /dev/null +} + +# Tailscale has no status field naming its login server, so tailscale.conf +# records which Core it was set up for +joined() { + [ -n "$TAILSCALE_DOMAIN" ] && running +} + +# Done when on the main Core's network +is_configured() { + [ -n "$CORE_DOMAIN" ] && [ "$TAILSCALE_DOMAIN" = "$CORE_DOMAIN" ] && joined +} + +# Log out rather than only disconnect, so this Mac's key is expired on +# headscale and it's off the network until it joins again +leave_network() { + tailscale logout || return 1 + rm -f "$TAILSCALE_CONF" + echo "This Mac has left your Core's Tailscale network. To join again: configure tailscale" +} + +# The first time it opens, Tailscale asks you to allow its VPN configuration +# (and, for the standalone app, its system extension); until then its command +# line can't reach it +tailscale_ready() { + tailscale status --json 2> /dev/null | json_get 'd.BackendState' > /dev/null +} + +run_configure() { + local choice + if joined &> /dev/null; then + echo "This Mac 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 + + app_ensure tailscale "It joins this Mac to your Core's network." || return 1 + if ! tailscale_ready; then + open -a "$(app_path tailscale)" + echo "Tailscale is opening. If it asks to add a VPN configuration or allow a system" + echo "extension, allow it (System Settings may open for that)." + wait_until 300 tailscale_ready || { echo "Tailscale isn't ready yet. Run this again when it is."; return 1; } + fi + + # --reset and --force-reauth move the Mac from any other tailnet + echo "Open the link below to sign in to your Core's Tailscale network (headscale.$CORE_DOMAIN)." + tailscale up --reset --force-reauth --login-server "https://headscale.$CORE_DOMAIN" \ + --accept-routes || return 1 + + mkdir -p "$(dirname "$TAILSCALE_CONF")" + printf 'TAILSCALE_DOMAIN=%q\n' "$CORE_DOMAIN" > "$TAILSCALE_CONF" + echo "This Mac 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..36b9b3a --- /dev/null +++ b/configure.d/20-backup.sh @@ -0,0 +1,308 @@ +#!/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" +ACCESS_CHECK="$CONF_DIR/backup-access-check" +NOW_REQUEST="$CONF_DIR/backup-now" +BACKUP_LOG="$HOME/Library/Logs/Federated Connector/backup.log" +BACKUP_KEYCHAIN="federated-connector-backup" +BACKUP_APP="$HOME/Applications/Federated Backup.app" +BACKUP_SCRIPT="$CONNECTOR/system/backup" +LABEL="computer.federated.connector.backup" +PLIST="$HOME/Library/LaunchAgents/$LABEL.plist" +FULL_DISK_ACCESS_PANE="x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles" +source "$CONNECTOR/configure.d/lib/json.sh" +source "$CONNECTOR/configure.d/lib/keychain.sh" +source "$CONNECTOR/configure.d/lib/nextcloud.sh" +source "$CONNECTOR/configure.d/lib/tools.sh" +[ -f "$CORE_CONF" ] && source "$CORE_CONF" + +job_loaded() { + launchctl print "gui/$(id -u)/$LABEL" > /dev/null 2>&1 +} + +backups_on() { + [ -f "$BACKUP_CONF" ] || return 1 + source "$CONNECTOR/system/backup-env.sh" > /dev/null || return 1 + [ -n "$RESTIC_PASSWORD_COMMAND" ] && job_loaded +} + +# 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() { + keychain_save "$BACKUP_KEYCHAIN" "$1" "$2" +} + +# The backup gets its own app password, so revoking it stops only backups +nextcloud_login() { + [ -n "$(backup_secret "nextcloud:$WEBDAV")" ] \ + && rclone lsf --max-depth 1 ":webdav:" > /dev/null 2>&1 && return 0 + APP_PASSWORD="" + for _ in 1 2 3; do + read -rsp "Your Core password: " PASSWORD + echo + nextcloud_app_password "Federated Backup on $COMPUTER" + case $? in + 0) break ;; + 2) echo "Nextcloud says that password is wrong." ;; + *) echo "Couldn't reach Nextcloud at $NEXTCLOUD."; unset PASSWORD; 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 -)" + export RCLONE_WEBDAV_PASS +} + +new_passphrase() { + local pass + pass="$(openssl rand -base64 24)" + echo "Your backup is encrypted with this passphrase:" + echo + echo " $pass" + echo + echo "Save it somewhere other than this Mac, such as Bitwarden. Without it, the backup" + echo "can't be read if this Mac is lost. It's kept in your keychain so the daily" + echo "backup can run." + until confirm "Have you saved it?"; do :; done + save_secret "passphrase:$WEBDAV/$BACKUP_DIR" "$pass" +} + +# The app launchd starts, which runs system/backup. Full Disk Access belongs +# to this build of the app, so it's only made again if it runs another script +# (e.g. this folder moved), and then needs Full Disk Access again. +backup_app_current() { + [ "$(plutil -extract FederatedBackupScript raw -o - "$BACKUP_APP/Contents/Info.plist" 2> /dev/null)" \ + = "$BACKUP_SCRIPT" ] +} + +make_backup_app() { + local script + backup_app_current && return 0 + # Quoted for an AppleScript string + script="${BACKUP_SCRIPT//\\/\\\\}" + script="${script//\"/\\\"}" + mkdir -p "$HOME/Applications" + rm -rf "$BACKUP_APP" + osacompile -o "$BACKUP_APP" \ + -e 'on run' \ + -e ' try' \ + -e " do shell script \"/bin/bash \" & quoted form of \"$script\" & \" > /dev/null 2>&1\"" \ + -e ' end try' \ + -e 'end run' || return 1 + # No Dock icon while it runs; a name of its own in Privacy & Security + plutil -replace LSUIElement -bool true "$BACKUP_APP/Contents/Info.plist" \ + && plutil -replace CFBundleIdentifier -string "$LABEL" "$BACKUP_APP/Contents/Info.plist" \ + && plutil -replace FederatedBackupScript -string "$BACKUP_SCRIPT" "$BACKUP_APP/Contents/Info.plist" \ + && codesign --force --sign - "$BACKUP_APP" > /dev/null 2>&1 +} + +# Start the app the way launchd does (as itself, not as part of Terminal), +# and have system/backup say whether it can read what Full Disk Access guards +full_disk_access() { + local answer + echo "?" > "$ACCESS_CHECK" + open -g -W "$BACKUP_APP" 2> /dev/null + answer="$(cat "$ACCESS_CHECK" 2> /dev/null)" + rm -f "$ACCESS_CHECK" + [ "$answer" = yes ] +} + +grant_access() { + echo "Checking that Federated Backup can read all your files..." + full_disk_access && { echo "It can."; return 0; } + echo + echo "macOS keeps apps out of Desktop, Documents, Mail, Photos and other folders until" + echo "you let them in. To back them up, give Federated Backup Full Disk Access:" + echo "System Settings opens at Full Disk Access, and Finder shows the app. Drag it into" + echo "the list (or click + and choose it), and make sure it's turned on." + open "$FULL_DISK_ACCESS_PANE" + open -R "$BACKUP_APP" + if wait_until 600 full_disk_access; then + echo "Federated Backup can read all your files." + else + echo "Without Full Disk Access, backups leave out the folders macOS guards, and" + echo "you get a notification each time. To give it later: configure backup" + fi +} + +# Hourly and at login; system/backup backs up once a day. Background +# priority keeps it out of the way of what you're doing. +install_job() { + mkdir -p "$(dirname "$PLIST")" + cat > "$PLIST" << EOF +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>Label</key><string>$LABEL</string> + <key>ProgramArguments</key> + <array> + <string>$(xml_escape "$BACKUP_APP/Contents/MacOS/applet")</string> + </array> + <key>RunAtLoad</key><true/> + <key>StartInterval</key><integer>3600</integer> + <key>ProcessType</key><string>Background</string> + <key>LowPriorityIO</key><true/> + <key>Nice</key><integer>19</integer> +</dict> +</plist> +EOF + launchctl bootout "gui/$(id -u)/$LABEL" 2> /dev/null + launchctl bootstrap "gui/$(id -u)" "$PLIST" +} + +xml_escape() { + local s="$1" + s="${s//&/\&}" + s="${s//</\<}" + s="${s//>/\>}" + printf '%s' "$s" +} + +# Stop the daily backup and remove the app and the job +stop_backups() { + launchctl bootout "gui/$(id -u)/$LABEL" 2> /dev/null + rm -f "$PLIST" + rm -rf "$BACKUP_APP" + rm -f "$CONF_DIR/backup-last" +} + +# Delete the backup from Nextcloud, then what's on this Mac 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" + keychain_delete "$BACKUP_KEYCHAIN" "nextcloud:$WEBDAV" + keychain_delete "$BACKUP_KEYCHAIN" "passphrase:$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 host + 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 "The last backups are in: $BACKUP_LOG" + 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 " 3) Back up now" + echo " q) Leave it as it is" + echo + read -rp "Choose: " choice + case "$choice" in + 1) ;; + 2) turn_off; return ;; + 3) touch "$NOW_REQUEST" + launchctl kickstart "gui/$(id -u)/$LABEL" + echo "Started. To follow it: tail -f \"$BACKUP_LOG\"" + return 0 ;; + *) 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 + tool_ensure restic rclone || return 1 + + CORE_USER="${CORE_EMAIL%@*}" + NEXTCLOUD="https://nextcloud.$CORE_DOMAIN" + WEBDAV="$NEXTCLOUD/remote.php/dav/files/$CORE_USER" + host="$(scutil --get LocalHostName 2> /dev/null || hostname -s)" + BACKUP_DIR=".backup-$host" + + 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" + printf 'BACKUP_HOST=%q\n' "$host" + } > "$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 macOS: 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 + + make_backup_app || { echo "Couldn't make the Federated Backup app."; return 1; } + grant_access + # launchd starts the app as soon as the job is added; the first backup + # waits for a day unless you start it below + [ -f "$CONF_DIR/backup-last" ] || touch "$CONF_DIR/backup-last" + install_job || return 1 + echo "Your home folder will be backed up daily to $BACKUP_DIR in your Nextcloud files." + echo "(macOS may say a background item was added: that's this. If it's turned off in" + echo "System Settings > General > Login Items, backups don't run.)" + + if confirm_yes "Start the first backup now? It runs in the background and can take hours."; then + touch "$NOW_REQUEST" + launchctl kickstart "gui/$(id -u)/$LABEL" + echo "Started. To follow it: tail -f \"$BACKUP_LOG\"" + fi +} diff --git a/configure.d/30-agents.sh b/configure.d/30-agents.sh new file mode 100644 index 0000000..4706aaf --- /dev/null +++ b/configure.d/30-agents.sh @@ -0,0 +1,163 @@ +#!/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" +# Your shell reads these when it starts. zsh is macOS' shell; bash reads +# .bash_profile in Terminal. +SHELL_FILES=("$HOME/.zshrc" "$HOME/.bash_profile") +BLOCK_START="# >>> Federated Connector >>>" +BLOCK_END="# <<< Federated Connector <<<" +source "$CONNECTOR/configure.d/lib/json.sh" +source "$CONNECTOR/configure.d/lib/tools.sh" +source "$CONNECTOR/configure.d/lib/agents.sh" + +# name|title|installer|installer's arguments. Each agent's own installer, from +# its makers; they all support macOS. +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" +) + +# Typing an agent's name runs sandbox/bin's, which runs it in the sandbox. +# The block goes last in each file, 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 +} + +block_last() { + [ -f "$1" ] && [ "$(grep -v '^[[:space:]]*$' "$1" | tail -n 4)" = "$(path_block)" ] +} + +on_path() { + local file + for file in "${SHELL_FILES[@]}"; do + block_last "$file" || return 1 + done +} + +put_on_path() { + local file tmp + for file in "${SHELL_FILES[@]}"; do + block_last "$file" && continue + touch "$file" || 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 }' "$file" > "$tmp" + { cat "$tmp"; echo; path_block; } > "$file" + rm -f "$tmp" + done + echo "Agents run in the sandbox in new Terminal windows. To run one without it: unsandboxed <agent>" +} + +# Claude Code runs every command it starts in its own sandbox, also built on +# Seatbelt; it can't run inside srt, as Seatbelt sandboxes can't be nested. +# Anything already in the sandbox section of your settings wins over these +# defaults. +claude_sandbox_on() { + [ -f "$CLAUDE_SETTINGS" ] \ + && json_get 'd.sandbox && d.sandbox.enabled === true' < "$CLAUDE_SETTINGS" > /dev/null +} + +turn_on_claude_sandbox() { + local domains + domains="$(json_get 'd.network.allowedDomains' < "$BASE_CONFIG")" || return 1 + json_edit "$CLAUDE_SETTINGS" ' + var defaults = {enabled: true, network: {allowedDomains: JSON.parse(a[0])}}; + function under(base, mine) { + Object.keys(mine).forEach(function (k) { + if (base[k] && typeof base[k] === "object" && !Array.isArray(base[k]) + && mine[k] && typeof mine[k] === "object" && !Array.isArray(mine[k])) { + under(base[k], mine[k]); + } else { + base[k] = mine[k]; + } + }); + return base; + } + d.sandbox = under(defaults, d.sandbox || {});' "$domains" || return 1 + echo "Claude Code runs the commands it starts in its own sandbox." +} + +sandbox_ready() { + srt_path > /dev/null && on_path \ + && { ! agent_installed claude || claude_sandbox_on; } +} + +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 "$RED$title was not installed.$RESET" + status=1 + fi + fi + done + + echo + if ! srt_path > /dev/null; then + echo "The sandbox for opencode and Hermes is Anthropic's sandbox runtime (srt)." + tool_ensure node srt || { echo "${RED}Without srt, opencode and Hermes can't run in the sandbox.$RESET"; return 1; } + fi + if ! on_path; then + echo "Typing opencode or hermes should run it in the sandbox. That takes a line at the" + echo "end of ~/.zshrc and ~/.bash_profile." + 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 && ! claude_sandbox_on; then + turn_on_claude_sandbox || status=1 + fi + + 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..bae864c --- /dev/null +++ b/configure.d/32-opencode.sh @@ -0,0 +1,27 @@ +#!/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/json.sh" +source "$CONNECTOR/configure.d/lib/agents.sh" + +is_installed() { + agent_installed opencode +} + +# Signed in to at least one provider +is_configured() { + json_get 'Object.keys(d).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/50-ai-servers.sh b/configure.d/50-ai-servers.sh new file mode 100644 index 0000000..a61e722 --- /dev/null +++ b/configure.d/50-ai-servers.sh @@ -0,0 +1,317 @@ +#!/bin/bash +# allow_entries prints one entry per line, for the shell to split into +# arguments; the JavaScript in single quotes isn't for the shell to expand +# shellcheck disable=SC2046,SC2016 + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="AI servers" +# shellcheck disable=SC2034 +DESCRIPTION="Use LLM servers on this Mac or 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 networks without one. +AI_SERVERS_CONF="$CONF_DIR/ai-servers" +# Your own sandbox config, which 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/json.sh" +source "$CONNECTOR/configure.d/lib/mdns.sh" +source "$CONNECTOR/configure.d/lib/agents.sh" + +# Ports LLM servers listen on by default. All of them answer OpenAI's API at +# /v1, which is how every agent here talks to them. +LLM_PORTS="11434 1234 8080 8000" + +port_name() { + case "$1" in + 11434) echo Ollama ;; + 1234) echo "LM Studio" ;; + 8080) echo llama.cpp ;; + 8000) echo vLLM ;; + *) echo "LLM server" ;; + esac +} + +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" \ + | json_get 'd.data.map(function (m) { return m.id; }).join("\n")' +} + +# What the server is, e.g. Ollama, for its name in the agents' settings +server_kind() { + if curl -sf -m 3 "http://$1/api/version" > /dev/null; then + echo Ollama + else + port_name "${1##*:}" + fi +} + +is_local() { + case "${1%:*}" in + localhost|127.0.0.1) return 0 ;; + *) return 1 ;; + esac +} + +# What the sandboxes allow for a server. srt's proxy only lets through a +# loopback address that's listed as an address, so a server on this Mac is +# listed both ways. +allow_entries() { + if is_local "$1"; then + echo "localhost:${1##*:}" + echo "127.0.0.1:${1##*:}" + else + echo "$1" + fi +} + +# The LLM servers on this Mac and 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 file + dir="$(mktemp -d)" || return 1 + for host in localhost $(mdns_hosts); do + for port in $LLM_PORTS; do + (server_models "$host:$port" | grep -c . > "$dir/$host:$port") & + done + done + wait + for file in "$dir"/*; do + [ -f "$file" ] && [ "$(cat "$file")" -gt 0 ] && echo "$(basename "$file")|$(cat "$file")" + done + rm -rf "$dir" +} + +# Let every sandboxed agent (opencode, Hermes) reach host:port, and only that +# port +sandbox_allow() { + json_edit "$SANDBOX_CONF" ' + d.network = d.network || {}; + var list = (d.network.allowedDomains || []).filter(function (x) { return a.indexOf(x) < 0; }); + d.network.allowedDomains = list.concat(a);' $(allow_entries "$1") +} + +sandbox_disallow() { + [ -f "$SANDBOX_CONF" ] || return 0 + json_edit "$SANDBOX_CONF" ' + if (d.network && d.network.allowedDomains) { + d.network.allowedDomains = d.network.allowedDomains.filter(function (x) { return a.indexOf(x) < 0; }); + }' $(allow_entries "$1") +} + +# Claude Code's sandbox only covers the commands it runs, e.g. curl, not its +# own connection to Anthropic. Its list replaces the defaults `configure +# agents` gives it, so if it has none yet, it starts from those. +claude_allow() { + local defaults + [ -f "$CLAUDE_SETTINGS" ] || return 0 + defaults="$(json_get 'd.network.allowedDomains' < "$CONNECTOR/sandbox/config/base.json")" || return 1 + json_edit "$CLAUDE_SETTINGS" ' + var defaults = JSON.parse(a[0]), add = a.slice(1); + d.sandbox = d.sandbox || {}; + d.sandbox.network = d.sandbox.network || {}; + var list = (d.sandbox.network.allowedDomains || defaults).filter(function (x) { return add.indexOf(x) < 0; }); + d.sandbox.network.allowedDomains = list.concat(add);' "$defaults" $(allow_entries "$1") +} + +claude_disallow() { + [ -f "$CLAUDE_SETTINGS" ] || return 0 + json_edit "$CLAUDE_SETTINGS" ' + if (d.sandbox && d.sandbox.network && d.sandbox.network.allowedDomains) { + d.sandbox.network.allowedDomains = d.sandbox.network.allowedDomains.filter(function (x) { return a.indexOf(x) < 0; }); + }' $(allow_entries "$1") +} + +# 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:]' +} + +where() { + if is_local "$1"; then echo "this Mac"; else echo "${1%%:*}"; fi +} + +# 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 + id="$(opencode_provider "$server")" + json_edit "$OPENCODE_CONF" ' + if (!d["$schema"]) d["$schema"] = "https://opencode.ai/config.json"; + var models = {}; + a[3].split("\n").filter(function (m) { return m; }).forEach(function (m) { models[m] = {name: m}; }); + d.provider = d.provider || {}; + d.provider[a[0]] = {npm: "@ai-sdk/openai-compatible", name: a[1], options: {baseURL: a[2]}, models: models};' \ + "$id" "$kind on $(where "$server")" "http://$server/v1" "$(server_models "$server")" || return 1 + echo "opencode: added $kind on $(where "$server") (choose its models with /models)." + if confirm_yes "Start opencode with $model?"; then + json_edit "$OPENCODE_CONF" 'd.model = a[0];' "$id/$model" || return 1 + fi +} + +opencode_remove() { + local id + [ -f "$OPENCODE_CONF" ] || return 0 + id="$(opencode_provider "$1")" + json_edit "$OPENCODE_CONF" ' + if (d.provider) delete d.provider[a[0]]; + if ((d.model || "").indexOf(a[0] + "/") === 0) delete d.model;' "$id" +} + +# 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 $(where "$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." +} + +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=() line model choice i + while IFS= read -r line; do + [ -n "$line" ] && models+=("$line") + done < <(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 $(where "$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" -lt 1 ] || [ "$choice" -gt ${#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 +} + +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 and add the one you choose +find_and_add() { + local servers=() line server models choice i + echo "Looking for LLM servers on this Mac and your network..." + while IFS= read -r line; do + servers+=("$line") + done < <(find_servers) + if [ ${#servers[@]} -eq 0 ]; then + echo "No LLM servers found. A server on another machine has to accept connections from" + echo "other machines: in Ollama's settings, turn on \"Expose Ollama to the network\" (or" + echo "set OLLAMA_HOST=0.0.0.0); in LM Studio, turn on \"Serve on Local Network\". Or" + echo "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" -lt 1 ] || [ "$choice" -gt ${#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=() line choice i + while IFS= read -r line; do + servers+=("$line") + done < <(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" -lt 1 ] || [ "$choice" -gt ${#servers[@]} ]; then + echo "Choose a number from the list." + return 1 + fi + remove_server "${servers[$((choice - 1))]}" +} + +run_configure() { + local choice + 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, such as Ollama, on this Mac and your network, allows them and sets up" + echo "the agents." + + while true; do + echo + if [ -s "$AI_SERVERS_CONF" ]; then + echo "The agents can reach: $(saved_servers | tr '\n' ' ')" + echo + fi + echo " 1) Find servers" + 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/60-storage.sh b/configure.d/60-storage.sh new file mode 100644 index 0000000..6f52dfb --- /dev/null +++ b/configure.d/60-storage.sh @@ -0,0 +1,210 @@ +#!/bin/bash + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="Network storage" +# shellcheck disable=SC2034 +DESCRIPTION="Mount shared folders from your network" + +# What's mounted, one smb://user@host/share per line. It exists once you've +# run this, even if you added nothing, so this isn't "to do" without a server. +STORAGE_CONF="$CONF_DIR/storage" +STORAGE_MOUNT="$CONNECTOR/system/storage-mount" +LABEL="computer.federated.connector.storage" +PLIST="$HOME/Library/LaunchAgents/$LABEL.plist" +source "$CONNECTOR/configure.d/lib/mdns.sh" +source "$CONNECTOR/configure.d/lib/smb.sh" + +is_configured() { + [ -f "$STORAGE_CONF" ] +} + +# launchd runs system/storage-mount at login and whenever the network changes +# (macOS rewrites SystemConfiguration then), so shares come back on their own +install_job() { + mkdir -p "$(dirname "$PLIST")" + cat > "$PLIST" << EOF +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>Label</key><string>$LABEL</string> + <key>ProgramArguments</key> + <array> + <string>/bin/bash</string> + <string>$(xml_escape "$STORAGE_MOUNT")</string> + </array> + <key>RunAtLoad</key><true/> + <key>WatchPaths</key> + <array> + <string>/Library/Preferences/SystemConfiguration</string> + </array> + <key>ThrottleInterval</key><integer>30</integer> + <key>ProcessType</key><string>Background</string> +</dict> +</plist> +EOF + launchctl bootout "gui/$(id -u)/$LABEL" 2> /dev/null + launchctl bootstrap "gui/$(id -u)" "$PLIST" +} + +remove_job() { + launchctl bootout "gui/$(id -u)/$LABEL" 2> /dev/null + rm -f "$PLIST" +} + +xml_escape() { + local s="$1" + s="${s//&/\&}" + s="${s//</\<}" + s="${s//>/\>}" + printf '%s' "$s" +} + +# Mount smb://[user@]host[/share] and record what was mounted. Without a +# share, macOS lists the server's shares to choose from. Its sign-in window +# can keep the password in your keychain, which mounting again later needs. +add_share() { + local url="$1" host before after line new=0 user share entry + host="$(host_of "$url")" + echo "macOS asks you to sign in to $host. Tick \"Remember this password in my" + echo "keychain\", so the share can be mounted again at login." + before="$(smb_mounts)" + if ! mount_share "$url"; then + if mounted_at "$url" > /dev/null; then + echo "$url is already mounted." + else + echo "$host's share wasn't mounted (wrong password, or cancelled)." + return 1 + fi + fi + after="$(smb_mounts)" + while IFS= read -r line; do + [ -n "$line" ] || continue + grep -qxF "$line" <<< "$before" && continue + # //user@host/share -> smb://user@<the host you gave>/share + entry="${line%%|*}" + entry="${entry#//}" + user="" + [[ "$entry" == *@* ]] && user="${entry%%@*}@" + share="${entry#*/}" + record "smb://$user$host/$share" "${line#*|}" + new=$((new + 1)) + done <<< "$after" + if [ $new -eq 0 ] && [[ "${url#smb://}" == */?* ]] && mounted_at "$url" > /dev/null; then + record "$url" "$(mounted_at "$url")" + fi +} + +record() { + local url="$1" point="$2" line + while IFS= read -r line; do + [ "$(share_key "$line")" = "$(share_key "$url")" ] && { echo "$url was already added."; return 0; } + done < "$STORAGE_CONF" + echo "$url" >> "$STORAGE_CONF" + [ -f "$PLIST" ] || install_job + echo "$url is at $point (in Finder's sidebar under Locations). It's mounted again at login." +} + +# Unmount it and take it out of the list +remove_share() { + local url="$1" point tmp + if point="$(mounted_at "$url")"; then + diskutil unmount "$point" > /dev/null 2>&1 || umount "$point" 2> /dev/null \ + || echo "Couldn't unmount $point; eject it in Finder." + fi + tmp="$(mktemp)" || return 1 + grep -vxF "$url" "$STORAGE_CONF" > "$tmp" + mv -f "$tmp" "$STORAGE_CONF" + [ -s "$STORAGE_CONF" ] || remove_job + echo "$url won't be mounted again. Its password stays in your keychain (Keychain Access)." +} + +# The SMB servers on the network, other than this Mac: "host|name" per line +find_servers() { + local own name host + own="$(mdns_own_host)" + mdns_services _smb._tcp | while IFS='|' read -r name _ host _; do + [ "$(tr '[:upper:]' '[:lower:]' <<< "$host")" = "$(tr '[:upper:]' '[:lower:]' <<< "$own")" ] && continue + echo "$host|$name" + done | sort -u +} + +find_and_add() { + local found=() line host name choice i + echo "Looking for shared folders on your network..." + while IFS= read -r line; do + found+=("$line") + done < <(find_servers) + if [ ${#found[@]} -eq 0 ]; then + echo "Nothing found. Windows PCs, NAS boxes and Macs with File Sharing on share folders" + echo "over SMB, but some don't announce it. Enter the address instead." + return 0 + fi + for i in "${!found[@]}"; do + IFS='|' read -r host name <<< "${found[$i]}" + printf ' %2d) %-26s %s\n' $((i + 1)) "$host" "$name" + done + read -rp "Which? " choice + if ! [[ "$choice" =~ ^[0-9]+$ ]] || [ "$choice" -lt 1 ] || [ "$choice" -gt ${#found[@]} ]; then + echo "Choose a number from the list." + return 1 + fi + add_share "smb://${found[$((choice - 1))]%%|*}" +} + +enter_and_add() { + local address + read -rp "Address, e.g. smb://nas.local/files (or smb://nas.local to choose a share): " address + case "$address" in + "") return 0 ;; + smb://?*) add_share "$address" ;; + *) echo "Start it with smb://. (Folders over SSH need macFUSE, which this doesn't set up.)" + return 1 ;; + esac +} + +choose_and_remove() { + local entries=() line choice i + while IFS= read -r line; do + [ -n "$line" ] && entries+=("$line") + done < "$STORAGE_CONF" + for i in "${!entries[@]}"; do + printf ' %2d) %s\n' $((i + 1)) "${entries[$i]}" + done + read -rp "Which? " choice + if ! [[ "$choice" =~ ^[0-9]+$ ]] || [ "$choice" -lt 1 ] || [ "$choice" -gt ${#entries[@]} ]; then + echo "Choose a number from the list." + return 1 + fi + remove_share "${entries[$((choice - 1))]}" +} + +run_configure() { + local choice url point + mkdir -p "$(dirname "$STORAGE_CONF")" && touch "$STORAGE_CONF" || return 1 + echo "This mounts shared folders from other machines on your network (Windows PCs, NAS" + echo "boxes, Macs with File Sharing on) and mounts them again each time you log in." + + while true; do + echo + if [ -s "$STORAGE_CONF" ]; then + while IFS='|' read -r url point; do + echo " $url ${point:-(not mounted now)}" + done < <(bash "$STORAGE_MOUNT" --list) + 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..912b538 --- /dev/null +++ b/configure.d/65-sandbox.sh @@ -0,0 +1,95 @@ +#!/bin/bash + +# configure reads TITLE and DESCRIPTION +# shellcheck disable=SC2034 +TITLE="Agent sandbox" +# shellcheck disable=SC2034 +DESCRIPTION="Choose what agents may read, e.g. iCloud Drive" + +# Your own sandbox config, which every sandboxed agent reads after +# sandbox/config/base.json (see sandbox/agent) +SANDBOX_CONF="$CONF_DIR/sandbox/base.json" +source "$CONNECTOR/configure.d/lib/json.sh" +source "$CONNECTOR/configure.d/lib/agents.sh" + +# Folders the sandbox hides from agents (sandbox/config/base.json) that you +# may let them read: "path|what it is". Your SSH keys, keychains, password +# managers, browsers, mail and messages 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. +# Cloud drives are hidden because they hold everything you've put in them, +# and reading a file macOS keeps only in the cloud downloads it. +# The paths are written as in base.json, with ~ for srt to expand +# shellcheck disable=SC2088 +OPTIONAL_HIDDEN=( + "~/Library/Mobile Documents|iCloud Drive" + "~/Library/CloudStorage|Nextcloud's and other cloud drives' files" +) + +# Offered once the sandbox is installed and one of the folders is on this Mac +is_installed() { + local entry path + srt_path > /dev/null || return 1 + 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() { + [ -f "$SANDBOX_CONF" ] \ + && json_get '(d.filesystem && d.filesystem.allowRead || []).indexOf(a[0]) >= 0' "$1" \ + < "$SANDBOX_CONF" > /dev/null +} + +let_read() { + json_edit "$SANDBOX_CONF" ' + d.filesystem = d.filesystem || {}; + var list = (d.filesystem.allowRead || []).filter(function (p) { return p !== a[0]; }); + list.push(a[0]); + d.filesystem.allowRead = list;' "$1" +} + +hide() { + [ -f "$SANDBOX_CONF" ] || return 0 + json_edit "$SANDBOX_CONF" ' + if (d.filesystem && d.filesystem.allowRead) { + d.filesystem.allowRead = d.filesystem.allowRead.filter(function (p) { return p !== a[0]; }); + }' "$1" +} + +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. 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="${YELLOW}agents can read it$RESET"; else state="${GREEN}hidden$RESET"; fi + printf " %d) %-28s %s %s\n" $((i + 1)) "$path" "$state" "$what" + done + echo " q) Done" + echo + read -rp "Choose one to switch: " choice || return 0 + if ! [[ "$choice" =~ ^[0-9]+$ ]] || [ "$choice" -lt 1 ] || [ "$choice" -gt ${#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..4d4daaa --- /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.d +# items and by 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:/opt/homebrew/bin:/usr/local/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="$(cd "$SANDBOX_BIN" 2> /dev/null && pwd -P)" + for dir in $PATH:$AGENT_DIRS; do + [ -n "$dir" ] && [ -d "$dir" ] || continue + [ "$(cd "$dir" && pwd -P)" = "$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:/opt/homebrew/bin:/usr/local/bin" command -v srt +} diff --git a/configure.d/lib/apps.sh b/configure.d/lib/apps.sh new file mode 100644 index 0000000..0090773 --- /dev/null +++ b/configure.d/lib/apps.sh @@ -0,0 +1,140 @@ +#!/bin/bash +# +# Purpose : Find the apps the Core's services need that macOS doesn't come +# with, and offer to download and install them. Source this file +# after lib/json.sh; it uses confirm_yes from configure. +# +# Each app is downloaded from its maker, and installed only if it's signed +# with the maker's Developer ID (the Team ID below) and Gatekeeper accepts it +# (it's notarized by Apple). The apps update themselves after that. +# +# To check an app's Team ID on a Mac where it's installed: +# codesign -dv /Applications/<App>.app 2>&1 | grep TeamIdentifier + +# app_info <name>: sets APP_TITLE, APP_BUNDLE, APP_TEAM, APP_KIND (dmg or +# pkg) and APP_URL. Nextcloud's URL changes with each release, so app_url +# looks it up. +app_info() { + case "$1" in + element) + APP_TITLE="Element" APP_BUNDLE="Element.app" APP_TEAM="7J4U792NQT" APP_KIND=dmg + APP_URL="https://packages.element.io/desktop/install/macos/Element.dmg" ;; + nextcloud) + APP_TITLE="Nextcloud" APP_BUNDLE="Nextcloud.app" APP_TEAM="NKUJUXUJ3B" APP_KIND=pkg + APP_URL="https://api.github.com/repos/nextcloud-releases/desktop/releases/latest" ;; + tailscale) + APP_TITLE="Tailscale" APP_BUNDLE="Tailscale.app" APP_TEAM="W5364U7YZB" APP_KIND=pkg + APP_URL="https://pkgs.tailscale.com/stable/Tailscale-latest-macos.pkg" ;; + *) return 1 ;; + esac +} + +# Where the app is installed, if it is +app_path() { + app_info "$1" || return 1 + if [ -d "/Applications/$APP_BUNDLE" ]; then + echo "/Applications/$APP_BUNDLE" + elif [ -d "$HOME/Applications/$APP_BUNDLE" ]; then + echo "$HOME/Applications/$APP_BUNDLE" + else + return 1 + fi +} + +app_installed() { + app_path "$1" > /dev/null +} + +# The download URL for app_info's app +app_url() { + case "$APP_URL" in + https://api.github.com/*) + curl -sf --max-time 30 "$APP_URL" \ + | json_get 'd.assets.map(function (x) { return x.browser_download_url; }) + .filter(function (u) { return /\.pkg$/.test(u); })[0]' ;; + *) echo "$APP_URL" ;; + esac +} + +# The Team ID a signed installer package or app is signed with +pkg_team() { + pkgutil --check-signature "$1" 2> /dev/null \ + | sed -nE 's/^ *1\. Developer ID Installer: .*\(([A-Z0-9]{10})\)$/\1/p' +} + +app_team() { + codesign -dv "$1" 2>&1 | sed -n 's/^TeamIdentifier=//p' +} + +verify_team() { + local what="$1" team="$2" + if [ "$team" != "$APP_TEAM" ]; then + echo "$RED$what isn't signed by $APP_TITLE's maker (Team ID ${team:-none}, not $APP_TEAM). Not installing it.$RESET" + return 1 + fi +} + +# Install a downloaded .pkg, once it's checked. The installer needs admin. +install_pkg() { + local pkg="$1" + verify_team "The download" "$(pkg_team "$pkg")" || return 1 + if ! spctl --assess --type install "$pkg" 2> /dev/null; then + echo "${RED}Gatekeeper doesn't accept the download (it isn't notarized). Not installing it.$RESET" + return 1 + fi + echo "Installing $APP_TITLE needs your Mac password." + sudo installer -pkg "$pkg" -target / > /dev/null +} + +# Copy the app out of a downloaded .dmg into /Applications, once it's checked +install_dmg() { + local dmg="$1" mount="$2/mount" app status=0 + hdiutil attach -nobrowse -readonly -noautoopen -mountpoint "$mount" "$dmg" > /dev/null || return 1 + app="$mount/$APP_BUNDLE" + if [ ! -d "$app" ]; then + echo "The download doesn't have $APP_BUNDLE in it." + status=1 + elif ! codesign --verify --deep --strict "$app" 2> /dev/null; then + echo "$RED$APP_BUNDLE's signature doesn't check out. Not installing it.$RESET" + status=1 + elif ! verify_team "$APP_BUNDLE" "$(app_team "$app")"; then + status=1 + elif ! spctl --assess --type execute "$app" 2> /dev/null; then + echo "${RED}Gatekeeper doesn't accept $APP_BUNDLE (it isn't notarized). Not installing it.$RESET" + status=1 + elif ! ditto "$app" "/Applications/$APP_BUNDLE" 2> /dev/null; then + echo "Copying $APP_TITLE to Applications needs your Mac password." + sudo ditto "$app" "/Applications/$APP_BUNDLE" || status=1 + fi + hdiutil detach -quiet "$mount" || hdiutil detach -quiet -force "$mount" + return $status +} + +# Download and install an app +app_install() { + local name="$1" url tmp status + app_info "$name" || return 1 + url="$(app_url)" + [ -n "$url" ] || { echo "Couldn't find where to download $APP_TITLE."; return 1; } + tmp="$(mktemp -d)" || return 1 + echo "Downloading $APP_TITLE from $url" + if curl -fL --progress-bar --max-time 1800 -o "$tmp/download.$APP_KIND" "$url"; then + "install_$APP_KIND" "$tmp/download.$APP_KIND" "$tmp" + status=$? + else + echo "Couldn't download $APP_TITLE." + status=1 + fi + rm -rf "$tmp" + [ $status -eq 0 ] && app_installed "$name" || return 1 + echo "Installed $APP_TITLE." +} + +# app_ensure <name> <why it's needed>: offer to install the app if it's +# missing. Fails if it's still missing. +app_ensure() { + app_installed "$1" && return 0 + echo "$APP_TITLE isn't on this Mac. $2" + confirm_yes "Download and install $APP_TITLE?" || return 1 + app_install "$1" +} diff --git a/configure.d/lib/json.sh b/configure.d/lib/json.sh new file mode 100644 index 0000000..7bcc039 --- /dev/null +++ b/configure.d/lib/json.sh @@ -0,0 +1,54 @@ +#!/bin/bash +# +# Purpose : Read and edit JSON for configure.d items. Source this file. +# +# macOS has no jq before macOS 15, and python3 needs the Command Line Tools, +# so this uses JavaScript for Automation (osascript -l JavaScript), which +# every macOS has. Expressions are JavaScript; the JSON is "d", and any +# arguments after the expression are a[0], a[1], ... so values never have to +# be pasted into the code. + +# json_get <expression> [args...] < file.json +# Prints the expression's value: strings as they are, anything else as JSON. +# Fails if the input isn't JSON, or the value is undefined, null, false or "". +# shellcheck disable=SC2016 +json_get() { + osascript -l JavaScript -e ' +function run(argv) { + ObjC.import("Foundation"); + var data = $.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile; + var text = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding).js; + var d = JSON.parse(text); + var v; + try { + v = (new Function("d", "a", "return (" + argv[0] + ");"))(d, argv.slice(1)); + } catch (e) { + v = undefined; + } + if (v === undefined || v === null || v === false || v === "") throw new Error("no value"); + return typeof v === "string" ? v : JSON.stringify(v); +}' "$@" 2> /dev/null +} + +# json_edit <file> <statements> [args...] +# Runs JavaScript statements that change "d", the file's JSON, and saves it. +# A missing or empty file starts as {}. Leaves the file alone if it isn't +# valid JSON. +# shellcheck disable=SC2016 +json_edit() { + local file="$1" + mkdir -p "$(dirname "$file")" || return 1 + osascript -l JavaScript -e ' +function run(argv) { + ObjC.import("Foundation"); + var path = argv[0]; + var s = $.NSString.stringWithContentsOfFileEncodingError(path, $.NSUTF8StringEncoding, null); + var text = s.isNil() ? "" : s.js; + var d = text.trim() === "" ? {} : JSON.parse(text); + (new Function("d", "a", argv[1]))(d, argv.slice(2)); + var out = $(JSON.stringify(d, null, 2) + "\n"); + if (!out.writeToFileAtomicallyEncodingError(path, true, $.NSUTF8StringEncoding, null)) { + throw new Error("could not write " + path); + } +}' "$@" > /dev/null 2>&1 || { echo "Couldn't change $file; is it valid JSON?"; return 1; } +} diff --git a/configure.d/lib/keychain.sh b/configure.d/lib/keychain.sh new file mode 100644 index 0000000..13bc5cd --- /dev/null +++ b/configure.d/lib/keychain.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# +# Purpose : Keep secrets in your login keychain. Source this file; the +# scripts in system/ do too. +# +# Items the security tool makes can be read back by it without asking, so +# background jobs (backups) can use them while you're logged in. + +# keychain_load <service> <account> +keychain_load() { + security find-generic-password -s "$1" -a "$2" -w 2> /dev/null +} + +# keychain_save <service> <account> <secret> +# Saved through security's interactive mode, so the secret isn't in the +# process list (printf is a shell builtin). That mode splits on spaces and +# reads quotes, so only secrets without them are taken: Nextcloud's app +# passwords and the passphrases this makes. +keychain_save() { + if [[ ! "$3" =~ ^[A-Za-z0-9+/=._-]+$ ]]; then + echo "That secret has characters the keychain helper can't save." >&2 + return 1 + fi + printf 'add-generic-password -U -s "%s" -a "%s" -l "%s" -w "%s"\n' "$1" "$2" "$1 ($2)" "$3" \ + | security -i > /dev/null 2>&1 \ + && [ "$(keychain_load "$1" "$2")" = "$3" ] +} + +# keychain_delete <service> <account> +keychain_delete() { + security delete-generic-password -s "$1" -a "$2" > /dev/null 2>&1 +} diff --git a/configure.d/lib/mdns.sh b/configure.d/lib/mdns.sh new file mode 100644 index 0000000..15577bd --- /dev/null +++ b/configure.d/lib/mdns.sh @@ -0,0 +1,81 @@ +#!/bin/bash +# +# Purpose : Find what's on the local network over mDNS (Bonjour), for the +# configure.d items that set up servers and storage on it. Source +# this file. +# +# macOS has dns-sd rather than avahi-browse. dns-sd keeps browsing until it's +# stopped, and macOS has no timeout command, so run_for stops it. + +# run_for <seconds> <command> [args]: run the command, and stop it after that +# many seconds +run_for() { + local seconds="$1" pid + shift + "$@" & + pid=$! + sleep "$seconds" + kill -INT "$pid" 2> /dev/null + wait "$pid" 2> /dev/null + return 0 +} + +# The instance names dns-sd -B lists, which can have spaces in them: they're +# the rest of each line from where the "Instance Name" heading starts +dns_sd_names() { + awk ' + /Instance Name/ { start = index($0, "Instance Name"); next } + start && $2 == "Add" { print substr($0, start) }' +} + +# The service types announced on the network, e.g. _smb._tcp +mdns_types() { + run_for 3 dns-sd -B _services._dns-sd._udp local. 2> /dev/null \ + | awk '$2 == "Add" { split($6, proto, "."); print $7 "." proto[1] }' | sort -u +} + +# The instances of a service type, one name per line +mdns_instances() { + run_for 3 dns-sd -B "$1" local. 2> /dev/null | dns_sd_names | sort -u +} + +# Where an instance is: "host port", host without the trailing dot +mdns_resolve() { + run_for 2 dns-sd -L "$1" "$2" local. 2> /dev/null \ + | sed -nE 's/.* can be reached at ([^ ]+)\.:([0-9]+).*/\1 \2/p' | head -n 1 +} + +# Every instance of the types given (or of all types): "name|type|host|port" +mdns_services() { + local dir types type name n=0 + dir="$(mktemp -d)" || return 1 + if [ $# -gt 0 ]; then types="$*"; else types="$(mdns_types)"; fi + for type in $types; do + mdns_instances "$type" > "$dir/browse.$type" & + done + wait + for type in $types; do + while IFS= read -r name; do + [ -n "$name" ] || continue + n=$((n + 1)) + # shellcheck disable=SC2046 + ( set -- $(mdns_resolve "$name" "$type") + [ -n "$1" ] && printf '%s|%s|%s|%s\n' "$name" "$type" "$1" "$2" ) > "$dir/resolve.$n" & + done < "$dir/browse.$type" + done + wait + cat "$dir"/resolve.* 2> /dev/null | sort -u + rm -rf "$dir" +} + +# This Mac's own .local name, which mdns_hosts leaves out +mdns_own_host() { + echo "$(scutil --get LocalHostName 2> /dev/null).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 -fu +} diff --git a/configure.d/lib/nextcloud.sh b/configure.d/lib/nextcloud.sh new file mode 100644 index 0000000..67da519 --- /dev/null +++ b/configure.d/lib/nextcloud.sh @@ -0,0 +1,70 @@ +#!/bin/bash +# +# Purpose : Nextcloud app passwords for configure.d items, and keeping them in +# your login keychain. Source this file after lib/json.sh +# and lib/keychain.sh. + +KEYCHAIN_SERVICE="Federated Connector" + +# Basic auth header for curl, read from stdin (-H @-) so the password isn't +# in the process list (printf is a shell builtin) +auth_header() { + printf 'Authorization: Basic %s\n' "$(printf '%s:%s' "$1" "$2" | base64 | tr -d '\n')" +} + +# Create a Nextcloud app password, so this Mac doesn't keep your Core +# password for Calendar and Contacts. 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 --max-time 30 -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="$(json_get 'd.ocs.data.apppassword' <<< "${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 --max-time 30 -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 --max-time 30 -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 +} + +# The app password this Mac gave Calendar and Contacts is kept in your login +# keychain too, so it can be put in the profile again (e.g. when your Core +# password changes) without making another, and revoked when you remove the +# Core. Uses KEYCHAIN_ACCOUNT. + +app_password_load() { + keychain_load "$KEYCHAIN_SERVICE" "$KEYCHAIN_ACCOUNT" +} + +app_password_save() { + keychain_save "$KEYCHAIN_SERVICE" "$KEYCHAIN_ACCOUNT" "$1" +} + +app_password_delete() { + keychain_delete "$KEYCHAIN_SERVICE" "$KEYCHAIN_ACCOUNT" +} diff --git a/configure.d/lib/profile.sh b/configure.d/lib/profile.sh new file mode 100644 index 0000000..9c2cdbd --- /dev/null +++ b/configure.d/lib/profile.sh @@ -0,0 +1,87 @@ +#!/bin/bash +# +# Purpose : Configuration profiles (.mobileconfig) for configure.d items. +# Source this file; it uses wait_until from configure. +# +# A configuration profile is how macOS itself sets up Mail, Calendar and +# Contacts accounts: each account is a payload in the profile, and installing +# the profile adds the accounts, with their passwords in the keychain. +# Removing the profile removes them again. +# +# Since macOS 11 only you can install a profile (profiles install no longer +# works without device management), so profile_install opens it, which puts +# it under Downloaded in System Settings > Profiles, and waits until you've +# installed it there. A profile with the same PayloadIdentifier as one that's +# installed replaces it, and payloads keep their PayloadUUID between versions, +# so the accounts are changed rather than added again. + +PROFILES_PANE="x-apple.systempreferences:com.apple.Profiles-Settings.extension" + +xml_escape() { + local s="$1" + s="${s//&/\&}" + s="${s//</\<}" + s="${s//>/\>}" + s="${s//\"/\"}" + printf '%s' "$s" +} + +# The same UUID each time for the same name, so a payload is the same account +# in each version of the profile +stable_uuid() { + md5 -q -s "$1" | tr a-f A-F \ + | sed -E 's/^(.{8})(.{4})(.{4})(.{4})(.{12})$/\1-\2-\3-\4-\5/' +} + +# The installed configuration profiles, as XML. The form of the command +# changed in macOS 10.13; the old one still works on some versions. +profiles_xml() { + profiles show -type configuration -output stdout-xml 2> /dev/null \ + || profiles -P -o stdout-xml 2> /dev/null +} + +# profile_installed <identifier> [uuid]: with a UUID, only that version +profile_installed() { + local xml + xml="$(profiles_xml)" || return 1 + grep -qF "<string>$1</string>" <<< "$xml" || return 1 + [ -z "$2" ] || grep -qF "<string>$2</string>" <<< "$xml" +} + +# profile_install <file> <identifier> <uuid> <name> +# Opens the profile and waits for you to install it in System Settings. The +# file has passwords in it, so the caller deletes it afterwards either way. +profile_install() { + local file="$1" id="$2" uuid="$3" name="$4" + open "$file" || return 1 + sleep 1 + open "$PROFILES_PANE" 2> /dev/null + echo + echo "System Settings shows \"$name\" under Downloaded (in Privacy & Security >" + echo "Profiles, or General > Device Management). Double-click it, choose Install," + echo "and enter your Mac password when asked." + if wait_until 480 profile_installed "$id" "$uuid"; then + echo "Installed \"$name\"." + return 0 + fi + echo "\"$name\" wasn't installed. macOS forgets a downloaded profile after a few" + echo "minutes; to try again, run this again." + return 1 +} + +# Removing a profile you installed yourself works from the command line on +# most versions of macOS; if it doesn't, you remove it in System Settings. +profile_remove() { + local id="$1" name="$2" + profile_installed "$id" || return 0 + profiles remove -identifier "$id" > /dev/null 2>&1 \ + || profiles -R -p "$id" > /dev/null 2>&1 + profile_installed "$id" || return 0 + open "$PROFILES_PANE" 2> /dev/null + echo "In System Settings > Profiles, choose \"$name\", then the - button to remove it." + wait_until 300 not_installed "$id" +} + +not_installed() { + ! profile_installed "$1" +} diff --git a/configure.d/lib/smb.sh b/configure.d/lib/smb.sh new file mode 100644 index 0000000..9fefc75 --- /dev/null +++ b/configure.d/lib/smb.sh @@ -0,0 +1,47 @@ +#!/bin/bash +# +# Purpose : SMB shares: which are mounted, and mounting one the way Finder +# does. Sourced by configure.d/60-storage.sh and system/storage-mount. + +# smb://user@host/share and //user@host/share (as mount shows it) the same +# way: no user, lower case, host without .local or Bonjour's ._smb._tcp.local, +# %20 as a space +share_key() { + local s="${1#smb:}" host share + s="${s#//}" + s="${s#*@}" + host="${s%%/*}" + share="${s#*/}" + host="${host%._smb._tcp.local}" + host="${host%.local}" + host="${host%.}" + echo "$host/${share//%20/ }" | tr '[:upper:]' '[:lower:]' +} + +# The SMB shares mounted now: "//user@host/share|mount point" per line +smb_mounts() { + mount -t smbfs | sed -nE 's#^(//[^ ]+) on (.+) \(smbfs.*#\1|\2#p' +} + +# The mount point of a share, if it's mounted +mounted_at() { + local key line + key="$(share_key "$1")" + while IFS= read -r line; do + if [ "$(share_key "${line%%|*}")" = "$key" ]; then + echo "${line#*|}" + return 0 + fi + done < <(smb_mounts) + return 1 +} + +host_of() { + local s="${1#*://}" + s="${s#*@}" + echo "${s%%/*}" +} + +mount_share() { + osascript -e 'on run argv' -e 'mount volume (item 1 of argv)' -e 'end run' "$1" > /dev/null 2>&1 +} diff --git a/configure.d/lib/tools.sh b/configure.d/lib/tools.sh new file mode 100644 index 0000000..e71d35b --- /dev/null +++ b/configure.d/lib/tools.sh @@ -0,0 +1,144 @@ +#!/bin/bash +# +# Purpose : Find the command-line tools some items need (restic and rclone +# for backups; Node.js and Anthropic's sandbox runtime, srt, for the +# agent sandbox), and offer to download them. Source this file after +# lib/json.sh; it uses confirm_yes from configure. +# +# A tool already installed, e.g. with Homebrew, is used as it is. Otherwise +# it's downloaded from its maker's releases into TOOLS, checked against the +# SHA-256 sums the release publishes, and kept to itself there: nothing in +# /usr/local or your shell changes. These are command-line programs, not +# apps, so they aren't notarized; downloaded with curl, Gatekeeper doesn't +# quarantine them. + +TOOLS="$HOME/.local/share/federated-connector" +TOOLS_BIN="$TOOLS/bin" + +# Where to look for a tool, in order. launchd jobs start with a short PATH, +# so Homebrew's directories are named too. +TOOLS_PATH="$TOOLS_BIN:$TOOLS/node/bin:$TOOLS/srt/bin:/opt/homebrew/bin:/usr/local/bin" + +# The full path of a tool, if it's installed +tool_path() { + PATH="$TOOLS_PATH:$PATH" command -v "$1" +} + +# restic and rclone name the architectures differently from Node +machine_arch() { + case "$(uname -m)" in + arm64) echo arm64 ;; + *) echo amd64 ;; + esac +} + +# 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="$(shasum -a 256 "$dest" | cut -d' ' -f1)" + if [ -z "$expected" ] || [ "$expected" != "$actual" ]; then + echo "${RED}The download doesn't match the checksum its release publishes. Not installing it.$RESET" + rm -f "$dest" + return 1 + fi +} + +install_restic() { + local tmp version name status=1 + version="$(curl -fsL --max-time 30 https://api.github.com/repos/restic/restic/releases/latest \ + | json_get 'd.tag_name.replace(/^v/, "")')" || { echo "Couldn't find restic's latest release."; return 1; } + name="restic_${version}_darwin_$(machine_arch).bz2" + tmp="$(mktemp -d)" || return 1 + if download_checked "https://github.com/restic/restic/releases/download/v$version/$name" \ + "https://github.com/restic/restic/releases/download/v$version/SHA256SUMS" "$name" "$tmp/$name" \ + && bunzip2 "$tmp/$name" && mkdir -p "$TOOLS_BIN" \ + && install -m 755 "$tmp/${name%.bz2}" "$TOOLS_BIN/restic"; then + status=0 + fi + rm -rf "$tmp" + return $status +} + +install_rclone() { + local tmp version name status=1 + version="$(curl -fsL --max-time 30 https://downloads.rclone.org/version.txt | sed -n 's/^rclone v//p')" + [ -n "$version" ] || { echo "Couldn't find rclone's latest release."; return 1; } + name="rclone-v$version-osx-$(machine_arch).zip" + tmp="$(mktemp -d)" || return 1 + if download_checked "https://downloads.rclone.org/v$version/$name" \ + "https://downloads.rclone.org/v$version/SHA256SUMS" "$name" "$tmp/$name" \ + && unzip -q "$tmp/$name" -d "$tmp" && mkdir -p "$TOOLS_BIN" \ + && install -m 755 "$tmp/${name%.zip}/rclone" "$TOOLS_BIN/rclone"; then + status=0 + fi + rm -rf "$tmp" + return $status +} + +# srt needs Node.js 22.12 or later +node_ok() { + local node version + node="$(tool_path node)" || return 1 + version="$("$node" -p 'process.versions.node' 2> /dev/null)" || return 1 + [ "$(printf '%s\n' 22.12.0 "$version" | sort -t. -k1,1n -k2,2n -k3,3n | head -n 1)" = 22.12.0 ] +} + +# The current long-term support release, kept in TOOLS/node +install_node() { + local tmp version arch name status=1 + version="$(curl -fsL --max-time 30 https://nodejs.org/dist/index.json \ + | json_get 'd.filter(function (x) { return x.lts; })[0].version')" \ + || { echo "Couldn't find Node.js' current release."; return 1; } + case "$(uname -m)" in arm64) arch=arm64 ;; *) arch=x64 ;; esac + name="node-$version-darwin-$arch.tar.gz" + 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 -xzf "$tmp/$name" -C "$tmp" && mkdir -p "$TOOLS"; then + rm -rf "$TOOLS/node" && mv "$tmp/${name%.tar.gz}" "$TOOLS/node" && status=0 + fi + rm -rf "$tmp" + return $status +} + +# srt from npm, into TOOLS/srt, with the Node.js found or installed. 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 npm + node_ok || install_node || return 1 + npm="$(dirname "$(tool_path node)")/npm" + PATH="$(dirname "$npm"):$PATH" "$npm" install --global --prefix "$TOOLS/srt" \ + --no-fund --no-audit --ignore-scripts @anthropic-ai/sandbox-runtime > /dev/null +} + +tool_title() { + case "$1" in + restic) echo "restic (backups)" ;; + rclone) echo "rclone (reaches your Nextcloud files for restic)" ;; + node) echo "Node.js (runs the sandbox)" ;; + srt) echo "the sandbox runtime (srt, from Anthropic)" ;; + esac +} + +# tool_ensure <name>...: offer to install the tools that are missing. Fails if +# any is still missing. +tool_ensure() { + local name missing=() + for name in "$@"; do + tool_path "$name" > /dev/null || missing+=("$name") + done + [ ${#missing[@]} -eq 0 ] && return 0 + echo "This needs:" + for name in "${missing[@]}"; do + echo " - $(tool_title "$name")" + done + confirm_yes "Download and install them (into $TOOLS)?" || return 1 + for name in "${missing[@]}"; do + "install_$name" || { echo "$RED$(tool_title "$name") was not installed.$RESET"; return 1; } + echo "Installed $(tool_title "$name")." + done +} diff --git a/sandbox/agent b/sandbox/agent new file mode 100755 index 0000000..7c58ec6 --- /dev/null +++ b/sandbox/agent @@ -0,0 +1,132 @@ +#!/bin/bash +# +# Purpose : Run an AI agent inside Anthropic's sandbox runtime (srt). On +# macOS, srt uses Seatbelt (sandbox-exec) to limit which files the +# agent can read and write, and lets it reach the network only +# through a proxy that lets through the domains in its config. +# +# sandbox/bin/<agent> links here, and `configure agents` puts sandbox/bin +# first on PATH, 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 base.json and <agent>.json in ~/Library/Application Support/ +# Federated Connector/sandbox, in the same format. Later files add to the +# lists in earlier ones. Domains in FEDERATED_SANDBOX_DOMAINS (space- +# separated) are allowed too. + +# Wrapped in { ...; exit; } so bash reads the whole script up front; an update +# may replace this file while agents are running. +{ + +# This script, through the link in sandbox/bin +self="$0" +while [ -L "$self" ]; do + link="$(readlink "$self")" + case "$link" in + /*) self="$link" ;; + *) self="$(dirname "$self")/$link" ;; + esac +done +SANDBOX="$(cd "$(dirname "$self")" && pwd -P)" +CONNECTOR="$(dirname "$SANDBOX")" +USER_CONFIG="$HOME/Library/Application Support/Federated Connector/sandbox" +name="$(basename "$0")" +source "$CONNECTOR/configure.d/lib/agents.sh" || exit 1 + +if [ "$name" = "unsandboxed" ]; then + if [ $# -eq 0 ]; then + echo "Usage: unsandboxed <agent> [arguments]" + exit 2 + fi + agent="$1" + shift + real="$(agent_path "$agent")" || { echo "$agent isn't installed."; exit 127; } + exec "$real" "$@" +fi + +agent="$name" +real="$(agent_path "$agent")" || { echo "$agent isn't installed. To install it: configure agents"; exit 127; } + +# Commands that share another agent's sandbox config +case "$agent" in + hermes-agent) profile=hermes ;; + *) profile="$agent" ;; +esac + +srt="$(srt_path)" +if [ -z "$srt" ]; then + echo "The sandbox (srt) isn't installed; run: configure agents. To run $agent without it: unsandboxed $agent" + exit 1 +fi +# srt is a Node.js program; its own Node.js, if it has one, comes first +PATH="$(dirname "$srt"):$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") +for file in "$USER_CONFIG/base.json" "$USER_CONFIG/$profile.json"; do + [ -f "$file" ] && configs+=("$file") +done + +# Outside the folders the agent may change, so it can't change its own rules. +# Named after this process, as srt replaces it (exec below) and nothing is +# left to remove it afterwards; files whose process has ended are removed here. +SETTINGS_DIR="${TMPDIR:-/tmp}/federated-sandbox" +mkdir -m 700 "$SETTINGS_DIR" 2> /dev/null || [ -d "$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 +settings="$SETTINGS_DIR/$agent.$$.json" + +# Objects are merged and lists joined, so later files only add to earlier ones +# shellcheck disable=SC2016 +if ! osascript -l JavaScript -e ' +function run(argv) { + ObjC.import("Foundation"); + function read(path) { + var s = $.NSString.stringWithContentsOfFileEncodingError(path, $.NSUTF8StringEncoding, null); + if (s.isNil()) throw new Error("could not read " + path); + return JSON.parse(s.js); + } + function merge(a, b) { + Object.keys(b).forEach(function (k) { + var x = a[k], y = b[k]; + if (Array.isArray(x) && Array.isArray(y)) { + a[k] = x.concat(y.filter(function (v) { return x.indexOf(v) < 0; })); + } else if (x && y && typeof x === "object" && typeof y === "object" && !Array.isArray(x)) { + merge(x, y); + } else { + a[k] = y; + } + }); + return a; + } + var out = argv[0], domains = argv[1].split(" ").filter(function (d) { return d; }); + var config = argv.slice(2).reduce(function (c, path) { return merge(c, read(path)); }, {}); + config.network = config.network || {}; + merge(config.network, {allowedDomains: domains}); + if (!$(JSON.stringify(config, null, 2)).writeToFileAtomicallyEncodingError(out, true, $.NSUTF8StringEncoding, null)) { + throw new Error("could not write " + out); + } +}' "$settings" "$FEDERATED_SANDBOX_DOMAINS" "${configs[@]}" > /dev/null; then + echo "Couldn't read the sandbox config: ${configs[*]}" + exit 1 +fi +chmod 600 "$settings" + +# On macOS the sandbox lets the agent reach the network only through srt's +# proxy, so nothing may go around it: srt would otherwise tell it to connect +# directly to private addresses (192.168.x.x and so on) and localhost, which +# the sandbox then blocks. Through the proxy, a server on your network that +# the config allows, e.g. one from `configure ai-servers`, can be reached. +exec "$srt" --settings "$settings" -- env NO_PROXY= no_proxy= "$real" "$@" +} 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..1d009a6 --- /dev/null +++ b/sandbox/config/base.json @@ -0,0 +1,107 @@ +{ + "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", + "formulae.brew.sh", + "ghcr.io", + "*.ghcr.io" + ], + "deniedDomains": [] + }, + "filesystem": { + "denyRead": [ + "~/.ssh", + "~/.gnupg", + "~/.password-store", + "~/Library/Keychains", + "~/.netrc", + "~/.git-credentials", + "~/.aws", + "~/.azure", + "~/.config/gcloud", + "~/.kube", + "~/.docker", + "~/.config/gh", + "~/.config/tea", + "~/Library/Application Support/Bitwarden", + "~/Library/Application Support/1Password", + "~/Library/Group Containers/2BUA8C4S2C.com.1password", + "~/Library/Application Support/Element", + "~/Library/Application Support/Signal", + "~/Library/Application Support/Telegram Desktop", + "~/Library/Application Support/Federated Connector", + "~/Library/Preferences/Nextcloud", + + "~/Library/Safari", + "~/Library/Cookies", + "~/Library/Containers/com.apple.Safari", + "~/Library/Application Support/Google/Chrome", + "~/Library/Application Support/Chromium", + "~/Library/Application Support/BraveSoftware", + "~/Library/Application Support/Firefox", + "~/Library/Application Support/zen", + "~/Library/Application Support/Arc", + "~/Library/Application Support/Vivaldi", + "~/Library/Application Support/Microsoft Edge", + "~/Library/Application Support/net.imput.helium", + + "~/Library/Mail", + "~/Library/Messages", + "~/Library/Calendars", + "~/Library/Application Support/AddressBook", + "~/Library/Group Containers/group.com.apple.notes", + "~/Library/Mobile Documents", + "~/Library/CloudStorage", + + "~/.claude", + "~/.claude.json", + "~/.hermes", + "~/.config/opencode", + "~/.local/share/opencode" + ], + "allowRead": [], + "allowWrite": [ + ".", + "/tmp", + "/private/tmp", + "~/.npm", + "~/Library/Caches/pip", + "~/.cargo/registry", + "~/.cargo/git", + "~/go/pkg/mod" + ], + "denyWrite": [] + }, + "allowPty": true +} diff --git a/sandbox/config/hermes.json b/sandbox/config/hermes.json new file mode 100644 index 0000000..4a09a1d --- /dev/null +++ b/sandbox/config/hermes.json @@ -0,0 +1,13 @@ +{ + "network": { + "allowedDomains": [] + }, + "filesystem": { + "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/smoketest/README.md b/smoketest/README.md new file mode 100644 index 0000000..01267be --- /dev/null +++ b/smoketest/README.md @@ -0,0 +1,82 @@ +# Smoketest + +These tests run `configure`'s pieces on real macOS, in throwaway virtual machines made with [Tart](https://tart.run) on an Apple silicon Mac. They check what can't be checked on Linux: + +- macOS' bash 3.2 +- JavaScript for Automation, the keychain and `profiles` +- `dns-sd` +- Seatbelt, which srt's sandbox uses +- launchd +- Gatekeeper and code signatures +- real downloads + +## Running it + +On an Apple silicon Mac: + +``` +brew install cirruslabs/cli/tart +smoketest/run --list # scenarios and their tier +smoketest/run # the quick scenarios +smoketest/run --tier all # everything, including the big downloads +smoketest/run 60-backup # one scenario (or: smoketest/run 60) +smoketest/run --keep 50 # leave the VM running afterwards, to look around +smoketest/run --image ghcr.io/cirruslabs/macos-sequoia-vanilla:latest # another macOS +``` + +It tests the working copy as it is, including uncommitted changes. The first run downloads the image, about 25 GB. After that, each scenario takes a minute or two plus its own work. The backup scenario takes a few minutes, and `70-apps` downloads about 400 MB. + +Each run writes its logs to `smoketest/results/<time>/`, one per scenario, and prints which scenarios passed. + +## How it works + +Each scenario runs on a fresh clone of Cirrus Labs' **vanilla** macOS image (default: Tahoe): + +- **What's in it:** macOS as it comes, with auto-login and a user `admin` (password `admin`) who has passwordless sudo. +- **Why vanilla:** the "base" images come with Homebrew, Node.js and jq. Those would hide the paths a new Mac takes, where `configure` has to download its tools. +- **Gatekeeper:** the vanilla image switches Gatekeeper off, so `70-apps` switches it back on before testing downloads. + +`run` drives each scenario from your Mac: + +1. Clones the image with `tart clone` and starts it with `tart run --no-graphics`. +2. Puts a throwaway SSH key in the VM. The password `admin` is entered once, through `SSH_ASKPASS`. +3. Copies the working copy to `~/connector` in the VM. +4. Runs `lib/runner.sh` with the scenario in the VM's desktop session, through `launchctl asuser`. That is where `configure`'s GUI pieces run on a real Mac: `open`, launchd's gui domain, the unlocked login keychain. An SSH session isn't. +5. Stops and deletes the VM, unless `--keep` is given. + +## Scenarios + +| Scenario | Checks | +|----------|--------| +| `00-environment` | Every script parses with `/bin/bash` 3.2. None uses a tool macOS lacks: no python3, which would start installing the Command Line Tools, and no jq, timeout or mapfile. The macOS tools used are all there. | +| `10-configure` | `configure --help`, `--list` (nothing on stderr; agent sign-ins hidden until installed), the menu, and an item's questions | +| `20-json-keychain` | `json_get` and `json_edit` through real `osascript`; saving, replacing and deleting keychain secrets | +| `30-core-local` | The profile: valid, passwords and names survive escaping, stable payload UUIDs, and the format of `profiles show -output stdout-xml`. Superpanel's app: built, re-signed after the icon changes, and it opens. Element's config, and `nextcloud.cfg` matching | +| `40-mdns` | `dns-sd` output comes through a pipe and is stopped on time; the VM finds its own `_ssh._tcp` and resolves its `.local` name | +| `50-sandbox` | Node.js and srt download and install. A stand-in agent in the sandbox can't read `~/.ssh` or the keychains, and can't write outside its project. It can use /tmp, mktemp and a pty. It reaches allowed sites only. It reaches a local LLM server only once `ai-servers` allows it. A new zsh finds the sandboxed command first. | +| `60-backup` | restic and rclone download. A local WebDAV server stands in for Nextcloud. The Federated Backup app is built and answers whether it has Full Disk Access. launchd runs a backup, a snapshot appears, a file restores from it, and a second run the same day does nothing. Turning backups off removes the app and the job. | +| `70-apps` *(all)* | With Gatekeeper on: an un-notarized app is turned down, and a package signed by the wrong Team ID is refused. Element, Nextcloud and Tailscale download and install, and their Team IDs match `apps.sh`. Nextcloud opens with the Core's address. | +| `80-storage` | The launchd job is added with the first share and removed with the last; a share whose server can't be reached is skipped quickly without asking | + +## What still needs a person + +macOS deliberately allows these only with a click, so test them by hand on a VM (`--keep`) or a Mac. Each scenario notes which apply to it as a `skip` line. + +- **Installing the profile:** in System Settings > Profiles, choose "Federated Core (...)", then Install. Then check Mail, Calendar and Contacts against a real Core. `configure core` notices the profile was installed. +- **Full Disk Access for Federated Backup:** after granting it, `configure backup` says it can read all your files, and the backup log no longer has permission errors for Documents and Desktop. +- **Mounting a real SMB share:** the sign-in window, "Remember this password in my keychain", and whether `mount volume "smb://host"` without a share offers a list of shares. +- **Tailscale's VPN approval**, and **Nextcloud's sign-in** in the browser. + +## Writing a scenario + +A scenario is a bash file in `scenarios/` that sets `DESCRIPTION` and `TIER`, either `quick` or `all`, and defines `scenario`. It runs in the VM 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. 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 100644 index 0000000..e1f01c3 --- /dev/null +++ b/smoketest/lib/runner.sh @@ -0,0 +1,100 @@ +#!/bin/bash +# +# Purpose : Run one smoketest scenario inside the VM (smoketest/run starts +# this in the desktop session). 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. + +CONNECTOR="$HOME/connector" +CONF_DIR="$HOME/Library/Application Support/Federated Connector" +COMPUTER="$(scutil --get ComputerName 2> /dev/null || hostname -s)" +RED=$'\033[31m' GREEN=$'\033[32m' YELLOW=$'\033[33m' BOLD=$'\033[1m' RESET=$'\033[0m' +export PATH="/usr/bin:/bin:/usr/sbin:/sbin" +export TMPDIR="${TMPDIR:-$(getconf DARWIN_USER_TEMP_DIR)}" +FAILURES=0 + +# configure's questions, answered yes; ask takes the default +confirm() { echo "$1 [y/N] y"; return 0; } +confirm_yes() { echo "$1 [Y/n] y"; return 0; } +ask() { printf -v "$1" '%s' "$3"; } + +# wait_until without reading stdin: try every 2 seconds for up to $1 +wait_until() { + local seconds="$1" waited=0 + shift + while [ "$waited" -lt "$seconds" ]; do + "$@" && return 0 + sleep 2 + waited=$((waited + 2)) + done + "$@" +} + +# 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" +} + +# A step whose output is worth seeing, run as it is +step() { + echo "-- $*" +} + +# The VM's login keychain is open in the desktop session; ssh's wouldn't be +security unlock-keychain -p admin "$HOME/Library/Keychains/login.keychain-db" 2> /dev/null + +cd "$HOME" || exit 1 +# shellcheck disable=SC1090 +source "$1" || { echo "Couldn't read $1"; exit 1; } +echo "$DESCRIPTION" +echo "(macOS $(sw_vers -productVersion), $(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..5b7f12f --- /dev/null +++ b/smoketest/run @@ -0,0 +1,181 @@ +#!/bin/bash +# +# Purpose : Run the smoketest scenarios, each in a fresh macOS VM, with Tart +# on an Apple silicon Mac. See README.md. +# +# Usage: smoketest/run [--image REF] [--tier quick|all] [--keep] [scenario...] +# smoketest/run --list +# +# Runs with the bash macOS comes with (3.2). + +# Wrapped in { ...; exit; } so bash reads the whole script up front +{ + +SMOKETEST="$(cd "$(dirname "$0")" && pwd)" +REPO="$(dirname "$SMOKETEST")" +IMAGE="ghcr.io/cirruslabs/macos-tahoe-vanilla:latest" +TIER=quick +KEEP=0 +SCENARIOS=() +# The vanilla images' user; it has passwordless sudo and logs in by itself +VM_USER="admin" +VM_PASSWORD="admin" + +usage() { + cat << EOF +Usage: smoketest/run [options] [scenario...] + + --image REF Tart image to clone (default: $IMAGE) + --tier quick|all quick leaves out the slow scenarios (default: quick) + --keep Leave each VM running afterwards, to look around in it + --list List the scenarios and their tier + +Scenarios are named by file name or number, e.g. 60-backup or 60. +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 + --image) IMAGE="$2"; shift 2 ;; + --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 + +if [ "$(uname -s)" != Darwin ] || [ "$(uname -m)" != arm64 ]; then + echo "Tart runs macOS VMs on Apple silicon Macs only." + exit 1 +fi +command -v tart > /dev/null || { echo "Tart isn't installed: brew install cirruslabs/cli/tart"; 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 +} + +RESULTS="$SMOKETEST/results/$(date +%Y%m%d-%H%M%S)" +mkdir -p "$RESULTS" +KEY="$RESULTS/id_ed25519" +ssh-keygen -q -t ed25519 -N '' -f "$KEY" || exit 1 + +# Answers ssh's password question once, to put the key in the VM +ASKPASS="$RESULTS/askpass" +printf '#!/bin/sh\necho %s\n' "$VM_PASSWORD" > "$ASKPASS" +chmod 700 "$ASKPASS" + +SSH_OPTS=(-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR + -o ConnectTimeout=5 -o ServerAliveInterval=15) + +vm_ssh() { + ssh "${SSH_OPTS[@]}" -i "$KEY" -o BatchMode=yes "$VM_USER@$IP" "$@" +} + +# Clone the image, start it and wait until ssh with the key works +vm_start() { + local name="$1" i + echo " Cloning $IMAGE (the first time downloads it, about 25 GB)..." + tart clone "$IMAGE" "$name" || return 1 + tart run --no-graphics "$name" > "$RESULTS/$name.tart.log" 2>&1 & + IP="$(tart ip --wait 180 "$name")" || { echo " The VM didn't get an address."; return 1; } + for i in $(seq 1 60); do + SSH_ASKPASS="$ASKPASS" SSH_ASKPASS_REQUIRE=force DISPLAY=none \ + ssh "${SSH_OPTS[@]}" -o PubkeyAuthentication=no "$VM_USER@$IP" \ + 'mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys' \ + < "$KEY.pub" 2> /dev/null && break + sleep 5 + done + vm_ssh true || { echo " Couldn't ssh to the VM at $IP."; return 1; } + # The VM logs in by itself; wait for its desktop session, which the + # scenarios run in + for i in $(seq 1 60); do + vm_ssh 'pgrep -x Dock > /dev/null' && return 0 + sleep 5 + done + echo " The VM's desktop session didn't start." + return 1 +} + +# The working copy, as it is now, to ~/connector in the VM +vm_copy() { + COPYFILE_DISABLE=1 tar -C "$REPO" --exclude ./.claude --exclude ./smoketest/results \ + --exclude ./.git -czf - . | vm_ssh 'rm -rf ~/connector && mkdir ~/connector && tar -xzf - -C ~/connector' +} + +# Run in the desktop session (launchctl asuser), as macOS' GUI pieces +# (open, launchd's gui domain, Gatekeeper, the keychain) expect, rather than +# in ssh's own session +vm_scenario() { + vm_ssh "sudo launchctl asuser \$(id -u) sudo -u $VM_USER -H /bin/bash ~/connector/smoketest/lib/runner.sh ~/connector/smoketest/scenarios/$1" +} + +vm_stop() { + local name="$1" + if [ $KEEP -eq 1 ]; then + echo " Kept $name running at $IP (ssh -i \"$KEY\" $VM_USER@$IP). Afterwards: tart stop $name; tart delete $name" + return 0 + fi + tart stop "$name" > /dev/null 2>&1 + tart delete "$name" > /dev/null 2>&1 +} + +PASSED=() FAILED=() +FILES=() +while IFS= read -r file; do + FILES+=("$file") +done < <(pick) +if [ ${#FILES[@]} -eq 0 ]; then + echo "No scenarios to run. smoketest/run --list shows them." + exit 2 +fi + +for file in "${FILES[@]}"; do + scenario="$(basename "$file" .sh)" + name="connector-smoke-$scenario-$$" + log="$RESULTS/$scenario.log" + echo + echo "== $scenario: $(scenario_var "$file" DESCRIPTION)" + if vm_start "$name" && vm_copy; then + vm_scenario "$(basename "$file")" 2>&1 | tee "$log" + status=${PIPESTATUS[0]} + else + status=1 + echo " The VM didn't start; see $RESULTS/$name.tart.log" | tee "$log" + fi + vm_stop "$name" + 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/00-environment.sh b/smoketest/scenarios/00-environment.sh new file mode 100644 index 0000000..959c381 --- /dev/null +++ b/smoketest/scenarios/00-environment.sh @@ -0,0 +1,37 @@ +# shellcheck shell=bash +DESCRIPTION="The scripts parse with macOS' bash 3.2, and the macOS tools they use are there" +TIER=quick + +# Patterns, expanded in CONNECTOR +SCRIPTS=("configure" "configure.d/*.sh" "configure.d/lib/*.sh" "system/backup" "system/backup-env.sh" + "system/storage-mount" "sandbox/agent" "smoketest/run" "smoketest/lib/runner.sh") + +# Commands that macOS doesn't have, or that would start installing the +# Command Line Tools if called (python3), outside comments +uses_missing_tools() { + (cd "$CONNECTOR" && grep -nE '(^|[^#[:alnum:]_-])(python3|jq|gsed|gawk|timeout|realpath|mapfile|readarray|declare -A)([^[:alnum:]_-]|$)' \ + configure configure.d/*.sh configure.d/lib/*.sh system/backup system/storage-mount sandbox/agent \ + | grep -vE ':[[:space:]]*#') +} + +scenario() { + local pattern file tool + check_eq "/bin/bash is 3.2" "3.2" "${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}" + for pattern in "${SCRIPTS[@]}"; do + # shellcheck disable=SC2231 + for file in "$CONNECTOR"/$pattern; do + check "parses: ${file#"$CONNECTOR"/}" /bin/bash -n "$file" + done + done + check_not "no tools macOS doesn't have (python3, jq, timeout, mapfile...)" uses_missing_tools + for tool in osascript plutil xmllint security profiles dns-sd sips osacompile codesign \ + pkgutil spctl hdiutil ditto installer launchctl shasum bunzip2 unzip nc md5 uuidgen \ + openssl scutil curl diskutil base64; do + check "has $tool" command -v "$tool" + done + if command -v brew > /dev/null || [ -x /opt/homebrew/bin/brew ]; then + skip "This image has Homebrew, so the download paths for tools Homebrew already has aren't tested" + else + check "no Homebrew, as on a new Mac" true + fi +} diff --git a/smoketest/scenarios/10-configure.sh b/smoketest/scenarios/10-configure.sh new file mode 100644 index 0000000..4b44067 --- /dev/null +++ b/smoketest/scenarios/10-configure.sh @@ -0,0 +1,26 @@ +# shellcheck shell=bash +DESCRIPTION="configure's menu, --list and an item run on bash 3.2 without errors" +TIER=quick + +list_quietly() { + local out err + err="$("$CONNECTOR/configure" --list 2>&1 > /dev/null < /dev/null)" + [ -z "$err" ] || { echo "$err"; return 1; } +} + +lists() { + "$CONNECTOR/configure" --list < /dev/null | grep -qE "^(to do|done) +$1 " +} + +scenario() { + check "configure --help" "$CONNECTOR/configure" --help + check "configure --list, nothing on stderr" list_quietly + for item in core tailscale backup agents ai-servers storage; do + check "--list has $item" lists "$item" + done + check_not "--list leaves out claude, opencode and hermes before they're installed" lists claude + check_not "configure <unknown item> fails" "$CONNECTOR/configure" no-such-item + check "the menu quits on q" bash -c "echo q | '$CONNECTOR/configure'" + check "configure core asks for the Superpanel and rejects an empty one" \ + bash -c "printf '\n' | '$CONNECTOR/configure' core | grep -q \"That isn't a Superpanel address\"" +} diff --git a/smoketest/scenarios/20-json-keychain.sh b/smoketest/scenarios/20-json-keychain.sh new file mode 100644 index 0000000..3fc5a0f --- /dev/null +++ b/smoketest/scenarios/20-json-keychain.sh @@ -0,0 +1,33 @@ +# shellcheck shell=bash +DESCRIPTION="JSON through JavaScript for Automation, and secrets in the login keychain" +TIER=quick + +source "$CONNECTOR/configure.d/lib/json.sh" +source "$CONNECTOR/configure.d/lib/keychain.sh" + +scenario() { + local file="$TMPDIR/smoke.json" pass + check_eq "json_get reads a value" abc123 \ + "$(echo '{"ocs":{"data":{"apppassword":"abc123"}}}' | json_get 'd.ocs.data.apppassword')" + check_not "json_get fails on false" bash -c "source '$CONNECTOR/configure.d/lib/json.sh'; echo '{\"m\":false}' | json_get d.m" + check_not "json_get fails on bad JSON" bash -c "source '$CONNECTOR/configure.d/lib/json.sh'; echo nope | json_get d.m" + check_eq "json_get passes arguments as a[]" true \ + "$(echo '{"x":"a b"}' | json_get 'd.x === a[0]' 'a b')" + rm -f "$file" + check "json_edit makes a file" json_edit "$file" 'd.k = {"m.x": a[0]};' 'v"1' + check_eq "json_edit wrote it" 'v"1' "$(json_get 'd.k["m.x"]' < "$file")" + check "json_edit changes it" json_edit "$file" 'd.n = 2;' + check_eq "json_edit kept what was there" 'v"1' "$(json_get 'd.k["m.x"]' < "$file")" + echo 'not json' > "$file" + check_not "json_edit leaves bad JSON alone" json_edit "$file" 'd.n = 3;' + check_eq "...and doesn't change it" 'not json' "$(cat "$file")" + + pass="$(openssl rand -base64 24)" + check "keychain_save" keychain_save federated-smoke test "$pass" + check_eq "keychain_load" "$pass" "$(keychain_load federated-smoke test)" + check "keychain_save replaces" keychain_save federated-smoke test abc + check_eq "keychain_load gets the new one" abc "$(keychain_load federated-smoke test)" + check_not "keychain_save refuses a secret with spaces or quotes" keychain_save federated-smoke bad 'a b"c' + check "keychain_delete" keychain_delete federated-smoke test + check_eq "it's gone" "" "$(keychain_load federated-smoke test)" +} diff --git a/smoketest/scenarios/30-core-local.sh b/smoketest/scenarios/30-core-local.sh new file mode 100644 index 0000000..393cf08 --- /dev/null +++ b/smoketest/scenarios/30-core-local.sh @@ -0,0 +1,66 @@ +# shellcheck shell=bash +DESCRIPTION="The Core item's local parts: the profile, Superpanel's app, Element's and Nextcloud's config" +TIER=quick + +source "$CONNECTOR/configure.d/10-core.sh" + +superpanel_opens() { + open -g -W "$SUPERPANEL_APP" +} + +scenario() { + local dir file uuid icon + CORE_DOMAIN=smoke.invalid CORE_EMAIL=jo@smoke.invalid CORE_NAME='Jo "Q" & <Co>' + core_names + PASSWORD='p&ss<w>"rd '\''x' APP_PASSWORD=abc123XYZ + + step "Mail settings for a domain without autoconfig" + mail_settings + check_eq "falls back to the usual IMAP server" "mail.smoke.invalid 993 SSL" "$IMAP_HOST $IMAP_PORT $IMAP_SOCKET" + check_eq "...and SMTP" "mail.smoke.invalid 587 STARTTLS" "$SMTP_HOST $SMTP_PORT $SMTP_SOCKET" + + step "The profile" + dir="$(mktemp -d)" + file="$dir/$PROFILE_NAME.mobileconfig" + uuid="$(uuidgen)" + check "write_profile, and plutil -lint takes it" write_profile "$file" "mail calendar contacts" "$uuid" + check_eq "the mail password survives escaping" "$PASSWORD" \ + "$(plutil -extract PayloadContent.0.IncomingPassword raw -o - "$file")" + check_eq "the name survives escaping" "$CORE_NAME" \ + "$(plutil -extract PayloadContent.0.EmailAccountName raw -o - "$file")" + check_eq "CalDAV payload" com.apple.caldav.account "$(plutil -extract PayloadContent.1.PayloadType raw -o - "$file")" + check_eq "CardDAV payload" com.apple.carddav.account "$(plutil -extract PayloadContent.2.PayloadType raw -o - "$file")" + check_eq "payload UUIDs stay the same" "$(stable_uuid "$PROFILE_ID.mail")" \ + "$(plutil -extract PayloadContent.0.PayloadUUID raw -o - "$file")" + check "profiles show -output stdout-xml gives a property list" bash -c \ + "source '$CONNECTOR/configure.d/lib/profile.sh'; profiles_xml | plutil -lint -s -" + check_not "profile_installed is false for a profile that isn't" profile_installed "$PROFILE_ID" + check "open hands the profile to System Settings" open -g "$file" + skip "Installing it needs a click in System Settings: check that by hand (see README)" + rm -rf "$dir" + + step "Superpanel's app" + SUPERPANEL="https://example.com" + SUPERPANEL_APP="$HOME/Applications/Superpanel (smoke).app" + check "setup_superpanel" setup_superpanel + check "its signature checks out" codesign --verify --deep --strict "$SUPERPANEL_APP" + check "it opens" superpanel_opens + icon="$TMPDIR/icon.png" + check "an icon converts to .icns" bash -c "sips -s format png -z 512 512 \ + /System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericApplicationIcon.icns \ + --out '$icon' && sips -s format icns '$icon' --out '$SUPERPANEL_APP/Contents/Resources/applet.icns'" + check "re-signed after the icon changes" codesign --force --sign - "$SUPERPANEL_APP" + check "...and still checks out" codesign --verify --deep --strict "$SUPERPANEL_APP" + check "...and opens" superpanel_opens + + step "Element and Nextcloud" + MATRIX="https://matrix.smoke.invalid" + check "setup_element writes Element's config" setup_element + check_eq "...pointing at the Core" matrix.smoke.invalid \ + "$(json_get 'd.default_server_config["m.homeserver"].server_name' < "$ELEMENT_CONFIG")" + mkdir -p "$(dirname "$NEXTCLOUD_CFG")" + printf '[Accounts]\n0\\url=https://nextcloud.smoke.invalid\n' > "$NEXTCLOUD_CFG" + check "files_done finds the account in nextcloud.cfg" files_done + printf '[Accounts]\n0\\url=https://nextcloud.smoke.invalid.evil\n' > "$NEXTCLOUD_CFG" + check_not "...and not another server's" files_done +} diff --git a/smoketest/scenarios/40-mdns.sh b/smoketest/scenarios/40-mdns.sh new file mode 100644 index 0000000..47824ef --- /dev/null +++ b/smoketest/scenarios/40-mdns.sh @@ -0,0 +1,33 @@ +# shellcheck shell=bash +DESCRIPTION="Finding things on the network with dns-sd (the VM announces its own ssh)" +TIER=quick + +source "$CONNECTOR/configure.d/lib/mdns.sh" + +finds_type() { + mdns_types | grep -qx '_ssh._tcp' +} + +finds_instance() { + [ -n "$(mdns_instances _ssh._tcp)" ] +} + +resolves_own_host() { + mdns_services _ssh._tcp | cut -d'|' -f3 | grep -qixF "$(mdns_own_host)" +} + +quick_enough() { + local start=$SECONDS + run_for 2 dns-sd -B _ssh._tcp local. > /dev/null + [ $((SECONDS - start)) -le 4 ] +} + +scenario() { + step "Remote Login is on in the VM, so it announces _ssh._tcp" + check "run_for stops dns-sd on time" quick_enough + check "mdns_types lists _ssh._tcp (dns-sd's output comes through a pipe)" finds_type + check "mdns_instances lists the VM's ssh" finds_instance + check "mdns_services resolves it to this Mac's .local name ($(mdns_own_host))" resolves_own_host + check "mdns_hosts runs (and leaves this Mac out)" bash -c \ + "source '$CONNECTOR/configure.d/lib/mdns.sh'; ! mdns_hosts | grep -qixF \"\$(mdns_own_host)\"" +} diff --git a/smoketest/scenarios/50-sandbox.sh b/smoketest/scenarios/50-sandbox.sh new file mode 100644 index 0000000..c2c2459 --- /dev/null +++ b/smoketest/scenarios/50-sandbox.sh @@ -0,0 +1,71 @@ +# shellcheck shell=bash +DESCRIPTION="Installs Node.js and srt, and the sandbox keeps a (fake) agent in: files, network, local servers" +TIER=quick + +source "$CONNECTOR/configure.d/30-agents.sh" +source "$CONNECTOR/configure.d/50-ai-servers.sh" +PROJECT="$HOME/proj" + +# Run a command as the "opencode" agent, in the sandbox, from a project +sandboxed() { + (cd "$PROJECT" && "$CONNECTOR/sandbox/bin/opencode" "$@") +} + +fetch() { + sandboxed /usr/bin/curl -fsS -o /dev/null --max-time 20 "$1" +} + +zsh_finds_sandboxed() { + [ "$(zsh -ic 'command -v opencode' 2> /dev/null)" = "$CONNECTOR/sandbox/bin/opencode" ] +} + +scenario() { + local node server + step "Installing Node.js and srt" + check "tool_ensure node srt" tool_ensure node srt + check "Node.js is 22.12 or later" node_ok + check "srt is found" srt_path + + # The agent is a stand-in that runs what it's given, so commands can be + # tried in its sandbox + mkdir -p "$HOME/.local/bin" "$PROJECT" "$HOME/.ssh" + printf '#!/bin/bash\nexec "$@"\n' > "$HOME/.local/bin/opencode" + chmod +x "$HOME/.local/bin/opencode" + echo secret > "$HOME/.ssh/smoke-secret" + + step "Files" + check "the agent runs in the sandbox" sandboxed /usr/bin/true + check_not "it can't read ~/.ssh" sandboxed /bin/cat "$HOME/.ssh/smoke-secret" + check_not "it can't read the keychains" sandboxed /bin/ls "$HOME/Library/Keychains" + check "it can write in its project" sandboxed /usr/bin/touch "$PROJECT/written" + check_not "it can't write elsewhere in your home folder" sandboxed /usr/bin/touch "$HOME/outside" + check "it can write in /tmp" sandboxed /usr/bin/touch /tmp/smoke-written + check "it can make temp files (mktemp)" sandboxed /usr/bin/mktemp + check "it can open a pty (allowPty)" sandboxed /usr/bin/script -q /dev/null /usr/bin/true + check_not "it won't start in your home folder" bash -c "cd ~ && '$CONNECTOR/sandbox/bin/opencode' /usr/bin/true" + check "unsandboxed runs it outside" bash -c "cd '$PROJECT' && '$CONNECTOR/sandbox/bin/unsandboxed' opencode /bin/cat '$HOME/.ssh/smoke-secret'" + + step "Network" + check "it reaches an allowed site (registry.npmjs.org)" fetch https://registry.npmjs.org/ + check_not "it doesn't reach others (example.com)" fetch https://example.com/ + + step "An LLM server on this Mac" + node="$(tool_path node)" + "$node" -e 'require("http").createServer((q, s) => { s.setHeader("content-type", "application/json"); + s.end(JSON.stringify({data: [{id: "smoke-model"}]})); }).listen(11434, "127.0.0.1")' & + server=$! + sleep 2 + check_eq "server_models reads its models" smoke-model "$(server_models localhost:11434)" + check_not "the agent can't reach it before it's allowed" fetch http://localhost:11434/v1/models + check "sandbox_allow localhost:11434" sandbox_allow localhost:11434 + check "...then it can, through srt's proxy" fetch http://localhost:11434/v1/models + check "sandbox_disallow" sandbox_disallow localhost:11434 + check_not "...then it can't again" fetch http://localhost:11434/v1/models + kill "$server" 2> /dev/null + + step "Shell and Claude Code" + check "put_on_path" put_on_path + check "a new zsh finds sandbox/bin's opencode first" zsh_finds_sandboxed + check "turn_on_claude_sandbox" turn_on_claude_sandbox + check "Claude Code's sandbox is on" claude_sandbox_on +} diff --git a/smoketest/scenarios/60-backup.sh b/smoketest/scenarios/60-backup.sh new file mode 100644 index 0000000..f023a6a --- /dev/null +++ b/smoketest/scenarios/60-backup.sh @@ -0,0 +1,92 @@ +# shellcheck shell=bash +DESCRIPTION="Backup end to end: restic and rclone, the app, launchd, the keychain, a snapshot and a restore" +TIER=quick + +source "$CONNECTOR/configure.d/20-backup.sh" +DAV="$HOME/davroot" +SMOKE_FILE="$HOME/Documents/smoke-file.txt" + +ran() { + grep -qE 'Backup (finished|failed)' "$BACKUP_LOG" 2> /dev/null +} + +finished() { + grep -q 'Backup finished' "$BACKUP_LOG" || { tail -n 30 "$BACKUP_LOG"; return 1; } +} + +has_snapshot() { + [ "$(restic snapshots --host smoketest --json | json_get 'd.length')" -ge 1 ] +} + +restores() { + local target="$TMPDIR/restored" + rm -rf "$target" + restic restore latest --host smoketest --target "$target" --include "$SMOKE_FILE" > /dev/null \ + && cmp "$SMOKE_FILE" "$target$SMOKE_FILE" +} + +access_answer() { + echo "?" > "$ACCESS_CHECK" + open -g -W "$BACKUP_APP" + cat "$ACCESS_CHECK" + rm -f "$ACCESS_CHECK" +} + +scenario() { + local pass answer lines DAV_SERVER + step "Installing restic and rclone" + check "tool_ensure restic rclone" tool_ensure restic rclone + export PATH="$TOOLS_PATH:$PATH" + + # A plain WebDAV server stands in for Nextcloud. Without a password, so the + # backup's check that Nextcloud is up (status.php) answers. + mkdir -p "$DAV" "$(dirname "$SMOKE_FILE")" + echo ok > "$DAV/status.php" + rclone serve webdav "$DAV" --addr 127.0.0.1:8081 > /dev/null 2>&1 & + DAV_SERVER=$! + sleep 3 + date > "$SMOKE_FILE" + + WEBDAV=http://127.0.0.1:8081 BACKUP_DIR=.backup-smoketest + mkdir -p "$CONF_DIR" + { + printf 'BACKUP_WEBDAV=%q\n' "$WEBDAV" + printf 'BACKUP_USER=tester\nBACKUP_DIR=%q\nBACKUP_HOST=smoketest\nBACKUP_VENDOR=other\n' "$BACKUP_DIR" + } > "$BACKUP_CONF" + echo "$DAV" > "$CONF_DIR/backup-exclude" + pass="$(openssl rand -base64 24)" + check "the app password goes in the keychain" keychain_save "$BACKUP_KEYCHAIN" "nextcloud:$WEBDAV" smokepass + check "the passphrase goes in the keychain" keychain_save "$BACKUP_KEYCHAIN" "passphrase:$WEBDAV/$BACKUP_DIR" "$pass" + source "$CONNECTOR/system/backup-env.sh" + check "backup-env.sh finds the passphrase" test -n "$RESTIC_PASSWORD_COMMAND" + check "restic init, through rclone" restic init + + step "The Federated Backup app and its launchd job" + check "make_backup_app" make_backup_app + check "the app knows which script it runs" backup_app_current + check "its signature checks out" codesign --verify --deep --strict "$BACKUP_APP" + answer="$(access_answer)" + check "started as itself, it says whether it has Full Disk Access" test "$answer" = yes -o "$answer" = no + [ "$answer" = no ] && skip "Full Disk Access needs a click in System Settings; this backup leaves protected folders out" + touch "$CONF_DIR/backup-last" + check "install_job" install_job + check "launchd has the job" job_loaded + + step "A backup, started the way configure does" + touch "$NOW_REQUEST" + launchctl kickstart "gui/$(id -u)/$LABEL" + wait_until 900 ran > /dev/null + check "it finished" finished + check "restic has a snapshot from this Mac" has_snapshot + check "a file comes back from it" restores + lines="$(wc -l < "$BACKUP_LOG")" + launchctl kickstart "gui/$(id -u)/$LABEL" + sleep 15 + check_eq "started again within the day, it does nothing" "$lines" "$(wc -l < "$BACKUP_LOG")" + + step "Turning backups off" + stop_backups + check_not "launchd no longer has the job" job_loaded + check_not "the app is gone" test -e "$BACKUP_APP" + kill "$DAV_SERVER" 2> /dev/null +} diff --git a/smoketest/scenarios/70-apps.sh b/smoketest/scenarios/70-apps.sh new file mode 100644 index 0000000..d401742 --- /dev/null +++ b/smoketest/scenarios/70-apps.sh @@ -0,0 +1,57 @@ +# shellcheck shell=bash +DESCRIPTION="Downloads Element, Nextcloud and Tailscale with Gatekeeper on: Team IDs, notarization, refusals" +TIER=all + +source "$CONNECTOR/configure.d/lib/json.sh" +source "$CONNECTOR/configure.d/lib/apps.sh" + +gatekeeper_on() { + spctl --status | grep -q 'assessments enabled' +} + +# An app no one notarized: Gatekeeper should turn it down +unnotarized_refused() { + local app="$TMPDIR/Unnotarized.app" + rm -rf "$app" + osacompile -o "$app" -e 'return' && codesign --force --sign - "$app" > /dev/null 2>&1 || return 2 + ! spctl --assess --type execute "$app" 2> /dev/null +} + +# Tailscale's package, offered as someone else's +wrong_team_refused() { + local pkg="$TMPDIR/tailscale.pkg" + app_info tailscale + curl -fsL --max-time 600 -o "$pkg" "$APP_URL" || return 2 + APP_TEAM=ZZZZZZZZZZ + ! install_pkg "$pkg" +} + +team_of() { + codesign -dv "$(app_path "$1")" 2>&1 | sed -n 's/^TeamIdentifier=//p' +} + +nextcloud_opens() { + open -a "$(app_path nextcloud)" --args --overrideserverurl https://nextcloud.smoke.invalid + sleep 10 + pgrep -x Nextcloud > /dev/null +} + +scenario() { + local app + # The vanilla image turns Gatekeeper off; a real Mac has it on + sudo spctl --global-enable 2> /dev/null || sudo spctl --master-enable 2> /dev/null + check "Gatekeeper is on" gatekeeper_on + gatekeeper_on || { skip "Gatekeeper couldn't be turned on, so the checks below prove less"; } + check "Gatekeeper turns down an app no one notarized" unnotarized_refused + check "install_pkg refuses a package signed by another Team ID" wrong_team_refused + + for app in element nextcloud tailscale; do + step "$app" + check "app_install $app (its Team ID and notarization check out)" app_install "$app" + app_info "$app" + check_eq "$app's Team ID is the one in apps.sh" "$APP_TEAM" "$(team_of "$app")" + done + check "Nextcloud opens with the Core's address" nextcloud_opens + pkill -x Nextcloud 2> /dev/null + skip "Tailscale's VPN approval and Nextcloud's sign-in need clicks: check those by hand" +} diff --git a/smoketest/scenarios/80-storage.sh b/smoketest/scenarios/80-storage.sh new file mode 100644 index 0000000..502253d --- /dev/null +++ b/smoketest/scenarios/80-storage.sh @@ -0,0 +1,34 @@ +# shellcheck shell=bash +DESCRIPTION="Network storage's launchd job: mounts on login and network changes, skips servers it can't reach" +TIER=quick + +source "$CONNECTOR/configure.d/60-storage.sh" +UNREACHABLE="smb://smoke@nas.smoke.invalid/files" + +job_loaded() { + launchctl print "gui/$(id -u)/$LABEL" > /dev/null 2>&1 +} + +skips_quickly() { + local start=$SECONDS + bash "$STORAGE_MOUNT" || return 1 + [ $((SECONDS - start)) -le 10 ] +} + +lists_unmounted() { + [ "$(bash "$STORAGE_MOUNT" --list)" = "$UNREACHABLE|" ] +} + +scenario() { + mkdir -p "$CONF_DIR" + : > "$STORAGE_CONF" + check "record adds a share and the job" record "$UNREACHABLE" "/Volumes/files" + check "launchd has the job" job_loaded + check "the plist names the script" plutil -lint "$PLIST" + check "a server it can't reach is skipped, quickly and without asking" skips_quickly + check "--list shows it as not mounted" lists_unmounted + check_not "mounted_at doesn't find it" mounted_at "$UNREACHABLE" + check "remove_share" remove_share "$UNREACHABLE" + check_not "the job is gone with the last share" job_loaded + skip "Mounting a real share needs another machine and the sign-in window: check by hand" +} diff --git a/system/backup b/system/backup new file mode 100755 index 0000000..d079622 --- /dev/null +++ b/system/backup @@ -0,0 +1,165 @@ +#!/bin/bash +# +# Purpose : Back up your home folder with restic to your Nextcloud files, in +# .backup-<this Mac's name>. `configure backup` sets it up. +# +# launchd starts the Federated Backup app hourly and at login, and the app +# runs this. It backs up once a day, so a Mac that was asleep or off catches +# up soon after. The app exists so that you can give it Full Disk Access: +# what it runs gets that access too, and without it macOS keeps restic out of +# Desktop, Documents, Mail and the like. +# +# Keeps 7 daily, 4 weekly and 6 monthly backups. To leave out more, list +# paths or patterns in ~/Library/Application Support/Federated Connector/ +# backup-exclude, one per line. + +# Wrapped in { ...; exit; } so bash reads the whole script up front; an update +# may replace this file while a backup is running. +{ + +CONNECTOR="$(cd "$(dirname "$0")/.." && pwd)" +CONF_DIR="$HOME/Library/Application Support/Federated Connector" +USER_EXCLUDE="$CONF_DIR/backup-exclude" +STAMP="$CONF_DIR/backup-last" +NOW_REQUEST="$CONF_DIR/backup-now" +ACCESS_CHECK="$CONF_DIR/backup-access-check" +LOCK="$CONF_DIR/backup.lock" +LOG_DIR="$HOME/Library/Logs/Federated Connector" +LOG="$LOG_DIR/backup.log" +DAY=82800 # 23 hours, so the daily backup doesn't drift later each day + +# Full Disk Access is what lets this read the TCC folder +full_disk_access() { + ls "$HOME/Library/Application Support/com.apple.TCC" > /dev/null 2>&1 +} + +# configure asks, by starting the app, whether it has Full Disk Access +if [ -f "$ACCESS_CHECK" ]; then + if full_disk_access; then echo yes > "$ACCESS_CHECK"; else echo no > "$ACCESS_CHECK"; fi + exit 0 +fi + +mkdir -p "$LOG_DIR" +if [ "$(stat -f %z "$LOG" 2> /dev/null || echo 0)" -gt 5000000 ]; then + mv -f "$LOG" "$LOG.1" +fi +exec >> "$LOG" 2>&1 + +# Tell you when a backup fails, as no one watches launchd +notify() { + osascript -e 'on run argv' -e 'display notification (item 2 of argv) with title (item 1 of argv)' \ + -e 'end run' "$1" "$2" 2> /dev/null +} + +fail() { + echo "$(date '+%F %T') Backup failed: $1" + notify "Backup failed" "$1" + rm -f "$LOCK" + exit 1 +} + +# Once a day, unless configure asked for one now +if [ -f "$NOW_REQUEST" ]; then + rm -f "$NOW_REQUEST" +elif [ -f "$STAMP" ] && [ $(($(date +%s) - $(stat -f %m "$STAMP"))) -lt $DAY ]; then + exit 0 +fi + +# One backup at a time +if [ -f "$LOCK" ] && kill -0 "$(cat "$LOCK" 2> /dev/null)" 2> /dev/null; then + exit 0 +fi +echo $$ > "$LOCK" + +source "$CONNECTOR/system/backup-env.sh" || fail "Backups aren't set up. Run: configure backup" +[ -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 keychain. Run: configure backup" +if ! command -v restic > /dev/null || ! command -v rclone > /dev/null; then + fail "restic or rclone is missing. Run: configure backup" +fi + +if ! full_disk_access; then + notify "Backup can't read all your files" \ + "Give Federated Backup Full Disk Access (run: configure backup). Backing up what it can." +fi + +# Run at login, perhaps before the network is up; give it a few minutes +for _ in 1 2 3 4 5 6 7 8 9 10; do + curl -sf --max-time 10 -o /dev/null "${BACKUP_WEBDAV%%/remote.php/*}/status.php" && break + sleep 30 +done + +L="$HOME/Library" +# Rebuilt by restic, or by reinstalling, so not worth the space +excludes=( + "$HOME/.Trash" + "$L/Caches" + "$L/Logs" + "$L/Containers/*/Data/Library/Caches" + "$L/Group Containers/*/Library/Caches" + "$L/Developer/Xcode/DerivedData" + "$L/Developer/Xcode/iOS DeviceSupport" + "$L/Developer/CoreSimulator" + # Files already in the cloud. Reading them would also download the ones + # macOS keeps only in the cloud. + "$HOME/Nextcloud" + "$L/CloudStorage" + "$L/Mobile Documents" + # Docker's and other VMs' disks: large, and changing whenever they run + "$L/Containers/com.docker.docker" + "$HOME/.orbstack" + "$HOME/.colima" + "$HOME/.lima" + "$L/Containers/com.utmapp.UTM" + # Package caches and tool installs + "$HOME/.local/share/federated-connector" + "$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/claude" + "$HOME/.opencode/bin" + # 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" + # Models can be downloaded again + "$HOME/.ollama/models" + "$HOME/.lmstudio/models" + "$HOME/.cache" + # Electron and Chromium apps (Element, browsers, editors) keep caches here + "$L/Application Support/*/Cache" + "$L/Application Support/**/Code Cache" + "$L/Application Support/**/GPUCache" + "$L/Application Support/**/Service Worker/CacheStorage" + # Element's search index for encrypted messages, which it rebuilds + "$L/Application Support/Element/EventStore" +) +exclude_args=(--exclude-caches) +for path in "${excludes[@]}"; do + exclude_args+=(--exclude "$path") +done +[ -f "$USER_EXCLUDE" ] && exclude_args+=(--exclude-file "$USER_EXCLUDE") + +echo "$(date '+%F %T') Backing up $HOME to $BACKUP_DIR in your Nextcloud files..." +restic backup --one-file-system --host "$BACKUP_HOST" "${exclude_args[@]}" "$HOME" +status=$? +# 3 means some files couldn't be read; the rest were backed up +[ $status -eq 0 ] || [ $status -eq 3 ] || fail "restic couldn't back up $HOME (exit $status). See $LOG" + +echo "$(date '+%F %T') Removing old backups..." +restic forget --host "$BACKUP_HOST" --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --prune \ + || fail "restic couldn't remove old backups. See $LOG" + +touch "$STAMP" +rm -f "$LOCK" +echo "$(date '+%F %T') Backup finished." +exit 0 +} diff --git a/system/backup-env.sh b/system/backup-env.sh new file mode 100644 index 0000000..3889d97 --- /dev/null +++ b/system/backup-env.sh @@ -0,0 +1,51 @@ +#!/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 (in bash +# or zsh) to look at or restore from a backup: +# +# source <this folder>/backup-env.sh +# restic snapshots +# +# To use another computer's backup, name its folder: +# +# source <this folder>/backup-env.sh .backup-<name> +# +# restic reaches Nextcloud over WebDAV through rclone. The Nextcloud app +# password and the backup's passphrase are in your login keychain. This is +# sourced by zsh too, so it uses no bash-only syntax. + +BACKUP_CONF="$HOME/Library/Application Support/Federated Connector/backup.conf" +BACKUP_KEYCHAIN="federated-connector-backup" +FC_TOOLS="$HOME/.local/share/federated-connector" +PATH="$FC_TOOLS/bin:/opt/homebrew/bin:/usr/local/bin:$PATH" +export PATH + +# A secret from the keychain: nextcloud:<webdav> (app password) or +# passphrase:<webdav>/<folder> +backup_secret() { + security find-generic-password -s "$BACKUP_KEYCHAIN" -a "$1" -w 2> /dev/null +} + +if [ -f "$BACKUP_CONF" ]; then + . "$BACKUP_CONF" + BACKUP_DIR="${1:-$BACKUP_DIR}" + + export RCLONE_WEBDAV_URL="$BACKUP_WEBDAV" + # BACKUP_VENDOR is only set by the smoketest, whose stand-in for Nextcloud + # is a plain WebDAV server + export RCLONE_WEBDAV_VENDOR="${BACKUP_VENDOR:-nextcloud}" + export RCLONE_WEBDAV_USER="$BACKUP_USER" + RCLONE_WEBDAV_PASS="$(backup_secret "nextcloud:$BACKUP_WEBDAV" | rclone obscure - 2> /dev/null)" + export RCLONE_WEBDAV_PASS + export RESTIC_REPOSITORY="rclone::webdav:$BACKUP_DIR" + + # Without a passphrase in the keychain, 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="security find-generic-password -s $BACKUP_KEYCHAIN -a passphrase:$BACKUP_WEBDAV/$BACKUP_DIR -w" + fi +else + echo "Backups aren't set up. Run: configure backup" >&2 +fi diff --git a/system/storage-mount b/system/storage-mount new file mode 100755 index 0000000..1cea3fb --- /dev/null +++ b/system/storage-mount @@ -0,0 +1,49 @@ +#!/bin/bash +# +# Purpose : Mount the shared folders `configure storage` added, at login and +# whenever the network changes (launchd starts this then). +# +# A share whose server can't be reached, e.g. away from home, is skipped +# quietly. macOS signs in with the password you saved in your keychain when +# you added the share. If it can't, it asks; if you cancel, this doesn't ask +# again for an hour. +# +# Usage: storage-mount [--list] (--list: show each share and whether it's mounted) + +# Wrapped in { ...; exit; } so bash reads the whole script up front +{ + +CONF_DIR="$HOME/Library/Application Support/Federated Connector" +STORAGE_CONF="$CONF_DIR/storage" +FAILED_DIR="${TMPDIR:-/tmp}/federated-storage-failed" +RETRY_AFTER=3600 + +source "$(cd "$(dirname "$0")/.." && pwd)/configure.d/lib/smb.sh" || exit 1 + +[ -f "$STORAGE_CONF" ] || exit 0 + +if [ "$1" = --list ]; then + while IFS= read -r url; do + [ -n "$url" ] || continue + if point="$(mounted_at "$url")"; then echo "$url|$point"; else echo "$url|"; fi + done < "$STORAGE_CONF" + exit 0 +fi + +mkdir -p "$FAILED_DIR" +while IFS= read -r url; do + [ -n "$url" ] || continue + mounted_at "$url" > /dev/null && continue + nc -z -G 3 "$(host_of "$url")" 445 > /dev/null 2>&1 || continue + marker="$FAILED_DIR/$(share_key "$url" | tr '/ ' '__')" + if [ -f "$marker" ] && [ $(($(date +%s) - $(stat -f %m "$marker"))) -lt $RETRY_AFTER ]; then + continue + fi + if mount_share "$url"; then + rm -f "$marker" + else + touch "$marker" + fi +done < "$STORAGE_CONF" +exit 0 +}