From 2238046925d021aaf75324f07e24c0726c69caad Mon Sep 17 00:00:00 2001 From: James Tervit Date: Mon, 30 Nov 2026 13:19:49 +0800 Subject: [PATCH] Machines: this server shows its own restart, failed-service and port readings A joined computer's connector reports whether it needs a restart, how many system services have failed and which ports it listens on, and its machine page shows them beside the gauges. This server showed none of that about itself. - omarchyd/posture.mjs reads the same things for this server: a restart needed after a kernel update (or when the system says so), failed system services (systemctl, asked at most once a minute) and TCP ports listening beyond this machine (/proc/net/tcp and tcp6). Reads only, nothing needs root. - New query system.posture, owner only, as a joined computer's details are. A member's browser never asks for it. - This server's card and machine page pass it to the same readings a joined computer uses, so no new screen or drawing. Security updates stay absent for this server: its waiting updates are not split into security and other. Co-Authored-By: Chronara AI --- omarchyd/posture.mjs | 90 ++++++++++++++++++++++++++++++++ omarchyd/server.mjs | 4 ++ server/app.mjs | 1 + test/fake-omarchyd.mjs | 8 +++ test/omarchyd.test.mjs | 11 ++++ test/posture.test.mjs | 77 +++++++++++++++++++++++++++ web/src/data.ts | 7 +++ web/src/fleet/MachineManager.tsx | 4 +- web/src/fleet/ServerSheet.tsx | 5 +- web/src/fleet/serverGauges.tsx | 6 ++- 10 files changed, 208 insertions(+), 5 deletions(-) create mode 100644 omarchyd/posture.mjs create mode 100644 test/posture.test.mjs diff --git a/omarchyd/posture.mjs b/omarchyd/posture.mjs new file mode 100644 index 00000000..e8b860bf --- /dev/null +++ b/omarchyd/posture.mjs @@ -0,0 +1,90 @@ +// This server's own posture: whether it needs a restart, how many system services have failed, +// and which ports it listens on beyond itself. A joined computer's connector reports the same +// readings (connector/agent.py host_posture), so this server's machine page can show what theirs do. +// Reads only: two /proc files, two paths and one `systemctl list-units`. Nothing here needs root. +import {execFile} from 'node:child_process' +import {access, readdir, readFile} from 'node:fs/promises' +import os from 'node:os' + +const FAILED_TTL_MS = 60_000 +const SERVICE_NAME = /^[A-Za-z0-9@._:-]{1,120}\.service$/ +const MAX_PORTS = 50 + +const execRun = (cmd, args, {timeout = 2000} = {}) => + new Promise((resolve) => execFile(cmd, args, {timeout, maxBuffer: 1024 * 1024}, (error, stdout) => resolve({code: error ? 1 : 0, stdout: String(stdout ?? '')}))) + +/** + * TCP ports listening on something other than this machine alone, from /proc/net/tcp and tcp6. + * `addr` is '0.0.0.0' or '::' for every address, and 'lan' for one address of this machine. + */ +export function listeningPorts(tcp = '', tcp6 = '') { + const seen = new Set() + const out = [] + for (const [raw, proto] of [[tcp, 'tcp'], [tcp6, 'tcp6']]) { + for (const line of String(raw ?? '').split('\n').slice(1)) { + const parts = line.trim().split(/\s+/) + // 0A is TCP_LISTEN. + if (parts.length < 4 || parts[3] !== '0A') continue + const at = parts[1].lastIndexOf(':') + if (at < 0) continue + const ip = parts[1].slice(0, at).toUpperCase() + const port = parseInt(parts[1].slice(at + 1), 16) + if (!Number.isInteger(port) || port <= 0 || port > 65535) continue + let addr + if (proto === 'tcp') { + // The address is little-endian hex, so 127.x.x.x ends in 7F. + if (ip.endsWith('7F')) continue + addr = ip === '00000000' ? '0.0.0.0' : 'lan' + } else { + // ::1, and 127.0.0.1 written as an IPv6 address. + if (ip === '00000000000000000000000001000000' || ip === '0000000000000000FFFF00000100007F') continue + addr = ip === '0'.repeat(32) ? '::' : 'lan' + } + const key = `${port}/${proto}/${addr}` + if (seen.has(key)) continue + seen.add(key) + out.push({port, proto, addr}) + } + } + return out.sort((a, b) => a.port - b.port || a.proto.localeCompare(b.proto)).slice(0, MAX_PORTS) +} + +/** Failed system services in `systemctl list-units --plain --no-legend` output. */ +export function failedUnits(stdout = '') { + return String(stdout) + .split('\n') + .map((line) => line.trim().split(/\s+/)) + .filter((parts) => parts.length >= 4 && SERVICE_NAME.test(parts[0])).length +} + +const fileExists = (path) => access(path).then(() => true, () => false) +const fileText = (path) => readFile(path, 'utf8').catch(() => '') + +export function createPosture({read = fileText, exists = fileExists, listDir = readdir, kernel = os.release(), run = execRun, now = Date.now} = {}) { + let failed = {at: -Infinity, count: 0} + + // A restart is needed when the system says so (Debian, Ubuntu), or when the running kernel's + // modules are gone because a newer kernel replaced them (Arch, Omarchy). + async function restart() { + if (await exists('/var/run/reboot-required')) return {rebootRequired: true, rebootReason: 'System updates require a restart'} + if (kernel && (await exists('/usr/lib/modules'))) { + const mods = await Promise.resolve(listDir('/usr/lib/modules')).catch(() => []) + if (mods.length && !mods.includes(kernel)) return {rebootRequired: true, rebootReason: `Kernel updated (running ${kernel})`} + } + return {rebootRequired: false, rebootReason: ''} + } + async function failedCount() { + if (now() - failed.at < FAILED_TTL_MS) return failed.count + const r = await run('systemctl', ['--system', 'list-units', '--type=service', '--state=failed', '--no-pager', '--no-legend', '--plain']) + // A machine without systemd, or a systemctl that didn't answer, keeps the last count. + failed = {at: now(), count: r.code === 0 ? failedUnits(r.stdout) : failed.count} + return failed.count + } + return { + async get() { + const [state, count, tcp, tcp6] = await Promise.all([restart(), failedCount(), read('/proc/net/tcp'), read('/proc/net/tcp6')]) + // This server's waiting updates are not split into security and other, so that reading is absent. + return {...state, securityUpdates: null, listeningPorts: listeningPorts(tcp, tcp6), failedUnits: count} + }, + } +} diff --git a/omarchyd/server.mjs b/omarchyd/server.mjs index 48633c02..4a4dd5fc 100644 --- a/omarchyd/server.mjs +++ b/omarchyd/server.mjs @@ -48,6 +48,7 @@ import {createHermes} from './hermes.mjs' import * as system from './system.mjs' import {createSampler} from './stats.mjs' import {createOsInfo} from './os-info.mjs' +import {createPosture} from './posture.mjs' import {WebSocketServer} from 'ws' import {viewerBackpressure} from './backpressure.mjs' import {nixCacheConfText, readNixCache, writeNixCache} from './nix-cache.mjs' @@ -305,6 +306,7 @@ export async function startOmarchyd({port = 2021, host = '127.0.0.1', dataDir, t } const release = await system.osRelease() const osInfo = createOsInfo({release}) + const posture = createPosture() // Live gauges: hardware is sampled on its own interval while a screen is reading. // The timer starts on the first read and stops about 15s after the last one, @@ -450,6 +452,8 @@ export async function startOmarchyd({port = 2021, host = '127.0.0.1', dataDir, t 'system.getIpAddresses': {kind: 'query', run: () => system.ipAddresses()}, 'system.device': {kind: 'query', run: async () => ({device: await system.deviceName(), os: release.pretty})}, 'system.osInfo': {kind: 'query', run: () => osInfo.get()}, + // This server's restart, failed-service and listening-port readings. Owner only, like a joined computer's. + 'system.posture': {kind: 'query', run: (_input, {auth}) => (ownerOnly(auth, 'see this server’s security readings'), posture.get())}, // ---- Settings: power, logs, device name, two-factor, sessions, reset ---------------------- 'system.restart': {kind: 'mutation', run: async (input, {auth}) => (ownerOnly(auth, 'restart the server'), await bootGuard(input, 'restart'), power('reboot'))}, diff --git a/server/app.mjs b/server/app.mjs index e6dbde0e..091905b6 100644 --- a/server/app.mjs +++ b/server/app.mjs @@ -101,6 +101,7 @@ export const ALLOWED = { 'system.cpuTemperature': 'query', 'system.stats': 'query', 'system.history': 'query', + 'system.posture': 'query', 'system.bootStart': 'query', 'system.enableBootStart': 'mutation', 'system.cpuUsage': 'query', diff --git a/test/fake-omarchyd.mjs b/test/fake-omarchyd.mjs index d9b7a9ca..12fb96df 100644 --- a/test/fake-omarchyd.mjs +++ b/test/fake-omarchyd.mjs @@ -398,6 +398,14 @@ export async function startFakeserverd({ }), }, 'system.batteryUsage': {kind: 'query', run: () => ({batteries: []})}, + // Owner only, like the real one. A restart is waiting and one service has failed. + 'system.posture': { + kind: 'query', + run: (_input, auth) => + accountOf(auth.userId).role !== 'owner' + ? {error: ['FORBIDDEN', 'Only the server’s owner can see this server’s security readings']} + : {rebootRequired: true, rebootReason: 'Kernel updated (running 6.12.1-arch1-1)', securityUpdates: null, listeningPorts: [{port: 22, proto: 'tcp', addr: '0.0.0.0'}, {port: 7780, proto: 'tcp', addr: '0.0.0.0'}], failedUnits: 1}, + }, 'system.stats': { kind: 'query', run: () => ({ diff --git a/test/omarchyd.test.mjs b/test/omarchyd.test.mjs index 3ba1afdb..27255283 100644 --- a/test/omarchyd.test.mjs +++ b/test/omarchyd.test.mjs @@ -259,6 +259,17 @@ describe('network shares are owner-only', () => { } assert.equal((await call('query', 'storage.pools', undefined, member)).status, 200, 'members can still see pools') }) + test('this server’s posture readings are the owner’s: a member is refused', async () => { + const r = await call('query', 'system.posture', undefined, member) + assert.equal(r.status, 403) + assert.match(r.body.error.message, /owner/i) + const mine = await call('query', 'system.posture', undefined, owner) + assert.equal(mine.status, 200) + const p = mine.body.result.data + assert.equal(typeof p.rebootRequired, 'boolean') + assert.equal(typeof p.failedUnits, 'number') + assert.ok(Array.isArray(p.listeningPorts)) + }) test('a member cannot read or change a NixOS configuration', async () => { const rpcs = [ ['query', 'machines.nixosConfig', {id: 'abcd1234'}], diff --git a/test/posture.test.mjs b/test/posture.test.mjs new file mode 100644 index 00000000..d939d3e5 --- /dev/null +++ b/test/posture.test.mjs @@ -0,0 +1,77 @@ +// This server's own posture readings: restart needed, failed services and listening ports. +import assert from 'node:assert/strict' +import {test} from 'node:test' + +import {createPosture, failedUnits, listeningPorts} from '../omarchyd/posture.mjs' + +const HEAD = ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n' +const row = (local, state = '0A') => ` 0: ${local} 00000000:0000 ${state} 00000000:00000000 00:00000000 00000000 0 0 1 1 0 100 0 0 10 0\n` +const HEAD6 = ' sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n' + +test('listening ports: every address, one address, and nothing that listens on this machine alone', () => { + const tcp = HEAD + row('00000000:1E64') + row('0100007F:07E5') + row('3644A8C0:0016') + row('00000000:01BB', '01') + row('00000000:1E64') + const tcp6 = HEAD6 + row('00000000000000000000000000000000:1E64') + row('00000000000000000000000001000000:0277') + row('0000000000000000FFFF00000100007F:1F90') + row('000080FE00000000FF005450B6AD1DFE:0050') + assert.deepEqual(listeningPorts(tcp, tcp6), [ + {port: 22, proto: 'tcp', addr: 'lan'}, + {port: 80, proto: 'tcp6', addr: 'lan'}, + {port: 7780, proto: 'tcp', addr: '0.0.0.0'}, + {port: 7780, proto: 'tcp6', addr: '::'}, + ]) +}) + +test('listening ports: damaged or missing files give an empty list, and the list stops at 50', () => { + assert.deepEqual(listeningPorts('', ''), []) + assert.deepEqual(listeningPorts(undefined, null), []) + assert.deepEqual(listeningPorts(HEAD + 'rubbish\n' + row('nocolon') + row('00000000:ZZZZ') + row('00000000:0000') + row('00000000:FFFFF'), ''), []) + const many = HEAD + Array.from({length: 80}, (_, i) => row(`00000000:${(1000 + i).toString(16).toUpperCase().padStart(4, '0')}`)).join('') + assert.equal(listeningPorts(many, '').length, 50) +}) + +test('failed services are counted from systemctl’s list, and odd lines are ignored', () => { + assert.equal(failedUnits(''), 0) + assert.equal(failedUnits('smb.service loaded failed failed Samba SMB Daemon\nfoo@1.service loaded failed failed Foo\n'), 2) + assert.equal(failedUnits('\n \nnot a unit line\nbad name! loaded failed failed x\n'), 0) +}) + +const machine = ({files = {}, dirs = {}, kernel = '6.12.1-arch1-1', units = '', code = 0, calls = []} = {}) => + createPosture({ + read: async (path) => files[path] ?? '', + exists: async (path) => path in files || path in dirs, + listDir: async (path) => dirs[path] ?? [], + kernel, + run: async (cmd, args) => (calls.push([cmd, ...args].join(' ')), {code, stdout: units}), + now: () => machine.now, + }) +machine.now = 0 + +test('a healthy server: no restart, no failed services, its ports listed', async () => { + const p = await machine({dirs: {'/usr/lib/modules': ['6.12.1-arch1-1']}, files: {'/proc/net/tcp': HEAD + row('00000000:1E64')}}).get() + assert.deepEqual(p, {rebootRequired: false, rebootReason: '', securityUpdates: null, listeningPorts: [{port: 7780, proto: 'tcp', addr: '0.0.0.0'}], failedUnits: 0}) +}) + +test('a restart is needed after a kernel update, or when the system says so', async () => { + const arch = await machine({dirs: {'/usr/lib/modules': ['6.12.2-arch1-1']}}).get() + assert.equal(arch.rebootRequired, true) + assert.equal(arch.rebootReason, 'Kernel updated (running 6.12.1-arch1-1)') + const debian = await machine({files: {'/var/run/reboot-required': ''}, dirs: {'/usr/lib/modules': ['6.12.1-arch1-1']}}).get() + assert.deepEqual([debian.rebootRequired, debian.rebootReason], [true, 'System updates require a restart']) + // No modules folder (a container), or one that can't be read: no restart is claimed. + assert.equal((await machine().get()).rebootRequired, false) + assert.equal((await machine({dirs: {'/usr/lib/modules': []}}).get()).rebootRequired, false) +}) + +test('failed services: systemctl is asked once a minute, and a failed ask keeps the last count', async () => { + const calls = [] + machine.now = 0 + const p = machine({units: 'smb.service loaded failed failed Samba\n', calls}) + assert.equal((await p.get()).failedUnits, 1) + machine.now = 30_000 + assert.equal((await p.get()).failedUnits, 1) + assert.equal(calls.length, 1, 'not asked again within a minute') + assert.equal(calls[0], 'systemctl --system list-units --type=service --state=failed --no-pager --no-legend --plain') + machine.now = 61_000 + await p.get() + assert.equal(calls.length, 2) + machine.now = 0 + assert.equal((await machine({code: 1, units: 'x.service loaded failed failed X\n'}).get()).failedUnits, 0, 'no systemd: zero, not a guess') +}) diff --git a/web/src/data.ts b/web/src/data.ts index 55e4a298..fdc05094 100644 --- a/web/src/data.ts +++ b/web/src/data.ts @@ -14,6 +14,8 @@ import { type UserApp, } from './api' import {OFFLINE_ACTION_MESSAGE, isBrowserOnline} from './connection' +import type {PostureSummary} from './fleet/statView' +import {isOwner} from './isOwner' import {applyOptimisticAppState, rollbackOptimisticAppState} from './optimisticApps' import {isAppBusy, useToast} from './ui' @@ -47,6 +49,11 @@ export const useGpus = () => useQuery({...statsQuery, select: (s) => s.gpu}) export const useBattery = () => useQuery({...statsQuery, select: (s) => s.battery}) export const useUptime = () => useQuery({...statsQuery, select: (s) => s.uptime}) export const useSystemNet = () => useQuery({...statsQuery, select: (s) => s.net ?? null}) +/** This server's restart, failed-service and listening-port readings. The owner's only, so a member's browser never asks. */ +export const useServerPosture = () => { + const owner = isOwner(useUser().data) + return useQuery({queryKey: ['system.posture'], queryFn: () => query('system.posture'), enabled: owner, refetchInterval: 60_000, staleTime: 30_000}) +} export const useNotifications = () => useQuery({queryKey: ['notifications.get'], queryFn: () => query('notifications.get'), refetchInterval: 30_000}) export const useMachines = () => diff --git a/web/src/fleet/MachineManager.tsx b/web/src/fleet/MachineManager.tsx index 92549ad4..dff4534e 100644 --- a/web/src/fleet/MachineManager.tsx +++ b/web/src/fleet/MachineManager.tsx @@ -44,6 +44,7 @@ import { } from './machineManagerLogic' import {LiveStats} from './StatRegion' import {useServerGaugeMetrics} from './serverGauges' +import {useServerPosture} from '../data' const TerminalTabs = lazy(() => import('../TerminalTabs').then((m) => ({default: m.TerminalTabs}))) type Alert = {agentId: string; severity: 'info' | 'warning' | 'critical'} @@ -320,12 +321,13 @@ function ServerRow({ onDesktop: () => void }) { const {metrics, temp, sensors, uptime} = useServerGaugeMetrics() + const posture = useServerPosture() if (lines) return const seen = seenFact(member.online, uptime, null, Date.now()) return (
- + query('system.getIpAddresses')}) const [historyRange, setHistoryRange] = useState<'1h' | '24h'>('1h') @@ -204,7 +205,7 @@ export function ServerSheet({ terminal={{enabled: !!onTerminal, onOpen: () => onTerminal?.()}} desktop={owner ? {enabled: true, onOpen: onDesktop} : undefined} pin={} - stats={} + stats={} facts={} />} onBack={onBack} > diff --git a/web/src/fleet/serverGauges.tsx b/web/src/fleet/serverGauges.tsx index 175cbf16..3297d7f4 100644 --- a/web/src/fleet/serverGauges.tsx +++ b/web/src/fleet/serverGauges.tsx @@ -2,7 +2,7 @@ import type {ReactNode} from 'react' import {useQuery} from '@tanstack/react-query' import {query, type ThermalSensor} from '../api' -import {useBattery, useCpu, useDisk, useGpus, useMemory, useTemp, useUptime} from '../data' +import {useBattery, useCpu, useDisk, useGpus, useMemory, useServerPosture, useTemp, useUptime} from '../data' import {BatteryRing} from './BatteryRing' import type {FleetRings, GaugeKind} from './aggregate' import {Icon, type IconName} from '../icons' @@ -165,7 +165,9 @@ export function GaugeCluster({ ) } +/** This server's readings on its machine page, with its posture readings (restart, failed services, ports) like a joined computer's. */ export function ServerRings({name}: {name?: string} = {}) { const {metrics, temp, sensors} = useServerGaugeMetrics() - return + const posture = useServerPosture() + return }