#!/bin/sh # palaia v3 — universal one-command installer. # # curl -fsSL https://get.palaia.ai | sh # # Works on any Linux server you can log in to (Ubuntu and Debian tested), new # or already in use: it installs Docker and Tailscale only if they are missing, # joins your private network (tailnet) unless the server is on one already, and # starts the hub bound to the tailnet address only — never the public internet. # Plain POSIX sh, so `| sh` and `| bash` both work. Safe to run again: it keeps # your data and replaces only the palaia container. # # Joining the tailnet: without a key it opens a one-time setup page # (http://:8420/, protected by the code it prints, or by # PALAIA_SETUP_CODE) where you log in to Tailscale in the browser. The same page # offers cloud access: Tailscale Funnel then forwards palaia's AI-connection # endpoints, and nothing else, so ChatGPT and Claude can reach it over HTTPS. # # Options (environment variables): # PALAIA_SETUP_CODE=XXXX-XXXX-XXXX code for the setup page (else made up) # PALAIA_TSKEY_FILE=/path join with an auth key read from this file; # the file is deleted afterwards # PALAIA_CLOUD=0 do not offer cloud access (Funnel) # PALAIA_CHANNEL=stable|beta|edge image channel (default: this release's) # PALAIA_NO_TAILSCALE=1 LAN/local without Tailscale (binds 0.0.0.0) # PALAIA_TS_LOGIN_SERVER=URL a self-hosted control server (Headscale) # PALAIA_FIREWALL=on switch an inactive ufw on (SSH stays open) # A key in PALAIA_TSKEY still works but lands in your shell history; prefer # the file. The key never appears in a command line: Tailscale reads the file. set -eu # pipefail where the shell has it (bash, ksh, newer dash); plain sh carries on. # shellcheck disable=SC3040 (set -o pipefail) 2>/dev/null && set -o pipefail # rc-channel-note — this release is a release candidate, so the default image # is the `beta` channel (no `stable` image exists until 3.0.0 is final). # server/tests/test_version_drift.py keeps this line in step with v3/VERSION. DEFAULT_CHANNEL="beta" CHANNEL="${PALAIA_CHANNEL:-$DEFAULT_CHANNEL}" IMAGE="${PALAIA_IMAGE:-ghcr.io/byte5ai/palaia:${CHANNEL}}" CONTAINER_NAME="${PALAIA_CONTAINER_NAME:-palaia}" PORT="${PALAIA_INSTALL_PORT:-8420}" CLOUD_PORT="${PALAIA_CLOUD_PORT:-8422}" VOLUME="${PALAIA_VOLUME:-palaia_home}" HOSTNAME_TS="${PALAIA_TS_HOSTNAME:-palaia}" LOGIN_SERVER="${PALAIA_TS_LOGIN_SERVER:-}" CLOUD="${PALAIA_CLOUD:-1}" CLOUD_TARGET="http://127.0.0.1:${CLOUD_PORT}" log() { echo "palaia: $*"; } err() { echo "palaia: ERROR: $*" >&2; } die() { err "$@"; exit 1; } SUDO="" [ "$(id -u)" = "0" ] || SUDO="sudo" # Tailscale's own installer ends with "Log in to start using Tailscale by # running: tailscale up". Here the setup page (or the key) does that login, and # a `tailscale up` typed in the console would start one outside palaia's flow. # So its output goes to a log and reaches the screen only when it fails; a # download that fails stops here instead of piping nothing into sh (issue #616). install_tailscale() { ts_dir="$(mktemp -d)" if ! curl -fsSL https://tailscale.com/install.sh -o "${ts_dir}/install.sh"; then rm -rf "${ts_dir}" die "could not download Tailscale's installer from tailscale.com. Check the network and run this again." fi if $SUDO sh "${ts_dir}/install.sh" >"${ts_dir}/install.log" 2>&1 && command -v tailscale >/dev/null 2>&1; then rm -rf "${ts_dir}" return 0 fi err "installing Tailscale failed. Its last lines:" tail -n 20 "${ts_dir}/install.log" | sed 's/^/ /' >&2 die "fix what they name and run this again (the whole log: ${ts_dir}/install.log)." } # --- Clean-up on every exit: the key file and a temporary firewall rule ------- KEYFILE="" UFW_OPENED=0 cleanup() { if [ -n "$KEYFILE" ]; then # A secret is removed for good, never moved somewhere recoverable. # No `[ -e ]` first: run as a sudo user, /root is not searchable # without sudo, so the test would say "missing" and keep the key. $SUDO rm -f "$KEYFILE" 2>/dev/null || rm -f "$KEYFILE" 2>/dev/null || true fi if [ "$UFW_OPENED" = "1" ]; then $SUDO ufw delete allow "${PORT}/tcp" >/dev/null 2>&1 || true UFW_OPENED=0 fi } trap cleanup EXIT trap 'cleanup; exit 130' INT TERM HUP # Does an active ufw already let everyone reach PORT/tcp? Only a rule from # Anywhere on every interface counts: the tailnet-only rule a previous run # left ("on tailscale0") or a rule for one source address would keep the # setup page unreachable from the browser. ufw_allows_everyone() { $SUDO ufw status 2>/dev/null | grep -Eq "^$1(/tcp)?[[:space:]]+ALLOW( IN)?[[:space:]]+Anywhere([[:space:]]|$)" } # Port 80 of the tailnet address too, so palaia opens as http://palaia/, # without a port number (#620). Docker publishes it straight to the # container's front door: its forwarding keeps each caller's own tailnet # address, so the hub's per-device sign-in limits stay per device, and the # container needs no extra permission. Only when nothing listens there yet — # on every address (0.0.0.0, [::], *) or on the given address itself; a # listener on another single address (say 127.0.0.1:80) is no conflict. # Without an address (before the join, when the tailnet address does not # exist yet) only the every-address listeners count. port80_free() { listeners="$($SUDO ss -Hltn "sport = :80" 2>/dev/null | awk '{print $4}')" || listeners="" for listener in $listeners; do case "$listener" in "0.0.0.0:80"|"*:80"|"[::]:80") return 1 ;; esac if [ -n "$1" ] && [ "$listener" = "${1}:80" ]; then return 1 fi done return 0 } # Sets HTTP_PUBLISH (the port-80 publish, or nothing) and PORT80 (1 when # palaia answers on port 80 of the tailnet address). Never without Tailscale: # that path (BIND_ADDR 0.0.0.0) stays as it is. choose_port80() { HTTP_PUBLISH="" PORT80=0 [ "$BIND_ADDR" != "0.0.0.0" ] || return 0 if [ "$PORT" = "80" ]; then PORT80=1 elif port80_free "$BIND_ADDR"; then HTTP_PUBLISH="-p ${BIND_ADDR}:80:8420" PORT80=1 fi } # The last line: where to open palaia. On the tailnet that is a name, not a # number (#619): with MagicDNS on, the machine's tailnet name — without a port # when the hub is on port 80 there too (#620), so http://palaia/. The # setup page shows the same address on its "Done" screen. The first sign-in # fixes the address palaia issues its sign-in for, so the name is what to open # from the start. Without an answer the address stays the one in URL. report_address() { full_url="" url_note="" if [ "$BIND_ADDR" != "0.0.0.0" ]; then out="$($SUDO python3 /opt/palaia/setup-page.py address \ --port "$PORT" --port-80 "${PORT80:-0}" /dev/null)" || out="" name_url="$(printf '%s\n' "$out" | sed -n 's/^address=//p' | tail -n1)" full_url="$(printf '%s\n' "$out" | sed -n 's/^full_address=//p' | tail -n1)" url_note="$(printf '%s\n' "$out" | sed -n 's/^address_note=//p' | tail -n1)" [ -z "$name_url" ] || URL="$name_url" fi log "done ✓ Open ${URL} from any device on your tailnet to finish setup." [ -z "$full_url" ] || log " full name: ${full_url}" [ -z "$url_note" ] || log " ${url_note}" } # The key, if any, goes into a file only root can read; Tailscale reads it # from there (`--auth-key=file:`), so it is never a command-line argument. if [ -n "${PALAIA_TSKEY_FILE:-}" ]; then $SUDO test -s "$PALAIA_TSKEY_FILE" || die "PALAIA_TSKEY_FILE=${PALAIA_TSKEY_FILE} does not exist or is empty." KEYFILE="$PALAIA_TSKEY_FILE" elif [ -n "${PALAIA_TSKEY:-}" ]; then KEYFILE="$($SUDO mktemp /root/.palaia-tskey.XXXXXX 2>/dev/null || mktemp)" printf '%s' "$PALAIA_TSKEY" | $SUDO tee "$KEYFILE" >/dev/null $SUDO chmod 600 "$KEYFILE" fi unset PALAIA_TSKEY 2>/dev/null || true # Tailscale's own keys start with tskey-; a self-hosted control server # (PALAIA_TS_LOGIN_SERVER, e.g. Headscale) has its own format. if [ -n "$KEYFILE" ] && [ -z "$LOGIN_SERVER" ]; then case "$($SUDO head -c 6 "$KEYFILE")" in tskey-) : ;; *) die "that is not a Tailscale auth key (it should start with 'tskey-auth-'). You may have copied an access token — use 'Generate auth key'." ;; esac fi # --- Docker ----------------------------------------------------------------- if ! command -v docker >/dev/null 2>&1; then log "installing Docker ..." curl -fsSL https://get.docker.com | $SUDO sh fi $SUDO systemctl enable --now docker >/dev/null 2>&1 || true DOCKER="docker" docker info >/dev/null 2>&1 || DOCKER="$SUDO docker" # Is 127.0.0.1:CLOUD_PORT free, or held by this palaia's own container? cloud_port_is_ours() { if $DOCKER inspect --format '{{range .HostConfig.PortBindings}}{{range .}}{{.HostIp}}:{{.HostPort}} {{end}}{{end}}' \ "${CONTAINER_NAME}" 2>/dev/null | grep -q "127.0.0.1:${CLOUD_PORT} "; then return 0 fi ! $SUDO ss -Htln "sport = :${CLOUD_PORT}" 2>/dev/null | grep -q . } $DOCKER info >/dev/null 2>&1 || die "Docker is installed but not reachable (daemon down, or no permission)." # --- Tailscale (unless explicitly disabled) --------------------------------- BIND_ADDR="0.0.0.0" CLOUD_URL="" if [ "${PALAIA_NO_TAILSCALE:-0}" = "1" ]; then log "PALAIA_NO_TAILSCALE=1 — skipping Tailscale; the hub will bind to ${BIND_ADDR} (LAN only if you firewall it)." CLOUD=0 else if ! command -v tailscale >/dev/null 2>&1; then log "installing Tailscale ..." install_tailscale fi $SUDO systemctl enable --now tailscaled >/dev/null 2>&1 || true # After a reboot, start Docker only once tailscaled is up, so the container # usually finds its tailnet address to bind to (issue #400). tailscaled # being up does not mean the address is there, though: it needs the # control server first. When it is late, Docker's start fails ("cannot # assign requested address") and Docker never tries again — its restart # policy covers a container that exits, not one that never started, and # the failed start can leave it detached from its network. A small boot # unit waits for the address, attaches the container again and repeats # that one failed start (issue #614), without holding Docker up for other # containers. if [ -d /etc/systemd/system ]; then $SUDO mkdir -p /etc/systemd/system/docker.service.d /opt/palaia printf '[Unit]\nAfter=tailscaled.service\nWants=tailscaled.service\n' \ | $SUDO tee /etc/systemd/system/docker.service.d/palaia-after-tailscale.conf >/dev/null $SUDO tee /opt/palaia/start-on-tailnet.sh >/dev/null <<'PALAIA_START_ON_TAILNET' #!/bin/sh # palaia v3 — start the hub once its tailnet address is up (issue #614). # # Written by get-palaia.sh and run at boot by # palaia-start-on-tailnet@.service. The container publishes its # port on this server's tailnet address only. If Docker starts it before # Tailscale has that address, the start fails with "cannot assign requested # address" and Docker does not retry. This waits until every address the # container binds to exists, then repeats exactly that failed start. A running # container, one stopped on purpose, and one that failed for another reason # are left alone. set -u NAME="${1:-palaia}" INTERVAL="${PALAIA_START_INTERVAL:-5}" addresses_up() { for addr in $(docker inspect --format '{{range $p, $b := .HostConfig.PortBindings}}{{range $b}}{{.HostIp}} {{end}}{{end}}' "$NAME" 2>/dev/null); do case "$addr" in 0.0.0.0|127.*|*:*) continue ;; esac ip -4 -o addr show 2>/dev/null | grep -q " inet ${addr}/" || return 1 done return 0 } # The failed start can leave the container detached from its network (seen # with Docker 29); a plain start would then run it without its published # ports. Attach it again first. reattach() { mode="$(docker inspect --format '{{.HostConfig.NetworkMode}}' "$NAME" 2>/dev/null)" || return 0 case "$mode" in default) mode=bridge ;; ""|host|none|container:*) return 0 ;; esac docker inspect --format '{{json .NetworkSettings.Networks}}' "$NAME" 2>/dev/null | grep -q "\"${mode}\"" && return 0 docker network connect "$mode" "$NAME" >/dev/null 2>&1 || true } while :; do state="$(docker inspect --format '{{.State.Running}}|{{.State.Error}}' "$NAME" 2>/dev/null)" || exit 0 case "$state" in "true|"*) exit 0 ;; esac if addresses_up; then case "$state" in *"cannot assign requested address"*) reattach if docker start "$NAME" >/dev/null 2>&1; then echo "started ${NAME}: its tailnet address is up" exit 0 fi ;; *) exit 0 ;; esac fi sleep "$INTERVAL" done PALAIA_START_ON_TAILNET $SUDO chmod 755 /opt/palaia/start-on-tailnet.sh printf '%s\n' '[Unit]' \ 'Description=Start palaia (%i) once its tailnet address is up' \ 'After=docker.service tailscaled.service' \ 'Wants=docker.service' \ '' '[Service]' \ 'Type=simple' \ 'ExecStart=/bin/sh /opt/palaia/start-on-tailnet.sh %i' \ '' '[Install]' \ 'WantedBy=multi-user.target' \ | $SUDO tee /etc/systemd/system/palaia-start-on-tailnet@.service >/dev/null $SUDO systemctl daemon-reload >/dev/null 2>&1 || true $SUDO systemctl enable "palaia-start-on-tailnet@${CONTAINER_NAME}.service" >/dev/null 2>&1 || true fi # The setup page is needed for a fresh join, and for cloud access too. if ! command -v python3 >/dev/null 2>&1; then log "installing python3 for the setup page ..." $SUDO apt-get install -y python3 >/dev/null 2>&1 || die "python3 is needed for the setup page. Install it, or pass PALAIA_TSKEY_FILE=... instead." fi $SUDO mkdir -p /opt/palaia $SUDO tee /opt/palaia/setup-page.py >/dev/null <<'PALAIA_SETUP_PAGE' #!/usr/bin/env python3 # palaia v3 — one-time setup page (SPEC-605). # # Joins this server to the owner's Tailscale network without anyone handling # a key: it starts `tailscale up` without an auth key, takes the login link # Tailscale prints, and shows it on a small web page — but only to someone # who enters the one-time setup code. The person opens # http://:8420/, types the code, clicks "Connect with # Tailscale" and logs in. # # Once the server is on the tailnet, the same page offers cloud access # (--cloud-target): Tailscale Funnel then forwards palaia's cloud entry — the # AI-connection endpoints only, never the dashboard — so ChatGPT and Claude # can reach it over HTTPS. If the tailnet has not allowed Funnel yet, the page # shows Tailscale's own "allow" link; "Keep it private" skips the step. # # Exit status: 0 once the server is on the tailnet (cloud access on or not), # 1 on timeout (default 30 minutes) or when Tailscale fails. Either way the # port is closed again the moment it exits; the installer then starts the hub # bound to the private-network address only. # # `setup-page.py cloud --target URL` runs only the cloud step, without a page: # it prints Tailscale's link if one is needed, waits, and ends with a line # `cloud_url=https://...` (exit 0) or `cloud_url=` (exit 3: not set up); # `--check-only` just reports. # # palaia's private address is a name, not a number (issues #619, #620): with # MagicDNS on, the machine's tailnet name — and no port number when the # installer also publishes the hub on port 80 of the tailnet address, which it # does only when port 80 is free there (`--port-80 1`). So `http://palaia/`. # `setup-page.py address --port N --port-80 0|1` prints `address=`, # `full_address=` and `address_note=` lines; the "Done" screen shows the same # address. Nothing here changes Tailscale's settings. # # Standard library only — python3 is on every image that runs cloud-init. # The code comes from the PALAIA_SETUP_CODE environment variable, not the # command line, so it never shows up in a process list. Without one, a fresh # code is made up and printed together with the address to open. # # This file is the single source: get-palaia.sh embeds it verbatim (checked # by server/tests/deploy/test_setup_page.py). import argparse import hmac import html import json import os import re import secrets import signal import socket import subprocess import sys import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import parse_qs, urlparse LINK_RE = re.compile(r"https?://\S+") WRONG_CODE_DELAY = 1.0 MAX_CLIENTS = 32 # concurrent connections; more are dropped, not queued CLIENT_TIMEOUT = 10 # seconds a connection may take to send its request CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # no 0/O, 1/I look-alikes FUNNEL_PORTS = (443, 8443, 10000) # the only HTTPS ports Funnel offers NO_MAGICDNS_NOTE = ( "Your Tailscale network has MagicDNS turned off, so palaia has no name there " "and is opened by its number; turn MagicDNS on under DNS in Tailscale's admin " "console to open it by name." ) PORT_80_BUSY_NOTE = ( "Port 80 on this server's tailnet address is already used by another program, " "so palaia keeps its port number." ) def log(message): # stderr: in `cloud` mode stdout carries only the result line. print(f"palaia setup page: {message}", file=sys.stderr, flush=True) def normalise(code): """Codes are compared without case, spaces or dashes.""" return re.sub(r"[\s-]", "", code or "").upper() def new_code(): raw = "".join(secrets.choice(CODE_ALPHABET) for _ in range(12)) return f"{raw[:4]}-{raw[4:8]}-{raw[8:]}" def public_address(): """The address this server reaches the internet from — no packet is sent.""" try: with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: sock.connect(("1.1.1.1", 80)) return sock.getsockname()[0] except OSError: return "" def tailscale_json(*args): try: out = subprocess.run( ["tailscale", *args, "--json"], capture_output=True, text=True, timeout=15, check=False ) return json.loads(out.stdout) if out.returncode == 0 and out.stdout.strip() else {} except (OSError, subprocess.TimeoutExpired, ValueError): return {} def tailnet_ip(): try: out = subprocess.run( ["tailscale", "ip", "-4"], capture_output=True, text=True, timeout=10, check=False ) except (OSError, subprocess.TimeoutExpired): return None first = out.stdout.strip().splitlines()[:1] return first[0] if out.returncode == 0 and first else None # --- cloud access (Tailscale Funnel) ------------------------------------------- def dns_name(): """This machine's tailnet name, e.g. palaia.tail1234.ts.net.""" return str((tailscale_json("status").get("Self") or {}).get("DNSName") or "").rstrip(".") def _proxies(web_entry): handlers = (web_entry or {}).get("Handlers") or {} return {str(h.get("Proxy") or "") for h in handlers.values() if isinstance(h, dict)} def funnel_url(target): """The public https URL Funnel already serves `target` at, or None.""" name = dns_name() config = tailscale_json("serve", "status") for port in FUNNEL_PORTS: key = f"{name}:{port}" on = (config.get("AllowFunnel") or {}).get(key) if name and on and _proxies((config.get("Web") or {}).get(key)) == {target}: return f"https://{name}" + ("" if port == 443 else f":{port}") return None def free_funnel_port(target): """A Funnel port that is unused, or already serves `target`; None if all are taken. A port another service of this machine already uses is never touched. """ name = dns_name() if not name: return None config = tailscale_json("serve", "status") for port in FUNNEL_PORTS: web = (config.get("Web") or {}).get(f"{name}:{port}") tcp = (config.get("TCP") or {}).get(str(port)) if web is None and tcp is None: return port if web is not None and _proxies(web) == {target}: return port return None class Cloud: """Turns on Funnel for `target` and remembers what happened.""" def __init__(self, target): self.target = target self.link = None self.text = [] self.url = None self.result = None # "on", "skipped" or a reason it is off self.proc = None def run(self, wait): self.url = funnel_url(self.target) if self.url: self.result = "on" return port = free_funnel_port(self.target) if port is None: self.result = "this machine's Tailscale HTTPS ports are already in use" return cmd = ["tailscale", "funnel", "--bg", "--yes", f"--https={port}", self.target] try: self.proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True ) except OSError as exc: self.result = f"could not start tailscale: {exc}" return timer = threading.Timer(wait, self.stop) timer.daemon = True timer.start() for line in self.proc.stdout: line = line.strip() match = LINK_RE.search(line) # Tailscale asks the owner to allow HTTPS or Funnel for the tailnet # with a login.tailscale.com/f/... link and waits; other links in # its output point at documentation. if match and "/f/" in match.group(0): self.link = match.group(0) log(f"Tailscale asks to allow cloud access: {self.link}") elif line: self.text.append(line) self.proc.wait() timer.cancel() if self.result == "skipped": return self.url = funnel_url(self.target) if self.url: self.result = "on" elif self.result is None: self.result = " ".join(self.text[-3:]) or "Tailscale did not turn on Funnel" def stop(self): if self.result is None: self.result = "nobody allowed cloud access in time" if self.proc and self.proc.poll() is None: self.proc.terminate() def skip(self): self.result = "skipped" if self.proc and self.proc.poll() is None: self.proc.terminate() # --- the private address (MagicDNS name) --------------------------------------- def tailnet_name(): """(short, full) MagicDNS name of this machine, e.g. ("palaia", "palaia.tail1234.ts.net"); None when the tailnet has MagicDNS off. The short name comes from the name Tailscale gave the machine, which is `palaia-1` when another machine already has `palaia`. """ status = tailscale_json("status") full = str((status.get("Self") or {}).get("DNSName") or "").rstrip(".") if not full or not (status.get("CurrentTailnet") or {}).get("MagicDNSEnabled"): return None return full.split(".", 1)[0], full def private_address(hub_port, port_80): """Where palaia opens on the tailnet: (address, full address, note). `http://palaia/` when the installer publishes the hub on port 80 of the tailnet address too (`port_80`), `http://palaia:/` when port 80 is taken there, and the tailnet IP with the port when MagicDNS is off. """ names = tailnet_name() if names is None: ip = tailnet_ip() or "" return f"http://{ip}:{hub_port}/", "", NO_MAGICDNS_NOTE short, full = names if port_80: return f"http://{short}/", f"http://{full}/", "" return f"http://{short}:{hub_port}/", f"http://{full}:{hub_port}/", PORT_80_BUSY_NOTE def address_main(args): address, full, note = private_address(args.port, args.port_80) log(f"palaia's private address: {address}") print(f"address={address}", flush=True) print(f"full_address={full}", flush=True) print(f"address_note={note}", flush=True) return 0 def cloud_main(args): cloud = Cloud(args.target) if args.check_only: cloud.url = funnel_url(args.target) cloud.result = "on" if cloud.url else "not set up" else: cloud.run(args.wait) if cloud.url: print(f"cloud_url={cloud.url}", flush=True) return 0 log(f"cloud access is not set up: {str(cloud.result).rstrip('.')}.") print("cloud_url=", flush=True) return 3 # --- the page ------------------------------------------------------------------ class State: def __init__(self, code, port): self.code = normalise(code) self.port = port self.login_url = None self.ip = None self.address = None # (address, full address, note) once joined self.failed = None self.proc = None self.cloud = None # a Cloud while the cloud step runs self.finished = threading.Event() self.lock = threading.Lock() def code_ok(self, given): return hmac.compare_digest(normalise(given).encode(), self.code.encode()) def run_tailscale(state, hostname, login_server): """`tailscale up` without a key prints a login link and waits for the login.""" cmd = ["tailscale", "up", f"--hostname={hostname}"] if login_server: cmd.append(f"--login-server={login_server}") try: state.proc = proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, ) except OSError as exc: state.failed = f"could not start tailscale: {exc}" return for line in proc.stdout: match = LINK_RE.search(line) if match and state.login_url is None: with state.lock: state.login_url = match.group(0) log("login link ready — waiting for the code on the setup page.") if proc.wait() != 0 and tailnet_ip() is None: state.failed = "tailscale up ended without joining (see the lines above)." # The design system's colours (v3/design/tokens.json), carried inline: this # page runs on the bare server before palaia exists and loads nothing. COLORS = { "canvas": ("#F5F7FA", "#0F1520"), "surface": ("#FFFFFF", "#161D2A"), "surface-muted": ("#EEF1F5", "#1C2433"), "border": ("#E3E7ED", "#263043"), "text": ("#1D232C", "#E8ECF1"), "text-2": ("#4B5563", "#AEB6C2"), "brand": ("#009FE3", "#009FE3"), "action": ("#0369A1", "#38BDF8"), "action-hover": ("#04618F", "#7DD3FC"), "on-action": ("#FFFFFF", "#0A0F1A"), "focus": ("#0369A1", "#009FE3"), "ok": ("#157A3A", "#4ADE80"), "error": ("#B91C1C", "#F87171"), } LIGHT = "".join(f"--{name}: {light};" for name, (light, _) in COLORS.items()) DARK = "".join(f"--{name}: {dark};" for name, (_, dark) in COLORS.items()) MARK = ( '' ) PAGE = ( ( """ palaia setup
""" + MARK + """palaia
{body}
""" ) .replace("@LIGHT@", LIGHT) .replace("@DARK@", DARK) ) def steps(active): names = ("Code", "Private network", "Cloud access", "Done") marks = (f'{n}' for i, n in enumerate(names)) return '
' + "".join(marks) + "
" def code_form(error=""): hint = f'' if error else "" return ( steps(0) + "

Set up palaia

" "

Enter the setup code you were given.

" f"{hint}" '
' '
' "
" ) def poll_script(code, shown): """Reload once the phase differs from the one this page shows — also when it changed between rendering and the first poll.""" status_url = "/status?code=" + html.escape(normalise(code)) return ( f'" ) def phase(state): if state.failed: return "failed" if not state.ip: return "join" if state.login_url else "preparing" if state.cloud is not None and state.cloud.result is None: return "cloud-link" if state.cloud.link else "cloud-check" return "done" def connect_body(state, code): current = phase(state) safe_code = html.escape(normalise(code)) if current == "failed": return steps(1) + f'

Something went wrong: {html.escape(state.failed)}

' if current == "preparing": return ( steps(1) + "

Preparing the connection

This takes a few seconds.

" + poll_script(code, current) ) if current == "join": return ( steps(1) + "

Connect this server to your private network

" "

Log in with the Tailscale account you use on your own devices. " "Your devices and this server then reach each other privately.

" f'' '

This page moves on by itself once you have logged in.

' + poll_script(code, current) ) if current == "cloud-check": return ( steps(2) + "

Setting up cloud access

This takes a few seconds.

" + poll_script(code, current) ) if current == "cloud-link": return ( steps(2) + "

Let ChatGPT and Claude reach palaia

" "

Cloud AI apps connect from the internet. Tailscale can forward " "only palaia's AI connection to this server over HTTPS; " "the dashboard stays on your private network. Each app still has to sign in.

" "

Your Tailscale network has not allowed this yet. Open the link, " "allow it, then come back.

" f'
Allow in Tailscale' f'
' '
' '

You can turn cloud access on later.

' + poll_script(code, current) ) return done_body(state) def done_body(state): url, full, note = state.address or (f"http://{state.ip}:{state.port}/", "", "") cloud = state.cloud if cloud is None: cloud_line = "" elif cloud.url: cloud_line = ( '

Cloud access is ready at ' f"{html.escape(cloud.url)} — you finish it in palaia.

" ) elif cloud.result == "skipped": cloud_line = '

Cloud access is off. You can turn it on later.

' else: cloud_line = ( f'

Cloud access is off ({html.escape(cloud.result or "")}). ' "You can turn it on later.

" ) return ( steps(3) + "

Done

This server is now on your private network.

" f"{cloud_line}" f'

In a minute or two, palaia opens at ' f"{html.escape(url)} on any device with the Tailscale app turned on.

" + (f'

Full name: {html.escape(full)}

' if full else "") + (f'

{html.escape(note)}

' if note else "") + '

This setup page closes itself now.

' ) class BoundedServer(ThreadingHTTPServer): """One thread per connection, but never more than MAX_CLIENTS at once.""" daemon_threads = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.slots = threading.BoundedSemaphore(MAX_CLIENTS) def process_request(self, request, client_address): if not self.slots.acquire(blocking=False): self.shutdown_request(request) return try: super().process_request(request, client_address) except Exception: self.slots.release() raise def process_request_thread(self, request, client_address): try: super().process_request_thread(request, client_address) finally: self.slots.release() def make_handler(state): class Handler(BaseHTTPRequestHandler): timeout = CLIENT_TIMEOUT def log_message(self, *args): pass def send(self, status, body, ctype="text/html; charset=utf-8", location=None): data = body.encode() self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(data))) self.send_header("Cache-Control", "no-store") self.send_header("Referrer-Policy", "no-referrer") self.send_header("X-Frame-Options", "DENY") if location: self.send_header("Location", location) self.end_headers() self.wfile.write(data) def checked(self): parsed = urlparse(self.path) code = parse_qs(parsed.query).get("code", [""])[0] if state.code_ok(code): return parsed.path, code time.sleep(WRONG_CODE_DELAY) if parsed.path == "/status": self.send(403, json.dumps({"joined": False}), "application/json") else: self.send(403, PAGE.format(body=code_form("That code is not right."))) return None, None def do_GET(self): path = urlparse(self.path).path if path == "/": return self.send(200, PAGE.format(body=code_form())) if path not in ("/connect", "/status"): return self.send(404, PAGE.format(body="

Not found.

")) path, code = self.checked() if path == "/status": answer = {"joined": bool(state.ip), "phase": phase(state)} return self.send(200, json.dumps(answer), "application/json") if path == "/connect": return self.send(200, PAGE.format(body=connect_body(state, code))) return None def do_POST(self): if urlparse(self.path).path != "/skip": return self.send(404, PAGE.format(body="

Not found.

")) path, code = self.checked() if path is None: return None if state.cloud is not None: state.cloud.skip() return self.send(303, "", location=f"/connect?code={normalise(code)}") return Handler def page_main(args): code = os.environ.get("PALAIA_SETUP_CODE", "").strip() or new_code() if len(normalise(code)) < 8: log("ERROR: PALAIA_SETUP_CODE is shorter than 8 characters.") return 2 state = State(code, args.hub_port) if tailnet_ip(): log("this server is already on a tailnet — nothing to set up.") return 0 # A plain `kill` (SIGTERM) or a closed terminal (SIGHUP) must still run the # clean-up below, not leave the page or a pending login behind. def stop(signum, _frame): raise SystemExit(128 + signum) signal.signal(signal.SIGTERM, stop) signal.signal(signal.SIGHUP, stop) server = BoundedServer((args.bind, args.port), make_handler(state)) threading.Thread(target=server.serve_forever, daemon=True).start() threading.Thread( target=run_tailscale, args=(state, args.hostname, args.login_server), daemon=True ).start() print( "\n" " ============================================================\n" f" Open http://{public_address()}:{args.port}/\n" f" Code {code}\n" " Then click 'Connect with Tailscale' and log in.\n" " ============================================================\n", flush=True, ) deadline = time.monotonic() + args.timeout try: while time.monotonic() < deadline and not state.failed: ip = tailnet_ip() if ip: # The address first: setting state.ip shows "Done", and that # screen must name palaia's address, not just its number. state.address = private_address(args.hub_port, args.port_80) state.ip = ip log(f"joined the tailnet as {ip}; palaia's address: {state.address[0]}") if args.cloud_target: state.cloud = Cloud(args.cloud_target) state.cloud.run(max(1, int(deadline - time.monotonic()))) log(f"cloud access: {state.cloud.url or state.cloud.result}.") time.sleep(args.linger) return 0 time.sleep(2) finally: server.shutdown() server.server_close() if state.cloud is not None and state.cloud.proc and state.cloud.proc.poll() is None: state.cloud.proc.terminate() if state.proc and state.proc.poll() is None: state.proc.terminate() try: state.proc.wait(timeout=10) except subprocess.TimeoutExpired: state.proc.kill() if not state.ip: # Drop the pending login, so the link can no longer be used by # anyone to pull this server into their network. try: subprocess.run( ["tailscale", "logout"], capture_output=True, timeout=30, check=False ) except (OSError, subprocess.TimeoutExpired): log("could not reset the pending Tailscale login — run 'tailscale logout'.") log(f"ERROR: {state.failed or 'nobody completed the setup page in time'} — the page is closed.") return 1 def main(argv=None): argv = list(sys.argv[1:] if argv is None else argv) if argv[:1] == ["cloud"]: parser = argparse.ArgumentParser(description="Turn on cloud access (Tailscale Funnel).") parser.add_argument("--target", required=True, help="e.g. http://127.0.0.1:8422") parser.add_argument("--wait", type=int, default=600, help="seconds to wait for approval") parser.add_argument("--check-only", action="store_true", help="only report, change nothing") return cloud_main(parser.parse_args(argv[1:])) port_80_help = "1 when the hub is also published on port 80 of the tailnet address" if argv[:1] == ["address"]: parser = argparse.ArgumentParser(description="Print palaia's private address.") parser.add_argument("--port", type=int, default=8420, help="where palaia answers") parser.add_argument("--port-80", type=int, choices=(0, 1), default=0, help=port_80_help) return address_main(parser.parse_args(argv[1:])) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--port", type=int, default=8420, help="where this page listens") parser.add_argument("--hub-port", type=int, default=8420, help="where palaia will answer") parser.add_argument("--port-80", type=int, choices=(0, 1), default=0, help=port_80_help) parser.add_argument("--bind", default="0.0.0.0") parser.add_argument("--hostname", default="palaia") parser.add_argument("--login-server", default="", help="a self-hosted control server") parser.add_argument("--cloud-target", default="", help="offer cloud access for this URL") parser.add_argument("--timeout", type=int, default=1800, help="seconds") parser.add_argument("--linger", type=int, default=30, help="seconds to show 'done'") return page_main(parser.parse_args(argv)) if __name__ == "__main__": sys.exit(main()) PALAIA_SETUP_PAGE $SUDO chmod 700 /opt/palaia/setup-page.py LOGIN_ARG="" [ -z "$LOGIN_SERVER" ] || LOGIN_ARG="--login-server=${LOGIN_SERVER}" # Cloud access points Tailscale Funnel at 127.0.0.1:CLOUD_PORT before the # hub runs. If another program already listens there (and it is not this # palaia's own container, on a re-install), Funnel would publish that # program instead — so cloud access is skipped. if [ "$CLOUD" != "0" ] && ! cloud_port_is_ours; then log "cloud access skipped: 127.0.0.1:${CLOUD_PORT} is used by another program." log " Free it, or set PALAIA_CLOUD_PORT to a free port, and run this again." CLOUD=0 fi CLOUD_ARG="" [ "$CLOUD" = "0" ] || CLOUD_ARG="--cloud-target=${CLOUD_TARGET}" if $SUDO tailscale ip -4 >/dev/null 2>&1; then log "already on a tailnet, skipping the join." elif [ -n "$KEYFILE" ]; then log "joining the tailnet with your auth key ..." # shellcheck disable=SC2086 if ! $SUDO tailscale up --auth-key="file:${KEYFILE}" --hostname="$HOSTNAME_TS" $LOGIN_ARG; then die "Tailscale rejected the key. It is likely expired, already used (non-reusable), or an access token rather than an auth key. Generate a fresh auth key and run this again." fi else # SPEC-605: no key — a one-time setup page in the browser joins the # tailnet (code-protected, closes itself afterwards). Open the port # for it only if ufw is on and does not allow it already, and remove # only the rule this run added, also when the run is interrupted. if command -v ufw >/dev/null 2>&1 && $SUDO ufw status 2>/dev/null | grep -q "Status: active" \ && ! ufw_allows_everyone "$PORT"; then $SUDO ufw allow "${PORT}/tcp" comment 'palaia setup page, temporary' >/dev/null && UFW_OPENED=1 fi log "starting the setup page (closes itself after 30 minutes) ..." # The code travels in the environment, never as a command argument. # stdin is detached: when this script arrives through `| sh`, its own # text is what stdin carries. export PALAIA_SETUP_CODE="${PALAIA_SETUP_CODE:-}" # Its "Done" screen names palaia's address, without a port when the # hub will be on port 80 too. The tailnet address does not exist yet, # so only a listener on every address can take port 80 now; the # installer checks again before it starts the hub. PAGE_PORT80=0 if [ "$PORT" = "80" ] || port80_free ""; then PAGE_PORT80=1 fi SETUP_OK=1 # shellcheck disable=SC2086 if [ -n "$SUDO" ]; then $SUDO --preserve-env=PALAIA_SETUP_CODE python3 /opt/palaia/setup-page.py \ --port "$PORT" --hub-port "$PORT" --port-80 "$PAGE_PORT80" --hostname "$HOSTNAME_TS" $LOGIN_ARG $CLOUD_ARG /dev/null 2>&1; then if $SUDO ufw status 2>/dev/null | grep -q "Status: active" || [ "${PALAIA_FIREWALL:-}" = "on" ]; then $SUDO ufw allow OpenSSH >/dev/null 2>&1 || true for ssh_port in $($SUDO ss -tlnpH 2>/dev/null | grep '"sshd"' | awk '{print $4}' | sed 's/.*://' | sort -u); do $SUDO ufw allow "${ssh_port}/tcp" comment 'ssh' >/dev/null 2>&1 || true done $SUDO ufw allow in on tailscale0 to any port "${PORT}" proto tcp comment 'palaia hub, tailnet only' >/dev/null 2>&1 || true $SUDO ufw --force enable >/dev/null 2>&1 || true log "ufw: ${PORT}/tcp on tailscale0 only." fi fi fi # --- Image ------------------------------------------------------------------ log "pulling ${IMAGE} ..." if ! $DOCKER pull "${IMAGE}"; then die "could not pull ${IMAGE}. Check the channel (PALAIA_CHANNEL) and your network." fi DIGEST="$($DOCKER image inspect --format '{{range .RepoDigests}}{{println .}}{{end}}' "${IMAGE}" 2>/dev/null | head -n1)" # --- Container -------------------------------------------------------------- if $DOCKER inspect "${CONTAINER_NAME}" >/dev/null 2>&1; then # Keep the data the existing container uses: a volume or folder chosen # with PALAIA_VOLUME on the first run must not be swapped for an empty # default one on a re-run without it. CURRENT_DATA="$($DOCKER inspect --format '{{range .Mounts}}{{if eq .Destination "/data"}}{{if eq .Type "volume"}}{{.Name}}{{else}}{{.Source}}{{end}}{{end}}{{end}}' "${CONTAINER_NAME}" 2>/dev/null || true)" if [ -n "$CURRENT_DATA" ] && [ "$CURRENT_DATA" != "$VOLUME" ]; then if [ -n "${PALAIA_VOLUME:-}" ]; then die "'${CONTAINER_NAME}' keeps its data in '${CURRENT_DATA}', not in '${VOLUME}' (PALAIA_VOLUME). Run this again without PALAIA_VOLUME to keep that data, or remove the container first if you really want a different one." fi VOLUME="$CURRENT_DATA" fi log "a container named '${CONTAINER_NAME}' exists — replacing it (your data in '${VOLUME}' is untouched)." $DOCKER rm -f "${CONTAINER_NAME}" >/dev/null fi # Two loopback ports for a tunnel on this server (they are not reachable from # outside it): the cloud entry, which answers only the AI-connection routes, # and the whole hub, for the explicit "open" mode. LOOPBACK_PUBLISH="" if [ "$BIND_ADDR" != "0.0.0.0" ]; then LOOPBACK_PUBLISH="-p 127.0.0.1:${PORT}:8420" fi # Port 80 of the tailnet address as well, when it is free (#620). Checked only # now: a previous palaia container held it, and that one is gone above. choose_port80 run_hub() { # shellcheck disable=SC2086 $DOCKER run -d \ --name "${CONTAINER_NAME}" \ -p "${BIND_ADDR}:${PORT}:8420" \ $HTTP_PUBLISH \ $LOOPBACK_PUBLISH \ -p "127.0.0.1:${CLOUD_PORT}:8422" \ -e PALAIA_CLOUD_URL_HINT="${CLOUD_URL}" \ -e PALAIA_CLOUD_HOST_PORT="${CLOUD_PORT}" \ -e PALAIA_HUB_HOST_PORT="${PORT}" \ -e PALAIA_SELF_RESTART=1 \ -v "${VOLUME}:/data" \ --restart unless-stopped \ --security-opt no-new-privileges:true \ --cap-drop ALL \ --read-only \ --tmpfs /tmp \ --tmpfs /run \ "${IMAGE}" >/dev/null } # Starts the hub. When port 80 turns out to be taken after all (something # grabbed it since the check), once more without it rather than failing the # install: palaia then keeps its port number. Any other failure stops here, # with Docker's own message. start_hub() { start_err="$(mktemp)" if run_hub 2>"$start_err"; then rm -f "$start_err" return 0 fi if [ -n "$HTTP_PUBLISH" ] \ && grep -Eq "$(printf '%s' "$BIND_ADDR" | sed 's/[.]/[.]/g'):80([^0-9]|\$)" "$start_err"; then log "port 80 on ${BIND_ADDR} is taken after all — starting palaia with its port number only." $DOCKER rm -f "${CONTAINER_NAME}" >/dev/null 2>&1 || true HTTP_PUBLISH="" PORT80=0 if run_hub 2>"$start_err"; then rm -f "$start_err" return 0 fi fi cat "$start_err" >&2 rm -f "$start_err" return 1 } log "starting ${CONTAINER_NAME} on ${BIND_ADDR}:${PORT}${HTTP_PUBLISH:+ and ${BIND_ADDR}:80} ..." start_hub || die "could not start ${CONTAINER_NAME} (Docker's message is above). Run this again; your data is kept." # --- Each tailnet device keeps its own address (issue #621) ----------------- # Docker forwards the ports published on the tailnet address into the # container. Tailscale marks every packet it forwards from tailscale0 and # masquerades marked packets on the way out (its subnet-router SNAT, on by # default). Its rule decides only when it comes before Docker's in the # forward chain — after every restart or update of tailscaled — but then the # hub sees every device as the Docker bridge's address, and the limit on # failed sign-ins (SPEC-502) counts all of them together. A rule in a table of # palaia's own clears that mark for palaia's published ports only, after # Tailscale set it and before its masquerade. Tailscale's settings and # everything else it forwards stay as they are (an exit node or subnet routes # still need its SNAT). The mark is Tailscale's subnet-route mark, 0x40000 in # the byte 0xff0000 it claims (tsconst.LinuxSubnetRouteMark). SOURCE_TABLE="ip palaia_source_${CONTAINER_NAME}" SOURCE_RULES="/opt/palaia/tailnet-source-${CONTAINER_NAME}.nft" SOURCE_UNIT="palaia-tailnet-source@${CONTAINER_NAME}.service" SOURCE_UNIT_FILE="/etc/systemd/system/palaia-tailnet-source@.service" # The ruleset: palaia's published ports on the tailnet address, port 80 only # when palaia has it. Loading it again replaces the table in one transaction. tailnet_source_rules() { ports="$PORT" [ -z "$HTTP_PUBLISH" ] || ports="${PORT}, 80" printf '%s\n' \ '# palaia v3 — each tailnet device keeps its own address (issue #621).' \ '#' \ "# Written by get-palaia.sh and loaded at boot by ${SOURCE_UNIT}." \ "# Tailscale masquerades the packets it forwards from tailscale0, so palaia's" \ "# container would see every device as the Docker bridge's address. This" \ "# clears Tailscale's mark for palaia's published ports (${ports} on" \ "# ${BIND_ADDR}) only, before its masquerade. Running get-palaia.sh again" \ '# rewrites this file.' \ "table ${SOURCE_TABLE}" \ "delete table ${SOURCE_TABLE}" \ "table ${SOURCE_TABLE} {" \ ' chain forward {' \ ' type filter hook forward priority filter + 10; policy accept;' \ " iifname \"tailscale0\" ct status dnat ct original ip daddr ${BIND_ADDR} ct original proto-dst { ${ports} } meta mark & 0x00ff0000 == 0x00040000 meta mark set meta mark & 0xff00ffff" \ ' }' \ '}' } # The boot unit, one instance per container; $1 is the nft binary. tailnet_source_unit() { printf '%s\n' '[Unit]' \ 'Description=palaia (%i): tailnet devices keep their own address' \ 'Documentation=https://github.com/byte5ai/palaia/issues/621' \ '' '[Service]' \ 'Type=oneshot' \ 'RemainAfterExit=yes' \ "ExecStart=$1 -f $(dirname "$SOURCE_RULES")/tailnet-source-%i.nft" \ "ExecStop=$1 delete table ip palaia_source_%i" \ '' '[Install]' \ 'WantedBy=multi-user.target' } keep_tailnet_source() { if [ "$BIND_ADDR" = "0.0.0.0" ]; then # Not on the tailnet (any more): a rule from an earlier install goes. if $SUDO test -f "$SOURCE_RULES"; then $SUDO systemctl disable --now "$SOURCE_UNIT" >/dev/null 2>&1 || true $SUDO nft delete table $SOURCE_TABLE >/dev/null 2>&1 || true $SUDO rm -f "$SOURCE_RULES" fi return 0 fi nft_bin="$($SUDO sh -c 'command -v nft' 2>/dev/null)" || nft_bin="" if [ -z "$nft_bin" ]; then log "installing nftables ..." $SUDO apt-get install -y nftables >/dev/null 2>&1 || true nft_bin="$($SUDO sh -c 'command -v nft' 2>/dev/null)" || nft_bin="" fi if [ -z "$nft_bin" ]; then log "WARNING: nft is not available, so after a restart of Tailscale palaia can see every tailnet device under one address, and the limit on failed sign-ins then counts them together. Install nftables and run this again." return 0 fi $SUDO mkdir -p "$(dirname "$SOURCE_RULES")" tailnet_source_rules | $SUDO tee "$SOURCE_RULES" >/dev/null if [ -d "$(dirname "$SOURCE_UNIT_FILE")" ]; then tailnet_source_unit "$nft_bin" | $SUDO tee "$SOURCE_UNIT_FILE" >/dev/null $SUDO systemctl daemon-reload >/dev/null 2>&1 || true $SUDO systemctl enable "$SOURCE_UNIT" >/dev/null 2>&1 || true # restart, not start: a re-run must load the rewritten file. if $SUDO systemctl restart "$SOURCE_UNIT" >/dev/null 2>&1; then return 0 fi elif $SUDO "$nft_bin" -f "$SOURCE_RULES" >/dev/null 2>&1; then return 0 fi log "WARNING: could not load ${SOURCE_RULES} (journalctl -u ${SOURCE_UNIT} shows why), so after a restart of Tailscale palaia can see every tailnet device under one address." } keep_tailnet_source # --- Readiness -------------------------------------------------------------- # The dashboard's static page answers even when the hub behind it does not, # so success means the hub's own health check answers through the container's # front door (issue #568) — and the container is not restarting in a loop. HOST_FOR_CHECK="$BIND_ADDR" [ "$HOST_FOR_CHECK" != "0.0.0.0" ] || HOST_FOR_CHECK="127.0.0.1" URL="http://${BIND_ADDR}:${PORT}/" [ "$BIND_ADDR" != "0.0.0.0" ] || URL="http://:${PORT}/" log "waiting for the hub to be ready ..." ok=0 i=0 while [ "$i" -lt 120 ]; do i=$((i + 1)) if curl -fsS --max-time 3 "http://${HOST_FOR_CHECK}:${PORT}/api/health" 2>/dev/null | grep -q '"status":"ok"'; then ok=1 break fi # A hub that exits (a configuration it refuses, say) makes the container # stop or restart; waiting longer would only hide that. # shellcheck disable=SC2046 set -- $($DOCKER inspect --format '{{.State.Status}} {{.RestartCount}}' "${CONTAINER_NAME}" 2>/dev/null || echo missing 0) case "$1" in exited|dead|missing) break ;; esac [ "${2:-0}" -ge 1 ] && break sleep 1 done echo "" if [ "$ok" != "1" ]; then err "the hub did not become ready (its health check never answered)." err "Its last log lines:" $DOCKER logs --tail 20 "${CONTAINER_NAME}" 2>&1 | sed 's/^/ /' >&2 || true err "Fix what they name and run this again; your data is kept." exit 1 fi log "image ${DIGEST:-$IMAGE}" report_address