Set up Pop!_OS for a Federated Core, like CoreDesktop's configure

A port of CoreDesktop's configure to Pop!_OS 24.04 with COSMIC, in the shape
of connector-macos: its own install.sh, update and configure, installed in
~/.local/share/federated-connector/connector.

Every configure item is ported: the Core (email, calendars and contacts
through GNOME Online Accounts and Evolution, as COSMIC has no accounts of its
own; Superpanel; files over davfs2; Element; Tally; the email watcher),
Tailscale, backups, AI agents in the sandbox and their sign-ins, languages
with mise, AI servers, printers, network storage and the agent sandbox.
Folders go in the COSMIC Files sidebar. Each item installs what it needs
from apt, Flathub or the tool's own apt repository when you set it up.

smoketest/run checks it in Ubuntu 24.04 containers with Docker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 14:20:47 -07:00
co-authored by Claude Opus 5.5
commit bc07e1d3e3
60 changed files with 5626 additions and 0 deletions
+919
View File
@@ -0,0 +1,919 @@
#!/bin/bash
# configure reads TITLE and DESCRIPTION
# shellcheck disable=SC2034
TITLE="Federated Core"
# shellcheck disable=SC2034
DESCRIPTION="Email, calendars, contacts, Superpanel, files and Element"
# Each Core is in cores/<domain>.conf, with what you entered last time, so
# running this again only does what's missing. core.conf is a copy of the main
# Core's: Element, Tailscale and Backup use that one.
CORE_CONF="$CONF_DIR/core.conf"
CORES_DIR="$CONF_DIR/cores"
TAILSCALE_CONF="$CONF_DIR/tailscale.conf"
BACKUP_CONF="$CONF_DIR/backup.conf"
GOA_ACCOUNT="$CONNECTOR/configure.d/lib/goa-account"
EMAIL_WATCH="$CONNECTOR/system/email-watch"
UNITS="$HOME/.config/systemd/user"
source "$CONNECTOR/configure.d/lib/nextcloud.sh"
source "$CONNECTOR/configure.d/lib/sidebar.sh"
[ -f "$CORE_CONF" ] && source "$CORE_CONF"
MAIN_DOMAIN="$CORE_DOMAIN"
core_domains() {
local file
for file in "$CORES_DIR"/*.conf; do
[ -f "$file" ] && basename "$file" .conf
done
}
load_core() {
CORE_DOMAIN="" CORE_EMAIL="" CORE_NAME=""
[ -n "$1" ] && source "$CORES_DIR/$1.conf"
core_names
}
# CORE_DOMAIN, CORE_EMAIL and CORE_NAME come from core.conf; the rest follow
core_names() {
CORE_USER="${CORE_EMAIL%@*}"
NEXTCLOUD="https://nextcloud.$CORE_DOMAIN"
WEBDAV="$NEXTCLOUD/remote.php/dav/files/$CORE_USER"
MOUNT="/mnt/$CORE_DOMAIN"
SUPERPANEL_DESKTOP="$HOME/.local/share/applications/core-$CORE_DOMAIN-superpanel.desktop"
MATRIX="https://matrix.$CORE_DOMAIN"
ELEMENT_CONFIG="$(element_config)"
PLAUSIBLE="plausible.$CORE_DOMAIN"
}
superpanel_done() {
[ -f "$SUPERPANEL_DESKTOP" ]
}
nextcloud_done() {
"$GOA_ACCOUNT" exists owncloud "$CORE_USER@nextcloud.$CORE_DOMAIN" 2> /dev/null
}
email_done() {
"$GOA_ACCOUNT" exists imap_smtp "$CORE_EMAIL" 2> /dev/null
}
files_done() {
grep -qs " $MOUNT davfs " /etc/fstab && grep -qs "^$MOUNT " "$HOME/.davfs2/secrets"
}
# Element from Flathub (as the COSMIC Store installs it), or the deb from
# packages.element.io
ELEMENT_FLATPAK=im.riot.Riot
element_installed() {
flatpak_installed "$ELEMENT_FLATPAK" || command -v element-desktop > /dev/null
}
# Element reads config.json in its own settings folder, which Flatpak keeps
# in the app's folder under ~/.var/app
element_config() {
if flatpak_installed "$ELEMENT_FLATPAK"; then
echo "$HOME/.var/app/$ELEMENT_FLATPAK/config/Element/config.json"
else
echo "$HOME/.config/Element/config.json"
fi
}
# Done when Element isn't installed, as there's nothing to set up
element_done() {
element_installed || return 0
jq -e --arg url "$MATRIX" \
'.default_server_config["m.homeserver"].base_url | rtrimstr("/") == $url' \
"$ELEMENT_CONFIG" &> /dev/null
}
# Tally for Plausible, a Flatpak, shows one Plausible Analytics. It follows the
# main Core, if that runs Plausible.
TALLY=com.cassidyjames.plausible
tally_installed() {
flatpak info "$TALLY" &> /dev/null
}
tally_setting() {
flatpak run --command=gsettings "$TALLY" "$@" 2> /dev/null
}
tally_done() {
[ "$(tally_setting get "$TALLY" domain)" = "'$PLAUSIBLE'" ]
}
plausible_on_core() {
curl -sf -o /dev/null --max-time 15 "https://$PLAUSIBLE/api/health"
}
# Element only follows the main Core
core_done() {
superpanel_done && nextcloud_done && email_done && files_done \
&& { [ "$CORE_DOMAIN" != "$MAIN_DOMAIN" ] || element_done; }
}
# Done when every Core is
is_configured() {
local domain domains
domains="$(core_domains)"
[ -n "$domains" ] || return 1
for domain in $domains; do
(load_core "$domain" && core_done) || return 1
done
}
# The first Core you set up is the main one
save_conf() {
mkdir -p "$CORES_DIR"
{
printf 'CORE_DOMAIN=%q\n' "$CORE_DOMAIN"
printf 'CORE_EMAIL=%q\n' "$CORE_EMAIL"
printf 'CORE_NAME=%q\n' "$CORE_NAME"
} > "$CORES_DIR/$CORE_DOMAIN.conf"
if [ -z "$MAIN_DOMAIN" ] || [ "$MAIN_DOMAIN" = "$CORE_DOMAIN" ]; then
make_main "$CORE_DOMAIN"
fi
}
make_main() {
cp "$CORES_DIR/$1.conf" "$CORE_CONF" && MAIN_DOMAIN="$1"
}
desktop_entry() {
local file="$1" name="$2" comment="$3" url="$4" icon="$5"
mkdir -p "$(dirname "$file")"
cat > "$file" << EOF
[Desktop Entry]
Type=Application
Name=$name
Comment=$comment
Exec=xdg-open $url
Icon=$icon
Categories=Network;
EOF
}
setup_superpanel() {
local url="https://superpanel.$CORE_DOMAIN"
local icon="$HOME/.local/share/icons/core-$CORE_DOMAIN-superpanel.png"
# The login page carries Superpanel's icon inline
mkdir -p "$(dirname "$icon")"
if ! curl -s "$url/" | grep -o 'rel="icon"[^>]*base64,[^"]*' | head -n 1 \
| sed 's/.*base64,//' | base64 -d > "$icon" 2> /dev/null || [ ! -s "$icon" ]; then
rm -f "$icon"
icon="applications-internet"
fi
desktop_entry "$SUPERPANEL_DESKTOP" "Superpanel" "Manage your Federated Core ($CORE_DOMAIN)" "$url" "$icon"
echo "Added Superpanel to your applications."
}
# COSMIC has no Online Accounts of its own, so GNOME's is used: it keeps the
# accounts and their passwords (in your keyring, as COSMIC does), and
# Evolution shows your email, calendars and contacts from it. goa-account adds
# accounts through it the way GNOME Settings does.
goa_ready() {
pkg_ensure "Email, calendars and contacts" gnome-online-accounts evolution \
python3-gi gir1.2-secret-1
}
setup_nextcloud() {
[ -n "$APP_PASSWORD" ] || { echo "This needs your Core password, and Nextcloud didn't accept it."; return 1; }
goa_ready || return 1
"$GOA_ACCOUNT" add << EOF || return 1
$(jq -n --arg user "$CORE_USER" --arg host "nextcloud.$CORE_DOMAIN" --arg url "$NEXTCLOUD" \
--arg password "$APP_PASSWORD" '{
provider: "owncloud",
identity: $user,
presentation_identity: "\($user)@\($host)",
credentials: {password: $password},
details: {
Uri: "\($url)/remote.php/webdav",
FilesEnabled: "true",
CalendarEnabled: "true",
CalDavUri: "\($url)/remote.php/dav",
ContactsEnabled: "true",
CardDavUri: "\($url)/remote.php/dav",
AcceptSslErrors: "false"
}}')
EOF
echo "Added Nextcloud's calendars and contacts; Evolution shows them."
}
# The mail server publishes its settings (Thunderbird's autoconfig format).
# Prints: imap_host imap_port imap_socket smtp_host smtp_port smtp_socket username
mail_settings() {
curl -sf --max-time 15 \
"https://autoconfig.$CORE_DOMAIN/mail/config-v1.1.xml?emailaddress=$CORE_EMAIL" \
| python3 -I -c '
import sys, xml.etree.ElementTree as ET
provider = ET.parse(sys.stdin).getroot().find("emailProvider")
imap = provider.find("incomingServer[@type=\"imap\"]")
smtp = provider.find("outgoingServer[@type=\"smtp\"]")
print(*(s.findtext(f) for s in (imap, smtp) for f in ("hostname", "port", "socketType")),
imap.findtext("username"))'
}
# Online Accounts takes host:port, and only the host for the usual port
host_port() {
if [ "$2" = "$3" ]; then echo "$1"; else echo "$1:$2"; fi
}
setup_email() {
[ -n "$PASSWORD" ] || { echo "This needs your Core password."; return 1; }
goa_ready || return 1
local imap_host imap_port imap_socket smtp_host smtp_port smtp_socket username
if ! read -r imap_host imap_port imap_socket smtp_host smtp_port smtp_socket username < <(mail_settings) \
|| [ -z "$smtp_socket" ]; then
echo "The mail server didn't give its settings; using mail.$CORE_DOMAIN with the usual ports."
imap_host="mail.$CORE_DOMAIN" imap_port=993 imap_socket=SSL
smtp_host="mail.$CORE_DOMAIN" smtp_port=587 smtp_socket=STARTTLS
username="%EMAILADDRESS%"
fi
case "$username" in
%EMAILLOCALPART%) username="$CORE_USER" ;;
*) username="$CORE_EMAIL" ;;
esac
[ "$imap_socket" = SSL ] && imap_std=993 || imap_std=143
[ "$smtp_socket" = SSL ] && smtp_std=465 || smtp_std=587
"$GOA_ACCOUNT" add << EOF || return 1
$(jq -n --arg email "$CORE_EMAIL" --arg name "$CORE_NAME" --arg user "$username" \
--arg password "$PASSWORD" \
--arg imap "$(host_port "$imap_host" "$imap_port" "$imap_std")" --arg imap_socket "$imap_socket" \
--arg smtp "$(host_port "$smtp_host" "$smtp_port" "$smtp_std")" --arg smtp_socket "$smtp_socket" '{
provider: "imap_smtp",
identity: $email,
presentation_identity: $email,
credentials: {"imap-password": $password, "smtp-password": $password},
details: {
Enabled: "true",
EmailAddress: $email,
Name: $name,
ImapHost: $imap,
ImapUserName: $user,
ImapUseSsl: (if $imap_socket == "SSL" then "true" else "false" end),
ImapUseTls: (if $imap_socket == "STARTTLS" then "true" else "false" end),
ImapAcceptSslErrors: "false",
SmtpHost: $smtp,
SmtpUseAuth: "true",
SmtpUserName: $user,
SmtpAuthLogin: "false",
SmtpAuthPlain: "true",
SmtpUseSsl: (if $smtp_socket == "SSL" then "true" else "false" end),
SmtpUseTls: (if $smtp_socket == "STARTTLS" then "true" else "false" end),
SmtpAcceptSslErrors: "false"
}}')
EOF
echo "Added $CORE_EMAIL; Evolution shows it."
}
# Save APP_PASSWORD for davfs2 to mount your files with. davfs2 only reads
# this file if no one else can.
save_files_secret() {
local secret
mkdir -p -m 700 "$HOME/.davfs2"
touch "$HOME/.davfs2/secrets"
chmod 600 "$HOME/.davfs2/secrets"
secret="${APP_PASSWORD//\\/\\\\}"
secret="${secret//\"/\\\"}"
sed -i "\\#^$MOUNT #d" "$HOME/.davfs2/secrets"
printf '%s %s "%s"\n' "$MOUNT" "$CORE_USER" "$secret" >> "$HOME/.davfs2/secrets"
}
# davfs2 lets you mount without sudo only if mount.davfs is setuid root, which
# Ubuntu's package asks about when it's installed (no, by default)
davfs2_ready() {
if ! pkg_installed davfs2; then
echo "Mounting your files needs davfs2."
confirm_yes "Install it now (with apt; asks for your password)?" || return 1
echo "davfs2 davfs2/suid_file boolean true" | sudo debconf-set-selections || return 1
pkg_install davfs2 || return 1
fi
if [ ! -u /usr/sbin/mount.davfs ]; then
echo "davfs2 davfs2/suid_file boolean true" | sudo debconf-set-selections \
&& sudo dpkg-reconfigure -f noninteractive davfs2 || return 1
fi
}
# Mount your Nextcloud files at /mnt/<domain> with davfs2. You can mount it
# without sudo once it's in /etc/fstab with "user" and you're in Ubuntu's
# davfs2 group. It's mounted now and each time you log in.
setup_files() {
[ -n "$APP_PASSWORD" ] || { echo "This needs your Core password, and Nextcloud didn't accept it."; return 1; }
davfs2_ready || return 1
sudo install -d -o "$USER" -g "$(id -gn)" "$MOUNT" || return 1
if ! grep -qs " $MOUNT davfs " /etc/fstab; then
echo "$WEBDAV $MOUNT davfs rw,user,noauto,uid=$USER,_netdev 0 0" | sudo tee -a /etc/fstab > /dev/null || return 1
# Otherwise mount warns that systemd is still using the old fstab
sudo systemctl daemon-reload
fi
if ! id -nG "$USER" | grep -qw davfs2; then
sudo usermod -aG davfs2 "$USER" || return 1
fi
save_files_secret || return 1
mkdir -p "$HOME/.config/autostart"
cat > "$HOME/.config/autostart/core-$CORE_DOMAIN-files.desktop" << EOF
[Desktop Entry]
Type=Application
Name=Nextcloud files ($CORE_DOMAIN)
Comment=Mount your Nextcloud files at $MOUNT
Exec=sh -c 'mountpoint -q $MOUNT || mount $MOUNT'
X-GNOME-Autostart-enabled=true
NoDisplay=true
EOF
# Shown in the Files sidebar as the domain
sidebar_add "$MOUNT" "$CORE_DOMAIN"
# A new session through sudo picks up the davfs2 group now, without
# logging out and in again
if ! mountpoint -q "$MOUNT"; then
sudo -u "$USER" mount "$MOUNT" || return 1
fi
echo "Your Nextcloud files are at $MOUNT (\"$CORE_DOMAIN\" in the Files sidebar)."
}
# Element Desktop reads config.json in its settings folder (element_config)
# over its built-in settings. Pointing it at the Core's Matrix server means you only choose
# "Sign in" (the Core offers single sign-on through Authelia). The Core's Matrix
# server is named after its address, matrix.<domain>, and says where its API is.
setup_element() {
local base_url config
base_url="$(curl -sf --max-time 15 "$MATRIX/.well-known/matrix/client" \
| jq -r '.["m.homeserver"].base_url // empty' 2> /dev/null)"
base_url="${base_url:-$MATRIX}"
mkdir -p "$(dirname "$ELEMENT_CONFIG")"
config="$(cat "$ELEMENT_CONFIG" 2> /dev/null)"
[ -n "$config" ] || config='{}'
jq --arg url "${base_url%/}" --arg name "matrix.$CORE_DOMAIN" \
'.default_server_config = {"m.homeserver": {base_url: $url, server_name: $name}}' \
<<< "$config" > "$ELEMENT_CONFIG.tmp" && mv -f "$ELEMENT_CONFIG.tmp" "$ELEMENT_CONFIG" || return 1
echo "Element will use $MATRIX the next time it starts."
}
# Tally opens the page it showed last, so forget that one too
setup_tally() {
tally_setting set "$TALLY" domain "$PLAUSIBLE" || return 1
tally_setting set "$TALLY" current-url "" || return 1
echo "Tally for Plausible will show https://$PLAUSIBLE the next time it starts. Sign in there."
}
# Pauses email if the mail server stops taking its password (system/email-watch)
email_watch_on() {
mkdir -p "$UNITS" \
&& cp "$CONNECTOR/system/systemd/federated-connector-email-watch.service" "$UNITS/" \
&& systemctl --user daemon-reload \
&& systemctl --user enable -q federated-connector-email-watch.service 2> /dev/null \
&& systemctl --user restart federated-connector-email-watch.service 2> /dev/null
}
# Offer to install Element for the main Core, as the app for its chat
element_offer() {
element_installed && return 0
flatpak_ensure "$ELEMENT_FLATPAK" Element "It's the app for your Core's chat (Matrix)." || return 0
ELEMENT_CONFIG="$(element_config)"
}
# Run a step unless it's done; a failed step doesn't stop the ones after it
core_step() {
local name="$1" title="$2"
if "${name}_done"; then
echo " $title: already set up"
return 0
fi
if ! confirm_yes "Set up $title?"; then
return 0
fi
"setup_$name" || { echo -e "\e[31m$title was not set up.\e[0m"; STATUS=1; }
}
# Ask for your Core password until Nextcloud takes it, and with a name ($1),
# create an app password by that name (APP_PASSWORD). PASSWORD is left empty
# if Nextcloud says it's wrong three times, and kept, unchecked, if Nextcloud
# can't be reached.
ask_password() {
local tries
for _ in 1 2 3; do
read -rsp "Your Core password: " PASSWORD
echo
if [ -n "$1" ]; then nextcloud_app_password "$1"; else nextcloud_sign_in; fi
case $? in
0) return 0 ;;
2) echo "Nextcloud says that password is wrong."; PASSWORD="" ;;
*) echo "Couldn't reach Nextcloud at $NEXTCLOUD; trying the password for email anyway."; return 1 ;;
esac
done
return 1
}
# Set up the Core loaded with load_core, or a new one
setup_core() {
local url
STATUS=0
read -erp "Your Superpanel's address (e.g. https://superpanel.example.com): " \
-i "${CORE_DOMAIN:+https://superpanel.$CORE_DOMAIN}" url
url="${url#*://}"
url="${url%%/*}"
CORE_DOMAIN="${url#superpanel.}"
if [ -z "$CORE_DOMAIN" ] || ! curl -s -o /dev/null --max-time 15 "https://superpanel.$CORE_DOMAIN/"; then
echo "Couldn't reach https://superpanel.$CORE_DOMAIN."
return 1
fi
read -erp "Your Core email: " -i "${CORE_EMAIL:-$USER@$CORE_DOMAIN}" CORE_EMAIL
read -erp "Your name, as shown on email you send: " \
-i "${CORE_NAME:-$(getent passwd "$USER" | cut -d: -f5 | cut -d, -f1)}" CORE_NAME
[[ "$CORE_EMAIL" == *@* ]] || { echo "That isn't an email address."; return 1; }
core_names
save_conf
# Nextcloud, email and files need your Core password; Nextcloud checks it
if ! nextcloud_done || ! email_done || ! files_done; then
ask_password "Pop!_OS on $HOSTNAME"
fi
echo
core_step superpanel "Superpanel in your applications"
core_step nextcloud "Nextcloud calendars and contacts"
core_step email "Email"
core_step files "Nextcloud files at $MOUNT"
[ "$CORE_DOMAIN" = "$MAIN_DOMAIN" ] && element_offer && element_installed \
&& core_step element "Element with your Core's Matrix server"
[ "$CORE_DOMAIN" = "$MAIN_DOMAIN" ] && tally_installed && plausible_on_core \
&& core_step tally "Tally for Plausible with your Core's Plausible"
unset PASSWORD APP_PASSWORD
email_done && email_watch_on
return $STATUS
}
# Check an app password this computer keeps for the Core
app_password_works() {
local title="$1" app_password="$2"
[ -n "$app_password" ] || return 0
case "$(nextcloud_sign_in "$app_password"; echo $?)" in
0) echo " $title: working" ;;
2) echo -e " \e[31m$title: Nextcloud doesn't accept its app password.\e[0m"
echo " It may have been revoked in Nextcloud under Settings > Security."
return 1 ;;
*) echo " $title: couldn't reach Nextcloud to check" ;;
esac
}
# After your Core password changes, e.g. in Superpanel. Email keeps your Core
# password, so it gets the new one. Nextcloud, files and backups use app
# passwords, which stay the same; Nextcloud turns them off until you sign in
# with the new password, and checking the password here does that.
change_password() {
local tries reached=1
load_core "$1"
STATUS=0
for _ in 1 2 3; do
read -rsp "Your new Core password: " PASSWORD
echo
nextcloud_sign_in
case $? in
0) break ;;
2) echo "Nextcloud says that password is wrong."; PASSWORD="" ;;
*) echo "Couldn't reach Nextcloud at $NEXTCLOUD; trying the password for email anyway."
reached=0; break ;;
esac
done
[ -n "$PASSWORD" ] || return 1
echo
if email_done; then
local was_paused=""
"$GOA_ACCOUNT" paused imap_smtp "$CORE_EMAIL" 2> /dev/null && was_paused=", and isn't paused any more"
jq -n --arg password "$PASSWORD" '{"imap-password": $password, "smtp-password": $password}' \
| "$GOA_ACCOUNT" update imap_smtp "$CORE_EMAIL" 2> /dev/null
case $? in
0) echo " Email: has your new password$was_paused" ;;
3) echo -e " \e[31mEmail: saved your new password, but the mail server didn't accept it.\e[0m"
STATUS=1 ;;
*) echo -e " \e[31mEmail: couldn't save your new password.\e[0m"; STATUS=1 ;;
esac
fi
unset PASSWORD
[ $reached = 1 ] || return 1
if nextcloud_done; then
if "$GOA_ACCOUNT" check owncloud "$CORE_USER@nextcloud.$CORE_DOMAIN" 2> /dev/null; then
echo " Nextcloud calendars and contacts: working"
else
echo -e " \e[31mNextcloud calendars and contacts: can't sign in.\e[0m"
echo " To fix it: configure core, then choose t) Test a Core"
STATUS=1
fi
fi
files_done && { app_password_works "Files at $MOUNT" "$(files_app_password)" || STATUS=1; }
app_password_works "Backups" \
"$(secret-tool lookup federated-connector backup item nextcloud url "$WEBDAV" 2> /dev/null)" || STATUS=1
return $STATUS
}
# Tailscale and Backup point at one Core, which can't be removed while they do
tailscale_on() {
[ "$(source "$TAILSCALE_CONF" 2> /dev/null && echo "$TAILSCALE_DOMAIN")" = "$1" ] \
&& tailscale status --json 2> /dev/null | jq -e '.BackendState == "Running"' > /dev/null
}
backup_on() {
[[ "$(source "$BACKUP_CONF" 2> /dev/null && echo "$BACKUP_WEBDAV")" == "https://nextcloud.$1/"* ]] \
&& systemctl --user is-enabled -q federated-connector-backup.timer 2> /dev/null
}
# Choose one of DOMAINS, other than $2 if given; sets PICKED
pick_core() {
local choices=() domain choice i
for domain in "${DOMAINS[@]}"; do
[ "$domain" != "$2" ] && choices+=("$domain")
done
if [ ${#choices[@]} -eq 1 ]; then
PICKED="${choices[0]}"
return 0
fi
for i in "${!choices[@]}"; do
printf ' %d) %s\n' $((i + 1)) "${choices[$i]}"
done
read -rp "$1 " choice
[[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= ${#choices[@]} )) || return 1
PICKED="${choices[$((choice - 1))]}"
}
# Point Element at the main Core, and say what else follows it
main_changed() {
load_core "$MAIN_DOMAIN"
echo "$MAIN_DOMAIN is now your main Core."
if element_installed && ! element_done && confirm_yes "Point Element at $MATRIX?"; then
setup_element
fi
if tally_installed && ! tally_done && plausible_on_core \
&& confirm_yes "Point Tally for Plausible at https://$PLAUSIBLE?"; then
setup_tally
fi
[ -f "$TAILSCALE_CONF" ] && echo "To move this computer to its Tailscale network: configure tailscale"
[ -f "$BACKUP_CONF" ] && echo "To back up to it instead: configure backup"
return 0
}
# The app password this computer uses for the Core, from davfs2's secrets
files_app_password() {
grep -s "^$MOUNT " "$HOME/.davfs2/secrets" \
| python3 -I -c 'import shlex, sys; print(shlex.split(sys.stdin.read())[2])' 2> /dev/null
}
# Undo what setup_core did. Nothing on the Core itself changes.
remove_core() {
local domain="$1" new_main="" app_password mount_re
if tailscale_on "$domain"; then
echo "This computer is on $domain's Tailscale network. Leave it first: configure tailscale"
return 1
fi
if backup_on "$domain"; then
echo "Your backups go to $domain. Turn them off first: configure backup"
return 1
fi
if [ "$domain" = "$MAIN_DOMAIN" ] && [ ${#DOMAINS[@]} -gt 1 ]; then
echo "$domain is your main Core. Which Core should be the main one instead?"
pick_core "Choose:" "$domain" || { echo "Choose a number from the list."; return 1; }
new_main="$PICKED"
fi
echo "This removes $domain's Superpanel, Nextcloud, email and files from this computer."
echo "Your files, email and everything else stay on the Core."
confirm "Remove $domain?" || return 0
load_core "$domain"
app_password="$(files_app_password)"
[ -n "$app_password" ] && nextcloud_revoke_app_password "$app_password"
mountpoint -q "$MOUNT" && { umount "$MOUNT" 2> /dev/null || sudo umount "$MOUNT"; }
mount_re="${MOUNT//./\\.}"
if grep -qs " $MOUNT davfs " /etc/fstab; then
sudo sed -i "\\# $mount_re davfs #d" /etc/fstab && sudo systemctl daemon-reload
fi
[ -d "$MOUNT" ] && sudo rmdir "$MOUNT" 2> /dev/null
sed -i "\\#^$mount_re #d" "$HOME/.davfs2/secrets" 2> /dev/null
sidebar_remove "$MOUNT"
rm -f "$HOME/.config/autostart/core-$CORE_DOMAIN-files.desktop"
"$GOA_ACCOUNT" remove owncloud "$CORE_USER@nextcloud.$CORE_DOMAIN"
"$GOA_ACCOUNT" remove imap_smtp "$CORE_EMAIL"
rm -f "$SUPERPANEL_DESKTOP" "$HOME/.local/share/icons/core-$CORE_DOMAIN-superpanel.png"
# Element keeps its default server, unless that was this Core
if [ "$domain" = "$MAIN_DOMAIN" ] && [ -z "$new_main" ] && [ -f "$ELEMENT_CONFIG" ] \
&& jq -e --arg name "matrix.$domain" '.default_server_config["m.homeserver"].server_name == $name' \
"$ELEMENT_CONFIG" &> /dev/null; then
jq 'del(.default_server_config)' "$ELEMENT_CONFIG" > "$ELEMENT_CONFIG.tmp" \
&& mv -f "$ELEMENT_CONFIG.tmp" "$ELEMENT_CONFIG"
fi
rm -f "$CORES_DIR/$domain.conf"
echo "Removed $domain from this computer."
if [ -n "$new_main" ]; then
make_main "$new_main" && main_changed
elif [ "$domain" = "$MAIN_DOMAIN" ]; then
rm -f "$CORE_CONF"
fi
}
# Testing a Core checks each part this computer set up for it against the
# Core itself, then offers to fix what doesn't work. A test that fails adds a
# fix, if there is one, to FIXES (with its title in FIX_TITLES).
passed() {
echo -e " $1: \e[32mworking\e[0m"
}
# failed <title> <problem> [fix] [more]
failed() {
echo -e " \e[31m$1: $2\e[0m"
[ -n "$4" ] && echo " $4"
PROBLEMS=$((PROBLEMS + 1))
[ -n "$3" ] && FIXES+=("$3") FIX_TITLES+=("$1")
}
# Test an Online Accounts account, and that none of what this set it up
# for is turned off (e.g. with GNOME Settings, if it was ever installed):
# <title> <provider> <identity> <setup> <fix> <enable>
# Email's password is checked with Nextcloud before it's tried on the mail
# server: each wrong password counts towards the mail server blocking this
# computer. Online Accounts 3.50, which Pop!_OS 24.04 has, marks an account
# as needing attention when the server can't be reached too, so that isn't
# taken to mean a wrong password.
test_account() {
local error off works=1
if ! "$GOA_ACCOUNT" exists "$2" "$3" 2> /dev/null; then
failed "$1" "not set up" "$4"
return
fi
if "$GOA_ACCOUNT" paused "$2" "$3" 2> /dev/null; then
failed "$1" "paused, as the server stopped taking its password" "$5" \
"So this computer doesn't keep trying it. Did your Core password change?"
works=0
elif [ "$2" = imap_smtp ] && { "$EMAIL_WATCH" --check-password "$3"; [ $? -eq 2 ]; }; then
failed "$1" "has an old password: Nextcloud doesn't take it" "$5" "Did your Core password change?"
works=0
elif ! error="$("$GOA_ACCOUNT" check "$2" "$3" 2>&1)"; then
failed "$1" "can't sign in" "$5" "$error"
works=0
fi
off="$("$GOA_ACCOUNT" disabled "$2" "$3" 2> /dev/null)"
if [ -n "$off" ]; then
failed "$1" "turned off: $off" "$6"
elif [ $works -eq 1 ]; then
passed "$1"
fi
}
test_files() {
local title="Nextcloud files at $MOUNT"
files_done || { failed "$title" "not set up" setup_files; return; }
nextcloud_sign_in "$(files_app_password)"
case $? in
0) if mountpoint -q "$MOUNT" && timeout 15 ls "$MOUNT" &> /dev/null; then
passed "$title"
else
failed "$title" "not mounted" remount_files
fi ;;
2) failed "$title" "Nextcloud doesn't accept its app password" fix_files \
"It may have been revoked in Nextcloud under Settings > Security." ;;
*) failed "$title" "couldn't check its app password" ;;
esac
}
test_element() {
local title="Element with your Core's Matrix server"
if ! element_done; then
failed "$title" "Element uses another server" setup_element
elif curl -sf -o /dev/null --max-time 15 "$MATRIX/_matrix/client/versions"; then
passed "$title"
else
failed "$title" "can't reach $MATRIX"
fi
}
test_tally() {
local title="Tally for Plausible with your Core's Plausible"
plausible_on_core || return 0
if tally_done; then
passed "$title"
else
failed "$title" "Tally shows another Plausible" setup_tally
fi
}
test_backups() {
local webdav
webdav="$(source "$BACKUP_CONF" && echo "$BACKUP_WEBDAV")"
nextcloud_sign_in "$(secret-tool lookup federated-connector backup item nextcloud url "$webdav" 2> /dev/null)"
case $? in
0) passed "Backups" ;;
2) failed "Backups" "Nextcloud doesn't accept their app password" fix_backups ;;
*) failed "Backups" "couldn't check their app password" ;;
esac
}
# Test the Core loaded with load_core. Fails if Nextcloud can't be reached,
# as then nothing else can be tested.
test_core() {
local status
FIXES=() FIX_TITLES=() PROBLEMS=0
status="$(curl -sf --max-time 15 "$NEXTCLOUD/status.php")"
if [ -z "$status" ]; then
echo -e " \e[31mCouldn't reach Nextcloud at $NEXTCLOUD.\e[0m"
echo " Check this computer's internet connection, or whether your Core is down."
return 1
fi
if jq -e '.maintenance' <<< "$status" > /dev/null 2>&1; then
echo " Nextcloud is being updated (maintenance mode). Test again when it's done."
return 1
fi
if ! superpanel_done; then
failed "Superpanel in your applications" "not set up" setup_superpanel
elif curl -s -o /dev/null --max-time 15 "https://superpanel.$CORE_DOMAIN/"; then
passed "Superpanel"
else
failed "Superpanel" "can't reach https://superpanel.$CORE_DOMAIN"
fi
test_account "Nextcloud calendars and contacts" owncloud "$CORE_USER@nextcloud.$CORE_DOMAIN" \
setup_nextcloud fix_nextcloud enable_nextcloud
test_account "Email" imap_smtp "$CORE_EMAIL" setup_email fix_email enable_email
test_files
[ "$CORE_DOMAIN" = "$MAIN_DOMAIN" ] && element_installed && test_element
[ "$CORE_DOMAIN" = "$MAIN_DOMAIN" ] && tally_installed && test_tally
backup_on "$CORE_DOMAIN" && test_backups
return 0
}
# Calendars and contacts get a new app password
fix_nextcloud() {
[ -n "$APP_PASSWORD" ] || { echo "This needs your Core password, and Nextcloud didn't accept it."; return 1; }
jq -n --arg password "$APP_PASSWORD" '{password: $password}' \
| "$GOA_ACCOUNT" update owncloud "$CORE_USER@nextcloud.$CORE_DOMAIN" || return 1
echo "Nextcloud calendars and contacts have a new app password."
}
enable_nextcloud() {
"$GOA_ACCOUNT" enable owncloud "$CORE_USER@nextcloud.$CORE_DOMAIN" || return 1
echo "Turned Nextcloud's calendar, contacts and files back on."
}
enable_email() {
"$GOA_ACCOUNT" enable imap_smtp "$CORE_EMAIL" || return 1
echo "Turned email back on."
}
# Email gets your Core password. If the mail server still says no, its
# settings may have changed, so add it again with the server's settings now.
fix_email() {
[ -n "$PASSWORD" ] || { echo "This needs your Core password."; return 1; }
jq -n --arg password "$PASSWORD" '{"imap-password": $password, "smtp-password": $password}' \
| "$GOA_ACCOUNT" update imap_smtp "$CORE_EMAIL" 2> /dev/null
case $? in
0) echo "Email has your Core password." ;;
3) echo "The mail server still says no; adding your email again with its current settings."
"$GOA_ACCOUNT" remove imap_smtp "$CORE_EMAIL" && setup_email ;;
*) return 1 ;;
esac
}
# Unmount if it's stuck, then mount
remount_files() {
if mountpoint -q "$MOUNT"; then
umount "$MOUNT" 2> /dev/null || sudo umount "$MOUNT" || return 1
fi
mount "$MOUNT" 2> /dev/null || sudo -u "$USER" mount "$MOUNT" || return 1
echo "Your Nextcloud files are at $MOUNT."
}
# davfs2 gets a new app password
fix_files() {
[ -n "$APP_PASSWORD" ] || { echo "This needs your Core password, and Nextcloud didn't accept it."; return 1; }
save_files_secret && remount_files
}
# Backups get their own new app password, as configure backup gives them
fix_backups() {
local APP_PASSWORD webdav
[ -n "$PASSWORD" ] || { echo "This needs your Core password."; return 1; }
webdav="$(source "$BACKUP_CONF" && echo "$BACKUP_WEBDAV")"
nextcloud_app_password "Federated Backup on $HOSTNAME" || return 1
printf '%s' "$APP_PASSWORD" | secret-tool store --label "Federated Connector backup nextcloud ($webdav)" \
federated-connector backup item nextcloud url "$webdav" || return 1
echo "Backups have a new app password."
}
# Run the fixes test_core found, asking for your Core password once if they
# need it
fix_core() {
local fix i needs=""
for fix in "${FIXES[@]}"; do
case "$fix" in
setup_nextcloud|fix_nextcloud|setup_files|fix_files) needs=app ;;
setup_email|fix_email|fix_backups) needs="${needs:-password}" ;;
esac
done
case "$needs" in
app) ask_password "Pop!_OS on $HOSTNAME" ;;
password) ask_password ;;
esac
STATUS=0
for i in "${!FIXES[@]}"; do
echo
echo "${FIX_TITLES[$i]}:"
"${FIXES[$i]}" || { echo -e "\e[31m${FIX_TITLES[$i]} was not fixed.\e[0m"; STATUS=1; }
done
unset PASSWORD APP_PASSWORD
return $STATUS
}
check_core() {
load_core "$1"
echo "Testing $CORE_DOMAIN..."
test_core || return 1
if [ $PROBLEMS -eq 0 ]; then
echo "Everything works."
return 0
fi
echo
if [ ${#FIXES[@]} -eq 0 ]; then
echo "This computer can't fix that; it's on the Core's side, or the network's."
return 1
fi
confirm_yes "Fix what doesn't work?" || return 1
fix_core
echo
echo "Testing $CORE_DOMAIN again..."
test_core || return 1
if [ $PROBLEMS -eq 0 ]; then
echo "Everything works now."
else
echo "Some of it still doesn't work."
return 1
fi
}
run_configure() {
local choice i state
mapfile -t DOMAINS < <(core_domains)
if [ ${#DOMAINS[@]} -eq 0 ]; then
load_core ""
setup_core
return
fi
echo "Your Cores:"
for i in "${!DOMAINS[@]}"; do
if (load_core "${DOMAINS[$i]}" && core_done); then
state="\e[32mdone\e[0m "
else
state="\e[33mto do\e[0m"
fi
printf " %d) $state %s%s\n" $((i + 1)) "${DOMAINS[$i]}" \
"$([ "${DOMAINS[$i]}" = "$MAIN_DOMAIN" ] && echo " (main)")"
done
echo
echo " Choose a number to finish or change its setup, or:"
echo " a) Add a Core"
[ ${#DOMAINS[@]} -gt 1 ] && echo " m) Make another Core the main one"
echo " t) Test a Core, and fix what doesn't work"
echo " p) Your Core password changed"
echo " r) Remove a Core"
echo " q) Leave it as it is"
echo
read -rp "Choose: " choice
case "$choice" in
a|A)
load_core ""
setup_core ;;
m|M)
[ ${#DOMAINS[@]} -gt 1 ] || return 0
pick_core "Which should be the main one?" "$MAIN_DOMAIN" || { echo "Choose a number from the list."; return 1; }
make_main "$PICKED" && main_changed ;;
p|P)
pick_core "Which Core's password changed?" || { echo "Choose a number from the list."; return 1; }
change_password "$PICKED" ;;
t|T)
pick_core "Which Core should be tested?" || { echo "Choose a number from the list."; return 1; }
check_core "$PICKED" ;;
r|R)
pick_core "Which Core should be removed?" || { echo "Choose a number from the list."; return 1; }
remove_core "$PICKED" ;;
*)
if [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= ${#DOMAINS[@]} )); then
load_core "${DOMAINS[$((choice - 1))]}"
setup_core
fi ;;
esac
}
+93
View File
@@ -0,0 +1,93 @@
#!/bin/bash
# configure reads TITLE and DESCRIPTION
# shellcheck disable=SC2034
TITLE="Tailscale"
# shellcheck disable=SC2034
DESCRIPTION="Join your Core's Tailscale network"
CORE_CONF="$CONF_DIR/core.conf"
TAILSCALE_CONF="$CONF_DIR/tailscale.conf"
[ -f "$CORE_CONF" ] && source "$CORE_CONF"
[ -f "$TAILSCALE_CONF" ] && source "$TAILSCALE_CONF"
# Tailscale's own installer adds its apt repository (pkgs.tailscale.com), so
# Pop!_OS' updates keep it up to date. It's downloaded, then run, rather than
# piped into a shell.
install_tailscale() {
local tmp status
echo "Tailscale isn't installed. It comes from Tailscale's own apt repository."
confirm_yes "Install it?" || return 1
tmp="$(mktemp -d)" || return 1
if curl -fsSL --max-time 60 -o "$tmp/install.sh" https://tailscale.com/install.sh; then
sh "$tmp/install.sh"
status=$?
else
echo "Couldn't download Tailscale's installer."
status=1
fi
rm -rf "$tmp"
return $status
}
# Tailscale has no status field naming its login server, so tailscale.conf
# records which Core it was set up for
joined() {
[ -n "$TAILSCALE_DOMAIN" ] \
&& tailscale status --json 2> /dev/null | jq -e '.BackendState == "Running"' > /dev/null
}
# Done when on the main Core's network
is_configured() {
[ -n "$CORE_DOMAIN" ] && [ "$TAILSCALE_DOMAIN" = "$CORE_DOMAIN" ] && joined
}
# Log out rather than only go down, so this computer's key is expired on
# headscale and it's off the network until it joins again
leave_network() {
sudo tailscale logout || return 1
rm -f "$TAILSCALE_CONF"
echo "This computer has left your Core's Tailscale network. To join again: configure tailscale"
}
run_configure() {
local choice
if joined &> /dev/null; then
echo "This computer is on $TAILSCALE_DOMAIN's Tailscale network (headscale.$TAILSCALE_DOMAIN)."
echo
if [ "$TAILSCALE_DOMAIN" = "$CORE_DOMAIN" ]; then
echo " 1) Join it again"
else
echo " 1) Join your main Core's network instead (headscale.$CORE_DOMAIN)"
fi
echo " 2) Leave the network"
echo " q) Leave it as it is"
echo
read -rp "Choose: " choice
case "$choice" in
1) ;;
2) leave_network; return ;;
*) return 0 ;;
esac
fi
if [ -z "$CORE_DOMAIN" ]; then
echo "This joins your Core's Tailscale network, so set up your Core first: configure core"
return 1
fi
command -v tailscale > /dev/null || install_tailscale || return 1
# --reset and --force-reauth move the machine from any other tailnet;
# --operator lets you use it without sudo
if ! systemctl is-active -q tailscaled; then
sudo systemctl enable --now tailscaled || return 1
fi
echo "Open the link below to sign in to your Core's Tailscale network (headscale.$CORE_DOMAIN)."
sudo tailscale up --reset --force-reauth --login-server "https://headscale.$CORE_DOMAIN" \
--accept-routes --operator="$USER" || return 1
mkdir -p "$(dirname "$TAILSCALE_CONF")"
printf 'TAILSCALE_DOMAIN=%q\n' "$CORE_DOMAIN" > "$TAILSCALE_CONF"
echo "This computer is on your Core's Tailscale network."
}
+188
View File
@@ -0,0 +1,188 @@
#!/bin/bash
# configure reads TITLE and DESCRIPTION
# shellcheck disable=SC2034
TITLE="Backup"
# shellcheck disable=SC2034
DESCRIPTION="Back up your home folder daily to your Nextcloud files"
CORE_CONF="$CONF_DIR/core.conf"
BACKUP_CONF="$CONF_DIR/backup.conf"
UNITS="$HOME/.config/systemd/user"
source "$CONNECTOR/configure.d/lib/nextcloud.sh"
[ -f "$CORE_CONF" ] && source "$CORE_CONF"
backups_on() {
source "$CONNECTOR/system/backup-env.sh" > /dev/null || return 1
[ -n "$RESTIC_PASSWORD_COMMAND" ] && systemctl --user is-enabled -q federated-connector-backup.timer
}
# Done when backing up to the main Core
is_configured() {
backups_on && [ "$BACKUP_WEBDAV" = "https://nextcloud.$CORE_DOMAIN/remote.php/dav/files/${CORE_EMAIL%@*}" ]
}
save_secret() {
printf '%s' "$3" | secret-tool store --label "Federated Connector backup $1 ($2)" \
federated-connector backup item "$1" url "$2"
}
# The backup gets its own app password, so revoking it stops only backups
nextcloud_login() {
local tries
[ -n "$(backup_secret nextcloud "$WEBDAV")" ] \
&& rclone lsf --max-depth 1 ":webdav:" > /dev/null 2>&1 && return 0
for _ in 1 2 3; do
read -rsp "Your Core password: " PASSWORD
echo
nextcloud_app_password "Federated Backup on $HOSTNAME"
case $? in
0) break ;;
2) echo "Nextcloud says that password is wrong." ;;
*) echo "Couldn't reach Nextcloud at $NEXTCLOUD."; return 1 ;;
esac
done
unset PASSWORD
[ -n "$APP_PASSWORD" ] || return 1
save_secret nextcloud "$WEBDAV" "$APP_PASSWORD" || return 1
unset APP_PASSWORD
RCLONE_WEBDAV_PASS="$(backup_secret nextcloud "$WEBDAV" | rclone obscure -)"
}
new_passphrase() {
local pass
pass="$(head -c 24 /dev/urandom | base64)"
echo "Your backup is encrypted with this passphrase:"
echo
echo " $pass"
echo
echo "Save it somewhere other than this computer, such as Bitwarden. Without it, the"
echo "backup can't be read if this computer is lost. It's kept in your keyring so the"
echo "daily backup can run."
until confirm "Have you saved it?"; do :; done
save_secret passphrase "$WEBDAV/$BACKUP_DIR" "$pass"
}
# Stop the daily backup and any running now, and remove its units
stop_backups() {
systemctl --user disable --now federated-connector-backup.timer 2> /dev/null
systemctl --user stop federated-connector-backup.service 2> /dev/null
rm -f "$UNITS"/federated-connector-backup.{service,timer}
systemctl --user daemon-reload
}
# Delete the backup from Nextcloud, then what's on this computer for it:
# without the backup, the passphrase and app password are no use
delete_backups() {
local app_password
nextcloud_login || { echo "Couldn't sign in to Nextcloud."; return 1; }
echo "Deleting $BACKUP_DIR from your Nextcloud files..."
rclone purge ":webdav:$BACKUP_DIR" \
|| { echo "rclone couldn't delete $BACKUP_DIR."; return 1; }
echo "Deleted. Nextcloud keeps it in its trash bin, where it still uses space, until you empty it."
app_password="$(backup_secret nextcloud "$WEBDAV")"
[ -n "$app_password" ] && nextcloud_revoke_app_password "$app_password"
secret-tool clear federated-connector backup item nextcloud url "$WEBDAV"
secret-tool clear federated-connector backup item passphrase url "$WEBDAV/$BACKUP_DIR"
rm -f "$BACKUP_CONF"
}
turn_off() {
local answer
WEBDAV="$BACKUP_WEBDAV"
CORE_USER="$BACKUP_USER"
NEXTCLOUD="${BACKUP_WEBDAV%%/remote.php/*}"
stop_backups
echo "Backups are off."
echo
echo "The backups made so far are still in $BACKUP_DIR in your Nextcloud files."
if ! confirm "Delete them? They can't be restored from after that."; then
echo "Kept them. To turn backups back on: configure backup"
return 0
fi
read -rp "To delete them, type the folder name ($BACKUP_DIR): " answer
if [ "$answer" != "$BACKUP_DIR" ]; then
echo "That's not the folder name, so the backups were kept."
return 0
fi
delete_backups
}
run_configure() {
local pass choice
if backups_on &> /dev/null; then
if is_configured &> /dev/null; then
echo "Your home folder is backed up daily to $BACKUP_DIR in your Nextcloud files."
echo
echo " 1) Set it up again"
else
echo "Your home folder is backed up daily to $BACKUP_DIR on ${BACKUP_WEBDAV%%/remote.php/*},"
echo "which isn't your main Core."
echo
echo " 1) Back up to your main Core ($CORE_DOMAIN) instead; the backups so far stay where they are"
fi
echo " 2) Turn backups off"
echo " q) Leave it as it is"
echo
read -rp "Choose: " choice
case "$choice" in
1) ;;
2) turn_off; return ;;
*) return 0 ;;
esac
fi
if [ -z "$CORE_DOMAIN" ] || [ -z "$CORE_EMAIL" ]; then
echo "Backups go to your Nextcloud files, so set up your Core first: configure core"
return 1
fi
# Ubuntu's restic and rclone are recent enough: restic reaches rclone's
# WebDAV backend since 0.8, and rclone obscure reads stdin since 1.52
pkg_ensure "Backups" restic rclone libsecret-tools || return 1
CORE_USER="${CORE_EMAIL%@*}"
NEXTCLOUD="https://nextcloud.$CORE_DOMAIN"
WEBDAV="$NEXTCLOUD/remote.php/dav/files/$CORE_USER"
BACKUP_DIR=".backup-$HOSTNAME"
mkdir -p "$(dirname "$BACKUP_CONF")"
{
printf 'BACKUP_WEBDAV=%q\n' "$WEBDAV"
printf 'BACKUP_USER=%q\n' "$CORE_USER"
printf 'BACKUP_DIR=%q\n' "$BACKUP_DIR"
} > "$BACKUP_CONF"
source "$CONNECTOR/system/backup-env.sh"
nextcloud_login || { echo "Couldn't sign in to Nextcloud."; return 1; }
if rclone lsf --files-only ":webdav:$BACKUP_DIR" 2> /dev/null | grep -qx config; then
# Already there, e.g. after reinstalling: it needs the passphrase from then
if [ -z "$RESTIC_PASSWORD_COMMAND" ] || ! restic cat config &> /dev/null; then
echo "There's already a backup in $BACKUP_DIR in your Nextcloud files."
read -rsp "Its passphrase: " pass
echo
RESTIC_PASSWORD_COMMAND='' RESTIC_PASSWORD="$pass" restic cat config > /dev/null \
|| { echo "restic couldn't open it with that passphrase."; return 1; }
save_secret passphrase "$WEBDAV/$BACKUP_DIR" "$pass" || return 1
fi
echo "Using the backup in $BACKUP_DIR."
else
new_passphrase || return 1
source "$CONNECTOR/system/backup-env.sh"
echo "Creating the backup in $BACKUP_DIR in your Nextcloud files..."
restic init || return 1
fi
mkdir -p "$UNITS"
cp "$CONNECTOR"/system/systemd/federated-connector-backup.{service,timer} "$UNITS/" || return 1
systemctl --user daemon-reload
systemctl --user enable --now federated-connector-backup.timer || return 1
echo "Your home folder will be backed up daily to $BACKUP_DIR in your Nextcloud files."
if confirm_yes "Start the first backup now? It runs in the background and can take hours."; then
systemctl --user start --no-block federated-connector-backup.service
echo "Started. To follow it: journalctl --user -fu federated-connector-backup"
fi
}
+260
View File
@@ -0,0 +1,260 @@
#!/bin/bash
# configure reads TITLE and DESCRIPTION
# shellcheck disable=SC2034
TITLE="AI agents"
# shellcheck disable=SC2034
DESCRIPTION="Install Claude Code, opencode and Hermes, sandboxed"
# Exists once you've run this, even if you installed no agents
AGENTS_CONF="$CONF_DIR/agents"
CLAUDE_SETTINGS="$HOME/.claude/settings.json"
BASE_CONFIG="$CONNECTOR/sandbox/config/base.json"
BASHRC="$HOME/.bashrc"
BLOCK_START="# >>> Federated Connector: agents >>>"
BLOCK_END="# <<< Federated Connector: agents <<<"
APPARMOR_PROFILE="/etc/apparmor.d/federated-connector-bwrap"
source "$CONNECTOR/configure.d/lib/json.sh"
source "$CONNECTOR/configure.d/lib/tools.sh"
# name|title|installer|installer's arguments. Each agent's own installer, from
# its makers. --non-interactive skips Hermes' setup questions and its gateway
# service; configure hermes chooses a model provider afterwards.
AGENTS=(
"claude|Claude Code (Anthropic)|https://claude.ai/install.sh|"
"opencode|opencode|https://opencode.ai/install|"
"hermes|Hermes Agent (Nous Research)|https://hermes-agent.nousresearch.com/install.sh|--non-interactive"
)
# srt (and Claude Code's own sandbox) use bubblewrap for the files an agent
# can see, socat to link it to the network proxy, and ripgrep to find the
# files it must not change. Node.js' own builds need libatomic.
SANDBOX_PACKAGES=(bubblewrap socat ripgrep libatomic1)
# --- Typing an agent's name runs it in the sandbox -------------------------------
# The block goes last in ~/.bashrc, so agents' installers adding their own
# folders to PATH don't come before it
path_block() {
cat << EOF
$BLOCK_START
# Typing an AI agent's name runs it in the sandbox: configure agents
export PATH="$SANDBOX_BIN:\$PATH"
$BLOCK_END
EOF
}
on_path() {
[ -f "$BASHRC" ] && [ "$(grep -v '^[[:space:]]*$' "$BASHRC" | tail -n 4)" = "$(path_block)" ]
}
put_on_path() {
local tmp
touch "$BASHRC" || return 1
tmp="$(mktemp)" || return 1
awk -v start="$BLOCK_START" -v end="$BLOCK_END" \
'$0 == start { skip = 1 } !skip { print } $0 == end { skip = 0 }' "$BASHRC" > "$tmp"
{ cat "$tmp"; echo; path_block; } > "$BASHRC"
rm -f "$tmp"
echo "Agents run in the sandbox in new terminals. To run one without it: unsandboxed <agent>"
}
# --- bubblewrap and Ubuntu's AppArmor ---------------------------------------------
# Ubuntu 24.04 lets only programs AppArmor allows make the user namespaces
# bubblewrap needs, and has no rule for bubblewrap itself
bwrap_works() {
bwrap --ro-bind / / --unshare-user --unshare-net true 2> /dev/null
}
allow_bwrap() {
echo "Ubuntu's AppArmor doesn't let bubblewrap, which the sandbox is built on, make"
echo "user namespaces. A profile for /usr/bin/bwrap allows it, as Ubuntu suggests."
confirm_yes "Add it ($APPARMOR_PROFILE)?" || return 1
sudo tee "$APPARMOR_PROFILE" > /dev/null << 'EOF' || return 1
# Written by Federated Connector (configure agents): let bubblewrap, which the
# AI agent sandbox uses, make user namespaces
abi <abi/4.0>,
include <tunables/global>
profile federated-connector-bwrap /usr/bin/bwrap flags=(unconfined) {
userns,
include if exists <local/federated-connector-bwrap>
}
EOF
sudo apparmor_parser -r "$APPARMOR_PROFILE" || return 1
bwrap_works || { echo "bubblewrap still can't make user namespaces."; return 1; }
}
# --- Claude Code -------------------------------------------------------------------
# Claude Code runs every command it starts in its own sandbox, also built on
# bubblewrap and socat; it can't run inside srt because bubblewrap can't be
# nested. Anything already in the sandbox section of your settings wins over
# these defaults.
claude_sandbox_on() {
jq -e '.sandbox.enabled == true' "$CLAUDE_SETTINGS" &> /dev/null
}
turn_on_claude_sandbox() {
local domains
domains="$(jq '.network.allowedDomains' "$BASE_CONFIG")" || return 1
edit_json "$CLAUDE_SETTINGS" '{}' --argjson domains "$domains" \
'.sandbox = ({enabled: true, network: {allowedDomains: $domains}} * (.sandbox // {}))' || return 1
echo "Claude Code runs the commands it starts in its own sandbox."
}
# A desktop notification when Claude Code needs you or is done, if you have no
# settings of your own yet
claude_notifications() {
[ -f "$CLAUDE_SETTINGS" ] && return 0
edit_json "$CLAUDE_SETTINGS" '{}' \
--arg needs "notify-send 'Claude Code' 'Needs your input'" \
--arg finished "notify-send 'Claude Code' 'Task completed'" \
'.hooks = {
Notification: [{matcher: "", hooks: [{type: "command", command: $needs}]}],
Stop: [{matcher: "", hooks: [{type: "command", command: $finished}]}]
}' || return 1
echo "Claude Code shows a notification when it needs you and when it's done."
}
# --- Hermes' gateway and Cline Desktop -----------------------------------------------
# Hermes' gateway acts on messages from outside this machine, so it runs in
# the sandbox too: a systemd drop-in starts it through sandbox/bin/hermes. It
# also needs to reach the Matrix server in Hermes' settings, which differs on
# each machine; for other messaging services, add their domains to
# ~/.config/federated-connector/sandbox/hermes.json.
GATEWAY_UNIT="$HOME/.config/systemd/user/hermes-gateway.service"
GATEWAY_DROPIN="$GATEWAY_UNIT.d/federated-connector-sandbox.conf"
gateway_dropin() {
local homeserver
homeserver="$(sed -nE "s#^MATRIX_HOMESERVER=[\"']?https?://([^/:\"']+).*#\1#p" "$HOME/.hermes/.env" 2> /dev/null | head -n 1)"
cat << EOF
# Written by Federated Connector (configure agents): run Hermes' gateway in the sandbox
[Service]
Environment="FEDERATED_SANDBOX_DOMAINS=$homeserver"
ExecStart=
ExecStart=$SANDBOX_BIN/hermes gateway run
EOF
}
gateway_ok() {
[ ! -f "$GATEWAY_UNIT" ] || [ "$(cat "$GATEWAY_DROPIN" 2> /dev/null)" = "$(gateway_dropin)" ]
}
sandbox_gateway() {
gateway_ok && return 0
mkdir -p "$(dirname "$GATEWAY_DROPIN")" && gateway_dropin > "$GATEWAY_DROPIN" \
&& systemctl --user daemon-reload || return 1
echo "Hermes' gateway runs in the sandbox (from its next start)."
}
# Cline Desktop is opened from the app menu, so an entry of the same name in
# ~/.local/share/applications, which wins over the package's, runs it in the
# sandbox. It's removed when the package is.
CLINE_DESKTOP="/usr/share/applications/cline-desktop.desktop"
CLINE_ENTRY="$HOME/.local/share/applications/cline-desktop.desktop"
cline_entry() {
sed "s#^Exec=.*#Exec=$SANDBOX_BIN/cline-desktop %U#" "$CLINE_DESKTOP"
}
cline_ok() {
if [ -f "$CLINE_DESKTOP" ]; then
[ "$(cat "$CLINE_ENTRY" 2> /dev/null)" = "$(cline_entry)" ]
else
[ ! -f "$CLINE_ENTRY" ]
fi
}
sandbox_cline() {
cline_ok && return 0
if [ -f "$CLINE_DESKTOP" ]; then
mkdir -p "$(dirname "$CLINE_ENTRY")" && cline_entry > "$CLINE_ENTRY" || return 1
echo "Cline Desktop runs in the sandbox."
else
rm -f "$CLINE_ENTRY"
fi
}
# --- The item -------------------------------------------------------------------------
sandbox_ready() {
srt_path > /dev/null && on_path && pkg_installed "${SANDBOX_PACKAGES[@]}" && bwrap_works \
&& { ! agent_installed claude || claude_sandbox_on; } && gateway_ok && cline_ok
}
is_configured() {
[ -f "$AGENTS_CONF" ] && sandbox_ready
}
# Download the installer, then run it, rather than piping it into bash
install_agent() {
local title="$1" url="$2" args="$3" tmp status
tmp="$(mktemp -d)" || return 1
echo "Downloading $title's installer from $url"
if curl -fsSL --max-time 120 -o "$tmp/install.sh" "$url"; then
# shellcheck disable=SC2086
(cd "$tmp" && bash ./install.sh $args)
status=$?
else
echo "Couldn't download it."
status=1
fi
rm -rf "$tmp"
return $status
}
run_configure() {
local entry name title url args status=0
mkdir -p "$CONF_DIR" && touch "$AGENTS_CONF" || return 1
echo "AI coding agents, run in a sandbox: an agent can change files only in the folder"
echo "you start it in, can't read your keys, passwords, browsers, mail or messages, and"
echo "reaches only AI providers and developer sites."
echo
for entry in "${AGENTS[@]}"; do
IFS='|' read -r name title url args <<< "$entry"
if agent_installed "$name"; then
echo " $title: installed"
elif confirm_yes "Install $title?"; then
if ! install_agent "$title" "$url" "$args" || ! agent_installed "$name"; then
echo -e "\e[31m$title was not installed.\e[0m"
status=1
fi
fi
done
echo
pkg_ensure "The sandbox" "${SANDBOX_PACKAGES[@]}" || return 1
if ! bwrap_works; then
if [ "$(sysctl -n kernel.apparmor_restrict_unprivileged_userns 2> /dev/null)" = 1 ]; then
allow_bwrap || { echo -e "\e[31mWithout it, the agents can't run in the sandbox.\e[0m"; return 1; }
else
echo -e "\e[31mbubblewrap can't make user namespaces on this computer, so the sandbox can't run.\e[0m"
return 1
fi
fi
srt_ensure || { echo -e "\e[31mWithout srt, opencode and Hermes can't run in the sandbox.\e[0m"; return 1; }
if ! on_path; then
echo "Typing opencode or hermes should run it in the sandbox. That takes a line at the"
echo "end of ~/.bashrc."
if confirm_yes "Add it?"; then
put_on_path || status=1
else
echo "Then run them sandboxed as $SANDBOX_BIN/<agent>."
fi
fi
if agent_installed claude; then
claude_notifications || status=1
claude_sandbox_on || turn_on_claude_sandbox || status=1
fi
sandbox_gateway || status=1
sandbox_cline || status=1
echo
echo "To sign in to them: configure claude, configure opencode, configure hermes"
return $status
}
+29
View File
@@ -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
}
+26
View File
@@ -0,0 +1,26 @@
#!/bin/bash
# configure reads TITLE and DESCRIPTION
# shellcheck disable=SC2034
TITLE="opencode"
# shellcheck disable=SC2034
DESCRIPTION="Sign in to AI providers"
source "$CONNECTOR/configure.d/lib/agents.sh"
is_installed() {
agent_installed opencode
}
# Signed in to at least one provider
is_configured() {
jq -e 'length > 0' "$HOME/.local/share/opencode/auth.json"
}
run_configure() {
echo "Choose a provider and sign in or paste its API key. You can pick the model inside opencode with /models."
unsandboxed opencode auth login || return 1
while confirm "Sign in to another provider?"; do
unsandboxed opencode auth login || return 1
done
}
+30
View File
@@ -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
}
+98
View File
@@ -0,0 +1,98 @@
#!/bin/bash
# configure reads TITLE and DESCRIPTION
# shellcheck disable=SC2034
TITLE="Languages"
# shellcheck disable=SC2034
DESCRIPTION="Install programming languages with mise, e.g. Ruby on Rails"
# Records that you've chosen, even if you chose nothing, so this isn't "to do"
LANGUAGES_CONF="$CONF_DIR/languages"
# mise installs these gems into each Ruby it installs, so Rails is still there
# after mise upgrade moves to a new Ruby
DEFAULT_GEMS="$HOME/.default-gems"
# mise's activation line goes in ~/.bashrc, so the languages it installs are
# on PATH in new terminals
BASHRC="$HOME/.bashrc"
BLOCK_START="# >>> Federated Connector: mise >>>"
BLOCK_END="# <<< Federated Connector: mise <<<"
# Ruby is built from source, which needs these (from ruby-build's wiki)
RUBY_BUILD_DEPS=(build-essential autoconf patch rustc libssl-dev libyaml-dev libreadline-dev
zlib1g-dev libgmp-dev libncurses-dev libffi-dev libgdbm-dev libdb-dev uuid-dev)
is_configured() {
[ -f "$LANGUAGES_CONF" ]
}
# Add a gem to ~/.default-gems unless it's there
add_default_gem() {
grep -qsx "$1" "$DEFAULT_GEMS" || echo "$1" >> "$DEFAULT_GEMS"
}
# From mise's own apt repository, so Pop!_OS' updates keep mise up to date
install_mise() {
echo "mise isn't installed. It comes from mise's own apt repository (mise.jdx.dev)."
confirm_yes "Install it?" || return 1
sudo install -dm 755 /etc/apt/keyrings || return 1
curl -fsSL --max-time 60 https://mise.jdx.dev/gpg-key.pub \
| sudo tee /etc/apt/keyrings/mise-archive-keyring.asc > /dev/null || return 1
echo "deb [signed-by=/etc/apt/keyrings/mise-archive-keyring.asc] https://mise.jdx.dev/deb stable main" \
| sudo tee /etc/apt/sources.list.d/mise.list > /dev/null || return 1
sudo apt-get update && sudo apt-get install -y mise
}
activated() {
grep -qsxF "$BLOCK_START" "$BASHRC"
}
activate() {
{
echo
echo "$BLOCK_START"
echo "# The languages configure languages installs: see mise ls"
echo 'eval "$(mise activate bash)"'
echo "$BLOCK_END"
} >> "$BASHRC" || return 1
echo "Added mise to ~/.bashrc; the languages it installs work in new terminals."
}
install_rails() {
pkg_ensure "Building Ruby" "${RUBY_BUILD_DEPS[@]}" || return 1
echo "Installing Ruby and Rails..."
add_default_gem bundler || return 1
add_default_gem rails || return 1
mise use -g ruby@latest || return 1
# Ruby may already have been installed before ~/.default-gems listed these
mise exec -- gem install --conservative bundler rails || return 1
grep -qsx rails "$LANGUAGES_CONF" || echo rails >> "$LANGUAGES_CONF"
}
run_configure() {
local tools tool
export MISE_YES=1
# From home, so a project's mise.toml in the current directory doesn't count
cd "$HOME" || return 1
echo "mise installs programming languages and tools for you, and the version a"
echo "project asks for in its mise.toml."
command -v mise > /dev/null || install_mise || return 1
activated || activate || return 1
mkdir -p "$(dirname "$LANGUAGES_CONF")"
touch "$LANGUAGES_CONF" || return 1
if confirm "Install Ruby on Rails?"; then
install_rails || return 1
fi
echo "Anything else? Name tools mise knows (mise registry lists them), with a version,"
read -rp "e.g. node@lts python@3.13 go@latest, or press Enter for none: " tools
for tool in $tools; do
echo "Installing $tool..."
mise use -g "$tool" || return 1
done
echo "To update them: mise upgrade. To remove one later: mise unuse -g <tool>"
}
+274
View File
@@ -0,0 +1,274 @@
#!/bin/bash
# configure reads TITLE and DESCRIPTION
# shellcheck disable=SC2034
TITLE="AI servers"
# shellcheck disable=SC2034
DESCRIPTION="Use LLM servers on your network, e.g. Ollama"
# The servers you've added, one host:port per line. It exists once you've run
# this, even if you added none, so this isn't "to do" on machines without one.
AI_SERVERS_CONF="$CONF_DIR/ai-servers"
# The sandbox config every sandboxed agent reads (see sandbox/agent)
SANDBOX_CONF="$CONF_DIR/sandbox/base.json"
CLAUDE_SETTINGS="$HOME/.claude/settings.json"
OPENCODE_CONF="$HOME/.config/opencode/opencode.json"
source "$CONNECTOR/configure.d/lib/mdns.sh"
source "$CONNECTOR/configure.d/lib/json.sh"
# Ports LLM servers listen on by default, and who uses each. All of them answer
# OpenAI's API at /v1, which is how every agent here talks to them.
LLM_PORTS=(11434 1234 8080 8000)
declare -A LLM_PORT_NAMES=([11434]=Ollama [1234]="LM Studio" [8080]=llama.cpp [8000]=vLLM)
is_configured() {
[ -f "$AI_SERVERS_CONF" ]
}
# The models a server at host:port offers, one per line; fails if it doesn't
# answer like an LLM server
server_models() {
curl -sf -m 3 "http://$1/v1/models" | jq -er '.data[].id' 2> /dev/null
}
# What the server is, e.g. Ollama, for its name in the agents' settings
server_kind() {
local port="${1##*:}"
if curl -sf -m 3 "http://$1/api/version" > /dev/null; then
echo Ollama
else
echo "${LLM_PORT_NAMES[$port]:-LLM server}"
fi
}
# The LLM servers on the network: "host:port|models" per line. mDNS finds the
# machines, but LLM servers don't announce themselves on it, so each machine
# is asked on the usual ports.
find_servers() {
local dir host port
dir="$(mktemp -d)" || return 1
for host in $(mdns_hosts); do
for port in "${LLM_PORTS[@]}"; do
(server_models "$host:$port" | wc -l > "$dir/$host:$port") &
done
done
wait
for host in "$dir"/*; do
[ -f "$host" ] && [ "$(cat "$host")" -gt 0 ] && echo "$(basename "$host")|$(cat "$host")"
done
rm -rf "$dir"
}
# Let every sandboxed agent (opencode, Hermes, Cline) reach host:port, and
# only that port
sandbox_allow() {
edit_json "$SANDBOX_CONF" '{}' --arg server "$1" \
'.network.allowedDomains = ((.network.allowedDomains // []) - [$server] + [$server])'
}
sandbox_disallow() {
[ -f "$SANDBOX_CONF" ] || return 0
edit_json "$SANDBOX_CONF" '{}' --arg server "$1" \
'.network.allowedDomains -= [$server]'
}
# Claude Code's sandbox only covers the commands it runs, e.g. curl, not its
# own connection to Anthropic. Its list replaces the defaults sandbox/setup.sh
# gives it, so if it has none yet, it starts from those.
claude_allow() {
local defaults
[ -f "$CLAUDE_SETTINGS" ] || return 0
defaults="$(jq '.network.allowedDomains' "$CONNECTOR/sandbox/config/base.json")" || return 1
edit_json "$CLAUDE_SETTINGS" '{}' --arg server "$1" --argjson defaults "$defaults" \
'.sandbox.network.allowedDomains = ((.sandbox.network.allowedDomains // $defaults) - [$server] + [$server])'
}
claude_disallow() {
[ -f "$CLAUDE_SETTINGS" ] || return 0
edit_json "$CLAUDE_SETTINGS" '{}' --arg server "$1" \
'if .sandbox.network.allowedDomains then .sandbox.network.allowedDomains -= [$server] else . end'
}
# opencode's name for the server: llm.local:11434 -> llm-11434
opencode_provider() {
local id="${1%%:*}"
id="${id%.local}-${1##*:}"
echo "${id//[^a-zA-Z0-9-]/-}" | tr '[:upper:]' '[:lower:]'
}
# Add the server to opencode as a provider with its models, and make $3 the
# model opencode starts with if you say so
opencode_add() {
local server="$1" kind="$2" model="$3" id models
id="$(opencode_provider "$server")"
models="$(server_models "$server" | jq -R '{(.): {name: .}}' | jq -s 'add')" || return 1
edit_json "$OPENCODE_CONF" '{"$schema": "https://opencode.ai/config.json"}' \
--arg id "$id" --arg name "$kind on ${server%%:*}" --arg url "http://$server/v1" \
--argjson models "$models" \
'.provider[$id] = {npm: "@ai-sdk/openai-compatible", name: $name, options: {baseURL: $url}, models: $models}' \
|| return 1
echo "opencode: added $kind on ${server%%:*} (choose its models with /models)."
if confirm_yes "Start opencode with $model?"; then
edit_json "$OPENCODE_CONF" '{}' --arg model "$id/$model" '.model = $model' || return 1
fi
}
opencode_remove() {
local id
[ -f "$OPENCODE_CONF" ] || return 0
id="$(opencode_provider "$1")"
edit_json "$OPENCODE_CONF" '{}' --arg id "$id" \
'del(.provider[$id]) | if (.model // "") | startswith($id + "/") then del(.model) else . end'
}
# Hermes uses one model at a time, so ask before replacing the one it has
hermes_use() {
local server="$1" model="$2"
confirm_yes "Use $model on ${server%%:*} for Hermes?" || return 0
unsandboxed hermes config set model.provider custom > /dev/null \
&& unsandboxed hermes config set model.base_url "http://$server/v1" > /dev/null \
&& unsandboxed hermes config set model.default "$model" > /dev/null || return 1
echo "Hermes: now uses $model."
}
# Hermes' gateway reads the sandbox config when it starts, so it can't reach a
# new server until it restarts. (A sandboxed opencode starts its own server
# each time, so it reads the config again then.)
restart_gateway() {
if systemctl --user is-active -q hermes-gateway 2> /dev/null \
&& confirm_yes "Restart Hermes' gateway so it can reach the server?"; then
systemctl --user restart hermes-gateway || return 1
fi
}
saved_servers() {
grep -v '^$' "$AI_SERVERS_CONF" 2> /dev/null
}
# Choose a model from the server and set the agents up to use it
add_server() {
local server="$1" kind models model choice i
mapfile -t models < <(server_models "$server")
if [ ${#models[@]} -eq 0 ]; then
echo "$server doesn't answer like an LLM server (http://$server/v1/models)."
return 1
fi
kind="$(server_kind "$server")"
echo
echo "$kind on $server has these models:"
for i in "${!models[@]}"; do
printf ' %2d) %s\n' $((i + 1)) "${models[$i]}"
done
read -rp "Which should the agents use? [1] " choice
choice="${choice:-1}"
if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#models[@]} )); then
echo "Choose a number from the list."
return 1
fi
model="${models[$((choice - 1))]}"
sandbox_allow "$server" || return 1
claude_allow "$server" || return 1
grep -qsxF "$server" "$AI_SERVERS_CONF" || echo "$server" >> "$AI_SERVERS_CONF"
echo "The sandbox lets the agents reach $server."
if agent_installed opencode; then
opencode_add "$server" "$kind" "$model" || return 1
fi
if agent_installed hermes; then
hermes_use "$server" "$model" || return 1
fi
restart_gateway
}
remove_server() {
local server="$1" tmp
sandbox_disallow "$server" || return 1
claude_disallow "$server" || return 1
opencode_remove "$server" || return 1
tmp="$(mktemp)" || return 1
grep -vxF "$server" "$AI_SERVERS_CONF" > "$tmp"
mv -f "$tmp" "$AI_SERVERS_CONF"
echo "The agents can no longer reach $server."
if grep -qsF "$server" "$HOME/.hermes/config.yaml"; then
echo "Hermes still uses it; choose another model provider with: configure hermes"
fi
}
# Find servers on the network and add the one you choose
find_and_add() {
local servers server models choice i
echo "Looking for LLM servers on your network..."
mapfile -t servers < <(find_servers)
if [ ${#servers[@]} -eq 0 ]; then
echo "No LLM servers found. A server has to accept connections from other machines:"
echo "in Ollama's settings, turn on \"Expose Ollama to the network\" (or set OLLAMA_HOST=0.0.0.0);"
echo "in LM Studio, turn on \"Serve on Local Network\". Or enter its address instead."
return 0
fi
for i in "${!servers[@]}"; do
IFS='|' read -r server models <<< "${servers[$i]}"
printf ' %2d) %-28s %s, %s models\n' $((i + 1)) "$server" "$(server_kind "$server")" "$models"
done
read -rp "Which server? " choice
if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#servers[@]} )); then
echo "Choose a number from the list."
return 1
fi
add_server "${servers[$((choice - 1))]%%|*}"
}
# host, host:port or a URL such as http://host:port/v1 -> host:port
enter_and_add() {
local address
read -rp "The server's address, e.g. llm.local or llm.local:11434: " address
address="${address#*://}"
address="${address%%/*}"
[ -n "$address" ] || return 0
[[ "$address" == *:* ]] || address="$address:11434"
add_server "$address"
}
choose_and_remove() {
local servers choice i
mapfile -t servers < <(saved_servers)
for i in "${!servers[@]}"; do
printf ' %2d) %s\n' $((i + 1)) "${servers[$i]}"
done
read -rp "Which server? " choice
if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#servers[@]} )); then
echo "Choose a number from the list."
return 1
fi
remove_server "${servers[$((choice - 1))]}"
}
run_configure() {
local choice
pkg_ensure "Finding servers on your network" avahi-utils || return 1
mkdir -p "$(dirname "$AI_SERVERS_CONF")" && touch "$AI_SERVERS_CONF" || return 1
echo "Agents run in a sandbox that only lets them reach the servers you allow. This finds"
echo "LLM servers on your network, such as Ollama on a Mac, allows them and sets up the agents."
while true; do
echo
if [ -s "$AI_SERVERS_CONF" ]; then
echo "The agents can reach: $(saved_servers | paste -sd' ')"
echo
fi
echo " 1) Find servers on your network"
echo " 2) Enter a server's address"
[ -s "$AI_SERVERS_CONF" ] && echo " 3) Remove a server"
echo " q) Done"
echo
read -rp "Choose: " choice || return 0
case "$choice" in
1) find_and_add ;;
2) enter_and_add ;;
3) [ -s "$AI_SERVERS_CONF" ] && choose_and_remove ;;
*) return 0 ;;
esac
done
}
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
# configure reads TITLE and DESCRIPTION
# shellcheck disable=SC2034
TITLE="Printers"
# shellcheck disable=SC2034
DESCRIPTION="Add your network's printers to every print dialog"
# Exists once you've run this, even if you added none, so this isn't "to do"
# on machines without a printer
PRINTERS_CONF="$CONF_DIR/printers"
# Set up here, or a network printer was already added some other way
is_configured() {
[ -f "$PRINTERS_CONF" ] || LC_ALL=C lpstat -v 2> /dev/null | grep -qE ': (ipps?|dnssd)://'
}
run_configure() {
bash "$CONNECTOR/system/setup-printers.sh" || return 1
mkdir -p "$(dirname "$PRINTERS_CONF")" && touch "$PRINTERS_CONF"
}
+319
View File
@@ -0,0 +1,319 @@
#!/bin/bash
# configure reads TITLE and DESCRIPTION
# shellcheck disable=SC2034
TITLE="Network storage"
# shellcheck disable=SC2034
DESCRIPTION="Mount shared folders from your network in /mnt"
# What's mounted, one "kind|source|mount point" per line, e.g.
# smb|//pi-star.local/files|/mnt/pi-star-files. It exists once you've run
# this, even if you mounted nothing, so this isn't "to do" without a server.
STORAGE_CONF="$CONF_DIR/storage"
# Passwords for SMB shares, readable only by root, which mounts them
SMB_CREDENTIALS="/etc/federated-connector/smb"
source "$CONNECTOR/configure.d/lib/mdns.sh"
source "$CONNECTOR/configure.d/lib/sidebar.sh"
is_configured() {
[ -f "$STORAGE_CONF" ]
}
# A name usable in a path: "Pi-Star Files" -> pi-star-files
slug() {
local s
s="$(tr '[:upper:]' '[:lower:]' <<< "$1" | sed -E 's/[^a-z0-9._-]+/-/g; s/^-+//; s/-+$//')"
echo "${s:-share}"
}
# /mnt/<host>[-<name>], with -2, -3... if that's taken
mount_point() {
local base n=2 point
base="/mnt/$(slug "${1%.local}")"
[ -n "$2" ] && base="$base-$(slug "$2")"
point="$base"
while [ -e "$point" ] || grep -qsF "|$point" "$STORAGE_CONF"; do
point="$base-$n"
n=$((n + 1))
done
echo "$point"
}
# --- SMB: Windows, Samba (e.g. a NAS) and Mac file sharing --------------------
# The disk shares on an SMB server, one per line, leaving out admin shares
# like C$. smbclient reads the password from PASSWD, not the command line.
smb_shares() {
local host="$1" user="$2" password="$3" auth=(-N)
[ -n "$user" ] && auth=(-U "$user")
PASSWD="$password" timeout 20 smbclient -L "//$host" "${auth[@]}" -g 2> /dev/null \
| awk -F'|' '$1 == "Disk" && $2 !~ /\$$/ { print $2 }'
}
# The /etc/fstab line: root mounts the share the first time something opens
# the folder (x-systemd.automount), as you, and unmounts it after 10 idle
# minutes. nofail and the timeout keep a missing server from holding up boot
# or hanging whatever opened the folder. Spaces are \040 in fstab.
smb_fstab_line() {
local source="${1// /\\040}" point="$2" credentials="$3" auth
if [ -n "$credentials" ]; then auth="credentials=$credentials"; else auth="guest"; fi
echo "$source $point cifs $auth,uid=$(id -u),gid=$(id -g),iocharset=utf8,nofail,_netdev,x-systemd.automount,x-systemd.idle-timeout=600,x-systemd.mount-timeout=20 0 0"
}
add_smb() {
local host="$1" share="$2" user password shares point source credentials="" choice i
pkg_ensure "SMB shared folders" smbclient cifs-utils || return 1
echo "Sign in to $host. Leave the user name empty for a share anyone can open."
read -rp "User name: " user
password=""
if [ -n "$user" ]; then
read -rsp "Password: " password
echo
fi
if [ -z "$share" ]; then
mapfile -t shares < <(smb_shares "$host" "$user" "$password")
if [ ${#shares[@]} -eq 0 ]; then
echo "$host didn't list any shares for ${user:-guests} (wrong password, or it doesn't list them)."
read -rp "The share's name, if you know it (Enter to stop): " share
[ -n "$share" ] || return 1
else
for i in "${!shares[@]}"; do
printf ' %2d) %s\n' $((i + 1)) "${shares[$i]}"
done
read -rp "Which share? " choice
if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#shares[@]} )); then
echo "Choose a number from the list."
return 1
fi
share="${shares[$((choice - 1))]}"
fi
fi
source="//$host/$share"
point="$(mount_point "$host" "$share")"
if [ -n "$user" ]; then
credentials="$SMB_CREDENTIALS/$(basename "$point")"
printf 'username=%s\npassword=%s\n' "$user" "$password" \
| sudo install -D -m 600 -o root -g root /dev/stdin "$credentials" || return 1
fi
sudo install -d "$point" || return 1
smb_fstab_line "$source" "$point" "$credentials" | sudo tee -a /etc/fstab > /dev/null || return 1
sudo systemctl daemon-reload || return 1
sudo systemctl restart "$(systemd-escape -p --suffix=automount "$point")" || return 1
finish_add smb "$source" "$point" "$share on ${host%.local}"
}
remove_smb() {
local point="$1" tmp
sudo systemctl stop "$(systemd-escape -p --suffix=automount "$point")" \
"$(systemd-escape -p --suffix=mount "$point")" 2> /dev/null
tmp="$(mktemp)" || return 1
awk -v point="$point" '!($2 == point && $3 == "cifs")' /etc/fstab > "$tmp"
sudo cp /etc/fstab /etc/fstab.bak && sudo install -m 644 "$tmp" /etc/fstab || { rm -f "$tmp"; return 1; }
rm -f "$tmp"
sudo systemctl daemon-reload
sudo rm -f "$SMB_CREDENTIALS/$(basename "$point")"
sudo rmdir "$point" 2> /dev/null
return 0
}
# --- SFTP: any machine you can ssh to --------------------------------------------
sftp_unit_name() {
echo "federated-connector-sftp-$(basename "$1").service"
}
# systemd would expand $ and % in the unit's ExecStart
sftp_unit() {
local source="$1" point="$2"
cat << EOF
# Written by Federated Connector (configure storage)
[Unit]
Description=Mount $source at $point
After=network-online.target
[Service]
ExecStart=%h/.local/share/federated-connector/connector/system/sftp-mount "$source" "$point"
ExecStop=/usr/bin/fusermount3 -u "$point"
Restart=on-failure
RestartSec=30
[Install]
WantedBy=default.target
EOF
}
add_sftp() {
local host="$1" user="${2:-$USER}" path="$3" source point name unit
pkg_ensure "SFTP folders" sshfs || return 1
read -rp "User name on $host [$user]: " name
user="${name:-$user}"
if [ -z "$path" ]; then
read -rp "Folder on $host (Enter for your home folder): " path
fi
if [[ "$user$host$path" == *[\$%\"\\]* ]]; then
echo "The user name and folder can't contain \$, %, \" or \\."
return 1
fi
source="$user@$host:$path"
# Accepts the server's key the first time; the mount can't ask
echo "Checking that $host accepts one of your SSH keys..."
if [ -S "$HOME/.bitwarden-ssh-agent.sock" ]; then
export SSH_AUTH_SOCK="$HOME/.bitwarden-ssh-agent.sock"
fi
ssh -o ConnectTimeout=10 -o PasswordAuthentication=no -o KbdInteractiveAuthentication=no \
"$user@$host" true || {
echo "$host didn't accept any of your SSH keys, and the mount can't ask for a password."
echo "Add your key to $host first (e.g. ssh-copy-id $user@$host), then try again."
return 1
}
point="$(mount_point "$host" "$(basename "${path:-}")")"
unit="$(sftp_unit_name "$point")"
sudo install -d -o "$USER" -g "$(id -gn)" "$point" || return 1
mkdir -p "$HOME/.config/systemd/user"
sftp_unit "$source" "$point" > "$HOME/.config/systemd/user/$unit" || return 1
systemctl --user daemon-reload
systemctl --user enable --now "$unit" || return 1
finish_add sftp "$source" "$point" "${host%.local}${path:+ $(basename "$path")}"
}
remove_sftp() {
local point="$1" unit
unit="$(sftp_unit_name "$point")"
systemctl --user disable --now "$unit" 2> /dev/null
rm -f "$HOME/.config/systemd/user/$unit"
systemctl --user daemon-reload
sudo rmdir "$point" 2> /dev/null
return 0
}
# --- Both ------------------------------------------------------------------------
# Record it, add it to the Files sidebar and check it opens
finish_add() {
local kind="$1" source="$2" point="$3" label="$4"
echo "$kind|$source|$point" >> "$STORAGE_CONF"
sidebar_add "$point" "$label"
if timeout 30 ls "$point" > /dev/null 2>&1 && mountpoint -q "$point"; then
echo "$source is at $point (\"$label\" in the Files sidebar)."
else
echo "$source was added at $point, but didn't open yet. If it doesn't, see:"
if [ "$kind" = smb ]; then
echo " journalctl -b -u '$(systemd-escape -p --suffix=mount "$point")'"
else
echo " journalctl --user -u $(sftp_unit_name "$point")"
fi
fi
}
remove_storage() {
local kind="$1" point="$3" tmp
"remove_$kind" "$point" || return 1
tmp="$(mktemp)" || return 1
grep -vF "|$point" "$STORAGE_CONF" > "$tmp"
mv -f "$tmp" "$STORAGE_CONF"
sidebar_remove "$point"
echo "$point is no longer mounted."
}
# The file servers on the network: "kind|host|name" per line
find_storage() {
local own name type host
own="$(mdns_own_host)"
mdns_services | while IFS='|' read -r name type host _; do
[[ "${host,,}" == "${own,,}" ]] && continue
case "$type" in
_smb._tcp) echo "smb|$host|$name" ;;
_sftp-ssh._tcp) echo "sftp|$host|$name" ;;
esac
done | sort -u
}
find_and_add() {
local found kind host name choice i
echo "Looking for shared folders on your network..."
mapfile -t found < <(find_storage)
if [ ${#found[@]} -eq 0 ]; then
echo "Nothing found. A Mac shares folders over SMB once File Sharing is on (System Settings >"
echo "General > Sharing). Or enter the address instead."
return 0
fi
for i in "${!found[@]}"; do
IFS='|' read -r kind host name <<< "${found[$i]}"
printf ' %2d) %-26s %s\n' $((i + 1)) "$host" "$( [ "$kind" = smb ] && echo "SMB shared folders" || echo "SFTP (over SSH)")"
done
read -rp "Which? " choice
if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#found[@]} )); then
echo "Choose a number from the list."
return 1
fi
IFS='|' read -r kind host _ <<< "${found[$((choice - 1))]}"
"add_$kind" "$host"
}
# smb://host/share or sftp://[user@]host[/path]
enter_and_add() {
local address rest host user="" path
read -rp "Address, e.g. smb://nas.local/files or sftp://me@server.local/srv/data: " address
rest="${address#*://}"
case "$address" in
smb://*/?*) add_smb "${rest%%/*}" "${rest#*/}" ;;
sftp://*)
[[ "$rest" == *@* ]] && { user="${rest%%@*}"; rest="${rest#*@}"; }
host="${rest%%/*}"
path=""
[[ "$rest" == */* ]] && path="/${rest#*/}"
add_sftp "$host" "$user" "$path" ;;
"") return 0 ;;
*) echo "Start it with smb:// (and include the share) or sftp://."; return 1 ;;
esac
}
choose_and_remove() {
local entries choice i
mapfile -t entries < <(grep -v '^$' "$STORAGE_CONF")
for i in "${!entries[@]}"; do
IFS='|' read -r _ source point <<< "${entries[$i]}"
printf ' %2d) %-30s %s\n' $((i + 1)) "$point" "$source"
done
read -rp "Which? " choice
if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#entries[@]} )); then
echo "Choose a number from the list."
return 1
fi
IFS='|' read -r -a entry <<< "${entries[$((choice - 1))]}"
remove_storage "${entry[@]}"
}
run_configure() {
local choice source point
pkg_ensure "Finding shared folders" avahi-utils || return 1
mkdir -p "$(dirname "$STORAGE_CONF")" && touch "$STORAGE_CONF" || return 1
echo "This mounts shared folders from other machines on your network in /mnt: SMB shares"
echo "(Windows, a NAS, a Mac with File Sharing on) and, over SSH, any machine you can ssh to."
while true; do
echo
if [ -s "$STORAGE_CONF" ]; then
while IFS='|' read -r _ source point; do
echo " $point <- $source"
done < "$STORAGE_CONF"
echo
fi
echo " 1) Find shared folders on your network"
echo " 2) Enter an address"
[ -s "$STORAGE_CONF" ] && echo " 3) Remove one"
echo " q) Done"
echo
read -rp "Choose: " choice || return 0
case "$choice" in
1) find_and_add ;;
2) enter_and_add ;;
3) [ -s "$STORAGE_CONF" ] && choose_and_remove ;;
*) return 0 ;;
esac
done
}
+83
View File
@@ -0,0 +1,83 @@
#!/bin/bash
# configure reads TITLE and DESCRIPTION
# shellcheck disable=SC2034
TITLE="Agent sandbox"
# shellcheck disable=SC2034
DESCRIPTION="Choose what agents may read, e.g. WinBoat's settings"
# The sandbox config every sandboxed agent reads (see sandbox/agent)
SANDBOX_CONF="$CONF_DIR/sandbox/base.json"
source "$CONNECTOR/configure.d/lib/json.sh"
# Folders the sandbox hides from agents (sandbox/config/base.json) that you
# may let them read: "path|what it is". Your SSH keys, password stores,
# browsers and the like aren't here; they're always hidden. A path in
# allowRead can be read even inside one in denyRead, so letting agents read
# one is adding it to allowRead in your own config.
# The paths are written as in sandbox/config/base.json, with ~ for srt to expand
# shellcheck disable=SC2088
OPTIONAL_HIDDEN=(
"~/.winboat|WinBoat's settings, which include your Windows password"
)
# Offered only when one of the folders is on this machine
is_installed() {
local entry path
for entry in "${OPTIONAL_HIDDEN[@]}"; do
path="${entry%%|*}"
[ -e "${path/#\~/$HOME}" ] && return 0
done
return 1
}
# Hiding them is the default, so there's nothing you need to do
is_configured() {
true
}
# True if agents may read $1 (it's in your config's allowRead)
readable() {
jq -e --arg path "$1" '.filesystem.allowRead // [] | index($path)' "$SANDBOX_CONF" &> /dev/null
}
let_read() {
edit_json "$SANDBOX_CONF" '{}' --arg path "$1" \
'.filesystem.allowRead = ((.filesystem.allowRead // []) - [$path] + [$path])'
}
hide() {
[ -f "$SANDBOX_CONF" ] || return 0
edit_json "$SANDBOX_CONF" '{}' --arg path "$1" \
'if .filesystem.allowRead then .filesystem.allowRead -= [$path] else . end'
}
run_configure() {
local choice i path what state
echo "Agents in the sandbox can't read these unless you let them. Changes apply the next"
echo "time you start an agent (restart Hermes' gateway with: systemctl --user restart hermes-gateway)."
echo "Claude Code's own sandbox doesn't use this list."
while true; do
echo
for i in "${!OPTIONAL_HIDDEN[@]}"; do
IFS='|' read -r path what <<< "${OPTIONAL_HIDDEN[$i]}"
if readable "$path"; then state="\e[33magents can read it\e[0m"; else state="\e[32mhidden\e[0m"; fi
printf " %d) %-12s $state %s\n" $((i + 1)) "$path" "$what"
done
echo " q) Done"
echo
read -rp "Choose one to switch: " choice || return 0
if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#OPTIONAL_HIDDEN[@]} )); then
return 0
fi
IFS='|' read -r path what <<< "${OPTIONAL_HIDDEN[$((choice - 1))]}"
if readable "$path"; then
hide "$path" || return 1
echo "$path is hidden from agents again."
elif confirm "Let agents read $path ($what)?"; then
let_read "$path" || return 1
echo "Agents can read $path."
fi
done
}
+47
View File
@@ -0,0 +1,47 @@
#!/bin/bash
#
# Purpose : Find the AI agents' real commands, outside the sandbox's own
# (sandbox/bin), and the sandbox runtime. Sourced by configure and
# sandbox/agent. Needs CONNECTOR.
SANDBOX_BIN="$CONNECTOR/sandbox/bin"
FC_TOOLS="$HOME/.local/share/federated-connector"
# Where the agents' installers put them, in case your shell's PATH doesn't
# have them yet (e.g. right after installing)
AGENT_DIRS="$HOME/.local/bin:$HOME/.opencode/bin:$HOME/.hermes/bin:/usr/local/bin:/usr/bin"
# The real command for an agent: the first on PATH, or in AGENT_DIRS, that
# isn't in sandbox/bin
agent_path() {
local dir bin_dir IFS=:
bin_dir="$(realpath "$SANDBOX_BIN" 2> /dev/null)"
for dir in $PATH:$AGENT_DIRS; do
[ -n "$dir" ] && [ -d "$dir" ] || continue
[ "$(realpath "$dir")" = "$bin_dir" ] && continue
if [ -x "$dir/$1" ] && [ ! -d "$dir/$1" ]; then
echo "$dir/$1"
return 0
fi
done
return 1
}
agent_installed() {
agent_path "$1" > /dev/null
}
# Run an agent's real command rather than its sandboxed one: setting an agent
# up writes outside its sandbox
unsandboxed() {
local agent="$1" real
shift
real="$(agent_path "$agent")" || { echo "$agent isn't installed."; return 127; }
"$real" "$@"
}
# srt, and the Node.js it runs with: Federated Connector's own, or one
# already installed
srt_path() {
PATH="$FC_TOOLS/srt/bin:$FC_TOOLS/node/bin:$PATH" command -v srt
}
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env python3
"""Add or remove a folder in the COSMIC Files sidebar.
COSMIC Files keeps the sidebar's places in its cosmic-config setting
"favorites": ~/.config/cosmic/com.system76.CosmicFiles/v1/favorites, a RON
list such as [Home, Documents, Path("/mnt/x"), Named(path: "/mnt/y", name: "y")].
COSMIC Files watches the file, so a change shows at once. This adds a folder
as Named (a path with the name to show), which COSMIC Files has had since
epoch 1.7, and leaves the rest of the list as it is. Without the file, COSMIC
Files uses its defaults, so those are written first.
Usage:
cosmic-favorites has <path>
cosmic-favorites add <path> <name>
cosmic-favorites remove <path>
"""
import os
import sys
CONFIG = os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"),
"cosmic/com.system76.CosmicFiles/v1/favorites")
DEFAULTS = ["Home", "Documents", "Downloads", "Music", "Pictures", "Videos"]
def split_items(text):
"""The top-level items of a RON list, as text."""
text = text.strip()
if not (text.startswith("[") and text.endswith("]")):
raise ValueError("not a RON list")
items, depth, start, quoted, escaped = [], 0, 1, False, False
for i, ch in enumerate(text[1:-1], 1):
if quoted:
if escaped:
escaped = False
elif ch == "\\":
escaped = True
elif ch == '"':
quoted = False
elif ch == '"':
quoted = True
elif ch in "([{":
depth += 1
elif ch in ")]}":
depth -= 1
elif ch == "," and depth == 0:
items.append(text[start:i].strip())
start = i + 1
last = text[start:-1].strip()
if last:
items.append(last)
return [item for item in items if item]
def ron_string(value):
return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
def unquote(value):
out, escaped = [], False
for ch in value[1:-1]:
if escaped:
out.append(ch)
escaped = False
elif ch == "\\":
escaped = True
else:
out.append(ch)
return "".join(out)
def item_path(item):
"""The path of a Path, Named or Network item, or None."""
for prefix in ("Path(", "Named(", "Network("):
if not item.startswith(prefix):
continue
body = item[len(prefix):-1].strip().rstrip(",")
if prefix == "Path(":
return unquote(body.strip())
for field in split_items("[" + body + "]"):
key, _, value = field.partition(":")
if key.strip() == "path":
return unquote(value.strip())
return None
def load():
try:
with open(CONFIG, encoding="utf-8") as f:
return split_items(f.read())
except FileNotFoundError:
return list(DEFAULTS)
def save(items):
os.makedirs(os.path.dirname(CONFIG), exist_ok=True)
tmp = CONFIG + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
f.write("[\n" + "".join(f" {item},\n" for item in items) + "]")
os.replace(tmp, CONFIG)
def main():
args = sys.argv[1:]
if len(args) == 2 and args[0] == "has":
return 0 if any(item_path(i) == args[1] for i in load()) else 1
if len(args) == 3 and args[0] == "add":
items = [i for i in load() if item_path(i) != args[1]]
items.append(f"Named(path: {ron_string(args[1])}, name: {ron_string(args[2])})")
save(items)
return 0
if len(args) == 2 and args[0] == "remove":
items = load()
kept = [i for i in items if item_path(i) != args[1]]
if kept != items:
save(kept)
return 0
print(__doc__.strip().split("\n\n")[-1], file=sys.stderr)
return 2
if __name__ == "__main__":
try:
sys.exit(main())
except (OSError, ValueError) as error:
print(f"COSMIC Files sidebar: {error}", file=sys.stderr)
sys.exit(1)
+263
View File
@@ -0,0 +1,263 @@
#!/usr/bin/env python3
"""Add, change or remove an account in GNOME Online Accounts, the way GNOME Settings does.
COSMIC has no accounts of its own, so configure keeps your Core's email,
calendars and contacts in GNOME Online Accounts, which runs as a D-Bus
service without GNOME, and Evolution shows them.
Settings adds accounts by calling AddAccount on the Online Accounts service,
which saves the account and keeps its password in the GNOME keyring. This
calls the same method. The service can't change a password, so when you sign
in again, Settings saves the new one in the keyring itself and asks the
service to check it (EnsureCredentials); update does the same. Passwords come
on stdin rather than as arguments, so they don't show up in the process list.
Usage:
goa-account exists <provider> <presentation-identity>
goa-account add < account.json
goa-account update <provider> <presentation-identity> < credentials.json
goa-account check <provider> <presentation-identity>
goa-account disabled <provider> <presentation-identity>
goa-account enable <provider> <presentation-identity>
goa-account attention <provider> <presentation-identity>
goa-account pause <provider> <presentation-identity>
goa-account paused <provider> <presentation-identity>
goa-account remove <provider> <presentation-identity>
account.json:
{"provider": "owncloud", "identity": "...", "presentation_identity": "...",
"credentials": {"password": "..."}, "details": {"Uri": "...", ...}}
credentials.json is the account's "credentials", e.g. {"password": "..."}.
check signs in with what's saved, and fails if the server says no. update
exits with 3 if it saved the password but the server didn't accept it.
disabled prints the features configure uses that are turned off (e.g. in
GNOME Settings), such as "Calendar, Files", and enable turns them back on.
attention exits 0 if Online Accounts marked the account as needing
attention. It doesn't sign in, so it doesn't add to the server's count of
failed logins. Online Accounts 3.50, which Pop!_OS 24.04 has, marks it for
any failure, including a server it couldn't reach, so it's only a hint that
the password may be wrong (see system/email-watch).
pause empties the account's saved password, keeping its place in the keyring.
Online Accounts signs in again whenever the network changes, and Evolution
whenever it fetches mail; with no password neither tries, so a mail server
with fail2ban doesn't block this computer for repeated wrong passwords.
update puts a password back, which ends the pause. paused exits 0 if paused.
"""
import json
import sys
import gi
gi.require_version("Gio", "2.0")
gi.require_version("Secret", "1")
from gi.repository import Gio, GLib, Secret # noqa: E402
BUS_NAME = "org.gnome.OnlineAccounts"
# How Online Accounts keeps passwords in the keyring: the credentials printed
# as a GVariant, under "<provider>:gen<N>:<account id>"
SCHEMA = Secret.Schema.new("org.gnome.OnlineAccounts", Secret.SchemaFlags.DONT_MATCH_NAME,
{"goa-identity": Secret.SchemaAttributeType.STRING})
# The features configure sets each kind of account up for. Every account has
# a <feature>Disabled property for each feature, used or not.
FEATURES = {"owncloud": ["Calendar", "Contacts", "Files"], "imap_smtp": ["Mail"]}
def call(bus, path, interface, method, parameters, reply_type):
return bus.call_sync(BUS_NAME, path, interface, method, parameters,
GLib.VariantType(reply_type), Gio.DBusCallFlags.NONE,
-1, None).unpack()
def accounts(bus):
(objects,) = call(bus, "/org/gnome/OnlineAccounts",
"org.freedesktop.DBus.ObjectManager", "GetManagedObjects",
None, "(a{oa{sa{sv}}})")
for path, interfaces in objects.items():
account = interfaces.get("org.gnome.OnlineAccounts.Account")
if account:
yield path, account
def find_accounts(bus, provider, presentation_identity):
return [(path, account) for path, account in accounts(bus)
if account.get("ProviderType") == provider
and account.get("PresentationIdentity") == presentation_identity]
def find(bus, provider, presentation_identity):
return [path for path, _ in find_accounts(bus, provider, presentation_identity)]
def exists(bus, provider, presentation_identity):
return bool(find(bus, provider, presentation_identity))
def add(bus, account):
credentials = {key: GLib.Variant("s", value)
for key, value in account["credentials"].items()}
parameters = GLib.Variant("(sssa{sv}a{ss})", (
account["provider"], account["identity"],
account["presentation_identity"], credentials, account["details"]))
call(bus, "/org/gnome/OnlineAccounts/Manager",
"org.gnome.OnlineAccounts.Manager", "AddAccount", parameters, "(o)")
def ensure_credentials(bus, path):
call(bus, path, "org.gnome.OnlineAccounts.Account", "EnsureCredentials", None, "(i)")
# N in the keyring's name comes from the provider, so this saves over the
# account's own item rather than making one
def store_credentials(provider, account_id, credentials):
items = Secret.password_search_sync(
None, {"xdg:schema": "org.gnome.OnlineAccounts"},
Secret.SearchFlags.ALL | Secret.SearchFlags.UNLOCK, None)
identities = [item.get_attributes().get("goa-identity", "") for item in items]
identities = [identity for identity in identities
if identity.startswith(f"{provider}:gen") and identity.endswith(f":{account_id}")]
if not identities:
raise LookupError(f"there's no saved password for {account_id} in the keyring")
secret = GLib.Variant("a{sv}", {key: GLib.Variant("s", value)
for key, value in credentials.items()}).print_(True)
for identity in identities:
Secret.password_store_sync(SCHEMA, {"goa-identity": identity}, Secret.COLLECTION_DEFAULT,
f"GOA {provider} credentials for identity {account_id}",
secret, None)
# The account's saved credentials, e.g. {"imap-password": "..."}
def lookup_credentials(provider, account_id):
items = Secret.password_search_sync(
None, {"xdg:schema": "org.gnome.OnlineAccounts"},
Secret.SearchFlags.ALL | Secret.SearchFlags.UNLOCK | Secret.SearchFlags.LOAD_SECRETS, None)
for item in items:
identity = item.get_attributes().get("goa-identity", "")
if identity.startswith(f"{provider}:gen") and identity.endswith(f":{account_id}"):
return GLib.Variant.parse(None, item.get_secret().get_text(), None, None).unpack()
raise LookupError(f"there's no saved password for {account_id} in the keyring")
# The credential each kind of account signs in with
PASSWORD_KEYS = {"owncloud": "password", "imap_smtp": "imap-password"}
def attention(bus, provider, presentation_identity):
found = find_accounts(bus, provider, presentation_identity)
if not found:
raise LookupError(f"there's no {provider} account for {presentation_identity}")
return any(account.get("AttentionNeeded") for _, account in found)
def pause(bus, provider, presentation_identity):
found = find_accounts(bus, provider, presentation_identity)
if not found:
raise LookupError(f"there's no {provider} account for {presentation_identity}")
for _, account in found:
store_credentials(provider, account["Id"], {})
def paused(bus, provider, presentation_identity):
found = find_accounts(bus, provider, presentation_identity)
if not found:
raise LookupError(f"there's no {provider} account for {presentation_identity}")
return any(PASSWORD_KEYS[provider] not in lookup_credentials(provider, account["Id"])
for _, account in found)
def update(bus, provider, presentation_identity, credentials):
found = find_accounts(bus, provider, presentation_identity)
if not found:
raise LookupError(f"there's no {provider} account for {presentation_identity}")
for path, account in found:
store_credentials(provider, account["Id"], credentials)
try:
for path, _ in found:
ensure_credentials(bus, path)
except GLib.Error as error:
print(f"GNOME Online Accounts: {error.message}", file=sys.stderr)
return 3
return 0
def check(bus, provider, presentation_identity):
found = find(bus, provider, presentation_identity)
if not found:
raise LookupError(f"there's no {provider} account for {presentation_identity}")
for path in found:
ensure_credentials(bus, path)
def disabled(bus, provider, presentation_identity):
found = find_accounts(bus, provider, presentation_identity)
if not found:
raise LookupError(f"there's no {provider} account for {presentation_identity}")
return [feature for feature in FEATURES.get(provider, [])
if any(account.get(f"{feature}Disabled") for _, account in found)]
# Settings turns a feature off or on by setting its property
def enable(bus, provider, presentation_identity):
for path, account in find_accounts(bus, provider, presentation_identity):
for feature in FEATURES.get(provider, []):
if account.get(f"{feature}Disabled"):
call(bus, path, "org.freedesktop.DBus.Properties", "Set",
GLib.Variant("(ssv)", ("org.gnome.OnlineAccounts.Account",
f"{feature}Disabled", GLib.Variant("b", False))),
"()")
def remove(bus, provider, presentation_identity):
for path in find(bus, provider, presentation_identity):
call(bus, path, "org.gnome.OnlineAccounts.Account", "Remove", None, "()")
def main():
bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
if len(sys.argv) == 4 and sys.argv[1] == "exists":
return 0 if exists(bus, sys.argv[2], sys.argv[3]) else 1
if len(sys.argv) == 2 and sys.argv[1] == "add":
account = json.load(sys.stdin)
if exists(bus, account["provider"], account["presentation_identity"]):
return 0
add(bus, account)
return 0
if len(sys.argv) == 4 and sys.argv[1] == "update":
return update(bus, sys.argv[2], sys.argv[3], json.load(sys.stdin))
if len(sys.argv) == 4 and sys.argv[1] == "check":
check(bus, sys.argv[2], sys.argv[3])
return 0
if len(sys.argv) == 4 and sys.argv[1] == "disabled":
print(", ".join(disabled(bus, sys.argv[2], sys.argv[3])))
return 0
if len(sys.argv) == 4 and sys.argv[1] == "enable":
enable(bus, sys.argv[2], sys.argv[3])
return 0
if len(sys.argv) == 4 and sys.argv[1] == "attention":
return 0 if attention(bus, sys.argv[2], sys.argv[3]) else 1
if len(sys.argv) == 4 and sys.argv[1] == "pause":
pause(bus, sys.argv[2], sys.argv[3])
return 0
if len(sys.argv) == 4 and sys.argv[1] == "paused":
return 0 if paused(bus, sys.argv[2], sys.argv[3]) else 1
if len(sys.argv) == 4 and sys.argv[1] == "remove":
remove(bus, sys.argv[2], sys.argv[3])
return 0
print(__doc__.strip().split("\n\n")[2], file=sys.stderr)
return 2
if __name__ == "__main__":
try:
sys.exit(main())
except GLib.Error as error:
print(f"GNOME Online Accounts: {error.message}", file=sys.stderr)
sys.exit(1)
except LookupError as error:
print(f"GNOME Online Accounts: {error}", file=sys.stderr)
sys.exit(1)
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash
#
# Purpose : Edit JSON settings files for configure.d items. Source this file.
# Edit a JSON file in place with jq, creating it from $2 if it's missing.
# Leaves the file alone if it isn't valid JSON or jq fails.
edit_json() {
local file="$1" empty="$2" tmp
shift 2
mkdir -p "$(dirname "$file")" || return 1
[ -f "$file" ] || echo "$empty" > "$file"
tmp="$(mktemp "$file.XXXXXX")" || return 1
if jq "$@" "$file" > "$tmp"; then
mv -f "$tmp" "$file"
else
echo "Couldn't change $file; is it valid JSON?"
rm -f "$tmp"
return 1
fi
}
+48
View File
@@ -0,0 +1,48 @@
#!/bin/bash
#
# Purpose : Find what's on the local network over mDNS (Avahi), for the
# configure.d items that set up servers, printers and storage on it.
# Source this file.
# Every service Avahi can see, or only those of type $1 (e.g. _ipp._tcp), one
# per line after waiting a few seconds for answers:
# "name|type|host|address|port|txt". IPv4 only, so a machine isn't listed once
# per address family. The name has Avahi's escapes decoded.
mdns_services() {
local name type host address port txt
timeout 15 avahi-browse "${1:---all}" --resolve --terminate --parsable --no-db-lookup 2> /dev/null \
| awk -F';' '$1 == "=" && $3 == "IPv4"' \
| while IFS=';' read -r _ _ _ name type _ host address port txt; do
printf '%s|%s|%s|%s|%s|%s\n' "$(mdns_unescape "$name")" "$type" "$host" "$address" "$port" "$txt"
done | sort -u
}
# Avahi writes a space as \032 and a dot in a name as \. (decimal escapes)
mdns_unescape() {
local s="$1" out="" ch code escape='^([^\\]*)\\([0-9][0-9][0-9]|.)(.*)$'
while [[ "$s" =~ $escape ]]; do
out+="${BASH_REMATCH[1]}"
code="${BASH_REMATCH[2]}"
s="${BASH_REMATCH[3]}"
if [[ "$code" == [0-9][0-9][0-9] ]]; then
# shellcheck disable=SC2059
printf -v ch "\\$(printf %03o "$((10#$code))")"
out+="$ch"
else
out+="$code"
fi
done
echo "$out$s"
}
# This machine's own .local name, which mdns_hosts leaves out
mdns_own_host() {
echo "$(hostnamectl hostname 2> /dev/null || cat /etc/hostname).local"
}
# The other machines on the network: one .local name per line
mdns_hosts() {
local own
own="$(mdns_own_host)"
mdns_services | cut -d'|' -f3 | grep -vixF "$own" | sort -u
}
+48
View File
@@ -0,0 +1,48 @@
#!/bin/bash
#
# Purpose : Nextcloud app passwords for configure.d items. Source this file.
# Basic auth header for curl, read from stdin (-H @-) so the password isn't
# in the process list
auth_header() {
printf 'Authorization: Basic %s\n' "$(printf '%s:%s' "$1" "$2" | base64 -w0)"
}
# Create a Nextcloud app password, so what configure sets up doesn't keep
# your Core password. It shows in Nextcloud under Settings > Security with the
# name given, where it can be revoked. Uses CORE_USER, PASSWORD and NEXTCLOUD;
# sets APP_PASSWORD. Returns 2 if Nextcloud says the password is wrong.
nextcloud_app_password() {
local name="$1" response code
response="$(auth_header "$CORE_USER" "$PASSWORD" | curl -s -w '\n%{http_code}' -H @- \
-H 'OCS-APIRequest: true' -A "$name" \
"$NEXTCLOUD/ocs/v2.php/core/getapppassword?format=json")"
code="${response##*$'\n'}"
case "$code" in
200) APP_PASSWORD="$(jq -r '.ocs.data.apppassword // empty' <<< "${response%$'\n'*}")"
[ -n "$APP_PASSWORD" ] ;;
401) return 2 ;;
*) return 1 ;;
esac
}
# Revoke an app password, signing in with it. Uses CORE_USER and NEXTCLOUD.
nextcloud_revoke_app_password() {
auth_header "$CORE_USER" "$1" | curl -sf -o /dev/null -X DELETE -H @- \
-H 'OCS-APIRequest: true' "$NEXTCLOUD/ocs/v2.php/core/apppassword"
}
# Sign in to Nextcloud as CORE_USER with a password ($1), or PASSWORD if not
# given. Signing in with your Core password (not an app password) also turns
# back on the app passwords Nextcloud turned off when the Core password
# changed. Uses NEXTCLOUD. Returns 2 if Nextcloud says the password is wrong.
nextcloud_sign_in() {
local code
code="$(auth_header "$CORE_USER" "${1:-$PASSWORD}" | curl -s -o /dev/null -w '%{http_code}' -H @- \
-H 'OCS-APIRequest: true' "$NEXTCLOUD/ocs/v2.php/cloud/user?format=json")"
case "$code" in
200) return 0 ;;
401) return 2 ;;
*) return 1 ;;
esac
}
+60
View File
@@ -0,0 +1,60 @@
#!/bin/bash
#
# Purpose : Install what an item needs from Pop!_OS' and Ubuntu's apt
# repositories, and from Flathub. Source this file; it uses
# confirm_yes from configure.
#
# Pop!_OS comes with less than CoreDesktop installs up front, so each item
# installs what it needs the first time you set it up, after asking.
is_pop() {
[ "$(. /etc/os-release 2> /dev/null && echo "$ID")" = pop ]
}
os_name() {
(. /etc/os-release 2> /dev/null && echo "${PRETTY_NAME:-$ID}") || uname -s
}
# True if every package named is installed
pkg_installed() {
local pkg
for pkg in "$@"; do
[ "$(dpkg-query -W -f '${db:Status-Status}' "$pkg" 2> /dev/null)" = installed ] || return 1
done
}
# pkg_ensure <what they're for> <package>...: offer to install the packages
# that are missing. Fails if any is still missing.
pkg_ensure() {
local why="$1" pkg missing=()
shift
for pkg in "$@"; do
pkg_installed "$pkg" || missing+=("$pkg")
done
[ ${#missing[@]} -eq 0 ] && return 0
echo "$why needs: ${missing[*]}"
confirm_yes "Install them now (with apt; asks for your password)?" || return 1
pkg_install "${missing[@]}"
}
# Install packages without asking. apt's lists may be old on a new install,
# so they're refreshed once per run if the install fails.
pkg_install() {
sudo apt-get install -y "$@" && return 0
[ -n "$PKG_UPDATED" ] && return 1
PKG_UPDATED=1
sudo apt-get update && sudo apt-get install -y "$@"
}
# Flatpak apps come from Flathub, as in the COSMIC Store
flatpak_installed() {
flatpak info "$1" &> /dev/null
}
# flatpak_ensure <app id> <name> <what it's for>
flatpak_ensure() {
flatpak_installed "$1" && return 0
echo "$2 isn't installed. $3"
confirm_yes "Install $2 from Flathub?" || return 1
flatpak install -y --noninteractive flathub "$1"
}
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
#
# Purpose : Show a folder in the Files sidebar. Source this file; needs
# CONNECTOR.
#
# COSMIC Files has its own list (see lib/cosmic-favorites). GTK apps, such
# as Evolution's file chooser, read ~/.config/gtk-3.0/bookmarks, so the folder
# goes in both.
GTK_BOOKMARKS="$HOME/.config/gtk-3.0/bookmarks"
COSMIC_FAVORITES="$CONNECTOR/configure.d/lib/cosmic-favorites"
# sidebar_add <folder> <name>
sidebar_add() {
mkdir -p "$(dirname "$GTK_BOOKMARKS")"
grep -qs "^file://$1 " "$GTK_BOOKMARKS" || echo "file://$1 $2" >> "$GTK_BOOKMARKS"
"$COSMIC_FAVORITES" add "$1" "$2"
}
sidebar_remove() {
local tmp
if [ -f "$GTK_BOOKMARKS" ]; then
tmp="$(mktemp)" || return 1
grep -vF "file://$1 " "$GTK_BOOKMARKS" > "$tmp"
mv -f "$tmp" "$GTK_BOOKMARKS"
fi
"$COSMIC_FAVORITES" remove "$1"
}
sidebar_has() {
"$COSMIC_FAVORITES" has "$1" 2> /dev/null
}
+74
View File
@@ -0,0 +1,74 @@
#!/bin/bash
#
# Purpose : Node.js and Anthropic's sandbox runtime (srt) for the agent
# sandbox. Source this file after lib/agents.sh; it uses
# confirm_yes from configure.
#
# srt needs Node.js 22.12 or later, and Pop!_OS 24.04's is 18. So unless a
# new enough one is installed already, the current long-term support release
# is downloaded from nodejs.org into FC_TOOLS/node, checked against the
# SHA-256 sums it publishes, and used only for srt: nothing in /usr or your
# shell changes.
# srt needs Node.js 22.12 or later
node_ok() {
local node version
node="$(PATH="$FC_TOOLS/node/bin:$PATH" command -v node)" || return 1
version="$("$node" -p 'process.versions.node' 2> /dev/null)" || return 1
[ "$(printf '%s\n' 22.12.0 "$version" | sort -V | head -n 1)" = 22.12.0 ]
}
# download_checked <url> <sums url> <file name in sums> <destination>
download_checked() {
local url="$1" sums_url="$2" name="$3" dest="$4" expected actual
echo "Downloading $url"
curl -fL --progress-bar --max-time 1800 -o "$dest" "$url" || return 1
expected="$(curl -fsL --max-time 30 "$sums_url" | awk -v f="$name" '$2 == f || $2 == "*" f { print $1; exit }')"
actual="$(sha256sum "$dest" | cut -d' ' -f1)"
if [ -z "$expected" ] || [ "$expected" != "$actual" ]; then
echo -e "\e[31mThe download doesn't match the checksum its release publishes. Not installing it.\e[0m"
rm -f "$dest"
return 1
fi
}
install_node() {
local tmp version arch name status=1
version="$(curl -fsL --max-time 30 https://nodejs.org/dist/index.json \
| jq -r '[.[] | select(.lts)][0].version // empty')"
[ -n "$version" ] || { echo "Couldn't find Node.js' current release."; return 1; }
case "$(uname -m)" in
aarch64|arm64) arch=arm64 ;;
*) arch=x64 ;;
esac
name="node-$version-linux-$arch.tar.xz"
tmp="$(mktemp -d)" || return 1
if download_checked "https://nodejs.org/dist/$version/$name" \
"https://nodejs.org/dist/$version/SHASUMS256.txt" "$name" "$tmp/$name" \
&& tar -xJf "$tmp/$name" -C "$tmp" && mkdir -p "$FC_TOOLS"; then
rm -rf "$FC_TOOLS/node" && mv "$tmp/${name%.tar.xz}" "$FC_TOOLS/node" && status=0
fi
rm -rf "$tmp"
return $status
}
# srt from npm, into FC_TOOLS/srt. It has no install scripts of its own; the
# ones npm would warn it blocked belong to a Windows-only package it
# optionally depends on.
install_srt() {
local node_dir
node_ok || install_node || return 1
node_dir="$(dirname "$(PATH="$FC_TOOLS/node/bin:$PATH" command -v node)")"
echo "Installing the sandbox runtime (srt) from npm..."
PATH="$node_dir:$PATH" "$node_dir/npm" install --global --prefix "$FC_TOOLS/srt" \
--no-fund --no-audit --ignore-scripts @anthropic-ai/sandbox-runtime > /dev/null
}
# Updating srt is installing it again
srt_ensure() {
srt_path > /dev/null && return 0
echo "The sandbox is Anthropic's sandbox runtime (srt), which runs on Node.js."
node_ok || echo "This computer's Node.js is older than srt needs, so it gets its own, from nodejs.org."
confirm_yes "Install it (into $FC_TOOLS)?" || return 1
install_srt
}