LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.
C cdebiandesktop-environmentebpffirewalllandlocklinuxlinux-distributionopen-sourceprivacyquickjsraspberry-pi-5reactsecuritywaylandwayland-compositor
Merge v084-net for 0.8.5: Monitor → Network second generation, LordOS components as their own firewall apps, blocklists (lord-fetch), deny mode, menu bar network item
Federico Pereira9120fbd99a07
diff --cc CHANGELOG.mdindex 823b551,c8b8cc6..13cdd4c--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -10,153 -10,36 +10,181 @@@ of the matching [GitHub release](https:## [Unreleased]-## [0.8.4] - Unreleased-+ ### Added++ - **Monitor → Network, second generation.** The app list is now a tree: each app opens into the+ sites and addresses it talks to, and each address into its ports, with what was sent and received+ everywhere, a small live meter and an allow/block switch on every destination. One pop-up button+ holds the whole view (group by app, domain, address, port or country; incoming or outgoing; TCP or+ UDP; allowed, denied or with rules; sort by name, most or least traffic, most recent or most+ connections), remembered for each user. The search turns `app:`, `domain:`, `ip:`, `port:`,+ `proto:` and `country:` into chips you can combine, and the history zoom (1 h to 30 d) now also+ shows each app's traffic for that window.+ - **LordOS's own parts have their own rows and rules.** Mail and the calendar sync, the Store and+ updates, printers and scanners, the Terminal (with the names of the programs you run in it) and+ the blocklist updates each run in a process of their own, so you can see and block each one+ separately, and the kernel enforces it. Blocking the Store asks first, because security updates+ stop. Name resolution, time synchronization, the network service and your VPN tunnels are shown+ too, and are never blocked.+ - **Blocklists.** Settings → Privacy → Blocklists offers public lists of advertising, tracker,+ malware and attacking sites, each with its source and licence; turn one on and LordOS downloads+ it over HTTPS once a day, in a sandboxed downloader, and blocks those destinations for every app.+ You can add your own list by its https address. A rule you write for a site always wins over a+ list: switch a blocked site on in the Monitor and it stays allowed.+ - **Deny silently.** A new firewall mode: only what a rule allows can connect, and everything else is+ denied and recorded (this computer's own services keep working). In Settings → Privacy and in the+ new menu bar item.+ - **Network activity in the menu bar** (optional, off by default): upload and download rates in the+ menu bar, and a panel with the last five minutes, the apps moving data now, what was recently+ denied, the firewall mode, the blocklists and a link to the Monitor.++### Fixed++- A monitor plugged in after boot now shows the login screen. The login screen never listened for the+ kernel's display events, so a board booted without HDMI (a Raspberry Pi 5) stayed without video until+ it was restarted. It now follows them like a session does, without the system bus.+- The Store's package engine could not download packages with a `+` in their name (`kms++-utils`,+ `libkms++0`) from lordos.org: the CDN reads a bare `+` as a space and answered 404. It now sends+ `%2B`, as apt does, so Settings → Board firmware can install the bootloader tools from the LordOS+ repository alone.++## [0.8.4.1-beta] - 2026-10-25++An update of 0.8.4 for the Raspberry Pi 5: its bootloader from Settings, and a new Pi image with the+HDMI fix, the browsers and the ISO's system packages (0.8.4 held its Pi image back).++### Added++- **Settings → Board firmware (Raspberry Pi 5).** A new page, only on a Raspberry Pi 5 (and Pi 500,+ Compute Module 5), for the bootloader that lives in the board's EEPROM: the installed version, the+ newest one available, whether it is up to date, and **Update**. After updating it says a restart+ finishes the job and offers **Restart…**; the board installs the new bootloader as it starts,+ keeping its recovery path. This is LordOS's replacement for the bootloader part of+ `raspi-config` (ignore `rpi-eeprom-update`'s hint to run it). It runs only the system's+ `rpi-eeprom-update` with a fixed set of options, through two closed admin actions: reading the+ status is open to everyone, updating needs an administrator (`docs/SETTINGS.md`, "Board+ firmware").+- **The bootloader updater in the LordOS repository.** `rpi-eeprom` (the bootloader images and+ `rpi-eeprom-update`) and the few Raspberry Pi packages it needs (`raspi-utils` and its parts,+ `raspinfo`, `kms++`) are now mirrored in `lordos.org/apt` for arm64, copied from Raspberry Pi's+ archive only after its signature and every file's SHA-256 check out against a pinned list+ (`tools/release/rpi-mirror.list`). A Pi with only the LordOS and Debian repositories gets new+ bootloaders with the usual updates; PCs never see these packages (`docs/UPDATES.md`, "Raspberry+ Pi firmware packages").+- **Browsers in the Raspberry Pi image.** Chromium and Firefox ESR come preinstalled, as on the ISO,+ with the same defaults: a single bar with their tabs and LordOS's window buttons, the LordOS GTK+ theme and the video settings of Settings → Displays → Video (the defaults are now one script+ shared by both images, `tools/iso/browser-defaults.sh`).+- **The rest of the ISO's system packages in the Pi image:** automatic time (`systemd-timesyncd`),+ printing (`cups`, `avahi-daemon`), exFAT and NTFS drives, power profiles, the MIME database and+ the GTK settings schemas. The first user is also allowed to manage printers (`lpadmin`), as on a PC.++### Fixed++- **Raspberry Pi 5 on an HDMI monitor stayed on the text console** ("no display device with KMS").+ The firmware ignored the display driver line in the image's `config.txt` because it came before+ the `display_auto_detect` and `camera_auto_detect` lines; it now comes after them. Together with+ 0.8.4's longer wait for the display driver, the desktop shows on HDMI at the first boot.+- **The Pi image's clock.** The board keeps no time without a battery and the image had no network+ time client, so it started months behind and every update failed with "not valid yet". It now+ sets the time from the network at boot.++### Known issues and limitations++- **A monitor plugged in after boot stays black** until the board is restarted: the login screen+ doesn't follow the kernel's display events yet. Connect the HDMI monitor before switching the board+ on. Fixed for 0.8.5.+- **A Pi set up from the 0.8.3 image** has no network time client: if Store → Updates fails, set the+ time in Settings → Date & Time first, then install `systemd-timesyncd` from the Store.+- **The bootloader release** (*Default* or *Latest*) is shown but not changed from Settings: it is+ `/etc/default/rpi-eeprom-update`, a file of the `rpi-eeprom` package.+- **Raspberry Pi archive on the Pi image.** The image still lists Raspberry Pi's archive, limited by+ apt priorities to the firmware, kernel tools and utilities; the Store's own package engine does+ not read apt priorities yet, so "Update all" there may take Raspberry Pi's builds of a few+ packages (such as Chromium or BlueZ) instead of Debian's. `apt` follows the priorities.+- **`install.sh` does not install browsers** (on a Raspberry Pi OS Lite or any Debian 13): install+ Chromium or Firefox ESR from the Store if the system has none (`docs/INSTALL-DEBIAN.md`).++### Upgrading++- **From 0.8.4 (and 0.8.3 to 0.8.1):** Store → Updates shows "LordOS 0.8.4.1 is available" with+ these notes; **Update** installs it and a restart finishes it. `sudo apt update && sudo apt+ upgrade` does the same. No migration runs (`ls /var/lib/lordos/migrations` is unchanged from+ 0.8.4); your settings are kept. On a PC nothing else changes.+- **Raspberry Pi 5:** after the update, Settings shows **Board firmware**. If it says+ "The bootloader tools are not installed", **Install** adds `rpi-eeprom` from the LordOS+ repository. The browsers and the other image packages above are not added to a board that is+ already set up: install them from the Store.++## [0.8.4-beta] - 2026-10-19++### Added++- **Settings → Appearance → «Browsers: tabs in the title bar».** One switch for both preinstalled+ browsers: on (the default), Chromium and Firefox draw a single bar with their tabs and LordOS's+ window buttons; off, they use the LordOS frame. It changes the setting in your own browser+ profiles and applies the next time each browser opens; if Chromium is open, it waits until you+ quit it. Chromium profiles from before this version that still use the LordOS frame are shown on+ the page, with a button to change them too. A choice you made yourself in a Firefox `user.js`+ file is left alone, and choices you make later in the browsers' own settings stick.+- **Remote desktop as video.** The remote desktop now arrives as real video (H.264, or VP8 when the+ browser has no H.264) with the session's sound (Opus), instead of images. Still areas are then+ made pixel-perfect with lossless tiles, so text stays sharp. Dragging a window went from about 23+ frames per second and 12.5 Mbit/s to about 29 frames per second and under 1 Mbit/s, and the+ connection's own process from 57 % of a core to 2 %. The session encodes once (on the graphics+ card with VA-API when it can, else in software) for every viewer of that session; the screen keeps+ being composed on the graphics card while someone watches. Keyboard, mouse and clipboard go over a+ WebRTC data channel. Video is the only way the remote desktop works (see Removed).+- **The remote desktop works where UDP is blocked.** Besides UDP, the video also connects over TCP+ on the remote desktop's own port (5673), so a firewall or VPN that only lets that port through+ is enough; on the local network nothing else is needed. With UDP blocked, video plays about 2 s+ after the page loads.+- **The remote desktop reconnects by itself.** When the network drops or changes, the page keeps the+ last frame with a "Reconnecting…" note and recovers on its own, without signing in again: first+ on the same encrypted connection (back within a fraction of a second once the network returns,+ after a 20-second outage), then with a new one, then with a new connection to the computer after+ longer outages (75 seconds were tested).+- **Clear messages when it can't connect.** If there is really no way through, the page says why+ (nothing gets through over UDP or TCP, the encrypted channel couldn't be set up, the connection+ was lost, the browser can't play the video…) and what to do, with a Try again button. A browser+ without WebRTC, or without H.264 and VP8, gets a page that lists what it needs.+- **Settings → Sharing → Connection:** add public STUN servers and a TURN relay for connecting across+ networks, reached over UDP, TCP or TLS (port 443 works). Over TLS the relay's certificate is+ checked against the system's certificate authorities and its name, or against a fingerprint you+ paste for a relay with its own certificate. A built-in STUN server covers the local network, and+ nothing reaches outside servers unless you add them. The relay's password stays on the computer,+ readable only by the system, and is never sent to the browser.+- **LordOS Imager.** Write LordOS to an SD card or a USB stick and have the Raspberry Pi 5 start+ ready to use: choose the device (Raspberry Pi 5, or a PC from a USB stick), the system image (the+ latest signed release, downloaded once and resumed if interrupted, or a file of your own with a+ clear warning) and the drive (only SD cards and USB drives; internal disks and the disk the+ computer runs from are never shown), then customise the first boot: computer name, language,+ time zone, keyboard, your account (only a hash of the password goes on the card), Wi-Fi (only the+ derived key), SSH with keys or a password, LordOS remote desktop (local network only), Bluetooth,+ Lord Default or Classic in light or dark with your accent, and cooling (case with a fan, active+ cooler, passive case or nothing, with a matching profile and an optional mild overclock with a+ fan). Lumo gives a tip at every step and celebrates at the end. Every official image is checked+ against the LordOS release signature before anything is erased, and every card is read back and+ compared after writing; cancelling clears the card. In English, Spanish and Portuguese, with+ keyboard navigation. See [docs/IMAGER.md](docs/IMAGER.md).+- **The LordOS Imager for other computers**: the same app for the three common desktop platforms (Tauri, about+ 6 MB), sharing the interface with the one in LordOS, attached to this release as+ `lordos_imager_0.8.4_universal.dmg` (both processor families, signed and notarized, so it opens+ without warnings), `lordos_imager_0.8.4_amd64.deb` (needs udisks2 and a polkit agent) and+ `lordos_imager_0.8.4_x64_setup.exe` (not code-signed yet, see Known issues), all listed in the+ signed `SHA256SUMS`.+- **First-run file on the Raspberry Pi** (`lordos-firstrun.txt` on the boot partition): read once on+ the first boot by `lordos-firstrun`, strictly validated (nothing is applied if any part is wrong),+ then overwritten and deleted. See [docs/RASPBERRY.md](docs/RASPBERRY.md), "First boot".++### Security++- The imager's privileged part is four closed actions: downloads run `curl` as the user against two+ fixed URL shapes; writing accepts only a whole removable disk whose size, model and serial are+ re-checked right before it is opened exclusively, decompresses with `xz` running as the user, and+ never writes an official image whose signature or hash doesn't match. Over 2 TiB is refused.+- Saved Wi-Fi networks may hold a derived WPA2 key (`psk=`) instead of the password.+### Changed- **Browsers with a single top bar.** Chromium and Firefox now draw their own bar, with the tabs indiff --cc apps/monitor/Blocklists.jsxindex 0000000,5297241..3c3d652mode 000000,100644..100644--- a/apps/monitor/Blocklists.jsx+++ b/apps/monitor/Blocklists.jsx@@@ -1,0 -1,112 +1,112 @@@-// Blocklists.jsx — Settings → Privacy → "Blocklists" (0.8.4; registered with registerPrivacySection,++// Blocklists.jsx — Settings → Privacy → "Blocklists" (0.8.5; registered with registerPrivacySection,+ // like the other Monitor items). See docs/FIREWALL.md, "Blocklists".+ // - the curated catalog by topic (advertising, trackers, malware), each list with its source, its+ // licence, how many entries it has and when it was last downloaded; a checkbox turns it on;+ // - custom lists: an https address and its format (hosts file, one domain per line, one address+ // or network per line);+ // - "Update now"; otherwise lord-server downloads the enabled lists once a day.+ // Lists never override a rule the owner wrote for a destination, and lord-server writes every file+ // (lord.fw.*List); this screen writes none.+ import { View, Text, Button, Segmented, GroupBox, TextInput, useTheme, useLocale, useStore, firewall, firewallState, spacing, typeScale, formatNumber, formatDate, formatTime, tOptional, errorText } from '@lordos/sdk';+ import { useEffect, useState } from 'react';++ const TOPICS = ['ads', 'trackers', 'malware', 'custom'];++ function CheckBox({ on, onChange }) {+ const t = useTheme();+ return (+ <View onClick={() => onChange(!on)} style={{ width: 16, height: 16, borderRadius: 4, border: `1px solid ${on ? t.accent : t.textDim}`,+ backgroundColor: on ? t.accent : 'transparent', alignItems: 'center', justifyContent: 'center' }}>+ {on ? <Text style={{ fontSize: 11, color: '#fff', fontWeight: 700 }}>✓</Text> : null}+ </View>+ );+ }++ const when = (s) => { const d = new Date(s * 1000); return `${formatDate(d)} ${formatTime(d)}`; };++ function ListRow({ l, tr, onToggle, onRemove }) {+ const t = useTheme();+ const name = l.custom ? l.url.replace(/^https:\/\//, '') : tOptional(`firewall.lists.name.${l.id}`) || l.id;+ const entries = l.domains + l.nets;+ const status = l.error ? tr('firewall.lists.failed', { error: tOptional(`firewall.lists.err.${l.error.split(' ')[0]}`) || l.error })+ : l.updated ? tr('firewall.lists.updated', { count: formatNumber(entries, 0), when: when(l.updated) })+ : l.on ? tr('firewall.lists.pending') : l.approx ? tr('firewall.lists.about', { count: formatNumber(l.approx, 0) }) : '';+ return (+ <View style={{ minHeight: 44, flexDirection: 'row', alignItems: 'center', gap: spacing.m, paddingVertical: 7 }}>+ <CheckBox on={l.on} onChange={onToggle} />+ <View style={{ flex: 1, minWidth: 0, gap: 2 }}>+ <Text style={{ fontSize: typeScale.body, color: t.text, textAlign: 'start' }} numberOfLines={2}>{name}</Text>+ <Text style={{ fontSize: typeScale.caption, color: t.textDim, lineHeight: 1.35, textAlign: 'start' }} numberOfLines={2}>+ {l.custom ? tr(`firewall.lists.format.${l.format}`) : tr('firewall.lists.source', { source: l.source, license: l.license })}+ </Text>+ {status ? <Text style={{ fontSize: typeScale.caption, color: l.error ? '#ff9f0a' : t.textDim, lineHeight: 1.35, textAlign: 'start' }}>+ {status}{l.truncated ? ` · ${tr('firewall.lists.truncated')}` : ''}</Text> : null}+ </View>+ {onRemove ? <Button small label={tr('firewall.remove')} onClick={onRemove} /> : null}+ </View>+ );+ }++ export function BlocklistsPrivacy() {+ const t = useTheme();+ const { t: tr } = useLocale();+ useStore(firewallState);+ const [st, setSt] = useState(() => firewall.lists());+ const [url, setUrl] = useState('');+ const [format, setFormat] = useState('domains');+ const [msg, setMsg] = useState(null);+ // while a job runs (a download, a compile) the state is read again every 2 s+ useEffect(() => {+ const id = setInterval(() => setSt(firewall.lists()), st?.busy ? 1500 : 6000);+ return () => clearInterval(id);+ }, [st?.busy]);+ if (!firewall.available() || !st) return null;+ const refresh = () => setSt(firewall.lists());+ const toggle = (l, on) => { try { firewall.setList(l.id, on); } catch (e) { setMsg(errorText(e)); } refresh(); };+ const add = () => {+ try { firewall.addList(url.trim(), format); setUrl(''); setMsg(null); } catch (e) { setMsg(e.message || errorText(e)); }+ refresh();+ };+ const head = (text) => <Text style={{ fontSize: typeScale.body, fontWeight: 600, color: t.text, paddingHorizontal: spacing.xs, textAlign: 'start' }}>{text}</Text>;+ const foot = (text, color) => <Text style={{ fontSize: typeScale.caption, color: color || t.textDim, lineHeight: 1.4, marginHorizontal: spacing.xs, textAlign: 'start' }}>{text}</Text>;+ const on = st.lists.filter((l) => l.on).length;+ return (+ <View style={{ gap: 20 }}>+ <View style={{ gap: 6 }}>+ <View style={{ flexDirection: 'row', alignItems: 'center', minHeight: 22, paddingHorizontal: spacing.xs, gap: spacing.s }}>+ <Text style={{ flex: 1, fontSize: typeScale.body, fontWeight: 600, color: t.text, textAlign: 'start' }}>{tr('firewall.lists.title')}</Text>+ <Button small plain label={st.busy ? tr('firewall.lists.working') : tr('firewall.lists.update')} disabled={st.busy || !on}+ onClick={() => { firewall.updateLists(true); refresh(); }} />+ </View>+ {foot(tr('firewall.lists.summary', { lists: formatNumber(on, 0), entries: formatNumber(st.domains + st.nets, 0) }))}+ </View>+ {TOPICS.map((topic) => {+ const lists = st.lists.filter((l) => l.topic === topic);+ if (!lists.length && topic !== 'custom') return null;+ return (+ <View key={topic} style={{ gap: 6 }}>+ {head(tr(`firewall.lists.topic.${topic}`))}+ <GroupBox>+ {lists.map((l) => <ListRow key={l.id} l={l} tr={tr} onToggle={(v) => toggle(l, v)}+ onRemove={l.custom ? () => { try { firewall.removeList(l.id); } catch (e) { setMsg(e.message); } refresh(); } : null} />)}+ {topic === 'custom' ? (+ <View style={{ gap: spacing.s, paddingVertical: spacing.s }}>+ <TextInput value={url} onChange={setUrl} placeholder={tr('firewall.lists.urlPlaceholder')} onSubmit={add} />+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: spacing.s }}>+ <Segmented small value={format} onChange={setFormat}+ options={[['hosts', tr('firewall.lists.format.hosts')], ['domains', tr('firewall.lists.format.domains')], ['ips', tr('firewall.lists.format.ips')]]} />+ <View style={{ flex: 1 }} />+ <Button small label={tr('firewall.lists.add')} disabled={!/^https:\/\/\S+$/.test(url.trim())} onClick={add} />+ </View>+ {msg ? <Text style={{ fontSize: typeScale.caption, color: '#ff453a', textAlign: 'start' }}>{msg}</Text> : null}+ </View>+ ) : null}+ </GroupBox>+ {topic === 'custom' ? foot(tr('firewall.lists.customHint')) : null}+ </View>+ );+ })}+ {foot(tr('firewall.lists.footer'))}+ </View>+ );+ }diff --cc apps/monitor/Firewall.jsxindex 4d9b5f5,cb2b1ee..0e526d6--- a/apps/monitor/Firewall.jsx+++ b/apps/monitor/Firewall.jsx@@@ -24,7 -24,12 +24,12 @@@ const LINUX_NOT_YET = ['no-clipboard']// sound streams, notifications), except files: the app's view is built when it starts.const NEXT_LAUNCH = ['no-files'];const isLinux = (id) => id.startsWith('desktop:');- const offered = (id) => (id === 'lordos' ? firewall.RESTRICTIONS.filter((f) => !DESKTOP_ALWAYS.includes(f))-// (0.8.4) LordOS's components with their own scope (Mail, Store, Printers, Terminal, Blocklists): they++// (0.8.5) LordOS's components with their own scope (Mail, Store, Printers, Terminal, Blocklists): they+ // take restrictions like an app; the system services (system:*) and the VPN row never do+ const { COMPONENTS } = netModel;+ const COMPONENT_IDS = Object.keys(COMPONENTS).filter((id) => id.startsWith('lordos:') && !COMPONENTS[id].system);+ const NET_ONLY = ['no-internet', 'no-lan', 'no-network', 'no-incoming'];+ const offered = (id) => (COMPONENTS[id] ? NET_ONLY : id === 'lordos' ? firewall.RESTRICTIONS.filter((f) => !DESKTOP_ALWAYS.includes(f)): isLinux(id) ? firewall.RESTRICTIONS.filter((f) => !LINUX_NOT_YET.includes(f)) : firewall.RESTRICTIONS);function useAppIndex() {diff --cc apps/monitor/FwRules.jsxindex ff90abe,d03dd68..087b4e5--- a/apps/monitor/FwRules.jsx+++ b/apps/monitor/FwRules.jsx@@@ -32,7 -32,10 +32,10 @@@ function useAppIndex()return byId;}- export const appLabelOf = (tr, apps, id) => (id === 'lordos' ? tr('monitor.lordos') : apps.get(id)?.name || id.replace(/^(desktop|lpk):/, ''));-// (0.8.4) LordOS's own components with their own scope take rules too (Mail, Store, Printers, Terminal, Blocklists)++// (0.8.5) LordOS's own components with their own scope take rules too (Mail, Store, Printers, Terminal, Blocklists)+ const { COMPONENTS } = netModel;+ const COMPONENT_IDS = Object.keys(COMPONENTS).filter((id) => id.startsWith('lordos:') && !COMPONENTS[id].system);+ export const appLabelOf = (tr, apps, id) => (id === 'lordos' ? tr('monitor.lordos') : COMPONENTS[id] ? tr(COMPONENTS[id].label) : apps.get(id)?.name || id.replace(/^(desktop|lpk):/, ''));function AppIcon({ a, size = 24 }) {const t = useTheme();diff --cc apps/monitor/NetTree.jsxindex 0000000,220ecce..b70f789mode 000000,100644..100644--- a/apps/monitor/NetTree.jsx+++ b/apps/monitor/NetTree.jsx@@@ -1,0 -1,290 +1,290 @@@-// NetTree.jsx — Monitor → Network's left column, second generation (0.8.4, docs/MONITOR.md):++// NetTree.jsx — Monitor → Network's left column, second generation (0.8.5, docs/MONITOR.md):+ // TokenSearch the search field: "app:firefox", "port:443"… (and, on Enter, any word) become chips+ // that combine (sdk/netmodel.js parseSearch / chipFor)+ // ViewButton one pop-up button with the whole view: group by (app, domain, IP, port, country),+ // direction, protocol, status and sort; remembered per user (settings.monitor.netView)+ // NetTree the tree: app → destination (name or address) → address → port, or the other+ // groupings, each row with its sent and received bytes, a small up/down meter and,+ // where a rule can be written, its switch; "N more…" folds long lists+ import {+ View, Text, SearchField, Overlay, useTheme, useLocale, useSettings, formatBytes, formatNumber, tOptional, direction, firewall, fwRule, netModel, addListener,+ } from '@lordos/sdk';+ import { useEffect, useRef, useState } from 'react';+ import { C, AppGlyph } from './index.jsx';++ const { parseSearch, addChips, fold, normView } = netModel;+ const countryName = (cc) => (cc ? tOptional(`countries.${cc}`) || cc : '');++ // ---- search with chips ----++ const CHIP_COLORS = { app: '#0a84ff', domain: '#30b0c7', ip: '#5e5ce6', port: '#ff9f0a', proto: '#bf5af2', country: '#34c759' };++ export function TokenSearch({ chips, setChips, text, setText, tr }) {+ const t = useTheme();+ // a finished "type:value" token (followed by a space) becomes a chip at once; Enter turns every word+ const change = (v) => {+ if (/\s$/.test(v)) {+ const q = parseSearch(v, false);+ if (q.chips.length) { setChips(addChips(chips, q.chips)); setText(q.rest ? `${q.rest} ` : ''); return; }+ }+ setText(v);+ };+ const commit = () => {+ const q = parseSearch(text, true);+ if (q.chips.length) setChips(addChips(chips, q.chips));+ setText(q.rest);+ };+ return (+ <View style={{ gap: 6 }}>+ <SearchField value={text} onChange={change} onSubmit={commit} placeholder={tr('monitor.net.searchTokens')}+ onKeyDown={(e) => { if ((e.key === 'Backspace') && !text && chips.length) { setChips(chips.slice(0, -1)); return true; } return false; }} />+ {chips.length ? (+ <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 4 }}>+ {chips.map((c) => (+ <View key={`${c.type}:${c.value}`} onClick={() => setChips(chips.filter((x) => x !== c))}+ style={{ flexDirection: 'row', alignItems: 'center', gap: 4, height: 20, paddingHorizontal: 7, borderRadius: 10, backgroundColor: `${CHIP_COLORS[c.type]}2e` }}>+ <Text style={{ fontSize: 10, fontWeight: 600, color: CHIP_COLORS[c.type] }}>{tr(`monitor.net.chip.${c.type}`)}</Text>+ <Text style={{ fontSize: 11, color: t.text, direction: 'ltr' }}>{c.type === 'country' && c.value.length === 2 ? countryName(c.value) : c.value}</Text>+ <Text style={{ fontSize: 10, color: t.textDim }}>✕</Text>+ </View>+ ))}+ <View onClick={() => setChips([])} style={{ height: 20, justifyContent: 'center', paddingHorizontal: 4 }}>+ <Text style={{ fontSize: 10, color: t.accent }}>{tr('monitor.net.clearChips')}</Text>+ </View>+ </View>+ ) : null}+ </View>+ );+ }++ // ---- the view pop-up button ----++ export function useNetView() {+ const [s, set] = useSettings();+ const m = s.monitor || {};+ const view = normView(m.netView);+ const setView = (patch) => set({ monitor: { ...m, netView: { ...view, ...patch } } });+ return [view, setView, m, (patch) => set({ monitor: { ...m, ...patch } })];+ }++ const SECTIONS = [+ ['group', ['app', 'domain', 'ip', 'port', 'country']],+ ['dir', ['all', 'out', 'in']],+ ['proto', ['all', 'tcp', 'udp']],+ ['status', ['all', 'allowed', 'denied', 'rules']],+ ['sort', ['name', 'most', 'least', 'recent', 'conns']],+ ];++ export function ViewButton({ view, setView, extra, tr }) {+ const t = useTheme();+ const [open, setOpen] = useState(false);+ const btn = useRef(null), menu = useRef(null);+ useEffect(() => {+ if (!open) return undefined;+ return addListener('pointerdown', (e) => {+ const inside = (n) => { if (!n) return false; const [x, y, w, h] = lord.getLayout(n.id); return e.x >= x && e.x <= x + w && e.y >= y && e.y <= y + h; };+ if (!inside(menu.current) && !inside(btn.current)) setOpen(false);+ });+ }, [open]);+ const changed = ['dir', 'proto', 'status'].filter((k) => view[k] !== 'all').length;+ return (+ <View ref={btn}>+ <View onClick={() => setOpen((o) => !o)} style={{ height: 24, paddingHorizontal: 9, borderRadius: t.controlRadiusSmall || 6, flexDirection: 'row', alignItems: 'center', gap: 6,+ backgroundColor: t.control, boxShadow: '0 1px 1px rgba(0,0,0,0.12)', ...(t.buttonBorder ? { border: `1px solid ${t.separator}` } : null) }}>+ <Text style={{ fontSize: 12, color: t.text, whiteSpace: 'nowrap' }}>{tr('monitor.net.view.button', { group: tr(`monitor.net.view.group.${view.group}`) })}</Text>+ {changed ? (+ <View style={{ minWidth: 14, height: 14, borderRadius: 7, paddingHorizontal: 3, backgroundColor: t.accent, alignItems: 'center', justifyContent: 'center' }}>+ <Text style={{ fontSize: 9, fontWeight: 700, color: '#fff' }}>{formatNumber(changed, 0)}</Text>+ </View>+ ) : null}+ {t.menuHighlight === 'subtle'+ ? <View style={{ width: 16, height: 18, alignItems: 'center', justifyContent: 'center' }}>+ <View style={{ width: 6, height: 6, marginTop: -3, borderRightWidth: 1.5, borderBottomWidth: 1.5, borderColor: t.textDim, transform: 'rotate(45deg)' }} />+ </View>+ : <View style={{ width: 16, height: 18, borderRadius: 4, backgroundColor: t.accent, alignItems: 'center', justifyContent: 'center' }}>+ <Text style={{ fontSize: 8, color: '#fff', lineHeight: 8 }}>▲</Text>+ <Text style={{ fontSize: 8, color: '#fff', lineHeight: 8 }}>▼</Text>+ </View>}+ </View>+ {open && (+ <Overlay anchor={btn}>+ <View ref={menu} style={{ position: 'absolute', top: 28, [direction() === 'rtl' ? 'right' : 'left']: 0, width: 420, paddingVertical: 6, paddingHorizontal: 5,+ borderRadius: t.menuRadius, backgroundColor: t.popupBg || (t.mode === 'dark' ? '#2c2c31' : '#ffffff'), border: `1px solid ${t.separator}`,+ boxShadow: '0 10px 30px rgba(0,0,0,0.35)' }}>+ {/* two columns: what the list is (grouping, order) and what it shows (direction, protocol, status) */}+ <View style={{ flexDirection: 'row', gap: 4 }}>+ {[['group', 'sort'], ['dir', 'proto', 'status']].map((col, ci) => (+ <View key={ci} style={{ flex: 1, minWidth: 0 }}>+ {col.map((key, si) => (+ <View key={key}>+ {si ? <View style={{ height: 1, marginVertical: 3, marginHorizontal: 6, backgroundColor: t.separator }} /> : null}+ <Text style={{ fontSize: 10, fontWeight: 600, color: t.textDim, paddingHorizontal: 8, paddingVertical: 2 }}>{tr(`monitor.net.view.${key}`)}</Text>+ {SECTIONS.find(([k]) => k === key)[1].map((v) => <MenuItem key={v} label={tr(`monitor.net.view.${key}.${v}`)} checked={view[key] === v} onClick={() => setView({ [key]: v })} />)}+ </View>+ ))}+ </View>+ ))}+ </View>+ {(extra || []).length ? <View style={{ height: 1, marginVertical: 4, marginHorizontal: 6, backgroundColor: t.separator }} /> : null}+ {(extra || []).map((it) => (+ <MenuItem key={it.label} label={it.label} checked={it.checked} onClick={() => { setOpen(false); it.onClick(); }} />+ ))}+ </View>+ </Overlay>+ )}+ </View>+ );+ }++ function MenuItem({ label, checked, onClick }) {+ const t = useTheme();+ const [hover, setHover] = useState(false);+ const on = hover && t.menuHighlight !== 'subtle';+ return (+ <View onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}+ style={{ height: 21, paddingHorizontal: 8, borderRadius: t.menuItemRadius, flexDirection: 'row', alignItems: 'center', gap: 6,+ backgroundColor: on ? t.accent : hover ? t.hover : 'transparent' }}>+ <Text style={{ width: 12, fontSize: 11, color: on ? '#fff' : t.text }}>{checked ? '✓' : ''}</Text>+ <Text style={{ flex: 1, fontSize: 12, whiteSpace: 'nowrap', color: on ? '#fff' : t.text, textAlign: 'start' }}>{label}</Text>+ </View>+ );+ }++ // ---- the tree ----++ // A small up/down meter: received (down, green) and sent (up, orange) on a log scale of the rate.+ function Meter({ rx, tx, selected }) {+ const t = useTheme();+ const h = (v) => (v > 0 ? Math.max(1, Math.min(6, Math.round(Math.log10(v / 64 + 1) * 1.6))) : 0);+ return (+ <View style={{ width: 9, height: 14, justifyContent: 'center', alignItems: 'center', direction: 'ltr' }}>+ <View style={{ width: 4, height: 6, justifyContent: 'flex-end' }}>+ <View style={{ width: 4, height: h(tx), borderRadius: 1, backgroundColor: selected ? '#fff' : C.tx }} />+ </View>+ <View style={{ width: 7, height: 1, backgroundColor: selected ? 'rgba(255,255,255,0.5)' : t.separator }} />+ <View style={{ width: 4, height: 6 }}>+ <View style={{ width: 4, height: h(rx), borderRadius: 1, backgroundColor: selected ? '#fff' : C.rx }} />+ </View>+ </View>+ );+ }++ // "↓ 1.2 MB ↑ 40 KB", shorter when one side is empty+ export function upDownShort(n) {+ const parts = [];+ if (n.rx) parts.push(`↓ ${formatBytes(n.rx)}`);+ if (n.tx) parts.push(`↑ ${formatBytes(n.tx)}`);+ return parts.join(' ') || '—';+ }++ const placeOf = (tr, n) => (n.cc ? countryName(n.cc) : n.scope ? tr(`monitor.net.scope.${n.scope}`) : '');++ // The verdict of a destination row for its app (sdk/fwrule.js decide, as the kernel decides), and a+ // click that writes, flips or removes the rule for exactly that name or address.+ function DestSwitch({ app, name, addr, port, proto, listed, mode, restricted }) {+ if (!firewall.available() || !firewall.enforceable(app)) return null;+ const rules = firewall.rules(app);+ const opts = { listed: !!listed, mode };+ const q = { names: name ? [name] : [], addr, port: port || 443, proto: proto === 'udp' ? 'udp' : 'tcp' };+ const v = fwRule.decide(rules, q, restricted, opts);+ const on = v ? v.action === 'allow' : true;+ const locked = v?.by === 'restricted';+ const flip = (e) => {+ e.stopPropagation();+ if (locked) return;+ const op = fwRule.toggleOp(rules, { name, addr, proto: q.proto, port: q.port }, restricted, opts);+ if (!op) return;+ if (op.op === 'add') firewall.addRule({ app, ...op.rule });+ else if (op.op === 'update') firewall.updateRule(op.id, op.rule);+ else firewall.removeRule(op.id);+ };+ return (+ <View onClick={flip} style={{ width: 22, height: 12, borderRadius: 6, backgroundColor: on ? 'rgba(48,209,88,0.32)' : 'rgba(255,69,58,0.32)',+ opacity: locked ? 0.45 : 1, justifyContent: 'center', alignItems: on ? 'flex-end' : 'flex-start', paddingHorizontal: 2, direction: 'ltr' }}>+ <View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: on ? '#30d158' : '#ff453a' }} />+ </View>+ );+ }++ const SHOWN = 8;++ // Why a destination is allowed or blocked when its own switch isn't what decides: a blocklist, a+ // restriction, another rule ("*.example.com") or the app's default.+ function verdictHint(tr, ctx, app, name, addr, port, proto, listed) {+ if (!app || !firewall.available() || !firewall.enforceable(app)) return listed ? tr('monitor.net.onList', { list: ctx.listName(listed) }) : '';+ const v = fwRule.decide(firewall.rules(app), { names: name ? [name] : [], addr, port: port || 443, proto: proto === 'udp' ? 'udp' : 'tcp' },+ ctx.restrictedOf(app), { listed: !!listed, mode: ctx.mode });+ if (!v) return '';+ if (v.by === 'list') return tr('monitor.net.blockedByList', { list: ctx.listName(listed) });+ if (v.by === 'restricted') return tr('monitor.net.domainRestricted');+ if (v.by === 'mode') return tr('monitor.net.deniedByMode');+ const own = name ? fwRule.normDomain(name) : addr;+ if (v.rule.dst === own && !v.rule.port && !v.rule.proto) return '';+ return v.rule.dst === 'any' ? tr('monitor.net.domainByDefault') : tr('monitor.net.domainByRule', { rule: v.rule.dst });+ }++ // One row below the top level (a destination, an address, a port or an app under a destination).+ export function Child({ node, depth, path, ctx }) {+ const t = useTheme();+ const { tr } = ctx;+ const key = path ? `${path}\u0001${node.key}` : node.key;+ const open = ctx.open.has(key);+ const kids = node.children || [];+ const { list, more } = fold(kids, SHOWN, ctx.all.has(key));+ const appOf = ctx.appOf(node, path);+ const sel = ctx.selectedHost && node.addr && ctx.selectedHost === node.addr && ctx.selected === appOf;+ const label = node.kind === 'app' ? ctx.appLabel(node) : node.kind === 'country' ? (node.cc ? countryName(node.cc) : tr(`monitor.net.scope.${node.scope || 'local'}`)) : node.label;+ const dot = node.denied || node.blocked ? '#ff453a' : node.listed ? '#ff9f0a' : node.rateRx + node.rateTx > 0 ? t.accent : t.textDim;+ const destName = node.kind === 'domain' ? node.name : null;+ const destAddr = node.addr || node.flows[0]?.addr;+ const canSwitch = appOf && (node.kind === 'domain' || node.kind === 'ip') && !ctx.isSystem(appOf);+ const inset = depth ? 14 + depth * 14 : 4;+ return (+ <View>+ <View onClick={() => ctx.onPick(node, appOf)} style={{ flexDirection: 'row', alignItems: 'center', gap: 5, minHeight: depth ? 22 : 32, borderRadius: 5,+ ...(direction() === 'rtl' ? { paddingRight: inset } : { paddingLeft: inset }), backgroundColor: sel ? (t.mode === 'dark' ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.05)') : 'transparent' }}>+ <View onClick={(e) => { if (!kids.length) return; e.stopPropagation(); ctx.toggle(key); }} style={{ width: 10, alignItems: 'center' }}>+ <Text style={{ fontSize: 8, color: t.textDim }}>{kids.length ? (open ? '▾' : direction() === 'rtl' ? '◂' : '▸') : ''}</Text>+ </View>+ {node.kind === 'app' ? <AppGlyph item={ctx.itemOf(node)} size={13} /> : <View style={{ width: 6, height: 6, borderRadius: 3, backgroundColor: dot }} />}+ <View style={{ flex: 1, minWidth: 0 }}>+ <Text style={{ fontSize: depth ? 11 : 12, fontWeight: depth ? 400 : 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', fontFamily: node.kind === 'app' || node.kind === 'country' ? undefined : 'monospace',+ direction: node.kind === 'app' || node.kind === 'country' ? undefined : 'ltr', textAlign: 'start' }}>+ {label}{node.kind === 'domain' && new Set(node.flows.map((f) => f.addr)).size > 1 ? ` (${new Set(node.flows.map((f) => f.addr)).size})` : ''}+ </Text>+ <Text style={{ fontSize: 9, color: t.textDim, whiteSpace: 'nowrap', overflow: 'hidden', textAlign: 'start' }}>+ {[upDownShort(node), node.kind !== 'country' && node.kind !== 'port' ? placeOf(tr, node.flows[0] || {}) : '',+ canSwitch ? verdictHint(tr, ctx, appOf, destName, destAddr, node.flows[0]?.port, node.flows[0]?.proto, node.listed)+ : node.listed ? tr('monitor.net.onList', { list: ctx.listName(node.listed) }) : ''].filter(Boolean).join(' · ')}+ </Text>+ </View>+ <Meter rx={node.rateRx} tx={node.rateTx} />+ {canSwitch ? <DestSwitch app={appOf} name={destName} addr={destAddr} port={node.flows[0]?.port} proto={node.flows[0]?.proto} listed={node.listed}+ mode={ctx.mode} restricted={ctx.restrictedOf(appOf)} /> : <View style={{ width: 22 }} />}+ </View>+ {open && list.map((c) => <Child key={c.key} node={c} depth={depth + 1} path={key} ctx={ctx} />)}+ {open && (more || ctx.all.has(key)) && kids.length > SHOWN ? (+ <View onClick={() => ctx.toggleAll(key)} style={{ height: 18, justifyContent: 'center', ...(direction() === 'rtl' ? { paddingRight: inset + 26 } : { paddingLeft: inset + 26 }) }}>+ <Text style={{ fontSize: 10, color: t.accent }}>{more ? tr('monitor.net.moreDomains', { count: more }) : tr('monitor.net.fewer')}</Text>+ </View>+ ) : null}+ </View>+ );+ }++ export function TreeChildren({ node, ctx }) {+ const t = useTheme();+ const key = node.key;+ const kids = node.children || [];+ const { list, more } = fold(kids, SHOWN, ctx.all.has(key));+ return (+ <View style={{ paddingBottom: 4, gap: 0 }}>+ {list.map((c) => <Child key={c.key} node={c} depth={1} path={key} ctx={ctx} />)}+ {kids.length > SHOWN ? (+ <View onClick={() => ctx.toggleAll(key)} style={{ height: 20, justifyContent: 'center', ...(direction() === 'rtl' ? { paddingRight: 40 } : { paddingLeft: 40 }) }}>+ <Text style={{ fontSize: 10, color: t.accent }}>{more ? ctx.tr('monitor.net.moreDomains', { count: more }) : ctx.tr('monitor.net.fewer')}</Text>+ </View>+ ) : null}+ </View>+ );+ }diff --cc apps/monitor/Network.jsxindex 5bcfa06,b4f9a16..0f499d5--- a/apps/monitor/Network.jsx+++ b/apps/monitor/Network.jsx@@@ -23,8 -24,15 +24,15 @@@ import { TrafficChart, systemBuckets }import { RuleSheet } from './RuleSheet.jsx';import { HistoryControls, HistoryChart, useHistory } from './History.jsx';import { REMOTE_KEY, RemoteDetail, remoteGroup, useRemoteDesktop } from './RemoteDesktop.jsx';+ import { TokenSearch, ViewButton, useNetView, TreeChildren, Child } from './NetTree.jsx';- export const appKeyOf = (c) => (c.self ? 'lordos' : c.app || c.exe || c.name || '?');+ const { COMPONENTS, isSystemId, filterFlows, groupFlows, sortTree } = netModel;+-// (0.8.4) a socket made in an app's scope is that app's (conn.c "cgApp"), whoever holds it: the ones++// (0.8.5) a socket made in an app's scope is that app's (conn.c "cgApp"), whoever holds it: the ones+ // Mail's connector made are Mail's, a program in the Terminal is the Terminal's+ export const appKeyOf = (c) => c.cgApp || (c.self ? 'lordos' : c.app || c.exe || c.name || '?');+ // The row's name: LordOS's own components by their label, LordOS itself, or the app's name.+ export const labelOf = (tr, g) => (COMPONENTS[g.key] ? tr(COMPONENTS[g.key].label) : g.key === 'lordos' ? tr('monitor.lordos') : g.name);const countryName = (cc) => (cc ? tOptional(`countries.${cc}`) || cc : '');// Where an address is: its country, LAN / this computer, or, for a destination known only from the@@@ -34,6 -42,10 +42,10 @@@ const placeOf = (tr, h) => (h.cc ? coun// Names the system resolver gave for each address, if lord-netperm's notices carry them ("host" or// "hosts"). The names belong to the system, not to one app (docs/FIREWALL.md, "Where the names come// from"), so one map serves every app. Without them a row offers a rule for its address instead.-// (0.8.4) An address the resolver reached through a CNAME chain has several names (deb.debian.org →++// (0.8.5) An address the resolver reached through a CNAME chain has several names (deb.debian.org →+ // debian.map.fastlydns.net): the row shows the shortest, usually the one the app asked for, and+ // allNamesOf keeps them all for the search chips and the blocklists.+ const allNames = new Map();function namesOf(events) {const out = new Map();for (const e of events || []) {@@@ -134,6 -153,7 +153,7 @@@ function applyBytes(g, v)h.rateRx = f[3] || 0;h.rateTx = f[4] || 0;h.blocked = f[5] || 0;- h.portStats = Array.isArray(f[6]) ? f[6] : null; // (0.8.4) [[port, proto, dir, rx, tx, rxRate, txRate], ...]++ h.portStats = Array.isArray(f[6]) ? f[6] : null; // (0.8.5) [[port, proto, dir, rx, tx, rxRate, txRate], ...]g.hosts.set(f[0], h);}}@@@ -707,6 -673,94 +673,94 @@@ function PlaceDetail({ p, tr }));}-// ---- the list's flows (0.8.4) ----++// ---- the list's flows (0.8.5) ----++ // When each destination last moved bytes (ms), for "Most recent".+ const lastSeen = new Map();+ function seen(key, active) {+ if (active) { if (lastSeen.size > 8192 && !lastSeen.has(key)) lastSeen.delete(lastSeen.keys().next().value); lastSeen.set(key, Date.now()); }+ return lastSeen.get(key) || 0;+ }++ // One flow per (app, address, port) for sdk/netmodel.js: the kernel's per-port counters when+ // lord-netperm sends them (COUNTS), the open sockets' ports otherwise. Apps with no destination yet+ // (only listening, or a component that hasn't connected) keep a flow with no address, so their row stays.+ function flowsOf(apps, names, tr) {+ const out = [];+ const listedCache = new Map();+ const listed = (list, addr) => {+ const k = `${list.join(',')}|${addr}`;+ if (!listedCache.has(k)) listedCache.set(k, firewall.listMatch(list, addr));+ return listedCache.get(k);+ };+ for (const g of apps) {+ const base = { app: g.key, appName: labelOf(tr, g), system: !!g.system };+ let any = false;+ for (const h of g.hosts.values()) {+ if (!h.remote) continue;+ any = true;+ const name = names.get(h.remote) || null;+ const all = allNamesOf(h.remote, name);+ const common = { ...base, name, names: all, addr: h.remote, cc: h.cc || '', scope: h.scope || '', denied: h.denied ? 1 : 0, blocked: h.blocked || 0, listed: listed(all, h.remote) };+ const ps = (h.portStats || []).filter((p) => Array.isArray(p) && p.length >= 7);+ if (ps.length) {+ const share = Math.max(1, ps.length);+ for (const p of ps) {+ const active = (p[5] || 0) + (p[6] || 0) > 0;+ out.push({ ...common, port: Number(p[0]) || 0, proto: p[1] === 'udp' ? 'udp' : p[1] === 'tcp' ? 'tcp' : 'other', dir: p[2] === 'in' ? 'in' : 'out',+ rx: p[3] || 0, tx: p[4] || 0, rateRx: p[5] || 0, rateTx: p[6] || 0, conns: Math.ceil((h.count || 0) / share), last: seen(`${g.key}|${h.remote}|${p[0]}`, active) });+ }+ continue;+ }+ const ports = [...(h.ports || [])].map((x) => /^(TCP|UDP) (\d+)$/.exec(x)).filter(Boolean);+ const active = (h.rateRx || 0) + (h.rateTx || 0) > 0;+ const dir = g.conns.some((c) => c.remote === h.remote && c.dir === 'in') ? 'in' : 'out';+ if (!ports.length) ports.push([null, 'TCP', '0']);+ ports.forEach((m, i) => out.push({ ...common, port: Number(m[2]) || 0, proto: m[1] === 'UDP' ? 'udp' : 'tcp', dir,+ rx: i ? 0 : h.recv || 0, tx: i ? 0 : h.sent || 0, rateRx: i ? 0 : h.rateRx || 0, rateTx: i ? 0 : h.rateTx || 0, conns: i ? 0 : h.count || 0,+ last: seen(`${g.key}|${h.remote}`, active) }));+ }+ if (!any) out.push({ ...base, name: null, addr: '', port: 0, proto: 'other', dir: g.listen.length ? 'in' : 'out', rx: g.recv || 0, tx: g.sent || 0,+ rateRx: g.rateRx || 0, rateTx: g.rateTx || 0, conns: 0, denied: g.denied || 0, cc: '', scope: '', last: 0, listed: null, empty: true });+ }+ return out;+ }+-// The VPN tunnels as one row (0.8.4): LordOS's own VPN interfaces (Settings → Network), their++// The VPN tunnels as one row (0.8.5): LordOS's own VPN interfaces (Settings → Network), their+ // interface counters and rates. Shown, not blockable: the tunnel is the system's network.+ function useVpnGroup(tr) {+ const [st, setSt] = useState({ at: 0, list: [] });+ useEffect(() => {+ const prev = new Map();+ const read = () => {+ let ifs = [];+ try { ifs = typeof lord !== 'undefined' && lord.net ? lord.net.interfaces() || [] : []; } catch (e) { ifs = []; }+ const now = Date.now();+ const list = ifs.filter((i) => i.managed === 'lordos' && (i.type === 'wireguard' || i.type === 'tun' || /^(wg|ovpn|ips|ppp|oc|fvpn)-/.test(i.name)) && i.up)+ .map((i) => {+ const p = prev.get(i.name);+ const dt = p ? Math.max(0.5, (now - p.t) / 1000) : 0;+ const r = { name: i.name, rx: i.rxBytes || 0, tx: i.txBytes || 0, rateRx: dt ? Math.max(0, (i.rxBytes - p.rx) / dt) : 0, rateTx: dt ? Math.max(0, (i.txBytes - p.tx) / dt) : 0 };+ prev.set(i.name, { t: now, rx: i.rxBytes || 0, tx: i.txBytes || 0 });+ return r;+ });+ setSt({ at: now, list });+ };+ read();+ const id = setInterval(read, 2000);+ return () => clearInterval(id);+ }, []);+ if (!st.list.length) return null;+ const g = { key: 'lordos:vpn', item: { app: 'lordos:vpn' }, name: null, exe: '', pids: new Set(), conns: [], hosts: new Map(), listen: [], incoming: 0,+ sent: 0, recv: 0, rateTx: 0, rateRx: 0, rule: null, allowed: 0, denied: 0, programs: new Set(), system: true, tunnels: st.list };+ for (const v of st.list) {+ g.recv += v.rx; g.sent += v.tx; g.rateRx += v.rateRx; g.rateTx += v.rateTx;+ g.hosts.set(v.name, { remote: v.name, cc: '', scope: 'local', ports: new Set(), recv: v.rx, sent: v.tx, rateRx: v.rateRx, rateTx: v.rateTx, count: 1 });+ }+ void tr;+ return g;+ }+// ---- pestaña ----export function NetworkTab({ last, prefs }) {@@@ -720,11 -774,15 +774,15 @@@const { apps: connApps } = useGroups(conns);const launcher = useLauncherApps();const fwApps = useMemo(() => withFirewall(connApps, fw, launcher), [connApps, fw, launcher]);- // the remote desktop (lord-sessiond, root) as one more app while it's on (RemoteDesktop.jsx)+ // the remote desktop (lord-sessiond, root) as one more app while it's on (RemoteDesktop.jsx), and- // the VPN tunnels (0.8.4)++ // the VPN tunnels (0.8.5)const rd = useRemoteDesktop();const rdg = remoteGroup(rd, tr);- const apps = rdg ? [...fwApps, rdg].sort((a, b) => b.sent + b.recv - (a.sent + a.recv) || b.conns.length - a.conns.length) : fwApps;- const [q, setQ] = useState('');+ const vpn = useVpnGroup(tr);+ const apps = [...fwApps, ...(rdg ? [rdg] : []), ...(vpn ? [vpn] : [])].sort((a, b) => b.sent + b.recv - (a.sent + a.recv) || b.conns.length - a.conns.length);+ const [view, setView, mprefs, setPrefs] = useNetView();+ const [chips, setChips] = useState([]);+ const [text, setText] = useState('');const [open, setOpen] = useState(() => new Set());const [selected, setSelected] = useState(null); // app elegida (clave)const [place, setPlace] = useState(null); // país elegido en el mapadiff --cc apps/monitor/icons.jsxindex a6e9486,8fa965d..69e7e9d--- a/apps/monitor/icons.jsx+++ b/apps/monitor/icons.jsx@@@ -122,6 -122,52 +122,52 @@@ export function Glyph({ name, color, si<View style={{ position: 'absolute', left: s * 0.06, right: s * 0.06, top: s * 0.48, height: b, backgroundColor: color }} /></View>);- // (0.8.4) LordOS's own components and the system services (Monitor → Network rows)++ // (0.8.5) LordOS's own components and the system services (Monitor → Network rows)+ case 'printer':+ return (+ <View style={box}>+ <View style={{ width: s * 0.56, height: s * 0.26, borderTopLeftRadius: 1, borderTopRightRadius: 1, border: `${b}px solid ${color}`, borderBottomWidth: 0 }} />+ <View style={{ width: s * 0.92, height: s * 0.38, borderRadius: 2, backgroundColor: color }} />+ <View style={{ width: s * 0.56, height: s * 0.24, border: `${b}px solid ${color}`, borderTopWidth: 0 }} />+ </View>+ );+ case 'shield':+ return (+ <View style={box}>+ <View style={{ width: s * 0.72, height: s * 0.86, borderTopLeftRadius: s * 0.12, borderTopRightRadius: s * 0.12, borderBottomLeftRadius: s * 0.36,+ borderBottomRightRadius: s * 0.36, border: `${b}px solid ${color}`, alignItems: 'center', justifyContent: 'center' }}>+ <View style={{ width: s * 0.3, height: b * 1.2, backgroundColor: color }} />+ </View>+ </View>+ );+ case 'tunnel':+ return (+ <View style={box}>+ <View style={{ width: s * 0.86, height: s * 0.62, borderTopLeftRadius: s * 0.43, borderTopRightRadius: s * 0.43, border: `${b}px solid ${color}`, borderBottomWidth: 0,+ alignItems: 'center', justifyContent: 'flex-end' }}>+ <View style={{ width: s * 0.4, height: s * 0.36, borderTopLeftRadius: s * 0.2, borderTopRightRadius: s * 0.2, backgroundColor: color }} />+ </View>+ <View style={{ width: s, height: b, backgroundColor: color }} />+ </View>+ );+ case 'dns':+ return (+ <View style={box}>+ {[0, 1, 2].map((i) => (+ <View key={i} style={{ width: s * 0.86, height: s * 0.24, marginTop: i ? s * 0.06 : 0, borderRadius: 1.5, border: `${b}px solid ${color}`, justifyContent: 'center' }}>+ <View style={{ width: s * 0.1, height: s * 0.1, marginLeft: s * 0.08, borderRadius: s * 0.05, backgroundColor: color }} />+ </View>+ ))}+ </View>+ );+ case 'clock':+ return (+ <View style={box}>+ <View style={{ width: s * 0.92, height: s * 0.92, borderRadius: s * 0.46, border: `${b}px solid ${color}` }} />+ <View style={{ position: 'absolute', left: s * 0.47, top: s * 0.2, width: b, height: s * 0.32, backgroundColor: color }} />+ <View style={{ position: 'absolute', left: s * 0.47, top: s * 0.5, width: s * 0.24, height: b, backgroundColor: color }} />+ </View>+ );default:return <View style={box} />;}diff --cc apps/monitor/index.jsxindex 6a6bcef,4009bc0..ef8b582--- a/apps/monitor/index.jsx+++ b/apps/monitor/index.jsx@@@ -32,6 -33,8 +33,8 @@@ if (typeof sdk.registerPrivacySection =if (typeof sdk.registerPrivacySection === 'function') sdk.registerPrivacySection({ id: 'firewall', order: 11, Component: FirewallPrivacy });// … and the rules of each app: domains, addresses and networks, with the app's defaultif (typeof sdk.registerPrivacySection === 'function') sdk.registerPrivacySection({ id: 'fwrules', order: 12, Component: FirewallRulesPrivacy });-// … and (0.8.4) the subscribed blocklists (docs/FIREWALL.md, "Blocklists")++// … and (0.8.5) the subscribed blocklists (docs/FIREWALL.md, "Blocklists")+ if (typeof sdk.registerPrivacySection === 'function') sdk.registerPrivacySection({ id: 'blocklists', order: 13, Component: BlocklistsPrivacy });// ---- formats ----export const fmt = {@@@ -327,8 -330,22 +330,22 @@@ export function Cell({ col, children, c// as Mail or Passwords; the process is shown with the app's name and icon.export const isolatedAppOf = (item) => (typeof item?.app === 'string' && item.app.startsWith('lpk:') ? getApp(item.app.slice(4)) : null);-// (0.8.4) LordOS's own components: the built-in app's icon (Mail, Store, Terminal) or a glyph++// (0.8.5) LordOS's own components: the built-in app's icon (Mail, Store, Terminal) or a glyph+ function ComponentGlyph({ comp, size }) {+ const t = useTheme();+ const a = comp.icon ? getApp(comp.icon) : null;+ if (a?.Icon) return <a.Icon size={size} />;+ return (+ <View style={{ width: size, height: size, borderRadius: size * 0.24, backgroundColor: comp.system ? '#8e8e93' : t.accent, alignItems: 'center', justifyContent: 'center' }}>+ <Glyph name={comp.glyph || 'network'} color="#fff" size={Math.round(size * 0.62)} />+ </View>+ );+ }+export function AppGlyph({ item, size = 16 }) {if (item.app === 'lordos') return <LordOSLogo size={size} />;+ const comp = sdk.netModel?.COMPONENTS?.[item.app];+ if (comp) return <ComponentGlyph comp={comp} size={size} />;if (item.app === 'remote-desktop') return <RemoteGlyph size={size} />;const iso = isolatedAppOf(item);if (iso?.Icon) return <iso.Icon size={size} />;diff --cc assets/locales/en/errors.jsonindex 17ecc64,91e640d..ff38e30--- a/assets/locales/en/errors.json+++ b/assets/locales/en/errors.json@@@ -571,37 -567,10 +571,43 @@@"app.codeRefused": "This app's code was modified and was not loaded","remote.badAddress": "Not a valid address or network","remote.listFull": "The list is full (64 entries)",+ "remote.badIceServer": "Not a valid server: use name:port, like stun.example.org:3478 (at most 4)",+ "remote.badTurnUser": "Not a valid relay user name (no spaces, at most 128 characters)",+ "remote.badTurnPassword": "Not a valid relay password (at most 128 characters, no line breaks)",+ "imager.cacheFailed": "The imager's download folder (~/.cache/lordos/imager) can't be used",+ "imager.noCurl": "The download tool (curl) isn't installed",+ "imager.fetchCancelled": "Download cancelled",+ "imager.fetchTooLarge": "The download is larger than expected",+ "imager.fetchNotFound": "The release file wasn't found",+ "imager.fetchNetwork": "No connection to the LordOS releases page",+ "imager.fetchFailed": "The download failed (code {code})",+ "imager.nothingRunning": "Nothing is being downloaded",+ "imager.notRemovable": "{name} is not a removable drive: the imager only writes SD cards and USB drives",+ "imager.readOnly": "{name} is write-protected",+ "imager.diskChanged": "{name} is not the drive that was chosen (it changed or was replaced)",+ "imager.badImageName": "That file isn't an .img, .img.xz or .iso image",+ "imager.xzDamaged": "The .xz image is damaged or incomplete",+ "imager.noXz": "The .xz tool (xz-utils) isn't installed",+ "imager.noSignature": "The release signature files couldn't be read",+ "imager.badSignature": "The release signature doesn't match the LordOS key",+ "imager.notListed": "The signed list doesn't include {name}",+ "imager.hashMismatch": "The image doesn't match its signed SHA-256: it was not written",+ "imager.cancelledWiped": "Cancelled: the drive was cleared",+ "imager.xzFailed": "The image couldn't be decompressed",+ "imager.imageChanged": "The image file changed while it was written: the drive was cleared",+ "imager.driveTooLarge": "{name} is larger than 2 TiB: LordOS images can't use it",+ "imager.notAuthorized": "Writing to the drive wasn't allowed",+ "imager.listFailed": "The drives couldn't be listed",+ "imager.bootNotFound": "The card's boot partition didn't appear",+ "imager.ejectFailed": "The drive couldn't be ejected",+ "imager.noUdisks": "The disk service (udisks2) isn't running",+ "imager.hashFailed": "The password couldn't be hashed",+ "imager.pskFailed": "The Wi-Fi key couldn't be derived",- "remote.badTurnFingerprint": "Not a valid certificate fingerprint: 64 hexadecimal digits (pairs may be separated by colons)"++ "remote.badTurnFingerprint": "Not a valid certificate fingerprint: 64 hexadecimal digits (pairs may be separated by colons)",+ "fw.list.unknown": "Unknown blocklist",+ "fw.list.badUrl": "Not a valid https address",+ "fw.list.badFormat": "Unknown list format",+ "fw.list.tooMany": "There are already 16 lists of your own",+ "fw.list.exists": "That list is already there",+ "fw.list.unavailable": "Blocklists are not available in this session"}diff --cc assets/locales/es/errors.jsonindex ea1e9b3,9a92746..081ee85--- a/assets/locales/es/errors.json+++ b/assets/locales/es/errors.json@@@ -571,37 -567,10 +571,43 @@@"app.codeRefused": "El código de esta app fue modificado y no se cargó","remote.badAddress": "No es una dirección o red válida","remote.listFull": "La lista está llena (64 entradas)",+ "remote.badIceServer": "No es un servidor válido: usá nombre:puerto, como stun.ejemplo.org:3478 (como mucho 4)",+ "remote.badTurnUser": "No es un usuario de relé válido (sin espacios, hasta 128 caracteres)",+ "remote.badTurnPassword": "No es una contraseña de relé válida (hasta 128 caracteres, sin saltos de línea)",+ "imager.cacheFailed": "No se puede usar la carpeta de descargas del grabador (~/.cache/lordos/imager)",+ "imager.noCurl": "La herramienta de descarga (curl) no está instalada",+ "imager.fetchCancelled": "Descarga cancelada",+ "imager.fetchTooLarge": "La descarga es más grande de lo esperado",+ "imager.fetchNotFound": "No se encontró el archivo de la versión",+ "imager.fetchNetwork": "No hay conexión con la página de versiones de LordOS",+ "imager.fetchFailed": "La descarga falló (código {code})",+ "imager.nothingRunning": "No se está descargando nada",+ "imager.notRemovable": "{name} no es una unidad extraíble: el grabador solo graba tarjetas SD y unidades USB",+ "imager.readOnly": "{name} está protegida contra escritura",+ "imager.diskChanged": "{name} no es la unidad elegida (cambió o la reemplazaron)",+ "imager.badImageName": "Ese archivo no es una imagen .img, .img.xz o .iso",+ "imager.xzDamaged": "La imagen .xz está dañada o incompleta",+ "imager.noXz": "La herramienta .xz (xz-utils) no está instalada",+ "imager.noSignature": "No se pudieron leer los archivos de firma de la versión",+ "imager.badSignature": "La firma de la versión no coincide con la clave de LordOS",+ "imager.notListed": "La lista firmada no incluye {name}",+ "imager.hashMismatch": "La imagen no coincide con su SHA-256 firmado: no se grabó",+ "imager.cancelledWiped": "Cancelado: la unidad quedó limpia",+ "imager.xzFailed": "No se pudo descomprimir la imagen",+ "imager.imageChanged": "El archivo de imagen cambió mientras se grababa: la unidad quedó limpia",+ "imager.driveTooLarge": "{name} tiene más de 2 TiB: las imágenes de LordOS no pueden usarla",+ "imager.notAuthorized": "No se permitió grabar en la unidad",+ "imager.listFailed": "No se pudieron listar las unidades",+ "imager.bootNotFound": "No apareció la partición de arranque de la tarjeta",+ "imager.ejectFailed": "No se pudo expulsar la unidad",+ "imager.noUdisks": "El servicio de discos (udisks2) no está funcionando",+ "imager.hashFailed": "No se pudo calcular el hash de la contraseña",+ "imager.pskFailed": "No se pudo derivar la clave del Wi-Fi",- "remote.badTurnFingerprint": "No es una huella de certificado válida: 64 dígitos hexadecimales (los pares pueden ir separados por dos puntos)"++ "remote.badTurnFingerprint": "No es una huella de certificado válida: 64 dígitos hexadecimales (los pares pueden ir separados por dos puntos)",+ "fw.list.unknown": "Lista de bloqueo desconocida",+ "fw.list.badUrl": "No es una dirección https válida",+ "fw.list.badFormat": "Formato de lista desconocido",+ "fw.list.tooMany": "Ya hay 16 listas propias",+ "fw.list.exists": "Esa lista ya está",+ "fw.list.unavailable": "Las listas de bloqueo no están disponibles en esta sesión"}diff --cc assets/locales/pt/errors.jsonindex ff831bc,3f55d3e..dfe26a2--- a/assets/locales/pt/errors.json+++ b/assets/locales/pt/errors.json@@@ -571,37 -567,10 +571,43 @@@"app.codeRefused": "O código deste app foi modificado e não foi carregado","remote.badAddress": "Não é um endereço ou rede válida","remote.listFull": "A lista está cheia (64 entradas)",+ "remote.badIceServer": "Não é um servidor válido: use nome:porta, como stun.exemplo.org:3478 (no máximo 4)",+ "remote.badTurnUser": "Não é um usuário de retransmissor válido (sem espaços, até 128 caracteres)",+ "remote.badTurnPassword": "Não é uma senha de retransmissor válida (até 128 caracteres, sem quebras de linha)",+ "imager.cacheFailed": "Não é possível usar a pasta de downloads do gravador (~/.cache/lordos/imager)",+ "imager.noCurl": "A ferramenta de download (curl) não está instalada",+ "imager.fetchCancelled": "Download cancelado",+ "imager.fetchTooLarge": "O download é maior do que o esperado",+ "imager.fetchNotFound": "O arquivo da versão não foi encontrado",+ "imager.fetchNetwork": "Sem conexão com a página de versões do LordOS",+ "imager.fetchFailed": "O download falhou (código {code})",+ "imager.nothingRunning": "Nada está sendo baixado",+ "imager.notRemovable": "{name} não é uma unidade removível: o gravador só grava cartões SD e unidades USB",+ "imager.readOnly": "{name} está protegido contra gravação",+ "imager.diskChanged": "{name} não é a unidade escolhida (ela mudou ou foi trocada)",+ "imager.badImageName": "Esse arquivo não é uma imagem .img, .img.xz ou .iso",+ "imager.xzDamaged": "A imagem .xz está danificada ou incompleta",+ "imager.noXz": "A ferramenta .xz (xz-utils) não está instalada",+ "imager.noSignature": "Não foi possível ler os arquivos de assinatura da versão",+ "imager.badSignature": "A assinatura da versão não confere com a chave do LordOS",+ "imager.notListed": "A lista assinada não inclui {name}",+ "imager.hashMismatch": "A imagem não confere com o seu SHA-256 assinado: ela não foi gravada",+ "imager.cancelledWiped": "Cancelado: a unidade foi limpa",+ "imager.xzFailed": "Não foi possível descompactar a imagem",+ "imager.imageChanged": "O arquivo de imagem mudou durante a gravação: a unidade foi limpa",+ "imager.driveTooLarge": "{name} tem mais de 2 TiB: as imagens do LordOS não podem usá-la",+ "imager.notAuthorized": "A gravação na unidade não foi permitida",+ "imager.listFailed": "Não foi possível listar as unidades",+ "imager.bootNotFound": "A partição de boot do cartão não apareceu",+ "imager.ejectFailed": "Não foi possível ejetar a unidade",+ "imager.noUdisks": "O serviço de discos (udisks2) não está funcionando",+ "imager.hashFailed": "Não foi possível calcular o hash da senha",+ "imager.pskFailed": "Não foi possível derivar a chave do Wi-Fi",- "remote.badTurnFingerprint": "Não é uma impressão digital de certificado válida: 64 dígitos hexadecimais (os pares podem ser separados por dois-pontos)"++ "remote.badTurnFingerprint": "Não é uma impressão digital de certificado válida: 64 dígitos hexadecimais (os pares podem ser separados por dois-pontos)",+ "fw.list.unknown": "Lista de bloqueio desconhecida",+ "fw.list.badUrl": "Não é um endereço https válido",+ "fw.list.badFormat": "Formato de lista desconhecido",+ "fw.list.tooMany": "Já existem 16 listas suas",+ "fw.list.exists": "Essa lista já está aí",+ "fw.list.unavailable": "As listas de bloqueio não estão disponíveis nesta sessão"}diff --cc docs/ARCHITECTURE.mdindex 218d019,ce88a8c..8f6d36a--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@@ -57,7 -57,7 +57,8 @@@ like React Native but on top of our dis| `server/src/vault/`, `js_vault.c`, `sdk/vault.js`, `apps/passwords` | **M9** | Passwords and the system keyring: the sandboxed helper `lord-vault` (Monocypher: XChaCha20-Poly1305, Argon2id), own `.lvault` format, FIDO2/CTAP2 client, session keyring opened at login, Secret Service on D-Bus with own code (see `PASSWORDS.md`) || `server/src/net/netd.c`, `remote/netsup.c` | **M9** | `lord-netd`: the network belongs to the system. A root service started and supervised by `lord-sessiond` at boot, serving the `net-*` actions for every session (see `NETWORK.md`) || `server/src/disk/`, `js_disk.c`, `sdk/disks.js`, `apps/disks` | **M9** | Disks: listing without root (sysfs, udev database, mountinfo), our own SMART reader (ATA PASS-THROUGH over SG_IO, NVMe health log), closed `disk-*` actions, bootable USB verified with SHA-256 (see `SYSTEM.md`) |-| `server/src/fw/fwlists.c`, `fwsub.c`, `server/src/fetch/`, `server/src/sec/netconn.c`, `apps/monitor/NetTree.jsx`, `Blocklists.jsx`, `sdk/netmodel.js`, `sdk/netstatus.jsx` | **0.8.4** | Monitor → Network, second generation: blocklists (the sandboxed downloader `lord-fetch`, compiled into lord-netperm's maps), the deny mode, LordOS's components in their own scopes (the `--net-connector` processes), the system services' traffic, the tree, chips and view menu, the menu bar network item (see `MONITOR.md`, `FIREWALL.md`) |+| `server/src/imager/`, `server/src/firstrun/`, `js_imager.c`, `apps/imager`, `desktop/imager` | **0.8.4** | LordOS Imager: verified image → removable drive (`imager-*` actions, `xz` and `curl` as the user), the Raspberry Pi first-run file and its applier `lordos-firstrun`, and the same UI as a Tauri app for other computers (see `IMAGER.md`) |++| `server/src/fw/fwlists.c`, `fwsub.c`, `server/src/fetch/`, `server/src/sec/netconn.c`, `apps/monitor/NetTree.jsx`, `Blocklists.jsx`, `sdk/netmodel.js`, `sdk/netstatus.jsx` | **0.8.5** | Monitor → Network, second generation: blocklists (the sandboxed downloader `lord-fetch`, compiled into lord-netperm's maps), the deny mode, LordOS's components in their own scopes (the `--net-connector` processes), the system services' traffic, the tree, chips and view menu, the menu bar network item (see `MONITOR.md`, `FIREWALL.md`) || `server/src/mail/`, `js_mail.c`, `sdk/{mail,calendar,contacts}.js`, `apps/{mail,calendar,contacts,reminders}` | **M9** | Mail, Calendar, Contacts and Reminders: the sandboxed helper `lord-maild` (IMAP with IDLE/CONDSTORE, SMTP, CalDAV/CardDAV, OpenSSL) with no sockets of its own — `lord-server` connects only to configured servers and hands it the fd; own MIME, HTML sanitizer, iCalendar, vCard and XML parsers (see `MAIL.md`) || `server/src/backup/`, `js_backup.c`, `sdk/backup.js`, `apps/backup` | **M9** | Backups: hard-link snapshots in a lord-server thread (nice 19, idle I/O), hourly/daily/weekly retention, optional encryption with the vendored Monocypher; no root and no `admin.c` actions (see `SYSTEM.md`) || `server/src/logs/`, `js_logs.c`, `sdk/logs.js`, `apps/logs` | **M9** | Logs: our own systemd journal reader (no libsystemd), LordOS logs, system logs for admins through a closed action, live follow with inotify (see `SYSTEM.md`) |@@@ -86,10 -86,9 +87,10 @@@ Besides the kernel and libc, only thes| Mesa: `libgbm`, `libEGL`, `libGLESv2` | GPU composition and dmabuf buffers from apps (games); optional: without a 3D GPU or without the `-dev` packages it builds and runs without Mesa (approved by the user on 2026-10-16, see `GPU.md`) | system || QuickJS | ES2023 JavaScript engine, ~1 MB, written in C | vendored|| `stb_truetype`, `stb_image` | fonts and images; public domain, a single header | vendored|-| `stb_image_write` | PNG and JPEG for the remote desktop (`lord-sessiond` only); public domain | vendored|-| OpenSSL (`libssl`, `libcrypto`) | TLS. **Only three binaries link it**: `lord-sessiond` (remote desktop on the LAN, `REMOTE.md`), `lord-maild` (IMAP/SMTP/CalDAV/CardDAV, certificates checked against the system CA store, `MAIL.md`) and (0.8.4) `lord-fetch` (the blocklist downloads, sandboxed, no sockets of its own, `FIREWALL.md` "Blocklists"). Never `lord-server` | system |+| `stb_image_write` | PNG for the remote desktop's lossless refresh of still areas and cursor images (`lord-sessiond` only); public domain | vendored|- | OpenSSL (`libssl`, `libcrypto`) | TLS. **Only two binaries link it**: `lord-sessiond` (remote desktop on the LAN, `REMOTE.md`) and `lord-maild` (IMAP/SMTP/CalDAV/CardDAV, certificates checked against the system CA store, `MAIL.md`). Never `lord-server` | system |++| OpenSSL (`libssl`, `libcrypto`) | TLS. **Only three binaries link it**: `lord-sessiond` (remote desktop on the LAN, `REMOTE.md`), `lord-maild` (IMAP/SMTP/CalDAV/CardDAV, certificates checked against the system CA store, `MAIL.md`) and (0.8.5) `lord-fetch` (the blocklist downloads, sandboxed, no sockets of its own, `FIREWALL.md` "Blocklists"). Never `lord-server` | system || `libcrypt` | verifying passwords against `/etc/shadow` (`lord-sessiond`, `admin.c`) | system |+| `libsrtp2`, `usrsctp` | the remote desktop's video (WebRTC, 0.8.4): SRTP and the data channels' SCTP, in `lord-sessiond`'s bridge only (as the user, after it dropped root); with OpenSSL's DTLS and our own ICE-lite, SDP and RTP code (`remote/rtc.c`, `remote/rtcwire.c`) because Debian 13 packages no libdatachannel. Required for `lord-sessiond` since the remote desktop shows the screen only over WebRTC (the image path was removed in 0.8.4). Never `lord-server` | system || FFmpeg (`libavcodec`, `libavformat`, `libavutil`, `libswscale`, `libswresample`) and `libva` (+ `libva-drm`) | Decoding and encoding video, audio and images; VA-API for hardware decoding (M9, approved by the user). **Only `lord-media` links them**, the sandboxed helper; the player, synchronization and interface are our own. Never `lord-server` (`MEDIA.md`) | system || Poppler (`libpoppler-glib`) and libarchive | PDF and archives (M9, approved by the user). **Only `lord-doc` links them**, the sandboxed helper; Poppler brings cairo, FreeType and fontconfig, which `lord-doc` also uses for font samples and for building PDFs. Never `lord-server` (`DOCUMENTS.md`) | system || `clang` (build time only) | the BPF programs of `lord-netperm` (`np.bpf.c`, `clang -target bpf`); they are embedded in the binary. Without clang (`BPF=0`) the service runs without BPF. Neither libbpf nor bcc is used | build machine |@@@ -151,6 -147,18 +152,18 @@@ Since M8 there are two programs, and siof the accounts file (or, after *Load Images*, to public addresses for remote images) and passesthe connected fd. Its only writable folder is its cache. See `MAIL.md`.-- **`lord-fetch`** (0.8.4): the blocklist downloader. Same rules as `lord-maild` (fixed path, no++- **`lord-fetch`** (0.8.5): the blocklist downloader. Same rules as `lord-maild` (fixed path, no+ arguments, minimal environment, `sandbox_apply_helper` after loading the CA bundle, no sockets of+ its own); it lives for one download job, gets each list's already-connected socket, speaks TLS+ and one HTTP GET with a size limit, parses the list strictly and returns normalized lines in a+ sealed memfd. See `FIREWALL.md`, "Blocklists".+-- **The components' connectors** (0.8.4): `lord-server --net-connector mail|print|lists`, the same++- **The components' connectors** (0.8.5): `lord-server --net-connector mail|print|lists`, the same+ binary re-executed with a fixed argv (like the terminal holders), each in its own+ `lordos-net-<name>.scope`, only creating and connecting sockets for lord-server so the kernel+ counts and decides them as that component (`sec/netconn.h`, `FIREWALL.md`, "LordOS components in+ their own scopes").+`lord-server` can still run on its own, with its own DRM and evdev, for development.Data shipped with LordOS for the Monitor (`MONITOR.md`): `assets/monitor/geoip-country.mmdb.xz`diff --cc docs/FIREWALL.mdindex a23a960,3e1bccc..88a51eb--- a/docs/FIREWALL.md+++ b/docs/FIREWALL.md@@@ -11,6 -11,7 +11,7 @@@ access" permission on Android and othe| 4 | Settings: "Trusted apps" and "Restricted apps" | **done**: lists and mode (silent / off) || 4b | Settings: network rules by app (domains, addresses, networks) | **done** (VM 122), see [Rules by app](#rules-by-app-settings-and-monitor) || 5 | "Ask" mode | planned (see "The ask mode") |-| 0.8.4 | Blocklists, the deny mode, LordOS's components and the system services as their own apps | **done** (VM 118), see [Blocklists](#blocklists-084), [components](#lordos-components-in-their-own-scopes-084) |++| 0.8.5 | Blocklists, the deny mode, LordOS's components and the system services as their own apps | **done** (VM 118), see [Blocklists](#blocklists-084), [components](#lordos-components-in-their-own-scopes-084) |Step 1 is C code only, with no daemon and without touching the kernel or the network (step 2,below, is the service that enforces it):@@@ -388,6 -389,11 +389,11 @@@ instant); `GetConnectionCredentials` wi| `lan` / `internet` | lower than any network || `any` | the lowest |- (0.8.4) **2b. A subscribed blocklist** (`FwQuery.listed`): when the destination is on one of the++ (0.8.5) **2b. A subscribed blocklist** (`FwQuery.listed`): when the destination is on one of the+ user's blocklists, it is denied unless the winning rule names the destination (an exact or+ wildcard domain, an address or a network): a list beats `lan`, `internet` and `any` rules, never+ a rule the owner wrote for that destination. Trusted apps are not exempt. See "Blocklists".+Ties are broken in this order:1. the smallest port range (a concrete port beats "any");2. a concrete protocol beats "any";@@@ -966,8 -971,16 +972,16 @@@ in the kernel. Before, it was the stand|---|---|| silent (default) | whatever has no rule is allowed, and each new connection is counted and reported to the Monitor (`record`) || off | only explicit denials and restrictions apply; the rest is allowed without recording |-| deny (0.8.4, "Deny silently") | whatever no rule allows is denied and recorded; loopback (127/8, `::1`) stays allowed, so the resolver's stub and local services keep working; trusted apps keep the network; the essential system services are not apps and are never affected |++| deny (0.8.5, "Deny silently") | whatever no rule allows is denied and recorded; loopback (127/8, `::1`) stays allowed, so the resolver's stub and local services keep working; trusted apps keep the network; the essential system services are not apps and are never affected || ask | for now, the same as silent |+ The deny mode is `FW_MODE_DENY` in `fw/rules.c` and `NP_M_DENY` in `np_decide` (the last step: a+ rule, a restriction or a list decides first); with it every app's packet filter decides, so a+ connection that was open when the mode changed is cut ("Existing connections are cut"). It is offered+ in Settings → Privacy → App network and in the menu bar item. Tested: `fw-rules-test` (loopback,+ `::1`, a mapped `127.0.0.1`, a rule that allows, a trusted app, the file round trip) and the random+ comparison of `npcompile-test`, which now draws the deny mode too.+### The ask mode (next step)A `connect` hook can't wait for the owner, and holding the connection in user space (like@@@ -1081,6 -1094,78 +1095,78 @@@ programs- Script: `bench-monred-118.sh` in the scratchpad (veth `npb0`/`npb1`, namespace `npb`, bothremoved afterwards); `iperf3` was installed on VM 118 for this (`VM-SETUP.md`).-### LordOS components in their own scopes (0.8.4)++### LordOS components in their own scopes (0.8.5)++ Built-in parts that use the network used to run inside lord-server, so their traffic was-"LordOS" and a rule could only take all of them at once. Since 0.8.4 each one has its own process in++"LordOS" and a rule could only take all of them at once. Since 0.8.5 each one has its own process in+ its own scope, `lordos-net-<name>.scope`, which lord-netperm reads as the firewall app+ `lordos:<name>` (`fw_component_scope`, a fixed list: `mail`, `store`, `print`, `terminal`,+ `lists`). The kernel attributes a socket to the cgroup of the process that *created* it, so:++ - **Connectors** (`server/src/sec/netconn.c`): for Mail (lord-maild's servers: Mail, Calendar,+ Contacts, Reminders), printers and scanners (IPP and eSCL over TCP, the mDNS socket) and the+ blocklist downloads, lord-server starts `lord-server --net-connector <name>`: the **same binary**+ re-executed (like the terminal holders), fixed argv, `LANG` and `LORDOS_SESSIOND` only, the channel+ on fd 3 and every other descriptor closed. It asks lord-sessiond to place it in its scope, waits a+ quarter of a second so lord-netperm sees the new scope, and then only answers fixed-size requests:+ family (IPv4/IPv6), type (stream/datagram), and an address and port to `connect()` to+ (non-blocking; lord-server waits for the result). It returns the socket over SCM_RIGHTS and+ lord-server checks it is the kind it asked for. It takes no names or paths, runs nothing, has+ `no_new_privs`, is not dumpable and has 64 file descriptors; it only does what lord-server could+ do itself, as the same user. **Fail closed:** in a LordOS session a connector that can't enter its+ scope exits and the request fails (the traffic would otherwise be lord-server's and decided by+ its rules). Outside a session (development, the tests) the socket is made in place, as before.+ - **Store and updates:** the package engine's download child (the root admin helper's fork that+ drops to `nobody`) moves itself into `lordos-net-store.scope` before dropping root+ (`cgroup_enter_root`: only from its session's `server` leaf, only itself, a root-owned scope;+ lord-sessiond's placement service only places session users).+ - **Terminal:** the shell of each terminal (`term/pty.c`) enters `lordos-net-terminal.scope` before+ exec, so every program started there is "Terminal" (the Monitor lists them by name). Best effort:+ a terminal that can't be placed still opens.+ - **The network service:** lord-sessiond starts lord-netd in `lordos.service/netd`, its own leaf+ (`cgroup_service_leaf`), so its traffic (DHCP, the VPN daemons) can be counted apart from+ lord-sessiond's.++ Because these are ordinary firewall apps, every rule, restriction and switch works on them (Settings+ → Privacy lists them, restrictions are the network ones). The Monitor shows the VPN tunnels from+ their interfaces' counters and never offers a switch for them.++ **What was tested on VM 118:** a program in the Terminal and the Store's download each had their own+ row with their own bytes; blocking the Store (after its warning) made a download in its scope fail+ with `denied out tcp 151.101.66.132:80 (rule)`; `netconn-test` checks the requests on both sides,+ the sockets, the real connector process (the test binary re-executed) and that a connector that+ can't enter its scope refuses. Mail and the printers use the same connector as the blocklists,+ which were tested live; Mail against a real server and a network printer were not (VM 118 has+ neither).+-### The essential system services (0.8.4)++### The essential system services (0.8.5)++ Name resolution, time and the network service are shown but can never be blocked: they are not in+ any app's scope, so no rule reaches them. The accounting programs alone (`cgroup/skb_ingress`,+ `skb_egress`) are also attached to `system.slice/systemd-resolved.service` and+ `systemd-timesyncd.service` (lord-netd's leaf is already under `lordos.service`), and `np_sysc`+ gets an entry for each, keyed by its cgroup id; a packet that isn't an app's is looked up there by+ its socket's cgroup (`bpf_skb_cgroup_id`) and only counted, never filtered. COUNTS carries them as+ `system:dns`, `system:time` and `system:network` for every user. lord-netd's DHCP client uses a+ raw socket for discovery, which the cgroup programs don't see: only its unicast renewals count.+-### Measurements, 0.8.4 (VM 118)++### Measurements, 0.8.5 (VM 118)++ `iperf3` through a veth pair into a private namespace (eth0 untouched), the client in an app scope,+ system CPU in % of one core over 15 s, 0.8.3's lord-netperm and this one interleaved twice:+-| | 0.8.3 | 0.8.4 |++| | 0.8.3 | 0.8.5 |+ |---|---|---|+ | UDP 1 Gbit/s, 1200 B datagrams (104,000 packets/s), sending | 104, 109, 107, 102 % | 112, 117, 112, 110 % |+ | the same, receiving | 105, 101, 104, 98 % | 116, 116, 110, 114 % |+ | TCP (~22 Gbit/s) | 166, 163 % | 172, 168 % |++ About 0.6 µs more per packet at this extreme rate (the per-port flow key and the bound-port lookup+ on every packet): a video over QUIC at a few thousand packets per second costs well under 0.5 % of a+ core. Blocklists add nothing per packet: with four lists (399,396 entries) on and off, the same+ bench gave 105–115 % and 109–111 %, within run-to-run noise. A build without the per-port parsing+ gave the same numbers as this one, so the difference is not the port parsing itself.+### Known limits- **App scopes are root's now** (was: "Scopes belong to the user"). `lord-sessiond` creates the@@@ -1131,6 -1216,105 +1217,105 @@@- "LAN only" from Settings: no internet, the gateway yes. -## Blocklists (0.8.4)++## Blocklists (0.8.5)++ A curated catalog of public lists by topic (advertising, trackers, malware and attacks), domain-+ and address-based, that the owner turns on in Settings → Privacy → Blocklists, plus custom lists by+ https address. Lists are downloaded daily over HTTPS by an unprivileged, sandboxed helper, parsed+ strictly, checked again by lord-server, compiled into one file and enforced by lord-netperm in the+ existing per-app maps. They never override a rule the owner wrote for a destination.++ ```+ assets/fw/blocklists.json the catalog: id, topic, url, format, licence, source, date checked+ server/src/fw/fwlists.{c,h} raw parsers, the set (hashes), the compiled file's reader+ server/src/fw/fwsub.{c,h} lord-server: subscriptions, the download job, compiling+ server/src/fetch/fetch.c lord-fetch, the downloader (OpenSSL), fetchproto.h its protocol+ server/src/ui/js_fw.c lord.fw.lists / setList / addList / removeList / updateLists / listMatch+ apps/monitor/Blocklists.jsx Settings → Privacy → Blocklists+ tests/fwlists_test.c, fwsub_test.c+ ```++ ### The catalog and its licences++ Each list was added only after its licence was checked (the list file's own header and its+ project's licence file, 2026-10-19), and the catalog records what was found; LordOS ships no list+ data, each machine downloads what its owner turns on.++ | List | Topic | Format | Source | Licence |+ |---|---|---|---|---|+ | Advertising (domains) | ads | domains | The Block List Project | MIT (list file), Unlicense (repository) |+ | Advertising and malware (unified hosts) | ads | hosts | Unified hosts (Steven Black) | MIT |+ | Trackers and analytics | trackers | domains | The Block List Project | MIT, Unlicense |+ | Phishing sites, Scam sites, Ransomware, Hidden crypto mining | malware | domains | The Block List Project | MIT, Unlicense |+ | Attacking addresses | malware | addresses | IPsum, level 3 | Unlicense |++ Left out: a malware URL feed whose terms are fair use without a stated licence; a botnet controller+ address list (CC0) that was empty when checked; The Block List Project's malware list (2.6 million+ entries, over the size limit); lists under non-commercial licences.++ ### Downloading: lord-fetch++ - **Who connects:** lord-server resolves the list's host and connects through the blocklists'+ connector, so the socket is `lordos:lists`'s (its own row and rules). Only `https://` addresses+ (`fws_split_url`: a host name with a dot, an optional port, a printable path; no user info, no+ addresses in brackets).+ - **lord-fetch** (`server/src/fetch/fetch.c`): posix_spawned by the job thread from lord-server's+ folder (root's or the user's, not writable by others), no arguments, `LANG` only, the channel+ (lord-doc's framing) on fd 3. It loads the CA bundle and then calls `sandbox_apply_helper` (scope+ `lordos-fetch.scope`, 256 MB; no socket, connect, bind or exec; no files). For each list it gets the+ connected socket and `{host, path, format, sub}`; it speaks TLS 1.2 or later with the certificate+ checked against the system CA store and the host name (mail/net.c, never relaxed), sends one+ HTTP/1.1 GET with `Accept-Encoding: identity`, and reads at most 16 MB with deadlines+ (mail/http.c). A redirect comes back to lord-server, which follows at most three, https only.+ - **Strict parsing, in the helper** (`fwl_parse_raw`): a NUL byte, a line over 1024 bytes or a body+ over 16 MB reject the list; comments (`#`, `!`, `;`, `//`, inline ` #`) are dropped; a hosts file+ only maps names to `0.0.0.0`, `127.0.0.1`, `::` or `::1`; a domain list has one name per line+ (`*.name` and `||name^` mean the name and its subdomains); an address list has an address or a+ CIDR network first on the line (other columns ignored; host bits must be 0). Skipped and counted:+ localhost names, names without a dot, LAN networks (it would cut the machine off its own network)+ and networks broader than /8 or /16. More than 10 % unparsable lines (over 20) reject the list as+ the wrong format. At most 300,000 names or 100,000 networks per list (the rest is cut and said).+ What comes back is normalized lines (`d name`, `s name`, `n cidr`), each once, in a sealed memfd.+ - **lord-server checks it again** (every line with the same validator) before keeping a copy in+ `~/.cache/lordos/fwlists/<id>.txt` with its state (`<id>.json`: when, how many, the last error).+ - **Daily:** `sdk/netstatus.jsx` asks once an hour (`lord.fw.updateLists`); lord-server downloads+ only the enabled lists whose copy is more than 20 hours old, and a list that failed is tried again+ after an hour. Turning a list on downloads it at once if there's no copy.++ ### Compiling and enforcing++ - **One file:** the job thread writes every enabled list's lines into `~/.config/lordos/fwlists.txt`+ (header `lordos-fwlists 1`, at most 32 MB) and keeps a set of hashes for the Monitor's "on the list+ …" (`lord.fw.listMatch`); when the job ends lord-server sends the usual RELOAD. The three files+ are on `lord.fs`'s deny list.+ - **lord-netperm** reads `fwlists.txt` with the same fixed-path, no-links, user-owned, size-limited+ reader as `firewall.json`, and any invalid line keeps the previous set. Names are kept as 64-bit+ hashes (keyed per process) in sorted arrays, about 10 bytes a name: 380,000 names and 19,000+ networks take 13.8 MB of lord-netperm's memory.+ - **In the kernel:** each user with lists gets a set in `np_blk4`/`np_blk6` (LPM tries keyed by+ set and address), and each of their apps carries it (`NpApp.blk`). The set holds the lists'+ networks and, from the system resolver's answers, the addresses of listed names; an address is+ only added when **every** name the resolver gave for it is listed, so an address a tracker shares+ with a site that isn't listed (a shared CDN) stays allowed. A DNS answer updates its addresses at+ once, before the app connects; every 30 s the whole set is recomputed (what the resolver forgot+ goes); learned addresses are capped at 16,384 per user. `np_decide` checks the set after the+ rules naming the destination and before `lan`/`internet`/`any`.+ - **No per-packet cost:** lists don't make the packet filter decide for every app: `connect()` and+ `sendmsg()` deny, and after each change that adds entries a sweep cuts the sockets already open+ to them (as for rules).++ **What lists can't see:** the same as domain rules ("What domain rules can't see"): an app with its+ own encrypted DNS is only checked by address.++ **Tested:** `fwlists-test` (hosts, domains and address formats, every rejection rule, the set and its+ lookups, CNAME-style shared addresses, the file reader, 20,000 mutated lists; also under ASan and+ UBSan) and `fwsub-test` (URL parsing, the catalog and config, compiling seeded copies, custom lists,+ and lord-fetch refusing bad requests and a peer without TLS, without network). On VM 118: two lists+ downloaded over HTTPS (8,527 names and 19,405 networks), then all four; `curl` from the Terminal to+ a listed domain and to a listed address failed with `denied out tcp … (list)`; switching that+ domain's row on in the Monitor wrote `{"app":"lordos:terminal","dst":"nationalityship.com","action":"allow"}`+ and the next connection went through; switching it off removed the rule.+## Rules by app (Settings and Monitor)The rules the store always supported (`lord.fw.addRule`: domains, wildcards, addresses, networks,diff --cc docs/MAIL.mdindex ba47f6c,da8b360..b177e89--- a/docs/MAIL.md+++ b/docs/MAIL.md@@@ -57,7 -57,10 +57,10 @@@ run in one sandboxed helper process, **- **No socket of its own.** `lord-maild` cannot create sockets. To reach a server it sends`MR_CONNECT {host, port}`; `lord-server` (`mailc.c`) checks the endpoint against the accountsfile and, if allowed, resolves it, connects (10 s timeout) on a thread of its own and passes the- connected socket back (`MQ_SOCK`). The allowed endpoints are exactly: each account's IMAP and- connected socket back (`MQ_SOCK`). (0.8.4) The socket itself is made and connected by Mail's connector++ connected socket back (`MQ_SOCK`). (0.8.5) The socket itself is made and connected by Mail's connector+ (`lord-server --net-connector mail`, in `lordos-net-mail.scope`), so Mail and the calendar sync+ are their own app for the firewall and Monitor → Network ("Mail and calendars", `lordos:mail`;+ `FIREWALL.md`, "LordOS components in their own scopes"); the endpoint check above is unchanged. The allowed endpoints are exactly: each account's IMAP andSMTP `host:port`, each DAV URL's `host:port`, and — for CalDAV/CardDAV discovery redirects insidethe same provider (for example `pNN-caldav.icloud.com`) — other hosts of the same domain on port 443.So a malicious message that takes over `lord-maild` still cannot talk to anything else.diff --cc docs/MONITOR.mdindex 86684ea,363d5e6..6f7213d--- a/docs/MONITOR.md+++ b/docs/MONITOR.md@@@ -30,6 -30,10 +30,10 @@@ itself### Network-Since 0.8.4 the left column is a tree with a view menu, search chips and rows for LordOS's own-parts and the system's services: see "Network, second generation (0.8.4)" below. What follows is++Since 0.8.5 the left column is a tree with a view menu, search chips and rows for LordOS's own++parts and the system's services: see "Network, second generation (0.8.5)" below. What follows is+ the rest of the tab, and the first generation of the list.+- **Left:** search (by app, address or country) and one row per app with its icon, number ofconnections, a traffic bar (received in green, sent in orange, relative to the app that movedthe most), a tiny live activity indicator (its traffic over the last 12 s, one bar per second),@@@ -107,6 -111,132 +111,132 @@@ server, and this app's rule is that no**"This computer"** is placed by the time zone (`/etc/localtime` → coordinates from`/usr/share/zoneinfo/zone1970.tab`), without the network.-### Network, second generation (0.8.4)++### Network, second generation (0.8.5)++ ++ **Rows for LordOS's own parts.** Everything built in that uses the network is a row of its own,+ backed by its own process and cgroup scope, so its rules are enforced by the kernel like any app's+ (`FIREWALL.md`, "LordOS components in their own scopes"):++ | Row | Firewall id | Its traffic |+ |---|---|---|+ | Mail and calendars | `lordos:mail` | lord-maild's servers (Mail, Calendar, Contacts, Reminders sync), made by Mail's connector |+ | Store and updates | `lordos:store` | the package engine's downloads (the Store, Settings → General, the daily update check) |+ | Printers and scanners | `lordos:print` | IPP and eSCL to network printers and scanners, and their mDNS discovery |+ | Terminal | `lordos:terminal` | the shell of every terminal and every program it starts; the detail lists the programs by name |+ | Blocklist updates | `lordos:lists` | the daily blocklist downloads (`lord-fetch`) |+ | VPN | `lordos:vpn` | the counters of LordOS's own VPN interfaces (Settings → Network); not blockable |+ | Name resolution (DNS) | `system:dns` | systemd-resolved; shown, never blockable |+ | Time synchronization | `system:time` | systemd-timesyncd; shown, never blockable |+ | Network service | `system:network` | lord-netd's own leaf (DHCP, Wi-Fi, the VPN daemons); shown, never blockable |++ Apps that never touch the network (Calculator, Notes…) never appear: a row exists only for traffic.+ The essential system rows show "System" instead of a connection count and a dash instead of a switch.+ Blocking the Store asks first, because no security update arrives while it is blocked:++ ++ The **"LordOS" row** is now what is left in lord-server itself, close to zero; every socket a+ component's connector made counts as that component's, also in the open-connections list (the+ socket's cgroup, `INET_DIAG_CGROUP_ID`, mapped to the session's scopes: conn.c `cgApp`).++ ++ **The tree.** Each app opens into its destinations (the name the system resolver gave, or the+ address), a name with several addresses opens into them, and each address into its ports (TCP 443,+ UDP 443…). Every row has its received and sent bytes, a tiny up/down meter of its current rate+ (log scale), and, for a destination, its own allow/deny switch with a hint when something else+ decides it (another rule, the app's default, a restriction, the deny mode or a blocklist: "Blocked+ by the list Scam sites"). Long lists fold after eight rows ("N more…"). For an address reached+ through a CNAME chain the row shows the shortest name (usually the one the app asked for) and+ searches every name of the chain. The per-port bytes come from lord-netperm (np_flows is per-address and port since 0.8.4; COUNTS sends each address's eight busiest ports).++address and port since 0.8.5; COUNTS sends each address's eight busiest ports).++ **The view menu** (one pop-up button at the top of the column) holds the whole view, kept per user in+ `settings.monitor.netView`:++ - group by: apps, domains, addresses, ports or countries (the tree's levels follow: a domain opens+ into its apps and their ports, a port into its apps and their destinations…);+ - direction: all, outgoing, incoming; protocol: all, TCP, UDP and QUIC; status: everything,+ allowed, denied, with rules;+ - sort by: name, most traffic, least traffic, most recent, most connections;+ - "Show network activity in the menu bar" and "Blocklists…" (Settings → Privacy).++  ++ **Search with chips.** Typing `app:firefox`, `domain:example.com`, `ip:10.0.0.0/8`, `port:443`,+ `proto:udp` (or `quic`) or `country:AR` and a space turns the token into a chip; Enter turns every+ word (an address or network becomes an IP chip, a number a port, `tcp`/`udp` a protocol, two+ capital letters a country, a name with a dot a domain, anything else an app). Chips of different+ kinds combine (app *and* domain), two of the same kind are alternatives; the rest of the text+ matches anywhere. Backspace in an empty field removes the last chip. There is no city chip: there+ is no city-level IP database with a compatible licence (see "Map").++ ++ **The time range.** The traffic chart's zoom (1 h, 24 h, 7 d, 30 d, with ‹ ›) now also drives the+ list: in a history window it shows each app's bytes in that window, from the history file. The+ history never keeps destinations (see "Traffic history", Privacy), so in a window the rows have no+ children; the live view keeps the tree.++ The pure part (tokens, filters, grouping, sorting, the saved view) is `sdk/netmodel.js`, tested by+ `server/tests/netmodel_test.mjs`; the tab is `apps/monitor/Network.jsx` and `apps/monitor/NetTree.jsx`.+-### The menu bar network item (0.8.4)++### The menu bar network item (0.8.5)++ Optional and off by default (Settings → Privacy → Monitor → "Network activity in the menu bar", or+ the view menu). It shows the upload and download rates in the status area, rounded ("↑5K ↓231K",+ "0" under 1 KB/s), updated every other second and only redrawn when the rounded value changes.+ Its panel:++ - the sent (up) and received (down) graph of the last five minutes, 60 bars of 5 s, and their totals;+ - the apps moving data now, with their rates;+ - **Recently denied** in the last ten minutes, with a count, the same destination grouped (×N);+ - the firewall mode: Allow silently, Deny silently, Off (`FIREWALL.md`, "The modes"). The ask mode+ is not offered until it exists; rule profiles come with the rules manager (0.8.5);+ - the blocklists (lists on, entries) and "Open Monitor…".++ While the item is shown it reads `lord.monitor.netTotals()` (one read of `/proc/net/dev`) once+ per second, without the Monitor's sampling thread; lord-netperm's notices are read only while the+ panel is open. Hidden, it costs nothing. `sdk/netstatus.jsx`.++  +-### Blocklists (0.8.4)++### Blocklists (0.8.5)++ Settings → Privacy → Blocklists (`apps/monitor/Blocklists.jsx`): the curated catalog by topic, each+ list with its source, its licence, how many entries it had and when it was downloaded; a checkbox+ turns it on, "Update Now" downloads again, and your own lists take an https address and a format.+ How they are downloaded, checked and enforced is in `FIREWALL.md`, "Blocklists". The Monitor shows+ the lists in its summary, "On the list …" under a destination, and "by a blocklist" in Recently+ denied.++ ++  +-### Measurements (0.8.4, VM 118, 4 vCPU Xeon Silver 4108, kernel 6.12)++### Measurements (0.8.5, VM 118, 4 vCPU Xeon Silver 4108, kernel 6.12)++ Same session, same test traffic (curl in an app scope: a 120 KB/s download and HTTPS requests every+ 4 s), main's build (0.8.3 + 0.8.4 so far) against this one, 30 s each, lord-server's CPU in % of+ one core:++ | | main | this build |+ |---|---|---|+ | Monitor open on Network, traffic | 17.1 / 16.1 % | 14.8 / 14.0 % (the tree, chips, system rows; 4 blocklists on) |+ | desktop idle, menu bar item off | 2.65 % (the VM's previous install) | 2.93 % (4 blocklists on) |+ | desktop idle, menu bar item on | — | 2.95 % |+ | desktop with traffic, item on / its panel open | — | 0.97 % / 3.87 % |++ Memory with 4 lists (379,991 names, 19,405 networks): lord-netperm 13.8 MB (2.9 MB without lists),+ lord-server 142 MB with the Monitor open (131 MB on main). The per-packet cost is in `FIREWALL.md`-("Measurements, 0.8.4").++("Measurements, 0.8.5").++ **Before** (main, no lists: the scam site connects) **and after:**++  +### Remote desktop (0.8.3)While the remote desktop is on (Settings → Sharing), it is one more row in the app list, **Remote@@@ -389,7 -519,8 +519,8 @@@ bottom of the tab (`settings.monitor.di## Architecture```- apps/monitor/ index.jsx (tabs), Network.jsx (Network), MapView.jsx (map), Chart.jsx,-apps/monitor/ index.jsx (tabs), Network.jsx (Network), NetTree.jsx (0.8.4: the tree, chips and- view menu), Blocklists.jsx (0.8.4: Settings → Privacy → Blocklists), MapView.jsx (map), Chart.jsx,++apps/monitor/ index.jsx (tabs), Network.jsx (Network), NetTree.jsx (0.8.5: the tree, chips and++ view menu), Blocklists.jsx (0.8.5: Settings → Privacy → Blocklists), MapView.jsx (map), Chart.jsx,TrafficChart.jsx (mirrored sent/received chart), History.jsx (zoom andhistory windows), draw.js (pixels),icons.jsx, Privacy.jsx, countries.js (generated)@@@ -397,6 -528,8 +528,8 @@@ apps/monitor/Processes.jsx the Procesapps/monitor/DisksTab.jsx the Disks tab: rates, temperature and health per disk, the chosen disk's cardssdk/smart.js, sdk/smartparse.js SMART summaries and smartctl's JSON → one model (Disks app too)sdk/diskwatch.js notices when a disk gets too hot or less healthy-sdk/netmodel.js (0.8.4) search tokens, filters, the tree, sorting and the component rows (pure)-sdk/netstatus.jsx (0.8.4) the menu bar network item and the blocklists' hourly update check++sdk/netmodel.js (0.8.5) search tokens, filters, the tree, sorting and the component rows (pure)++sdk/netstatus.jsx (0.8.5) the menu bar network item and the blocklists' hourly update checksdk/monitor.js useMonitor(), stores monitorSamples / monitorProcesses / monitorConnections /monitorDetail; monitor.watchProcess(), monitor.stopProcess()server/src/ui/js_monitor.c lord.monitor (read-only, validated API)@@@ -436,6 -569,7 +569,7 @@@ Each disk in `sample().disk.disks` carr`null`; `temp` in °C or `null`; `tempT`: when it was read; `tempIdle`: a spinning disk at rest, notread; `awake`: I/O in the last minute).| `history({ from, step, n, app })` | the traffic history in `n` buckets (see "Traffic history"), or `null` |-| `netTotals()` | (0.8.4) `{ t, rx, tx }`: the machine's byte counters now (every interface but `lo`), without the sampling thread (the menu bar item) |++| `netTotals()` | (0.8.5) `{ t, rx, tx }`: the machine's byte counters now (every interface but `lo`), without the sampling thread (the menu bar item) || `historyEnable(on)` / `historyClear()` | the "Keep a traffic history" setting; deletes the history |No function takes paths or commands: the only arguments are booleans, a language code (letters,@@@ -486,6 -620,9 +620,9 @@@ listening one) or `out`. Scope: `intern**From process to app** (`js_monitor.c`, on the screen thread with the list from `apps.c`):-0. (0.8.4) a socket made in one of the session's scopes is that scope's app (`cgApp`, from the++0. (0.8.5) a socket made in one of the session's scopes is that scope's app (`cgApp`, from the+ socket's cgroup id; conn.c reads the session's scope ids every 5 s): Mail's connector, the+ Terminal's programs, an app's own sockets;1. `lord-server` itself is **LordOS** (native apps and the Store run inside it);2. otherwise, the `.desktop` whose `Exec` program (`DesktopApp.bin`) matches the executable,`argv[0]` or the process name;diff --cc docs/NETWORK.mdindex 5c179fa,c15ba6f..7a881ed--- a/docs/NETWORK.md+++ b/docs/NETWORK.md@@@ -35,6 -35,11 +35,11 @@@ lord-server --user ana ── lord-adm- **What it is.** `lord-netd` is `admin.c` built with `LORD_NETD` (`server/src/net/netd.c` only has`main`). Its table has **only** the `net-*` actions, with the same validation, and it runsnothing those actions didn't already run. libc only.-- **Its own cgroup leaf** (0.8.4): before its execve, the child moves itself into the root-owned++- **Its own cgroup leaf** (0.8.5): before its execve, the child moves itself into the root-owned+ `lordos.service/netd` leaf (`cgroup_service_leaf`), next to lord-sessiond's `supervisor` leaf, so+ Monitor → Network can count the network service's own traffic ("Network service", never+ blockable; `FIREWALL.md`, "The essential system services"). A lord-netd adopted from before the+ update stays where it was until it restarts.- **When it starts.** `lord-sessiond` starts it at boot, before the greeter(`server/src/remote/netsup.c`):- fixed path `<lord-sessiond's directory>/lord-netd`, root-owned and not writable by othersdiff --cc docs/PACKAGES.mdindex 56e808d,81782af..e9ce26c--- a/docs/PACKAGES.md+++ b/docs/PACKAGES.md@@@ -44,6 -44,11 +44,11 @@@ The code is in `server/src/pkg/`- **Local repositories.** A `file:/path` source (a repository on a disk or a USB stick, like apt's`file:` method) is read by the same unprivileged child, as `nobody`: only world-readable files,checked exactly like a download. An HTTP redirect can never lead to a `file:` URL.-- **Its own firewall app** (0.8.4): before dropping root the download child moves itself into++- **Its own firewall app** (0.8.5): before dropping root the download child moves itself into+ `lordos-net-store.scope` (`cgroup_enter_root`), so the Store and the updates are "Store and+ updates" (`lordos:store`) in Monitor → Network, with their own rules; blocking them asks first,+ because no security update arrives while they are blocked (`FIREWALL.md`, "LordOS components in+ their own scopes").- **Downloads without root.** The process that talks to the network drops privileges beforeconnecting: it becomes `nobody`, with no groups, with `no_new_privs` and no way back to root.It passes the bytes to the root process through a pipe. The root process only writes them intodiff --cc docs/PRINTING.mdindex 3fda553,0475c44..81b3178--- a/docs/PRINTING.md+++ b/docs/PRINTING.md@@@ -100,6 -100,12 +100,12 @@@ CUPS (/run/cups/cups.sock) → Debian flengths and no control characters. There are tests in `ipp-test`: a hand-built packet, truncatedat every byte and with a pointer loop.-**Their own firewall app** (0.8.4): the IPP and eSCL connections to network printers and scanners,++**Their own firewall app** (0.8.5): the IPP and eSCL connections to network printers and scanners,+ and the mDNS discovery socket, are made by the printers' connector (`lord-server --net-connector+ print`, `lordos-net-print.scope`), so they are "Printers and scanners" (`lordos:print`) in Monitor →+ Network, with their own rules (`FIREWALL.md`, "LordOS components in their own scopes"). The local+ CUPS socket is a Unix socket and isn't affected.+### Scanner (eSCL, `apps/scanner`)`server/src/print/escl.c` + the **Scanner** app (opened from Settings or from the app launcher):diff --cc docs/ROADMAP.mdindex 9e1da63,9ff72cb..cd40df7--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@@ -508,7 -508,10 +508,10 @@@ Details in `MAIL.md`. Tested on VM 123## Before 1.0- - [ ] **Monitor → Network, second generation (0.8.4)** — our own design; same function as the-- [x] **Monitor → Network, second generation (0.8.4)** — done 2026-10-19 on VM 118, see++- [x] **Monitor → Network, second generation (0.8.5)** — done 2026-10-19 on VM 118, see+ `MONITOR.md` ("Network, second generation", "The menu bar network item", "Blocklists") and+ `FIREWALL.md` ("LordOS components in their own scopes", "The essential system services",+ "Blocklists", "The modes"). Our own design; same function as thebest per-app firewalls, no copied look or names.- **Native apps as their own rows:** every built-in component that uses the network gets a rowwith its name and icon, backed by its own process and cgroup so rules are enforced by the@@@ -540,8 -543,16 +543,16 @@@format limits, parsed strictly, compiled into the existing domain/IP rule maps; custom listURLs allowed. Lists never override a user's explicit allow rule.- Performance budget measured as in 0.8.3 (no visible cost with thousands of list entries).+ - **Done as described, except:** no city chip and no grouping by city (no city-level IP database+ with a compatible licence); a history window lists apps only (the history never keeps+ destinations); the switches are on destinations, not on single ports; the menu bar item offers+ allow silently / deny silently / off (the ask mode doesn't exist yet) and no rule profiles+ (0.8.5); "Recently denied" counts the last ten minutes.+ - [ ] Test Mail's and the printers' connectors against a real mail server and a network printer+ (the same connector was tested live with the blocklists); a laptop's real DHCP and VPN rows.+ - [ ] The per-packet cost of the per-port accounting (+0.6 µs at 104,000 packets/s): find it.-- [ ] **Firewall rules manager (0.8.5)** — a "Rules" section in the Monitor (our own design):+- [ ] **Firewall rules manager (its own release after 0.8.5)** — a "Rules" section in the Monitor (our own design):- **Sidebar:** All rules, Active, Denied, Recently modified, Recently used, Temporary, Unapproved(rules created silently, waiting for review, with a count); then Rule groups, Blocklists andProfiles, each with an on/off checkbox.diff --cc docs/TERMINAL.mdindex 9188553,18756bb..132f804--- a/docs/TERMINAL.md+++ b/docs/TERMINAL.md@@@ -282,6 -282,10 +282,10 @@@ RemoteHost (user@host, for automatic prline without newlines: it's the same thing the user could type into that tmux.- `lord.fs.read()` (for the importer) reads regular files under `$HOME`, 8 MB maximum.- Fonts are only looked up in font folders; those in `~/.fonts` belong to the user.-- (0.8.4) The shell enters `lordos-net-terminal.scope` before exec (`pty.c`), so it and every++- (0.8.5) The shell enters `lordos-net-terminal.scope` before exec (`pty.c`), so it and every+ program it starts are the firewall app "Terminal" (`lordos:terminal`): its own row in Monitor →+ Network, with each program's name, and its own rules (`FIREWALL.md`, "LordOS components in their+ own scopes"). Best effort: a terminal that can't be placed still opens.## Testsdiff --cc docs/VM-SETUP.mdindex 8a7a98a,d1f657c..9f3e24d--- a/docs/VM-SETUP.md+++ b/docs/VM-SETUP.md@@@ -1372,244 -1372,41 +1372,283 @@@ in `~/LordOS-csd`, built there (`make -the profiles, the tree, the script and the backup removed, `lordos.service` restarted to the loginscreen. No network or Proxmox setting was touched.-## Step 41 — 0.8.4: Monitor → Network, second generation (VM 118 `lordos-notes`, October 19)+## Step 39 — 0.8.4: the browsers' title bar switch in Settings (VM 119 `lordos-spot`, October 19)++See `WAYLAND.md` ("The switch in Settings"). On VM 119 (172.17.0.54), tree in `~/LordOS-brs` (copied+with `tar` over SSH: the VM has no `rsync`), built there (`make -C server`, `make -C server test`)+and installed over `/usr/lib/lordos` by `~/deploy-brs-119.sh` (it saved `/usr/lib/lordos` to+`/var/backups/lordos-brs-bak` and `settings.json` to `/var/tmp` first).++- **Installed for the tests,** as in step 38: `gsettings-desktop-schemas` and `assets/gtk/LordOS*` in+ `/usr/share/themes/` (Chromium's GTK theme needs them for the traffic lights); both removed at the+ end.+- **Session:** `/etc/lordos/session.conf` with `AUTOLOGIN=lord` (it didn't exist; removed at the+ end), English and light in `settings.json` (restored at the end). A new session for the login-time+ tidy-up: the session's `lord-server` ended, `/run/lordos/autologin-done` removed, `systemctl+ restart lordos`.+- **Browsers,** started from SSH in the session (`WAYLAND_DISPLAY=wayland-0`, the session bus,+ `GSETTINGS_BACKEND=keyfile`) by `~/brs-run.sh`, quit with `SIGTERM` (Chromium) or Ctrl+Q and+ Return through `qm monitor 119` `sendkey` (Firefox: mouse clicks don't reach it on this VM).+ - **Chromium:** the user's `~/.config/chromium` was moved aside to `~/.config/chromium.brs-saved`+ and a throwaway profile made by starting Chromium; it was turned into a 0.8.3-style profile+ (`custom_chrome_frame` false) by hand, then: «Change them», the switch turned off while Chromium+ was open (applied seconds after it quit), and a check that Chromium keeps the edited values when+ it rewrites `Preferences`. Chromium left a stale `SingletonLock` after `SIGTERM`; it was+ correctly ignored. At the end the throwaway profile was deleted and the saved folder put back.+ - **Firefox:** `lord` already had two Firefox ESR profiles in `~/.config/mozilla/firefox` from+ October 16 (not checked before the first toggle, so the switch wrote to them): `user.js` lines+ and `user.js.lordos-backup` files, and Firefox ran three times on `eb7mmslg.default-esr` (its+ normal session files changed; `prefs.js` got `browser.tabs.inTitlebar`). At the end LordOS's+ files were removed from both profiles (`user.js`, `user.js.lordos-backup`; Firefox never creates a `user.js`, and both+ backups held only LordOS's line) and the `inTitlebar` line removed from+ `prefs.js` with Firefox closed, so it follows the default again.+- **Input and screenshots:** `lord-qmp-input.py 119 1280 800` from the host, `screendump` holding+ `flock /tmp/sistema-119-screen.lock`.+- **Undone at the end:** `/usr/lib/lordos` restored from the backup (the 90 paths the deploy added+ removed, `diff -r` against the backup empty), `settings.json` restored, `gsettings-desktop-schemas`+ purged, the GTK themes, `session.conf`, the scripts, the tree, the backup and `/tmp/brs-*` removed,+ `lordos.service` restarted to the login screen (the 0.8.3-era greeter kept running, as before).+ `eth0` keeps 172.17.0.54; no network or Proxmox setting was touched.++## Step 40 — 0.8.4: remote desktop over WebRTC (VM 122 `lordos-sandbox`, October 19)++See `REMOTE.md`, "Video (WebRTC)". On VM 122 (172.17.0.56), tree in `~/LordOS-rtc` (synced from the+Mac's `v084-rtc` worktree by a script of its own name, `sync-rtc-122.sh`, kept outside the repo),+built there (`make -C server`, `make -C server test`) and installed over the package's files by+`~/deploy-rtc-122.sh`, which saved `/usr/lib/lordos`, `/etc/lordos` and `/var/lib/lordos/remote` to+`/var/backups/lordos-rtc-20261019` first (`~/restore-rtc-122.sh` put them back). The theme bundles+were built on the Mac (the VM has no Node).++- **Installed for the build:** `libsrtp2-dev` and `libusrsctp-dev` (with `libsrtp2-1`, `libusrsctp2`,+ `libnss3-dev`, `libnspr4-dev`); removed at the end with `apt-get purge` + `autoremove`.+- **Installed for the TURN tests:** `coturn` (`--no-install-recommends`, with its 11 dependencies);+ its unit was stopped and disabled right after installing, and `turnserver` ran by hand on+ 172.17.0.56:3478 with a test-only user from `/tmp/turn-rtc.conf`. Purged at the end.+- **Test-only accounts** `rtest` and `rtest2` (one password, only for these tests); `rtest` was put+ in `sudo` for the Settings → Sharing screenshots and the `remote-ice` action. Both deleted with+ their homes at the end.+- **The GPU path:** a drop-in `/etc/systemd/system/lordos.service.d/rtc-gpu-test.conf`+ (`Environment=LORD_GPU=1`, llvmpipe on this virtio card) and `rtest` signed in on the login screen+ through the Proxmox host's `lord-qmp-input.py` and `lord-type.py`; screenshots with `qm monitor 122`+ (`screendump`). The drop-in was removed.+- **Browsers:** headless Chrome on the Mac with throwaway profiles in the scratchpad (deleted after+ each run), driven over the DevTools protocol; CPU and traffic sampled on the VM by+ `~/cpu-rtc-122.sh` (`/proc/<pid>/stat`, `eth0` counters); the ICE/STUN probes by+ `/tmp/icetest-rtc.py` from the VM itself.+- **Configuration changed during the tests** (all restored from the backup): `config` (`net=`+ switched to `any` by a stray test click and back, `net=list` for one test, the TURN lines),+ `access` (one test `allow` entry), `turn.key`, `session.conf`.+- **Undone at the end:** `/usr/lib/lordos` and `/etc/lordos` restored from the backup (`diff -r`+ empty), `/var/lib/lordos/remote` restored, `/var/lib/lordos/last-user` back to `lord`, the+ packages above purged, the test accounts, the tree, the scripts, `/tmp` files and the backup+ removed, `lordos.service` restarted on the package's binaries, at the login screen. eth0 and the+ VM's network were not touched; VM 123 was not used.++## Step 41 — 0.8.4: the Pi kernel with socket destroy (VM 116 and the Raspberry Pi, October 19)++See `RASPBERRY.md` ("The LordOS kernel", "Switching kernels on a board") and `FIREWALL.md`+("Existing connections are cut").++- **VM 116 (172.17.0.52), cross build:** installed `gcc-aarch64-linux-gnu` and+ `libc6-dev-arm64-cross` (with their dependencies: `binutils-aarch64-linux-gnu`, the arm64 cross+ libraries) and the kernel build packages it lacked: `bison`, `flex`, `libelf-dev`, `libdw-dev`,+ `dwarves`, `rsync`, `debhelper`. They stay, for the next cross build. Work folder+ `/var/tmp/imager-scratch/pik-kernel` (the 24 GB scratch disk; about 16 GB at the peak) with a+ temporary 4 GB swap file; `RPI_KERNEL_REF=234188315037… tools/rpi/build-kernel.sh … 2712`, 67 min.+ The swap file and the work folder were removed afterwards; the `.debs` were copied out first.+- **Raspberry Pi 5 (172.17.0.24):** a first attempt to build natively (in a tmpfs, the SD card being+ 86 % full) ended when the card was removed; nothing of it is left. Then:+ - `/var/tmp/lordos-kernel/out/`: the `-3` image and headers `.debs` and their config added+ (`SHA256SUMS` regenerated), where `build-img.sh` takes them from.+ - `dpkg -i linux-image-6.18.57-lordos.3-rpi-2712_6.18.57-3+lordos_arm64.deb`: the hooks put it at+ the top level of `/boot/firmware` (over Raspberry Pi's 6.18.50 copy there, which is still+ installed; the October 18 backup is in `/var/tmp/lordos-kernel/bootbak-20261018`). `-2` stays+ installed.+ - `/boot/firmware/lordos/` (the `-2` boot files) renamed `lordos-prev/`; `config.txt` lost its+ `os_prefix=lordos/` lines (a comment explains how to go back); `tryboot.txt` now boots+ `lordos-prev/` once. Before the change: `/var/tmp/lordos-pik/config.txt.before` and+ `tryboot.txt.before`. First boot of `-3` through `tryboot`, then a normal boot, a `tryboot` into+ `-2` (69 modules loaded, everything active) and back.+ - `lord-netperm` was still the 0.8.2 binary (not restarted by the 0.8.3 upgrade): restarted.+ - Tests in `/var/tmp/lordos-pik` (tree copy in `src/`, logs): `netperm_cut.sh` as root with a+ hand-made `lordos-session-0` cgroup (gone at the reboot; `/root/.config/lordos` removed), before+ (12/15, the stall) and after (15/15); `verify-board`; `lord-fand` `FORCE 1`/`FORCE off`;+ `make -C server test`.+ - Not changed: the network configuration, the `lordbasex` account, the partitions, `cmdline.txt`+ (this board's lacks `cgroup_enable=memory`, so `verify-board` reports the memory controller as+ FAIL; the image's has it).++## Step 42 — 0.8.4: LordOS Imager (VM 116 `lordos-gpu`, October 19)++See `IMAGER.md`. Tree in `~/LordOS-imager`, built there (`make -C server`, `make -C server test`:+23 passed, the imager suites included) and installed over `/usr/local/lib/lordos` by+`~/deploy-imager-116.sh`, which first saved `/usr/local/lib/lordos` and lord's `settings.json` in+`/var/backups/lordos-imager-bak`.++- **A scratch disk:** `qm set 116 --scsi1 local-lvm:24,discard=on` on the Proxmox host (as VM 119's+ `sata1` before it), formatted ext4 (label `imgscratch`) and mounted at `/var/tmp/imager-scratch`+ (not in fstab); `~/ImagerTest` was a bind mount of its `user/` folder, so test images sat in the+ home folder as the imager requires. It also served as the internal, non-removable disk the+ imager must refuse.+- **A virtual USB stick:** `modprobe dummy_hcd` and `modprobe g_mass_storage+ file=/var/tmp/imager-scratch/usb-stick-116.img removable=1` (4 GB, then 16 GB, sparse): `sdc`,+ `TRAN usb`, `RM 1`. Every write was preceded by `~/ImagerTest/vguard.sh sdc`, which prints the+ device and stops unless it is that gadget with the backing file's size. No other disk was written.+- **Images:** the signed 0.8.1 release folder copied from the development machine, and 0.8.3+ downloaded from GitHub by `imager-fetch` into `~/.cache/lordos/imager`.+- **Session:** `/etc/lordos/session.conf` with `AUTOLOGIN=lord` (it didn't exist) and lord's+ `settings.json` set to English, both put back at the end; the locked `pwtest` session from an earlier+ test was ended by the service restarts.+- **The Linux download (Tauri) inside the LordOS session:** installed for the test only+ `libwebkit2gtk-4.1-0` and `udisks2` with their dependencies (61 packages, listed in+ `~/ImagerTest/linux-test-packages.txt`), and `/etc/polkit-1/rules.d/49-lordos-imager-test.rules`+ allowing `lord` the udisks2 open/mount/eject actions (the LordOS session has no polkit agent to+ ask); the app ran as a Wayland client with `WAYLAND_DISPLAY=wayland-0`. All of it was removed at+ the end (`apt-get purge` of those packages, then the rule).+- **Screenshots** with `qm monitor 116` (`screendump`) from the Proxmox host, the pointer with+ `/root/lord-qmp-input.py 116` and keys with `/root/lord-type.py 116`.+- **Undone at the end:** `/usr/local/lib/lordos` restored from the backup, `session.conf` removed and+ lord's `settings.json` restored, `lordos.service` restarted to the login screen; the gadget+ unloaded (`rmmod g_mass_storage dummy_hcd`), the bind mount and the scratch mount removed, and the+ scratch disk detached and deleted from the VM (`qm set 116 --delete scsi1`, then the unused volume+ removed); `~/ImagerTest`, `~/.cache/lordos/imager`, `~/.config/LordOS Imager` and the test key and+ image files deleted. `~/LordOS-imager` (the tree) is kept, like the other agents' trees. No network+ or Proxmox setting other than the scratch disk was touched.++## Step 43 — 0.8.4: the remote desktop WebRTC only (VM 122 `lordos-sandbox`, October 19)++See `REMOTE.md`, "Video (WebRTC)", "ICE over TCP", "Reconnecting" and "When it can't connect". On+VM 122 (172.17.0.56), tree in `~/LordOS-rtc2` (copied from the Mac's `v084-rtc-only` worktree with+`tar` over SSH: the VM has no `rsync`), built there (`make -C server`, `make -C server test`) and+installed over the package's files by `~/deploy-rtc2-122.sh`, which needed the backup of+`/usr/lib/lordos`, `/etc/lordos`, `/var/lib/lordos/remote`, `/var/lib/lordos/last-user`, the+`iptables-save` output and the package selections in `/var/backups/lordos-rtc2-20261019` first+(`~/restore-rtc2-122.sh` put them back). The theme bundles were built on the Mac (the VM has no Node).+For the before/after measurements, `main`'s `server/` was built in `~/LordOS-rtc2-base` and its three+binaries installed for one round, then this branch's again.++- **Installed for the build:** `libsrtp2-dev` and `libusrsctp-dev` (with `libsrtp2-1`, `libusrsctp2`,+ `libnss3-dev`, `libnspr4-dev`); purged at the end.+- **Installed for the TURN tests:** `coturn` (`--no-install-recommends`, with `inetutils-telnet`,+ `telnet`, `libevent-extra-2.1-7t64`, `libevent-openssl-2.1-7t64`, `libevent-pthreads-2.1-7t64`,+ `libhiredis1.1.0`, `libmariadb3`, `libpq5`, `mariadb-common`, `mysql-common`, `sqlite3`); its unit+ was disabled and stopped right after installing, and `turnserver` ran by hand on 172.17.0.56 (3478+ UDP/TCP, 5349 TLS with a throwaway self-signed P-256 certificate, relay ports 49160–49200) with a+ test-only user from `/tmp/turn-rtc2/turn.conf`. Purged at the end; `/tmp/turn-rtc2` removed.+- **Firewall rules for the tests only:** `iptables` (the nftables backend, already installed) on the+ VM's INPUT chain, only for the Mac's address (172.17.0.5): drop UDP; drop TCP 5673; drop new TCP+ connections to 5673 beyond the first (`connlimit`, so the WebSocket stays and ICE-TCP can't); drop+ UDP except the relay ports. Each rule was deleted right after its test; eth0 and the VM's network+ configuration were never touched. The rules left an empty `ip filter` table behind, removed with+ `nft delete table ip filter` (`nftables` installed for that one command and purged), so+ `iptables-save` is empty again, as before.+- **Test-only accounts** `rtest` and `rtest2` (one password, only for these tests); `rtest` was put+ in `sudo` for Settings → Sharing → Connection (the `remote-ice` action through the UI) and its+ screenshots. Both deleted with their homes at the end (their `/run/lordos/spawn-<uid>.lock` too).+- **Browsers:** headless Chrome on the Mac with throwaway profiles in the scratchpad, driven over the+ DevTools protocol; the ICE and ICE-TCP probes (`/tmp/iceprobe-rtc2.py`) ran from the VM itself as a+ second address; CPU and traffic from `/proc` and `eth0` (`/tmp/cpu-rtc2.py`). The fuzzer's 1,000,000+ input run: `./build/remote-fuzz 1000000 7` (2 min 29 s).+- **Configuration changed during the tests** (all restored from the backup): `config` (`turn*` lines+ written by hand and by Settings, `net=list` for one test, `net=lan` written by Settings), `access`+ (one test `allow` line), `turn.key`. One `systemctl kill -s HUP lordos` signalled the whole unit+ instead of only `lord-sessiond`, so `lord-netd` restarted once ("the network was not interrupted");+ use `systemctl reload lordos` (`ExecReload` sends SIGHUP to the main process only).+- **Undone at the end:** `/usr/lib/lordos`, `/etc/lordos`, `/var/lib/lordos/remote` and `last-user`+ restored (`diff -r` empty), the packages above purged (`dpkg --get-selections` identical to before),+ `iptables-save` as before, the test accounts, both trees, the scripts, the `/tmp` files and the+ backup removed, `lordos.service` restarted on the package's binaries, at the login screen.+ VMs 115, 106 and 123 were not used.++## Step 44 — 0.8.4 release test (VMs 116, 117, 120 and the Raspberry Pi, October 19–25)++See `ISO.md`, "Release test (0.8.4 Beta, October 19–25)".++- **VM 116:** installed `libsrtp2-dev` and `libusrsctp-dev` (with `libsrtp2-1`, `libusrsctp2`,+ `libnss3-dev`, `libnspr4-dev`), which `lord-sessiond` now needs; they stay, for the next release+ builds. The release tree in `~/LordOS-iso`, built there; ISO and `.deb` in+ `/var/tmp/lordos-iso/out/` (the 0.8.2 and 0.8.3 ISOs there were removed to make room: identical+ copies are in Proxmox's `local:iso`), `apt-get clean` run. Left stopped, as it was found on the+ 25th.+- **Proxmox:** `local:iso/lordos-live-0.8.4-amd64.iso` added. A temporary typing helper in the+ host's `/root` was removed afterwards.+- **VMs 117 and 120:** a Proxmox snapshot `r084pre` first; then 120 got a fresh 0.8.3 install from+ the 0.8.3 ISO (test user `rtester`, `openssh-server`, a sudoers drop-in, `lordos.sources` on+ `apt-staging`, xterm, a Chromium profile opened once) and a snapshot `r084base`, and was upgraded+ three times (Store with the first build; apt and Store again with the final build, back at+ `r084base` each time; for the tests also `smartmontools` and `iptables`); 117 installed the 0.8.4+ ISO. Both were rolled back to `r084pre` (ISO, boot order and disks as before: the earlier "Test+ User" installs, at the login screen), the snapshots deleted, and both left stopped.+- **Raspberry Pi 5 (172.17.0.24):** installed `libsrtp2-dev` and `libusrsctp-dev` (with `libsrtp2-1`,+ `libusrsctp2`, `libnss3-dev`, `libnspr4-dev`) for the native build. Removed the old image work+ folders `/var/tmp/lordos-rpi-v081` (an unpublished 0.8.1 build) and `-v082b` (its image is the+ published 0.8.2 one, same SHA-256) to make room. Built the arm64 package and the image in+ `/var/tmp/lordos-src-084` and `/var/tmp/lordos-rpi-v084c`. The installed LordOS went from 0.8.3 to+ 0.8.4 with apt (from staging, then the source put back on the live repository), migration 005;+ `lordos`, `lord-netperm` and `lord-fand` restarted, no reboot. The firewall cut test ran as root+ with a hand-made `lordos-session-0` cgroup (removed afterwards, with the empty+ `/root/.config/lordos` it created); the first-run check used a loop device on a decompressed copy+ of the image in `/var/tmp/r084-fr` (removed). Network, the `lordbasex` account and the SD+ partitions untouched; the board was not reflashed.++## Step 45 — 0.8.4.1 release test (VMs 116 and 120 and the Raspberry Pi, October 25)++See `ISO.md`, "Release test (0.8.4.1 Beta, October 25)".++- **VM 116:** started (it was stopped); the release tree in `~/LordOS-0841`, built and tested there;+ the `.deb` and its SBOM in `/var/tmp/`. Nothing installed. Left stopped.+- **VM 120:** a Proxmox snapshot `r0841pre` first; then a fresh 0.8.4 install from the 0.8.4 ISO+ (test user `rtester`, `openssh-server`, a sudoers drop-in, `lordos.sources` on `apt-staging`) and+ a snapshot `r0841base`; upgraded with the Store, then again with apt from `r0841base`. Rolled back+ to `r0841pre` (the earlier "Test User" install, at the login screen; ISO and boot order as+ before), both snapshots deleted, left stopped.+- **Raspberry Pi 5 (172.17.0.24, the user's TEST SD with the 0.8.4 image):** clock set by hand+ (the image had no time client), `debootstrap`, `xz-utils`, `curl`, `gpg`, `dosfstools`, `fdisk`,+ `dpkg-dev`, `python3`, `dpkg-repack` and `file` installed for the native image build; the+ installed LordOS kernels repacked with `dpkg-repack` into `/var/tmp/lordos-kernel/out` (`dpkg+ --verify` clean first: the same files as the 0.8.4 image's). Tree in `/var/tmp/lordos-src-0841`,+ image work folder `/var/tmp/lordos-rpi-v0841`. `lordos` 0.8.4 → 0.8.4.1 from staging (then the+ source put back on the live repository). For the Settings test: a test-only account `rtest`+ (sudo group) and the remote desktop turned on; both removed afterwards. Bootloader updated once+ through Settings → Board firmware (2026/05/26 → 2026/09/25). Chromium and Firefox ESR installed+ from Debian with the image's browser defaults, to check them (left installed). Network and+ partitions untouched; the board was not reflashed.++++## Step 46 — Monitor → Network, second generation, for 0.8.5 (VM 118 `lordos-notes`, October 19)++ See `MONITOR.md` ("Network, second generation", "The menu bar network item", "Blocklists") and+ `FIREWALL.md` ("LordOS components in their own scopes", "The essential system services",+ "Blocklists"). On VM 118 (172.17.0.53), tree in `~/LordOS-netmon` (copied over SSH with `tar`: the+ VM has no rsync), built there (`make -C server`, `make -C server test`, `sudo build/npverify-test`)+ and installed over `/usr/local/lib/lordos` (`lord-server`, `lord-netperm`, the new `lord-fetch`,+ themes and assets) by `~/deploy-netmon-118.sh`, which first saved `/usr/local/lib/lordos` in+ `/var/backups/lordos-netmon-bak` and `~/.config/lordos` in `~/.config-lordos-backup-netmon`.+ `lord-sessiond` was not replaced (lord-netd isn't installed on this VM, so the network service row+ was not tested here). Nothing was installed with apt.++ - **Unit drop-in:** `/etc/systemd/system/lord-netperm.service.d/netmon084.conf` with+ `RestrictAddressFamilies=AF_UNIX AF_PACKET AF_NETLINK` (this VM's unit predates 0.8.3's sock_diag);+ removed at the end.+ - **Session:** the autologin session of `lord` (`/run/lordos/autologin-done` removed, the session's+ lord-server ended, `lordos` restarted), English, dark and then light for the screenshots, the menu+ bar item on (all in `settings.json`, restored at the end).+ - **Test traffic:** `curl` started from SSH inside `lordos-net-terminal.scope` (as a Terminal program)+ and, for the A/B measurements, inside `app-lordos-npbench.scope`: HTTPS requests to public sites+ every 4 s, two rate-limited downloads from Debian mirrors, and attempts to a listed scam domain+ (denied by the list; while the lists were off for the A/B runs, a few requests to it went through).+ `nc -z` to a listed domain checked that the owner's allow rule wins. The Store's "Check for+ updates" for the Store's own row.+ - **Blocklists:** four catalog lists and one custom list downloaded over HTTPS from their sources;+ copies in `~/.cache/lordos/fwlists`, removed at the end with `fwlists.json` and `fwlists.txt`.+ - **Measurements:** `iperf3` (already on this VM since step 28) through a veth pair `npb0`/`npb1`+ into a private namespace `npb` (10.213.7.0/30), deleted after each run; eth0 and the network+ configuration were not touched. For the A/B runs the 0.8.3 `lord-netperm` and main's build+ (built in `~/LordOS-netmon-base`) were swapped in for a few minutes and the new build put back.+ - **Input and screenshots:** `lord-qmp-input.py 118 2987 1067` and `lord-type.py 118` from the+ Proxmox host, `screendump` converted to PNG on the development machine.+ - **Undone at the end:** `/usr/local/lib/lordos` restored from the backup (`diff -r` empty), the+ drop-in removed and `lord-netperm` restarted with the old binary, `~/.config/lordos` restored+ (`diff -r` against the backup empty), the blocklist files and the test scopes removed, the trees,+ scripts and backups deleted, `lordos` restarted to the login screen. The traffic history+ (`~/.local/state/lordos/net-history.bin`) keeps the test minutes (app ids and byte counts only).+ No Proxmox setting was touched.diff --cc sdk/fwrule.jsindex 6c833bb,6c669bc..8d9415d--- a/sdk/fwrule.js+++ b/sdk/fwrule.js@@@ -272,7 -272,18 +272,18 @@@ function destMatches(r, names, a, lan)}}- export function decide(rules, { names = [], addr = '', proto = 'tcp', port = 0, dir = 'out' } = {}, restricted = []) {-// (0.8.4) opts: { listed } — a subscribed blocklist covers the destination: it denies unless the++// (0.8.5) opts: { listed } — a subscribed blocklist covers the destination: it denies unless the+ // winning rule names the destination (a domain, an address or a network), as rules.c's FwQuery.listed;+ // { mode } — 'deny' ("deny silently"): what no rule allows is denied, loopback excepted. Without a+ // deciding rule, list or deny mode the result stays null (the app's default: allowed).+ const isLoopback = (a) => {+ if (!a) return false;+ const b = Array.from(a.b);+ if (a.fam === 4) return b[0] === 127;+ if (b.slice(0, 10).every((x) => x === 0) && b[10] === 255 && b[11] === 255) return b[12] === 127; /* ::ffff:127.x.y.z */+ return b.slice(0, 15).every((x) => x === 0) && b[15] === 1;+ };+ export function decide(rules, { names = [], addr = '', proto = 'tcp', port = 0, dir = 'out' } = {}, restricted = [], opts = {}) {const a = addrBytes(addr);const lan = a ? isLan(addr) : false;const has = (f) => restricted.includes(f);diff --cc sdk/index.jsindex 2d7567b,ce4b370..a91ae63--- a/sdk/index.js+++ b/sdk/index.js@@@ -38,8 -38,7 +38,9 @@@ import { EmojiPanel } from './emoji.jsxexport { admin } from './admin.js';export { videoPrefs, setVideoPrefs, videoHardware, videoError, videoOptimizing, VIDEO_MODES, VIDEO_DEFAULTS } from './video.js'; // docs/VIDEO.mdimport { startVideo } from './video.js';+export { browserFrameResult, browserFrameState, browserTabsInTitlebar, setBrowserTabsInTitlebar } from './browserframe.js'; // docs/WAYLAND.md+import { startBrowserFrame } from './browserframe.js';+ import { startNetStatus } from './netstatus.jsx';export { errorText, statusText, codeError, parseCode } from './errors.js';export { logs } from './logs.js';export { LordOSLogo, LordOSGlyph, LordOSWordmark } from './logo.js';@@@ -54,6 -53,7 +55,7 @@@ exportexport { sound, useSound, useSoundPeak, soundState, defaultSink, defaultSource, microphones } from './sound.js';export { monitor, useMonitor, monitorSamples, monitorProcesses, monitorConnections, monitorDevices, monitorDetail, MONITOR_HISTORY, diskTempHistory, DISK_TEMP_HISTORY, firewall, firewallState } from './monitor.js';export * as fwRule from './fwrule.js'; // checks what the user types for a firewall rule-export * as netModel from './netmodel.js'; // (0.8.4) Monitor → Network: search tokens, filters, the tree++export * as netModel from './netmodel.js'; // (0.8.5) Monitor → Network: search tokens, filters, the treeexport { packages, packageList, refreshPackages, packageFile, loadWasm } from './packages.js';import { refreshPackages } from './packages.js';export {@@@ -195,7 -195,7 +197,8 @@@ export function startShell(element)startHardware(); // Night Light, idle timers, battery in the menu bar (hardware.jsx)startDiskWatch(); // notices when a disk gets too hot or its health gets worsestartVideo(); // browser video without hardware decoding (video.js, docs/VIDEO.md)- startNetStatus(); // (0.8.4) the menu bar's network item and the blocklists' daily update+ startBrowserFrame(); // "Browsers: tabs in the title bar" left for Chromium to quit (browserframe.js)++ startNetStatus(); // (0.8.5) the menu bar's network item and the blocklists' daily updatesetTimeout(reportRefusedCode, 800); // "This LordOS component was modified and was not loaded" (docs/SIGNING.md)}diff --cc sdk/monitor.jsindex 32fd372,3a2552c..f1ed7b5--- a/sdk/monitor.js+++ b/sdk/monitor.js@@@ -163,8 -164,12 +164,12 @@@ function fwPoll(force)}const fwBump = (r) => { firewallState.set((s) => ({ ...s, rev: s.rev + 1 })); fwPoll(true); return r; };const fwCall = (fn, dflt) => { try { const api = fwApi(); return api ? fn(api) : dflt; } catch (e) { return dflt; } };- // A rule can only be applied to an app with its own scope: LordOS, a .desktop app or an .lpk.- const fwEnforceable = (app) => app === 'lordos' || /^(desktop|lpk):/.test(app || '');-// A rule can only be applied to an app with its own scope: LordOS, a .desktop app, an .lpk or (0.8.4)++// A rule can only be applied to an app with its own scope: LordOS, a .desktop app, an .lpk or (0.8.5)+ // one of LordOS's own components with its own scope (lordos:mail, lordos:store, lordos:print,+ // lordos:terminal, lordos:lists). The essential system services (system:dns, system:time,+ // system:network) are shown but never take a rule.+ const fwEnforceable = (app) => app === 'lordos' || /^(desktop|lpk|lordos):/.test(app || '');+ const fwCallThrow = (fn) => { const api = fwApi(); if (!api) throw codeError('fw.list.unavailable'); return fn(api); };export const firewall = {available: () => !!fwApi(),enforceable: fwEnforceable,@@@ -181,6 -186,14 +186,14 @@@removeRule: (id) => fwBump(fwCall((f) => f.removeRule(id), false)),updateRule: (id, r) => fwBump(fwCall((f) => f.updateRule(id, r), false)),ruleApps: () => fwCall((f) => (f.ruleApps ? f.ruleApps() : []), []),- // (0.8.4) subscribed blocklists (docs/FIREWALL.md, "Blocklists"): lists() → { lists: [{ id, url, format,++ // (0.8.5) subscribed blocklists (docs/FIREWALL.md, "Blocklists"): lists() → { lists: [{ id, url, format,+ // custom, on, updated, tried, domains, nets, truncated, error }], busy, domains, nets } | null+ lists: () => fwCall((f) => (f.lists ? f.lists() : null), null),+ setList: (id, on) => fwBump(fwCallThrow((f) => f.setList(id, !!on))),+ addList: (url, format) => fwBump(fwCallThrow((f) => f.addList(url, format))),+ removeList: (id) => fwBump(fwCallThrow((f) => f.removeList(id))),+ updateLists: (force) => fwCall((f) => (f.updateLists ? f.updateLists(!!force) : 1), 1),+ listMatch: (names, addr) => fwCall((f) => (f.listMatch ? f.listMatch(names || [], addr || '') : null), null),// the app whose rules Settings → Privacy shows open (the Monitor's "Rules for this app")focus: createStore(null),refresh: () => fwPoll(true),diff --cc sdk/netmodel.jsindex 0000000,1487d3e..ecc64f9mode 000000,100644..100644--- a/sdk/netmodel.js+++ b/sdk/netmodel.js@@@ -1,0 -1,294 +1,294 @@@-// netmodel.js — Monitor → Network's list, second generation (0.8.4, docs/MONITOR.md): search tokens,++// netmodel.js — Monitor → Network's list, second generation (0.8.5, docs/MONITOR.md): search tokens,+ // filters, grouping into a tree and sorting. Pure functions, no lord.* (tests/netmodel_test.mjs).+ //+ // The input is a flat list of flows, one per (app, destination, port):+ // { app, appName, name, addr, port, proto: 'tcp'|'udp'|'other', dir: 'out'|'in', rx, tx, rateRx, rateTx,+ // cc, scope, conns, denied, last, listed, system }+ // name: the name the system resolver gave for addr (or null), names: all of them (a CNAME chain);+ // last: ms of the last activity;+ // listed: the id of a subscribed blocklist that covers it (or null); system: an essential system+ // service (name resolution, time, the network service), shown but never blockable.+ //+ // const q = parseSearch('app:firefox port:443 video'); // { chips: [{type:'app',value:'firefox'},…], rest: 'video' }+ // const shown = filterFlows(flows, { dir: 'all', proto: 'all', status: 'all' }, q, { hasRule });+ // const tree = sortTree(groupFlows(shown, 'app'), 'most');+ // // [{ key, kind: 'app'|'domain'|'ip'|'port'|'country', label, rx, tx, rateRx, rateTx, conns, denied,+ // // last, flows, children: [...] }]+-// LordOS's own parts that use the network, each a row of its own (0.8.4): label key, the built-in app++// LordOS's own parts that use the network, each a row of its own (0.8.5): label key, the built-in app+ // whose icon it shows (or a glyph), whether the firewall can block it, and what blocking it means.+ // lordos:<name> in its own scope (sec/netconn.h): the kernel enforces its rules+ // system:<name> an essential system service: shown, never blocked+ // lordos:vpn the VPN tunnels (their interfaces' counters): shown, managed in Settings → Network+ export const COMPONENTS = {+ 'lordos:mail': { label: 'monitor.comp.mail', icon: 'mail', hint: 'monitor.comp.mailHint' },+ 'lordos:store': { label: 'monitor.comp.store', icon: 'store', hint: 'monitor.comp.storeHint', warn: 'monitor.comp.storeWarn' },+ 'lordos:print': { label: 'monitor.comp.print', glyph: 'printer', hint: 'monitor.comp.printHint' },+ 'lordos:terminal': { label: 'monitor.comp.terminal', icon: 'terminal', hint: 'monitor.comp.terminalHint' },+ 'lordos:lists': { label: 'monitor.comp.lists', glyph: 'shield', hint: 'monitor.comp.listsHint' },+ 'lordos:vpn': { label: 'monitor.comp.vpn', glyph: 'tunnel', hint: 'monitor.comp.vpnHint', system: true },+ 'system:dns': { label: 'monitor.comp.dns', glyph: 'dns', hint: 'monitor.comp.dnsHint', system: true },+ 'system:time': { label: 'monitor.comp.time', glyph: 'clock', hint: 'monitor.comp.timeHint', system: true },+ 'system:network': { label: 'monitor.comp.network', glyph: 'network', hint: 'monitor.comp.networkHint', system: true },+ };+ export const isSystemId = (id) => !!COMPONENTS[id]?.system || /^system:/.test(id || '');++ export const CHIP_TYPES = ['app', 'domain', 'ip', 'port', 'proto', 'country'];+ const ALIASES = { host: 'domain', name: 'domain', addr: 'ip', address: 'ip', cidr: 'ip', protocol: 'proto', cc: 'country' };+ export const GROUPS = ['app', 'domain', 'ip', 'port', 'country'];+ export const SORTS = ['name', 'most', 'least', 'recent', 'conns'];++ // ---- addresses ----++ function v4(s) {+ const p = s.split('.');+ if (p.length !== 4) return null;+ const b = p.map((x) => (/^\d{1,3}$/.test(x) ? Number(x) : -1));+ return b.every((x) => x >= 0 && x <= 255) ? b : null;+ }++ function v6(s) {+ if (!/^[0-9a-fA-F:.]+$/.test(s) || !s.includes(':')) return null;+ let tail = [];+ let t = s;+ const m = /^(.*:)(\d+\.\d+\.\d+\.\d+)$/.exec(s);+ if (m) { const b = v4(m[2]); if (!b) return null; tail = b; t = m[1].endsWith('::') ? m[1] : m[1].slice(0, -1); }+ const halves = t.split('::');+ if (halves.length > 2) return null;+ const words = (x) => (x ? x.split(':') : []);+ const a = words(halves[0]), c = halves.length === 2 ? words(halves[1]) : [];+ const need = 8 - tail.length / 2;+ if (halves.length === 1 && a.length !== need) return null;+ if (a.length + c.length > need) return null;+ const all = [...a, ...Array(halves.length === 2 ? need - a.length - c.length : 0).fill('0'), ...c];+ const out = [];+ for (const w of all) {+ if (!/^[0-9a-fA-F]{1,4}$/.test(w)) return null;+ const n = parseInt(w, 16);+ out.push(n >> 8, n & 255);+ }+ return [...out, ...tail];+ }++ // "192.0.2.7", "10.0.0.0/8", "2001:db8::/32" → { bytes, prefix } | null+ export function parseCidr(s) {+ if (typeof s !== 'string' || !s) return null;+ const [ip, pre, extra] = s.split('/');+ if (extra !== undefined) return null;+ const b = v4(ip) || v6(ip);+ if (!b) return null;+ const max = b.length * 8;+ const prefix = pre === undefined ? max : /^\d{1,3}$/.test(pre) ? Number(pre) : -1;+ if (prefix < 0 || prefix > max) return null;+ return { bytes: b, prefix };+ }++ // is addr (text) inside cidr ({ bytes, prefix })? IPv4-mapped IPv6 addresses count as IPv4.+ export function cidrContains(c, addr) {+ let b = v4(addr) || v6(addr);+ if (!b || !c) return false;+ if (b.length === 16 && c.bytes.length === 4 && b.slice(0, 10).every((x) => x === 0) && b[10] === 255 && b[11] === 255) b = b.slice(12);+ if (b.length !== c.bytes.length) return false;+ for (let i = 0; i < c.prefix; i++) {+ const bit = (x) => (x[i >> 3] >> (7 - (i & 7))) & 1;+ if (bit(b) !== bit(c.bytes)) return false;+ }+ return true;+ }++ // ---- search ----++ // What a token typed without a "type:" means: an address or network, a port, a protocol, a+ // two-letter country code (upper case), a name with a dot (a domain) or else an app.+ export function chipFor(token) {+ const s = String(token || '').trim();+ if (!s) return null;+ const m = /^([a-z]+):(.+)$/i.exec(s);+ if (m && !parseCidr(s)) {+ const type = ALIASES[m[1].toLowerCase()] || m[1].toLowerCase();+ if (!CHIP_TYPES.includes(type)) return null;+ return normChip({ type, value: m[2] });+ }+ if (parseCidr(s)) return normChip({ type: 'ip', value: s });+ if (/^\d{1,5}$/.test(s) && Number(s) >= 1 && Number(s) <= 65535) return { type: 'port', value: String(Number(s)) };+ if (/^(tcp|udp|quic)$/i.test(s)) return normChip({ type: 'proto', value: s });+ if (/^[A-Z]{2}$/.test(s)) return { type: 'country', value: s };+ if (s.includes('.')) return normChip({ type: 'domain', value: s });+ return { type: 'app', value: s };+ }++ function normChip(c) {+ const v = String(c.value).trim();+ if (!v) return null;+ switch (c.type) {+ case 'ip': return parseCidr(v) ? { type: 'ip', value: v.toLowerCase() } : null;+ case 'port': return /^\d{1,5}$/.test(v) && Number(v) >= 1 && Number(v) <= 65535 ? { type: 'port', value: String(Number(v)) } : null;+ case 'proto': { const p = v.toLowerCase() === 'quic' ? 'udp' : v.toLowerCase(); return p === 'tcp' || p === 'udp' ? { type: 'proto', value: p } : null; }+ case 'country': return /^[A-Za-z]{2}$/.test(v) ? { type: 'country', value: v.toUpperCase() } : { type: 'country', value: v };+ case 'domain': return { type: 'domain', value: v.toLowerCase().replace(/^\*\./, '').replace(/\.$/, '') };+ default: return { type: c.type, value: v };+ }+ }++ // The text of the search field: every "type:value" token becomes a chip, the rest is free text+ // (also turned into chips when commit is true: the user pressed Enter).+ export function parseSearch(text, commit = false) {+ const chips = [];+ const rest = [];+ for (const tok of String(text || '').split(/\s+/).filter(Boolean)) {+ const typed = /^([a-z]+):(.+)$/i.test(tok) && !parseCidr(tok);+ const c = typed || commit ? chipFor(tok) : null;+ if (c) chips.push(c); else rest.push(tok);+ }+ return { chips, rest: rest.join(' ') };+ }++ // Adds chips without repeating one.+ export function addChips(list, more) {+ const out = [...(list || [])];+ for (const c of more || []) if (c && !out.some((x) => x.type === c.type && x.value === c.value)) out.push(c);+ return out;+ }++ const lc = (s) => String(s || '').toLowerCase();++ function chipMatches(f, c, countryName) {+ switch (c.type) {+ case 'app': return lc(f.appName).includes(lc(c.value)) || lc(f.app).includes(lc(c.value));+ case 'domain': {+ const v = lc(c.value);+ return (f.names && f.names.length ? f.names : [f.name]).some((x) => { const n = lc(x); return !!n && (n === v || n.endsWith(`.${v}`) || (!v.includes('.') && n.includes(v))); });+ }+ case 'ip': { const x = parseCidr(c.value); return !!f.addr && (x ? cidrContains(x, f.addr) : lc(f.addr).startsWith(lc(c.value))); }+ case 'port': return Number(f.port) === Number(c.value);+ case 'proto': return f.proto === c.value;+ case 'country': return c.value.length === 2 ? f.cc === c.value : lc(countryName?.(f.cc)).includes(lc(c.value));+ default: return true;+ }+ }++ // Every chip type must match (two chips of the same type: either one); the free text anywhere.+ export function matchesSearch(f, { chips = [], rest = '' } = {}, countryName) {+ const byType = new Map();+ for (const c of chips) byType.set(c.type, [...(byType.get(c.type) || []), c]);+ for (const list of byType.values()) if (!list.some((c) => chipMatches(f, c, countryName))) return false;+ if (rest) {+ const hay = lc([f.appName, f.app, f.name, ...(f.names || []), f.addr, f.port, f.proto, f.cc, countryName?.(f.cc)].join(' '));+ for (const w of lc(rest).split(/\s+/)) if (w && !hay.includes(w)) return false;+ }+ return true;+ }++ // filters: { dir: 'all'|'in'|'out', proto: 'all'|'tcp'|'udp', status: 'all'|'allowed'|'denied'|'rules' }+ // ctx: { hasRule(flow) → bool, countryName(cc) → text }+ export function filterFlows(flows, filters = {}, search = {}, ctx = {}) {+ const { dir = 'all', proto = 'all', status = 'all' } = filters;+ return (flows || []).filter((f) => {+ if (dir !== 'all' && f.dir !== dir) return false;+ if (proto !== 'all' && f.proto !== proto) return false;+ if (status === 'allowed' && (f.denied || f.blocked)) return false;+ if (status === 'denied' && !(f.denied || f.blocked)) return false;+ if (status === 'rules' && !(ctx.hasRule && ctx.hasRule(f))) return false;+ return matchesSearch(f, search, ctx.countryName);+ });+ }++ // ---- the tree ----++ const portLabel = (f) => (f.port ? `${f.proto === 'other' ? '' : f.proto.toUpperCase()} ${f.port}`.trim() : f.proto.toUpperCase());+ const LEVELS = {+ app: ['app', 'dest', 'ip', 'port'],+ domain: ['dest', 'app', 'port'],+ ip: ['ip', 'app', 'port'],+ port: ['port', 'app', 'dest'],+ country: ['country', 'app', 'dest'],+ };++ function keyOf(f, level) {+ if (!f.addr && (level === 'dest' || level === 'ip' || level === 'country' || (level === 'port' && !f.port))) return null; /* an app with no destination yet */+ switch (level) {+ case 'app': return { key: `a:${f.app}`, kind: 'app', label: f.appName || f.app, app: f.app };+ case 'dest': return f.name ? { key: `d:${f.name}`, kind: 'domain', label: f.name, name: f.name } : { key: `i:${f.addr}`, kind: 'ip', label: f.addr, addr: f.addr };+ case 'ip': return { key: `i:${f.addr}`, kind: 'ip', label: f.addr, addr: f.addr };+ case 'port': return { key: `p:${f.proto}/${f.port}/${f.dir}`, kind: 'port', label: portLabel(f), port: f.port, proto: f.proto, dir: f.dir };+ case 'country': return { key: `c:${f.cc || f.scope || '?'}`, kind: 'country', label: f.cc || f.scope || '?', cc: f.cc || '', scope: f.scope || '' };+ default: return null;+ }+ }++ function node(k) {+ return { ...k, rx: 0, tx: 0, rateRx: 0, rateTx: 0, conns: 0, denied: 0, blocked: 0, last: 0, listed: null, system: false, flows: [], children: [] };+ }++ function add(n, f) {+ n.rx += f.rx || 0;+ n.tx += f.tx || 0;+ n.rateRx += f.rateRx || 0;+ n.rateTx += f.rateTx || 0;+ n.conns += f.conns || 0;+ n.denied += f.denied || 0;+ n.blocked += f.blocked || 0;+ if ((f.last || 0) > n.last) n.last = f.last;+ if (f.listed && !n.listed) n.listed = f.listed;+ if (f.system) n.system = true;+ n.flows.push(f);+ }++ function build(flows, levels) {+ const [level, ...rest] = levels;+ if (!level) return [];+ const map = new Map();+ for (const f of flows) {+ const k = keyOf(f, level);+ if (!k) continue;+ const n = map.get(k.key) || map.set(k.key, node(k)).get(k.key);+ add(n, f);+ }+ const out = [...map.values()];+ for (const n of out) {+ let next = rest;+ // an address level only under a domain row, and only when that name has several addresses+ if (next[0] === 'ip' && (n.kind !== 'domain' || new Set(n.flows.map((f) => f.addr)).size < 2)) next = next.slice(1);+ n.children = build(n.flows, next);+ }+ return out;+ }++ export function groupFlows(flows, group = 'app') {+ return build(flows || [], LEVELS[group] || LEVELS.app);+ }++ const total = (n) => (n.rx || 0) + (n.tx || 0);+ const cmp = {+ name: (a, b) => String(a.label).localeCompare(String(b.label)),+ most: (a, b) => total(b) - total(a) || b.conns - a.conns || String(a.label).localeCompare(String(b.label)),+ least: (a, b) => total(a) - total(b) || a.conns - b.conns || String(a.label).localeCompare(String(b.label)),+ recent: (a, b) => (b.last || 0) - (a.last || 0) || total(b) - total(a),+ conns: (a, b) => b.conns - a.conns || total(b) - total(a),+ };++ // Sorts every level (ports always by number under their parent).+ export function sortTree(nodes, sort = 'most') {+ const f = cmp[sort] || cmp.most;+ return [...(nodes || [])].sort((a, b) => (a.kind === 'port' && b.kind === 'port' && sort === 'name' ? Number(a.port) - Number(b.port) : f(a, b)))+ .map((n) => ({ ...n, children: sortTree(n.children, sort) }));+ }++ // The first `shown` children, and how many more ("N more…").+ export function fold(children, shown = 8, all = false) {+ const list = children || [];+ if (all || list.length <= shown) return { list, more: 0 };+ return { list: list.slice(0, shown), more: list.length - shown };+ }++ // The view settings kept per user (settings.monitor.netView), with defaults and only known values.+ export function normView(v) {+ const o = v && typeof v === 'object' ? v : {};+ return {+ group: GROUPS.includes(o.group) ? o.group : 'app',+ dir: ['all', 'in', 'out'].includes(o.dir) ? o.dir : 'all',+ proto: ['all', 'tcp', 'udp'].includes(o.proto) ? o.proto : 'all',+ status: ['all', 'allowed', 'denied', 'rules'].includes(o.status) ? o.status : 'all',+ sort: SORTS.includes(o.sort) ? o.sort : 'most',+ };+ }diff --cc sdk/netstatus.jsxindex 0000000,e4b84aa..d00df9fmode 000000,100644..100644--- a/sdk/netstatus.jsx+++ b/sdk/netstatus.jsx@@@ -1,0 -1,251 +1,251 @@@-// netstatus.jsx — the network item of the menu bar and the blocklists' daily update (0.8.4,++// netstatus.jsx — the network item of the menu bar and the blocklists' daily update (0.8.5,+ // docs/MONITOR.md "The menu bar network item", docs/FIREWALL.md "Blocklists").+ //+ // The item is optional and off by default (settings.monitor.menuItem; Settings → Privacy → Monitor+ // or the Monitor's view menu). While it is shown, once per second: the machine's byte counters+ // (lord.monitor.netTotals(), one small file read) and lord-netperm's notices (firewall.refresh()).+ // Hidden, it costs nothing. Its panel shows the sent/received graph of the last five minutes, the+ // apps moving bytes now, what was denied in the last ten minutes, the firewall mode, the+ // blocklists and a link to the Monitor.+ //+ // startNetStatus() (startShell) also asks lord-server, once an hour, to download the enabled+ // blocklists that are a day old (lord.fw.updateLists; lord-server does nothing when they are fresh).+ import { memo, useEffect, useRef, useState } from 'react';+ import { View, Text, addListener } from '@lordos/runtime';+ import { createStore, useStore } from './store.js';+ import { settings } from './settings.js';+ import { useTheme, popupBg } from './theme.js';+ import { t, formatNumber } from './i18n.js';+ import { formatBytes } from './system.js';+ import { registerStatusItem } from './statusitems.js';+ import { Overlay } from './layers.js';+ import { Segmented } from './components.jsx';+ import { firewall, firewallState } from './monitor.js';+ import { wm } from './windows.js';+ import { useLauncherApps } from './apps.js';+ import { COMPONENTS } from './netmodel.js';++ const SAMPLES = 300; // one per second: the last five minutes+ // What the bar shows ({ rx, tx } as short text): it changes only when the rounded rates do, so an+ // idle network redraws nothing. The rates and the five minutes behind them stay out of any store;+ // the panel, while open, reads them once per second.+ export const netStatus = createStore({ rx: '0', tx: '0' });+ const live = { rx: 0, tx: 0, hist: [], n: 0 }; // hist: [[rxRate, txRate], …]; n: samples so far+ let timer = null, prev = null, panelOpen = false, ticks = 0;++ const shown = () => settings.get()?.monitor?.menuItem === true;++ function tick() {+ let s = null;+ try { s = typeof lord !== 'undefined' && lord.monitor?.netTotals ? lord.monitor.netTotals() : null; } catch (e) { s = null; }+ if (s && prev) {+ const dt = Math.max(0.2, (s.t - prev.t) / 1000);+ live.rx = Math.max(0, (s.rx - prev.rx) / dt);+ live.tx = Math.max(0, (s.tx - prev.tx) / dt);+ live.hist.push([live.rx, live.tx]);+ live.n++;+ if (live.hist.length > SAMPLES) live.hist.shift();+ // the bar's text every other second (the panel's numbers every second)+ if (++ticks % 2 === 0) {+ const o = netStatus.get(), n = live.hist.slice(-2), rx = short(n.reduce((a, p) => a + p[0], 0) / n.length),+ tx = short(n.reduce((a, p) => a + p[1], 0) / n.length);+ if (o.rx !== rx || o.tx !== tx) netStatus.set({ rx, tx });+ }+ }+ if (s) prev = s;+ if (panelOpen) firewall.refresh(); // lord-netperm's notices only while the panel shows them+ }++ function sync() {+ const on = shown();+ if (on && !timer) { prev = null; tick(); timer = setInterval(tick, 1000); }+ else if (!on && timer) { clearInterval(timer); timer = null; prev = null; live.hist = []; netStatus.set({ rx: '0', tx: '0' }); }+ }++ const rate = (n) => t('monitor.rate', { v: formatBytes(Math.max(0, n || 0)) });++ // a compact rate for the bar: "1.2M", "340K", "0" (under 1 KB/s: background chatter); changing the+ // text relays out the bar, so it changes only when this rounded value does+ function short(n) {+ const v = Math.max(0, n || 0);+ if (v >= 1e9) return `${(v / 1e9).toFixed(1)}G`;+ if (v >= 1e6) return `${(v / 1e6).toFixed(v >= 1e7 ? 0 : 1)}M`;+ if (v >= 1e3) return `${Math.round(v / 1e3)}K`;+ return '0';+ }++ // ---- the panel ----++ // redrawn when a new 5-second bar is complete, not every second (60 bars are 180 nodes)+ const Graph = memo(function Graph({ hist }) {+ const th = useTheme();+ // 60 bars of 5 s each (the newest on the right), sent above the line and received below+ const bars = Array.from({ length: 60 }, (_, i) => {+ const end = hist.length - (59 - i) * 5, part = hist.slice(Math.max(0, end - 5), Math.max(0, end));+ const n = part.length || 1;+ return [part.reduce((a, p) => a + p[0], 0) / n, part.reduce((a, p) => a + p[1], 0) / n];+ });+ const peak = Math.max(1, ...bars.map((b) => Math.max(b[0], b[1])));+ const H = 28;+ return (+ <View style={{ height: H * 2 + 1, flexDirection: 'row', alignItems: 'center', gap: 1, direction: 'ltr' }}>+ {bars.map((b, i) => (+ <View key={i} style={{ flex: 1, height: H * 2 + 1 }}>+ <View style={{ height: H, justifyContent: 'flex-end' }}>+ <View style={{ height: b[1] ? Math.max(1, (b[1] / peak) * H) : 0, backgroundColor: '#f97316', borderRadius: 1 }} />+ </View>+ <View style={{ height: 1, backgroundColor: th.separator }} />+ <View style={{ height: H }}>+ <View style={{ height: b[0] ? Math.max(1, (b[0] / peak) * H) : 0, backgroundColor: '#22c55e', borderRadius: 1 }} />+ </View>+ </View>+ ))}+ </View>+ );+ }, (a, b) => a.bucket === b.bucket);++ function appLabel(id, launcher) {+ if (id === 'lordos') return t('monitor.lordos');+ if (COMPONENTS[id]) return t(COMPONENTS[id].label);+ const a = launcher.find((x) => x.id === id || `lpk:${x.id}` === id || `desktop:${x.id}` === id);+ return a?.name || String(id).replace(/^(desktop|lpk):/, '');+ }++ function Panel({ onClose }) {+ const th = useTheme();+ const [, setTick] = useState(0);+ useEffect(() => {+ panelOpen = true;+ firewall.refresh();+ const id = setInterval(() => setTick((x) => x + 1), 1000);+ return () => { panelOpen = false; clearInterval(id); };+ }, []);+ const st = live;+ const fw = useStore(firewallState);+ const launcher = useLauncherApps();+ const mode = firewall.state().mode || 'silent';+ const lists = firewall.lists();+ const sum = st.hist.reduce((a, p) => [a[0] + p[0], a[1] + p[1]], [0, 0]);+ const active = Object.entries(fw.counts || {}).filter(([, v]) => Array.isArray(v) && (v[4] || v[5]))+ .sort((a, b) => b[1][4] + b[1][5] - (a[1][4] + a[1][5])).slice(0, 5);+ const now = Date.now();+ const denied = (fw.events || []).filter((e) => e.v === 'deny' && e.at && now - e.at < 10 * 60 * 1000);+ const seenDst = new Map(); // the latest of each (app, destination), with how many+ for (const e of denied) {+ const k = `${e.app}|${(e.hosts && e.hosts[0]) || e.addr}`;+ seenDst.set(k, { e, n: (seenDst.get(k)?.n || 0) + 1 });+ }+ const recent = [...seenDst.values()].slice(-3).reverse();+ const label = (k) => <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim, textAlign: 'start' }}>{k}</Text>;+ const row = (k, v, color) => (+ <View style={{ flexDirection: 'row', gap: 8 }}>+ <Text style={{ flex: 1, minWidth: 0, fontSize: 12, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden', textAlign: 'start' }}>{k}</Text>+ <Text style={{ fontSize: 12, color: color || th.textDim, whiteSpace: 'nowrap' }}>{v}</Text>+ </View>+ );+ return (+ <View style={{ width: 320, padding: 14, gap: 10 }}>+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>+ <Text style={{ flex: 1, fontSize: 13, fontWeight: 600, color: th.text, textAlign: 'start' }}>{t('monitor.status.title')}</Text>+ <Text style={{ fontSize: 11, color: '#22c55e' }}>{`↓ ${rate(st.rx)}`}</Text>+ <Text style={{ fontSize: 11, color: '#f97316' }}>{`↑ ${rate(st.tx)}`}</Text>+ </View>+ <Graph hist={st.hist} bucket={Math.floor(st.n / 5)} />+ <Text style={{ fontSize: 10, color: th.textDim, textAlign: 'start' }}>+ {t('monitor.status.lastMinutes', { down: formatBytes(sum[0]), up: formatBytes(sum[1]) })}+ </Text>+ <View style={{ height: 1, backgroundColor: th.separator }} />+ {label(t('monitor.status.activity'))}+ {active.length ? active.map(([id, v]) => row(appLabel(id, launcher), `↓ ${rate(v[4])} · ↑ ${rate(v[5])}`))+ : <Text style={{ fontSize: 12, color: th.textDim, textAlign: 'start' }}>{t('monitor.status.quiet')}</Text>}+ <View style={{ height: 1, backgroundColor: th.separator }} />+ <View style={{ flexDirection: 'row', alignItems: 'center' }}>+ <View style={{ flex: 1 }}>{label(t('monitor.status.denied'))}</View>+ <View style={{ minWidth: 18, height: 16, borderRadius: 8, paddingHorizontal: 5, alignItems: 'center', justifyContent: 'center',+ backgroundColor: denied.length ? 'rgba(255,69,58,0.2)' : th.control }}>+ <Text style={{ fontSize: 10, fontWeight: 700, color: denied.length ? '#ff453a' : th.textDim }}>{formatNumber(denied.length, 0)}</Text>+ </View>+ </View>+ {recent.map(({ e, n }, i) => (+ <View key={i}>{row(`${(e.hosts && e.hosts[0]) || e.addr || '?'}${n > 1 ? ` ×${n}` : ''}`, appLabel(e.app, launcher))}</View>+ ))}+ <View style={{ height: 1, backgroundColor: th.separator }} />+ {label(t('monitor.status.mode'))}+ <Segmented small fill value={mode === 'ask' ? 'silent' : mode} onChange={(m) => firewall.setMode(m)}+ options={[['silent', t('firewall.mode.silent')], ['deny', t('firewall.mode.deny')], ['off', t('firewall.mode.off')]]} />+ <Text style={{ fontSize: 10, color: th.textDim, lineHeight: 1.35, textAlign: 'start' }}>+ {t(mode === 'deny' ? 'firewall.mode.denyHint' : mode === 'off' ? 'firewall.mode.offHint' : 'firewall.mode.silentHint')}+ </Text>+ {lists ? (+ <View onClick={() => { onClose(); wm.open('settings', { args: { section: 'privacy', nonce: Date.now() } }); }}>+ {row(t('monitor.status.lists'), t('monitor.status.listsValue', { lists: formatNumber(lists.lists.filter((l) => l.on).length, 0),+ entries: formatNumber((lists.domains || 0) + (lists.nets || 0), 0) }))}+ </View>+ ) : null}+ <View style={{ height: 1, backgroundColor: th.separator }} />+ <View onClick={() => { onClose(); wm.open('monitor', { args: { tab: 'network', nonce: Date.now() } }); }}>+ <Text style={{ fontSize: 12, color: th.accent, textAlign: 'start' }}>{t('monitor.status.open')}</Text>+ </View>+ </View>+ );+ }++ function NetStatusItem({ color, height }) {+ const th = useTheme();+ const s = useStore(settings);+ const st = useStore(netStatus);+ const [open, setOpen] = useState(false);+ const btn = useRef(null), panel = useRef(null);+ useEffect(() => {+ if (!open) return undefined;+ return addListener('pointerdown', (e) => {+ const inside = (n) => { if (!n) return false; const [x, y, w, hh] = lord.getLayout(n.id); return e.x >= x && e.x <= x + w && e.y >= y && e.y <= y + hh; };+ if (!inside(panel.current) && !inside(btn.current)) setOpen(false);+ });+ }, [open]);+ if (s?.monitor?.menuItem !== true) return null;+ return (+ <View ref={btn} onClick={() => setOpen((o) => !o)} style={{ height, paddingHorizontal: 6, justifyContent: 'center', direction: 'ltr' }}>+ <View style={{ width: 44 }}>+ <Text style={{ fontSize: 9, lineHeight: 1.05, color, fontFamily: 'monospace', textAlign: 'end' }}>{`↑${st.tx}`}</Text>+ <Text style={{ fontSize: 9, lineHeight: 1.05, color, fontFamily: 'monospace', textAlign: 'end' }}>{`↓${st.rx}`}</Text>+ </View>+ {open && (+ <Overlay anchor={btn}>+ <View ref={panel} style={{ position: 'absolute', top: height + 4, right: 0, borderRadius: th.menuRadius || 10, backgroundColor: popupBg(th),+ border: `1px solid ${th.separator}`, boxShadow: '0 10px 30px rgba(0,0,0,0.35)' }}>+ <Panel onClose={() => setOpen(false)} />+ </View>+ </Overlay>+ )}+ </View>+ );+ }++ // ---- start ----++ let started = false;++ function updateLists() {+ if (!firewall.available()) return;+ firewall.updateLists(false);+ // lord-server swaps the new set in and tells lord-netperm when the job ends; reading the state+ // is what lets it notice, so keep reading while it works+ let n = 0;+ const poll = () => {+ const st = firewall.lists();+ if (st?.busy && n++ < 400) setTimeout(poll, 3000);+ };+ setTimeout(poll, 3000);+ }++ export function startNetStatus() {+ if (started) return;+ started = true;+ registerStatusItem('network', NetStatusItem, 3);+ sync();+ settings.subscribe(sync);+ setTimeout(updateLists, 20 * 1000);+ setInterval(updateLists, 60 * 60 * 1000);+ }+diff --cc server/Makefileindex 752130e,ee15ec4..fc55def--- a/server/Makefile+++ b/server/Makefile@@@ -339,6 -313,16 +339,16 @@@ build/fw-rules-test: tests/fw_rules_tes@mkdir -p build$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/fw_rules_test.c src/fw/rules.c src/fw/fwmap.c src/sec/json.c./$@ || { rm -f $@; exit 1; }-# subscribed blocklists (0.8.4): raw parsers, the set, the compiled file, fuzzing (docs/FIREWALL.md, "Blocklists")++# subscribed blocklists (0.8.5): raw parsers, the set, the compiled file, fuzzing (docs/FIREWALL.md, "Blocklists")+ test: build/fwlists-test+ build/fwlists-test: tests/fwlists_test.c src/fw/fwlists.c src/fw/rules.c src/fw/fwmap.c src/sec/json.c $(wildcard src/fw/*.h) src/sec/json.h+ @mkdir -p build+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/fwlists_test.c src/fw/fwlists.c src/fw/rules.c src/fw/fwmap.c src/sec/json.c+ ./$@ || { rm -f $@; exit 1; }+ build/fwlists-test-asan: tests/fwlists_test.c src/fw/fwlists.c src/fw/rules.c src/fw/fwmap.c src/sec/json.c $(wildcard src/fw/*.h)+ @mkdir -p build+ $(CC) $(CPPFLAGS) -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=undefined $(WARN) -std=c11 -o $@ tests/fwlists_test.c src/fw/fwlists.c src/fw/rules.c src/fw/fwmap.c src/sec/json.c+ ./$@# the destinations a user types in the rule sheet (tests/fw_dest_cases.txt), through the store's# parser; tests/fwrule_input_test.mjs checks the same file against sdk/fwrule.js (run_suites.sh)test: build/fwdest-test@@@ -562,9 -536,17 +572,17 @@@ build/arcpath-test: tests/arcpath_test.@mkdir -p build$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/arcpath_test.c src/doc/arcpath.c# IPP encoder/decoder, mDNS and page ranges (tests/ipp_test.c)- build/ipp-test: tests/ipp_test.c src/print/ipp.c src/print/mdns.c src/print/cups.c src/print/phttp.c src/doc/wire.c src/sec/json.c $(wildcard src/print/*.h)-# (0.8.4) the components' network connectors (src/sec/netconn.c) and what they need, for the tests++# (0.8.5) the components' network connectors (src/sec/netconn.c) and what they need, for the tests+ NETCONN_SRC := src/sec/netconn.c src/sec/cgroup.c src/fw/rules.c src/fw/fwmap.c+ # the connectors: requests, sockets, the real connector process and its fail-closed start+ test: build/netconn-test+ build/netconn-test: tests/netconn_test.c $(NETCONN_SRC) src/sec/json.c src/sec/netconn.h src/sec/cgroup.h+ @mkdir -p build+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/netconn_test.c $(NETCONN_SRC) src/sec/json.c -lpthread+ ./$@ || { rm -f $@; exit 1; }+ build/ipp-test: tests/ipp_test.c src/print/ipp.c src/print/mdns.c src/print/cups.c src/print/phttp.c src/doc/wire.c src/sec/json.c $(NETCONN_SRC) $(wildcard src/print/*.h)@mkdir -p build- $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/ipp_test.c src/print/ipp.c src/print/mdns.c src/print/cups.c src/print/phttp.c src/doc/wire.c src/sec/json.c+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/ipp_test.c src/print/ipp.c src/print/mdns.c src/print/cups.c src/print/phttp.c src/doc/wire.c src/sec/json.c $(NETCONN_SRC) -lpthread# lord-doc end to end: malicious archives, PDF and the lockdown (needs build/lord-doc)build/doc-test: tests/doc_test.c src/doc/wire.c src/sec/json.c $(wildcard src/doc/*.h)@mkdir -p builddiff --cc server/mk/fetch.mkindex 0000000,fd6afd3..36dbef7mode 000000,100644..100644--- a/server/mk/fetch.mk+++ b/server/mk/fetch.mk@@@ -1,0 -1,22 +1,22 @@@-# lord-fetch (0.8.4, docs/FIREWALL.md "Blocklists"): the sandboxed helper that downloads the++# lord-fetch (0.8.5, docs/FIREWALL.md "Blocklists"): the sandboxed helper that downloads the+ # subscribed blocklists over HTTPS and parses them. With lord-sessiond and lord-maild, the only+ # binaries that link OpenSSL; built when its headers are there (MAILNET, mk/mail.mk).+ FETCH_SRC := src/fetch/fetch.c src/fw/fwlists.c src/fw/rules.c src/fw/fwmap.c src/mail/http.c src/mail/net.c \+ src/doc/wire.c src/sec/json.c src/sec/sandbox.c src/sec/cgroup.c+ MAILNET ?= $(shell pkg-config --exists openssl 2>/dev/null && echo 1 || echo 0)+ ifeq ($(MAILNET),1)+ all: build/lord-fetch+ endif+ build/lord-fetch: $(FETCH_SRC) src/fetch/fetchproto.h src/fw/fwlists.h src/mail/http.h src/mail/net.h src/sec/sandbox.h+ @mkdir -p build+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ $(FETCH_SRC) $(shell pkg-config --libs openssl) -lpthread -lm+ # subscriptions (fw/fwsub.c) without network, and lord-fetch's refusals (tests/fwsub_test.c)+ FWSUB_SRC := src/fw/fwsub.c src/fw/fwlists.c src/fw/rules.c src/fw/fwmap.c src/doc/wire.c src/sec/json.c src/sec/netconn.c src/sec/cgroup.c+ ifeq ($(MAILNET),1)+ test: build/fwsub-test+ build/fwsub-test: build/lord-fetch+ endif+ build/fwsub-test: tests/fwsub_test.c $(FWSUB_SRC) src/fw/fwsub.h src/fetch/fetchproto.h+ @mkdir -p build+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/fwsub_test.c $(FWSUB_SRC) -lpthread+ ./$@ build/lord-fetch || { rm -f $@; exit 1; }diff --cc server/src/fetch/fetchproto.hindex 0000000,fefa0bb..28eaa4fmode 000000,100644..100644--- a/server/src/fetch/fetchproto.h+++ b/server/src/fetch/fetchproto.h@@@ -1,0 -1,26 +1,26 @@@-/* fetchproto.h — lord-server ↔ lord-fetch, the blocklist downloader (0.8.4, docs/FIREWALL.md,++/* fetchproto.h — lord-server ↔ lord-fetch, the blocklist downloader (0.8.5, docs/FIREWALL.md,+ * "Blocklists"). The channel and the framing are lord-doc's (doc/wire.h: header + JSON + fds over a+ * SOCK_SEQPACKET pair on fd 3).+ *+ * FQ_GET {"host":"example.org","path":"/list.txt","format":"hosts|domains|ips","sub":0|1}+ * + 1 fd: a TCP socket lord-server already connected (the blocklists' connector, in+ * lordos-net-lists.scope) to host:443+ * FQ_END {}: the helper exits+ *+ * FR_DONE {"domains":N,"nets":N,"skipped":N,"bad":N,"dups":N,"truncated":0|1,"bytes":N,+ * "lastModified":"…"} + 1 sealed memfd with the normalized lines (fw/fwlists.h)+ * FR_REDIRECT {"location":"https://…"} (lord-server checks it and connects again; at most 3)+ * FR_ERR {"error":"tls|cert|http|status|big|nul|line|format|empty|oom|bad-request","detail":"…"}+ *+ * lord-fetch never opens a socket or a file: it loads the CA bundle, locks itself in with+ * sandbox_apply_helper (no socket/connect/exec, no files), speaks TLS 1.2+ (certificate checked+ * against the system CA store and the host name, never relaxed) and HTTP/1.1 GET with a size+ * limit, and parses what came strictly (fwl_parse_raw). lord-server validates every line again+ * before it compiles the lists. */+ #ifndef LORD_FETCH_PROTO_H+ #define LORD_FETCH_PROTO_H++ enum { FQ_GET = 1, FQ_END = 2 };+ enum { FR_DONE = 101, FR_REDIRECT = 102, FR_ERR = 103 };++ #endifdiff --cc server/src/fsops.cindex e641128,730ebc7..7798bd0--- a/server/src/fsops.c+++ b/server/src/fsops.c@@@ -65,6 -65,9 +65,9 @@@ int fsops_protected(const char *real)"/.local/share/lordos/apps", "/.config/lordos/settings.json","/.config/lordos/permisos.json","/.config/lordos/firewall.json", /* network permissions: an app does not write its own rules */- "/.config/lordos/fwlists.json", /* (0.8.4) subscribed blocklists: only lord.fw */++ "/.config/lordos/fwlists.json", /* (0.8.5) subscribed blocklists: only lord.fw */+ "/.config/lordos/fwlists.txt", /* their compiled entries, read by lord-netperm */+ "/.cache/lordos/fwlists", /* their downloads: only lord-server writes them */"/.config/lordos/backup.json", /* Backups: decides where the data goes */"/.config/lordos/mail", /* Mail accounts and trusted certificates: only lord.mail.saveConfig (docs/MAIL.md) */"/.local/share/lordos/mail", /* Mail cache: only lord-maild writes it */diff --cc server/src/fw/fwlists.hindex 0000000,6ea267b..51a3b06mode 000000,100644..100644--- a/server/src/fw/fwlists.h+++ b/server/src/fw/fwlists.h@@@ -1,0 -1,95 +1,95 @@@-/* fwlists.h — subscribed blocklists (0.8.4, docs/FIREWALL.md, "Blocklists").++/* fwlists.h — subscribed blocklists (0.8.5, docs/FIREWALL.md, "Blocklists").+ *+ * Three pieces, all pure C with no network and no files of their own:+ *+ * 1. The raw parsers (fwl_parse_raw): what a list's server sent (a hosts file, one domain per+ * line, or one address / network per line) → normalized lines. They run in lord-fetch, the+ * sandboxed helper, on untrusted bytes. Strict: a NUL byte, a line longer than FWL_LINE_MAX,+ * or too many lines that don't parse reject the whole list; LAN networks, networks broader+ * than /8 (IPv4) or /16 (IPv6), names without a dot and the usual hosts-file names+ * (localhost…) are skipped and counted.+ *+ * 2. The set (FwLists): exact names, names with every subdomain, and networks, each with a tag+ * (which list it came from, for the Monitor's "blocked by the list …"). Names are kept as+ * 64-bit hashes (seeded per process) in sorted arrays: about 10 bytes a name. Name lookups walk+ * the labels right to left; address lookups try each prefix length present (binary search).+ *+ * 3. The compiled file, ~/.config/lordos/fwlists.txt: written by lord-server (js_fw.c, after+ * validating every line again) and read by lord-netperm (root) through the same fixed-path,+ * no-links reader as firewall.json, with fwl_load_text:+ *+ * lordos-fwlists 1+ * d tracker.example an exact name+ * s ads.example the name and every name below it+ * n 192.0.2.0/24 an address or a network (bits outside the prefix are 0)+ *+ * Any line that doesn't validate rejects the whole file (the previous set stays in use).+ *+ * Lists never override a rule the owner wrote for that destination (rules.h, FwQuery.listed). */+ #ifndef LORD_FW_FWLISTS_H+ #define LORD_FW_FWLISTS_H++ #include <stddef.h>+ #include <stdint.h>++ #define FWL_RAW_MAX (16u << 20) /* the most a list's server may send */+ #define FWL_LINE_MAX 1024 /* longer lines reject the list */+ #define FWL_LIST_DOMAINS 400000 /* names in one list */+ #define FWL_LIST_NETS 100000 /* networks in one list */+ #define FWL_MAX_DOMAINS 600000 /* in the compiled set, every list together */+ #define FWL_MAX_NETS 150000+ #define FWL_FILE_MAX (32u << 20) /* the compiled file */+ #define FWL_HEADER "lordos-fwlists 1"++ typedef enum { FWL_FMT_HOSTS = 1, FWL_FMT_DOMAINS = 2, FWL_FMT_IPS = 3 } FwlFormat;++ typedef struct {+ size_t lines; /* lines read (without comments and blank lines) */+ size_t domains, nets; /* entries written */+ size_t skipped; /* valid lines we don't use (LAN, too broad, localhost, no dot) */+ size_t bad; /* lines that didn't parse */+ size_t dups; /* entries repeated inside the list */+ int truncated; /* 1: the list had more than FWL_LIST_DOMAINS / FWL_LIST_NETS */+ } FwlStats;++ /* Parses a raw list in format fmt; sub = 1 makes every name cover its subdomains ("s" lines).+ * Writes the normalized lines into *out (malloc'd, NUL-terminated, *outlen bytes). 0 ok; -1 the+ * whole list is rejected (err: a short code: "nul", "line", "format", "empty", "big", "oom"). */+ int fwl_parse_raw(const char *raw, size_t len, FwlFormat fmt, int sub, char **out, size_t *outlen,+ FwlStats *st, char *err, size_t errlen);+ FwlFormat fwl_format_from_name(const char *name); /* "hosts" / "domains" / "ips"; 0 if unknown */++ typedef struct FwLists FwLists;++ FwLists *fwl_new(void);+ void fwl_free(FwLists *l);+ /* Adds one normalized line ("d name", "s name", "n cidr") with a tag (1..65535). 0 added (a+ * repeated entry goes at the next lookup or fwl_finish, the first tag stays), -1 invalid line,+ * -2 the set is full. */+ int fwl_add_line(FwLists *l, const char *line, size_t len, uint16_t tag);+ /* Only checks a line, as fwl_add_line would (lord-server compiles the file without keeping it). */+ int fwl_check_line(const char *line, size_t len);+ /* Sorts and drops repeated entries; returns how many went. Lookups and counts do it on their own. */+ size_t fwl_finish(FwLists *l);+ /* Adds every line of a normalized text (the lines fwl_parse_raw writes). Returns the number of+ * lines added, or -1 if a line is invalid (the lines before it stay). */+ long fwl_add_text(FwLists *l, const char *text, size_t len, uint16_t tag);+ /* The compiled file: header + lines. Replaces nothing on error: a fresh set is returned, or NULL+ * with err set. */+ FwLists *fwl_load_text(const char *text, size_t len, char *err, size_t errlen);++ size_t fwl_domains(const FwLists *l);+ size_t fwl_nets(const FwLists *l);+ /* The tag of the list that covers this name (normalized or not), or 0. */+ uint16_t fwl_match_name(const FwLists *l, const char *name);+ /* The tag of the list whose network contains the address (fam 4: 4 bytes, 6: 16), or 0. */+ uint16_t fwl_match_addr(const FwLists *l, int fam, const uint8_t *addr);+ /* Walks the networks (fam, network, prefix); cb returns != 0 to stop. */+ void fwl_net_each(const FwLists *l, int (*cb)(void *u, int fam, const uint8_t *addr, int prefix), void *u);++ /* Should the resolver's addresses for these names be blocked? Only when at least one name is+ * listed and none is unlisted: an address a listed tracker shares with a site that isn't listed+ * (a shared CDN) stays allowed. Returns the first listed name's tag, or 0. */+ uint16_t fwl_block_names(const FwLists *l, const char *const *names, int n);++ #endifdiff --cc server/src/fw/fwsub.hindex 0000000,6a012d1..29bdc99mode 000000,100644..100644--- a/server/src/fw/fwsub.h+++ b/server/src/fw/fwsub.h@@@ -1,0 -1,49 +1,49 @@@-/* fwsub.h — the user's blocklist subscriptions, lord-server's side (0.8.4, docs/FIREWALL.md,++/* fwsub.h — the user's blocklist subscriptions, lord-server's side (0.8.5, docs/FIREWALL.md,+ * "Blocklists").+ *+ * assets/fw/blocklists.json the curated catalog (our own asset: id, topic, url, format,+ * licence, source); every entry's licence was checked before it+ * went in+ * ~/.config/lordos/fwlists.json which ones are on, and the custom lists (https URLs)+ * ~/.cache/lordos/fwlists/<id>.txt the normalized download of each list, and <id>.json its state+ * ~/.config/lordos/fwlists.txt every enabled list compiled (fw/fwlists.h); lord-netperm reads it+ *+ * All three user files are written only here (fsops_protected). The work (downloading through+ * lord-fetch and compiling) runs on its own thread: the screen never waits. When it ends,+ * fws_poll() swaps the set in and says so, and lord.fw sends lord-netperm its RELOAD. Lists are+ * downloaded when enabled, and again when the last download is older than a day (fws_update(0)+ * every hour from the SDK). */+ #ifndef LORD_FW_FWSUB_H+ #define LORD_FW_FWSUB_H++ #include <stddef.h>+ #include <stdint.h>++ #define FWS_MAX_LISTS 48 /* catalog + custom */+ #define FWS_MAX_CUSTOM 16+ #define FWS_URL_MAX 400+ #define FWS_STALE_S (20 * 3600) /* "daily": older than this is downloaded again */++ /* home: the user's real home folder; assets: LordOS's assets folder; bindir: where lord-fetch is. */+ int fws_init(const char *home, const char *assets, const char *bindir);+ /* {"catalog":[…],"custom":[…],"enabled":[…],"state":{id:{…}},"busy":bool,"domains":N,"nets":N} (malloc'd) */+ char *fws_json(void);+ /* 0 ok; -1 unknown id. Starts a job (compile, and download what has no copy yet). */+ int fws_set(const char *id, int on);+ /* Adds a custom list; 0 with its id in id_out (32 bytes), or -1 with a code in err+ * ("fw.list.badUrl", "fw.list.badFormat", "fw.list.tooMany", "fw.list.exists"). */+ int fws_add_custom(const char *url, const char *format, char *id_out, char *err, size_t errlen);+ int fws_remove_custom(const char *id);+ /* Downloads the enabled lists (all of them with force, else only the stale ones). 0 started, 1 nothing+ * to do, -1 a job is already running (it runs again when that one ends). */+ int fws_update(int force);+ /* Main thread: 1 if a job just ended and the compiled set changed (send RELOAD). */+ int fws_poll(void);+ /* Which enabled list covers these names or this address (fam 4 or 6, or 0): its id, or NULL. */+ const char *fws_match(const char *const *names, int n, int fam, const uint8_t *addr);++ /* ---- exposed for tests ---- */+ /* https://host[:port]/path → parts; 0 ok. host: lowercase name or IPv4, port 1..65535. */+ int fws_split_url(const char *url, char *host, size_t hcap, int *port, char *path, size_t pcap);++ #endifdiff --cc server/src/fw/rules.hindex ec8cce7,f867f9e..816c2a7--- a/server/src/fw/rules.h+++ b/server/src/fw/rules.h@@@ -32,7 -36,8 +36,8 @@@ typedef enum { FW_PROTO_ANY = 0, FW_PROtypedef enum { FW_ALLOW = 0, FW_DENY = 1 } FwAction;/* forever (saved) / until the app closes / just once (not saved) */typedef enum { FW_LIFE_FOREVER = 0, FW_LIFE_UNTIL_QUIT = 1, FW_LIFE_ONCE = 2 } FwLife;- typedef enum { FW_MODE_SILENT = 0, FW_MODE_ASK = 1, FW_MODE_OFF = 2 } FwMode;-/* deny (0.8.4, "deny silently"): what no rule allows is denied and recorded; loopback stays allowed */++/* deny (0.8.5, "deny silently"): what no rule allows is denied and recorded; loopback stays allowed */+ typedef enum { FW_MODE_SILENT = 0, FW_MODE_ASK = 1, FW_MODE_OFF = 2, FW_MODE_DENY = 3 } FwMode;typedef enum {FW_DST_ANY = 0,@@@ -112,6 -120,14 +120,14 @@@ void fw_store_free(FwStore *s)* desktop:<id>. 0 ok, -1 if it isn't a valid id (empty, too long, odd characters). */int fw_app_canon(const char *in, char *out, size_t n);-/* (0.8.4) LordOS's own components that use the network, each in its own scope++/* (0.8.5) LordOS's own components that use the network, each in its own scope+ * lordos-net-<name>.scope so the kernel enforces their rules (docs/MONITOR.md, "Native apps as+ * their own rows"): their firewall id is "lordos:<name>". 1 if name is one of them. */+ #define FW_COMPONENTS { "mail", "store", "print", "terminal", "lists", NULL }+ int fw_component_ok(const char *name);+ /* "lordos-net-<name>.scope" of a known component → "lordos:<name>" in app. 0 ok, -1 otherwise. */+ int fw_component_scope(const char *scope, char *app, size_t n);+/* Destination as text ("any", "lan", "internet", "example.com", "*.example.com", "10.0.0.0/8",* "2001:db8::1") → kind/wildcard/domain/fam/addr/prefix of r. 0 ok, -1 invalid. */int fw_parse_dest(const char *s, FwRule *r);diff --cc server/src/mail/mailc.cindex 6c0b7d4,d36a3b9..7d6479c--- a/server/src/mail/mailc.c+++ b/server/src/mail/mailc.c@@@ -505,18 -506,16 +506,16 @@@ static int send_msg(uint32_t op, uint32return r;}-/* The socket is made and connected by Mail's own connector, in lordos-net-mail.scope (0.8.4,++/* The socket is made and connected by Mail's own connector, in lordos-net-mail.scope (0.8.5,+ * sec/netconn.h): Mail and the calendar sync are their own app for the firewall and the Monitor. */static int connect_timeout(const struct addrinfo *ai, int ms) {- int fd = socket(ai->ai_family, ai->ai_socktype | SOCK_CLOEXEC | SOCK_NONBLOCK, ai->ai_protocol);+ int fd = netconn_socket(NC_MAIL, ai->ai_family, SOCK_STREAM, ai->ai_addr, ai->ai_addrlen);if (fd < 0) return -1;- int r = connect(fd, ai->ai_addr, ai->ai_addrlen);- if (r && errno != EINPROGRESS) { close(fd); return -1; }- if (r) {- struct pollfd p = { fd, POLLOUT, 0 };- if (poll(&p, 1, ms) != 1) { close(fd); return -1; }- int err = 0;- socklen_t el = sizeof err;- if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &el) || err) { close(fd); return -1; }- }+ struct pollfd p = { fd, POLLOUT, 0 };+ if (poll(&p, 1, ms) != 1) { close(fd); return -1; }+ int err = 0;+ socklen_t el = sizeof err;+ if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &el) || err) { close(fd); return -1; }int fl = fcntl(fd, F_GETFL);fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);return fd;diff --cc server/src/main.cindex 2d4acac,d6499be..33cdfb3--- a/server/src/main.c+++ b/server/src/main.c@@@ -1549,6 -1518,8 +1550,8 @@@ int main(int argc, char **argv)sigaction(SIGPIPE, &pipe_sa, NULL);/* guardián de una sesión de terminal (ver term/hold.c): no abre pantalla ni input */if (argc > 1 && !strcmp(argv[1], "--term-holder")) return hold_main(argc, argv);- /* (0.8.4) a component's network connector (sec/netconn.h): only creates sockets in its scope */++ /* (0.8.5) a component's network connector (sec/netconn.h): only creates sockets in its scope */+ if (argc > 1 && !strcmp(argv[1], "--net-connector")) return netconn_main(argc, argv);if (argc > 1 && !strcmp(argv[1], "--check-code")) return check_code(argc, argv);/* «modo app»: lord-server --app <id> corre una app .lpk como cliente Wayland aislado* (app/appclient.c). El id ya viene validado del propio lord-server (no de JS). */diff --cc server/src/monitor/conn.cindex e091990,e4b6b0b..d10b5d1--- a/server/src/monitor/conn.c+++ b/server/src/monitor/conn.c@@@ -6,8 -6,15 +6,15 @@@* the user's own processes (/proc/<pid>/fd → "socket:[inode]"), with a cache so they aren't walked* on every sample. For other users' sockets only how many there are is counted.*- * (0.8.4) Each socket's cgroup comes too (INET_DIAG_CGROUP_ID): a socket made in one of the session's++ * (0.8.5) Each socket's cgroup comes too (INET_DIAG_CGROUP_ID): a socket made in one of the session's+ * scopes is that app's, whoever holds it now (lord-server holds the ones Mail's connector made, a+ * program in the Terminal is the Terminal's), so the list says "scope": the app's firewall id, the+ * same lord-netperm counts it under ("cgApp").+ ** The country comes from the local database (mmdb.c). No address leaves the machine. */#include "monpriv.h"+ #include "../fw/rules.h"+ #include "../sec/cgroup.h"#include <arpa/inet.h>#include <ctype.h>diff --cc server/src/monitor/netrec.cindex 033d93e,244f6b1..38b8e7a--- a/server/src/monitor/netrec.c+++ b/server/src/monitor/netrec.c@@@ -169,6 -169,27 +169,27 @@@ static void total_tick(long long now)nh_add(hist, now, NULL, rx, tx);}-/* (0.8.4) The machine's byte counters right now, every interface but lo (the menu bar's network++/* (0.8.5) The machine's byte counters right now, every interface but lo (the menu bar's network+ * item: one small file read per second while it is shown). 0 ok. */+ int netrec_totals(uint64_t *rx, uint64_t *tx) {+ char txt[8192];+ if (mon_read_small("/proc/net/dev", txt, sizeof txt) <= 0) return -1;+ *rx = *tx = 0;+ for (char *l = txt; l; l = strchr(l, '\n') ? strchr(l, '\n') + 1 : NULL) {+ char *colon = strchr(l, ':'), *nl = strchr(l, '\n');+ if (!colon || (nl && colon > nl)) continue;+ char *s = l;+ while (*s == ' ') s++;+ if (colon - s == 2 && !strncmp(s, "lo", 2)) continue;+ unsigned long long v[16];+ char *p = colon + 1;+ for (int i = 0; i < 16; i++) v[i] = strtoull(p, &p, 10);+ *rx += v[0];+ *tx += v[8];+ }+ return 0;+ }+void netrec_tick(void) {if (!netrec_enabled()) return;double t = mono_ms();diff --cc server/src/monitor/netrec.hindex 879fccd,7745ed5..156e1ce--- a/server/src/monitor/netrec.h+++ b/server/src/monitor/netrec.h@@@ -16,5 -16,6 +16,6 @@@ double netrec_timeout(void)NetHist *netrec_hist(void); /* NULL when not allowed */long long netrec_now(void); /* Unix time */void netrec_shutdown(void); /* writes the minute in progress */-int netrec_totals(uint64_t *rx, uint64_t *tx); /* (0.8.4) every interface but lo, now; 0 ok */++int netrec_totals(uint64_t *rx, uint64_t *tx); /* (0.8.5) every interface but lo, now; 0 ok */#endifdiff --cc server/src/netperm/netperm.cindex 89549b1,b82c9ae..7878bd6--- a/server/src/netperm/netperm.c+++ b/server/src/netperm/netperm.c@@@ -12,6 -12,9 +12,9 @@@* - learns names only from the system resolver (npdns.c);* - tells each lord-server about its apps' new connections over /run/lordos/netperm.sock* (npproto.h). The only thing it accepts there is "reload my rules";- * - (0.8.4) reads each user's subscribed blocklists (~/.config/lordos/fwlists.txt, the same++ * - (0.8.5) reads each user's subscribed blocklists (~/.config/lordos/fwlists.txt, the same+ * fixed-path reader) into np_blk4/np_blk6: their networks, and the addresses the resolver gave+ * for their domains; and counts the essential system services' bytes (np_sysc);* - cuts the connections a rule now denies: the packet filter drops their packets in the* kernel, and this process destroys their sockets over sock_diag netlink (npdiag.c, the only* socket besides AF_UNIX and the DNS AF_PACKET one), right after a reload and whenever the@@@ -91,8 -96,19 +96,19 @@@ typedef structint dirty_counts;uint64_t user_cg; /* id of user@<uid>.service, or 0 if it isn't there (nor attached) */int ulinks[16], nulinks; /* the programs attached to user@<uid>.service */- FwLists *lists; /* (0.8.4) the subscribed blocklists, NULL: none */++ FwLists *lists; /* (0.8.5) the subscribed blocklists, NULL: none */+ uint32_t blkset; /* its set in np_blk4/np_blk6 (NpApp.blk) */+ FwMap blkin; /* installed entries: (fam, prefix, address) → BlkEnt */+ int nlearned; /* entries from the resolver among them */} Session;+ typedef struct {+ int learned; /* 1: an address the resolver gave for a listed name */+ long long mark; /* the pass that last wanted it */+ } BlkEnt;++ #define BLK_LEARNED_MAX 16384 /* resolver addresses per user */+typedef struct {int fd;unsigned uid;@@@ -213,6 -233,27 +233,27 @@@ static void load_rules(Session *s)logf_("uid %u: %zu rules, mode %d", s->uid, fw_rule_count(n), (int)fw_mode(n));}-/* (0.8.4) ~/.config/lordos/fwlists.txt, the user's subscribed blocklists compiled by lord-server++/* (0.8.5) ~/.config/lordos/fwlists.txt, the user's subscribed blocklists compiled by lord-server+ * (fw/fwlists.h), through the same reader. A file that doesn't validate keeps the previous set. */+ static void load_lists(Session *s) {+ size_t len = 0;+ char why[160] = "", err[120] = "";+ char *text = read_user_file(s->uid, "fwlists.txt", FWL_FILE_MAX, &len, why, sizeof why);+ if (!text) {+ if (strcmp(why, "no rules")) logf_("uid %u: blocklists: %s", s->uid, why);+ fwl_free(s->lists);+ s->lists = NULL;+ return;+ }+ FwLists *l = fwl_load_text(text, len, err, sizeof err);+ free(text);+ if (!l) { logf_("uid %u: invalid fwlists.txt (%s); the previous blocklists stay in use", s->uid, err); return; }+ fwl_free(s->lists);+ s->lists = fwl_domains(l) || fwl_nets(l) ? l : (fwl_free(l), NULL);+ if (s->lists) logf_("uid %u: blocklists: %zu names, %zu networks", s->uid, fwl_domains(s->lists), fwl_nets(s->lists));+ malloc_trim(0); /* the file's text and the set's growth: back to the system */+ }+/* ---- maps ------------------------------------------------------------------------------------ */#ifdef NP_HAVE_BPF /* the program loader's relocations (bpf_setup) */@@@ -323,6 -371,107 +371,107 @@@ static void drop_scope(Scope *sc)prune(sc->idx, 0);}-/* ---- blocklists (0.8.4, docs/FIREWALL.md "Blocklists") --------------------------------------++/* ---- blocklists (0.8.5, docs/FIREWALL.md "Blocklists") --------------------------------------+ *+ * Each user with subscribed lists gets a set in np_blk4/np_blk6 (NpApp.blk of each of their apps):+ * the lists' networks, and the addresses the system resolver gave for a listed name, as long as+ * every name the resolver gave for that address is listed (a shared CDN address stays allowed).+ * The whole set is recomputed on a reload and every 30 s (what the resolver forgot goes); a DNS+ * answer updates its own addresses at once, before the app connects. The kernel decides with+ * np_decide: a rule the owner wrote for that destination still wins. */++ static size_t blk_key(int fam, const uint8_t *addr, int prefix, unsigned char *k) {+ memset(k, 0, 18);+ k[0] = (unsigned char)fam;+ k[1] = (unsigned char)prefix;+ memcpy(k + 2, addr, fam == 4 ? 4 : 16);+ return 18;+ }++ static int blk_map(uint32_t set, int fam, const uint8_t *addr, int prefix, int del) {+ uint8_t one = 1;+ if (fam == 4) {+ NpLpm4Key k;+ memset(&k, 0, sizeof k);+ k.prefixlen = 32 + (uint32_t)prefix;+ k.data[0] = (uint8_t)(set >> 24); k.data[1] = (uint8_t)(set >> 16); k.data[2] = (uint8_t)(set >> 8); k.data[3] = (uint8_t)set;+ memcpy(k.data + 4, addr, 4);+ return del ? bpfs_map_delete(G.m_np_blk4, &k) : bpfs_map_update(G.m_np_blk4, &k, &one, BPF_ANY);+ }+ NpLpm6Key k;+ memset(&k, 0, sizeof k);+ k.prefixlen = 32 + (uint32_t)prefix;+ k.data[0] = (uint8_t)(set >> 24); k.data[1] = (uint8_t)(set >> 16); k.data[2] = (uint8_t)(set >> 8); k.data[3] = (uint8_t)set;+ memcpy(k.data + 4, addr, 16);+ return del ? bpfs_map_delete(G.m_np_blk6, &k) : bpfs_map_update(G.m_np_blk6, &k, &one, BPF_ANY);+ }++ static int blk_added; /* entries sync_blk installed (a sweep follows) */++ static void blk_want(Session *s, int fam, const uint8_t *addr, int prefix, int learned) {+ unsigned char k[18];+ size_t kl = blk_key(fam, addr, prefix, k);+ void **slot = fwmap_slot(&s->blkin, k, kl, 1);+ if (!slot) return;+ BlkEnt *e = *slot;+ if (e) {+ e->mark = G.blk_pass;+ if (!learned && e->learned) { e->learned = 0; s->nlearned--; }+ return;+ }+ if ((learned && s->nlearned >= BLK_LEARNED_MAX) || blk_map(s->blkset, fam, addr, prefix, 0) || !(e = malloc(sizeof *e))) {+ fwmap_take(&s->blkin, k, kl);+ return;+ }+ e->learned = learned;+ e->mark = G.blk_pass;+ s->nlearned += learned;+ *slot = e;+ blk_added++;+ }++ /* An address the resolver now also gives for an unlisted name: no longer blocked. */+ static void blk_unwant_learned(Session *s, int fam, const uint8_t *addr) {+ unsigned char k[18];+ size_t kl = blk_key(fam, addr, fam == 4 ? 32 : 128, k);+ BlkEnt *e = fwmap_get(&s->blkin, k, kl);+ if (!e || !e->learned) return;+ blk_map(s->blkset, fam, addr, fam == 4 ? 32 : 128, 1);+ free(fwmap_take(&s->blkin, k, kl));+ s->nlearned--;+ }++ static int blk_net_cb(void *u, int fam, const uint8_t *addr, int prefix) { blk_want(u, fam, addr, prefix, 0); return 0; }++ static int blk_dns_cb(void *u, int fam, const uint8_t *addr, const char (*names)[FW_NAME_MAX], int n) {+ Session *s = u;+ const char *p[DNSMAP_PER_IP];+ for (int i = 0; i < n && i < DNSMAP_PER_IP; i++) p[i] = names[i];+ if (fwl_block_names(s->lists, p, n < DNSMAP_PER_IP ? n : DNSMAP_PER_IP)) blk_want(s, fam, addr, fam == 4 ? 32 : 128, 1);+ return 0;+ }++ static void sweep(unsigned uid);++ static void sync_blk(Session *s) {+ if (!G.bpf_ok) return;+ G.blk_pass++;+ blk_added = 0;+ if (s->lists) {+ if (!s->blkset) s->blkset = ++G.next_blkset;+ fwl_net_each(s->lists, blk_net_cb, s);+ if (fwl_domains(s->lists)) dnsmap_each(G.names, NAMES_APP, mono(), blk_dns_cb, s);+ }+ FWMAP_EACH(&s->blkin, e) {+ BlkEnt *b = e->val;+ if (b->mark == G.blk_pass) continue;+ blk_map(s->blkset, e->key[0], e->key + 2, e->key[1], 1);+ s->nlearned -= b->learned;+ free(fwmap_take(&s->blkin, e->key, e->klen));+ }+ if (blk_added) sweep(s->uid); /* open connections to what was just added */+ }+/* ---- user@<uid>.service: the systemd-run escape ------------------------------------------- *//* An app without a sandbox, running as the user, can ask its systemd manager@@@ -398,6 -547,8 +547,8 @@@ static void sync_user_scope(Session *sstatic int scope_app(const char *name, char *app) {if (!strcmp(name, "server")) { snprintf(app, FW_APP_MAX, "lordos"); return 0; }size_t n = strlen(name);- /* (0.8.4) LordOS's own components that use the network: lordos-net-<name>.scope → lordos:<name> */++ /* (0.8.5) LordOS's own components that use the network: lordos-net-<name>.scope → lordos:<name> */+ if (!strncmp(name, "lordos-net-", 11)) return fw_component_scope(name, app, FW_APP_MAX);if (n < 18 || strncmp(name, "app-lordos-", 11) || strcmp(name + n - 6, ".scope")) return -1;return fw_app_canon(name, app, FW_APP_MAX);}@@@ -520,8 -675,19 +675,19 @@@ static void scan_all(void)snprintf(path, sizeof path, CG_ROOT "/" CG_SERVICE "/%s", s->dir);s->wd = inotify_add_watch(G.ifd, path, IN_CREATE | IN_DELETE | IN_ONLYDIR);load_rules(s);+ load_lists(s);+ sync_blk(s);}s->seen = 1;+ /* a session that ended and started again has a new folder under the same name: watch the+ * one there now (for the same folder this returns the same watch), or a new scope would only- * be found by the 5-second rescan (0.8.4: a component's scope connects right away) */++ * be found by the 5-second rescan (0.8.5: a component's scope connects right away) */+ {+ char path[160];+ snprintf(path, sizeof path, CG_ROOT "/" CG_SERVICE "/%s", s->dir);+ int wd = inotify_add_watch(G.ifd, path, IN_CREATE | IN_DELETE | IN_ONLYDIR);+ if (wd >= 0) s->wd = wd;+ }scan_session(s);}if (d) closedir(d);@@@ -912,6 -1099,46 +1099,46 @@@ static void on_net_event(const NpEventev.flag ? " " : "", ev.flag && flag ? flag : "");}-/* ---- the essential system services (0.8.4) ----------------------------------------------------++/* ---- the essential system services (0.8.5) ----------------------------------------------------+ *+ * Name resolution, time and the network service are not apps and can't be blocked, but the Monitor+ * shows their traffic: the accounting programs alone are attached to resolved's and timesyncd's+ * cgroups (lord-netd's leaf, lordos.service/netd, is already under lordos.service), and np_sysc+ * gets an entry for each, keyed by its cgroup id (the programs only add to existing entries). */+ static const struct { const char *id, *parent, *leaf; } SYS[3] = {+ { "system:dns", CG_ROOT "/system.slice", "systemd-resolved.service" },+ { "system:time", CG_ROOT "/system.slice", "systemd-timesyncd.service" },+ { "system:network", CG_ROOT "/" CG_SERVICE, "netd" },+ };++ static void sync_system(void) {+ if (!G.bpf_ok || G.acct_ok != 2) return;+ for (int i = 0; i < 3; i++) {+ int dfd = open(SYS[i].parent, O_RDONLY | O_DIRECTORY | O_CLOEXEC);+ uint64_t id = dfd >= 0 ? bpfs_cgroup_id(dfd, SYS[i].leaf) : 0;+ if (id == G.sys[i].cgid) { if (dfd >= 0) close(dfd); continue; }+ for (int k = 0; k < G.sys[i].nlinks; k++) close(G.sys[i].links[k]);+ if (G.sys[i].cgid) bpfs_map_delete(G.m_np_sysc, &G.sys[i].cgid);+ memset(&G.sys[i], 0, sizeof G.sys[i]);+ if (!id) { if (dfd >= 0) close(dfd); continue; }+ NpCount z = { 0, 0, 0, 0, 0 };+ bpfs_map_update(G.m_np_sysc, &id, &z, BPF_ANY);+ if (strcmp(SYS[i].leaf, "netd")) {+ int cfd = openat(dfd, SYS[i].leaf, O_RDONLY | O_DIRECTORY | O_CLOEXEC);+ for (int p = 0; cfd >= 0 && p < G.nprogs && G.sys[i].nlinks < 4; p++) {+ if (!np_attach_system(G.attach[p])) continue;+ int l = bpfs_link_create(G.progs[p], cfd, G.attach[p]);+ if (l < 0) { logf_("%s: could not attach the accounting: %s", SYS[i].leaf, strerror(errno)); break; }+ G.sys[i].links[G.sys[i].nlinks++] = l;+ }+ if (cfd >= 0) close(cfd);+ }+ close(dfd);+ G.sys[i].cgid = id;+ logf_("counting %s (%s)", SYS[i].id, SYS[i].leaf);+ }+ }+/* ---- traffic per address (np_flows) ------------------------------------------------------- */typedef struct {@@@ -970,9 -1197,33 +1197,33 @@@ static void idle_flows(void)}}- /* [["addr",rx,tx,rxRate,txRate,blocked],...] of one app, busiest first. */+ /* [["addr",rx,tx,rxRate,txRate,blocked,[[port,"tcp"|"udp"|"other","out"|"in",rx,tx,rxRate,txRate],...]],...]- * of one app, busiest address first (0.8.4: np_flows is per address and port; this folds the ports++ * of one app, busiest address first (0.8.5: np_flows is per address and port; this folds the ports+ * of each address together and lists its 8 busiest under it). */+ #define PORTS_PER_ADDR 8+ typedef struct { const NpFlowKey *k; uint64_t rx, tx, blocked; double rrx, rtx; int first, n; } AddrAgg;++ static int agg_cmp(const void *a, const void *b) {+ const AddrAgg *x = a, *y = b;+ double rx = x->rrx + x->rtx, ry = y->rrx + y->rtx;+ if (rx != ry) return rx < ry ? 1 : -1;+ uint64_t bx = x->rx + x->tx, by = y->rx + y->tx;+ return bx < by ? 1 : bx > by ? -1 : 0;+ }++ static int same_addr(const NpFlowKey *a, const NpFlowKey *b) { return a->fam == b->fam && !memcmp(a->addr, b->addr, 16); }++ static int ref_addr_cmp(const void *a, const void *b) {+ const NpFlowKey *x = ((const FlowRef *)a)->k, *y = ((const FlowRef *)b)->k;+ if (x->fam != y->fam) return x->fam - y->fam;+ int c = memcmp(x->addr, y->addr, 16);+ if (c) return c;+ return flow_cmp(a, b);+ }+static size_t flows_json(uint64_t cgid, char *j, size_t cap) {static FlowRef refs[NP_MAX_FLOWS];+ static AddrAgg agg[NP_MAX_FLOWS];int n = 0;FWMAP_EACH(&G.flows, e) {const NpFlowKey *k = (const NpFlowKey *)(const void *)e->key;diff --cc server/src/netperm/np.bpf.cindex d97dddc,1be756c..0974603--- a/server/src/netperm/np.bpf.c+++ b/server/src/netperm/np.bpf.c@@@ -17,7 -17,8 +17,8 @@@* cgroup/lsm_socket_create "no Bluetooth": socket(AF_BLUETOOTH) (a per-cgroup LSM program,* BPF_LSM_CGROUP: the inet sock_create hook never sees that family)* cgroup/skb_ingress, egress traffic accounting for the Monitor: bytes per app (np_counts) and- * per (app, remote address) (np_flows); and the cut of connections- * per (app, remote address, port) (np_flows), and (0.8.4) of the++ * per (app, remote address, port) (np_flows), and (0.8.5) of the+ * essential system services (np_sysc); and the cut of connections* opened before a rule changed: a packet whose connection the app's* current rules deny is dropped (counted as "blocked") and its socket* is reported once, so lord-netperm destroys it (SOCK_DESTROY).@@@ -143,6 -148,29 +148,29 @@@ NP_INLINE NpList *lookup_list(NpApp *apreturn l;}-/* (0.8.4) Is the address in the app's blocklist set (the user's subscribed lists: their networks++/* (0.8.5) Is the address in the app's blocklist set (the user's subscribed lists: their networks+ * and the addresses the resolver gave for their domains)? */+ NP_INLINE int lookup_blk(NpApp *app, int fam, const np_u8 *addr) {+ if (!app->blk) return 0;+ if (fam == 4) {+ NpLpm4Key k;+ k.prefixlen = 64;+ k.data[0] = (np_u8)(app->blk >> 24); k.data[1] = (np_u8)(app->blk >> 16);+ k.data[2] = (np_u8)(app->blk >> 8); k.data[3] = (np_u8)app->blk;+ k.data[4] = addr[0]; k.data[5] = addr[1]; k.data[6] = addr[2]; k.data[7] = addr[3];+ return bpf_map_lookup_elem(&np_blk4, &k) != 0;+ }+ if (fam == 6) {+ NpLpm6Key k;+ k.prefixlen = 160;+ k.data[0] = (np_u8)(app->blk >> 24); k.data[1] = (np_u8)(app->blk >> 16);+ k.data[2] = (np_u8)(app->blk >> 8); k.data[3] = (np_u8)app->blk;+ for (int i = 0; i < 16; i++) k.data[4 + i] = addr[i];+ return bpf_map_lookup_elem(&np_blk6, &k) != 0;+ }+ return 0;+ }+/* fam 0: unknown address. addr: 16 bytes (IPv4 in the first 4). always_count: connect and* bind always count; sendto only the first time within NP_REPEAT_NS. */NP_INLINE int handle(int fam, np_u8 *addr, int port, int proto, int dir, int always_count) {@@@ -422,11 -450,26 +450,26 @@@ NP_INLINE void report_cut(struct __sk_bbpf_ringbuf_output(&np_events, &ev, sizeof ev, 0);}-/* (0.8.4) The essential system services (name resolution, time, the network service), which are++/* (0.8.5) The essential system services (name resolution, time, the network service), which are+ * not apps: lord-netperm attaches these programs to their own cgroups too and keys np_sysc by the+ * socket's cgroup. They are only counted, never filtered: their traffic can't be blocked. */+ NP_INLINE int count_system(struct __sk_buff *skb, int in) {+ np_u64 id = bpf_skb_cgroup_id(skb);+ if (!id) return 1;+ NpCount *c = bpf_map_lookup_elem(&np_sysc, &id);+ if (!c) return 1;+ np_u64 len = skb->len;+ if (in) __sync_fetch_and_add(&c->rx, len);+ else __sync_fetch_and_add(&c->tx, len);+ return 1;+ }+/* Only for apps lord-netperm knows (it creates their np_counts entry when the scope appears), so* nothing else (the login screen, the system) is counted, stored or filtered. Loopback isn't* counted or filtered. The skb starts at the IP header in both directions. Returns 1 (let it* through) or 0 (drop). An allowed packet adds its bytes to its app (the socket's cgroup, the- * scope at cfg->level) and to the (app, remote address) pair; a dropped one to "blocked". */- * scope at cfg->level) and to the (app, remote address, port) flow (0.8.4: the port too: the++ * scope at cfg->level) and to the (app, remote address, port) flow (0.8.5: the port too: the+ * remote one, or the local one of a port the app bound); a dropped one to "blocked". */NP_INLINE int filter(struct __sk_buff *skb, int in) {if (skb->ifindex == LOOPBACK_IFINDEX) return 1;np_u32 zero = 0;diff --cc server/src/netperm/np_shared.hindex ea5d94c,8d624fd..9b3baea--- a/server/src/netperm/np_shared.h+++ b/server/src/netperm/np_shared.h@@@ -20,6 -20,10 +20,10 @@@* np_events RINGBUF NpEvent towards lord-netperm* np_snd HASH ALSA minor (u32) → u32 every ALSA node in /sys/class/sound: NP_SND_CAPTURE for the* capture PCMs (/dev/snd/pcmC*D*c), NP_SND_OTHER for the rest- * np_blk4 LPM (list set, IPv4/n) → u8 (0.8.4) a user's subscribed blocklists: their networks and++ * np_blk4 LPM (list set, IPv4/n) → u8 (0.8.5) a user's subscribed blocklists: their networks and+ * np_blk6 LPM (list set, IPv6/n) → u8 the addresses the resolver gave for their domains (NpApp.blk)- * np_sysc HASH cgroup id → NpCount (0.8.4) the essential system services' bytes (name++ * np_sysc HASH cgroup id → NpCount (0.8.5) the essential system services' bytes (name+ * resolution, time, the network service), counted only** Besides the network, the same per-app policy carries the device restrictions (docs/FIREWALL.md,* "Linux apps"): "no camera", "no USB" and "no screen capture" (/dev/fb*) (cgroup/dev, by device@@@ -143,7 -152,12 +152,12 @@@ typedef structnp_u64 cgid;np_u8 addr[16]; /* the remote address; IPv4 (also IPv4-mapped IPv6) in the first 4 */np_u8 fam; /* 4 or 6 */- np_u8 pad[7];- np_u8 proto; /* (0.8.4) NP_P_TCP / NP_P_UDP / NP_P_OTHER */- np_u8 dir; /* (0.8.4) NP_D_OUT: port is the remote one; NP_D_IN: a port the app++ np_u8 proto; /* (0.8.5) NP_P_TCP / NP_P_UDP / NP_P_OTHER */++ np_u8 dir; /* (0.8.5) NP_D_OUT: port is the remote one; NP_D_IN: a port the app+ * bound (np_bound), its local one */+ np_u8 pad;- np_u16 port; /* (0.8.4) host order; 0 when there is none (ICMP, a later fragment) */++ np_u16 port; /* (0.8.5) host order; 0 when there is none (ICMP, a later fragment) */+ np_u8 pad2[2];} NpFlowKey;typedef struct { np_u64 rx, tx, blocked; } NpFlow;diff --cc server/src/netperm/npcompile.hindex a7c5074,bfe4e0f..65c1dd9--- a/server/src/netperm/npcompile.h+++ b/server/src/netperm/npcompile.h@@@ -11,7 -11,8 +11,8 @@@* as fw_decide.** "Just once" rules aren't compiled (there's nobody to delete them in the kernel; without ask- * mode they don't appear). "Ask" mode is compiled as silent. */- * mode they don't appear). "Ask" mode is compiled as silent, "deny" (0.8.4) as NP_M_DENY.++ * mode they don't appear). "Ask" mode is compiled as silent, "deny" (0.8.5) as NP_M_DENY.+ * The blocklist set (NpApp.blk) is lord-netperm's: it sets it after compiling (fw/fwlists.h). */#ifndef LORD_NP_COMPILE_H#define LORD_NP_COMPILE_Hdiff --cc server/src/netperm/npload.hindex 19fd189,0ef4abb..8166887--- a/server/src/netperm/npload.h+++ b/server/src/netperm/npload.h@@@ -56,6 -59,8 +59,8 @@@ static const NpProgSpec np_prog_specs[#define NP_NSPECS (int)(sizeof np_prog_specs / sizeof np_prog_specs[0])static inline int np_attach_user(uint32_t attach) { return attach != BPF_CGROUP_INET_INGRESS && attach != BPF_CGROUP_INET_EGRESS; }-/* (0.8.4) Only the accounting programs go to the essential system services' cgroups. */++/* (0.8.5) Only the accounting programs go to the essential system services' cgroups. */+ static inline int np_attach_system(uint32_t attach) { return !np_attach_user(attach); }/* The license the kernel sees: LSM programs must declare a GPL-compatible one (see bpfsys.h). */static inline const char *np_prog_license(const NpProgSpec *p) { return p->type == BPF_PROG_TYPE_LSM ? "Dual MIT/GPL" : "LordOS"; }diff --cc server/src/netperm/npproto.hindex 95acf72,27c249d..1c6d2c1--- a/server/src/netperm/npproto.h+++ b/server/src/netperm/npproto.h@@@ -7,7 -7,8 +7,8 @@@* u32 length (little endian, counts the type and the data) · u8 type · data** From lord-server to lord-netperm there is ONE single message, with no data:- * NP_MSG_RELOAD "reread my user's ~/.config/lordos/firewall.json"- * NP_MSG_RELOAD "reread my user's ~/.config/lordos/firewall.json" (and, 0.8.4, fwlists.txt, the++ * NP_MSG_RELOAD "reread my user's ~/.config/lordos/firewall.json" (and, 0.8.5, fwlists.txt, the+ * compiled blocklists, through the same reader)* Rules never travel over the socket: lord-netperm reads the user's file itself, from a fixed,* validated path (no links, owned by the user, regular file, up to 4 MB) with the strict reader* of fw/rules.c. Any other message, or one longer than NP_IN_MAX bytes, closes the connection.@@@ -21,7 -22,13 +22,13 @@@* up to 4 names the resolver* gave for addr* NP_MSG_COUNTS {"desktop:x":[allowed,denied,rx,tx,rxRate,txRate,- * [["1.2.3.4",rx,tx,rxRate,txRate,blocked],...],blocked],...}+ * [["1.2.3.4",rx,tx,rxRate,txRate,blocked,+ * [[port,"tcp"|"udp"|"other","out"|"in",rx,tx,rxRate,txRate],...]],...],blocked],+ * "system:dns":[0,0,rx,tx,rxRate,txRate,[],0],...}- * (0.8.4: each address's 8 busiest++ * (0.8.5: each address's 8 busiest+ * ports; the essential system+ * services' bytes, the same for+ * every user)* every second, if it changed:* connections, bytes (the* cgroup_skb accounting), thediff --cc server/src/pkg/http.cindex 82cc1bc,c667d81..635acbc--- a/server/src/pkg/http.c+++ b/server/src/pkg/http.c@@@ -388,6 -380,9 +389,9 @@@ int fetch_batch(FetchItem *items, int nsyscall(SYS_close_range, 4, ~0u, 0);signal(SIGPIPE, SIG_IGN);prctl(PR_SET_PDEATHSIG, SIGKILL);- /* (0.8.4) in lordos-net-store.scope, so the Store and the updates are their own app for the++ /* (0.8.5) in lordos-net-store.scope, so the Store and the updates are their own app for the+ * firewall and Monitor → Network (lordos:store); outside a LordOS session, where it is */+ if (getenv("LORDOS_SESSIOND")) cgroup_enter_root("lordos-net-store.scope");if (drop_to_nobody()) _exit(2);Conn c = { .fd = -1, .out = 3 };for (int i = 0; i < n; i++) get_one(&c, &items[i], (uint32_t)i);diff --cc server/src/remote/netsup.cindex e97d45f,56bb431..96c3bed--- a/server/src/remote/netsup.c+++ b/server/src/remote/netsup.c@@@ -95,6 -96,7 +96,7 @@@ void sd_netd_start(void)signal(SIGTERM, SIG_DFL);signal(SIGHUP, SIG_DFL);setsid(); /* does not die with lord-sessiond (KillMode=process) */- cgroup_service_leaf("netd"); /* its own leaf: Monitor → Network counts its traffic (0.8.4) */++ cgroup_service_leaf("netd"); /* its own leaf: Monitor → Network counts its traffic (0.8.5) */char *const argv[] = { path, NULL };char *const env[] = { "PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C.UTF-8", NULL };execve(path, argv, env);diff --cc server/src/sec/cgroup.hindex a275a93,d42a28b..cf5022c--- a/server/src/sec/cgroup.h+++ b/server/src/sec/cgroup.h@@@ -43,6 -43,23 +43,23 @@@ int cgroup_delegate_session(unsigned ui* sessions' subtrees (cgroup v2's "no internal processes" rule). 0 if it did. */int cgroup_service_init(void);-/* (0.8.4) Called by lord-sessiond in lord-netd's child, before its execve: moves the process into++/* (0.8.5) Called by lord-sessiond in lord-netd's child, before its execve: moves the process into+ * the root-owned lordos.service/<name> leaf (only "netd"), so lord-netperm can count the network+ * service's own traffic (DHCP, the VPN daemons) apart from lord-sessiond's. Best effort: 0 placed. */+ int cgroup_service_leaf(const char *name);+-/* (0.8.4) A root process of a session (the admin helper's download child, before it drops to++/* (0.8.5) A root process of a session (the admin helper's download child, before it drops to+ * nobody) moves itself into scope `name` of its own session's subtree: lord-sessiond's placement+ * service only places session users, and root may write the root-owned cgroup.procs itself. Only+ * from the session's «server» leaf, only itself. 0 placed. */+ int cgroup_enter_root(const char *name);+-/* (0.8.4) A quarter of a second for lord-netperm to see a scope that was just created (it watches++/* (0.8.5) A quarter of a second for lord-netperm to see a scope that was just created (it watches+ * the session folder with inotify) before the process in it opens a connection: otherwise the first+ * connections would meet no policy. Called after placing a process in a new scope that connects at+ * once (the Store's download child, the components' connectors). */+ void cgroup_settle(void);+/* ---- Root-owned app scopes (lord-sessiond) ----* With lord-sessiond, a session's subtree stays root-owned: the scopes are created by root, with a* root-owned cgroup.procs, so an app cannot move itself to another cgroup (it would escape itsdiff --cc server/src/sec/netconn.hindex 0000000,0857a56..d673466mode 000000,100644..100644--- a/server/src/sec/netconn.h+++ b/server/src/sec/netconn.h@@@ -1,0 -1,61 +1,61 @@@-/* netconn.h — sockets for LordOS's own components, created in their own scopes (0.8.4).++/* netconn.h — sockets for LordOS's own components, created in their own scopes (0.8.5).+ *+ * lord-server opens connections for several of its parts: Mail and the calendar sync (for+ * lord-maild, which has no sockets of its own), printers and scanners, and the blocklist+ * downloads. The kernel ties a socket to the cgroup of the process that created it, so each of+ * those parts gets a small connector process of its own: lord-server re-executed as+ * `lord-server --net-connector <component>` (component from a fixed list, fw_component_ok), which+ * asks lord-sessiond to place it in lordos-net-<component>.scope and then only creates sockets on+ * request. lord-netperm sees that scope as the firewall app "lordos:<component>": its rules, its+ * traffic and its row in Monitor → Network are its own, enforced by the kernel.+ *+ * The connector only does what lord-server could do itself (same user): socket(), and connect()+ * to the address lord-server already chose (non-blocking: lord-server waits for the result). It+ * takes no paths or names, runs nothing, and its request is a fixed-size struct validated on its+ * side too. In a LordOS session a connector that can't be placed in its scope exits, and the+ * request fails (fail closed: otherwise the traffic would count, and be decided, as lord-server's+ * own). Outside a LordOS session (no LORDOS_SESSIOND: development, the tests) there are no scopes,+ * and netconn_socket() makes the socket in lord-server itself, as before. */+ #ifndef LORD_SEC_NETCONN_H+ #define LORD_SEC_NETCONN_H++ #include <sys/socket.h>++ typedef enum { NC_MAIL = 0, NC_PRINT = 1, NC_LISTS = 2, NC_COUNT } NcComponent;++ /* The connector's name ("mail", "print", "lists"), the same as its firewall id after "lordos:". */+ const char *netconn_name(NcComponent c);++ /* A new non-blocking, close-on-exec socket of family fam (AF_INET / AF_INET6) and type+ * (SOCK_STREAM / SOCK_DGRAM), created by comp's connector. With to, the connector also called+ * connect() (EINPROGRESS for TCP): the caller polls for POLLOUT and reads SO_ERROR as usual; a+ * connection the firewall denies fails with EPERM. Returns the fd, or -1 with errno set.+ * Thread-safe. */+ int netconn_socket(NcComponent comp, int fam, int type, const struct sockaddr *to, socklen_t tolen);++ /* `lord-server --net-connector <component>`: the connector process (main.c). Never returns+ * normally. */+ int netconn_main(int argc, char **argv);++ /* ---- the request (exposed for tests/netconn_test.c) ---- */+ #define NC_MAGIC 0x4c4e4331u /* "LNC1" */+ typedef struct {+ unsigned magic;+ unsigned char fam; /* 4 or 6 */+ unsigned char type; /* 1 stream, 2 datagram */+ unsigned char connect; /* 1: connect to addr:port */+ unsigned char pad;+ unsigned short port; /* host order */+ unsigned short pad2;+ unsigned char addr[16];+ unsigned scope_id; /* IPv6 link-local */+ } NcReq;++ /* 0 if a connector may act on it (checked again on the connector's side). */+ int netconn_req_ok(const NcReq *r);+ /* Builds the request from a sockaddr; 0 ok. */+ int netconn_req_make(NcReq *r, int fam, int type, const struct sockaddr *to, socklen_t tolen);+ /* The connector's side: does one request (socket, connect) and returns the fd or -errno. */+ int netconn_serve_one(const NcReq *r);++ #endifdiff --cc server/src/term/pty.cindex e0c9a83,b56d8a1..9b06a3b--- a/server/src/term/pty.c+++ b/server/src/term/pty.c@@@ -51,6 -52,14 +52,14 @@@ static void child(int fd, const char *cmemset(caps, 0, sizeof caps);syscall(SYS_capset, &hdr, caps);- /* (0.8.4) the shell and every program it runs in lordos-net-terminal.scope: one "Terminal" app++ /* (0.8.5) the shell and every program it runs in lordos-net-terminal.scope: one "Terminal" app+ * for the firewall and Monitor → Network (lordos:terminal), each connection with its program's+ * name. Best effort: a terminal that can't be placed still opens. */+ if (getenv("LORDOS_SESSIOND")) {+ CgroupLimits lim = { 0, 0, 0 };+ cgroup_enter("lordos-net-terminal.scope", &lim);+ }+struct passwd *pw = getpwuid(getuid());const char *home = getenv("HOME");if (!home && pw) home = pw->pw_dir;diff --cc server/src/ui/js_fw.cindex c2d2a7d,fcd85d9..b204806--- a/server/src/ui/js_fw.c+++ b/server/src/ui/js_fw.c@@@ -27,6 -27,15 +27,15 @@@* blocks(app, restriction) true if the app is restricted in it (sdk/notify.js asks before showing* a built-in app's notification)*- * (0.8.4) Subscribed blocklists (fw/fwsub.h; docs/FIREWALL.md, "Blocklists"):++ * (0.8.5) Subscribed blocklists (fw/fwsub.h; docs/FIREWALL.md, "Blocklists"):+ * lists() { lists: [{ id, url, format, custom, on, updated, tried, domains, nets,+ * truncated, error }], busy, domains, nets }+ * setList(id, on) a catalog or custom list on or off+ * addList(url, format) → id a custom list (https only; 'hosts' | 'domains' | 'ips'); throws fw.list.*+ * removeList(id) a custom list+ * updateLists(force) 0 started, 1 nothing to do, -1 already running+ * listMatch([names], addr) the id of the enabled list that covers that destination, or null+ ** The non-network restrictions are enforced in C where the resource is handed out (sec/restrict.h:* the broker and js_media.c read this same store); adding one to a running app takes the camera* or the microphone away at once (restrict_changed).@@@ -605,7 -622,118 +622,118 @@@ const char *js_fw_counts(uint64_t *seqreturn counts_json;}-/* ---- blocklists (0.8.4) ---- */++/* ---- blocklists (0.8.5) ---- */++ static void lists_init(void) {+ if (lists_on) return;+ const char *h = getenv("HOME");+ char real[PATH_MAX], self[PATH_MAX];+ if (!h || !realpath(h, real)) return;+ ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);+ if (n <= 0) return;+ self[n] = 0;+ char *sl = strrchr(self, '/');+ if (!sl) return;+ *sl = 0;+ if (!fws_init(real, js_sys_assets(), self)) lists_on = 1;+ }++ static JSValue f_lists(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t; (void)argc; (void)argv;+ lists_init();+ pump();+ char *j = lists_on ? fws_json() : NULL;+ if (!j) return JS_NULL;+ JSValue v = JS_ParseJSON(c, j, strlen(j), "<fw.lists>");+ free(j);+ return v;+ }++ static int arg_list_id(JSContext *c, JSValueConst v, char *out) {+ if (!JS_IsString(v)) return -1;+ const char *s = JS_ToCString(c, v);+ if (!s) return -1;+ size_t n = strlen(s);+ int ok = n > 0 && n < 32;+ for (size_t i = 0; ok && i < n; i++) ok = (s[i] >= 'a' && s[i] <= 'z') || (s[i] >= '0' && s[i] <= '9') || s[i] == '-';+ if (ok) memcpy(out, s, n + 1);+ JS_FreeCString(c, s);+ return ok ? 0 : -1;+ }++ static JSValue f_set_list(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t;+ char id[32];+ if (argc < 2 || arg_list_id(c, argv[0], id)) return js_throw_code(c, "fw.list.unknown", NULL);+ lists_init();+ if (!lists_on || fws_set(id, JS_ToBool(c, argv[1]))) return js_throw_code(c, "fw.list.unknown", NULL);+ return JS_TRUE;+ }++ static JSValue f_add_list(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t;+ if (argc < 2 || !JS_IsString(argv[0]) || !JS_IsString(argv[1])) return js_throw_code(c, "fw.list.badUrl", NULL);+ lists_init();+ if (!lists_on) return js_throw_code(c, "fw.list.unavailable", NULL);+ const char *url = JS_ToCString(c, argv[0]), *fmt = JS_ToCString(c, argv[1]);+ char id[32] = "", err[64] = "fw.list.badUrl";+ int r = url && fmt && strlen(url) <= FWS_URL_MAX ? fws_add_custom(url, fmt, id, err, sizeof err) : -1;+ if (url) JS_FreeCString(c, url);+ if (fmt) JS_FreeCString(c, fmt);+ if (r) return js_throw_code(c, err, NULL);+ return JS_NewString(c, id);+ }++ static JSValue f_remove_list(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t;+ char id[32];+ if (argc < 1 || arg_list_id(c, argv[0], id)) return js_throw_code(c, "fw.list.unknown", NULL);+ lists_init();+ if (!lists_on || fws_remove_custom(id)) return js_throw_code(c, "fw.list.unknown", NULL);+ return JS_TRUE;+ }++ static JSValue f_update_lists(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t;+ lists_init();+ if (!lists_on) return JS_NewInt32(c, 1);+ return JS_NewInt32(c, fws_update(argc > 0 && JS_ToBool(c, argv[0])));+ }++ /* listMatch([names], addr): up to 8 names (each checked by the set's own normalizer) and an+ * address in text form, or null */+ static JSValue f_list_match(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t;+ if (!lists_on) return JS_NULL;+ const char *names[8] = { NULL };+ int n = 0;+ if (argc > 0 && JS_IsArray(c, argv[0])) {+ for (uint32_t i = 0; i < 8; i++) {+ JSValue v = JS_GetPropertyUint32(c, argv[0], i);+ if (JS_IsString(v)) { const char *s = JS_ToCString(c, v); if (s && strlen(s) < FW_NAME_MAX) names[n++] = s; else if (s) JS_FreeCString(c, s); }+ JS_FreeValue(c, v);+ }+ }+ uint8_t a[16] = { 0 };+ int fam = 0;+ if (argc > 1 && JS_IsString(argv[1])) {+ const char *s = JS_ToCString(c, argv[1]);+ if (s && inet_pton(AF_INET, s, a) == 1) fam = 4;+ else if (s && inet_pton(AF_INET6, s, a) == 1) fam = 6;+ if (s) JS_FreeCString(c, s);+ }+ const char *id = fws_match(names, n, fam, fam ? a : NULL);+ for (int i = 0; i < n; i++) JS_FreeCString(c, names[i]);+ return id ? JS_NewString(c, id) : JS_NULL;+ }+static const JSCFunctionListEntry fw_funcs[] = {+ JS_CFUNC_DEF("lists", 0, f_lists),+ JS_CFUNC_DEF("setList", 2, f_set_list),+ JS_CFUNC_DEF("addList", 2, f_add_list),+ JS_CFUNC_DEF("removeList", 1, f_remove_list),+ JS_CFUNC_DEF("updateLists", 1, f_update_lists),+ JS_CFUNC_DEF("listMatch", 2, f_list_match),JS_CFUNC_DEF("status", 0, f_status),JS_CFUNC_DEF("state", 0, f_state),JS_CFUNC_DEF("appRule", 1, f_app_rule),diff --cc server/src/ui/js_monitor.cindex 74c75c9,9675e00..acd4267--- a/server/src/ui/js_monitor.c+++ b/server/src/ui/js_monitor.c@@@ -454,7 -455,23 +455,23 @@@ static JSValue f_history_clear(JSContexreturn JS_NewBool(c, h && nh_clear(h) == 0);}-/* (0.8.4) netTotals() → { t, rx, tx }: the machine's byte counters now (the menu bar's network item),++/* (0.8.5) netTotals() → { t, rx, tx }: the machine's byte counters now (the menu bar's network item),+ * without starting the sampling thread. */+ static JSValue f_net_totals(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t; (void)argc; (void)argv;+ uint64_t rx, tx;+ if (netrec_totals(&rx, &tx)) return JS_NULL;+ struct timespec ts;+ clock_gettime(CLOCK_MONOTONIC, &ts);+ JSValue o = JS_NewObject(c);+ JS_SetPropertyStr(c, o, "t", JS_NewFloat64(c, ts.tv_sec * 1e3 + ts.tv_nsec / 1e6));+ JS_SetPropertyStr(c, o, "rx", JS_NewFloat64(c, (double)rx));+ JS_SetPropertyStr(c, o, "tx", JS_NewFloat64(c, (double)tx));+ return o;+ }+static const JSCFunctionListEntry monitor_funcs[] = {+ JS_CFUNC_DEF("netTotals", 0, f_net_totals),JS_CFUNC_DEF("start", 0, f_start),JS_CFUNC_DEF("stop", 0, f_stop),JS_CFUNC_DEF("want", 3, f_want),diff --cc server/tests/fw_rules_test.cindex 20cc073,6ffd048..2b286eb--- a/server/tests/fw_rules_test.c+++ b/server/tests/fw_rules_test.c@@@ -66,6 -66,14 +66,14 @@@ static void test_canon(void)const char *bad[] = { "", "desktop:", ":x", "a b", "a\"b", "/usr/../bin/sh", "/usr//bin", "/usr/bin/", "rel/path","app-lordos-lpk-a:b.scope", "x\n", "\xc3\xa1" };for (size_t i = 0; i < sizeof bad / sizeof *bad; i++) CHECK(fw_app_canon(bad[i], o, sizeof o) == -1);- /* (0.8.4) the components' scopes */++ /* (0.8.5) the components' scopes */+ CHECK(!fw_component_scope("lordos-net-mail.scope", o, sizeof o) && !strcmp(o, "lordos:mail"));+ CHECK(!fw_component_scope("lordos-net-terminal.scope", o, sizeof o) && !strcmp(o, "lordos:terminal"));+ CHECK(!fw_app_canon("lordos:store", o, sizeof o) && !strcmp(o, "lordos:store"));+ const char *badsc[] = { "lordos-net-evil.scope", "lordos-net-.scope", "lordos-net-mail", "lordos-net-mail.scope.scope",+ "lordos-maild.scope", "app-lordos-mail.scope", "lordos-net-Mail.scope", NULL };+ for (int i = 0; badsc[i]; i++) CHECK(fw_component_scope(badsc[i], o, sizeof o) == -1);+ CHECK(fw_component_ok("lists") && !fw_component_ok("") && !fw_component_ok(NULL) && !fw_component_ok("vpn"));char longid[200];memset(longid, 'a', sizeof longid - 1);longid[sizeof longid - 1] = 0;@@@ -166,6 -174,76 +174,76 @@@ static void test_mode_and_trusted(voidfw_store_free(s);}-/* 0.8.4: the deny mode ("deny silently") and subscribed blocklists (FwQuery.listed) */++/* 0.8.5: the deny mode ("deny silently") and subscribed blocklists (FwQuery.listed) */+ static FwDecision decl(FwStore *s, const char *app, const char *ip, const char *host, int listed) {+ FwQuery q = qry(app, FW_OUT, ip, 443, host);+ q.listed = listed;+ return fw_decide(s, &q);+ }++ static void test_deny_mode_and_lists(void) {+ FwStore *s = fw_store_new();+ fw_set_mode(s, FW_MODE_DENY);+ CHECK(fw_mode(s) == FW_MODE_DENY);+ FwDecision d = dec(s, "desktop:a", "8.8.8.8", 443, NULL);+ CHECK(d.verdict == FW_V_DENY && d.reason == FW_BY_MODE && d.record == 1);+ d = dec(s, "desktop:a", "192.168.1.1", 443, NULL);+ CHECK(d.verdict == FW_V_DENY && d.reason == FW_BY_MODE);+ d = dec(s, "desktop:a", "127.0.0.53", 53, NULL); /* the resolver's stub: loopback stays */+ CHECK(d.verdict == FW_V_ALLOW && d.reason == FW_BY_MODE);+ d = dec(s, "desktop:a", "::1", 631, NULL);+ CHECK(d.verdict == FW_V_ALLOW);+ d = dec(s, "desktop:a", "::ffff:127.0.0.1", 631, NULL);+ CHECK(d.verdict == FW_V_ALLOW);+ add(s, "desktop:a", FW_OUT, "example.org", FW_ALLOW); /* a rule still allows */+ d = dec(s, "desktop:a", "203.0.113.5", 443, "example.org");+ CHECK(d.verdict == FW_V_ALLOW && d.reason == FW_BY_RULE);+ CHECK(!fw_set_trusted(s, "desktop:t", 1)); /* trusted apps keep the network */+ d = dec(s, "desktop:t", "8.8.8.8", 443, NULL);+ CHECK(d.verdict == FW_V_ALLOW && d.reason == FW_BY_TRUSTED);+ /* the mode survives the file */+ size_t n;+ char *j = fw_to_json(s, &n);+ CHECK(j && strstr(j, "\"mode\":\"deny\""));+ FwStore *t = fw_store_new();+ char err[128];+ CHECK(j && !fw_from_json(t, j, n, err, sizeof err) && fw_mode(t) == FW_MODE_DENY);+ free(j);+ fw_store_free(t);+ fw_store_free(s);++ /* lists: deny before lan/internet/any rules, never before a rule naming the destination */+ s = fw_store_new();+ const char *A = "desktop:b";+ d = decl(s, A, "203.0.113.9", "tracker.example", 1);+ CHECK(d.verdict == FW_V_DENY && d.reason == FW_BY_LIST && d.record == 1);+ d = decl(s, A, "203.0.113.9", "tracker.example", 0);+ CHECK(d.verdict == FW_V_ALLOW && d.reason == FW_BY_MODE);+ add(s, A, FW_OUT, "any", FW_ALLOW);+ add(s, A, FW_OUT, "internet", FW_ALLOW);+ d = decl(s, A, "203.0.113.9", "tracker.example", 1);+ CHECK(d.verdict == FW_V_DENY && d.reason == FW_BY_LIST); /* broad rules don't override a list */+ uint32_t mine = add(s, A, FW_OUT, "tracker.example", FW_ALLOW);+ d = decl(s, A, "203.0.113.9", "tracker.example", 1);+ CHECK(d.verdict == FW_V_ALLOW && d.reason == FW_BY_RULE && d.rule_id == mine); /* the owner's allow wins */+ uint32_t net = add(s, A, FW_OUT, "198.51.100.0/24", FW_ALLOW);+ d = decl(s, A, "198.51.100.7", NULL, 1);+ CHECK(d.verdict == FW_V_ALLOW && d.rule_id == net);+ add(s, A, FW_OUT, "*.ads.example", FW_DENY);+ d = decl(s, A, "203.0.113.10", "x.ads.example", 1);+ CHECK(d.verdict == FW_V_DENY && d.reason == FW_BY_RULE); /* the owner's own deny still says so */+ CHECK(!fw_set_trusted(s, A, 1));+ d = decl(s, "desktop:c", "203.0.113.9", NULL, 1);+ CHECK(d.verdict == FW_V_DENY && d.reason == FW_BY_LIST);+ CHECK(!fw_set_trusted(s, "desktop:c", 1)); /* lists apply to trusted apps too */+ d = decl(s, "desktop:c", "203.0.113.9", NULL, 1);+ CHECK(d.verdict == FW_V_DENY && d.reason == FW_BY_LIST);+ CHECK(!fw_set_restricted(s, "desktop:d", FW_R_NO_INTERNET)); /* a restriction comes first */+ d = decl(s, "desktop:d", "203.0.113.9", NULL, 1);+ CHECK(d.verdict == FW_V_DENY && d.reason == FW_BY_RESTRICTED);+ fw_store_free(s);+ }+static void test_precedence(void) {FwStore *s = fw_store_new();fw_set_mode(s, FW_MODE_ASK);diff --cc server/tests/fwrule_input_test.mjsindex be62c11,72400f1..49d0dc0--- a/server/tests/fwrule_input_test.mjs+++ b/server/tests/fwrule_input_test.mjs@@@ -124,5 -124,25 +124,25 @@@ eq('toggle: own deny under a deny wildceq('toggle: no name → the address', toggleOp([], { addr: '203.0.113.5', proto: 'udp', port: 443 }).rule.dst, '203.0.113.5');eq('toggle: restricted → nothing', toggleOp([], q, ['no-internet']), null);-// (0.8.4) blocklists and the deny mode, the same order as rules.c (fw_rules_test's cases)++// (0.8.5) blocklists and the deny mode, the same order as rules.c (fw_rules_test's cases)+ const t = 'tracker.example';+ const L = { listed: true };+ eq('list: no rules → denied by the list', decide([], { names: [t], addr: '203.0.113.9' }, [], L), { action: 'deny', rule: null, by: 'list' });+ eq('list: off → none', decide([], { names: [t], addr: '203.0.113.9' }, [], {}), null);+ const broad = [{ id: 1, dir: 'out', dst: 'any', port: '', proto: '', action: 'allow' }, { id: 2, dir: 'out', dst: 'internet', port: '', proto: '', action: 'allow' }];+ eq('list: beats any/internet allow rules', decide(broad, { names: [t], addr: '203.0.113.9' }, [], L).by, 'list');+ const mine = [...broad, { id: 3, dir: 'out', dst: t, port: '', proto: '', action: 'allow' }];+ eq('list: the owner\'s allow for the name wins', decide(mine, { names: [t], addr: '203.0.113.9' }, [], L).rule?.id, 3);+ const net = [{ id: 4, dir: 'out', dst: '198.51.100.0/24', port: '', proto: '', action: 'allow' }];+ eq('list: an allow for the network wins', decide(net, { names: [], addr: '198.51.100.7' }, [], L).rule?.id, 4);+ eq('list: a restriction comes first', decide([], { names: [t], addr: '203.0.113.9' }, ['no-internet'], L).by, 'restricted');+ eq('toggle: listed → add an allow for the name', toggleOp([], { name: t, addr: '203.0.113.9', proto: 'tcp', port: 443 }, [], L), { op: 'add', rule: { dir: 'out', dst: t, port: '', proto: '', action: 'allow' } });+ const D = { mode: 'deny' };+ eq('deny mode: internet', decide([], { addr: '8.8.8.8' }, [], D), { action: 'deny', rule: null, by: 'mode' });+ eq('deny mode: LAN', decide([], { addr: '192.168.1.1' }, [], D).action, 'deny');+ eq('deny mode: loopback stays', decide([], { addr: '127.0.0.53', port: 53, proto: 'udp' }, [], D), null);+ eq('deny mode: ::1 stays', decide([], { addr: '::1' }, [], D), null);+ eq('deny mode: a rule allows', decide([{ id: 5, dir: 'out', dst: 'example.org', port: '', proto: '', action: 'allow' }], { names: ['example.org'], addr: '203.0.113.5' }, [], D).action, 'allow');+console.log(`fwrule-input-test: ${n} checks, ${bad} failed`);process.exit(bad ? 1 : 0);diff --cc server/tests/fwsub_test.cindex 0000000,6e07c31..b3b967bmode 000000,100644..100644--- a/server/tests/fwsub_test.c+++ b/server/tests/fwsub_test.c@@@ -1,0 -1,188 +1,188 @@@+ /* fwsub_test.c — blocklist subscriptions, lord-server's side (src/fw/fwsub.c) and the lord-fetch- * helper's request checks (0.8.4, docs/FIREWALL.md "Blocklists"). No network: the downloads are++ * helper's request checks (0.8.5, docs/FIREWALL.md "Blocklists"). No network: the downloads are+ * seeded in the cache folder; lord-fetch is only asked things it must refuse.+ * build/fwsub-test [path to build/lord-fetch] */+ #include "fw/fwsub.h"+ #include "fw/fwlists.h"+ #include "doc/wire.h"+ #include "fetch/fetchproto.h"++ #include <arpa/inet.h>+ #include <errno.h>+ #include <fcntl.h>+ #include <poll.h>+ #include <signal.h>+ #include <stdio.h>+ #include <stdlib.h>+ #include <string.h>+ #include <sys/socket.h>+ #include <sys/stat.h>+ #include <sys/wait.h>+ #include <time.h>+ #include <unistd.h>++ static int fails, checks;+ #define CHECK(c) do { checks++; if (!(c)) { fails++; fprintf(stderr, "%s:%d: failed: %s\n", __FILE__, __LINE__, #c); } } while (0)++ static void put(const char *p, const char *s) {+ FILE *f = fopen(p, "w");+ if (!f) { perror(p); exit(2); }+ fputs(s, f);+ fclose(f);+ }++ static char *slurp(const char *p) {+ FILE *f = fopen(p, "r");+ if (!f) return NULL;+ static char b[1 << 16];+ size_t n = fread(b, 1, sizeof b - 1, f);+ fclose(f);+ b[n] = 0;+ return b;+ }++ static void test_urls(void) {+ char h[256], p[512];+ int port;+ CHECK(!fws_split_url("https://lists.example.org/a/b.txt", h, sizeof h, &port, p, sizeof p) && !strcmp(h, "lists.example.org") && port == 443 && !strcmp(p, "/a/b.txt"));+ CHECK(!fws_split_url("https://Lists.Example.org:8443/x?y=1", h, sizeof h, &port, p, sizeof p) && !strcmp(h, "lists.example.org") && port == 8443 && !strcmp(p, "/x?y=1"));+ CHECK(!fws_split_url("https://example.org", h, sizeof h, &port, p, sizeof p) && !strcmp(p, "/"));+ const char *bad[] = { "http://example.org/x", "https://", "https:///x", "https://exa mple.org/", "https://example.org:0/", "https://example.org:70000/",+ "https://[email protected]/", "https://localhost/x", "https://.example.org/", "https://example..org/", "https://example.org/a b",+ "https://example.org/\x01", "https://example.org?x", "file:///etc/passwd", "https://[::1]/x", "", NULL };+ for (int i = 0; bad[i]; i++) CHECK(fws_split_url(bad[i], h, sizeof h, &port, p, sizeof p) == -1);+ }++ static int wait_job(void) {+ for (int i = 0; i < 300; i++) {+ if (fws_poll()) return 1;+ struct timespec ts = { 0, 10 * 1000 * 1000 };+ nanosleep(&ts, NULL);+ }+ return 0;+ }++ static void test_subscriptions(const char *root) {+ char p[1024], assets[256];+ snprintf(assets, sizeof assets, "%s/assets", root);+ snprintf(p, sizeof p, "%s/fw", assets);+ mkdir(assets, 0700);+ mkdir(p, 0700);+ snprintf(p, sizeof p, "%s/fw/blocklists.json", assets);+ put(p, "{\"lists\":[{\"id\":\"ads\",\"url\":\"https://lists.example.org/ads.txt\",\"format\":\"domains\",\"sub\":0},"+ "{\"id\":\"bad id\",\"url\":\"https://x.example/\",\"format\":\"domains\"},"+ "{\"id\":\"ips\",\"url\":\"http://plain.example/ips\",\"format\":\"ips\"},"+ "{\"id\":\"nets\",\"url\":\"https://lists.example.org/nets.txt\",\"format\":\"ips\"}]}");+ CHECK(!fws_init(root, assets, "/nonexistent"));+ /* seeded downloads (what lord-fetch would have written) */+ snprintf(p, sizeof p, "%s/.cache/lordos/fwlists/ads.txt", root);+ put(p, "d tracker.example\ns ads.example\n");+ snprintf(p, sizeof p, "%s/.cache/lordos/fwlists/nets.txt", root);+ put(p, "n 203.0.113.0/24\n");+ char *j = fws_json();+ CHECK(j && strstr(j, "\"id\":\"ads\"") && strstr(j, "\"id\":\"nets\"") && !strstr(j, "bad id") && !strstr(j, "plain.example"));+ free(j);+ CHECK(fws_set("nope", 1) == -1);+ CHECK(!fws_set("ads", 1));+ CHECK(wait_job());+ const char *n1[] = { "x.ads.example" }, *n2[] = { "site.example" };+ CHECK(fws_match(n1, 1, 0, NULL) && !strcmp(fws_match(n1, 1, 0, NULL), "ads"));+ CHECK(!fws_match(n2, 1, 0, NULL));+ uint8_t a[16] = { 0 };+ inet_pton(AF_INET, "203.0.113.7", a);+ CHECK(!fws_match(NULL, 0, 4, a)); /* nets is off */+ CHECK(!fws_set("nets", 1) && wait_job());+ CHECK(fws_match(NULL, 0, 4, a) && !strcmp(fws_match(NULL, 0, 4, a), "nets"));+ /* the compiled file lord-netperm reads */+ snprintf(p, sizeof p, "%s/.config/lordos/fwlists.txt", root);+ char *t = slurp(p);+ char err[64];+ FwLists *l = t ? fwl_load_text(t, strlen(t), err, sizeof err) : NULL;+ CHECK(l && fwl_domains(l) == 2 && fwl_nets(l) == 1);+ fwl_free(l);+ struct stat st;+ CHECK(!stat(p, &st) && (st.st_mode & 0777) == 0600);+ /* the config: survives, and a custom list */+ char id[32], e[64];+ CHECK(fws_add_custom("http://x.example/l", "domains", id, e, sizeof e) == -1 && !strcmp(e, "fw.list.badUrl"));+ CHECK(fws_add_custom("https://x.example/l", "csv", id, e, sizeof e) == -1 && !strcmp(e, "fw.list.badFormat"));+ CHECK(fws_add_custom("https://lists.example.org/ads.txt", "domains", id, e, sizeof e) == -1 && !strcmp(e, "fw.list.exists"));+ CHECK(!fws_add_custom("https://own.example/mine.txt", "hosts", id, e, sizeof e) && !strcmp(id, "custom-1"));+ wait_job(); /* it tries to download it (no lord-fetch here: an error, no copy) */+ snprintf(p, sizeof p, "%s/.config/lordos/fwlists.json", root);+ t = slurp(p);+ CHECK(t && strstr(t, "\"enabled\":[\"ads\",\"nets\",\"custom-1\"]") && strstr(t, "own.example"));+ j = fws_json();+ CHECK(j && strstr(j, "\"error\":\"helper\""));+ free(j);+ CHECK(fws_remove_custom("ads") == -1); /* only custom ones */+ CHECK(!fws_remove_custom("custom-1") && wait_job());+ t = slurp(p);+ CHECK(t && !strstr(t, "own.example"));+ /* turning a list off removes it from the compiled set */+ CHECK(!fws_set("ads", 0) && wait_job());+ CHECK(!fws_match(n1, 1, 0, NULL));+ }++ /* lord-fetch refuses what it must, without any network (it never opens a socket itself) */+ static void test_helper(const char *bin) {+ if (access(bin, X_OK)) { printf("fwsub-test: lord-fetch skipped: needs %s\n", bin); return; }+ int sv[2];+ CHECK(!socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sv));+ pid_t p = fork();+ if (p == 0) {+ dup2(sv[1], 3);+ char *argv[] = { "lord-fetch", NULL }, *envp[] = { NULL };+ execve(bin, argv, envp);+ _exit(127);+ }+ close(sv[1]);+ int pair[2];+ socketpair(AF_UNIX, SOCK_STREAM, 0, pair); /* a stand-in for the connected socket */+ const char *reqs[] = { "{\"host\":\"../etc\",\"path\":\"/x\",\"format\":\"domains\"}", "{\"host\":\"a.example\",\"path\":\"x\",\"format\":\"domains\"}",+ "{\"host\":\"a.example\",\"path\":\"/x\",\"format\":\"csv\"}", "not json", NULL };+ for (int i = 0; reqs[i]; i++) {+ int fd = dup(pair[0]);+ CHECK(!doc_send(sv[0], FQ_GET, (uint32_t)i + 1, reqs[i], strlen(reqs[i]), &fd, 1));+ close(fd);+ DocMsg m;+ struct pollfd pf = { sv[0], POLLIN, 0 };+ CHECK(poll(&pf, 1, 5000) == 1 && !doc_recv(sv[0], &m));+ CHECK(m.h.op == FR_ERR && m.h.id == (uint32_t)i + 1 && m.json && strstr(m.json, "bad-request"));+ doc_msg_free(&m);+ }+ /* a peer that isn't TLS: the handshake fails, it says so */+ int fd = dup(pair[0]);+ const char *ok = "{\"host\":\"a.example\",\"path\":\"/x\",\"format\":\"domains\"}";+ CHECK(!doc_send(sv[0], FQ_GET, 9, ok, strlen(ok), &fd, 1));+ close(fd);+ close(pair[0]);+ (void)!write(pair[1], "HTTP/1.1 200 OK\r\n\r\nnot tls\n", 27);+ close(pair[1]);+ DocMsg m;+ struct pollfd pf = { sv[0], POLLIN, 0 };+ CHECK(poll(&pf, 1, 35000) == 1 && !doc_recv(sv[0], &m));+ CHECK(m.h.op == FR_ERR && m.json && strstr(m.json, "\"tls\""));+ doc_msg_free(&m);+ doc_send(sv[0], FQ_END, 0, "{}", 2, NULL, 0);+ int st;+ waitpid(p, &st, 0);+ CHECK(WIFEXITED(st) && WEXITSTATUS(st) == 0);+ close(sv[0]);+ printf("fwsub-test: lord-fetch refuses bad requests and a peer without TLS: ok\n");+ }++ int main(int argc, char **argv) {+ signal(SIGPIPE, SIG_IGN);+ char root[] = "/tmp/fwsub-test.XXXXXX";+ if (!mkdtemp(root)) return 2;+ unsetenv("LORDOS_SESSIOND");+ test_urls();+ test_subscriptions(root);+ test_helper(argc > 1 ? argv[1] : "build/lord-fetch");+ char cmd[600];+ snprintf(cmd, sizeof cmd, "rm -rf '%s'", root);+ (void)!system(cmd);+ printf("fwsub-test: %d/%d passed\n", checks - fails, checks);+ return fails ? 1 : 0;+ }diff --cc server/tests/netconn_test.cindex 0000000,e7bb6fb..4220234mode 000000,100644..100644--- a/server/tests/netconn_test.c+++ b/server/tests/netconn_test.c@@@ -1,0 -1,155 +1,155 @@@-/* netconn_test.c — the components' network connectors (src/sec/netconn.c, 0.8.4):++/* netconn_test.c — the components' network connectors (src/sec/netconn.c, 0.8.5):+ * request validation on both sides, the sockets the connector makes, the real connector process+ * (this binary re-executed with --net-connector, as lord-server is) and its fail-closed start. */+ #include "sec/netconn.h"++ #include <arpa/inet.h>+ #include <errno.h>+ #include <fcntl.h>+ #include <netinet/in.h>+ #include <poll.h>+ #include <stdio.h>+ #include <stdlib.h>+ #include <string.h>+ #include <sys/socket.h>+ #include <sys/wait.h>+ #include <unistd.h>++ static int fails, checks;+ #define CHECK(c) do { checks++; if (!(c)) { fails++; fprintf(stderr, "%s:%d: failed: %s\n", __FILE__, __LINE__, #c); } } while (0)++ static NcReq good(void) {+ NcReq r;+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(443) };+ inet_pton(AF_INET, "127.0.0.1", &a.sin_addr);+ netconn_req_make(&r, AF_INET, SOCK_STREAM, (struct sockaddr *)&a, sizeof a);+ return r;+ }++ static void test_requests(void) {+ NcReq r = good();+ CHECK(!netconn_req_ok(&r) && r.fam == 4 && r.type == 1 && r.connect == 1 && r.port == 443);+ NcReq x = r; x.magic ^= 1; CHECK(netconn_req_ok(&x));+ x = r; x.fam = 5; CHECK(netconn_req_ok(&x));+ x = r; x.type = 3; CHECK(netconn_req_ok(&x));+ x = r; x.connect = 2; CHECK(netconn_req_ok(&x));+ x = r; x.port = 0; CHECK(netconn_req_ok(&x)); /* connect needs a port */+ x = r; x.addr[9] = 1; CHECK(netconn_req_ok(&x)); /* IPv4 with bytes past the 4th */+ x = r; x.scope_id = 2; CHECK(netconn_req_ok(&x));+ x = r; x.pad = 1; CHECK(netconn_req_ok(&x));+ x = r; x.connect = 0; CHECK(netconn_req_ok(&x)); /* no connect: no port either */+ x.port = 0; CHECK(!netconn_req_ok(&x));+ CHECK(netconn_req_ok(NULL));+ NcReq y;+ CHECK(netconn_req_make(&y, AF_UNIX, SOCK_STREAM, NULL, 0)); /* only internet sockets */+ CHECK(netconn_req_make(&y, AF_INET, SOCK_RAW, NULL, 0)); /* no raw sockets */+ struct sockaddr_in6 a6 = { .sin6_family = AF_INET6, .sin6_port = htons(80) };+ CHECK(netconn_req_make(&y, AF_INET, SOCK_STREAM, (struct sockaddr *)&a6, sizeof a6)); /* family mismatch */+ CHECK(netconn_req_make(&y, AF_INET6, SOCK_STREAM, (struct sockaddr *)&a6, 4)); /* short address */+ CHECK(!netconn_req_make(&y, AF_INET6, SOCK_DGRAM, (struct sockaddr *)&a6, sizeof a6) && y.fam == 6 && y.type == 2);+ x = r; x.magic = 0;+ CHECK(netconn_serve_one(&x) == -EINVAL); /* the connector checks again */+ CHECK(!strcmp(netconn_name(NC_MAIL), "mail") && !strcmp(netconn_name(NC_LISTS), "lists") && !netconn_name(NC_COUNT));+ }++ static int listener(int *port) {+ int l = socket(AF_INET, SOCK_STREAM, 0);+ struct sockaddr_in a = { .sin_family = AF_INET };+ inet_pton(AF_INET, "127.0.0.1", &a.sin_addr);+ socklen_t al = sizeof a;+ if (bind(l, (struct sockaddr *)&a, sizeof a) || listen(l, 4) || getsockname(l, (struct sockaddr *)&a, &al)) return -1;+ *port = ntohs(a.sin_port);+ return l;+ }++ static int connected(int fd) {+ struct pollfd p = { fd, POLLOUT, 0 };+ int err = 1;+ socklen_t el = sizeof err;+ return poll(&p, 1, 3000) == 1 && !getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &el) && !err;+ }++ static void test_sockets(int via_process) {+ int port = 0, l = listener(&port);+ CHECK(l >= 0);+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons((uint16_t)port) };+ inet_pton(AF_INET, "127.0.0.1", &a.sin_addr);+ int fd = netconn_socket(NC_MAIL, AF_INET, SOCK_STREAM, (struct sockaddr *)&a, sizeof a);+ CHECK(fd >= 0);+ if (fd >= 0) {+ CHECK(connected(fd));+ CHECK(fcntl(fd, F_GETFL) & O_NONBLOCK);+ CHECK(fcntl(fd, F_GETFD) & FD_CLOEXEC);+ int c = accept(l, NULL, NULL);+ CHECK(c >= 0);+ CHECK(write(fd, "x", 1) == 1);+ char b;+ CHECK(c >= 0 && read(c, &b, 1) == 1 && b == 'x');+ if (c >= 0) close(c);+ close(fd);+ }+ int u = netconn_socket(NC_PRINT, AF_INET, SOCK_DGRAM, NULL, 0);+ int t = 0;+ socklen_t tl = sizeof t;+ CHECK(u >= 0 && !getsockopt(u, SOL_SOCKET, SO_TYPE, &t, &tl) && t == SOCK_DGRAM);+ if (u >= 0) close(u);+ /* a refused connection comes back as a socket whose SO_ERROR says so */+ close(l);+ fd = netconn_socket(NC_LISTS, AF_INET, SOCK_STREAM, (struct sockaddr *)&a, sizeof a);+ CHECK(fd < 0 || !connected(fd));+ if (fd >= 0) close(fd);+ errno = 0;+ CHECK(netconn_socket(NC_COUNT, AF_INET, SOCK_STREAM, NULL, 0) == -1 && errno == EINVAL);+ printf("netconn-test: sockets %s: ok\n", via_process ? "from the connector processes" : "made in place (no LordOS session)");+ }++ /* the connector's own checks: only a known component, only with a SEQPACKET channel on fd 3 */+ static void test_connector_start(void) {+ const char *bad[] = { "evil", "terminal", "store", "", NULL }; /* terminal and store have no connector */+ for (int i = 0; bad[i]; i++) {+ pid_t p = fork();+ if (p == 0) {+ char *argv[] = { "lord-net-x", "--net-connector", (char *)bad[i], NULL };+ _exit(netconn_main(3, argv));+ }+ int st;+ waitpid(p, &st, 0);+ CHECK(WIFEXITED(st) && WEXITSTATUS(st) == 2);+ }+ pid_t p = fork();+ if (p == 0) {+ close(3);+ int f = open("/dev/null", O_RDONLY);+ if (f != 3) dup2(f, 3);+ char *argv[] = { "lord-net-mail", "--net-connector", "mail", NULL };+ _exit(netconn_main(3, argv));+ }+ int st;+ waitpid(p, &st, 0);+ CHECK(WIFEXITED(st) && WEXITSTATUS(st) == 2); /* fd 3 isn't a channel */+ }++ int main(int argc, char **argv) {+ if (argc > 1 && !strcmp(argv[1], "--net-connector")) return netconn_main(argc, argv);+ test_requests();+ test_connector_start();+ unsetenv("LORDOS_SESSIOND");+ test_sockets(0);+ /* in a "session" the sockets come from real connector processes (this binary re-executed);+ * they can't be placed in a scope from here (no lord-sessiond for this process): with+ * LORD_NETCONN_TEST_PLACED unset the test checks that the request fails closed */+ setenv("LORDOS_SESSIOND", "1", 1);+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(9) };+ inet_pton(AF_INET, "127.0.0.1", &a.sin_addr);+ int fd = netconn_socket(NC_MAIL, AF_INET, SOCK_STREAM, (struct sockaddr *)&a, sizeof a);+ if (fd >= 0) {+ /* placed after all (development cgroup delegation): the full path works */+ close(fd);+ test_sockets(1);+ } else {+ CHECK(errno == EPIPE || errno == ETIMEDOUT);+ printf("netconn-test: a connector that can't enter its scope refuses (fail closed): ok\n");+ }+ printf("netconn-test: %d/%d passed\n", checks - fails, checks);+ return fails ? 1 : 0;+ }diff --cc server/tests/netmodel_test.mjsindex 0000000,ee617b1..5d2ec24mode 000000,100644..100644--- a/server/tests/netmodel_test.mjs+++ b/server/tests/netmodel_test.mjs@@@ -1,0 -1,90 +1,90 @@@-// netmodel_test.mjs — Monitor → Network's model (sdk/netmodel.js, 0.8.4): search tokens, filters,++// netmodel_test.mjs — Monitor → Network's model (sdk/netmodel.js, 0.8.5): search tokens, filters,+ // grouping and sorting. Run by tests/run_suites.sh (needs node).+ import { parseSearch, chipFor, addChips, filterFlows, groupFlows, sortTree, fold, normView, parseCidr, cidrContains, matchesSearch } from '../../sdk/netmodel.js';++ let n = 0, bad = 0;+ const eq = (what, got, want) => {+ n++;+ const g = JSON.stringify(got), w = JSON.stringify(want);+ if (g !== w) { bad++; console.log(`✗ ${what}\n got ${g}\n want ${w}`); }+ };++ // ---- tokens ----+ eq('typed tokens become chips', parseSearch('app:Firefox domain:Example.COM video port:443'), {+ chips: [{ type: 'app', value: 'Firefox' }, { type: 'domain', value: 'example.com' }, { type: 'port', value: '443' }], rest: 'video' });+ eq('aliases', parseSearch('host:a.example addr:10.0.0.0/8 protocol:QUIC cc:ar').chips, [+ { type: 'domain', value: 'a.example' }, { type: 'ip', value: '10.0.0.0/8' }, { type: 'proto', value: 'udp' }, { type: 'country', value: 'AR' }]);+ eq('unknown type stays text', parseSearch('city:Rosario mail').rest, 'city:Rosario mail');+ eq('an IPv6 address is not a "type:"', parseSearch('2001:db8::1').chips, []);+ eq('commit: bare words get a type', parseSearch('192.0.2.0/24 53 udp AR cdn.example firefox', true).chips, [+ { type: 'ip', value: '192.0.2.0/24' }, { type: 'port', value: '53' }, { type: 'proto', value: 'udp' }, { type: 'country', value: 'AR' },+ { type: 'domain', value: 'cdn.example' }, { type: 'app', value: 'firefox' }]);+ eq('commit: an IPv6 network', chipFor('2001:db8::/32'), { type: 'ip', value: '2001:db8::/32' });+ eq('bad values are dropped', [chipFor('port:0'), chipFor('port:70000'), chipFor('ip:300.1.1.1'), chipFor('proto:icmp'), chipFor('nope:x')], [null, null, null, null, null]);+ eq('no repeated chips', addChips([{ type: 'app', value: 'a' }], [{ type: 'app', value: 'a' }, { type: 'port', value: '1' }]).length, 2);++ // ---- addresses ----+ eq('cidr', [cidrContains(parseCidr('10.0.0.0/8'), '10.2.3.4'), cidrContains(parseCidr('10.0.0.0/8'), '11.0.0.1'),+ cidrContains(parseCidr('2001:db8::/32'), '2001:db8:1::5'), cidrContains(parseCidr('2001:db8::/32'), '2001:db9::1'),+ cidrContains(parseCidr('192.0.2.0/24'), '::ffff:192.0.2.9'), cidrContains(parseCidr('192.0.2.7'), '192.0.2.7')], [true, false, true, false, true, true]);+ eq('bad cidrs', [parseCidr('10.0.0.0/33'), parseCidr('1.2.3'), parseCidr('::1::2'), parseCidr('a/b/c')], [null, null, null, null]);++ // ---- flows ----+ const F = (o) => ({ app: 'desktop:firefox', appName: 'Firefox', name: null, addr: '203.0.113.5', port: 443, proto: 'tcp', dir: 'out', rx: 0, tx: 0,+ rateRx: 0, rateTx: 0, cc: 'US', scope: 'internet', conns: 1, denied: 0, last: 0, listed: null, ...o });+ const flows = [+ F({ name: 'video.example', addr: '203.0.113.5', port: 443, proto: 'udp', rx: 9000, tx: 500, last: 30 }),+ F({ name: 'video.example', addr: '203.0.113.6', port: 443, proto: 'udp', rx: 1000, tx: 100, last: 20 }),+ F({ name: 'video.example', addr: '203.0.113.6', port: 443, proto: 'tcp', rx: 50, tx: 50, last: 10 }),+ F({ name: 'ads.example', addr: '198.51.100.1', port: 443, rx: 10, tx: 10, denied: 2, listed: 'ads', last: 40 }),+ F({ addr: '192.0.2.44', port: 8080, rx: 5, tx: 5, cc: 'AR' }),+ F({ app: 'lordos:mail', appName: 'Mail', name: 'imap.example', addr: '192.0.2.10', port: 993, rx: 700, tx: 300, cc: 'AR', last: 50 }),+ F({ app: 'lordos:terminal', appName: 'Terminal', name: null, addr: '10.0.0.5', port: 22, dir: 'out', rx: 1, tx: 1, scope: 'lan', cc: '' }),+ F({ app: 'lordos:terminal', appName: 'Terminal', addr: '192.168.1.20', port: 8000, dir: 'in', rx: 3, tx: 3, scope: 'lan', cc: '' }),+ ];++ const tree = sortTree(groupFlows(flows, 'app'), 'most');+ eq('apps, busiest first', tree.map((x) => [x.label, x.rx + x.tx]), [['Firefox', 10730], ['Mail', 1000], ['Terminal', 8]]);+ const ff = tree[0];+ eq('app → destinations', ff.children.map((x) => [x.kind, x.label]), [['domain', 'video.example'], ['domain', 'ads.example'], ['ip', '192.0.2.44']]);+ eq('a name with two addresses has an address level', ff.children[0].children.map((x) => [x.kind, x.label]), [['ip', '203.0.113.5'], ['ip', '203.0.113.6']]);+ eq('… and ports under each address', ff.children[0].children[1].children.map((x) => x.label), ['UDP 443', 'TCP 443']);+ eq('a name with one address goes straight to its ports', ff.children[1].children.map((x) => [x.kind, x.label]), [['port', 'TCP 443']]);+ eq('an address row has its ports', ff.children[2].children.map((x) => x.label), ['TCP 8080']);+ eq('sums at every level', [ff.children[0].rx, ff.children[0].tx, ff.children[0].conns], [10050, 650, 3]);+ eq('denied and listed go up', [ff.denied, ff.listed, ff.children[1].listed], [2, 'ads', 'ads']);++ eq('group by domain', sortTree(groupFlows(flows, 'domain'), 'name').map((x) => x.label),+ ['10.0.0.5', '192.0.2.44', '192.168.1.20', 'ads.example', 'imap.example', 'video.example']);+ eq('domain → apps', groupFlows(flows, 'domain').find((x) => x.label === 'video.example').children.map((x) => x.label), ['Firefox']);+ eq('group by IP', groupFlows(flows, 'ip').length, 7);+ eq('group by port', sortTree(groupFlows(flows, 'port'), 'most').map((x) => x.label), ['UDP 443', 'TCP 993', 'TCP 443', 'TCP 8080', 'TCP 8000', 'TCP 22']);+ eq('group by country', sortTree(groupFlows(flows, 'country'), 'most').map((x) => x.label), ['US', 'AR', 'lan']);+ eq('sort least', sortTree(groupFlows(flows, 'app'), 'least').map((x) => x.label), ['Terminal', 'Mail', 'Firefox']);+ eq('sort recent', sortTree(groupFlows(flows, 'app'), 'recent').map((x) => x.label), ['Mail', 'Firefox', 'Terminal']);+ eq('sort conns', sortTree(groupFlows(flows, 'app'), 'conns').map((x) => x.label), ['Firefox', 'Terminal', 'Mail']);++ // ---- filters ----+ const only = (f, q = {}, ctx = {}) => filterFlows(flows, f, q, ctx).length;+ eq('direction', [only({ dir: 'in' }), only({ dir: 'out' }), only({})], [1, 7, 8]);+ eq('protocol', [only({ proto: 'udp' }), only({ proto: 'tcp' })], [2, 6]);+ eq('status', [only({ status: 'denied' }), only({ status: 'allowed' }), only({ status: 'rules' }, {}, { hasRule: (f) => f.app === 'lordos:mail' })], [1, 7, 1]);+ eq('search: app chip', only({}, parseSearch('app:mail')), 1);+ eq('search: app + domain chips combine', only({}, parseSearch('app:firefox domain:example')), 4);+ eq('search: a parent domain covers its names', only({}, parseSearch('domain:example')), 5);+ eq('search: two chips of one type: either', only({}, parseSearch('port:22 port:993')), 2);+ eq('search: network chip', only({}, parseSearch('ip:192.0.2.0/24')), 2);+ eq('search: country by code and by name', [only({}, parseSearch('country:AR')), only({}, parseSearch('country:argen'), { countryName: (cc) => (cc === 'AR' ? 'Argentina' : cc) })], [2, 2]);+ eq('search: free text', only({}, { chips: [], rest: 'imap' }), 1);+ eq('search: any name of a CNAME chain', matchesSearch(F({ name: 'deb.debian.org', names: ['deb.debian.org', 'debian.map.cdn.example'] }), parseSearch('domain:cdn.example')), true);+ eq('search: free text needs every word', only({}, { chips: [], rest: 'firefox 8080' }), 1);+ eq('search: nothing', matchesSearch(flows[0], { chips: [{ type: 'port', value: '1' }] }), false);++ // ---- fold and the saved view ----+ eq('fold', fold([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 8), { list: [1, 2, 3, 4, 5, 6, 7, 8], more: 2 });+ eq('fold all', fold([1, 2, 3], 2, true).more, 0);+ eq('view defaults', normView(null), { group: 'app', dir: 'all', proto: 'all', status: 'all', sort: 'most' });+ eq('view keeps only known values', normView({ group: 'port', dir: 'sideways', sort: 'least', x: 1 }), { group: 'port', dir: 'all', proto: 'all', status: 'all', sort: 'least' });++ console.log(`netmodel-test: ${n} checks, ${bad} failed`);+ process.exit(bad ? 1 : 0);diff --cc server/tests/run_suites.shindex 8a5aaf4,4ad9da6..3e76503--- a/server/tests/run_suites.sh+++ b/server/tests/run_suites.sh@@@ -168,6 -165,9 +168,9 @@@ EO# the overlay scroll bar's model (sdk/scrollbar.js): geometry, thumb hit-test and drag, fade timingif have node; then run "scrollbar-model-test (sdk/scrollbar.js)" node tests/scrollbar_model_test.mjselse skip "scrollbar-model-test" "node"; fi- # (0.8.4) Monitor → Network's model (sdk/netmodel.js): search tokens, filters, the tree, sorting++ # (0.8.5) Monitor → Network's model (sdk/netmodel.js): search tokens, filters, the tree, sorting+ if have node; then run "netmodel-test (sdk/netmodel.js)" node tests/netmodel_test.mjs+ else skip "netmodel-test" "node"; fi}full() {diff --cc tools/iso/mkdeb.shindex 462d9dc,87473c3..502ec2e--- a/tools/iso/mkdeb.sh+++ b/tools/iso/mkdeb.sh@@@ -71,6 -69,9 +71,9 @@@ strip --strip-unneeded "$L/bin/lord-ser# lord-maild: IMAP/SMTP/CalDAV/CardDAV with TLS for Mail (docs/MAIL.md); lord-server only launches the one in its own folder[ -x server/build/lord-maild ] && install -m 755 server/build/lord-maild "$L/bin/lord-maild"[ -x "$L/bin/lord-maild" ] && { strip --strip-unneeded "$L/bin/lord-maild" 2>/dev/null || true; }-# lord-fetch (0.8.4): downloads the subscribed blocklists over HTTPS, sandboxed (docs/FIREWALL.md, "Blocklists")++# lord-fetch (0.8.5): downloads the subscribed blocklists over HTTPS, sandboxed (docs/FIREWALL.md, "Blocklists")+ [ -x server/build/lord-fetch ] && install -m 755 server/build/lord-fetch "$L/bin/lord-fetch"+ [ -x "$L/bin/lord-fetch" ] && { strip --strip-unneeded "$L/bin/lord-fetch" 2>/dev/null || true; }# FIDO2 security keys reachable by the session user (lord-sessiond sessions have no logind seat)install -d "$PKG/usr/lib/udev/rules.d"install -m 644 packaging/udev/71-lordos-fido.rules "$PKG/usr/lib/udev/rules.d/71-lordos-fido.rules"