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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Harness OS: sign out, change password and SSH from a phone; factory reset is as installed (#1560)
Bubu-Dudu-52hzdea3f4d70212
diff --git a/cli/src/services/osDevice.spec.ts b/cli/src/services/osDevice.spec.tsindex b7b82d89f..8e310bfc0 100644--- a/cli/src/services/osDevice.spec.ts+++ b/cli/src/services/osDevice.spec.ts@@ -77,7 +77,7 @@ describe('the Harness OS computer, managed from the phone', () => {cli: { running: '0.9.1', available: true, next: null },},},- wifi: { ssid: 'Home: 5G' }, hotspot: 'Harness-BD19', encrypted: true,+ wifi: { ssid: 'Home: 5G' }, hotspot: 'Harness-BD19', encrypted: true, features: ['sign_out', 'password', 'ssh'],})expect(exec).toHaveBeenCalledWith('/usr/bin/python3', [LIVE_UPDATE, 'status'], { timeout: 15_000 })expect(exec).toHaveBeenCalledWith('/usr/bin/python3', [SETUP, 'name'], { timeout: 10_000 })@@ -88,8 +88,8 @@ describe('the Harness OS computer, managed from the phone', () => {it('still answers on Harness OS when its update tool or nmcli fails', async () => {const failing = (reason: unknown) => service({ exec: vi.fn(async () => { throw reason }) }).ask({ action: 'status' })- expect(await failing(new Error('Command failed: python3\nTraceback ...'))).toEqual({ harnessOs: true, update: { available: false, error: 'Command failed: python3' }, wifi: { ssid: null }, hotspot: null, encrypted: true })- expect(await failing('killed')).toEqual({ harnessOs: true, update: { available: false, error: 'killed' }, wifi: { ssid: null }, hotspot: null, encrypted: true })+ expect(await failing(new Error('Command failed: python3\nTraceback ...'))).toEqual({ harnessOs: true, update: { available: false, error: 'Command failed: python3' }, wifi: { ssid: null }, hotspot: null, encrypted: true, features: ['sign_out', 'password', 'ssh'] })+ expect(await failing('killed')).toEqual({ harnessOs: true, update: { available: false, error: 'killed' }, wifi: { ssid: null }, hotspot: null, encrypted: true, features: ['sign_out', 'password', 'ssh'] })const notJson = service({ exec: vi.fn(async () => 'not json') })expect(await notJson.ask({ action: 'status' })).toMatchObject({ update: { available: false, error: expect.stringContaining('JSON') } })const notObject = service({ exec: vi.fn(async () => '[1]') })@@ -135,6 +135,35 @@ describe('the Harness OS computer, managed from the phone', () => {expect(spawnDetached).toHaveBeenCalledWith('/usr/bin/harness', ['update', '--reboot'])})+ it('signs the computer out for another account, detached', async () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const { ask, spawnDetached } = service()+ expect(await ask({ action: 'sign_out' })).toEqual({ started: true })+ expect(spawnDetached).toHaveBeenCalledWith('sudo', ['-n', '/usr/bin/python3', SETUP, 'sign-out'])+ })++ it('changes the password with both only on the helper\'s stdin', async () => {+ const exec = vi.fn(async () => '{"ok": true, "disk": true}')+ const { ask } = service({ exec })+ expect(await ask({ action: 'password', current: '1234', next: 'abcd' })).toEqual({ ok: true, disk: true })+ expect(exec).toHaveBeenCalledWith('sudo', ['-n', '/usr/bin/python3', SETUP, 'password'],+ { timeout: 90_000, input: JSON.stringify({ current: '1234', new: 'abcd' }) })+ expect(await ask({ action: 'password', current: '1234' })).toMatchObject({ error: 'BAD_REQUEST' })+ exec.mockResolvedValueOnce('{"error": "WRONG_PASSWORD", "message": "That is not the computer\'s password."}')+ expect(await ask({ action: 'password', current: 'x', next: 'abcd' })).toMatchObject({ error: 'WRONG_PASSWORD' })+ })++ it('turns SSH on or off, or says how it is', async () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const answer = { enabled: true, active: true, user: 'me', addresses: [{ interface: 'wlo1', address: '172.168.21.13' }] }+ const exec = vi.fn(async () => JSON.stringify(answer))+ const { ask } = service({ exec })+ expect(await ask({ action: 'ssh', state: 'on' })).toEqual(answer)+ expect(exec).toHaveBeenLastCalledWith('sudo', ['-n', '/usr/bin/python3', SETUP, 'ssh', 'on'], { timeout: 30_000 })+ await ask({ action: 'ssh', state: 'rm -rf' })+ expect(exec).toHaveBeenLastCalledWith('sudo', ['-n', '/usr/bin/python3', SETUP, 'ssh', 'status'], { timeout: 30_000 })+ })+it('starts the update detached, once in ten minutes', async () => {const { ask, spawnDetached, tick } = service()expect(await ask({ action: 'update' })).toEqual({ started: true })diff --git a/cli/src/services/osDevice.ts b/cli/src/services/osDevice.tsindex 65ba2bae5..ae06e3617 100644--- a/cli/src/services/osDevice.ts+++ b/cli/src/services/osDevice.ts@@ -33,6 +33,9 @@ export const UPDATE_BUSY_MS = 10 * 60_000export const STATUS_TIMEOUT_MS = 15_000export const NMCLI_TIMEOUT_MS = 10_000export const SCAN_TIMEOUT_MS = 20_000+/** The disk's key slots are slow to change on purpose (a passphrase is hashed for seconds), twice. */+export const PASSWORD_TIMEOUT_MS = 90_000+const ACTIONS = ['update', 'wifi_scan', 'wifi_join', 'wifi_result', 'sign_out', 'password', 'ssh']/** The most output a command run here may print before it is stopped. */export const MAX_OUTPUT = 1024 * 1024@@ -181,7 +184,8 @@ export function startOsDevice(_core: CoreApi, deps: OsDeviceDeps = {}): ServiceRread(CMDLINE).catch(() => ''),])// Encrypted, it waits for its password at every start (installer.py: rd.luks.name=).- return { harnessOs: true, update, wifi: { ssid }, hotspot, encrypted: /(^|\s)rd\.luks\.name=/.test(cmdline) }+ // features: what this daemon does for a phone beyond the update and the Wi-Fi.+ return { harnessOs: true, update, wifi: { ssid }, hotspot, encrypted: /(^|\s)rd\.luks\.name=/.test(cmdline), features: ['sign_out', 'password', 'ssh'] }}const update = (payload: Payload): Payload => {@@ -215,17 +219,48 @@ export function startOsDevice(_core: CoreApi, deps: OsDeviceDeps = {}): ServiceR} catch { return { result: null } }}+ /** Signed out for another account: its harnesses and projects stay, its Wi-Fi goes and its hotspot+ * opens, for a phone on the other account to set it up. Out of reach right after: the reply first. */+ const signOut = (): Payload => {+ console.log('[os-device] sign-out')+ detached('sudo', ['-n', PYTHON, SETUP, 'sign-out'])+ return { started: true }+ }++ /** The computer's one password — the disk's where it is encrypted and the account's — changed, the+ * current one checked first. Both only on the helper's stdin, never in argv or a log. */+ const password = async (payload: Payload): Promise<Payload> => {+ const { current, next } = payload+ if (typeof current !== 'string' || typeof next !== 'string' || !next) return { error: 'BAD_REQUEST', message: 'Enter the current password and a new one.' }+ const out = await exec('sudo', ['-n', PYTHON, SETUP, 'password'], { timeout: PASSWORD_TIMEOUT_MS, input: JSON.stringify({ current, new: next }) })+ const parsed: unknown = JSON.parse(out)+ if (!record(parsed)) throw new Error('setup.py password did not answer an object')+ return parsed+ }++ /** SSH on, off, or how it is, with the private addresses it answers on. */+ const ssh = async (payload: Payload): Promise<Payload> => {+ const state = payload.state === 'on' || payload.state === 'off' ? payload.state : 'status'+ if (state !== 'status') console.log(`[os-device] ssh ${state}`)+ const parsed: unknown = JSON.parse(await exec('sudo', ['-n', PYTHON, SETUP, 'ssh', state], { timeout: NMCLI_TIMEOUT_MS * 3 }))+ if (!record(parsed)) throw new Error('setup.py ssh did not answer an object')+ return parsed+ }+return {os_device: async (payload, asker) => {if (!asker.owner) return { error: 'OWNER_REQUIRED' }const action = payload.actionif (action === 'status') return status()- if (action !== 'update' && action !== 'wifi_scan' && action !== 'wifi_join' && action !== 'wifi_result') return { error: 'BAD_REQUEST' }+ if (typeof action !== 'string' || !ACTIONS.includes(action)) return { error: 'BAD_REQUEST' }if (!harnessOs()) return { error: 'UNSUPPORTED_OS' }try {if (action === 'update') return update(payload)if (action === 'wifi_scan') return await scan()if (action === 'wifi_join') return join(payload)+ if (action === 'sign_out') return signOut()+ if (action === 'password') return await password(payload)+ if (action === 'ssh') return await ssh(payload)return await result()} catch (error) {// Never the payload: it may hold a Wi-Fi password.diff --git a/os/installer.py b/os/installer.pyindex 2ba7ca0f5..e7d37eb24 100644--- a/os/installer.py+++ b/os/installer.py@@ -293,6 +293,22 @@ def trial_source(config):return source, account+# The password as installed, for `harness factory-reset` to put back (setup.py restore_initial_password).+# Root's alone, on the installed root: inside the encrypted disk where there is one.+INITIAL_ACCOUNT = '/var/lib/harness-os/initial-account.json'+++def save_initial_password(target, config):+ """The account's password hash, and on an encrypted disk the password itself: the disk's key+ slots can only be changed with a passphrase that opens one, and a reset puts back this one."""+ shadow = next((line.split(':')[1] for line in (target / 'etc/shadow').read_text().splitlines()+ if line.split(':', 1)[0] == config['username']), None)+ record = {'username': config['username'], 'shadow': shadow}+ if config['encrypt']:+ record.update(initial=config['password'], current=config['password'])+ write(target, INITIAL_ACCOUNT, json.dumps(record) + '\n', 0o600)++def preserve_trial(trial, target, home):if trial is None:return None@@ -458,6 +474,7 @@ def install_image(config, source, target, progress, resources):chroot(target, 'userdel', '-r', 'me')chroot(target, 'useradd', '-m', '-G', 'wheel,video,audio', '-s', '/bin/bash', config['username'])chroot(target, 'chpasswd', input=f"{config['username']}:{config['password']}\n".encode())+ save_initial_password(target, config)chroot(target, 'passwd', '-l', 'root')(target / 'var/lib/systemd/linger/me').unlink(missing_ok=True)write(target, f'/var/lib/systemd/linger/{config["username"]}', '')diff --git a/os/network.py b/os/network.pyindex d2ddb97fd..a9bf49b59 100644--- a/os/network.py+++ b/os/network.py@@ -18,8 +18,10 @@ 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.+# the screen then started by itself (autologin), with nobody there. Written too by a sign-out from a+# phone and a factory reset (setup.py PHONE_SETS_UP): the computer waits for a phone to set it up.+# The Wi-Fi page opened then, first or offline, 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'@@ -384,7 +386,7 @@ class NetworkPage:# 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():+ if (self.first_use or not online) 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 = Falsediff --git a/os/root/etc/sudoers.d/20-harness-network b/os/root/etc/sudoers.d/20-harness-networkindex b643fa922..185657cd2 100644--- a/os/root/etc/sudoers.d/20-harness-network+++ b/os/root/etc/sudoers.d/20-harness-network@@ -4,5 +4,10 @@# The daemon switching Wi-Fi for the person's phone (cli services/osDevice.ts): the Wi-Fi comes as JSON# on stdin to the fixed, root-owned setup helper, which goes back to the previous Wi-Fi when it fails.%wheel ALL=(root) NOPASSWD: /usr/bin/python3 /usr/lib/harness-os/setup.py join-# `harness factory-reset`: this computer as just flashed (the reset button's action), from a terminal.+# `harness factory-reset`: this computer as just installed (the reset button's action), from a terminal.%wheel ALL=(root) NOPASSWD: /usr/bin/python3 /usr/lib/harness-os/setup.py reset, /usr/bin/python3 /usr/lib/harness-os/setup.py reset --keep-wifi+# For the person's phone, through the daemon (cli services/osDevice.ts): signed out for another account+# (everything else stays), the computer's password (both, as JSON on stdin; the current one checked+# first), and SSH on, off or how it is.+%wheel ALL=(root) NOPASSWD: /usr/bin/python3 /usr/lib/harness-os/setup.py sign-out, /usr/bin/python3 /usr/lib/harness-os/setup.py password+%wheel ALL=(root) NOPASSWD: /usr/bin/python3 /usr/lib/harness-os/setup.py ssh status, /usr/bin/python3 /usr/lib/harness-os/setup.py ssh on, /usr/bin/python3 /usr/lib/harness-os/setup.py ssh offdiff --git a/os/root/usr/bin/harness b/os/root/usr/bin/harnessindex d294fceb2..17c86871a 100644--- a/os/root/usr/bin/harness+++ b/os/root/usr/bin/harness@@ -27,9 +27,10 @@ if [ "${1:-}" = rollback ]; thenexec /usr/bin/python3 /usr/lib/harness-os/runtime_update.py rollback "$@"fiif [ "${1:-}" = factory-reset ]; then- # 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.+ # As just installed: off its account, everything in /home/me gone (projects, sign-ins, harnesses,+ # the hn/CLI updates it downloaded), Wi-Fi forgotten, SSH off, the installation's password again,+ # the setup hotspot open for a phone. At the computer only (a phone signs it out instead), and+ # later its 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/setup.py b/os/setup.pyindex 6ca7103e6..a34fc9a42 100644--- a/os/setup.py+++ b/os/setup.py@@ -24,20 +24,26 @@ the phone names, and a computer already signed in keeps its account (`login --ti"""import argparseimport array+import ctypes+import ctypes.utilimport fcntl+import hmacimport http.serverimport importlib.utilimport jsonfrom pathlib import Pathimport pwdimport queue+import reimport shutilimport socketimport structimport subprocessimport sys+import tempfileimport threadingimport time+import urllib.parseimport urllib.requestimport uuid@@ -98,7 +104,8 @@ nmcli = network.nmclidef log(message):- print(f'harness-setup: {message}', flush=True)+ # On stderr, the journal's as well: stdout is the answer the daemon reads (password, ssh).+ print(f'harness-setup: {message}', file=sys.stderr, flush=True)@@ -774,6 +781,14 @@ 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'+SIGN_OUT_UNIT = 'harness-sign-out'+# The password as installed (installer.py INITIAL_ACCOUNT): root's, inside the encrypted disk.+INITIAL_ACCOUNT = STATE / 'initial-account.json'+CMDLINE = Path('/proc/cmdline')+SSHD = 'sshd.service'+# A phone sets this computer up next (network.py UNLOCKED_BY_PHONE): the screen's Wi-Fi page keeps+# off the radio the hotspot needs, until a key there.+PHONE_SETS_UP = Path('/run/harness-os/unlocked-by-phone')def as_user(*command, timeout=30):@@ -822,11 +837,7 @@ def forget_desk():"""This computer's tabs and panes off the account's desk, which every computer shows: closing itswindows alone was raced by the sign-out, and they came back at the next sign-in. A tab of its owngoes; 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+ machine = this_machine()tabs = desk_ops() if machine else Noneops = []for tab in tabs or []:@@ -841,84 +852,267 @@ def forget_desk():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' + (', 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}')+def this_machine():+ """This computer's machine in its account, while signed in."""+ status = as_user('/usr/bin/harness', 'auth', 'status', '--json')+ try:+ return json.loads(status.stdout).get('machineId') if status else None+ except ValueError:+ return None+++def remove_from_account():+ """This computer off its account (the local daemon's DELETE /api/machines/<id>, as a phone's+ Remove from account), before it starts again as a new computer: none left behind there, offline."""+ machine = this_machine()+ if not machine:+ return+ request = urllib.request.Request(DAEMON + '/api/machines/' + urllib.parse.quote(machine, safe=''),+ headers={'X-Adapter-Local': '1'}, method='DELETE')+ try:+ with urllib.request.urlopen(request, timeout=20):+ log('removed from its account')+ except (OSError, ValueError) as error:+ log(f'factory reset: could not remove this computer from its account ({error})')+++def forget_wifi():+ for row in rows('-f', 'UUID,TYPE', 'connection', 'show'):+ if len(row) == 2 and row[1] == '802-11-wireless':+ nmcli('connection', 'delete', 'uuid', row[0])+++def open_hotspot():+ """The watcher opens the hotspot for a phone at once (headless or not: asked for), and the screen's+ Wi-Fi page, opening as the computer goes offline, leaves the radio to it until a key there."""+ NOW.parent.mkdir(parents=True, exist_ok=True)+ NOW.touch()+ PHONE_SETS_UP.touch()+++def sign_out(keep_wifi=False):+ """Signed out for another account (a phone's Sign out): this computer forgets its Wi-Fi and opens+ its hotspot to be set up again — a phone on the other account sets it up as before. Its harnesses,+ projects and everything else of the person stay, as a sign-out and a sign-in at the screen keep them."""+ log('signing out; the harnesses and projects stay')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'- 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)+ FROM_PHONE.unlink(missing_ok=True)+ if not keep_wifi:+ forget_wifi()+ open_hotspot()+ log('signed out')+++def luks_device():+ """The encrypted disk this computer starts from (installer.py: rd.luks.name=<uuid>=cryptroot), or None."""+ match = re.search(r'(?:^|\s)rd\.luks\.name=([0-9A-Fa-f-]+)=', CMDLINE.read_text())+ return Path('/dev/disk/by-uuid') / match[1] if match else None+++def opens_disk(device, secret):+ return subprocess.run(['cryptsetup', 'open', '--test-passphrase', '--key-file=-', str(device)],+ input=secret.encode(), capture_output=True, timeout=120).returncode == 0+++def opens_account(secret):+ """[secret] is the account's password, as its shadow entry hashes it (libxcrypt's crypt)."""+ shadow = next((line.split(':')[1] for line in Path('/etc/shadow').read_text().splitlines()+ if line.split(':', 1)[0] == USER), '')+ if not shadow or shadow[0] in '!*':+ return False+ libcrypt = ctypes.CDLL(ctypes.util.find_library('crypt'))+ libcrypt.crypt.restype, libcrypt.crypt.argtypes = ctypes.c_char_p, [ctypes.c_char_p, ctypes.c_char_p]+ result = libcrypt.crypt(secret.encode(), shadow.encode())+ return result is not None and hmac.compare_digest(result, shadow.encode())+++def replace_disk_key(device, old, new):+ """[new] among the disk's passphrases in place of [old]: added with [old], then [old] removed. The+ two only in /run, root's, for the moment cryptsetup reads them."""+ folder = Path(tempfile.mkdtemp(prefix='harness-key-', dir='/run'))+ try:+ old_file, new_file = folder / 'old', folder / 'new'+ old_file.write_bytes(old.encode())+ new_file.write_bytes(new.encode())+ subprocess.run(['cryptsetup', 'luksAddKey', '--batch-mode', '--key-file', str(old_file), str(device), str(new_file)],+ check=True, capture_output=True, timeout=180)+ subprocess.run(['cryptsetup', 'luksRemoveKey', '--batch-mode', str(device), str(old_file)],+ check=True, capture_output=True, timeout=180)+ finally:+ shutil.rmtree(folder, ignore_errors=True)+++def account_record():+ try:+ record = json.loads(INITIAL_ACCOUNT.read_text())+ except (OSError, ValueError):+ return {}+ return record if isinstance(record, dict) else {}+++def save_account_record(record):+ INITIAL_ACCOUNT.parent.mkdir(parents=True, exist_ok=True)+ partial = INITIAL_ACCOUNT.with_name(INITIAL_ACCOUNT.name + '.partial')+ partial.write_text(json.dumps(record) + '\n')+ partial.chmod(0o600)+ partial.replace(INITIAL_ACCOUNT)+++def change_password(request):+ """From a phone (the daemon, through sudo; JSON on stdin): the computer's one password changed —+ the disk's, asked at every start where it is encrypted, and the account's (SSH, sudo, the lock+ screen) together, as the installer set them. The current one first, as the disk checks it."""+ current = request.get('current') if isinstance(request, dict) else None+ new = request.get('new') if isinstance(request, dict) else None+ if not isinstance(current, str) or not isinstance(new, str) or not new:+ return {'error': 'BAD_REQUEST', 'message': 'Enter the current password and a new one.'}+ if any(c in new for c in '\n\r\0') or len(new.encode()) > 512:+ return {'error': 'BAD_REQUEST', 'message': 'That password cannot be used.'}+ if new == current:+ return {'error': 'SAME', 'message': 'That is the password already.'}+ device = luks_device()+ if not (opens_disk(device, current) if device else opens_account(current)):+ return {'error': 'WRONG_PASSWORD', 'message': 'That is not the computer\'s password.'}+ if device:+ replace_disk_key(device, current, new)+ record = account_record()+ record['current'] = new+ save_account_record(record)+ subprocess.run(['chpasswd'], input=f'{USER}:{new}\n'.encode(), check=True, capture_output=True, timeout=60)+ log('the computer\'s password changed' + (', the disk\'s with it' if device else ''))+ return {'ok': True, 'disk': device is not None}+++def restore_initial_password():+ """The password as installed (installer.py save_initial_password), account and disk. A computer+ installed before it was kept, or whose disk password changed outside a phone, keeps what it has."""+ record = account_record()+ if record.get('shadow'):+ subprocess.run(['usermod', '-p', record['shadow'], USER], capture_output=True, timeout=60)+ else:+ log('factory reset: no password from the installation; the current one stays')+ device, initial, current = luks_device(), record.get('initial'), record.get('current')+ if not device or not initial or current == initial:+ return+ if current and opens_disk(device, current):+ replace_disk_key(device, current, initial)+ record['current'] = initial+ save_account_record(record)+ log('factory reset: the disk password is the installation\'s again')+ elif not opens_disk(device, initial):+ log('factory reset: the disk password changed outside a phone; it stays')+++def ssh(action='status'):+ """SSH for this computer's network, off as installed: on, off, or how it is, with the addresses+ it answers on (the private ones, for `ssh me@<address>`)."""+ if action in ('on', 'off'):+ subprocess.run(['systemctl', 'enable' if action == 'on' else 'disable', '--now', SSHD],+ capture_output=True, timeout=60)+ def state(verb):+ return subprocess.run(['systemctl', verb, SSHD], capture_output=True, text=True, timeout=15).stdout.strip()+ try:+ links = json.loads(subprocess.run(['ip', '-4', '-j', 'addr', 'show', 'scope', 'global'],+ capture_output=True, text=True, timeout=15).stdout or '[]')+ except ValueError:+ links = []+ addresses = [{'interface': link.get('ifname'), 'address': info.get('local')}+ for link in links if isinstance(link, dict) and link.get('ifname') != HOTSPOT+ for info in link.get('addr_info') or [] if info.get('local') and info.get('local') != ADDRESS]+ return {'enabled': state('is-enabled') == 'enabled', 'active': state('is-active') == 'active',+ 'user': USER, 'addresses': addresses}+++def factory_reset(keep_wifi=False, keep_ssh=False):+ """This computer as just installed: off its account and a new computer to it (a new computer id and+ device key), everything of the person gone — /home/me as the installer made it, so its projects,+ the engines' sign-ins and the hn/CLI updates it downloaded too — its Wi-Fi forgotten, SSH off, the+ password as installed, and its setup hotspot open for a phone. The installed Harness OS stays.+ For `harness factory-reset` at the computer (and, later, its reset button). [keep_wifi], [keep_ssh]:+ for a test machine reached over them."""+ log('factory reset: everything of the person goes')+ # While signed in and its daemon up: off the account, then signed out.+ forget_desk()+ remove_from_account()+ as_user('/usr/bin/harness', 'logout', timeout=60)+ account = pwd.getpwnam(USER)+ # Every process of the person: the screen's session, the daemon, hn, tmux and its harnesses.+ subprocess.run(['loginctl', 'terminate-user', USER], capture_output=True, timeout=60)+ subprocess.run(['systemctl', 'stop', f'user@{account.pw_uid}.service'], capture_output=True, timeout=120)+ subprocess.run(['pkill', '-KILL', '-u', USER], capture_output=True)+ time.sleep(1)+ shutil.rmtree(f'/tmp/hn-{account.pw_uid}', ignore_errors=True)+ # Home as the installer made it: the skeleton and an empty ~/projects.+ wipe(HOME, {})+ subprocess.run(['cp', '-a', '/etc/skel/.', str(HOME)], check=True, timeout=120)+ (HOME / 'projects').mkdir(exist_ok=True)+ subprocess.run(['chown', '-R', f'{account.pw_uid}:{account.pw_gid}', str(HOME)], check=True, timeout=120)+ HOME.chmod(0o700)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).- as_user(HN, 'kill-server')- subprocess.run(['/usr/bin/pkill', '-u', USER, '-x', 'harness-tui'], capture_output=True)- as_user('systemctl', '--user', 'restart', 'hn-screen', timeout=60)+ restore_initial_password()+ if not keep_ssh:+ subprocess.run(['systemctl', 'disable', '--now', SSHD], capture_output=True, timeout=60)if not keep_wifi:- for row in rows('-f', 'UUID,TYPE', 'connection', 'show'):- if len(row) == 2 and row[1] == '802-11-wireless':- nmcli('connection', 'delete', 'uuid', row[0])- # The watcher opens the hotspot for a phone (headless or not: asked for).- NOW.parent.mkdir(parents=True, exist_ok=True)- NOW.touch()+ forget_wifi()+ # Started again as at boot: the person's daemon (lingering), and the screen's first use.+ subprocess.run(['systemctl', 'start', f'user@{account.pw_uid}.service'], capture_output=True, timeout=120)+ subprocess.run(['systemctl', 'restart', '[email protected]'], capture_output=True, timeout=60)+ open_hotspot()log('factory reset done')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('command', nargs='?', choices=['watch', 'now', 'name', 'join', 'reset', 'sign-out',+ 'password', 'ssh'], default='watch')+ parser.add_argument('action', nargs='?', choices=['status', 'on', 'off'], help='ssh: status, on or off')+ parser.add_argument('--keep-wifi', action='store_true', help='reset, sign-out: keep the saved Wi-Fi')+ parser.add_argument('--keep-ssh', action='store_true', help='reset: leave SSH as it is')parser.add_argument('--here', action='store_true', help=argparse.SUPPRESS)arguments = parser.parse_args()- if arguments.command == 'reset':+ if arguments.command in ('reset', 'sign-out'):+ reset = arguments.command == 'reset'if arguments.here:- factory_reset(keep_wifi=arguments.keep_wifi, keep_workspace=arguments.keep_workspace)+ if reset:+ factory_reset(keep_wifi=arguments.keep_wifi, keep_ssh=arguments.keep_ssh)+ else:+ sign_out(keep_wifi=arguments.keep_wifi)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`.- command = ['/usr/bin/systemd-run', f'--unit={RESET_UNIT}', '--collect', '--quiet',- '/usr/bin/python3', str(Path(__file__).resolve()), 'reset', '--here']+ # daemon for a phone) may go with it before it is done. `journalctl -u harness-factory-reset`.+ command = ['/usr/bin/systemd-run', f'--unit={RESET_UNIT if reset else SIGN_OUT_UNIT}', '--collect', '--quiet',+ '/usr/bin/python3', str(Path(__file__).resolve()), arguments.command, '--here']if arguments.keep_wifi:command.append('--keep-wifi')- if arguments.keep_workspace:- command.append('--keep-workspace')+ if arguments.keep_ssh:+ command.append('--keep-ssh')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.')+ raise SystemExit('Could not start: ' + (started.stderr.strip() or 'systemd-run failed'))+ if reset:+ print('Resetting this computer to as it was installed: it leaves its account, and everything in '+ '/home/me goes — projects, sign-ins, harnesses, settings'+ + ('' if arguments.keep_wifi else '; its Wi-Fi is forgotten')+ + '. Its password is the installation\'s again, and its setup hotspot opens for a phone '+ 'in about a minute.')+ else:+ print('Signing out. Its harnesses and projects stay; it opens its setup hotspot to be set up again.')+ return+ if arguments.command == 'password':+ # From the daemon, through sudo: both passwords as JSON on stdin, never in argv; the answer on stdout.+ try:+ request = json.loads(sys.stdin.read(4096) or '{}')+ except ValueError:+ request = None+ try:+ print(json.dumps(change_password(request)))+ except (OSError, subprocess.SubprocessError) as error:+ log(f'the password did not change: {error}')+ print(json.dumps({'error': 'FAILED', 'message': 'The password could not be changed. Try again.'}))+ return+ if arguments.command == 'ssh':+ print(json.dumps(ssh(arguments.action or 'status')))returnif arguments.command == 'join':# From the daemon, through sudo: the Wi-Fi as JSON on stdin, never in argv.diff --git a/os/tests/test_setup.py b/os/tests/test_setup.pyindex de476ff16..c219565df 100644--- a/os/tests/test_setup.py+++ b/os/tests/test_setup.py@@ -271,50 +271,76 @@ class FromPhone(unittest.TestCase):as_user.assert_called_once()+class Account:+ pw_uid, pw_gid = 1000, 1000++class FactoryReset(unittest.TestCase):def home(self, folder):- home = Path(folder)- for path in ['.harness/computer-id', '.harness/cli/data/e2e/identity.json', '.harness/cli/data/registry.json',- '.harness/auth/session.json', '.harness/tui/state.json', '.local/state/harness-os/onboarded',- '.claude/settings.json', 'projects/AGENTS.md']:+ home = Path(folder) / 'me'+ for path in ['.harness/computer-id', '.harness/cli/data/e2e/identity.json', '.harness/auth/session.json',+ '.harness/tui/state.json', '.local/state/harness-os/updates/builds/x/cli.mjs',+ '.claude/settings.json', 'projects/site/index.html', '.bashrc']:(home / path).parent.mkdir(parents=True, exist_ok=True)(home / path).write_text('x')return home- def run_reset(self, home, keep_wifi, keep_workspace=False):- users, wifi = [], []- self.desk = []- state = home / 'state'+ def run_reset(self, home, **flags):+ self.steps, wifi, commands = [], [], []+ state = home.parent / 'state'state.mkdir()(state / 'r.json').write_text('{}')(state / 'from-phone').touch()+ def step(name):+ return lambda *a, **k: self.steps.append(name)+ def user(*command, timeout=30):+ self.steps.append(' '.join(command[-2:]))+ return result()+ def run(command, **_):+ commands.append(command)+ self.steps.append(' '.join(command[:3]))+ return result()with patch.object(setup, 'HOME', home), patch.object(setup, 'RESULT', state / 'r.json'), \- patch.object(setup, 'FROM_PHONE', state / 'from-phone'), patch.object(setup, 'NOW', state / 'now'), \- 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, 'FROM_PHONE', state / 'from-phone'), patch.object(setup, 'NOW', state / 'now'), patch.object(setup, 'PHONE_SETS_UP', state / 'phone'), \+ patch.object(setup, 'SCREEN', state / 'screen'), patch.object(setup, 'as_user', side_effect=user), \+ patch.object(setup.subprocess, 'run', side_effect=run), patch.object(setup.time, 'sleep'), \+ patch.object(setup.pwd, 'getpwnam', return_value=Account()), \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()), \- 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+ patch.object(setup, 'forget_desk', side_effect=step('forget-desk')), \+ patch.object(setup, 'remove_from_account', side_effect=step('remove-from-account')), \+ patch.object(setup, 'restore_initial_password', side_effect=step('restore-password')):+ setup.factory_reset(**flags)+ return wifi, commands, 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):+ def test_it_is_as_just_installed(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])+ wifi, commands, state = self.run_reset(home)+ # Everything of the person: projects, sign-ins, the downloaded hn/CLI, the computer's id+ # and device key (a new computer to its next account). The skeleton is copied back.+ self.assertEqual(sorted(str(p.relative_to(home)) for p in home.rglob('*')), ['projects'])+ self.assertIn(['cp', '-a', '/etc/skel/.', str(home)], commands)+ self.assertIn(['chown', '-R', '1000:1000', str(home)], commands)+ self.assertFalse((state / 'r.json').exists() or (state / 'from-phone').exists())+ self.assertIn(['systemctl', 'disable', '--now', 'sshd.service'], commands)+ self.assertEqual(wifi, [('connection', 'delete', 'uuid', 'u-home')])+ self.assertTrue((state / 'now').exists() and (state / 'phone').exists())++ def test_off_its_account_while_signed_in_then_every_process_before_the_files(self):+ with tempfile.TemporaryDirectory() as folder:+ self.run_reset(self.home(folder))+ order = [self.steps.index(s) for s in ['forget-desk', 'remove-from-account', '/usr/bin/harness logout',+ 'loginctl terminate-user me', 'cp -a /etc/skel/.',+ 'restore-password', 'systemctl start [email protected]',+ 'systemctl restart [email protected]']]+ self.assertEqual(order, sorted(order))++ def test_a_test_machine_keeps_its_wifi_and_ssh(self):+ with tempfile.TemporaryDirectory() as folder:+ wifi, commands, _ = self.run_reset(self.home(folder), keep_wifi=True, keep_ssh=True)+ self.assertEqual(wifi, [])+ self.assertNotIn(['systemctl', 'disable', '--now', 'sshd.service'], commands)def test_the_desk_forgets_this_computer_alone(self):tabs = [{'id': 'own', 'panes': [{'machineId': 'me', 'agentId': 'a'}]},@@ -327,39 +353,109 @@ class FactoryReset(unittest.TestCase):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)- users, wifi, state = self.run_reset(home, keep_wifi=False)- left = sorted(str(p.relative_to(home)) for p in home.rglob('*') if p.is_file())- self.assertIn('.harness/computer-id', left)- self.assertIn('.harness/cli/data/e2e/identity.json', left)- for gone in ['.harness/cli/data/registry.json', '.harness/auth/session.json', '.harness/tui/state.json',- '.local/state/harness-os/onboarded', 'state/r.json', 'state/from-phone']:- self.assertNotIn(gone, left)- # The person's own: the engines' sign-ins and their projects.- self.assertIn('.claude/settings.json', left)- self.assertIn('projects/AGENTS.md', left)- # The account's tabs closed while still signed in, highest first, then the sign-out.- closes = [c for c in users if 'kill-window' in c]- self.assertEqual([c[-1] for c in closes], [':2', ':1'])- self.assertLess(users.index(closes[-1]), next(i for i, c in enumerate(users) if 'logout' in c))- self.assertEqual(wifi, [('connection', 'delete', 'uuid', 'u-home')])- self.assertTrue((state / 'now').exists())+ def test_the_commands_run_in_units_of_their_own(self):+ for argv, unit, tail in [(['reset', '--keep-wifi'], 'harness-factory-reset', ['reset', '--here', '--keep-wifi']),+ (['sign-out'], 'harness-sign-out', ['sign-out', '--here'])]:+ with self.subTest(argv=argv), patch.object(setup.subprocess, 'run', return_value=result()) as run, \+ patch.object(setup.sys, 'argv', ['setup.py', *argv]), patch('builtins.print'):+ setup.main()+ command = run.call_args.args[0]+ self.assertEqual(command[:2], ['/usr/bin/systemd-run', '--unit=' + unit])+ self.assertEqual(command[-len(tail):], tail)- def test_keep_wifi_keeps_it(self):- with tempfile.TemporaryDirectory() as folder:- _, wifi, _ = self.run_reset(self.home(folder), keep_wifi=True)- self.assertEqual(wifi, [])- def test_the_command_runs_it_in_a_unit_of_its_own(self):- with patch.object(setup.subprocess, 'run', return_value=result()) as run, \- patch.object(setup.sys, 'argv', ['setup.py', 'reset', '--keep-wifi']), \- patch('builtins.print'):- setup.main()- command = run.call_args.args[0]- self.assertEqual(command[:2], ['/usr/bin/systemd-run', '--unit=harness-factory-reset'])- self.assertEqual(command[-3:], ['reset', '--here', '--keep-wifi'])+class SignOut(unittest.TestCase):+ def test_it_signs_out_and_opens_the_hotspot_keeping_everything_of_the_person(self):+ users, wifi = [], []+ with tempfile.TemporaryDirectory() as folder:+ state = Path(folder)+ (state / 'from-phone').touch()+ with patch.object(setup, 'as_user', side_effect=lambda *c, timeout=30: users.append(c) or result()), \+ patch.object(setup, 'FROM_PHONE', state / 'from-phone'), patch.object(setup, 'NOW', state / 'now'), patch.object(setup, 'PHONE_SETS_UP', state / 'phone'), \+ patch.object(setup, 'rows', return_value=[['u-home', '802-11-wireless']]), \+ patch.object(setup, 'nmcli', side_effect=lambda *a, **k: wifi.append(a) or result()):+ setup.sign_out()+ self.assertEqual(users, [('/usr/bin/harness', 'logout')])+ self.assertEqual(wifi, [('connection', 'delete', 'uuid', 'u-home')])+ self.assertTrue((state / 'now').exists() and (state / 'phone').exists())+++class Password(unittest.TestCase):+ def change(self, request, device=Path('/dev/disk/by-uuid/u'), opens=True, record=None):+ saved, replaced, runs = [], [], []+ with patch.object(setup, 'luks_device', return_value=device), \+ patch.object(setup, 'opens_disk', return_value=opens), patch.object(setup, 'opens_account', return_value=opens), \+ patch.object(setup, 'replace_disk_key', side_effect=lambda *a: replaced.append(a)), \+ patch.object(setup, 'account_record', return_value=dict(record or {})), \+ patch.object(setup, 'save_account_record', side_effect=saved.append), \+ patch.object(setup.subprocess, 'run', side_effect=lambda c, **k: runs.append((c, k.get('input'))) or result()), \+ patch.object(setup, 'log'):+ answer = setup.change_password(request)+ return answer, replaced, saved, runs++ def test_the_disk_and_the_account_change_together(self):+ answer, replaced, saved, runs = self.change({'current': '1234', 'new': 'abcd'}, record={'initial': '1234'})+ self.assertEqual(answer, {'ok': True, 'disk': True})+ self.assertEqual(replaced, [(Path('/dev/disk/by-uuid/u'), '1234', 'abcd')])+ self.assertEqual(saved, [{'initial': '1234', 'current': 'abcd'}])+ self.assertEqual(runs, [(['chpasswd'], b'me:abcd\n')])++ def test_unencrypted_it_is_the_account_alone(self):+ answer, replaced, saved, runs = self.change({'current': '1234', 'new': 'abcd'}, device=None)+ self.assertEqual(answer, {'ok': True, 'disk': False})+ self.assertEqual((replaced, saved), ([], []))+ self.assertEqual(runs, [(['chpasswd'], b'me:abcd\n')])++ def test_a_wrong_or_unusable_one_changes_nothing(self):+ for request, error in [({'current': 'nope', 'new': 'abcd'}, 'WRONG_PASSWORD'),+ ({'current': '1234', 'new': '1234'}, 'SAME'),+ ({'current': '1234', 'new': ''}, 'BAD_REQUEST'),+ ({'current': '1234', 'new': 'a\nb'}, 'BAD_REQUEST'), (None, 'BAD_REQUEST')]:+ with self.subTest(request=request):+ answer, replaced, saved, runs = self.change(request, opens=request is None or request.get('current') == '1234')+ self.assertEqual(answer['error'], error)+ self.assertEqual((replaced, saved, runs), ([], [], []))++ def test_a_reset_puts_back_the_installation_password(self):+ saved, replaced, runs = [], [], []+ record = {'shadow': '$y$j9T$old', 'initial': '1234', 'current': 'abcd'}+ with patch.object(setup, 'account_record', return_value=dict(record)), \+ patch.object(setup, 'luks_device', return_value=Path('/dev/x')), \+ patch.object(setup, 'opens_disk', side_effect=lambda d, s: s == 'abcd'), \+ patch.object(setup, 'replace_disk_key', side_effect=lambda *a: replaced.append(a)), \+ patch.object(setup, 'save_account_record', side_effect=saved.append), \+ patch.object(setup.subprocess, 'run', side_effect=lambda c, **k: runs.append(c) or result()), \+ patch.object(setup, 'log'):+ setup.restore_initial_password()+ self.assertEqual(runs, [['usermod', '-p', '$y$j9T$old', 'me']])+ self.assertEqual(replaced, [(Path('/dev/x'), 'abcd', '1234')])+ self.assertEqual(saved[-1]['current'], '1234')++ def test_a_computer_installed_before_keeps_its_password(self):+ with patch.object(setup, 'account_record', return_value={}), \+ patch.object(setup, 'luks_device', return_value=Path('/dev/x')), \+ patch.object(setup, 'replace_disk_key') as replace, \+ patch.object(setup.subprocess, 'run') as run, patch.object(setup, 'log'):+ setup.restore_initial_password()+ replace.assert_not_called()+ run.assert_not_called()+++class Ssh(unittest.TestCase):+ def test_on_off_and_the_private_addresses(self):+ links = [{'ifname': 'wlo1', 'addr_info': [{'local': '172.168.21.13'}]},+ {'ifname': 'harness-setup', 'addr_info': [{'local': '10.42.0.1'}]}]+ calls = []+ def run(command, **_):+ calls.append(command)+ if command[0] == 'ip':+ return result(output=json.dumps(links))+ return result(output='enabled' if command[1] == 'is-enabled' else 'active')+ with patch.object(setup.subprocess, 'run', side_effect=run):+ answer = setup.ssh('on')+ self.assertEqual(calls[0], ['systemctl', 'enable', '--now', 'sshd.service'])+ self.assertEqual(answer, {'enabled': True, 'active': True, 'user': 'me',+ 'addresses': [{'interface': 'wlo1', 'address': '172.168.21.13'}]})class Server: