Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Harness OS: set an encrypted computer up from a phone in one stay on its startup hotspot (#1446)

Bubu-Dudu-52hz9f6ca1b3c30a
diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.ts
index 867d4a39a..c55059475 100644
--- a/cli/src/lib/terminalStreamManager.spec.ts
+++ b/cli/src/lib/terminalStreamManager.spec.ts
@@ -927,6 +927,39 @@ describe('TerminalStreamManager', () => {
expect(ready?.payload).not.toHaveProperty('heldBy')
})
+ // A phone set a Harness OS computer up and opened its OpenCode, taking it at the phone's size; the
+ // computer's screen watched. When the phone left, nothing told the screen, and OpenCode stayed
+ // phone-sized in a corner of the screen until someone typed there (2026-10-18).
+ it('tells the watchers when the controller leaves, not when it hands over', async () => {
+ await manager.handleFrame('screen-1', 'terminal_open', {
+ requestId: 'open-1', protocolVersion: 3, agentId: 'agent-1', cols: 211, rows: 57,
+ })
+ await manager.handleFrame('phone-1', 'terminal_open', {
+ requestId: 'open-2', protocolVersion: 3, agentId: 'agent-1', cols: 45, rows: 30,
+ })
+ await manager.handleFrame('screen-1', 'terminal_open', {
+ requestId: 'open-3', protocolVersion: 3, agentId: 'agent-1', cols: 211, rows: 57, takeover: false,
+ })
+ const ready = (connId: string) => sent.findLast((frame) => frame.connId === connId && frame.type === 'terminal_ready')
+ const watching = ready('screen-1')?.payload.streamId
+ expect(ready('screen-1')?.payload.readOnly).toBe(true)
+ const free = () => sent.filter((frame) => frame.type === 'terminal_free')
+ expect(free()).toHaveLength(0)
+
+ await manager.handleFrame('phone-1', 'terminal_close', { streamId: ready('phone-1')?.payload.streamId })
+ expect(free().map((frame) => [frame.connId, frame.payload.streamId])).toEqual([['screen-1', watching]])
+
+ // Taken by another view instead: that one has it, and nobody is told it is free.
+ sent.length = 0
+ await manager.handleFrame('phone-1', 'terminal_open', {
+ requestId: 'open-4', protocolVersion: 3, agentId: 'agent-1', cols: 45, rows: 30,
+ })
+ await manager.handleFrame('tablet-1', 'terminal_open', {
+ requestId: 'open-5', protocolVersion: 3, agentId: 'agent-1', cols: 90, rows: 40,
+ })
+ expect(free()).toHaveLength(0)
+ })
+
// hn with no terminal (its server, kept for the sessions a closed window left) reads every pane of the desk. On
// 2026-10-14 it reopened first after each daemon restart, took the terminals at its 80x24 layout and left the
// window the person was using watching a shrunken agent until they typed. It opens with `watch: true` now.
diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.ts
index 888957404..b03491f8d 100644
--- a/cli/src/lib/terminalStreamManager.ts
+++ b/cli/src/lib/terminalStreamManager.ts
@@ -1407,6 +1407,7 @@ export class TerminalStreamManager {
state.flushTimer = null
state.stallTimer = null
this.streams.delete(state.streamId)
+ const controlled = this.controllerByPlacement.get(state.placementKey) === state.ownerId
if (this.controllerByAgent.get(state.agentId) === state.ownerId) this.controllerByAgent.delete(state.agentId)
if (this.controllerByPlacement.get(state.placementKey) === state.ownerId) this.controllerByPlacement.delete(state.placementKey)
if (state.outputPaused) await state.handle.resumeOutput().catch(() => { /* best effort */ })
@@ -1418,6 +1419,21 @@ export class TerminalStreamManager {
...(code ? { code } : {}),
...(takenBy ? { takenBy } : {}),
})
+ // The controller left (a phone closed it, or went away) rather than handing it to another view:
+ // the views watching it are told, so one on screen can take it back at its own size. Without
+ // this the terminal kept the size of the one that left until someone typed in a watcher.
+ if (controlled && code !== 'TERMINAL_TAKEN_OVER') this.notifyFree(state)
+ }
+
+ private notifyFree(closed: ActiveStream): void {
+ for (const watcher of this.streams.values()) {
+ if (watcher.closing || watcher.ownerId === closed.ownerId) continue
+ if (watcher.agentId !== closed.agentId && watcher.placementKey !== closed.placementKey) continue
+ this.deps.sendTarget(watcher.connId, 'terminal_free', {
+ protocolVersion: PROTOCOL_VERSION,
+ streamId: watcher.streamId,
+ })
+ }
}
/**
diff --git a/os/build.sh b/os/build.sh
index 96af82b8a..f66f86798 100644
--- a/os/build.sh
+++ b/os/build.sh
@@ -75,6 +75,11 @@ if [[ $PLATFORM == pc ]]; then
--output "$PROFILE/airootfs/usr/share/harness-os/hardware/nvidia"
fi
cp -a live/. "$PROFILE/airootfs/"
+# A testing USB: what it installs keeps its logs on disk across restarts (installer.py KEEP_LOGS).
+if [[ ${HARNESS_OS_KEEP_LOGS:-} == 1 ]]; then
+ mkdir -p "$PROFILE/airootfs/etc/harness-os"
+ touch "$PROFILE/airootfs/etc/harness-os/keep-logs"
+fi
mkdir -p "$PROFILE/airootfs/root" "$PROFILE/airootfs/etc/pacman.d/hooks"
cp tools/customize-live.sh "$PROFILE/airootfs/root/setup-live.sh"
cat > "$PROFILE/airootfs/etc/pacman.d/hooks/99-harness-live.hook" <<'EOF'
diff --git a/os/installer.py b/os/installer.py
index a3577975a..2ba7ca0f5 100644
--- a/os/installer.py
+++ b/os/installer.py
@@ -26,6 +26,8 @@ LIVE_PAYLOADS = (Path('/run/archiso/copytoram/airootfs.sfs'),
WORDMARK = ('█ █ ▄▀█ █▀█ █▄ █ █▀▀ █▀ █▀', '█▀█ █▀█ █▀▄ █ ▀█ ██▄ ▄█ ▄█')
COMMAND_LOG = None
INSTALL_LOG = Path('/var/log/harness-install.log')
+# On a USB built with HARNESS_OS_KEEP_LOGS: what it installs keeps its journal on disk.
+KEEP_LOGS = Path('/etc/harness-os/keep-logs')
LAST_LOG = None
@@ -469,10 +471,13 @@ def install_image(config, source, target, progress, resources):
write(target, '/etc/hostname', config['hostname'] + '\n')
write(target, '/etc/hosts', f"127.0.0.1 localhost\n::1 localhost\n127.0.1.1 {config['hostname']}\n")
write(target, '/etc/machine-id', '')
+ # Encrypted: the setup hotspot comes up while the disk waits for its password, for a phone to
+ # send it (harness-unlock), beside the screen's own prompt.
write(target, '/etc/mkinitcpio.conf',
'HOOKS=(base systemd autodetect microcode modconf kms keyboard sd-vconsole '
+ ('plymouth ' if config['encrypt'] else '')
- + 'block sd-encrypt filesystems fsck)\nCOMPRESSION="zstd"\n')
+ + 'block ' + ('harness-unlock ' if config['encrypt'] else '')
+ + 'sd-encrypt filesystems fsck)\nCOMPRESSION="zstd"\n')
if platform['modules']:
write(target, '/etc/mkinitcpio.conf.d/20-harness-platform.conf',
'MODULES+=(' + ' '.join(platform['modules']) + ')\n')
@@ -492,9 +497,17 @@ def install_image(config, source, target, progress, resources):
if config['encrypt']:
write(target, '/etc/systemd/system/[email protected]/autologin.conf',
'[Service]\nExecStart=\n' + f'ExecStart=-/usr/bin/agetty --autologin {config["username"]} --noclear %I $TERM\n')
+ else:
+ # The one account is known: only its password is asked, as the disk's would be.
+ write(target, '/etc/systemd/system/[email protected]/password.conf',
+ '[Service]\nExecStart=\n' + f"ExecStart=-/usr/bin/agetty --skip-login --login-options '-p -- {config['username']}' --noclear %I $TERM\n")
+ # A USB built with HARNESS_OS_KEEP_LOGS (build.sh) installs computers that keep their logs
+ # across restarts, to read what went wrong after one. For testing; not set for a release.
+ if KEEP_LOGS.is_file():
+ write(target, '/etc/systemd/journald.conf.d/90-harness-keep-logs.conf', '[Journal]\nStorage=persistent\n')
# An encrypted root cannot appear until its owner returns to unlock it.
# Do not send a person who paused at the prompt into emergency mode.
- root_flags = 'subvol=@' + (',x-systemd.device-timeout=0' if config['encrypt'] else '')
+ root_flags ='subvol=@' + (',x-systemd.device-timeout=0' if config['encrypt'] else '')
kernel_args = f'quiet loglevel=3 rootflags={root_flags}'
if platform['parameters']:
kernel_args += ' ' + ' '.join(platform['parameters'])
@@ -504,7 +517,9 @@ def install_image(config, source, target, progress, resources):
# setup delays before Plymouth can display its unlock prompt.
kernel_args += ' console=ttyS0,115200 console=tty0 plymouth.ignore-serial-consoles'
if luks_uuid:
- kernel_args += f' rd.luks.name={luks_uuid}=cryptroot splash'
+ # tries=0: asked again however often it is wrong, as an open hotspot lets anyone try
+ # (the page slows them down); three wrong ones used to stop the computer starting.
+ kernel_args += f' rd.luks.name={luks_uuid}=cryptroot rd.luks.options={luks_uuid}=tries=0 splash'
write(target, '/etc/default/grub',
'GRUB_DEFAULT=0\nGRUB_TIMEOUT=1\nGRUB_DISTRIBUTOR="Harness"\n'
'GRUB_DISABLE_OS_PROBER=true\n' + f'GRUB_CMDLINE_LINUX="{kernel_args}"\n')
@@ -520,6 +535,9 @@ def install_image(config, source, target, progress, resources):
chroot(target, 'systemctl', 'enable', 'NetworkManager', 'systemd-resolved', 'systemd-timesyncd',
'harness-setup.service')
chroot(target, 'systemctl', 'disable', 'sshd.service')
+ # Its account's daemon from the start (the user lingers), not only with a session at the
+ # screen: a computer set up and unlocked from a phone may have no screen, or nobody at it.
+ chroot(target, 'systemctl', '--global', 'enable', 'harness-daemon.service')
report('Preparing startup and recovery…')
chroot(target, '/usr/lib/harness-os/init-keyring')
# Keep the live marker through this initial optional package transaction,
diff --git a/os/network.py b/os/network.py
index 76f456d05..d2ddb97fd 100644
--- a/os/network.py
+++ b/os/network.py
@@ -2,7 +2,6 @@
"""A full-page Wi-Fi step backed by NetworkManager, with no resident UI service."""
import argparse
import curses
-import json
import os
from pathlib import Path
import subprocess
@@ -11,9 +10,17 @@ import uuid
import unicodedata
WORDMARK = ('█ █ ▄▀█ █▀█ █▄ █ █▀▀ █▀ █▀', '█▀█ █▀█ █▀▄ █ ▀█ ██▄ ▄█ ▄█')
-# setup.py's hotspot for a phone, and the Wi-Fi it saw before taking the radio.
+# setup.py's hotspot for a phone. Opened (after someone typed this computer's password at its screen),
+# this page holds the radio: SETUP_SCREEN keeps setup.py from hosting the hotspot (setup.py SCREEN)
+# until the computer is signed in, or the page is left alone a while.
SETUP_HOTSPOT = 'harness-setup'
-SETUP_NETWORKS = '/run/harness-os/setup-networks.json'
+SETUP_SCREEN = '/run/harness-os/setup-screen'
+# Untouched this long, the page lets the hotspot back for a phone; a key takes the radio again.
+SCREEN_IDLE = 300
+# Written by the startup's unlock hotspot (unlock/http) when a phone opened the disk: the session at
+# the screen then started by itself (autologin), with nobody there. The first Wi-Fi page leaves the
+# radio to setup.py's hotspot, for that phone to choose the Wi-Fi, until a key here.
+UNLOCKED_BY_PHONE = '/run/harness-os/unlocked-by-phone'
def nmcli(*args, secret=None, wait=8):
@@ -42,8 +49,7 @@ def fields(line):
def setup_hotspot_up():
- """Whether the radio hosts setup.py's hotspot for a phone. It is not a network this computer is
- on, and while it is up the radio cannot scan: the list shown is the one setup.py read first."""
+ """Whether the radio hosts setup.py's hotspot for a phone. It is not a network this computer is on."""
try:
result = nmcli('-t', '-e', 'yes', '-f', 'NAME', 'connection', 'show', '--active', wait=3)
except (OSError, subprocess.TimeoutExpired):
@@ -64,21 +70,43 @@ def connected():
return any(row[1] == 'ethernet' and row[2] == 'connected' for row in wired_devices())
-def setup_networks():
- """What the radio saw before it became the setup hotspot (os/setup.py)."""
+def hold_radio():
+ """Someone at the screen is choosing a Wi-Fi: setup.py hosts no hotspot meanwhile, and one up now
+ goes first, for the radio to scan and join. Before the first scan, so the list is a real one.
+ Kept once the page is done: the Wi-Fi chosen here stays while they sign in at the screen."""
+ path = Path(SETUP_SCREEN)
try:
- rows = json.loads(Path(SETUP_NETWORKS).read_text())
- except (OSError, ValueError):
- return []
- networks = [dict(ssid=row['ssid'], signal=int(row['signal']), security=row.get('security') or '--',
- device=row['device'], bssid='', active=False)
- for row in rows if isinstance(row, dict) and row.get('ssid') and row.get('device')]
- return sorted(networks, key=lambda row: (-row['signal'], row['ssid']))
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.touch()
+ except OSError:
+ pass
+ if leave_setup_hotspot():
+ # A moment for the radio to leave access-point mode before it is asked to scan.
+ time.sleep(1)
+ return True
+ return False
+
+
+def phone_unlocked():
+ """Whether a phone unlocked this computer as it started (UNLOCKED_BY_PHONE), asked once: the mark
+ goes, so a Wi-Fi page opened later at the screen holds the radio as usual."""
+ path = Path(UNLOCKED_BY_PHONE)
+ try:
+ path.unlink()
+ return True
+ except OSError:
+ return False
+
+
+def release_radio():
+ """The hotspot may come back (setup.py) for a phone: the page was left alone."""
+ try:
+ Path(SETUP_SCREEN).unlink(missing_ok=True)
+ except OSError:
+ pass
def scan(rescan=None):
- if setup_hotspot_up():
- return setup_networks()
# Opening the page should reuse a recent scan, especially just after a
# reconnect. NetworkManager refreshes results older than 30 seconds in auto
# mode. Force a scan only when the user chooses Rescan.
@@ -163,10 +191,12 @@ def saved_connection(network):
def leave_setup_hotspot():
- # Chosen here, on the screen: the radio stops hosting the phone's setup hotspot to join it, and
- # setup.py, seeing this computer online, stops waiting for the phone.
+ # Wanted here, on the screen: the radio stops hosting the phone's setup hotspot to scan and join,
+ # and setup.py, seeing the page hold the radio, stops waiting for the phone.
if setup_hotspot_up():
nmcli('connection', 'down', 'id', SETUP_HOTSPOT, wait=10)
+ return True
+ return False
def connect(network, password=None):
@@ -351,13 +381,33 @@ class NetworkPage:
# or a router back on. Left open, it held the first tab and OpenCode never opened there.
# Opened while online, to change networks, it stays until closed.
until_online = self.first_use or not online
- self.refresh()
+ # Someone who typed this computer's password is here: the phone's hotspot goes first, and the
+ # list is the radio's own, scanned now.
+ touched = time.monotonic()
+ if self.first_use and phone_unlocked():
+ # A phone unlocked this computer and is setting it up: its hotspot stays. A key here
+ # still takes the radio, as below.
+ self.held = False
+ self.refresh()
+ self.message = 'A phone can set this computer up now. Press a key to choose a Wi-Fi here.'
+ else:
+ self.held = True
+ self.refresh(rescan=True if hold_radio() else None)
+ # Nothing yet: just started (NetworkManager has not scanned once since the card came up,
+ # and its recent list is empty) — scanned now, rather than waiting for a Rescan.
+ if not self.networks and not self.message:
+ self.refresh(rescan=True)
checked = time.monotonic()
while True:
if until_online and time.monotonic() - checked >= 2:
if connected():
return 0
checked = time.monotonic()
+ if self.held and time.monotonic() - touched >= SCREEN_IDLE:
+ # Left alone: a phone may set this computer up instead, until a key here.
+ release_radio()
+ self.held = False
+ self.message = 'A phone can set this computer up now. Press a key to choose a Wi-Fi here.'
rows = [('wifi', network) for network in self.networks] + [('rescan', None)]
rows += [('wired', device) for device in self.wired]
self.selected = min(self.selected, len(rows) - 1)
@@ -386,6 +436,12 @@ class NetworkPage:
key = self.screen.get_wch()
except curses.error:
continue
+ touched = time.monotonic()
+ if not self.held:
+ # Back at the screen: the radio again, and a fresh list.
+ self.held = True
+ self.refresh(rescan=True if hold_radio() else None)
+ continue
if key in ('\x1b', '\x03') and not self.first_use:
return 1
if key in (curses.KEY_UP, curses.KEY_BTAB):
diff --git a/os/root/usr/bin/harness b/os/root/usr/bin/harness
index ce7bb80fd..d294fceb2 100644
--- a/os/root/usr/bin/harness
+++ b/os/root/usr/bin/harness
@@ -27,8 +27,9 @@ if [ "${1:-}" = rollback ]; then
exec /usr/bin/python3 /usr/lib/harness-os/runtime_update.py rollback "$@"
fi
if [ "${1:-}" = factory-reset ]; then
- # As just flashed: signed out, no harnesses, Wi-Fi forgotten (--keep-wifi keeps it), the setup
- # hotspot open for a phone. The same as the reset button. Not `harness reset`, the CLI's own.
+ # As just flashed: signed out, no harnesses, hn's tabs and panes gone, here and on the account's
+ # desk (--keep-workspace keeps them), Wi-Fi forgotten (--keep-wifi keeps it), the setup hotspot
+ # open for a phone. The same as the reset button. Not `harness reset`, the CLI's own.
shift
[ "$(id -u)" = 0 ] && exec /usr/bin/python3 /usr/lib/harness-os/setup.py reset "$@"
exec sudo /usr/bin/python3 /usr/lib/harness-os/setup.py reset "$@"
diff --git a/os/root/usr/lib/harness-os/unlock/harness-unlock.service b/os/root/usr/lib/harness-os/unlock/harness-unlock.service
new file mode 100644
index 000000000..0823fa727
--- /dev/null
+++ b/os/root/usr/lib/harness-os/unlock/harness-unlock.service
@@ -0,0 +1,19 @@
+[Unit]
+Description=Harness setup hotspot, to unlock this computer from a phone
+Documentation=file:///usr/lib/harness-os/unlock/run
+DefaultDependencies=no
+ConditionPathExists=/etc/initrd-release
+After=systemd-udev-trigger.service systemd-modules-load.service
+Wants=systemd-udev-trigger.service
+# Gone before the system proper starts: its NetworkManager takes the radio (and setup.py its hotspot).
+Conflicts=initrd-switch-root.target
+Before=initrd-switch-root.target initrd-cleanup.service
+
+[Service]
+Type=simple
+ExecStart=/usr/lib/harness-os/unlock/run
+# The disk opened from the phone: the system proper starts at once, and this goes with it. A moment
+# first, for the page's "unlocked" to reach the phone over the air.
+ExecStop=/bin/sh -c 'sleep 2'
+ExecStopPost=/usr/lib/harness-os/unlock/run stop
+KillMode=control-group
diff --git a/os/root/usr/lib/harness-os/unlock/http b/os/root/usr/lib/harness-os/unlock/http
new file mode 100755
index 000000000..5d45d9f9a
--- /dev/null
+++ b/os/root/usr/lib/harness-os/unlock/http
@@ -0,0 +1,178 @@
+#!/bin/sh
+# One request on http://10.42.0.1 while the disk is locked (`run`), on stdin and stdout (tcpsvd).
+#
+# GET /setup {protocol, hotspot, locked: true, wait}: the phone asks for the password
+# GET /setup/networks the Wi-Fi around ({networks: [...]}, `networks`), from the startup's scan,
+# or with ?rescan=1 scanned now on the hotspot's card where it allows that
+# POST /setup/check the computer's password, as the body, only checked against the disk
+# (cryptsetup --test-passphrase): 200 {state: "right"}, 401 WRONG_PASSWORD.
+# Nothing opens; the phone asks it first, then the Wi-Fi, then unlocks. As
+# many tries as the person likes (protocol 3).
+# POST /setup/unlock the computer's password, as the body: it answers the disk's question
+# (systemd's ask-password, the one the screen answers), then says whether the
+# disk opened: 200, 401 WRONG_PASSWORD, 429 WAIT after many wrong ones, 409 BUSY
+#
+# Protocol 2: the unlock may carry the rest of the setup too, in one stay on the hotspot — the Wi-Fi
+# chosen, its password, the sign-in ticket and the phone's account, as setup.py's /setup/connect
+# takes them. The body is then the password followed by that JSON, its length in the header
+# X-Harness-Setup-Length. Kept, once the disk opened, in SETUP (/run, which outlives the switch to the
+# system proper; root's alone), where setup.py joins and signs in with it: no second hotspot.
+#
+# The password goes only to systemd-reply-password, on its stdin; it is never written or logged.
+set -u
+STATE=${HARNESS_UNLOCK_STATE:-/run/harness-unlock}
+ASK=${HARNESS_UNLOCK_ASK:-/run/systemd/ask-password}
+REPLY=${HARNESS_UNLOCK_REPLY:-/usr/lib/systemd/systemd-reply-password}
+MAPPER=${HARNESS_UNLOCK_MAPPER:-/dev/mapper}
+# How long a password may take to open the disk (argon2 takes a few seconds on purpose).
+OPENS=${HARNESS_UNLOCK_OPENS:-40}
+BY_PHONE=${HARNESS_UNLOCK_BY_PHONE:-/run/harness-os/unlocked-by-phone}
+SETUP=${HARNESS_UNLOCK_SETUP:-/run/harness-os/phone-setup.json}
+CRYPTSETUP=${HARNESS_UNLOCK_CRYPTSETUP:-/usr/bin/cryptsetup}
+HERE=$(dirname "$0")
+# Wrong ones before the page makes the phone wait, and the first wait; it doubles after each.
+FREE_TRIES=5
+FIRST_WAIT=30
+CR=$(printf '\r')
+
+reply() {
+ printf 'HTTP/1.1 %s\r\nContent-Type: application/json\r\nContent-Length: %s\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n%s' \
+ "$1" "${#2}" "$2"
+ exit 0
+}
+
+now() { cut -d. -f1 /proc/uptime 2>/dev/null || date +%s; }
+
+# Wrong passwords so far, and when the phone may try again: "count until".
+tries() { cat "$STATE/tries" 2>/dev/null || echo '0 0'; }
+
+wait_left() {
+ set -- $(tries)
+ left=$(( $2 - $(now) ))
+ [ "$left" -gt 0 ] && echo "$left" || echo 0
+}
+
+# The disk's question: the ask-password file systemd-cryptsetup wrote, and its socket.
+question() {
+ for file in "$ASK"/ask.*; do
+ [ -f "$file" ] || continue
+ grep -q '^Id=cryptsetup:' "$file" && { echo "$file"; return 0; }
+ done
+ return 1
+}
+
+opened() {
+ for device in "$MAPPER"/*; do
+ [ "${device##*/}" = control ] && continue
+ [ -e "$device" ] && return 0
+ done
+ return 1
+}
+
+read -r method target _ || exit 0
+query=
+case $target in *\?*) query=${target#*\?} ;; esac
+target=${target%%\?*}
+length=0
+extra=0
+while read -r line; do
+ line=${line%"$CR"}
+ [ -z "$line" ] && break
+ case $line in
+ [Cc]ontent-[Ll]ength:*) length=${line#*:}; length=${length# } ;;
+ [Xx]-[Hh]arness-[Ss]etup-[Ll]ength:*) extra=${line#*:}; extra=${extra# } ;;
+ esac
+done
+case $length in ''|*[!0-9]*) length=0 ;; esac
+case $extra in ''|*[!0-9]*) extra=0 ;; esac
+name=$(cat "$STATE/name" 2>/dev/null || echo Harness-Setup)
+
+case "$method $target" in
+ 'GET /setup')
+ reply '200 OK' "{\"protocol\":3,\"hotspot\":\"$name\",\"locked\":true,\"wait\":$(wait_left)}"
+ ;;
+ 'GET /setup/networks')
+ # Asked again (the phone's Rescan): scanned now, beside the hotspot, where the card allows it.
+ if [ "$query" = rescan=1 ] && [ -f "$STATE/device" ]; then
+ fresh=$("$HERE/networks" "$(cat "$STATE/device")" "$name" ap-force) && [ -n "$fresh" ] &&
+ printf '%s\n' "$fresh" > "$STATE/networks.json"
+ fi
+ reply '200 OK' "$(cat "$STATE/networks.json" 2>/dev/null || echo '{"networks":[]}')"
+ ;;
+ 'POST /setup/check')
+ [ "$length" -ge 1 ] && [ "$length" -le 512 ] || reply '400 Bad Request' '{"error":"BAD_REQUEST","message":"Enter the computer'"'"'s password."}'
+ password=$(dd bs=1 count="$length" 2>/dev/null)
+ opened && reply '200 OK' '{"state":"right"}'
+ asked=$(question) || reply '503 Service Unavailable' '{"error":"NOT_ASKING","message":"The computer is not asking for its password yet. Try again in a moment."}'
+ # The disk the question is about: "Id=cryptsetup:/dev/nvme0n1p3".
+ disk=$(sed -n 's/^Id=cryptsetup://p' "$asked")
+ [ -n "$disk" ] || reply '503 Service Unavailable' '{"error":"NOT_ASKING","message":"The computer is not asking for its password yet. Try again in a moment."}'
+ mkdir "$STATE/busy" 2>/dev/null || reply '409 Conflict' '{"error":"BUSY","message":"Already trying a password."}'
+ trap 'rmdir "$STATE/busy" 2>/dev/null' EXIT
+ # Checked only: the key slot is tried, nothing is opened. The password on stdin, as it is.
+ if printf '%s' "$password" | "$CRYPTSETUP" open --test-passphrase --key-file=- "$disk" >/dev/null 2>&1; then
+ password=
+ reply '200 OK' '{"state":"right"}'
+ fi
+ password=
+ reply '401 Unauthorized' '{"error":"WRONG_PASSWORD","message":"That is not this computer'"'"'s password. It is the one set when it was installed."}'
+ ;;
+ 'POST /setup/unlock')
+ ;;
+ *)
+ reply '404 Not Found' '{"error":"NOT_FOUND"}'
+ ;;
+esac
+
+[ "$extra" -le 8192 ] && [ "$extra" -lt "$length" ] || extra=0
+secret=$(( length - extra ))
+[ "$secret" -ge 1 ] && [ "$secret" -le 512 ] || reply '400 Bad Request' '{"error":"BAD_REQUEST","message":"Enter the computer'"'"'s password."}'
+# A byte at a time: head reads ahead on a pipe, and would take the setup that follows with it.
+password=$(dd bs=1 count="$secret" 2>/dev/null)
+setup=
+[ "$extra" -gt 0 ] && setup=$(head -c "$extra")
+left=$(wait_left)
+[ "$left" -gt 0 ] && reply '429 Too Many Requests' "{\"error\":\"WAIT\",\"wait\":$left,\"message\":\"Too many wrong passwords. Try again in $left seconds.\"}"
+mkdir "$STATE/busy" 2>/dev/null || reply '409 Conflict' '{"error":"BUSY","message":"Already trying a password."}'
+trap 'rmdir "$STATE/busy" 2>/dev/null' EXIT
+
+opened && reply '200 OK' '{"state":"unlocked"}'
+asked=$(question) || reply '503 Service Unavailable' '{"error":"NOT_ASKING","message":"The computer is not asking for its password yet. Try again in a moment."}'
+socket=$(sed -n 's/^Socket=//p' "$asked")
+printf '%s\n' "$password" | "$REPLY" 1 "$socket" 2>/dev/null
+password=
+
+# Opened, or asked again (a wrong one: systemd-cryptsetup asks anew, in a new file), within OPENS
+# seconds.
+result=
+for _ in $(seq "$OPENS"); do
+ opened && { result=opened; break; }
+ current=$(question) || current=
+ [ -n "$current" ] && [ "$current" != "$asked" ] && { result=wrong; break; }
+ sleep 1
+done
+if [ "$result" = opened ]; then
+ echo '0 0' > "$STATE/tries"
+ # Unlocked from a phone, not at the screen: /run outlives the switch to the system proper, where
+ # the screen's first Wi-Fi page reads this and leaves the radio to setup.py's hotspot, for the
+ # phone to choose the Wi-Fi (network.py UNLOCKED_BY_PHONE). Nobody at the screen typed anything.
+ mkdir -p "$(dirname "$BY_PHONE")" && : > "$BY_PHONE"
+ # The rest of the setup, for setup.py as the system starts: root's alone, and only in /run.
+ if [ -n "$setup" ]; then
+ (umask 077 && printf '%s' "$setup" > "$SETUP")
+ setup=
+ fi
+ reply '200 OK' '{"state":"unlocked"}'
+fi
+[ -z "$result" ] && reply '504 Gateway Timeout' '{"error":"TIMEOUT","message":"The computer did not say whether that opened it. Try again."}'
+set -- $(tries)
+count=$(( $1 + 1 ))
+until=0
+if [ "$count" -ge "$FREE_TRIES" ]; then
+ wait=$FIRST_WAIT
+ extra=$(( count - FREE_TRIES ))
+ while [ "$extra" -gt 0 ] && [ "$wait" -lt 600 ]; do wait=$(( wait * 2 )); extra=$(( extra - 1 )); done
+ until=$(( $(now) + wait ))
+fi
+echo "$count $until" > "$STATE/tries"
+reply '401 Unauthorized' '{"error":"WRONG_PASSWORD","message":"That is not this computer'"'"'s password. It is the one set when it was installed."}'
diff --git a/os/root/usr/lib/harness-os/unlock/networks b/os/root/usr/lib/harness-os/unlock/networks
new file mode 100755
index 000000000..834bb12df
--- /dev/null
+++ b/os/root/usr/lib/harness-os/unlock/networks
@@ -0,0 +1,75 @@
+#!/bin/sh
+# The Wi-Fi networks around, as setup.py's /setup/networks lists them — {"networks": [{ssid, signal,
+# security}]}, strongest first, one row a name — for the phone to choose one while the disk is still
+# locked (`http`). Read from `iw ... scan` output on stdin, or with a device, scanned now: `ap-force`
+# scans on the hotspot's own card while it hosts it, which most cards allow; one that refuses keeps
+# the list of the startup's scan (`run`).
+#
+# networks DEVICE OWN-NAME [ap-force] scan now
+# networks - OWN-NAME < iw-scan-output only read
+set -u
+device=$1
+own=${2:-}
+if [ "$device" = - ]; then
+ output=$(cat)
+else
+ output=$(iw dev "$device" scan ${3:-} 2>/dev/null) || exit 1
+fi
+printf '%s\n' "$output" | awk -v own="$own" '
+function flush() {
+ if (security == "" && privacy) security = "WEP"
+ if (ssid != "" && ssid != own && (!(ssid in best) || signal > best[ssid])) {
+ best[ssid] = signal
+ kind[ssid] = security
+ }
+ ssid = ""; signal = 0; security = ""; privacy = 0
+}
+# One access point a block: "BSS aa:bb:...(on wlan0)".
+/^BSS / { flush(); next }
+/^[ \t]*signal:/ {
+ # dBm to the 0-100 NetworkManager shows: -100 dBm is 0, -50 and above 100.
+ dbm = $2 + 0
+ signal = int(2 * (dbm + 100))
+ if (signal < 0) signal = 0
+ if (signal > 100) signal = 100
+ next
+}
+/^[ \t]*SSID:/ {
+ line = $0
+ sub(/^[ \t]*SSID: ?/, "", line)
+ ssid = line
+ next
+}
+/^[ \t]*capability:/ { if ($0 ~ /Privacy/) privacy = 1; next }
+/Authentication suites:/ {
+ psk = ($0 ~ /PSK/); sae = ($0 ~ /SAE/); eap = ($0 ~ /IEEE 802\.1X/)
+ if (psk && sae) security = "WPA2 WPA3"
+ else if (sae) security = "WPA3"
+ else if (psk) security = "WPA2"
+ else if (eap) security = "802.1X"
+ next
+}
+END {
+ flush()
+ count = 0
+ for (name in best) { names[++count] = name }
+ # Strongest first.
+ for (i = 2; i <= count; i++) {
+ for (j = i; j > 1 && best[names[j]] > best[names[j - 1]]; j--) {
+ swap = names[j]; names[j] = names[j - 1]; names[j - 1] = swap
+ }
+ }
+ printf "{\"networks\":["
+ for (i = 1; i <= count && i <= 40; i++) {
+ name = names[i]
+ # A character at a time: the backslashes of a gsub replacement differ between awks.
+ quoted = ""
+ for (k = 1; k <= length(name); k++) {
+ c = substr(name, k, 1)
+ if (c == "\\" || c == "\"") quoted = quoted "\\"
+ quoted = quoted c
+ }
+ printf "%s{\"ssid\":\"%s\",\"signal\":%d,\"security\":\"%s\"}", (i > 1 ? "," : ""), quoted, best[name], kind[name]
+ }
+ printf "]}\n"
+}'
diff --git a/os/root/usr/lib/harness-os/unlock/run b/os/root/usr/lib/harness-os/unlock/run
new file mode 100755
index 000000000..118c0218d
--- /dev/null
+++ b/os/root/usr/lib/harness-os/unlock/run
@@ -0,0 +1,77 @@
+#!/bin/sh
+# Runs in the computer's startup (initramfs), while the disk waits for its password: the same open
+# setup hotspot os/setup.py hosts later, `Harness-XXXX` after the Wi-Fi card's own address, and on
+# it http://10.42.0.1/setup, where a phone (mobile/lib/phone/add_device/) sends the computer's
+# password (`http`). The screen still asks too: whichever answers first opens the disk. Then the
+# system proper starts, and this goes (harness-unlock.service): its setup.py takes over the hotspot
+# when the computer is not signed in yet, or it joins its own Wi-Fi.
+#
+# busybox sh, wpa_supplicant (an access point, as NetworkManager's hotspot is), dnsmasq for the
+# phone's address, and busybox tcpsvd for the page. Only Wi-Fi: a computer with none, or a card whose
+# driver is not here, is unlocked at its screen as before.
+set -u
+STATE=${HARNESS_UNLOCK_STATE:-/run/harness-unlock}
+ADDRESS=10.42.0.1
+HERE=$(dirname "$0")
+
+stop() {
+ for name in tcpsvd dnsmasq wpa; do
+ [ -f "$STATE/$name.pid" ] && kill "$(cat "$STATE/$name.pid")" 2>/dev/null
+ done
+ if [ -f "$STATE/device" ]; then
+ device=$(cat "$STATE/device")
+ ip addr flush dev "$device" 2>/dev/null
+ ip link set "$device" down 2>/dev/null
+ fi
+ return 0
+}
+
+[ "${1:-}" = stop ] && { stop; exit 0; }
+
+mkdir -p "$STATE"
+# The Wi-Fi card, once its driver has loaded.
+device=
+for _ in $(seq 30); do
+ for path in /sys/class/net/*; do
+ [ -d "$path/wireless" ] && { device=${path##*/}; break; }
+ done
+ [ -n "$device" ] && break
+ sleep 1
+done
+if [ -z "$device" ]; then
+ echo 'harness-unlock: no Wi-Fi here; the screen unlocks this computer'
+ while :; do sleep 3600; done
+fi
+echo "$device" > "$STATE/device"
+# Its own address, as setup.py names the hotspot: nothing has randomized it yet this early.
+tail=$(sed 's/://g; s/.*\(....\)$/\1/; y/abcdef/ABCDEF/' "/sys/class/net/$device/address")
+name="Harness-$tail"
+echo "$name" > "$STATE/name"
+
+ip link set "$device" up
+# A scan first: some cards (Intel's) host no access point until they have heard others nearby. It is
+# also the Wi-Fi list the phone chooses from while the disk is locked (`http`, /setup/networks).
+iw dev "$device" scan 2>/dev/null | "$HERE/networks" - "$name" > "$STATE/networks.json" 2>/dev/null ||
+ echo '{"networks":[]}' > "$STATE/networks.json"
+cat > "$STATE/wpa.conf" <<EOF
+ap_scan=2
+network={
+ ssid="$name"
+ mode=2
+ frequency=2437
+ key_mgmt=NONE
+}
+EOF
+wpa_supplicant -B -i "$device" -D nl80211 -c "$STATE/wpa.conf" -P "$STATE/wpa.pid" -s || {
+ echo "harness-unlock: $device hosts no access point; the screen unlocks this computer"
+ while :; do sleep 3600; done
+}
+ip addr add "$ADDRESS/24" dev "$device"
+dnsmasq --interface="$device" --bind-interfaces --except-interface=lo --port=0 --user=root \
+ --dhcp-range=10.42.0.10,10.42.0.100,255.255.255.0,1h --dhcp-leasefile="$STATE/leases" \
+ --pid-file="$STATE/dnsmasq.pid"
+echo "harness-unlock: hotspot \"$name\" is up on $device"
+# The screen's password page says so (the theme `harness`, its message): another way in.
+command -v plymouth >/dev/null 2>&1 && plymouth display-message --text="hotspot:$name" 2>/dev/null
+echo $$ > "$STATE/tcpsvd.pid"
+exec tcpsvd -E "$ADDRESS" 80 "$HERE/http"
diff --git a/os/root/usr/lib/harness-os/wait-runtime b/os/root/usr/lib/harness-os/wait-runtime
index be1e89460..682c1db34 100755
--- a/os/root/usr/lib/harness-os/wait-runtime
+++ b/os/root/usr/lib/harness-os/wait-runtime
@@ -1,9 +1,16 @@
#!/bin/sh
# Type=exec establishes a process, not an agent runtime ready to accept hn.
# Keep startup ordering honest without a second persistent supervisor.
+#
+# Asked over the daemon's own Unix socket, which the filesystem limits to this user: over the
+# loopback port a caller without the local credential is answered only which daemon this is (cli
+# hookServer.ts publicStatus), never `discoveryReady`, and the unit failed every start, the daemon
+# restarted every 35 s (2026-10-20). The port says where the socket is.
set -eu
for attempt in $(seq 1 120); do
- if curl --fail --silent --max-time 1 http://127.0.0.1:18473/api/status |
+ socket=$(curl --fail --silent --max-time 1 http://127.0.0.1:18473/api/status | jq -r '.localSocket // empty' 2>/dev/null || true)
+ if [ -n "$socket" ] && [ -S "$socket" ] &&
+ curl --fail --silent --max-time 1 --unix-socket "$socket" http://localhost/api/status |
jq -e '.discoveryReady == true and .safeMode != true' >/dev/null 2>&1; then
exit 0
fi
diff --git a/os/root/usr/lib/initcpio/install/harness-unlock b/os/root/usr/lib/initcpio/install/harness-unlock
new file mode 100755
index 000000000..d5fba1bd4
--- /dev/null
+++ b/os/root/usr/lib/initcpio/install/harness-unlock
@@ -0,0 +1,41 @@
+#!/bin/bash
+# The setup hotspot before the disk is open: a phone joins Harness-XXXX and sends the computer's
+# password, which answers the same question the screen asks (sd-encrypt). For an encrypted Harness
+# with no screen. Placed before sd-encrypt in HOOKS (installer.py). See /usr/lib/harness-os/unlock/.
+
+build() {
+ local unlock=/usr/lib/harness-os/unlock
+
+ # This computer's Wi-Fi card: its driver (autodetect keeps only the one in use) and firmware.
+ add_checked_modules '/drivers/net/wireless/'
+ map add_module 'cfg80211' 'mac80211'
+ # And the parts its driver loads by itself rather than depends on (Intel's iwlwifi asks for
+ # iwlmvm or iwldvm once it knows the card): every Wi-Fi module running here now.
+ local module path
+ for module in /sys/module/*; do
+ module=${module##*/}
+ path=$(modinfo -k "$KERNELVERSION" -n "$module" 2>/dev/null) || continue
+ [[ $path == */drivers/net/wireless/* ]] && add_module "$module"
+ done
+ add_firmware 'regulatory.db' 'regulatory.db.p7s'
+
+ map add_binary \
+ '/usr/bin/wpa_supplicant' \
+ '/usr/bin/dnsmasq' \
+ '/usr/bin/iw' \
+ '/usr/bin/cryptsetup' \
+ '/usr/lib/systemd/systemd-reply-password'
+
+ add_file "$unlock/run" "$unlock/run" 755
+ add_file "$unlock/http" "$unlock/http" 755
+ add_file "$unlock/networks" "$unlock/networks" 755
+ add_file "$unlock/harness-unlock.service" '/usr/lib/systemd/system/harness-unlock.service' 644
+ add_symlink '/usr/lib/systemd/system/initrd.target.wants/harness-unlock.service' \
+ '../harness-unlock.service'
+}
+
+help() {
+ cat <<HELPEOF
+Hosts the Harness setup hotspot while the disk waits for its password, for a phone to unlock it.
+HELPEOF
+}
diff --git a/os/root/usr/share/plymouth/themes/harness/harness.script b/os/root/usr/share/plymouth/themes/harness/harness.script
index 2060e1173..53fb32c89 100644
--- a/os/root/usr/share/plymouth/themes/harness/harness.script
+++ b/os/root/usr/share/plymouth/themes/harness/harness.script
@@ -11,6 +11,13 @@ logo.SetPosition(Window.GetX() + (Window.GetWidth() - logo_image.GetWidth()) / 2
Window.GetY() + Window.GetHeight() / 2 - logo_image.GetHeight() - 24, 1);
label = Sprite();
entry = Sprite();
+# The startup's own setup hotspot (initramfs harness-unlock), for a phone to unlock with: its
+# badge blinks while the password is asked, its name under it. Told by `plymouth display-message`.
+badge = Sprite();
+phone = Sprite();
+hotspot = "";
+asking = 0;
+tick = 0;
fun display_password(prompt, bullets) {
label_image = Image.Text("Enter your password", 0.86, 0.86, 0.86, 1, "monospace 16", "center");
@@ -26,12 +33,51 @@ fun display_password(prompt, bullets) {
Window.GetY() + Window.GetHeight() / 2 + 56, 1);
label.SetOpacity(1);
entry.SetOpacity(1);
+ asking = 1;
+ show_hotspot();
}
fun display_normal() {
label.SetOpacity(0);
entry.SetOpacity(0);
+ asking = 0;
+ badge.SetOpacity(0);
+ phone.SetOpacity(0);
+}
+
+fun show_hotspot() {
+ if (hotspot == "" || asking == 0) return;
+ badge_image = Image.Text(" PHONE UNLOCK ON ", 0.85, 0.78, 0.1, 1, "monospace 16", "center");
+ badge.SetImage(badge_image);
+ badge.SetPosition(Window.GetX() + (Window.GetWidth() - badge_image.GetWidth()) / 2,
+ Window.GetY() + Window.GetHeight() / 2 + 120, 1);
+ # The app first, and in general words: it finds this computer's Wi-Fi itself, and its screens
+ # change faster than an installed computer's startup can be. Only the Wi-Fi's name is fixed.
+ phone_image = Image.Text("Or set it up from the Harness app on your phone.\n" +
+ "This computer's Wi-Fi: " + hotspot,
+ 0.86, 0.86, 0.86, 1, "monospace 14", "center");
+ phone.SetImage(phone_image);
+ phone.SetPosition(Window.GetX() + (Window.GetWidth() - phone_image.GetWidth()) / 2,
+ Window.GetY() + Window.GetHeight() / 2 + 160, 1);
+ badge.SetOpacity(1);
+ phone.SetOpacity(1);
+}
+
+fun display_message(text) {
+ if (text.SubString(0, 8) != "hotspot:") return;
+ hotspot = text.SubString(8, text.Length());
+ show_hotspot();
+}
+
+# The badge blinks, about once a second, while the hotspot is up and the password asked.
+fun refresh() {
+ if (hotspot == "" || asking == 0) return;
+ tick++;
+ if (tick % 50 == 0) badge.SetOpacity(1);
+ if (tick % 50 == 25) badge.SetOpacity(0);
}
Plymouth.SetDisplayPasswordFunction(display_password);
Plymouth.SetDisplayNormalFunction(display_normal);
+Plymouth.SetMessageFunction(display_message);
+Plymouth.SetRefreshFunction(refresh);
diff --git a/os/setup.py b/os/setup.py
index f80b81684..6ca7103e6 100644
--- a/os/setup.py
+++ b/os/setup.py
@@ -9,11 +9,14 @@ Internet and signs in with `harness login --ticket`. When the Wi-Fi fails, the h
with the reason (wrong password, out of reach, no address, no Internet), for the phone to read when
it rejoins, and the person tries again.
-The hotspot comes up by itself only while there is no network: at once on a computer not signed in
-yet (just installed or reset), screen or not, beside the screen's own Wi-Fi page; on one signed in,
-only with no screen and after a long outage (a new router). While nobody is on it, saved Wi-Fi is
-tried again every few minutes, so a router that was only off brings the computer back by itself.
-Its name ends in the Wi-Fi card's own address, the same however often the computer is flashed.
+A computer not signed in yet (just installed, reset, or signed out) hosts the hotspot from the moment
+it starts, screen or not, network or not: on Wi-Fi it leaves it for the hotspot, and on a cable the
+two run side by side and the phone only signs it in. The hotspot goes once the computer is signed
+in, from the phone or at the screen, and while someone who typed the computer's password at its
+screen has its Wi-Fi page open (network.py SETUP_SCREEN). One signed in hosts it only with no screen
+and after a long outage (a new router); while nobody is on it then, saved Wi-Fi is tried again every
+few minutes, so a router that was only off brings the computer back by itself. Its name ends in the
+Wi-Fi card's own address, the same however often the computer is flashed.
The hotspot has no password, for setup to be one tap: whoever is in range of a computer in setup
can choose its Wi-Fi, and the Wi-Fi password crosses an open network. Nothing here runs a command
@@ -35,15 +38,21 @@ import subprocess
import sys
import threading
import time
+import urllib.request
import uuid
STATE = Path('/var/lib/harness-os')
RESULT = STATE / 'setup-result.json'
NOW = Path('/run/harness-os/setup-now')
-# What the radio saw before hosting the hotspot, for the screen's Wi-Fi page (network.py SETUP_NETWORKS).
-SCREEN_NETWORKS = Path('/run/harness-os/setup-networks.json')
+# The screen's Wi-Fi page holds the radio while open (network.py SETUP_SCREEN): the pid of that page.
+SCREEN = Path('/run/harness-os/setup-screen')
# Signed in from a phone: its first workspace is OpenCode alone, not with two terminals (onboarding.py).
FROM_PHONE = STATE / 'set-up-from-phone'
+# A phone's Wi-Fi and sign-in, sent with the computer's password as it started (unlock/http): /run
+# outlives the switch from its startup to the system, and nothing of it reaches the disk.
+PHONE_SETUP = Path('/run/harness-os/phone-setup.json')
+# How long the Wi-Fi card may take to appear in NetworkManager as the system starts.
+DEVICE_WAIT = 30
HEADLESS = Path('/etc/harness-os/headless')
DRM = Path('/sys/class/drm')
USER = 'me'
@@ -57,8 +66,6 @@ PROTOCOL = 1
# Signed in with no screen: saved Wi-Fi gets this long to come back before the hotspot takes the radio.
OFFLINE_AT_START = 60
OFFLINE_LATER = 600
-# Not signed in, with saved Wi-Fi: this long for it to come back as the computer starts.
-SAVED_GRACE = 15
# With nobody on the hotspot, saved Wi-Fi is tried again this often, for this long.
RETRY_SAVED = 300
SAVED_JOIN = 45
@@ -74,6 +81,7 @@ MESSAGES = {
'NO_ADDRESS': 'Joined "{ssid}", but the router gave no address. Restart the router and try again.',
'TIMEOUT': 'Joining "{ssid}" took too long. Move the device closer to the router and try again.',
'NO_INTERNET': 'Joined "{ssid}", but it does not reach the Internet. A sign-in page or a firewall may be in the way.',
+ 'NO_INTERNET_WIRED': 'This computer is on a cable, but it does not reach the Internet. Check the cable or choose a Wi-Fi.',
'WIFI': 'Could not join "{ssid}". Try again.',
}
@@ -357,6 +365,10 @@ def sign_in(ticket):
ok, message = run_sign_in(ticket)
if not ok:
FROM_PHONE.unlink(missing_ok=True)
+ return ok, message
+ # Online in the account only with its daemon running, and nobody may ever sign in at a screen
+ # to start a session (one with no encryption asks for its password there first): started here.
+ as_user('systemctl', '--user', 'start', 'harness-daemon', timeout=150)
return ok, message
@@ -382,16 +394,21 @@ def run_sign_in(ticket):
def join(request, networks, device):
- """Leave the hotspot for the person's Wi-Fi. Returns the result the phone reads."""
- ssid, password, ticket = request['ssid'], request.get('password') or '', request.get('ticket')
- seen = next((row for row in networks if row['ssid'] == ssid), None)
- security = seen['security'] if seen else ('WPA2' if password else '')
- log(f'joining "{ssid}"')
+ """Leave the hotspot for the person's Wi-Fi, or with no Wi-Fi named (on a cable), only sign in.
+ Returns the result the phone reads."""
+ ssid, password, ticket = request.get('ssid') or '', request.get('password') or '', request.get('ticket')
started = time.monotonic()
- failed = connect(ssid, password, security, device)
- if not failed and not internet():
- forget(ssid)
- failed = 'NO_INTERNET'
+ if not ssid:
+ log('signing in on the cable')
+ failed = None if internet() else 'NO_INTERNET_WIRED'
+ else:
+ seen = next((row for row in networks if row['ssid'] == ssid), None)
+ security = seen['security'] if seen else ('WPA2' if password else '')
+ log(f'joining "{ssid}"')
+ failed = connect(ssid, password, security, device)
+ if not failed and not internet():
+ forget(ssid)
+ failed = 'NO_INTERNET'
if failed:
log(f'"{ssid}" failed after {int(time.monotonic() - started)}s: {failed}')
return dict(state='failed', error=failed, ssid=ssid, message=MESSAGES[failed].format(ssid=ssid))
@@ -404,11 +421,15 @@ def join(request, networks, device):
return dict(state='done', ssid=ssid, signedIn=signed_in())
-def check_request(body):
+def check_request(body, wired=False):
+ """[wired]: on a cable already, so a ticket alone signs in without a Wi-Fi."""
if not isinstance(body, dict):
return 'Send a JSON object.'
ssid, password, ticket = body.get('ssid'), body.get('password'), body.get('ticket')
- if not isinstance(ssid, str) or not ssid or len(ssid.encode()) > 32:
+ if wired and ssid in (None, '') and not password:
+ if not ticket:
+ return 'Sign in from the phone to set this computer up.'
+ elif not isinstance(ssid, str) or not ssid or len(ssid.encode()) > 32:
return 'Choose a Wi-Fi network.'
if password not in (None, ''):
if not isinstance(password, str) or '\n' in password or '\r' in password:
@@ -428,8 +449,9 @@ class Setup:
self.requests = queue.Queue()
def info(self):
+ # online: on a cable beside the hotspot (the radio hosts it), so the phone skips the Wi-Fi.
return dict(protocol=PROTOCOL, name=socket.gethostname(), hotspot=self.name, run=self.run,
- computerId=computer_id(), signedIn=signed_in(), result=read_result())
+ computerId=computer_id(), signedIn=signed_in(), online=online(), result=read_result())
def handler(self):
setup = self
@@ -464,7 +486,7 @@ class Setup:
body = json.loads(self.rfile.read(min(length, 16384)) or b'{}')
except ValueError:
return self.reply(400, dict(error='BAD_REQUEST', message='Send a JSON object.'))
- problem = check_request(body)
+ problem = check_request(body, wired=online())
if problem:
return self.reply(400, dict(error='BAD_REQUEST', message=problem))
if not setup.requests.empty():
@@ -500,75 +522,89 @@ def saved_comes_back(device):
def setup_mode(device, asked=False):
- """Hotspot until the phone sends a Wi-Fi that works, or saved Wi-Fi comes back.
-
- Saved Wi-Fi is tried again only for a computer signed in that lost its network (a router that
- was off). One not signed in still needs the phone, and one [asked] for setup by hand was taken
- off its Wi-Fi on purpose: both keep the hotspot until somebody uses it."""
- may_leave = not asked and signed_in()
+ """Hotspot until the phone sends a Wi-Fi that works (or, on a cable, signs the computer in), the
+ computer is signed in at its screen, or someone at the screen opens its Wi-Fi page.
+
+ Signed in, the computer lost its network (a router that was off): saved Wi-Fi is tried again,
+ and a cable plugged in ends it. One not signed in still needs the phone, and one [asked] for
+ setup by hand was taken off its Wi-Fi on purpose: both keep the hotspot until somebody uses it."""
+ was_signed_in = signed_in()
+ may_leave = not asked and was_signed_in
name = hotspot_name(device)
+ # Scanned before the radio becomes the hotspot: it cannot scan while hosting one.
networks = visible_networks(name)
- try:
- while True:
- if not start_hotspot(device, name):
- return False
- # The screen's Wi-Fi page lists these while the radio hosts the hotspot (network.py).
- show_networks(networks, device)
- run = int(read_result().get('run') or 0)
- log(f'hotspot "{name}" is up with {len(networks)} networks to offer')
- setup = Setup(name, networks, run)
- try:
- server = serve(setup)
- except OSError as error:
- log(f'could not answer on {ADDRESS}:{PORT}: {error}')
- stop_hotspot()
- return False
- request, idle_since, elsewhere = None, time.monotonic(), None
- while request is None:
- try:
- request = setup.requests.get(timeout=5)
- except queue.Empty:
- # Someone at the screen took the radio for a Wi-Fi (network.py): joined, or not.
- if not hotspot_up():
- elsewhere = online()
- break
- # Online another way meanwhile (a cable plugged in): the hotspot has no use.
- if online():
- elsewhere = True
- break
- if phones_on(device):
- idle_since = time.monotonic()
- elif may_leave and time.monotonic() - idle_since >= RETRY_SAVED and saved_wifi():
- break
- if request is not None:
- run += 1
- write_result(state='connecting', ssid=request['ssid'], run=run)
- # Let the phone read its answer before the hotspot goes.
- time.sleep(2)
- server.shutdown()
- server.server_close()
+ while True:
+ if screen_here():
+ return False
+ if not start_hotspot(device, name):
+ return False
+ run = int(read_result().get('run') or 0)
+ log(f'hotspot "{name}" is up with {len(networks)} networks to offer')
+ setup = Setup(name, networks, run)
+ try:
+ server = serve(setup)
+ except OSError as error:
+ log(f'could not answer on {ADDRESS}:{PORT}: {error}')
stop_hotspot()
- if elsewhere is not None:
- if elsewhere or wait_online(SAVED_JOIN):
- log('joined a Wi-Fi from the screen')
- return True
- # Their Wi-Fi failed: the hotspot comes back for the phone.
- continue
- if request is None:
- log('nobody is on the hotspot; trying saved Wi-Fi')
- if saved_comes_back(device):
- log('saved Wi-Fi is back')
- return True
- networks = visible_networks(name) or networks
- continue
- result = join(request, networks, device)
- write_result(run=run, **result)
- if result['state'] == 'done':
+ return False
+ request, idle_since, left = None, time.monotonic(), None
+ while request is None:
+ try:
+ request = setup.requests.get(timeout=5)
+ except queue.Empty:
+ # Someone typed this computer's password at its screen and opened its Wi-Fi page
+ # (network.py): the radio is theirs while it is open.
+ if screen_here():
+ left = 'screen'
+ break
+ # Signed in meanwhile at the screen (on a cable): nothing left to set up.
+ if not was_signed_in and signed_in():
+ left = 'signed in'
+ break
+ if not hotspot_up():
+ left = 'gone'
+ break
+ # Signed in, online another way meanwhile (a cable plugged in): the hotspot has no
+ # use. Not signed in, it stays for the phone, which signs in over that cable.
+ if may_leave and online():
+ left = 'online'
+ break
+ if phones_on(device):
+ idle_since = time.monotonic()
+ elif may_leave and time.monotonic() - idle_since >= RETRY_SAVED and saved_wifi():
+ break
+ if request is not None:
+ run += 1
+ write_result(state='connecting', ssid=request.get('ssid') or '', run=run)
+ # Let the phone read its answer before the hotspot goes.
+ time.sleep(2)
+ server.shutdown()
+ server.server_close()
+ stop_hotspot()
+ if left in ('signed in', 'online'):
+ log(f'{left}; the hotspot goes')
+ return True
+ if left == 'screen':
+ log('the screen took the radio for its Wi-Fi page')
+ return online()
+ if left == 'gone':
+ # Taken down by something else: back up, unless that brought the network.
+ if online() or wait_online(SAVED_JOIN):
+ return True
+ continue
+ if request is None:
+ log('nobody is on the hotspot; trying saved Wi-Fi')
+ if saved_comes_back(device):
+ log('saved Wi-Fi is back')
return True
- # Back to the hotspot with the reason; the list may have changed meanwhile.
networks = visible_networks(name) or networks
- finally:
- SCREEN_NETWORKS.unlink(missing_ok=True)
+ continue
+ result = join(request, networks, device)
+ write_result(run=run, **result)
+ if result['state'] == 'done':
+ return True
+ # Back to the hotspot with the reason; the list may have changed meanwhile.
+ networks = visible_networks(name) or networks
def hotspot_up():
@@ -584,13 +620,17 @@ def wait_online(seconds):
return online()
-def show_networks(networks, device):
- """For the screen's Wi-Fi page (network.py), which cannot scan while the radio hosts the hotspot."""
- try:
- SCREEN_NETWORKS.parent.mkdir(parents=True, exist_ok=True)
- SCREEN_NETWORKS.write_text(json.dumps([dict(row, device=device) for row in networks]))
- except OSError:
- pass
+def screen_here():
+ """Whether someone at the screen holds the radio (network.py SETUP_SCREEN): they typed this
+ computer's password there and opened its Wi-Fi page. Held until the computer is signed in, so
+ the hotspot does not take the Wi-Fi chosen there while they sign in at the screen; the page
+ lets it go when left alone a while, for a phone."""
+ if not SCREEN.exists():
+ return False
+ if signed_in():
+ SCREEN.unlink(missing_ok=True)
+ return False
+ return True
def asked_now():
@@ -611,38 +651,85 @@ def headless():
for status in DRM.glob('card*-*/status') if status.is_file())
-def offline_wait(now, started):
- """How long this computer must be offline before its hotspot opens; None: never by itself.
+def hotspot_wait(now, started):
+ """How long this computer must stay as it is now before its hotspot opens; None: not now.
- Not signed in (just installed, or reset), screen or not: at once, for setup from a phone beside
- the screen's own Wi-Fi page, which lists the Wi-Fi seen before the hotspot and takes the radio
- back for one chosen there. Saved Wi-Fi gets a moment to come back first, as it does at boot.
- Signed in: a computer with no screen after a long outage (a new router); one with a screen keeps
- its Wi-Fi page, as a laptop away from its network should."""
+ Not signed in (just installed, reset or signed out), screen or not, network or not: at once,
+ for setup from a phone; on Wi-Fi it leaves it for the hotspot. Not while someone at the screen
+ has its Wi-Fi page open. Signed in: only offline, and only a computer with no screen, after a
+ long outage (a new router); one with a screen keeps its Wi-Fi page, as a laptop away from its
+ network should."""
+ if screen_here():
+ return None
if not signed_in():
- return SAVED_GRACE if saved_wifi() and now - started < SAVED_GRACE + 5 else 0
- if not headless():
+ return 0
+ if online() or not headless():
return None
return OFFLINE_AT_START if now - started < OFFLINE_AT_START + 5 else OFFLINE_LATER
+def signed_in_account():
+ """The account this computer is signed in to: the session's `signInAcct` (cli recordSignInAccount)."""
+ try:
+ return json.loads(SESSION.read_text()).get('signInAcct')
+ except (OSError, ValueError, AttributeError):
+ return None
+
+
+def set_up_as_unlocked():
+ """The rest of a phone's setup, sent with the computer's password while its disk was locked
+ (unlock/http, protocol 2): the Wi-Fi, its password, the sign-in ticket and the phone's account.
+ Joined and signed in as the system starts — the phone never comes back to a second hotspot. Every
+ time, set up before or not: the Wi-Fi given is joined, and an account other than the phone's is
+ signed out for it. One that fails leaves its reason for the hotspot that follows (watch)."""
+ try:
+ request = json.loads(PHONE_SETUP.read_text())
+ except (OSError, ValueError):
+ return
+ finally:
+ PHONE_SETUP.unlink(missing_ok=True)
+ run = int(read_result().get('run') or 0) + 1
+ # The radio comes up a moment after NetworkManager.
+ deadline = time.monotonic() + DEVICE_WAIT
+ while not (device := wifi_device()) and time.monotonic() < deadline:
+ time.sleep(1)
+ ssid = request.get('ssid') if isinstance(request, dict) else None
+ problem = check_request(request, wired=not ssid and online())
+ if problem:
+ log('the phone\'s setup at the unlock: ' + problem)
+ write_result(run=run, state='failed', error='BAD_REQUEST', message=problem)
+ return
+ if ssid and not device:
+ write_result(run=run, state='failed', error='WIFI', ssid=ssid, message='This computer has no Wi-Fi.')
+ return
+ account = request.get('account')
+ if signed_in() and isinstance(account, str) and account and account != signed_in_account():
+ # The phone's account, in place of the one it was signed in to: a sign-out, then its sign-in.
+ log('signed in to another account than the phone\'s: signing out')
+ as_user('/usr/bin/harness', 'logout', timeout=60)
+ security = request.get('security')
+ networks = [dict(ssid=ssid, security=security)] if ssid and isinstance(security, str) else []
+ log('setting up as the phone asked at the unlock')
+ write_result(run=run, **join(request, networks, device))
+
+
def watch():
- started, offline_since = time.monotonic(), None
+ started, waiting_since = time.monotonic(), None
while True:
now = time.monotonic()
forced = asked_now()
- wait = None if forced else offline_wait(now, started)
- if (online() or wait is None) and not forced:
- offline_since = None
+ wait = 0 if forced else hotspot_wait(now, started)
+ if wait is None:
+ waiting_since = None
else:
- offline_since = offline_since or now
+ waiting_since = waiting_since or now
device = wifi_device()
- if device and (forced or now - offline_since >= wait):
+ if device and now - waiting_since >= wait:
if forced:
# Asked for by hand: leave the current Wi-Fi so the radio can host the hotspot.
nmcli('device', 'disconnect', device)
setup_mode(device, asked=forced)
- offline_since = None
+ waiting_since = None
time.sleep(5)
@@ -684,6 +771,8 @@ def change(request):
HN = '/usr/lib/harness/harness-tui'
+# The account's daemon on this computer (cli hookServer), for the desk.
+DAEMON = 'http://127.0.0.1:18473'
RESET_UNIT = 'harness-factory-reset'
@@ -713,26 +802,80 @@ def wipe(folder, keep):
path.unlink(missing_ok=True)
-def factory_reset(keep_wifi=False):
+def desk_ops(ops=None):
+ """The account's desk through the local daemon (its /api/desk proxy, signed in as this computer):
+ read it, or with [ops] write them. The answer's tabs, or None."""
+ request = urllib.request.Request(DAEMON + ('/api/desk/ops' if ops else '/api/desk'),
+ data=json.dumps({'ops': ops}).encode() if ops else None,
+ headers={'Content-Type': 'application/json', 'X-Adapter-Local': '1'},
+ method='POST' if ops else 'GET')
+ try:
+ with urllib.request.urlopen(request, timeout=15) as response:
+ body = json.loads(response.read())
+ except (OSError, ValueError):
+ return None
+ body = body.get('data', body) if isinstance(body, dict) else None
+ return body.get('tabs') if isinstance(body, dict) and isinstance(body.get('tabs'), list) else None
+
+
+def forget_desk():
+ """This computer's tabs and panes off the account's desk, which every computer shows: closing its
+ windows alone was raced by the sign-out, and they came back at the next sign-in. A tab of its own
+ goes; one shared with other computers keeps theirs."""
+ status = as_user('/usr/bin/harness', 'auth', 'status', '--json')
+ try:
+ machine = json.loads(status.stdout).get('machineId') if status else None
+ except ValueError:
+ machine = None
+ tabs = desk_ops() if machine else None
+ ops = []
+ for tab in tabs or []:
+ panes = [pane for pane in tab.get('panes') or [] if isinstance(pane, dict)]
+ mine = [pane for pane in panes if pane.get('machineId') == machine]
+ if mine and len(mine) == len(panes):
+ ops.append({'op': 'tab.close', 'id': tab.get('id')})
+ else:
+ ops += [{'op': 'pane.remove', 'tabId': tab.get('id'), 'machineId': machine,
+ 'agentId': pane.get('agentId')} for pane in mine]
+ if ops and desk_ops(ops) is None:
+ log('factory reset: the desk kept some tabs of this computer')
+
+
+def factory_reset(keep_wifi=False, keep_workspace=False):
"""This computer as it was just flashed: no account, no harnesses, the first workspace still to come,
and (unless [keep_wifi]) no Wi-Fi, so it opens its setup hotspot for a phone. It stays the same
computer: its id and its device key are kept, as a new key for the same computer is refused by the
account until the old one is removed. The engines' own sign-ins and ~/projects are the person's.
+ Its workspace goes too — hn's tabs and panes, here and on the account's desk, and what hn keeps
+ (~/.harness/tui) — unless [keep_workspace].
For the reset button and `harness factory-reset`."""
- log('factory reset')
- # Its windows first, while still signed in: the account keeps the tabs (the desk, the same on
- # every computer), and one left there comes back at the next sign-in in the first workspace's place.
- windows = as_user(HN, 'list-windows', '-F', '#{window_index}')
- for index in sorted((int(n) for n in (windows.stdout.split() if windows else []) if n.isdigit()), reverse=True):
- as_user(HN, 'kill-window', '-t', f':{index}')
+ log('factory reset' + (', keeping the workspace' if keep_workspace else ''))
+ if not keep_workspace:
+ # While still signed in: the account keeps the tabs (the desk, the same on every computer),
+ # and one left there comes back at the next sign-in in the first workspace's place.
+ forget_desk()
+ windows = as_user(HN, 'list-windows', '-F', '#{window_index}')
+ for index in sorted((int(n) for n in (windows.stdout.split() if windows else []) if n.isdigit()), reverse=True):
+ as_user(HN, 'kill-window', '-t', f':{index}')
as_user('/usr/bin/harness', 'logout', timeout=60)
+ if not keep_workspace:
+ # hn before its files: it writes its tabs out as it ends, and wrote the old ones back.
+ as_user(HN, 'kill-server')
+ subprocess.run(['/usr/bin/pkill', '-u', USER, '-x', 'harness-tui'], capture_output=True)
+ try:
+ shutil.rmtree(f'/tmp/hn-{pwd.getpwnam(USER).pw_uid}', ignore_errors=True)
+ except KeyError:
+ pass
# Every harness and terminal: the daemon, then the tmux server its panes run in.
as_user('systemctl', '--user', 'stop', 'harness-daemon', timeout=60)
as_user('tmux', 'kill-server')
harness = HOME / '.harness'
- wipe(harness, {'computer-id': True, 'cli': {'data': {'e2e': True}}})
+ keep = {'computer-id': True, 'cli': {'data': {'e2e': True}}}
+ if keep_workspace:
+ keep['tui'] = True
+ wipe(harness, keep)
(HOME / '.local/state/harness-os/onboarded').unlink(missing_ok=True)
- for path in (RESULT, FROM_PHONE):
+ for path in (RESULT, FROM_PHONE, SCREEN):
path.unlink(missing_ok=True)
as_user('systemctl', '--user', 'start', 'harness-daemon', timeout=60)
# hn again from its sign-in page. Its server outlives the screen unit (KillMode=process).
@@ -753,11 +896,13 @@ def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('command', nargs='?', choices=['watch', 'now', 'name', 'join', 'reset'], default='watch')
parser.add_argument('--keep-wifi', action='store_true', help='reset: keep the saved Wi-Fi')
+ parser.add_argument('--keep-workspace', action='store_true',
+ help="reset: keep hn's tabs and panes, here and on the account's desk")
parser.add_argument('--here', action='store_true', help=argparse.SUPPRESS)
arguments = parser.parse_args()
if arguments.command == 'reset':
if arguments.here:
- factory_reset(keep_wifi=arguments.keep_wifi)
+ factory_reset(keep_wifi=arguments.keep_wifi, keep_workspace=arguments.keep_workspace)
return
# In a unit of its own: the computer leaves its Wi-Fi, and whatever asked (an SSH session, the
# button's handler) may go with it before the reset is done. `journalctl -u harness-factory-reset`.
@@ -765,10 +910,13 @@ def main():
'/usr/bin/python3', str(Path(__file__).resolve()), 'reset', '--here']
if arguments.keep_wifi:
command.append('--keep-wifi')
+ if arguments.keep_workspace:
+ command.append('--keep-workspace')
started = subprocess.run(command, capture_output=True, text=True)
if started.returncode:
raise SystemExit('Could not start the reset: ' + (started.stderr.strip() or 'systemd-run failed'))
print('Resetting this computer. It signs out, closes every harness'
+ + ('' if arguments.keep_workspace else ', forgets its tabs')
+ ('' if arguments.keep_wifi else ', forgets its Wi-Fi')
+ ' and opens its setup hotspot for a phone in about a minute.')
return
@@ -788,6 +936,7 @@ def main():
if arguments.command == 'name':
print(hotspot_name())
return
+ set_up_as_unlocked()
log(f'watching; hotspot "{hotspot_name()}" when there is no network')
watch()
diff --git a/os/tests/setup_hotspot_vm.py b/os/tests/setup_hotspot_vm.py
new file mode 100644
index 000000000..bb62d0ff2
--- /dev/null
+++ b/os/tests/setup_hotspot_vm.py
@@ -0,0 +1,162 @@
+#!/usr/bin/env python3
+"""A Harness not signed in hosts its setup hotspot as it starts, network or not, and gives the
+radio to someone at its screen.
+
+The image installs (unencrypted, so nobody types a disk password) in a VM with two simulated Wi-Fi
+radios (mac80211_hwsim): the computer's card, and a "phone" in a network namespace of its own.
+
+ python3 tests/setup_hotspot_vm.py --iso dist/harness-dev-….iso [--output folder]
+"""
+import argparse
+import base64
+import json
+import re
+from pathlib import Path
+import shlex
+import sys
+import time
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from vm import VM # noqa: E402
+
+PASSWORD = 'harness'
+
+
+def put(vm, path, text, mode='644'):
+ data = base64.b64encode(text.encode()).decode()
+ vm.command(f': > {shlex.quote(path)}.b64')
+ for start in range(0, len(data), 1500):
+ vm.command(f"printf %s {shlex.quote(data[start:start + 1500])} >> {shlex.quote(path)}.b64")
+ vm.command(f'base64 -d {shlex.quote(path)}.b64 > {shlex.quote(path)} && rm {shlex.quote(path)}.b64 && chmod {mode} {shlex.quote(path)}')
+
+
+def root(command):
+ return f'printf %s\\\\n {shlex.quote(PASSWORD)} | sudo -S -p "" sh -c {shlex.quote(command)}'
+
+
+def until(vm, condition, seconds, what):
+ """[condition], a shell test run as root, true within [seconds]."""
+ _, status = vm.command(root(f'for n in $(seq {seconds}); do {condition} && exit 0; sleep 1; done; exit 1'),
+ timeout=seconds + 30, check=False)
+ if status:
+ raise AssertionError(what)
+
+
+HOTSPOT_UP = "nmcli -t -f NAME connection show --active | grep -qx harness-setup"
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument('--iso', required=True, type=Path)
+ parser.add_argument('--output', type=Path)
+ parser.add_argument('--memory', type=int, default=4096)
+ parser.add_argument('--video', choices=['virtio-vga', 'VGA'], default='virtio-vga')
+ args = parser.parse_args()
+ folder = (args.output or Path.cwd() / 'setup-hotspot-vm-results').resolve()
+ folder.mkdir(parents=True, exist_ok=False)
+ result = dict(iso=str(args.iso), checks=[], status='running', started_at_unix=time.time())
+ vm = VM(folder, args.iso.resolve(), 'bios', args.memory, video=args.video)
+ try:
+ vm.start(live=True)
+ vm.monitor('set_link', name='hnnet', up=False)
+ vm.wait(r'root@[^\r\n]*[#] ', timeout=300)
+ vm.shell_ready = True
+ vm.command('stty -echo')
+ vm.command('nmcli networking off')
+ config = dict(disk='/dev/vda', expected_serial='HN_OS_TEST', confirm_erase='/dev/vda', username='me', hostname='harness',
+ password=PASSWORD, encrypt=False, serial_console=True)
+ put(vm, '/run/hn-config.json', json.dumps(config), '600')
+ vm.command('python3 /usr/lib/harness-os/install.py --config /run/hn-config.json --yes-erase-disk '
+ '> /run/hn-install.log 2>&1 || { tail -40 /run/hn-install.log; exit 1; }', timeout=2400)
+ result['checks'].append('Unattended unencrypted installation')
+ vm.command('mount -o subvol=@ /dev/vda3 /mnt')
+ getty, _ = vm.command('cat /mnt/etc/systemd/system/[email protected]/password.conf')
+ assert "--login-options '-p -- me'" in getty, getty
+ result['checks'].append('The screen asks only the password of the one account')
+ put(vm, '/mnt/etc/modules-load.d/hwsim.conf', 'mac80211_hwsim\n')
+ put(vm, '/mnt/etc/modprobe.d/hwsim.conf', 'options mac80211_hwsim radios=2\n')
+ vm.command('sync; umount /mnt')
+ vm.stop()
+
+ vm.start(live=False)
+ # No cable yet: the computer starts offline.
+ vm.monitor('set_link', name='hnnet', up=False)
+ vm.wait(r'login:', timeout=400)
+ vm.send('me\n')
+ vm.wait(r'Password:')
+ vm.send(PASSWORD + '\n')
+ vm.wait(r'\$ ')
+ vm.shell_ready = True
+ vm.command('stty -echo')
+
+ # Not signed in, no network: the hotspot as it starts.
+ until(vm, HOTSPOT_UP, 90, 'No setup hotspot on a computer not signed in')
+ name, _ = vm.command('/usr/bin/python3 /usr/lib/harness-os/setup.py name')
+ result['hotspot'] = re.findall(r'Harness-[A-Za-z0-9]+', name)[-1]
+ result['checks'].append('Not signed in, the hotspot is up as the computer starts')
+
+ # The phone: the other radio, in its own namespace, on the hotspot.
+ phone = ('ap=$(nmcli -t -f DEVICE,CONNECTION device | grep ":harness-setup$" | cut -d: -f1); '
+ 'for d in /sys/class/net/*; do [ -d $d/wireless ] && [ ${d##*/} != "$ap" ] && dev=${d##*/}; done; '
+ 'phy=$(cat /sys/class/net/$dev/phy80211/name); ip netns add phone; iw phy $phy set netns name phone; '
+ 'ip netns exec phone ip link set lo up; ip netns exec phone ip link set $dev up; '
+ f'printf "network={{\\n ssid=\\"{result["hotspot"]}\\"\\n key_mgmt=NONE\\n}}\\n" > /run/phone.conf; '
+ 'ip netns exec phone wpa_supplicant -B -i $dev -c /run/phone.conf; echo $dev > /run/phone-dev')
+ vm.command(root(phone))
+ until(vm, 'ip netns exec phone iw dev $(cat /run/phone-dev) link | grep -q "Connected to"', 40,
+ 'The phone did not join the hotspot')
+ vm.command(root('ip netns exec phone ip addr add 10.42.0.77/24 dev $(cat /run/phone-dev)'))
+ until(vm, 'ip netns exec phone curl -sf -m 5 http://10.42.0.1/setup > /run/setup.json', 30,
+ 'The hotspot page did not answer the phone')
+ info = json.loads(vm.read_file('/run/setup.json'))
+ result['setup_offline'] = info
+ assert info['signedIn'] is False and info['online'] is False and info['hotspot'] == result['hotspot'], info
+ result['checks'].append('The phone joins it over the air and reads it is not signed in and offline')
+
+ # A cable: the hotspot stays for the phone, which now signs in without a Wi-Fi.
+ vm.monitor('set_link', name='hnnet', up=True)
+ until(vm, "nmcli -t -f TYPE,STATE device | grep -q '^ethernet:connected'", 60, 'Ethernet did not connect')
+ time.sleep(15)
+ until(vm, HOTSPOT_UP, 5, 'The hotspot went when a cable came, though not signed in')
+ until(vm, 'ip netns exec phone curl -sf -m 5 http://10.42.0.1/setup > /run/setup.json', 30,
+ 'The page went with the cable')
+ info = json.loads(vm.read_file('/run/setup.json'))
+ assert info['online'] is True, info
+ result['checks'].append('On a cable the hotspot stays, and says online so the phone skips the Wi-Fi')
+
+ # Someone at the screen, offline: the Wi-Fi page takes the radio, and keeps it.
+ vm.monitor('set_link', name='hnnet', up=False)
+ until(vm, "! nmcli -t -f TYPE,STATE device | grep -q '^ethernet:connected'", 60, 'Ethernet did not go')
+ vm.command(root("setsid script -qfc 'python3 /usr/lib/harness-os/network.py --first-use' /run/page.log "
+ '> /dev/null 2>&1 < /dev/null & echo $! > /run/page.pid'))
+ until(vm, f'test -f /run/harness-os/setup-screen && ! {HOTSPOT_UP}', 30,
+ 'The screen\'s Wi-Fi page did not take the radio from the hotspot')
+ time.sleep(20)
+ until(vm, f'! {HOTSPOT_UP}', 3, 'The hotspot came back while the screen holds the radio')
+ page, _ = vm.command(root("cat /run/page.log | tr -d '\\033' | grep -ao 'Connect to Wi-Fi\\|Rescan\\|No Wi-Fi networks found' | sort -u"))
+ result['page'] = page.strip().splitlines()
+ result['checks'].append('The screen\'s Wi-Fi page took the radio from the hotspot, scanned, and kept it')
+ vm.command(root('kill -- -$(cat /run/page.pid); sleep 2'))
+ time.sleep(15)
+ until(vm, f'! {HOTSPOT_UP}', 3, 'The hotspot came back once the page closed, before sign-in')
+ result['checks'].append('Held until signed in: the page gone, the hotspot stays down')
+ # Left alone (what the page does after SCREEN_IDLE): the hotspot comes back for a phone.
+ vm.command(root('rm -f /run/harness-os/setup-screen'))
+ until(vm, HOTSPOT_UP, 40, 'The hotspot did not come back once the screen let the radio go')
+ result['checks'].append('Let go, the hotspot comes back for a phone')
+ result['status'] = 'passed'
+ except BaseException as error:
+ result['status'] = 'failed'
+ result['error'] = repr(error)
+ raise
+ finally:
+ result['finished_at_unix'] = time.time()
+ (folder / 'result.json').write_text(json.dumps(result, indent=2) + '\n')
+ try:
+ vm.stop()
+ except Exception:
+ pass
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tests/test_network.py b/os/tests/test_network.py
index 94c400338..64328f983 100644
--- a/os/tests/test_network.py
+++ b/os/tests/test_network.py
@@ -41,6 +41,7 @@ class Network(unittest.TestCase):
hotspot = patch.object(network, 'setup_hotspot_up', return_value=False)
hotspot.start()
self.addCleanup(hotspot.stop)
+ self.enterContext(patch.object(network, 'hold_radio', return_value=False))
def test_privileged_form_uses_a_fixed_executable_not_the_callers_path(self):
with patch.object(network.subprocess, 'run', return_value=result()) as run:
network.nmcli('general')
@@ -305,25 +306,78 @@ class SetupHotspot(unittest.TestCase):
with patch.object(network, 'nmcli', return_value=result(output='Glinks 1\n')):
self.assertFalse(network.setup_hotspot_up())
- def test_the_list_is_the_one_seen_before_the_hotspot_not_the_hotspot(self):
+ def setUp(self):
import tempfile
- with tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) as handle:
- handle.write('[{"ssid": "Weak", "signal": 30, "security": "WPA2", "device": "wlo1"},'
- ' {"ssid": "Glinks 1", "signal": 80, "security": "WPA2", "device": "wlo1"},'
- ' {"ssid": "Cafe", "signal": 50, "security": "", "device": "wlo1"}, {"bad": 1}]')
- self.addCleanup(Path(handle.name).unlink)
- with patch.object(network, 'SETUP_NETWORKS', handle.name), \
+ folder = tempfile.TemporaryDirectory()
+ self.addCleanup(folder.cleanup)
+ self.held = Path(folder.name) / 'setup-screen'
+ self.enterContext(patch.object(network, 'SETUP_SCREEN', str(self.held)))
+ self.enterContext(patch.object(network.time, 'sleep'))
+
+ def test_the_page_takes_the_radio_from_the_hotspot_before_its_first_scan(self):
+ # Someone typed this computer's password at its screen and is offline: the phone's hotspot
+ # goes, then the radio scans, so the list is a real one.
+ events = []
+ screen = Screen(['\n'])
+ page = network.NetworkPage(screen, first_use=True)
+ with patch.object(network, 'connected', return_value=False), \
patch.object(network, 'setup_hotspot_up', return_value=True), \
- patch.object(network, 'nmcli') as command:
- rows = network.scan(rescan=True)
- command.assert_not_called()
- self.assertEqual([row['ssid'] for row in rows], ['Glinks 1', 'Cafe', 'Weak'])
- self.assertEqual(rows[1]['security'], '--')
- self.assertFalse(any(row['active'] for row in rows))
-
- def test_no_list_is_an_empty_one(self):
- with patch.object(network, 'SETUP_NETWORKS', '/nonexistent/setup-networks.json'):
- self.assertEqual(network.setup_networks(), [])
+ patch.object(network, 'wired_devices', return_value=[]), \
+ patch.object(network, 'connect', return_value=True), \
+ patch.object(network, 'nmcli', side_effect=lambda *a, secret=None, wait=8: events.append(a) or result()), \
+ patch.object(network, 'scan', side_effect=lambda rescan=None: events.append(('scan', rescan)) or [WIFI]):
+ self.assertEqual(page.run(), 0)
+ down = events.index(('connection', 'down', 'id', 'harness-setup'))
+ self.assertLess(down, events.index(('scan', True)))
+ # Still held once done: the Wi-Fi chosen here stays while they sign in at the screen.
+ self.assertTrue(self.held.exists())
+
+ def test_a_page_left_alone_lets_the_hotspot_back_until_a_key(self):
+ screen = Screen([])
+ page = network.NetworkPage(screen, first_use=True)
+ now = [0]
+ keys = iter([curses.error, curses.error, 'x', '\n'])
+
+ def key():
+ value = next(keys)
+ if value is curses.error:
+ # Nobody at the keyboard: time passes.
+ now[0] += network.SCREEN_IDLE
+ raise curses.error
+ return value
+
+ held = []
+ with patch.object(network, 'connected', return_value=False), \
+ patch.object(network, 'wired_devices', return_value=[]), \
+ patch.object(network, 'nmcli', return_value=result()), \
+ patch.object(network, 'scan', return_value=[WIFI]), \
+ patch.object(network, 'connect', side_effect=lambda *a: held.append(self.held.exists()) or True), \
+ patch.object(network, 'release_radio', wraps=network.release_radio) as release, \
+ patch.object(network.time, 'monotonic', side_effect=lambda: now[0]), \
+ patch.object(screen, 'get_wch', side_effect=key):
+ self.assertEqual(page.run(), 0)
+ release.assert_called_once()
+ # The key after it took the radio back; the next one chose the Wi-Fi, holding it.
+ self.assertEqual(held, [True])
+ self.assertIn('A phone can set this computer up now', '\n'.join(text for _, text in screen.lines))
+
+ def test_a_computer_a_phone_unlocked_leaves_it_the_radio_until_a_key(self):
+ # The disk opened from a phone: the screen's session started by itself, nobody at it. The
+ # phone sets the Wi-Fi up on setup.py's hotspot; a key here still takes the radio.
+ screen = Screen(['x', '\n'])
+ page = network.NetworkPage(screen, first_use=True)
+ held = []
+ with patch.object(network, 'phone_unlocked', return_value=True), \
+ patch.object(network, 'connected', return_value=False), \
+ patch.object(network, 'wired_devices', return_value=[]), \
+ patch.object(network, 'nmcli', return_value=result()), \
+ patch.object(network, 'scan', return_value=[WIFI]), \
+ patch.object(network, 'hold_radio', wraps=network.hold_radio) as hold, \
+ patch.object(network, 'connect', side_effect=lambda *a: held.append(self.held.exists()) or True):
+ self.assertEqual(page.run(), 0)
+ hold.assert_called_once()
+ self.assertEqual(held, [True])
+ self.assertIn('A phone can set this computer up now', '\n'.join(text for _, text in screen.lines))
def test_the_hotspot_alone_is_not_online(self):
with patch.object(network, 'nmcli', return_value=result(output='connected (local only)')), \
@@ -335,6 +389,27 @@ class SetupHotspot(unittest.TestCase):
patch.object(network, 'wired_devices', return_value=[['ens5', 'ethernet', 'connected']]):
self.assertTrue(network.connected())
+ def test_an_empty_list_just_after_starting_is_scanned_at_once(self):
+ # Unlocked at the keyboard after a reset: no hotspot to leave, and NetworkManager's recent
+ # list is still empty. The page scans now rather than showing nothing until Rescan.
+ screen = Screen(['\n'])
+ page = network.NetworkPage(screen, first_use=True)
+ scans = []
+
+ def scan(rescan=None):
+ scans.append(rescan)
+ return [] if len(scans) == 1 else [WIFI]
+
+ with patch.object(network, 'phone_unlocked', return_value=False), \
+ patch.object(network, 'hold_radio', return_value=False), \
+ patch.object(network, 'connected', return_value=False), \
+ patch.object(network, 'wired_devices', return_value=[]), \
+ patch.object(network, 'nmcli', return_value=result()), \
+ patch.object(network, 'scan', side_effect=scan), \
+ patch.object(network, 'connect', return_value=True):
+ self.assertEqual(page.run(), 0)
+ self.assertEqual(scans[:2], [None, True])
+
def test_choosing_a_network_on_screen_takes_the_radio_back_first(self):
calls = []
with patch.object(network, 'setup_hotspot_up', return_value=True), \
diff --git a/os/tests/test_setup.py b/os/tests/test_setup.py
index cf5bccb3f..de476ff16 100644
--- a/os/tests/test_setup.py
+++ b/os/tests/test_setup.py
@@ -1,3 +1,4 @@
+import contextlib
import importlib.util
import json
from pathlib import Path
@@ -200,18 +201,74 @@ class Change(unittest.TestCase):
self.assertEqual(setup.read_result()['error'], 'BAD_REQUEST')
+class SetUpAsUnlocked(unittest.TestCase):
+ """What a phone sent with the computer's password while its disk was locked (unlock/http)."""
+
+ def run_it(self, request, signed_in=False, account='u-1'):
+ with tempfile.TemporaryDirectory() as folder:
+ folder = Path(folder)
+ sent = folder / 'phone-setup.json'
+ if request is not None:
+ sent.write_text(json.dumps(request))
+ session = folder / 'session.json'
+ session.write_text(json.dumps(dict(signInAcct=account)))
+ users = []
+ with patch.object(setup, 'PHONE_SETUP', sent), patch.object(setup, 'SESSION', session), \
+ patch.object(setup, 'STATE', folder), patch.object(setup, 'RESULT', folder / 'r.json'), \
+ patch.object(setup, 'wifi_device', return_value='wlo1'), \
+ patch.object(setup, 'online', return_value=False), \
+ patch.object(setup, 'signed_in', return_value=signed_in), \
+ patch.object(setup, 'as_user', side_effect=lambda *c, timeout=30: users.append(c)), \
+ patch.object(setup, 'join', return_value=dict(state='done', ssid='Glinks', signedIn=True)) as join:
+ setup.set_up_as_unlocked()
+ self.assertFalse(sent.exists(), 'read once, then gone')
+ return join, users, setup.read_result()
+
+ def test_its_wifi_and_ticket_are_joined_as_the_system_starts(self):
+ request = dict(ssid='Glinks', password='wifi pass 1', security='WPA2', ticket='t', account='u-1')
+ join, users, out = self.run_it(request)
+ join.assert_called_once_with(request, [dict(ssid='Glinks', security='WPA2')], 'wlo1')
+ self.assertEqual((out['state'], out['run']), ('done', 1))
+ self.assertEqual(users, [])
+
+ def test_the_same_account_stays_signed_in(self):
+ _, users, _ = self.run_it(dict(ssid='Glinks', password='wifi pass 1', ticket='t', account='u-1'),
+ signed_in=True, account='u-1')
+ self.assertEqual(users, [])
+
+ def test_another_account_is_signed_out_for_the_phones(self):
+ join, users, _ = self.run_it(dict(ssid='Glinks', password='wifi pass 1', ticket='t', account='u-2'),
+ signed_in=True, account='u-1')
+ self.assertEqual(users, [('/usr/bin/harness', 'logout')])
+ join.assert_called_once()
+
+ def test_a_bad_request_is_said_and_joins_nothing(self):
+ join, _, out = self.run_it(dict(ssid='', password='x'))
+ join.assert_not_called()
+ self.assertEqual(out['error'], 'BAD_REQUEST')
+
+ def test_nothing_sent_is_nothing_done(self):
+ join, _, out = self.run_it(None)
+ join.assert_not_called()
+ self.assertEqual(out, {})
+
+
class FromPhone(unittest.TestCase):
def test_the_mark_is_there_before_the_sign_in_and_stays_only_when_it_worked(self):
with tempfile.TemporaryDirectory() as folder:
marker = Path(folder) / 'set-up-from-phone'
- with patch.object(setup, 'FROM_PHONE', marker), patch.object(setup, 'signed_in', return_value=False):
+ with patch.object(setup, 'FROM_PHONE', marker), patch.object(setup, 'signed_in', return_value=False), \
+ patch.object(setup, 'as_user') as as_user:
with patch.object(setup, 'run_sign_in', side_effect=lambda t: (marker.exists(), '')):
self.assertEqual(setup.sign_in('t'), (True, ''))
self.assertTrue(marker.exists())
+ # Online in the account only with its daemon, which no screen session may start.
+ as_user.assert_called_once_with('systemctl', '--user', 'start', 'harness-daemon', timeout=150)
marker.unlink()
with patch.object(setup, 'run_sign_in', return_value=(False, 'used')):
self.assertEqual(setup.sign_in('t'), (False, 'used'))
self.assertFalse(marker.exists())
+ as_user.assert_called_once()
class FactoryReset(unittest.TestCase):
@@ -224,8 +281,9 @@ class FactoryReset(unittest.TestCase):
(home / path).write_text('x')
return home
- def run_reset(self, home, keep_wifi):
+ def run_reset(self, home, keep_wifi, keep_workspace=False):
users, wifi = [], []
+ self.desk = []
state = home / 'state'
state.mkdir()
(state / 'r.json').write_text('{}')
@@ -235,10 +293,40 @@ class FactoryReset(unittest.TestCase):
patch.object(setup, 'as_user', side_effect=lambda *c, timeout=30: users.append(c) or result(output='2\n1\n')), \
patch.object(setup.subprocess, 'run', return_value=result()), \
patch.object(setup, 'rows', return_value=[['u-home', '802-11-wireless'], ['u-lo', 'loopback']]), \
- patch.object(setup, 'nmcli', side_effect=lambda *a, **k: wifi.append(a) or result()):
- setup.factory_reset(keep_wifi=keep_wifi)
+ patch.object(setup, 'nmcli', side_effect=lambda *a, **k: wifi.append(a) or result()), \
+ patch.object(setup, 'forget_desk', side_effect=lambda: users.append(('forget-desk',))):
+ setup.factory_reset(keep_wifi=keep_wifi, keep_workspace=keep_workspace)
return users, wifi, state
+ def test_its_tabs_leave_the_desk_before_the_sign_out_and_hn_before_its_files(self):
+ with tempfile.TemporaryDirectory() as folder:
+ users, _, _ = self.run_reset(self.home(folder), keep_wifi=False)
+ logout = next(i for i, c in enumerate(users) if 'logout' in c)
+ self.assertLess(users.index(('forget-desk',)), logout)
+ # hn ends before the files go: it writes its tabs out as it ends.
+ kill = next(i for i, c in enumerate(users) if 'kill-server' in c and setup.HN in c)
+ self.assertLess(logout, kill)
+
+ def test_keep_workspace_keeps_hn_and_the_desk(self):
+ with tempfile.TemporaryDirectory() as folder:
+ home = self.home(folder)
+ users, _, _ = self.run_reset(home, keep_wifi=False, keep_workspace=True)
+ self.assertTrue((home / '.harness/tui/state.json').exists())
+ self.assertFalse((home / '.harness/auth/session.json').exists())
+ self.assertNotIn(('forget-desk',), users)
+ self.assertFalse([c for c in users if 'kill-window' in c])
+
+ def test_the_desk_forgets_this_computer_alone(self):
+ tabs = [{'id': 'own', 'panes': [{'machineId': 'me', 'agentId': 'a'}]},
+ {'id': 'shared', 'panes': [{'machineId': 'me', 'agentId': 'b'}, {'machineId': 'mac', 'agentId': 'c'}]},
+ {'id': 'theirs', 'panes': [{'machineId': 'mac', 'agentId': 'd'}]}]
+ written = []
+ with patch.object(setup, 'as_user', return_value=result(output='{"machineId": "me"}')), \
+ patch.object(setup, 'desk_ops', side_effect=lambda ops=None: written.append(ops) or tabs):
+ setup.forget_desk()
+ self.assertEqual(written[-1], [{'op': 'tab.close', 'id': 'own'},
+ {'op': 'pane.remove', 'tabId': 'shared', 'machineId': 'me', 'agentId': 'b'}])
+
def test_it_is_as_just_flashed_but_the_same_computer(self):
with tempfile.TemporaryDirectory() as folder:
home = self.home(folder)
@@ -274,28 +362,47 @@ class FactoryReset(unittest.TestCase):
self.assertEqual(command[-3:], ['reset', '--here', '--keep-wifi'])
-class Screen(unittest.TestCase):
- def test_a_wifi_chosen_on_the_screen_ends_setup_and_its_list_goes(self):
- class Server:
- def shutdown(self): pass
- def server_close(self): pass
+class Server:
+ def shutdown(self): pass
+ def server_close(self): pass
- with tempfile.TemporaryDirectory() as folder:
- listed = Path(folder) / 'setup-networks.json'
- seen = []
- with patch.object(setup, 'SCREEN_NETWORKS', listed), \
- patch.object(setup, 'visible_networks', return_value=[dict(ssid='Glinks 1', signal=80, security='WPA2')]), \
- patch.object(setup, 'start_hotspot', return_value=True), \
- patch.object(setup, 'serve', return_value=Server()), \
- patch.object(setup, 'read_result', return_value={}), \
- patch.object(setup, 'signed_in', return_value=False), \
- patch.object(setup, 'stop_hotspot'), \
- patch.object(setup, 'hotspot_up', side_effect=lambda: seen.append(json.loads(listed.read_text())) or False), \
- patch.object(setup, 'online', return_value=True), \
- patch.object(setup.queue.Queue, 'get', side_effect=setup.queue.Empty):
- self.assertTrue(setup.setup_mode('wlo1'))
- self.assertEqual(seen[0], [dict(ssid='Glinks 1', signal=80, security='WPA2', device='wlo1')])
- self.assertFalse(listed.exists())
+
+class Screen(unittest.TestCase):
+ def hotspot(self, **checks):
+ """setup_mode with nobody on the hotspot, each check (screen_here, signed_in, online,
+ hotspot_up) as given; returns its result and whether the hotspot went."""
+ values = dict(screen_here=False, signed_in=False, online=False, hotspot_up=True) | checks
+ with contextlib.ExitStack() as stack:
+ for name, value in values.items():
+ stack.enter_context(patch.object(setup, name, side_effect=value) if callable(value)
+ else patch.object(setup, name, return_value=value))
+ stack.enter_context(patch.object(setup, 'visible_networks', return_value=[]))
+ start = stack.enter_context(patch.object(setup, 'start_hotspot', return_value=True))
+ stack.enter_context(patch.object(setup, 'serve', return_value=Server()))
+ stack.enter_context(patch.object(setup, 'read_result', return_value={}))
+ stop = stack.enter_context(patch.object(setup, 'stop_hotspot'))
+ stack.enter_context(patch.object(setup, 'phones_on', return_value=True))
+ stack.enter_context(patch.object(setup, 'wait_online', return_value=False))
+ stack.enter_context(patch.object(setup.queue.Queue, 'get', side_effect=setup.queue.Empty))
+ return setup.setup_mode('wlo1'), start.call_count, stop.called
+
+ def test_the_screens_wifi_page_takes_the_radio(self):
+ # Someone typed the computer's password at its screen and opened its Wi-Fi page.
+ screen = iter([False, True])
+ self.assertEqual(self.hotspot(screen_here=lambda: next(screen)), (False, 1, True))
+
+ def test_signed_in_at_the_screen_the_hotspot_goes(self):
+ signed = iter([False, False, True])
+ self.assertEqual(self.hotspot(signed_in=lambda: next(signed), online=True), (True, 1, True))
+
+ def test_not_signed_in_a_cable_keeps_the_hotspot_for_the_phone(self):
+ # On a cable, the hotspot stays: the phone signs the computer in over it.
+ checks = iter([False, False, False, True])
+ result, starts, _ = self.hotspot(online=True, screen_here=lambda: next(checks))
+ self.assertEqual((result, starts), (True, 1))
+
+ def test_signed_in_a_cable_ends_the_hotspot(self):
+ self.assertEqual(self.hotspot(signed_in=True, online=True), (True, 1, True))
class Machine(unittest.TestCase):
@@ -344,21 +451,48 @@ class Machine(unittest.TestCase):
def test_when_the_hotspot_opens_by_itself(self):
cases = [
- # signed in, headless, saved Wi-Fi, seconds since start → seconds offline first (None: never)
- (False, False, False, 0, 0), # just installed, screen, no Wi-Fi: at once
- (False, True, False, 0, 0), # just installed, no screen: at once
- (False, False, True, 3, setup.SAVED_GRACE), # saved Wi-Fi as it starts: a moment for it
- (False, False, True, 600, 0), # later, still offline: at once
- (True, False, True, 600, None), # signed-in laptop: its Wi-Fi page, never the hotspot
- (True, True, True, 3, setup.OFFLINE_AT_START),
- (True, True, True, 600, setup.OFFLINE_LATER),
+ # signed in, headless, online, screen's Wi-Fi page open, seconds since start
+ # → seconds as it is first (None: not now)
+ (False, False, False, False, 0, 0), # just installed, screen, no network: at once
+ (False, True, False, False, 0, 0), # just installed, no screen: at once
+ (False, False, True, False, 0, 0), # not signed in on Wi-Fi or a cable: at once
+ (False, False, False, True, 0, None), # someone at the screen chooses a Wi-Fi
+ (True, False, False, False, 600, None), # signed-in laptop: its Wi-Fi page, never the hotspot
+ (True, True, True, False, 600, None), # signed in and online: nothing to do
+ (True, True, False, False, 3, setup.OFFLINE_AT_START),
+ (True, True, False, False, 600, setup.OFFLINE_LATER),
]
- for signed, headless, saved, since, expected in cases:
+ for signed, headless, online, screen, since, expected in cases:
with patch.object(setup, 'signed_in', return_value=signed), \
patch.object(setup, 'headless', return_value=headless), \
- patch.object(setup, 'saved_wifi', return_value=saved):
- self.assertEqual(setup.offline_wait(1000 + since, 1000), expected,
- (signed, headless, saved, since))
+ patch.object(setup, 'online', return_value=online), \
+ patch.object(setup, 'screen_here', return_value=screen):
+ self.assertEqual(setup.hotspot_wait(1000 + since, 1000), expected,
+ (signed, headless, online, screen, since))
+
+ def test_the_screen_holds_the_radio_until_signed_in(self):
+ with tempfile.TemporaryDirectory() as folder:
+ path = Path(folder) / 'setup-screen'
+ with patch.object(setup, 'SCREEN', path), patch.object(setup, 'signed_in', return_value=False):
+ self.assertFalse(setup.screen_here())
+ path.touch()
+ self.assertTrue(setup.screen_here())
+ with patch.object(setup, 'SCREEN', path), patch.object(setup, 'signed_in', return_value=True):
+ self.assertFalse(setup.screen_here())
+ self.assertFalse(path.exists())
+
+ def test_on_a_cable_a_ticket_alone_signs_in(self):
+ self.assertIsNone(setup.check_request(dict(ticket='t'), wired=True))
+ self.assertEqual(setup.check_request(dict(ticket='t')), 'Choose a Wi-Fi network.')
+ self.assertIsNotNone(setup.check_request(dict(), wired=True))
+ with patch.object(setup, 'internet', return_value=True), \
+ patch.object(setup, 'connect') as connect, \
+ patch.object(setup, 'sign_in', return_value=(True, '')), \
+ patch.object(setup, 'signed_in', return_value=True):
+ self.assertEqual(setup.join(dict(ticket='t'), [], 'wlo1'), dict(state='done', ssid='', signedIn=True))
+ connect.assert_not_called()
+ with patch.object(setup, 'internet', return_value=False):
+ self.assertEqual(setup.join(dict(ticket='t'), [], 'wlo1')['error'], 'NO_INTERNET_WIRED')
def test_the_hotspot_is_named_after_the_computer(self):
with tempfile.TemporaryDirectory() as folder:
diff --git a/os/tests/test_unlock.py b/os/tests/test_unlock.py
new file mode 100644
index 000000000..90425f19c
--- /dev/null
+++ b/os/tests/test_unlock.py
@@ -0,0 +1,162 @@
+"""The page a phone unlocks a locked computer on, in its startup (root/usr/lib/harness-os/unlock/http),
+against a stand-in for systemd's ask-password and systemd-reply-password."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+
+HTTP = Path(__file__).resolve().parents[1] / 'root/usr/lib/harness-os/unlock/http'
+
+# systemd-reply-password's stand-in: the right password opens the disk; a wrong one is asked again,
+# in a new file, as systemd-cryptsetup does. What it was given is kept for the test to read.
+REPLY = '''#!/bin/sh
+read -r password
+printf '%s' "$password" > "$ROOT/given"
+rm -f "$ROOT"/ask/ask.*
+if [ "$password" = 'right horse' ]; then
+ touch "$ROOT/mapper/cryptroot"
+else
+ printf '[Ask]\\nId=cryptsetup:/dev/nvme0n1p3\\nSocket=%s/sock2\\n' "$ROOT" > "$ROOT/ask/ask.again$$"
+fi
+'''
+
+
+# cryptsetup's stand-in: `open --test-passphrase --key-file=- DISK` with the password on stdin, and
+# what it was asked kept for the test to read. Only "right horse" is the disk's.
+CRYPTSETUP = '''#!/bin/sh
+printf '%s' "$*" > "$ROOT/tested-args"
+password=$(cat)
+printf '%s' "$password" > "$ROOT/tested"
+[ "$password" = 'right horse' ]
+'''
+
+
+class Unlock(unittest.TestCase):
+ def setUp(self):
+ folder = tempfile.TemporaryDirectory()
+ self.addCleanup(folder.cleanup)
+ self.root = Path(folder.name)
+ for name in ('state', 'ask', 'mapper'):
+ (self.root / name).mkdir()
+ (self.root / 'mapper/control').touch()
+ (self.root / 'state/name').write_text('Harness-BD19\n')
+ reply = self.root / 'reply'
+ reply.write_text(REPLY)
+ reply.chmod(0o755)
+ cryptsetup = self.root / 'cryptsetup'
+ cryptsetup.write_text(CRYPTSETUP)
+ cryptsetup.chmod(0o755)
+ self.ask()
+ self.env = dict(os.environ, ROOT=str(self.root), HARNESS_UNLOCK_STATE=str(self.root / 'state'),
+ HARNESS_UNLOCK_ASK=str(self.root / 'ask'), HARNESS_UNLOCK_REPLY=str(reply),
+ HARNESS_UNLOCK_MAPPER=str(self.root / 'mapper'), HARNESS_UNLOCK_OPENS='3',
+ HARNESS_UNLOCK_BY_PHONE=str(self.root / 'run/unlocked-by-phone'),
+ HARNESS_UNLOCK_SETUP=str(self.root / 'run/phone-setup.json'),
+ HARNESS_UNLOCK_CRYPTSETUP=str(cryptsetup))
+
+ def ask(self):
+ (self.root / 'ask/ask.first').write_text(
+ f'[Ask]\nPID=1\nId=cryptsetup:/dev/nvme0n1p3\nSocket={self.root}/sock\n')
+
+ def request(self, method, path, body=b'', setup=None):
+ extra = ''
+ if setup is not None:
+ setup = json.dumps(setup).encode()
+ extra = f'X-Harness-Setup-Length: {len(setup)}\r\n'
+ body += setup
+ head = f'{method} {path} HTTP/1.1\r\nHost: 10.42.0.1\r\n{extra}Content-Length: {len(body)}\r\n\r\n'.encode()
+ done = subprocess.run([os.environ.get('UNLOCK_SHELL', '/bin/sh'), *os.environ.get('UNLOCK_SHELL_ARGS', '').split(), str(HTTP)], input=head + body, capture_output=True,
+ env=self.env, timeout=20)
+ status, _, rest = done.stdout.partition(b'\r\n')
+ headers, _, payload = rest.partition(b'\r\n\r\n')
+ self.assertIn(f'Content-Length: {len(payload)}'.encode(), headers)
+ return int(status.split()[1]), json.loads(payload)
+
+ def test_the_phone_is_told_the_computer_is_locked(self):
+ self.assertEqual(self.request('GET', '/setup'),
+ (200, dict(protocol=3, hotspot='Harness-BD19', locked=True, wait=0)))
+ self.assertEqual(self.request('GET', '/elsewhere')[0], 404)
+
+ def test_a_password_is_checked_first_and_nothing_opens(self):
+ self.assertEqual(self.request('POST', '/setup/check', b'right horse'), (200, dict(state='right')))
+ self.assertEqual((self.root / 'tested').read_text(), 'right horse')
+ self.assertEqual((self.root / 'tested-args').read_text(),
+ 'open --test-passphrase --key-file=- /dev/nvme0n1p3')
+ # Only checked: the disk's question is not answered, and it is still asked.
+ self.assertFalse((self.root / 'given').exists())
+ self.assertFalse((self.root / 'mapper/cryptroot').exists())
+ self.assertTrue((self.root / 'ask/ask.first').exists())
+
+ def test_wrong_ones_may_be_checked_as_often_as_the_person_likes(self):
+ for attempt in range(8):
+ status, body = self.request('POST', '/setup/check', b'wrong one')
+ self.assertEqual((status, body['error']), (401, 'WRONG_PASSWORD'), attempt)
+ self.assertEqual(self.request('POST', '/setup/check', b'right horse'), (200, dict(state='right')))
+ self.assertEqual(self.request('GET', '/setup')[1]['wait'], 0)
+
+ def test_the_wifi_around_is_the_startups_scan(self):
+ self.assertEqual(self.request('GET', '/setup/networks'), (200, dict(networks=[])))
+ networks = dict(networks=[dict(ssid='Glinks', signal=80, security='WPA2')])
+ (self.root / 'state/networks.json').write_text(json.dumps(networks))
+ self.assertEqual(self.request('GET', '/setup/networks'), (200, networks))
+
+ def test_the_rest_of_the_setup_comes_with_the_password_and_waits_in_run(self):
+ setup = dict(ssid='Glinks', password='wifi pass 1', ticket='t-1', account='u-1')
+ self.assertEqual(self.request('POST', '/setup/unlock', b'right horse', setup=setup),
+ (200, dict(state='unlocked')))
+ # The computer's password alone went to the disk's question.
+ self.assertEqual((self.root / 'given').read_text(), 'right horse')
+ kept = self.root / 'run/phone-setup.json'
+ self.assertEqual(json.loads(kept.read_text()), setup)
+ self.assertEqual(kept.stat().st_mode & 0o777, 0o600)
+
+ def test_a_wrong_password_keeps_none_of_the_setup(self):
+ status, body = self.request('POST', '/setup/unlock', b'wrong one', setup=dict(ssid='Glinks'))
+ self.assertEqual((status, body['error']), (401, 'WRONG_PASSWORD'))
+ self.assertEqual((self.root / 'given').read_text(), 'wrong one')
+ self.assertFalse((self.root / 'run/phone-setup.json').exists())
+
+ def test_the_right_password_opens_the_disk(self):
+ self.assertEqual(self.request('POST', '/setup/unlock', 'right horse'.encode()), (200, dict(state='unlocked')))
+ self.assertEqual((self.root / 'given').read_text(), 'right horse')
+ # Marked as opened from a phone, for the screen's Wi-Fi page to leave it the radio.
+ self.assertTrue((self.root / 'run/unlocked-by-phone').is_file())
+ # Opened already: said so again, with nothing more sent.
+ (self.root / 'given').unlink()
+ self.assertEqual(self.request('POST', '/setup/unlock', b'anything')[0], 200)
+ self.assertFalse((self.root / 'given').exists())
+
+ def test_a_wrong_password_is_said_so_and_many_make_the_phone_wait(self):
+ for attempt in range(5):
+ status, body = self.request('POST', '/setup/unlock', b'wrong one')
+ self.assertEqual((status, body['error']), (401, 'WRONG_PASSWORD'), attempt)
+ # Not opened: no mark of a phone.
+ self.assertFalse((self.root / 'run/unlocked-by-phone').exists())
+ status, body = self.request('POST', '/setup/unlock', b'right horse')
+ self.assertEqual((status, body['error']), (429, 'WAIT'))
+ self.assertGreater(body['wait'], 0)
+ self.assertEqual(self.request('GET', '/setup')[1]['wait'], body['wait'])
+
+ def test_nothing_is_sent_while_the_computer_is_not_asking(self):
+ for file in (self.root / 'ask').iterdir():
+ file.unlink()
+ self.assertEqual(self.request('POST', '/setup/unlock', b'right horse')[1]['error'], 'NOT_ASKING')
+ self.assertFalse((self.root / 'given').exists())
+
+ def test_one_try_at_a_time_and_no_empty_password(self):
+ (self.root / 'state/busy').mkdir()
+ self.assertEqual(self.request('POST', '/setup/unlock', b'right horse')[1]['error'], 'BUSY')
+ (self.root / 'state/busy').rmdir()
+ self.assertEqual(self.request('POST', '/setup/unlock')[0], 400)
+
+ def test_a_password_with_quotes_and_spaces_arrives_as_typed(self):
+ (self.root / 'reply').write_text(REPLY.replace("'right horse'", '"$password"'))
+ typed = 'a "b" \'c\' $d \\e f'
+ self.assertEqual(self.request('POST', '/setup/unlock', typed.encode())[0], 200)
+ self.assertEqual((self.root / 'given').read_text(), typed)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tests/unlock_vm.py b/os/tests/unlock_vm.py
new file mode 100644
index 000000000..d7415f456
--- /dev/null
+++ b/os/tests/unlock_vm.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python3
+"""An encrypted Harness unlocked from a "phone" over its setup hotspot, as it starts.
+
+The image installs encrypted in a VM with two simulated Wi-Fi radios (mac80211_hwsim). One is the
+computer's card: its startup hosts Harness-XXXX on it (harness-unlock). The other is the phone, in
+a network namespace of its own so nothing reaches the computer but over the air: it joins the
+hotspot, gets an address from it, reads /setup, sends a wrong password, then the right one. The
+computer must then start, with nobody at its screen.
+
+ python3 tests/unlock_vm.py --iso dist/harness-….iso [--output folder]
+"""
+import argparse
+import base64
+import json
+from pathlib import Path
+import shlex
+import sys
+import time
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from vm import VM # noqa: E402
+
+PASSWORD = 'test-password-123'
+
+# The phone, in the computer's startup: a test-only mkinitcpio hook beside harness-unlock.
+HOOK = '''#!/bin/bash
+build() {
+ add_file /usr/lib/harness-os/unlock-test/phone /usr/lib/harness-os/unlock-test/phone 755
+ add_file /usr/lib/harness-os/unlock-test/udhcpc /usr/lib/harness-os/unlock-test/udhcpc 755
+ add_file /usr/lib/harness-os/unlock-test/password /usr/lib/harness-os/unlock-test/password 600
+ add_file /usr/lib/harness-os/unlock-test/phone.service /usr/lib/systemd/system/harness-unlock-phone.service 644
+ add_symlink /usr/lib/systemd/system/initrd.target.wants/harness-unlock-phone.service ../harness-unlock-phone.service
+ add_file /etc/modprobe.d/hwsim.conf
+}
+'''
+
+PHONE = r'''#!/bin/sh
+say() { echo "HN_PHONE $*" > /dev/ttyS0; }
+for _ in $(seq 90); do [ -f /run/harness-unlock/tcpsvd.pid ] && break; sleep 1; done
+ap=$(cat /run/harness-unlock/device 2>/dev/null); name=$(cat /run/harness-unlock/name 2>/dev/null)
+say "hotspot ${name:-none} on ${ap:-none}"
+dev=
+for path in /sys/class/net/*; do
+ [ -d "$path/wireless" ] && [ "${path##*/}" != "$ap" ] && dev=${path##*/}
+done
+phy=$(cat "/sys/class/net/$dev/phy80211/name")
+unshare -n sleep 100000 &
+holder=$!
+sleep 1
+iw phy "$phy" set netns "$holder"
+on() { nsenter -t "$holder" -n "$@"; }
+on ip link set lo up
+on ip link set "$dev" up
+printf 'network={\n ssid="%s"\n key_mgmt=NONE\n scan_ssid=1\n}\n' "$name" > /run/phone.conf
+on wpa_supplicant -B -i "$dev" -c /run/phone.conf
+for _ in $(seq 40); do on iw dev "$dev" link | grep -q 'Connected to' && break; sleep 1; done
+say "link $(on iw dev "$dev" link | head -1)"
+on udhcpc -i "$dev" -n -q -t 10 -s /usr/lib/harness-os/unlock-test/udhcpc >/dev/null 2>&1
+say "address $(on ip -4 addr show dev "$dev" | grep -o 'inet [0-9./]*')"
+say "route $(on ip route get 10.42.0.1 | head -1)"
+say "setup $(on wget -q -T 10 -O - http://10.42.0.1/setup 2>&1)"
+say "wrong $(on wget -q -T 60 -O - --post-data=not-the-password http://10.42.0.1/setup/unlock 2>&1)"
+say "right $(on wget -q -T 60 -O - --post-data="$(cat /usr/lib/harness-os/unlock-test/password)" http://10.42.0.1/setup/unlock 2>&1)"
+'''
+
+UDHCPC = '''#!/bin/sh
+case $1 in bound|renew) ip addr add "$ip/${mask:-24}" dev "$interface" ;; esac
+'''
+
+UNIT = '''[Unit]
+Description=Test phone unlocking this computer over its setup hotspot
+DefaultDependencies=no
+After=harness-unlock.service
+Conflicts=initrd-switch-root.target
+Before=initrd-switch-root.target
+
+[Service]
+Type=simple
+ExecStart=/usr/lib/harness-os/unlock-test/phone
+ExecStop=/bin/sh -c 'sleep 3'
+'''
+
+
+def put(vm, path, text, mode='644'):
+ data = base64.b64encode(text.encode()).decode()
+ vm.command(f': > {shlex.quote(path)}.b64')
+ for start in range(0, len(data), 1500):
+ vm.command(f"printf %s {shlex.quote(data[start:start + 1500])} >> {shlex.quote(path)}.b64")
+ vm.command(f'base64 -d {shlex.quote(path)}.b64 > {shlex.quote(path)} && rm {shlex.quote(path)}.b64 && chmod {mode} {shlex.quote(path)}')
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument('--iso', required=True, type=Path)
+ parser.add_argument('--output', type=Path)
+ parser.add_argument('--memory', type=int, default=4096)
+ parser.add_argument('--video', choices=['virtio-vga', 'VGA'], default='virtio-vga')
+ args = parser.parse_args()
+ folder = (args.output or Path.cwd() / 'unlock-vm-results').resolve()
+ folder.mkdir(parents=True, exist_ok=False)
+ result = dict(iso=str(args.iso), checks=[], status='running', started_at_unix=time.time())
+ vm = VM(folder, args.iso.resolve(), 'bios', args.memory, video=args.video)
+ try:
+ vm.start(live=True)
+ vm.monitor('set_link', name='hnnet', up=False)
+ vm.wait(r'root@[^\r\n]*[#] ', timeout=300)
+ vm.shell_ready = True
+ vm.command('stty -echo')
+ # The computer's card and the phone, both simulated; loaded here, so the startup that the
+ # installer builds takes the driver as it takes a real card's (harness-unlock).
+ vm.command('modprobe mac80211_hwsim radios=2 && nmcli networking off')
+ config = dict(disk='/dev/vda', expected_serial='HN_OS_TEST', confirm_erase='/dev/vda', username='me', hostname='harness',
+ password=PASSWORD, encrypt=True, serial_console=True)
+ put(vm, '/run/hn-config.json', json.dumps(config), '600')
+ vm.command('python3 /usr/lib/harness-os/install.py --config /run/hn-config.json --yes-erase-disk '
+ '> /run/hn-install.log 2>&1 || { tail -40 /run/hn-install.log; exit 1; }', timeout=2400)
+ result['checks'].append('Unattended encrypted installation')
+ # The installed startup, plus the test phone.
+ vm.command(f'printf %s {shlex.quote(PASSWORD)} | cryptsetup open /dev/vda3 hnroot -d - '
+ '&& mount -o subvol=@ /dev/mapper/hnroot /mnt && mount /dev/vda2 /mnt/boot')
+ hooks, _ = vm.command("grep '^HOOKS' /mnt/etc/mkinitcpio.conf")
+ assert 'block harness-unlock sd-encrypt' in hooks, hooks
+ result['checks'].append('The installer put harness-unlock before sd-encrypt')
+ args_line, _ = vm.command("grep -h 'rd.luks.options' /mnt/etc/default/grub")
+ assert 'tries=0' in args_line, args_line
+ vm.command('mkdir -p /mnt/usr/lib/harness-os/unlock-test')
+ put(vm, '/mnt/usr/lib/initcpio/install/harness-unlock-test', HOOK)
+ put(vm, '/mnt/usr/lib/harness-os/unlock-test/phone', PHONE, '755')
+ put(vm, '/mnt/usr/lib/harness-os/unlock-test/udhcpc', UDHCPC, '755')
+ put(vm, '/mnt/usr/lib/harness-os/unlock-test/phone.service', UNIT)
+ put(vm, '/mnt/usr/lib/harness-os/unlock-test/password', PASSWORD, '600')
+ put(vm, '/mnt/etc/modprobe.d/hwsim.conf', 'options mac80211_hwsim radios=2\n')
+ put(vm, '/mnt/etc/mkinitcpio.conf.d/90-unlock-test.conf', 'MODULES+=(mac80211_hwsim)\n')
+ vm.command("sed -i 's/harness-unlock /harness-unlock harness-unlock-test /' /mnt/etc/mkinitcpio.conf")
+ vm.command('arch-chroot /mnt mkinitcpio -P > /run/hn-mkinitcpio.log 2>&1 || { tail -30 /run/hn-mkinitcpio.log; exit 1; }',
+ timeout=900)
+ listing, _ = vm.command('lsinitcpio /mnt/boot/initramfs-linux-lts.img | grep -E "harness-unlock|mac80211_hwsim|wpa_supplicant|dnsmasq"')
+ (folder / 'initramfs-listing.txt').write_text(listing)
+ vm.command('sync; umount -R /mnt; cryptsetup close hnroot')
+ vm.stop()
+
+ # Nobody types at the screen: only the phone can open the disk.
+ vm.start(live=False)
+ started = time.monotonic()
+ out = vm.wait(r'HN_PHONE wrong [^\r\n]*\r?\n', timeout=600)
+ # Nobody types at the screen: reaching the login is the phone's password having opened the disk.
+ out += vm.wait(r'login:', timeout=300)
+ lines = [line.strip() for line in out.splitlines() if line.startswith('HN_PHONE')]
+ result['phone'] = lines
+ print('\n'.join(lines), flush=True)
+ text = '\n'.join(lines)
+ assert 'hotspot Harness-' in text, text
+ assert 'link Connected to' in text, text
+ assert 'address inet 10.42.0.' in text, text
+ assert '"locked":true' in text, text
+ assert '401' in text.split('wrong ', 1)[1].splitlines()[0], text
+ assert 'right ' in text and '"state":"unlocked"' in text.split('right ', 1)[1], text
+ result['checks'].append('The phone joined Harness-XXXX over the air, got an address and read that it is locked')
+ result['checks'].append('A wrong password is refused and the disk stays locked')
+ result['checks'].append('The right password opened the disk')
+ result['unlocked_to_login_seconds'] = round(time.monotonic() - started, 1)
+ result['checks'].append('The computer went on starting to its login, with nobody at its screen')
+ result['status'] = 'passed'
+ except BaseException as error:
+ result['status'] = 'failed'
+ result['error'] = repr(error)
+ raise
+ finally:
+ result['finished_at_unix'] = time.time()
+ (folder / 'result.json').write_text(json.dumps(result, indent=2) + '\n')
+ try:
+ vm.stop()
+ except Exception:
+ pass
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tui/src/app.rs b/tui/src/app.rs
index f6580924e..bccb040d9 100644
--- a/tui/src/app.rs
+++ b/tui/src/app.rs
@@ -1895,10 +1895,14 @@ impl App {
if let Some(taken) = payload.get("takenBy") {
let who = taken.get("name").and_then(Value::as_str).unwrap_or("another window").to_string();
pane.phase = Phase::Watching(who);
- // Still worth seeing: watch it until someone types here.
+ // Watched until someone types here — the watcher is what hears `terminal_free`
+ // — but frozen: its frames come at the taker's size (a phone's), and drawn
+ // here they shrank the screen's pane. Its last frame stays, as the desktop's.
+ pane.frozen = true;
let id = pane.id;
self.open_stream(id, false);
} else {
+ pane.frozen = false;
let id = pane.id;
let reason = payload.get("reason").and_then(Value::as_str).unwrap_or("the terminal closed");
if matches!(reason, "heartbeat timeout" | "backend disconnected") {
@@ -1919,6 +1923,14 @@ impl App {
}
}
}
+ // The view that had the keyboard of a pane watched here left (a phone closed it): one on
+ // screen takes it back, at this window's size. Otherwise the agent kept the size of the
+ // one that left — a phone's, in a corner of a full screen — until someone typed here.
+ "terminal_free" => {
+ let stream = payload.get("streamId").and_then(Value::as_str).and_then(|s| Uuid::parse_str(s).ok());
+ let Some(id) = self.panes.values().find(|p| p.stream.is_some() && p.stream == stream).map(|p| p.id) else { return };
+ if self.rects.iter().any(|(pane, _)| *pane == id) { self.take_if_watching(id) }
+ }
// ── models: the daemon's picture of the grids changed — the whole list, pushed ──
"grid_models_changed" => crate::models::on_push(self, machine_id, &payload),
_ => {}
@@ -1937,6 +1949,8 @@ impl App {
pane.last_seq = Some(pane.last_seq.map(|s| s.max(frame.seq)).unwrap_or(frame.seq));
pane.ack_due = true;
if frame.kind == Kind::Sync { return }
+ // Taken by another client: acknowledged above, never drawn — see [Pane::frozen].
+ if pane.frozen { return }
let bytes = if frame.compressed { match pane::inflate(&frame.bytes) { Some(b) => b, None => return } } else { frame.bytes };
if let Ok(path) = std::env::var("HARNESS_TUI_TRACE") {
use std::io::Write;
@@ -2102,6 +2116,7 @@ impl App {
}
return;
}
+ let headless = self.headless;
let Some(pane) = self.panes.get_mut(&pane_id) else { return };
pane.opening = false;
let takeover_requested = std::mem::take(&mut pane.takeover_pending);
@@ -2116,6 +2131,11 @@ impl App {
pane.phase = if pane.read_only {
Phase::Watching(payload.get("heldBy").and_then(|h| h.get("name")).and_then(Value::as_str).unwrap_or("another window").to_string())
} else { Phase::Live };
+ // Held here: its frames come at this side's size, so they are drawn. Held by another
+ // client (a phone that opened it first, its Start): its frames come at that one's
+ // size and are not drawn here — the screen's pane says who has it, at its own size,
+ // until a key takes it. hn with no terminal reads them all the same: it has no size.
+ pane.frozen = pane.read_only && !headless;
let retake = takeover_requested && pane.read_only;
let queued = if retake { Vec::new() } else { std::mem::take(&mut pane.queued) };
let read_only = pane.read_only;
@@ -4209,7 +4229,8 @@ impl App {
// size the agent to its 80x24 layout under the window someone is using.
if self.headless { return }
let Some(p) = self.panes.get(&pane) else { return };
- if matches!(p.phase, Phase::Watching(_)) && !p.read_only && !p.opening { self.open_stream(pane, true) }
+ // A watcher is read-only (the daemon's `readOnly`): that is what there is to take.
+ if matches!(p.phase, Phase::Watching(_)) && !p.opening { self.open_stream(pane, true) }
}
/// A machine's first roster since hn started, read against when you last looked at each of
@@ -5884,8 +5905,18 @@ impl App {
// The OS opens on the agent launcher. An explicit `hn new ...` still gets
// its requested shell; reconnecting to existing work is handled by the desk.
if self.os_session && self.start_session.is_none() {
+ // Work of this computer's own on the desk: the "code" tab a phone's Start made. Tabs of
+ // other computers do not count — the account's desk can hold those of one since removed
+ // (this very computer before a reinstall), "Connecting…" for ever.
+ let local = self.fleet.local_id.clone();
+ let own_work = self.tabs.iter().flat_map(|t| t.panes())
+ .any(|id| self.panes.get(&id).is_some_and(|p| p.machine_id == local));
+ // The welcome waits for this computer's daemon to be up, not only linked: a sign-in
+ // restarts it, and a shell asked for meanwhile went to hn's own local shells
+ // (`shell_machine`) — OpenCode then ran where no phone or desktop could see it.
+ let daemon_ready = self.link(&self.fleet.local_id).is_some() && !self.daemon_down;
if (self.os_live || self.os_first_use) && self.tabs.len() == 1 && self.tabs[0].root.is_none() {
- if self.link(&self.fleet.local_id).is_none() { return }
+ if !daemon_ready { return }
self.shell_asked = true;
// The welcome reply may arrive after another terminal is requested.
// Fill its original tab instead of whichever tab is now active.
@@ -5893,7 +5924,26 @@ impl App {
crate::input::new_shell_from(self, None, Placement::Fill(tab), None, Some("/usr/bin/hn-os welcome".into()));
} else if (self.os_live || self.os_first_use) && crate::os_welcome::welcome_waits_on_wifi(self) {
// Asked again every tick until the Wi-Fi form gives the tab back.
- } else { self.shell_asked = true; }
+ } else if self.os_first_use && !self.os_live && !own_work {
+ // Only other computers' tabs on the desk: the welcome still comes, in a tab of its own.
+ if !daemon_ready { return }
+ self.shell_asked = true;
+ crate::input::new_shell_from(self, None, Placement::Tab, None, Some("/usr/bin/hn-os welcome".into()));
+ } else {
+ self.shell_asked = true;
+ // The desk already had work for this screen — the "code" tab a phone's Start made
+ // after setting this computer up — so it opens on that instead of a welcome with
+ // an OpenCode of its own. Its first use is over all the same: the welcome is what
+ // marks that (onboarding.py), and without the mark every boot is a first one.
+ if self.os_first_use && !self.os_live && own_work {
+ self.os_first_use = false;
+ // Not from a test: it would mark the developer's own home.
+ if let Some(home) = std::env::var_os("HOME").filter(|_| !cfg!(test)) {
+ let state = std::path::Path::new(&home).join(".local/state/harness-os");
+ let _ = std::fs::create_dir_all(&state).and_then(|_| std::fs::File::create(state.join("onboarded")));
+ }
+ }
+ }
return;
}
// `hn new -s work` (a session besides the desk's): made here, with its shell.
@@ -6778,6 +6828,53 @@ mod scroll_settle_tests {
mod recovery_tests {
use super::*;
+ #[tokio::test]
+ async fn os_welcome_waits_out_a_daemon_restarting_after_the_sign_in() {
+ // Signed in at the screen: the daemon restarts, and a welcome asked for meanwhile ran in
+ // hn's own local shells, where no phone or desktop could see its OpenCode.
+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(19791, sink, (80, 24));
+ app.handed_over = true;
+ app.os_session = true;
+ app.os_first_use = true;
+ app.desk_answered = true;
+ app.fleet.local_id = "this-computer".into();
+ app.fleet.machines.push(Machine { shared: false, id: "this-computer".into(), name: "me".into(), local: true, status: "running".into(), reach: Reach::Ready });
+ let link = Link::spawn(app.port, "this-computer", 1, app.sink.clone());
+ app.links.insert("this-computer".into(), LinkState { link: Some(link), generation: 1, attempts: 0, retry_at: None });
+ app.daemon_down = true;
+ app.maybe_start_shell();
+ assert!(!app.shell_asked, "not while its daemon is down");
+ app.daemon_down = false;
+ app.maybe_start_shell();
+ assert!(app.shell_asked, "once it is back");
+ app.links["this-computer"].link.as_ref().unwrap().close();
+ }
+
+ #[tokio::test]
+ async fn os_first_use_skips_its_welcome_only_for_work_of_this_computer() {
+ let first_use = |machine: &str| {
+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(19790, sink, (80, 24));
+ app.handed_over = true;
+ app.os_session = true;
+ app.os_first_use = true;
+ app.desk_answered = true;
+ app.fleet.local_id = "this-computer".into();
+ app.new_tab();
+ app.open_agent(machine, "a", Placement::Auto(None));
+ app.maybe_start_shell();
+ app
+ };
+ // A desk tab of another computer — one since removed, "Connecting…" for ever: the welcome
+ // still comes (it waits here only for this computer's daemon).
+ let app = first_use("removed-computer");
+ assert!(app.os_first_use && !app.shell_asked);
+ // A tab of its own (the "code" tab a phone's Start made): that, and its first use is done.
+ let app = first_use("this-computer");
+ assert!(!app.os_first_use && app.shell_asked);
+ }
+
#[tokio::test]
async fn os_first_workspace_waits_while_the_wifi_form_holds_the_tabs() {
let (sink, _) = tokio::sync::mpsc::unbounded_channel();
@@ -7555,7 +7652,8 @@ mod recovery_tests {
let pane = app.panes.get_mut(&1).unwrap();
// Taken over (`takenBy`), watching until someone comes to it.
pane.phase = Phase::Watching("Mac Auto terminal".into());
- pane.read_only = false;
+ // Watching, as the daemon answers a watcher.
+ pane.read_only = true;
app.headless = true;
app.take_if_watching(1);
assert!(!app.panes[&1].opening);
@@ -7567,6 +7665,49 @@ mod recovery_tests {
app.links["test-peer"].link.as_ref().unwrap().close();
}
+ #[tokio::test]
+ async fn a_pane_on_screen_takes_back_what_a_phone_left() {
+ // A phone opened this agent and took it at its own size; this screen watched. The phone left.
+ let mut app = fixture();
+ let (on_screen, hidden) = (1, 2);
+ app.rects = vec![(on_screen, Rect::new(0, 0, 80, 24))];
+ for id in [on_screen, hidden] {
+ let pane = app.panes.get_mut(&id).unwrap();
+ pane.phase = Phase::Watching("Pixel 8 Pro".into());
+ pane.read_only = true;
+ }
+ for id in [on_screen, hidden] {
+ let stream = app.panes[&id].stream.unwrap().to_string();
+ app.on_machine("test-peer".into(), 1, MachineEvent::Frame { ty: "terminal_free".into(), payload: json!({"streamId": stream}) });
+ }
+ assert!(app.panes[&on_screen].opening, "the pane on screen takes it back");
+ assert!(!app.panes[&hidden].opening, "one out of sight stays a watcher until someone comes to it");
+ app.links["test-peer"].link.as_ref().unwrap().close();
+ }
+
+ #[tokio::test]
+ async fn a_phone_taking_a_pane_does_not_shrink_it_here() {
+ // The phone took the terminal at its own size; this screen watches it frozen, as the
+ // desktop keeps its tile: the phone-sized frames are not drawn here.
+ let mut app = fixture();
+ app.rects = vec![(1, Rect::new(0, 0, 80, 24))];
+ let before = (app.panes[&1].cols, app.panes[&1].rows);
+ let stream = app.panes[&1].stream.unwrap().to_string();
+ app.on_machine("test-peer".into(), 1, MachineEvent::Frame {
+ ty: "terminal_closed".into(),
+ payload: json!({"streamId": stream, "code": "TERMINAL_TAKEN_OVER", "takenBy": {"name": "Pixel 8 Pro"}}),
+ });
+ let pane = app.panes.get_mut(&1).unwrap();
+ assert!(pane.frozen);
+ assert!(matches!(&pane.phase, Phase::Watching(who) if who == "Pixel 8 Pro"));
+ let watcher = Uuid::new_v4();
+ pane.stream = Some(watcher);
+ pane.read_only = true;
+ app.on_terminal(proto::Frame { kind: Kind::Keyframe, stream: watcher, seq: 1, bytes: b"phone".to_vec(), compressed: false, size: Some((45, 30)) });
+ assert_eq!((app.panes[&1].cols, app.panes[&1].rows), before, "the phone's size is not this screen's");
+ app.links["test-peer"].link.as_ref().unwrap().close();
+ }
+
#[tokio::test]
async fn pane_waits_for_machine_selection_before_opening() {
let mut app = fixture();
diff --git a/tui/src/pane.rs b/tui/src/pane.rs
index 0c22174a7..cbd734b20 100644
--- a/tui/src/pane.rs
+++ b/tui/src/pane.rs
@@ -101,6 +101,10 @@ pub struct Pane {
/// A user requested app-wide control while this pane's passive open was in flight.
pub takeover_pending: bool,
pub read_only: bool,
+ /// Taken by another client (`terminal_closed.takenBy`): its last frame stays at this side's size
+ /// and the watcher's frames — at the taker's size — are not drawn, as the desktop app keeps its
+ /// tile, until this side takes it back.
+ pub frozen: bool,
pub last_alive: Instant,
pub dirty: bool,
pub bell: bool,
@@ -472,6 +476,7 @@ impl Pane {
input_off: false,
opening: false,
takeover_pending: false,
+ frozen: false,
far_sized: false,
read_only: false,
last_alive: Instant::now(),
diff --git a/tui/src/ui.rs b/tui/src/ui.rs
index 008a76273..05ab2d1e6 100644
--- a/tui/src/ui.rs
+++ b/tui/src/ui.rs
@@ -3082,7 +3082,8 @@ fn pane_body(buf: &mut Buffer, pane: &mut Pane, area: Rect, active: bool, window
match &pane.phase {
// Opening: nothing to show yet. Lost (the machine's link down), the last screen is kept, as
// ssh and mosh keep it — below.
- Phase::Connecting(note) if pane.last_seq.is_none() => { card(buf, area, &[(note.clone(), Style::default().add_modifier(Modifier::DIM))]); return None }
+ // A frozen pane taking its terminal back still has its last frame: kept, under the notice.
+ Phase::Connecting(note) if pane.last_seq.is_none() && !pane.frozen => { card(buf, area, &[(note.clone(), Style::default().add_modifier(Modifier::DIM))]); return None }
Phase::Card { title, detail, keys } => {
let mut lines = vec![(title.clone(), Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD))];
for row in detail.lines() { lines.push((row.to_string(), Style::default())) }
@@ -3169,6 +3170,17 @@ fn pane_body(buf: &mut Buffer, pane: &mut Pane, area: Rect, active: bool, window
buf.set_stringn(area.x, area.y, format!("{:w$}", format!(" ! {note}"), w = area.width as usize), area.width as usize, notice);
return None;
}
+ // Taken by another client (a phone): its last frame here, at this screen's size, and one row
+ // saying who has it and how to have it back — the desktop app's band.
+ if let (true, Phase::Watching(who)) = (pane.frozen, &pane.phase) {
+ let who = if who.is_empty() { "Another window" } else { who.as_str() };
+ let row = Rect::new(area.x, area.y, area.width, 1);
+ let notice = Style::default().fg(window.0.unwrap_or(Color::Reset)).bg(window.1.unwrap_or(Color::Reset))
+ .remove_modifier(Modifier::DIM | Modifier::REVERSED).add_modifier(Modifier::BOLD);
+ buf.set_style(row, notice);
+ buf.set_stringn(area.x, area.y, format!("{:w$}", format!(" ! {who} is using this terminal — type to take it back"), w = area.width as usize), area.width as usize, notice);
+ return None;
+ }
// Local echo, drawn over the grid: underlined until the far side confirms it.
for (col, row, c, _) in pane.shown_predictions() {
let row = (*row as i32 - shift).max(0) as u16;