AnyBot/deploy/server/setup.sh

867 lines
48 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env bash
# AnyBot 伺服器設定: the account server, HTTPS and the brain on this server, step by step.
#
# make server (= ./setup.sh) the first time: no questions — find the address, make up the
# invite and the manager's key, write .env and Caddyfile, start,
# check. Accounts are made in the app; each gets its own cloud
# brain from 大腦管理員 (the brains service).
# ./setup.sh --ask the questions instead (a domain, one account with its brain)
# make update-server (= ./setup.sh --start after git pull) start with .env as it is: no questions
# make server-logs (= ./setup.sh --logs) follow the brain's log
# ./setup.sh --dry-run ask and write the files, but don't start anything
#
# The one place this server's settings live is .env (written here; edit it, then make update-server).
# Every start goes through this script, so it always comes up on the same Docker (DOCKER_SOCKET),
# with the same address and HTTPS port (ANYBOT_RELAY_PUBLIC_URL). Plain `docker compose` from a
# shell may reach another Docker daemon; use the make targets.
#
# Run it again any time: it offers to keep the current settings (to update and restart).
#
# Without questions (scripts, Ansible…): give the answers as environment variables.
# ANYBOT_SETUP_USER=me ANYBOT_SETUP_PASSWORD=… ANYBOT_SETUP_DOMAIN=anybot.example.com ./setup.sh
# leave out ANYBOT_SETUP_DOMAIN on a computer with Tailscale to use its Tailscale address.
# ANYBOT_SETUP_DOMAIN=10.0.0.25 (an IP): only the local network, with a certificate this server
# signs itself; ANYBOT_SETUP_LAN_IP=10.0.0.25 with Tailscale: both.
# An existing setup is kept (updated and restarted).
set -u
cd "$(dirname "$0")"
DRY=0; START=0; LOGS=0; ASK=0
case "${1:-}" in
--dry-run) DRY=1 ;;
--start) START=1 ;;
--logs) LOGS=1 ;;
--ask) ASK=1 ;;
esac
if [ "$START" = 1 ] || [ "$LOGS" = 1 ]; then
[ -f .env ] || { printf '這台還沒架伺服器。第一次架:make server\n' >&2; exit 1; }
fi
# A setup once run under sudo (an older install.sh did, before the new docker group counted) left
# .env, Caddyfile and ~/.docker to root, and every run as the user after it stopped at
# "Permission denied". Hand them back (sudo asks only when it must), or say exactly how.
if [ "$(id -u)" != 0 ]; then
me=$(id -un)
for f in .env Caddyfile "${HOME:-/nonexistent}/.docker"; do
[ -e "$f" ] || continue
[ -n "$(find "$f" ! -user "$me" -print -quit 2>/dev/null)" ] || continue
if sudo -n chown -R "$me" "$f" 2>/dev/null; then continue; fi
if [ -t 0 ]; then
printf '%s 是 root 的(之前用 sudo 設定過),改回給 %s(要你的密碼):\n' "$f" "$me"
sudo chown -R "$me" "$f" && continue
fi
printf '%s 是 root 的(之前用 sudo 設定過),這次讀寫不了。請執行:\n sudo chown -R %s %s\n再跑一次。\n' "$f" "$me" "$(cd "$(dirname "$f")" && pwd)/$(basename "$f")" >&2
exit 1
done
fi
# Run as root through sudo: what is written here belongs to the person who ran it.
own_files() {
[ "$(id -u)" = 0 ] && [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != root ] && chown "$SUDO_USER" .env Caddyfile 2>/dev/null
return 0
}
AUTO=0
[ -n "${ANYBOT_SETUP_USER:-}" ] && [ -n "${ANYBOT_SETUP_PASSWORD:-}" ] && AUTO=1
# --start asks nothing: it keeps .env as it is.
[ "$START" = 1 ] && AUTO=1
# The first setup asks nothing either (the easy way below), unless --ask.
EASY=0
if [ ! -f .env ] && [ "$ASK" = 0 ] && [ -z "${ANYBOT_SETUP_USER:-}" ]; then EASY=1; AUTO=1; fi
# The Docker this server lives on: the daemon that holds its data (the volumes). Picked once, at
# the first setup, from the docker CLI as it was then, and kept in .env as DOCKER_SOCKET; every
# start after that uses it, whatever plain `docker` points at now. A host can have two daemons
# (rootless Docker for this user, and the root one reached through the docker group); a start on
# the other one comes up as a second, empty server next to the real one.
stack_socket() {
local s h
s=$(sed -n "s/^DOCKER_SOCKET=['\"]\{0,1\}\([^'\"]*\)['\"]\{0,1\}\$/\1/p" .env 2>/dev/null | tail -n 1)
if [ -z "$s" ]; then
h=${DOCKER_HOST:-}
[ -z "$h" ] && h=$(docker context inspect --format '{{.Endpoints.docker.Host}}' 2>/dev/null)
case "$h" in unix://*) s=${h#unix://} ;; esac
fi
printf '%s' "$s"
}
SOCK=$(stack_socket)
if [ -n "$SOCK" ]; then
export DOCKER_HOST="unix://$SOCK" DOCKER_SOCKET="$SOCK"
fi
if [ "$LOGS" = 1 ]; then
# (Set up the easy way there is no one brain: the manager's log, which says what it made.)
svc=anybot; grep -q "^COMPOSE_PROFILES=.*owner-brain" .env 2>/dev/null || svc=brains
exec docker compose logs -f --tail 100 "${2:-$svc}"
fi
# 語音 on this server (docker-compose's voice service, speaches): speech to text with Whisper on
# the CPU. large-v3-turbo got every word of a Mandarin test right, about 3.5 s for 11 s of speech
# on 12 cores; Systran/faster-whisper-small is three times faster and slips a word now and then
# (ANYBOT_VOICE_LISTEN_MODEL=… before ./setup.sh). Reading aloud stays with a service chosen in
# 設定 › 語音 (xAI…): speaches 0.8.2 can't say Chinese (its espeak has no "zh").
VOICE_URL=http://voice:8000/v1
VOICE_LISTEN=${ANYBOT_VOICE_LISTEN_MODEL:-deepdml/faster-whisper-large-v3-turbo-ct2}
voice_lines() {
printf "COMPOSE_PROFILES='voice'\nANYBOT_VOICE_URL='%s'\nANYBOT_VOICE_LISTEN_MODEL='%s'\n" "$VOICE_URL" "$VOICE_LISTEN"
}
# ---------- looks ----------
if [ -t 1 ]; then
B=$'\e[1m'; D=$'\e[90m'; A=$'\e[36m'; G=$'\e[32m'; Y=$'\e[33m'; R=$'\e[31m'; N=$'\e[0m'
else
B=""; D=""; A=""; G=""; Y=""; R=""; N=""
fi
STEPS=("檢查" "網址" "帳號" "啟動")
AT=0
header() {
# --start runs inside make update(-server): keep what was printed before it on the screen.
[ "$START" = 1 ] && return
printf '\e[2J\e[H\n'
printf ' %s◆%s %sAnyBot 伺服器設定%s ' "$A" "$N" "$B" "$N"
local i
for i in "${!STEPS[@]}"; do
[ "$i" -gt 0 ] && printf '%s ─ %s' "$D" "$N"
if [ "$i" -lt "$AT" ]; then printf '%s✓ %s%s' "$G" "${STEPS[$i]}" "$N"
elif [ "$i" -eq "$AT" ]; then printf '%s%s%d %s%s' "$A" "$B" $((i + 1)) "${STEPS[$i]}" "$N"
else printf '%s%d %s%s' "$D" $((i + 1)) "${STEPS[$i]}" "$N"; fi
done
printf '\n\n'
}
# A card: title, then lines (each printed after the left edge).
card_open() { printf ' %s╭─%s %s%s%s\n %s│%s\n' "$D" "$N" "$B" "$1" "$N" "$D" "$N"; }
line() { printf ' %s│%s %s\n' "$D" "$N" "$*"; }
note() { printf ' %s│%s %s%s%s\n' "$D" "$N" "$D" "$*" "$N"; }
ok() { printf ' %s│%s %s✓%s %s\n' "$D" "$N" "$G" "$N" "$*"; }
warn() { WARNED=1; printf ' %s│%s %s!%s %s\n' "$D" "$N" "$Y" "$N" "$*"; }
bad() { printf ' %s│%s %s✗ %s%s\n' "$D" "$N" "$R" "$*" "$N"; }
card_close() { printf ' %s│%s\n %s╰────────────────────────────────────────────────%s\n' "$D" "$N" "$D" "$N"; [ -n "${1:-}" ] && printf ' %s%s%s\n' "$D" "$1" "$N"; }
# Pad a label to 10 columns (Chinese characters are two columns wide).
padl() {
local w
w=$(printf '%s' "$1" | LC_ALL=C.UTF-8 wc -L 2>/dev/null || printf '%s' "$1" | wc -m)
printf '%s%*s' "$1" $((10 - w > 1 ? 10 - w : 1)) ""
}
# ask VAR "標籤" [default] [secret]: once answered, the line is redrawn without the marker.
ask() {
local __v=$1 label=$2 def=${3:-} secret=${4:-} got shown
printf ' %s│%s %s❯%s %s%s%s' "$D" "$N" "$A" "$N" "$A" "$(padl "$label")" "$N"
if [ -n "$secret" ]; then
IFS= read -rs got; printf '\n'
shown=$(printf '%s' "$got" | sed 's/./●/g')
else
IFS= read -r -e -i "$def" got || true
shown=$got
fi
printf '\e[1A\r\e[K %s│%s %s%s%s%s\n' "$D" "$N" "$D" "$(padl "$label")" "$N" "$shown"
printf -v "$__v" '%s' "$got"
}
# choose VAR "問題" "選項|說明" ... (↑↓ and Enter)
choose() {
# Without questions: the first choice (keep the setup, use Tailscale).
if [ "$AUTO" = 1 ]; then printf -v "$1" '%s' 0; return; fi
local __v=$1 title=$2; shift 2
local opts=("$@") sel=0 n=$# key rest i
while :; do
header
card_open "$title"
for i in "${!opts[@]}"; do
local name=${opts[$i]%%|*} desc=${opts[$i]#*|}
if [ "$i" -eq "$sel" ]; then line "${A}❯ ● $B$name$N"; else line " ${D}○$N $name"; fi
[ "$desc" != "${opts[$i]}" ] && [ -n "$desc" ] && note " $desc"
line ""
done
card_close "↑↓ 選擇 Enter 確定"
IFS= read -rsn1 key
if [ "$key" = $'\e' ]; then
IFS= read -rsn2 -t 0.05 rest || true
case "$rest" in "[A") sel=$(((sel + n - 1) % n)) ;; "[B") sel=$(((sel + 1) % n)) ;; esac
elif [ "$key" = "k" ]; then sel=$(((sel + n - 1) % n))
elif [ "$key" = "j" ]; then sel=$(((sel + 1) % n))
elif [ -z "$key" ]; then break
fi
done
printf -v "$__v" '%s' "$sel"
}
spin() { # spin "做什麼" command… : runs it, shows a spinner and the newest log line
local what=$1; shift
local log; log=$(mktemp)
"$@" >"$log" 2>&1 &
local pid=$! f=0 c=("⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏")
while kill -0 "$pid" 2>/dev/null; do
local last; last=$(tail -n 1 "$log" | tr -d '\r' | cut -c1-60)
printf '\r\e[K %s│%s %s%s%s %s %s%s%s' "$D" "$N" "$A" "${c[$((f % 10))]}" "$N" "$what" "$D" "$last" "$N"
f=$((f + 1)); sleep 0.15
done
wait "$pid"; local rc=$?
printf '\r\e[K'
if [ $rc -eq 0 ]; then ok "$what"; else bad "$what 失敗:"; tail -n 8 "$log" | while IFS= read -r l; do note " $l"; done; fi
rm -f "$log"
return $rc
}
pause() { [ "$AUTO" = 1 ] && return; printf ' %s%s%s' "$D" "${1:-按 Enter 繼續}" "$N"; IFS= read -r _; }
die() { card_close; printf '\n'; exit 1; }
is_ip() { printf '%s' "$1" | grep -Eq '^([0-9]{1,3}\.){3}[0-9]{1,3}$'; }
# This server's address in the local network: the one its traffic leaves from.
lan_ip() {
local a
a=$(ip route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p' | head -1)
[ -z "$a" ] && a=$(hostname -I 2>/dev/null | awk '{print $1}')
printf '%s' "$a"
}
# A tailnet's address (100.64.0.0/10) and the local network's own (RFC 1918).
is_tailnet() { case "$1" in 100.*) local o=${1#100.}; o=${o%%.*}; [ "$o" -ge 64 ] 2>/dev/null && [ "$o" -le 127 ] ;; *) return 1 ;; esac; }
is_private() { case "$1" in 10.*|192.168.*) return 0 ;; 172.*) local o=${1#172.}; o=${o%%.*}; [ "$o" -ge 16 ] 2>/dev/null && [ "$o" -le 31 ] ;; *) return 1 ;; esac; }
# Questions need a terminal: without one (a pipe, a script) a setup already made is kept and
# updated; one that would have to ask stops and says so (its question loops used to run forever).
if [ "$AUTO" = 0 ] && [ ! -t 0 ]; then
if [ -f .env ] && [ -f Caddyfile ]; then AUTO=1
else printf '這次要回答問題(--ask,或只給了帳號沒給密碼):請在終端機執行。不想回答就什麼都不給,用不問問題的裝法。\n' >&2; exit 1; fi
fi
# ---------- 0. this server ----------
AT=0; header; card_open "檢查這台伺服器"
FAIL=0; WARNED=0
if command -v docker >/dev/null; then ok "Docker 已安裝"; else bad "沒有 Docker:curl -fsSL https://get.docker.com | sh"; FAIL=1; fi
if docker compose version >/dev/null 2>&1; then ok "docker compose 可以用"; elif [ $FAIL = 0 ]; then bad "沒有 docker compose(Docker 太舊?請更新 Docker)"; FAIL=1; fi
if [ $FAIL = 0 ] && ! docker info >/dev/null 2>&1; then
if [ -n "$SOCK" ] && [ ! -S "$SOCK" ]; then
# Never fall back to another daemon: this server's data is in this one.
case "$SOCK" in
/run/user/*) bad "這台伺服器的 Docker(rootless,${SOCK})沒有在跑:systemctl --user start docker" ;;
*) bad "這台伺服器的 Docker(${SOCK})沒有在跑:sudo systemctl start docker" ;;
esac
else
bad "沒有權限使用 Docker:sudo usermod -aG docker \$USER,登出再登入"
fi
FAIL=1
fi
[ $FAIL = 0 ] && [ -n "$SOCK" ] && ok "用這個 Docker:$SOCK"
# The brain drives Docker (through docker-socket-proxy, which can limit the kinds of calls but
# not what a container mounts). On the root daemon, whoever takes over the brain can mount this
# host's disk as root; on rootless Docker the most they get is this one user.
# A Docker just installed (get.docker.com) always runs as root: a note here, not a stop — it
# matters once the server is open to the internet (a domain), and is said again there.
ROOTDOCKER=0
if [ $FAIL = 0 ] && [ "$(docker info --format '{{range .SecurityOptions}}{{.}} {{end}}' 2>/dev/null | grep -c rootless)" = 0 ]; then
ROOTDOCKER=1
note "Docker 用 root 身分在跑(一般安裝都是這樣):只在區網、tailnet 裡用沒關係"
fi
# 開機自動啟動: the containers come back by themselves (restart: unless-stopped) once Docker runs,
# so Docker itself has to start at boot — a rootless one also with nobody logged in (linger).
# Turned on here when it can be (sudo asks only in a terminal); otherwise said how.
BOOT=""
boot_check() {
local me lg
BOOT=""; BOOTFIX=""
command -v systemctl >/dev/null || { BOOT=unknown; return; }
case "$SOCK" in
/run/user/*)
me=$(id -un)
[ "$(systemctl --user is-enabled docker 2>/dev/null)" = enabled ] || systemctl --user enable docker >/dev/null 2>&1 || true
lg=$(loginctl show-user "$me" -p Linger --value 2>/dev/null)
if [ "$lg" != yes ]; then
sudo -n loginctl enable-linger "$me" 2>/dev/null || { [ "$AUTO" = 0 ] && [ -t 0 ] && sudo loginctl enable-linger "$me"; } || true
lg=$(loginctl show-user "$me" -p Linger --value 2>/dev/null)
fi
if [ "$(systemctl --user is-enabled docker 2>/dev/null)" = enabled ] && [ "$lg" = yes ]; then BOOT=1
else BOOTFIX="systemctl --user enable docker && sudo loginctl enable-linger $me"; fi
;;
*)
if [ "$(systemctl is-enabled docker 2>/dev/null)" != enabled ]; then
if [ "$(id -u)" = 0 ]; then systemctl enable docker >/dev/null 2>&1
else sudo -n systemctl enable docker >/dev/null 2>&1 || { [ "$AUTO" = 0 ] && [ -t 0 ] && sudo systemctl enable docker >/dev/null 2>&1; }; fi || true
fi
if [ "$(systemctl is-enabled docker 2>/dev/null)" = enabled ]; then BOOT=1; else BOOTFIX="sudo systemctl enable docker"; fi
;;
esac
}
if [ $FAIL = 0 ]; then
boot_check
case "$BOOT" in
1) ok "開機會自己啟動(Docker 開機就跑,大腦跟著起來)" ;;
unknown) note "這台沒有 systemd:請自己讓 Docker 開機啟動,大腦會跟著起來" ;;
*) warn "重開機後大腦不會自己回來。執行:$BOOTFIX" ;;
esac
fi
# A kept Tailscale-only setup has no Caddy: 80 and 443 aren't this server's business then.
TSONLY=0
grep -q "^ANYBOT_TAILSCALE=['\"]\{0,1\}1" .env 2>/dev/null && ! grep -q '^ANYBOT_LAN_IP=' .env && TSONLY=1
if command -v ss >/dev/null && [ "$TSONLY" = 0 ]; then
# (Tailscale's own 443 on its 100.x address isn't in the way.)
busy=$(ss -ltnH 2>/dev/null | awk '{print $4}' | grep -E ':(80|443)$' | grep -v docker | grep -vE '^(100\.|\[fd7a:115c:a1e0:)' || true)
if [ -n "$busy" ] && ! docker compose ps -q caddy 2>/dev/null | grep -q .; then warn "80 或 443 埠已被別的程式佔用(HTTPS 需要它們)"; else ok "80、443 埠可以用"; fi
fi
mem=$(awk '/MemTotal/ {print int($2/1024/1024+0.5)}' /proc/meminfo 2>/dev/null || echo 0)
[ "${mem:-0}" -ge 2 ] && ok "記憶體 ${mem} GB" || warn "記憶體只有 ${mem:-?} GB(建議 2 GB 以上,第一次建置會比較久)"
disk=$(df -Pk . 2>/dev/null | awk 'NR==2 {print int($4/1024/1024)}')
[ "${disk:-0}" -ge 10 ] && ok "硬碟還有 ${disk} GB" || warn "硬碟只剩 ${disk:-?} GB(建議 10 GB 以上)"
if [ $FAIL = 1 ] && [ $DRY = 0 ]; then note ""; note "修好上面的問題後再執行一次 ./setup.sh"; die; fi
# All fine: go on by itself.
if [ $WARNED = 1 ]; then card_close; pause; else card_close; sleep 1; fi
# Keep the current settings? (--start always does.)
if [ -f .env ] && { [ -f Caddyfile ] || [ "$START" = 1 ]; }; then
# shellcheck disable=SC1091
set -a; . ./.env; set +a
if grep -q "^COMPOSE_PROFILES=.*voice" .env; then
VOICE_OPT="拿掉語音服務|不再在這台轉文字(設定 › 語音 可以改用 xAI、OpenAI 等)"
else
VOICE_OPT="加上語音服務|在這台的 CPU 上把說的話轉成文字,不用金鑰(第一次下載約 1.6 GB 的模型)"
fi
choose KEEP "這台已經設定過了(${ANYBOT_RELAY_PUBLIC_URL:-})" \
"用現有設定,更新並重新啟動|拉下最新版、重建、重新啟動,帳號和 Bot 都不變" \
"重新設定|網址、帳號或金鑰要改" \
"$VOICE_OPT"
if [ "$KEEP" = 2 ]; then
# Toggle the voice service in the kept .env, then update and restart like 0.
if grep -q "^COMPOSE_PROFILES=.*voice" .env; then
(umask 077; grep -v -e '^COMPOSE_PROFILES=' -e '^ANYBOT_VOICE_' .env >.env.new) && mv .env.new .env
unset COMPOSE_PROFILES ANYBOT_VOICE_URL ANYBOT_VOICE_LISTEN_MODEL ANYBOT_VOICE_SPEAK_MODEL ANYBOT_VOICE_VOICE
else
(umask 077; { grep -v -e '^COMPOSE_PROFILES=' -e '^ANYBOT_VOICE_' .env; voice_lines; } >.env.new) && mv .env.new .env
fi
set -a; . ./.env; set +a
KEEP=0
fi
# Set up again, a server set up the easy way (no ANYBOT_USER) stays that way: its address is
# found again; its invite, the manager's key and the cloud brains stay. (Asking for one account
# here would make that account a second brain the account server refuses.)
if [ "$KEEP" = 1 ] && [ -z "${ANYBOT_USER:-}" ]; then
EASY=1
unset COMPOSE_FILE ANYBOT_LAN_IP ANYBOT_TAILSCALE ANYBOT_RELAY_PUBLIC_URL
fi
if [ "$KEEP" = 0 ]; then
# (An address served over plain http — a tailnet's, the easy way's — is kept without it too:
# it used to come out as https://http://….)
DOMAIN=${ANYBOT_RELAY_PUBLIC_URL#https://}; DOMAIN=${DOMAIN#http://}; USERNAME=${ANYBOT_USER:-}; INVITE=${ANYBOT_RELAY_INVITE:-}; BRAIN=${ANYBOT_HOST_NAME:-}
LANIP=${ANYBOT_LAN_IP:-}
AT=3; SKIP=1
fi
fi
# Made-up keys: a long one for the manager, a short one people type (the invite).
gen_key() { head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n'; }
gen_code() { local c; c=$(LC_ALL=C tr -dc 'abcdefghjkmnpqrstuvwxyz23456789' </dev/urandom 2>/dev/null | head -c 8); printf '%s-%s' "${c:0:4}" "${c:4:4}"; }
# ---------- the easy way: a first setup, no questions ----------
# The address is found here; the accounts are made in the app, and each gets a cloud brain of its
# own from 大腦管理員 (no account or password on the server). The invite is needed by the first
# account too — or whoever reached the server first would own it.
if [ "$EASY" = 1 ] && [ "${SKIP:-0}" != 1 ]; then
AT=1; TS=0; LAN=0; OPEN=0; LANIP=""; USERNAME=""; BRAIN="雲端大腦"
TSNAME=$(tailscale status --json 2>/dev/null | sed -n 's/.*"DNSName": *"\([^"]*\)\.".*/\1/p' | head -1)
TSIP=""
if [ -n "$TSNAME" ] && ! tailscale status --json 2>/dev/null | tr -d ' \n' | grep -q '"CertDomains":\["'; then
# (headscale, or Tailscale with HTTPS off: no certificate for the name — its address instead.)
TSIP=$(tailscale ip -4 2>/dev/null | head -1)
TSNAME=""
fi
# Plain http only on a tailnet (WireGuard already encrypts it; AnyBot takes http only there).
# The local network gets https with a certificate this server signs; an address open to the
# internet without a domain gets nothing in the clear — a domain or Tailscale is asked for.
if [ -n "${ANYBOT_SETUP_DOMAIN:-}" ]; then
DOMAIN=${ANYBOT_SETUP_DOMAIN#https://}; DOMAIN=${DOMAIN#http://}; DOMAIN=${DOMAIN%%/*}
if is_ip "$DOMAIN"; then
LANIP=$DOMAIN
if is_tailnet "$DOMAIN"; then OPEN=1; else LAN=1; fi
fi
elif [ -n "$TSNAME" ]; then
DOMAIN=$TSNAME; TS=1
elif [ -n "$TSIP" ]; then
OPEN=1; LANIP=$TSIP; DOMAIN=$TSIP
else
LANIP=$(lan_ip)
if ! is_ip "${LANIP:-}"; then
header; card_open "網址"; bad "找不到這台的位址:請加上 ANYBOT_SETUP_DOMAIN=網域或 IP 再執行一次"; die
fi
if ! is_private "$LANIP"; then
header; card_open "網址"
bad "這台的位址 $LANIP 在網路上是公開的:不把帳號用明文開在網路上"
note "給它一個網域:ANYBOT_SETUP_DOMAIN=你的網域(DNS 先指到這台,HTTPS 憑證自動申請)"
note "或先裝 Tailscale(只有你的裝置連得到),再執行一次"
die
fi
LAN=1; DOMAIN=$LANIP
fi
INVITE=${ANYBOT_RELAY_INVITE:-}
[ -n "$INVITE" ] || INVITE=$(gen_code)
VOICE=1; [ "${ANYBOT_SETUP_VOICE:-}" = 1 ] && VOICE=0
q() { printf "%s='%s'\n" "$1" "$2"; }
# (Set up again: every other line of the older .env stays — settings added by hand, the
# voice service unless asked anew, the Docker it is on.)
keep=""
if [ -f .env ]; then
drop='^(#|ANYBOT_HOST_NAME=|ANYBOT_RELAY_INVITE=|ANYBOT_RELAY_MANAGER_TOKEN=|ANYBOT_RELAY_PUBLIC_URL=|ANYBOT_RESTORE_FROM_ACCOUNT=|ANYBOT_TAILSCALE=|ANYBOT_LAN_IP=|COMPOSE_FILE='
[ "$VOICE" = 0 ] && drop="$drop|ANYBOT_VOICE_"
keep=$(grep -E -v "$drop)" .env || true)
fi
umask 077
{
echo "# Written by setup.sh (the easy way). Change it, then make update-server."
[ -n "$keep" ] && printf '%s\n' "$keep"
q ANYBOT_HOST_NAME "$BRAIN"
q ANYBOT_RELAY_INVITE "$INVITE"
q ANYBOT_RELAY_MANAGER_TOKEN "${ANYBOT_RELAY_MANAGER_TOKEN:-$(gen_key)}"
if [ "$OPEN" = 1 ]; then q ANYBOT_RELAY_PUBLIC_URL "http://$DOMAIN"; else q ANYBOT_RELAY_PUBLIC_URL "https://$DOMAIN"; fi
q ANYBOT_RESTORE_FROM_ACCOUNT ""
[ "$TS" = 1 ] && q ANYBOT_TAILSCALE 1
[ -n "$LANIP" ] && q ANYBOT_LAN_IP "$LANIP"
[ "$TS" = 1 ] && q COMPOSE_FILE "docker-compose.yml:docker-compose.tailscale.yml"
[ -n "$LANIP" ] && q COMPOSE_FILE "docker-compose.yml:docker-compose.lan.yml"
[ "$VOICE" = 0 ] && voice_lines
true
} >.env
chmod 600 .env
umask 022
if [ "$OPEN" = 1 ]; then
sed "s/ADDR/$LANIP/g" ../../relay/Caddyfile.open >Caddyfile
elif [ "$LAN" = 1 ]; then
sed "s/LAN_IP/$LANIP/g" ../../relay/Caddyfile.lan >Caddyfile
else
sed "s/^anybot.example.com {/$DOMAIN {/" ../../relay/Caddyfile >Caddyfile
fi
[ "$TS" = 2 ] && TS=0
SKIP=1
fi
if [ "${SKIP:-0}" != 1 ]; then
# ---------- 1. the address ----------
AT=1; MSG=""; TS=0; LAN=0; LANIP=""; LANASKED=0
# On a tailnet: offer its address (HTTPS from Tailscale, no domain, nothing open to the internet).
TSNAME=$(tailscale status --json 2>/dev/null | sed -n 's/.*"DNSName": *"\([^"]*\)\.".*/\1/p' | head -1)
# A tailnet that hands out no certificates (headscale; Tailscale with HTTPS off in its admin
# page) can't give https://its-name: offered was an address that never answered. Its own
# address works, with a certificate this server signs (as for the local network).
TSIP=""
if [ -n "$TSNAME" ] && ! tailscale status --json 2>/dev/null | tr -d ' \n' | grep -q '"CertDomains":\["'; then
TSIP=$(tailscale ip -4 2>/dev/null | head -1)
TSNAME=""
fi
if [ "$AUTO" = 1 ] && [ -n "${ANYBOT_SETUP_DOMAIN:-}" ]; then
DOMAIN=${ANYBOT_SETUP_DOMAIN#https://}; TSNAME=""; TS=2
is_ip "$DOMAIN" && { LAN=1; LANIP=$DOMAIN; }
fi
if [ "$AUTO" = 1 ] && [ -n "$TSNAME" ] && [ -n "${ANYBOT_SETUP_LAN_IP:-}" ]; then LAN=1; LANIP=$ANYBOT_SETUP_LAN_IP; fi
# Without questions and no address given: the tailnet's own address when it has no certificates.
if [ "$AUTO" = 1 ] && [ "$TS" = 0 ] && [ -z "$TSNAME" ] && [ -n "$TSIP" ]; then
DOMAIN=$TSIP; LAN=1; LANIP=$TSIP; TS=2
fi
if [ "$AUTO" = 1 ] && [ "$TS" = 0 ] && [ -z "$TSNAME" ]; then
header; card_open "網址"; bad "這台沒有 Tailscale:請加上 ANYBOT_SETUP_DOMAIN=你的網域(或區網 IP)"; die
fi
# The local network's own address: HTTPS with a certificate this server signs itself.
LANDESC="憑證是這台自己簽的:每台手機和電腦要先信任一次。位址要固定(在路由器設成固定 IP)"
if [ -n "$TSIP" ] && [ "$AUTO" = 0 ]; then
choose HOW "手機和其他電腦用哪個網址連到這台?" \
"用 tailnet 位址:https://$TSIP|只有你 tailnet 裡的手機和電腦連得到,不用網域。這個 tailnet 不發 HTTPS 憑證(headscale,或 Tailscale 管理頁沒開 HTTPS),憑證由這台自己簽:每台手機和電腦先信任一次" \
"只用區網 IP:https://$(lan_ip)|只有同一個區網連得到。$LANDESC" \
"用自己的網域|任何地方都連得到(網域要先指到這台)"
case "$HOW" in
0) LAN=1; LANIP=$TSIP; TS=2; LANASKED=1 ;;
1) LAN=1; TS=2 ;;
esac
elif [ -n "$TSNAME" ]; then
choose HOW "手機和其他電腦用哪個網址連到這台?" \
"用 Tailscale:https://$TSNAME|只有你 Tailscale 裡的手機和電腦連得到。不用網域,也不用開 80、443 埠" \
"Tailscale + 區網 IP:https://$(lan_ip)|在同一個區網用 IP 連,出門用 Tailscale。$LANDESC" \
"只用區網 IP:https://$(lan_ip)|只有同一個區網連得到。$LANDESC" \
"用自己的網域|任何地方都連得到(網域要先指到這台)"
case "$HOW" in
0) DOMAIN=$TSNAME; TS=1 ;;
1) DOMAIN=$TSNAME; TS=1; LAN=1 ;;
2) LAN=1; TS=2 ;;
esac
elif [ "$AUTO" = 0 ]; then
choose HOW "手機和其他電腦用哪個網址連到這台?" \
"用區網 IP:https://$(lan_ip)|只有同一個區網連得到,不用網域。$LANDESC" \
"用自己的網域|任何地方都連得到(網域要先指到這台)"
[ "$HOW" = 0 ] && { LAN=1; TS=2; }
fi
while [ "$LAN" = 1 ] && [ "$AUTO" = 0 ] && [ "$LANASKED" = 0 ]; do
header; card_open "這台在區網的 IP"
note "手機和電腦在同一個區網打開 https://這個 IP。${LANDESC}。"
line ""
[ -n "$MSG" ] && { printf '%s\n' "$MSG"; line ""; }
ask LANIP "IP" "${LANIP:-$(lan_ip)}"
LANIP=${LANIP#https://}; LANIP=${LANIP#http://}; LANIP=${LANIP%%/*}
if ! is_ip "$LANIP"; then MSG=$(bad "請輸入像 10.0.0.25 這樣的 IP"); continue; fi
MSG=""
break
done
[ "$LAN" = 1 ] && [ "$TS" != 1 ] && DOMAIN=$LANIP
while [ "$TS" = 0 ]; do
header; card_open "手機和其他電腦用哪個網址連到這台?"
note "網域要先指到這台伺服器(DNS 的 A 紀錄)。HTTPS 憑證會自動申請、自動更新。"
line ""
[ -n "$MSG" ] && { printf '%s\n' "$MSG"; line ""; }
ask DOMAIN "網域" "${DOMAIN:-}"
DOMAIN=${DOMAIN#https://}; DOMAIN=${DOMAIN#http://}; DOMAIN=${DOMAIN%%/*}
if ! printf '%s' "$DOMAIN" | grep -Eq '^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'; then MSG=$(bad "請輸入像 anybot.example.com 這樣的網域"); continue; fi
ips=$(getent ahosts "$DOMAIN" 2>/dev/null | awk '{print $1}' | sort -u | tr '\n' ' ')
if [ -z "$ips" ]; then
card_close
choose GO "「${DOMAIN}」還沒有指到任何位址" "重新輸入|" "仍然繼續|DNS 剛設好、還沒生效時可以先繼續;生效後憑證會自動申請"
[ "$GO" = 0 ] && { MSG=""; continue; }
else
mine=$(hostname -I 2>/dev/null || true)
hit=0; for ip in $ips; do case " $mine " in *" $ip "*) hit=1 ;; esac; done
if [ $hit = 1 ]; then MSG=$(ok "$DOMAIN → ${ips}(就是這台)"); else MSG=$(warn "$DOMAIN → ${ips}(這台的位址:${mine:-不知道};在 NAT 或雲端主機後面時這是正常的)"); fi
header; card_open "手機和其他電腦用哪個網址連到這台?"; printf '%s\n' "$MSG"; card_close; sleep 1
fi
break
done
[ "$TS" = 2 ] && TS=0
# ---------- 2. the account ----------
AT=2; MSG=""
if [ "$AUTO" = 1 ]; then USERNAME=$ANYBOT_SETUP_USER; PW1=$ANYBOT_SETUP_PASSWORD; BRAIN="雲端大腦"; fi
while [ "$AUTO" = 0 ]; do
header; card_open "你的 AnyBot 帳號"
note "手機、電腦都用這個帳號登入。第一次啟動時會自動建立。"
line ""
[ -n "$MSG" ] && { printf '%s\n' "$MSG"; line ""; }
ask USERNAME "帳號" "${USERNAME:-}"
if ! printf '%s' "$USERNAME" | grep -Eq '^[A-Za-z0-9._@-]{2,64}$'; then MSG=$(bad "帳號只能用英文字母、數字和 . _ @ -(2–64 個字)"); continue; fi
ask PW1 "密碼" "" secret
ask PW2 "再一次" "" secret
if [ "${#PW1}" -lt 8 ]; then MSG=$(bad "密碼至少 8 個字"); continue; fi
if [ "$PW1" != "$PW2" ]; then MSG=$(bad "兩次密碼不一樣"); continue; fi
case "$PW1" in *"'"*) MSG=$(bad "密碼裡不能有單引號 '"); continue ;; esac
BRAIN="雲端大腦"
break
done
# ---------- 語音 ----------
# Without questions only when asked for (ANYBOT_SETUP_VOICE=1): it downloads about 1.6 GB.
if [ "$AUTO" = 1 ]; then
[ "${ANYBOT_SETUP_VOICE:-}" = 1 ] && VOICE=0 || VOICE=1
else
choose VOICE "要在這台架語音服務嗎?" \
"要|在這台的 CPU 上把說的話轉成文字,每台電腦和手機都用它,不用金鑰、不花錢。第一次會下載約 1.6 GB 的模型。朗讀另外在 App 的 設定 › 語音 選(例如 xAI)" \
"先不要|之後可以再執行一次 ./setup.sh 加上;或在 App 的 設定 › 語音 改用 xAI、OpenAI 等服務"
fi
# Only this account (others can be let in later: ANYBOT_RELAY_INVITE in .env). AI keys are set
# in the app (設定 › 模型); they stay on the brain.
# (A server set up again keeps its invite and the manager's key: people still sign up with
# the same invite, and the cloud brains already made stay theirs.)
INVITE=${ANYBOT_RELAY_INVITE:-}; XAI=""; ANT=""; OAI=""; GEM=""; RESTORE=""
q() { printf "%s='%s'\n" "$1" "$2"; }
umask 077
{
echo "# Written by setup.sh. Run ./setup.sh again to change."
q ANYBOT_USER "$USERNAME"
q ANYBOT_PASSWORD "$PW1"
q ANYBOT_HOST_NAME "$BRAIN"
q ANYBOT_RELAY_INVITE "$INVITE"
q ANYBOT_RELAY_PUBLIC_URL "https://$DOMAIN"
q ANYBOT_RESTORE_FROM_ACCOUNT "$RESTORE"
q XAI_API_KEY "$XAI"
q ANTHROPIC_API_KEY "$ANT"
q OPENAI_API_KEY "$OAI"
q GEMINI_API_KEY "$GEM"
[ "$TS" = 1 ] && q ANYBOT_TAILSCALE 1
[ "$LAN" = 1 ] && q ANYBOT_LAN_IP "$LANIP"
case "$TS$LAN" in
10) q COMPOSE_FILE "docker-compose.yml:docker-compose.tailscale.yml" ;;
11) q COMPOSE_FILE "docker-compose.yml:docker-compose.tailscale.yml:docker-compose.lan.yml" ;;
01) q COMPOSE_FILE "docker-compose.yml:docker-compose.lan.yml" ;;
esac
[ "$VOICE" = 0 ] && voice_lines
} >.env
chmod 600 .env
umask 022
if [ "$LAN" = 1 ]; then
sed "s/LAN_IP/$LANIP/g" ../../relay/Caddyfile.lan >Caddyfile
else
sed "s/^anybot.example.com {/$DOMAIN {/" ../../relay/Caddyfile >Caddyfile
fi
fi
# Pin this server's Docker in .env (see stack_socket), whether .env was just written or kept from
# an earlier setup (one made before this has no DOCKER_SOCKET, or only a rootless one has it).
# docker-socket-proxy mounts the same socket, so the brain drives the bots' computer there too.
if [ -n "$SOCK" ] && ! grep -qxF "DOCKER_SOCKET='$SOCK'" .env; then
(umask 077; { grep -v '^DOCKER_SOCKET=' .env; printf "DOCKER_SOCKET='%s'\n" "$SOCK"; } >.env.new) \
&& mv .env.new .env
fi
own_files
# Every setup — and every update of an older one — has the manager's key (each account its cloud
# brain); one set up for a single account (ANYBOT_USER) keeps that account's own brain running
# as before (the owner-brain profile), next to the voice service when it is on.
if [ -f .env ] && [ "$DRY" = 0 ]; then
if ! grep -q "^ANYBOT_RELAY_MANAGER_TOKEN=['\"]\{0,1\}[0-9a-f]\{32,\}" .env; then
(umask 077; { grep -v '^ANYBOT_RELAY_MANAGER_TOKEN=' .env; printf "ANYBOT_RELAY_MANAGER_TOKEN='%s'\n" "$(gen_key)"; } >.env.new) && mv .env.new .env
fi
# Who asked is believed only from Caddy, which sends this secret — where Caddy is the only way
# in (Tailscale serve can't send it: there the account server believes it as before). An older
# Caddyfile (one written by hand too) gets the line that sends it, and caddy is made again so it
# reads it; one where that line can't go keeps the old way.
secret=1
grep -q "^ANYBOT_TAILSCALE=['\"]\{0,1\}1" .env && secret=0
[ -f Caddyfile ] || secret=0
# (Spaces and tabs written out: the awk of older Debian and Ubuntu, mawk 1.3.3, has no
# [[:space:]] and would match nothing.)
ws="[ $(printf '\t')]"
block="^$ws*reverse_proxy$ws+relay:8080$ws*[{]$ws*\$"
# The blocks the line goes in, and any other reverse_proxy or `to` naming the relay (one line,
# a matcher, http://relay:8080, the container's name, a comment after the {) — what else this
# Caddy forwards (a NAS, another site) doesn't count.
blocks=0; others=0
if [ -f Caddyfile ]; then
blocks=$(grep -Ec "$block" Caddyfile || true)
others=$(grep -v "^$ws*#" Caddyfile | grep -E "^$ws*(reverse_proxy|to)$ws.*relay[:-]" | grep -Evc "$block" || true)
fi
if [ "$secret" = 1 ] && ! grep -q 'X-AnyBot-Proxy' Caddyfile; then
# Only where every way to the account server is a block the line can go in (any other would
# forward without it: the old way, and said so), each one got its line, and Caddy reads the
# file; written back into the same file (caddy has that one file mounted), the one before put
# back if that write fails half way.
if [ "${blocks:-0}" -gt 0 ] && [ "${others:-0}" = 0 ] \
&& awk -v re="$block" '{ print } $0 ~ re { print "\t\theader_up X-AnyBot-Proxy {$ANYBOT_PROXY_SECRET}" }' Caddyfile >Caddyfile.new \
&& [ "$(grep -c 'X-AnyBot-Proxy' Caddyfile.new)" = "$blocks" ] \
&& docker run --rm -e ANYBOT_PROXY_SECRET=check -v "$PWD/Caddyfile.new:/etc/caddy/Caddyfile:ro" caddy:2 caddy adapt --config /etc/caddy/Caddyfile --adapter caddyfile >/dev/null 2>&1 \
&& cp Caddyfile Caddyfile.before \
&& { cat Caddyfile.new >Caddyfile || { cat Caddyfile.before >Caddyfile; false; }; }; then
CADDY_PATCHED=1
else
secret=0
CADDY_NOSECRET=1
fi
rm -f Caddyfile.new Caddyfile.before
elif [ "$secret" = 1 ]; then
# One that has the line: a way to the account server without it (added later by hand, or one
# an older update let through) is said — the requests on it all come from Caddy as far as
# the account server knows, and share one limit for sign-ups and sign-ins.
heads=$(grep -v "^$ws*#" Caddyfile | grep -c 'X-AnyBot-Proxy' || true)
if [ "${others:-0}" != 0 ] || [ "${blocks:-0}" -gt "${heads:-0}" ]; then CADDY_PARTIAL=1; fi
fi
if [ "$secret" = 1 ] && ! grep -q "^ANYBOT_PROXY_SECRET=['\"]\{0,1\}[0-9a-f]\{32,\}" .env; then
(umask 077; { grep -v '^ANYBOT_PROXY_SECRET=' .env; printf "ANYBOT_PROXY_SECRET='%s'\n" "$(gen_key)"; } >.env.new) && mv .env.new .env
elif [ "$secret" = 0 ] && grep -q '^ANYBOT_PROXY_SECRET=' .env; then
(umask 077; grep -v '^ANYBOT_PROXY_SECRET=' .env >.env.new) && mv .env.new .env
fi
owner=$(sed -n "s/^ANYBOT_USER=['\"]\{0,1\}\([^'\"]*\)['\"]\{0,1\}\$/\1/p" .env | tail -n 1)
# (Profiles put there by hand stay; only these two follow the settings.)
profiles=$(sed -n "s/^COMPOSE_PROFILES=['\"]\{0,1\}\([^'\"]*\)['\"]\{0,1\}\$/\1/p" .env | tr ',' '\n' | grep -v -x -e owner-brain -e voice -e '' | sort -u | paste -sd, - || true)
[ -n "$owner" ] && profiles="${profiles:+$profiles,}owner-brain"
grep -q '^ANYBOT_VOICE_URL=' .env && profiles="${profiles:+$profiles,}voice"
(umask 077; { grep -v '^COMPOSE_PROFILES=' .env; if [ -n "$profiles" ]; then printf "COMPOSE_PROFILES='%s'\n" "$profiles"; fi; } >.env.new)
if cmp -s .env.new .env; then rm -f .env.new; else mv .env.new .env; fi
own_files
# (What was taken out above or by hand is out for this start too: what was read earlier stays
# in this shell, and docker compose takes the shell's before the file's.)
unset ANYBOT_PROXY_SECRET COMPOSE_PROFILES ANYBOT_VOICE_URL ANYBOT_VOICE_LISTEN_MODEL ANYBOT_VOICE_SPEAK_MODEL ANYBOT_VOICE_VOICE
set -a; . ./.env; set +a
fi
# At boot Docker can be up before the address caddy listens on (a tailnet's comes up late):
# caddy then fails to start, and Docker doesn't try again — the server is gone until someone
# starts it. Letting the system take an address that isn't up yet keeps that from happening.
BINDFIX=""
if [ -n "${ANYBOT_LAN_IP:-}" ] && [ "$DRY" = 0 ] && command -v sysctl >/dev/null && [ "$(sysctl -n net.ipv4.ip_nonlocal_bind 2>/dev/null)" != 1 ]; then
fix="echo net.ipv4.ip_nonlocal_bind=1 >/etc/sysctl.d/90-anybot.conf && sysctl -q -p /etc/sysctl.d/90-anybot.conf"
if [ "$(id -u)" = 0 ]; then sh -c "$fix" 2>/dev/null || BINDFIX="sudo sh -c '$fix'"
elif ! sudo -n sh -c "$fix" 2>/dev/null; then
if [ "$START" = 0 ] && [ -t 0 ]; then
printf ' 讓這台重開機時一定綁得到 %s(要你的密碼):\n' "$ANYBOT_LAN_IP"
sudo sh -c "$fix" || BINDFIX="sudo sh -c '$fix'"
else BINDFIX="sudo sh -c '$fix'"; fi
fi
fi
# ---------- 4. start ----------
AT=3; header; card_open "啟動"
[ "$START" = 1 ] && ok "用現有設定(.env)" || ok "寫好設定(.env、Caddyfile)"
if [ "${CADDY_NOSECRET:-0}" = 1 ]; then
warn "Caddyfile 沒辦法自動補上送暗號的那行(有別的轉到 relay 的寫法,或 Caddy 檢查沒過):帳號伺服器照舊相信請求自己說的來源,註冊、登入的次數限制擋不住偽造的。"
note "要補:在每個轉到 relay:8080 的 reverse_proxy 區塊裡加 header_up X-AnyBot-Proxy {\$ANYBOT_PROXY_SECRET},再 make update-server"
fi
if [ "${CADDY_PARTIAL:-0}" = 1 ]; then
warn "Caddyfile 裡有轉到 relay 的路沒帶暗號:走那條路的請求,帳號伺服器都當成從 Caddy 來(註冊、登入的次數限制大家共用)。"
note "要補:那些 reverse_proxy 寫成區塊(reverse_proxy relay:8080 { … }),裡面加 header_up X-AnyBot-Proxy {\$ANYBOT_PROXY_SECRET},再 make update-server"
fi
if [ $DRY = 1 ]; then
warn "試跑(--dry-run):沒有啟動。要啟動:make update-server"
card_close; exit 0
fi
# --start: make update(-server) has pulled already (or was told not to, PULL=0).
if [ "${SKIP:-0}" = 1 ] && [ "$START" = 0 ] && [ -d ../../.git ] && command -v git >/dev/null; then
spin "拉下最新版" git -C ../.. pull --ff-only || true
fi
# Small servers run out of memory compiling many crates at once: one compile per 2 GB.
if [ -z "${ANYBOT_BUILD_JOBS:-}" ] && [ -r /proc/meminfo ]; then
mem=$(awk '/MemTotal/ {m=$2} /SwapTotal/ {s=$2} END {print int((m + s / 2) / 1024)}' /proc/meminfo)
j=$((mem / 2000)); [ "$j" -lt 1 ] && j=1
export ANYBOT_BUILD_JOBS=$j
[ "$mem" -lt 3000 ] && warn "記憶體只有 ${mem} MB:編譯會比較久。被中斷的話先加 2 GB swap(見 docs/install.md)"
fi
spin "建置(第一次約 5–15 分鐘)" docker compose build || die
# (From here the manager's start line is this start's: one from before doesn't count.)
started=$(date -u +%Y-%m-%dT%H:%M:%SZ)
docker compose stop -t 120 brains >/dev/null 2>&1 || true
# (Stopped above: started again however this ends — a failed start, Ctrl-C — not left stopped.)
trap 'docker compose start brains >/dev/null 2>&1' EXIT
trap 'exit 130' INT TERM
spin "啟動" docker compose up -d || die
trap - EXIT INT TERM
if [ "${CADDY_PATCHED:-0}" = 1 ]; then
spin "Caddy 換上新設定" docker compose up -d --force-recreate --no-deps caddy || true
fi
[ "${ANYBOT_TAILSCALE:-}" = 1 ] && TS=1
if [ "${TS:-0}" = 1 ]; then
# Tailscale gives the address HTTPS and passes it to the account server (remembered across reboots).
# The HTTPS port is the one in the address (ANYBOT_RELAY_PUBLIC_URL in .env, e.g.
# https://name.ts.net:8443); 443 when it has none.
TSPORT=443
case "$DOMAIN" in *:*) TSPORT=${DOMAIN##*:} ;; esac
served() {
tailscale serve status --json 2>/dev/null | tr -d ' \n' \
| grep -q "\"[^\"]*:$TSPORT\":{\"Handlers\":{\"/\":{\"Proxy\":\"http://127.0.0.1:8780\"}"
}
if served || tailscale serve --bg --https="$TSPORT" http://127.0.0.1:8780 >/dev/null 2>&1 \
|| sudo tailscale serve --bg --https="$TSPORT" http://127.0.0.1:8780 >/dev/null 2>&1; then
ok "Tailscale:https://$DOMAIN → 帳號伺服器"
else
bad "沒辦法設定 tailscale serve。請執行:sudo tailscale serve --bg --https=$TSPORT http://127.0.0.1:8780"
fi
fi
# The brain joins the account (and makes it, the first time) — a setup for one account. Set up
# the easy way there is no account yet: 大腦管理員 is up, waiting for the first sign-up.
f=0; c=("⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏"); joined=""
manager=""
for _ in $(seq 1 200); do
mlogs=$(docker compose logs --no-color --since "$started" brains 2>/dev/null)
if docker compose ps --status running --services 2>/dev/null | grep -qx brains && printf '%s' "$mlogs" | grep -q "大腦管理員:每個帳號一個雲端大腦"; then manager=1; break; fi
printf '\r\e[K %s│%s %s%s%s 大腦管理員啟動中…' "$D" "$N" "$A" "${c[$((f % 10))]}" "$N"; f=$((f + 1)); sleep 0.3
done
printf '\r\e[K'
if [ -n "$manager" ]; then ok "大腦管理員就緒:每個註冊的帳號會自動有自己的雲端大腦"
else
bad "大腦管理員沒有啟動。最近的紀錄:"
printf '%s\n' "$mlogs" | grep "大腦管理員" | tail -n 4 | while IFS= read -r l; do note " ${l#*| }"; done
fi
[ -z "${USERNAME:-}" ] && joined=$manager
for _ in $(seq 1 600); do
[ -z "${USERNAME:-}" ] && break
logs=$(docker compose logs --no-color anybot 2>/dev/null | tail -n 40)
if printf '%s' "$logs" | grep -q "透過帳號"; then joined=1; break; fi
printf '\r\e[K %s│%s %s%s%s 大腦正在登入帳號…' "$D" "$N" "$A" "${c[$((f % 10))]}" "$N"; f=$((f + 1)); sleep 0.3
done
printf '\r\e[K'
if [ -z "${USERNAME:-}" ]; then :
elif [ -n "$joined" ]; then
printf '%s' "$logs" | grep -q "已建立帳號" && ok "建立帳號 ${USERNAME}" || ok "大腦「${BRAIN}」已登入帳號"
else
bad "大腦沒有登入帳號。最近的紀錄:"
printf '%s\n' "$logs" | grep "AnyBot:" | tail -n 4 | while IFS= read -r l; do note " ${l#*| }"; done
fi
# HTTPS from outside (the certificate can take a minute). Not for an address kept as plain http.
if [ "$DOMAIN" != "${LANIP:-}" ] && [ "${ANYBOT_RELAY_PUBLIC_URL#http://}" = "${ANYBOT_RELAY_PUBLIC_URL:-}" ]; then
https=""
for _ in $(seq 1 120); do
if curl -fsS --max-time 5 "https://$DOMAIN/api/hello" 2>/dev/null | grep -q anybot-relay; then https=1; break; fi
printf '\r\e[K %s│%s %s%s%s 等 HTTPS 憑證…' "$D" "$N" "$A" "${c[$((f % 10))]}" "$N"; f=$((f + 1)); sleep 1
done
printf '\r\e[K'
if [ -n "$https" ]; then ok "https://$DOMAIN 可以連"
elif [ "${TS:-0}" = 1 ]; then warn "https://$DOMAIN 還連不到。Tailscale 的 HTTPS 要在管理頁打開(DNS › HTTPS Certificates),看設定:tailscale serve status"
else warn "https://$DOMAIN 還連不到(DNS 還沒生效,或 80/443 埠被防火牆擋住)。看紀錄:deploy/server/setup.sh --logs caddy"; fi
fi
# The local network's address: checked with the certificate Caddy signed it with.
if [ -n "${LANIP:-}" ]; then
lanok=""; ca=$(mktemp)
for _ in $(seq 1 60); do
if docker compose exec -T caddy cat /data/caddy/pki/authorities/local/root.crt >"$ca" 2>/dev/null \
&& curl -fsS --max-time 5 --cacert "$ca" "https://$LANIP/api/hello" 2>/dev/null | grep -q anybot-relay; then lanok=1; break; fi
printf '\r\e[K %s│%s %s%s%s 等區網的 HTTPS…' "$D" "$N" "$A" "${c[$((f % 10))]}" "$N"; f=$((f + 1)); sleep 1
done
printf '\r\e[K'; rm -f "$ca"
if [ -n "$lanok" ]; then ok "https://$LANIP 可以連(憑證:http://$LANIP/anybot-ca.crt)"
else warn "https://$LANIP 還連不到(80/443 埠被防火牆擋住?)。看紀錄:deploy/server/setup.sh --logs caddy"; fi
fi
# The address served over plain http (a tailnet's, the easy way's): what AnyBot and the phone open.
URL=${ANYBOT_RELAY_PUBLIC_URL:-https://$DOMAIN}
if [ "${URL#http://}" != "$URL" ]; then
plain=""
for _ in $(seq 1 60); do
if curl -fsS --max-time 5 "$URL/api/hello" 2>/dev/null | grep -q anybot-relay; then plain=1; break; fi
printf '\r\e[K %s│%s %s%s%s 等 %s…' "$D" "$N" "$A" "${c[$((f % 10))]}" "$N" "$URL"; f=$((f + 1)); sleep 1
done
printf '\r\e[K'
if [ -n "$plain" ]; then ok "$URL 可以連"; else warn "$URL 還連不到(80 埠被防火牆擋住?)。看紀錄:deploy/server/setup.sh --logs caddy"; fi
fi
if [ "$START" = 1 ]; then
docker compose ps --format ' {{.Service}} {{.Status}}' 2>/dev/null | while IFS= read -r l; do note "$l"; done
[ -n "${BINDFIX:-}" ] && warn "重開機時可能綁不到 ${ANYBOT_LAN_IP:-}:執行 $BINDFIX"
note "看紀錄:make server-logs"
card_close
[ -n "$joined" ]; exit $?
fi
card_close
printf '\n'
card_open "$([ -n "$joined" ] && echo "完成了" || echo "差一點")"
boot_line() {
[ -n "${BINDFIX:-}" ] && line "${B}開機${N} ${Y}重開機時可能綁不到 ${ANYBOT_LAN_IP:-}${N}:執行 $BINDFIX"
case "$BOOT" in
1) line "${B}開機${N} 這台重開機後,帳號伺服器和每個雲端大腦會自己起來" ;;
unknown) ;;
*) line "${B}開機${N} ${Y}重開機後不會自己起來${N}:執行 $BOOTFIX" ;;
esac
}
# Set up the easy way: no account here — they are made in the app, each with its own cloud brain.
if [ -z "${USERNAME:-}" ]; then
line "${B}網址${N} ${A}$URL${N}"
line "${B}邀請碼${N} ${A}${ANYBOT_RELAY_INVITE:-}${N} 註冊要填(第一個人也要;給家人朋友也是這組)"
note " ${Y}先自己註冊${N}:第一個註冊的帳號是擁有者,只有它的雲端大腦有 Bot 的電腦(能動整台伺服器)"
note " ${Y}只給你信任的人${N}:每個帳號的雲端大腦能在這台伺服器的網路裡跑程式(連得到你的區網、tailnet)"
line ""
line "${B}電腦${N} 裝好 AnyBot 打開 →「登入帳號」→ 填上面的網址 →「註冊」"
note " 註冊好幾秒後就用上你自己的雲端大腦,這台電腦也自動是它的手腳"
line "${B}手機${N} 打開 ${A}$URL${N},登入同一個帳號(可以「加入主畫面」)"
if [ "${URL#http://}" != "$URL" ] && [ -n "${LANIP:-}" ]; then
note " 要手機通知:先打開 http://$LANIP/anybot-ca.crt 安裝並信任,再改用 https://$LANIP"
elif [ -n "${LANIP:-}" ]; then
line "${B}信任憑證${N} 每台電腦和手機先打開 ${A}http://$LANIP/anybot-ca.crt${N} 安裝它(一次就好)"
note " iPhone:裝好描述檔後,到 設定 › 一般 › 關於本機 › 憑證信任設定 打開它"
note " Mac:在「鑰匙圈存取」把它設成「永遠信任」;Linux:放進 /usr/local/share/ca-certificates/ 再執行 update-ca-certificates"
fi
if [ "$ROOTDOCKER" = 1 ] && [ "${TS:-0}" != 1 ] && ! is_ip "$DOMAIN"; then
line "${B}安全${N} ${Y}對外公開的網域${N}:Docker 用 root 在跑,伺服器萬一被攻破,對方等於拿到整台主機。"
note " 建議改用 rootless Docker:https://docs.docker.com/engine/security/rootless/"
fi
boot_line
line "${B}AI 金鑰${N} 第一次聊天前:AnyBot › 設定 › 模型(只存在你的雲端大腦上)"
line ""
note "看紀錄 make server-logs(大腦管理員:deploy/server/setup.sh --logs brains)"
note "更新 make update-server"
card_close
printf '\n'
exit 0
fi
line "${B}手機${N} 打開 ${A}https://$DOMAIN${N},用 ${B}$USERNAME${N} 登入,可以「加入主畫面」"
if [ -n "${LANIP:-}" ]; then
[ "$DOMAIN" != "$LANIP" ] && line "${B}區網${N} 也可以打開 ${A}https://$LANIP${N}(同一個區網)"
line "${B}信任憑證${N} 每台手機和電腦先打開 ${A}http://$LANIP/anybot-ca.crt${N} 安裝它(一次就好)"
note " iPhone:裝好描述檔後,到 設定 › 一般 › 關於本機 › 憑證信任設定 打開它"
note " Mac:在「鑰匙圈存取」把它設成「永遠信任」;Linux:放進 /usr/local/share/ca-certificates/ 再執行 update-ca-certificates"
fi
line "${B}電腦${N} 打開 AnyBot,歡迎畫面按「登入帳號」(已經在用:設定 › 一般 › 手機與帳號),"
line " 填 ${A}https://$DOMAIN${N} 和 ${B}$USERNAME${N}:登入後就用「${BRAIN}」當大腦"
if [ "$ROOTDOCKER" = 1 ] && [ "${TS:-0}" != 1 ] && ! is_ip "$DOMAIN"; then
line "${B}安全${N} ${Y}對外公開的網域${N}:Docker 用 root 在跑,大腦萬一被攻破,對方等於拿到整台主機。"
note " 建議改用 rootless Docker:https://docs.docker.com/engine/security/rootless/"
fi
boot_line
line "${B}AI 金鑰${N} 手機或電腦的 AnyBot › 設定 › 模型(只存在大腦上)"
line "${B}加一台電腦${N} 手機 AnyBot 右上 ⋯ › 加一台電腦,把那一行貼到那台的終端機"
line ""
note "看紀錄 make server-logs"
note "更新 make update-server(拉新版、重建、用 .env 重新啟動)"
note "改設定 改 deploy/server/.env 再 make update-server,或再跑一次 make server"
card_close
printf '\n'