Skip to content

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.

Monitor model and native plumbing for the second-generation Network tab

Federico Pereira7ecd841d21c7
diff --git a/sdk/fwrule.js b/sdk/fwrule.js
index 6c833bb..6c669bc 100644
--- a/sdk/fwrule.js
+++ b/sdk/fwrule.js
@@ -272,7 +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
+// 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);
@@ -287,10 +298,16 @@ export function decide(rules, { names = [], addr = '', proto = 'tcp', port = 0,
if (!p.ok || (p.port && (port < p.lo || port > p.hi))) return false;
return destMatches(r, ns, a, lan);
});
- if (!hits.length) return null;
+ const fallback = () => {
+ if (opts.listed) return { action: 'deny', rule: null, by: 'list' };
+ if (opts.mode === 'deny' && !isLoopback(a)) return { action: 'deny', rule: null, by: 'mode' };
+ return null;
+ };
+ if (!hits.length) return fallback();
// as rules.c weighs them: an exact name also counts its labels (a CNAME chain's longest name wins)
const spec = (r) => { const d = parseDest(r.dst); return d.ok && d.kind === 'domain' ? SC_EXACT + d.domain.split('.').length : specificity(r); };
const best = [...hits].sort((x, y) => spec(y) - spec(x) || comparePrecedence(x, y))[0];
+ if (opts.listed && spec(best) < SC_CIDR) return { action: 'deny', rule: null, by: 'list' };
return { action: best.action, rule: best, by: 'rule' };
}
@@ -298,9 +315,9 @@ export function decide(rules, { names = [], addr = '', proto = 'tcp', port = 0,
// port and protocol, set to the other verdict; if dropping that rule already gives the other
// verdict, it is removed instead of piling up rules (like the Monitor's per-app switch).
// → { op: 'add', rule } | { op: 'update', id, rule } | { op: 'remove', id } | null
-export function toggleOp(rules, { name, addr, proto = 'tcp', port = 0 }, restricted = []) {
+export function toggleOp(rules, { name, addr, proto = 'tcp', port = 0 }, restricted = [], opts = {}) {
const q = { names: name ? [name] : [], addr, proto, port };
- const now = decide(rules, q, restricted);
+ const now = decide(rules, q, restricted, opts);
if (now?.by === 'restricted') return null;
const allowedNow = now ? now.action === 'allow' : true; // no rule: the mode ("ask" is applied as silent)
const target = allowedNow ? 'deny' : 'allow';
@@ -308,7 +325,7 @@ export function toggleOp(rules, { name, addr, proto = 'tcp', port = 0 }, restric
if (!dst) return null;
const own = (rules || []).find((r) => (r.dir || 'out') === 'out' && r.dst === dst && !r.port && !r.proto);
if (own) {
- const without = decide(rules.filter((r) => r !== own), q, restricted);
+ const without = decide(rules.filter((r) => r !== own), q, restricted, opts);
const allowedWithout = without ? without.action === 'allow' : true;
if ((allowedWithout ? 'allow' : 'deny') === target) return { op: 'remove', id: own.id };
return { op: 'update', id: own.id, rule: { dir: 'out', dst, port: '', proto: '', action: target } };
diff --git a/sdk/index.js b/sdk/index.js
index 876e321..caa4380 100644
--- a/sdk/index.js
+++ b/sdk/index.js
@@ -52,6 +52,7 @@ export {
export { 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 { packages, packageList, refreshPackages, packageFile, loadWasm } from './packages.js';
import { refreshPackages } from './packages.js';
export {
diff --git a/sdk/monitor.js b/sdk/monitor.js
index 32fd372..7c388f6 100644
--- a/sdk/monitor.js
+++ b/sdk/monitor.js
@@ -163,8 +163,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)
+// 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 +185,14 @@ export const firewall = {
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,
+ // 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 --git a/sdk/netmodel.js b/sdk/netmodel.js
new file mode 100644
index 0000000..b8d0ba6
--- /dev/null
+++ b/sdk/netmodel.js
@@ -0,0 +1,290 @@
+// netmodel.js — Monitor → Network's list, second generation (0.8.4, 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); 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
+// 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 n = lc(f.name), v = lc(c.value); 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.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 --git a/server/Makefile b/server/Makefile
index 3e369ec..30b6c27 100644
--- a/server/Makefile
+++ b/server/Makefile
@@ -346,7 +346,7 @@ build/mmdb-test: tests/mmdb_test.c src/monitor/mmdb.c src/monitor/mmdb.h src/pkg
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/mmdb_test.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o -lm
# drawing time of the Monitor's vector map (not a test: it measures; see docs/MONITOR.md)
build/map-bench: tests/map_bench.c src/monitor/map.c src/monitor/map.h src/monitor/mon.c src/monitor/disktemp.c src/monitor/conn.c src/monitor/procctl.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o
- $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/map_bench.c src/monitor/map.c src/monitor/mon.c src/monitor/disktemp.c src/monitor/conn.c src/monitor/procctl.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o -lm -lpthread
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/map_bench.c src/monitor/map.c src/monitor/mon.c src/monitor/disktemp.c src/monitor/conn.c src/monitor/procctl.c src/monitor/mmdb.c src/pkg/xz.c src/fw/rules.c src/fw/fwmap.c src/sec/json.c src/sec/cgroup.c build/obj/ui/stb.o -lm -lpthread
# Monitor process actions (src/monitor/procctl.c): the protected list, stat parsing, a signal that
# refuses a stale start time (PID reuse), TERM/KILL on a child, and the Get Info JSON
test: build/procctl-test
diff --git a/server/src/monitor/conn.c b/server/src/monitor/conn.c
index e091990..0f54821 100644
--- a/server/src/monitor/conn.c
+++ b/server/src/monitor/conn.c
@@ -6,12 +6,20 @@
* 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
+ * 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.
+ *
* 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>
#include <dirent.h>
+#include <fcntl.h>
#include <errno.h>
#include <limits.h>
#include <linux/inet_diag.h>
@@ -37,9 +45,14 @@ typedef struct {
uint8_t src[16], dst[16];
uint16_t sport, dport;
uint64_t sent, recv;
+ uint64_t cg; /* the socket's cgroup id (0: the kernel didn't say) */
int bytes; /* sent/recv valid (TCP with tcp_info) */
} Sock;
+#ifndef INET_DIAG_CGROUP_ID
+#define INET_DIAG_CGROUP_ID 21
+#endif
+
static Sock socks[MAX_SOCK];
static int nsock;
@@ -84,6 +97,7 @@ static int dump(int fd, int fam, int proto) {
/* attributes: tcp_info */
int alen = (int)(h->nlmsg_len - NLMSG_LENGTH(sizeof *m));
for (struct rtattr *a = (struct rtattr *)(m + 1); RTA_OK(a, alen); a = RTA_NEXT(a, alen)) {
+ if (a->rta_type == INET_DIAG_CGROUP_ID && RTA_PAYLOAD(a) >= 8) { memcpy(&s->cg, RTA_DATA(a), 8); continue; }
if (a->rta_type != INET_DIAG_INFO) continue;
const struct tcp_info *ti = RTA_DATA(a);
size_t need = offsetof(struct tcp_info, tcpi_bytes_received) + sizeof ti->tcpi_bytes_received;
@@ -192,6 +206,58 @@ static const char *const TCP_STATE[] = { "", "ESTABLISHED", "SYN_SENT", "SYN_REC
"CLOSE", "CLOSE_WAIT", "LAST_ACK", "LISTEN", "CLOSING", "NEW_SYN_RECV" };
/* Name and executable of a pid (small per-sample cache). */
+/* ---- cgroup id → app (the session's scopes, rescanned every 5 s) ---- */
+
+static struct { uint64_t id; char app[FW_APP_MAX]; } scopes[256];
+static int nscopes;
+static double scopes_t;
+
+static uint64_t cg_id(int dfd, const char *name) {
+ struct { struct file_handle fh; unsigned char b[64]; } h;
+ h.fh.handle_bytes = sizeof h.b;
+ int mnt;
+ if (name_to_handle_at(dfd, name, &h.fh, &mnt, 0) || h.fh.handle_bytes < 8) return 0;
+ uint64_t id;
+ memcpy(&id, h.fh.f_handle, 8);
+ return id;
+}
+
+static void scopes_scan(void) {
+ if (mon_now_ms() - scopes_t < 5000 && scopes_t) return;
+ scopes_t = mon_now_ms();
+ nscopes = 0;
+ const char *self = cgroup_self(); /* ".../lordos-session-<uid>/server" */
+ char dir[PATH_MAX];
+ if (!self[0] || (size_t)snprintf(dir, sizeof dir, "/sys/fs/cgroup%s", self) >= sizeof dir) return;
+ char *sl = strrchr(dir, '/');
+ if (!sl || strcmp(sl, "/server")) return; /* not a LordOS session */
+ *sl = 0;
+ int dfd = open(dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+ DIR *d = dfd >= 0 ? fdopendir(dup(dfd)) : NULL;
+ struct dirent *e;
+ while (d && (e = readdir(d)) && nscopes < 256) {
+ if (e->d_type != DT_DIR || e->d_name[0] == '.') continue;
+ char app[FW_APP_MAX];
+ if (!strncmp(e->d_name, "lordos-net-", 11)) { if (fw_component_scope(e->d_name, app, sizeof app)) continue; }
+ else if (!strncmp(e->d_name, "app-lordos-", 11)) { if (fw_app_canon(e->d_name, app, sizeof app)) continue; }
+ else if (!strcmp(e->d_name, "server")) snprintf(app, sizeof app, "lordos");
+ else continue;
+ uint64_t id = cg_id(dfd, e->d_name);
+ if (!id) continue;
+ scopes[nscopes].id = id;
+ snprintf(scopes[nscopes].app, sizeof scopes[nscopes].app, "%s", app);
+ nscopes++;
+ }
+ if (d) closedir(d);
+ if (dfd >= 0) close(dfd);
+}
+
+static const char *scope_app_of(uint64_t cg) {
+ if (!cg) return "";
+ for (int i = 0; i < nscopes; i++) if (scopes[i].id == cg) return scopes[i].app;
+ return "";
+}
+
static struct { int pid; char name[64], exe[PATH_MAX]; } pinfo[256];
static int npinfo;
@@ -232,6 +298,7 @@ void conn_scan(Buf *b, const Mmdb *geo) {
if (socks[i].uid == me && socks[i].inode) map_find(socks[i].inode, 1);
}
npinfo = 0;
+ scopes_scan();
int self = (int)getpid(), n = 0;
mon_buf_printf(b, "{\"t\":%.0f,\"ok\":true,\"list\":[", mon_wall_ms());
for (int i = 0; i < nsock; i++) {
@@ -269,6 +336,8 @@ void conn_scan(Buf *b, const Mmdb *geo) {
mon_buf_str(b, pi >= 0 ? pinfo[pi].name : "");
mon_buf_printf(b, ",\"exe\":");
mon_buf_str(b, pi >= 0 ? pinfo[pi].exe : "");
+ mon_buf_printf(b, ",\"scope\":");
+ mon_buf_str(b, scope_app_of(s->cg));
if (s->bytes) mon_buf_printf(b, ",\"sent\":%llu,\"recv\":%llu}", (unsigned long long)s->sent, (unsigned long long)s->recv);
else mon_buf_printf(b, ",\"sent\":null,\"recv\":null}");
n++;
diff --git a/server/src/monitor/netrec.c b/server/src/monitor/netrec.c
index 033d93e..244f6b1 100644
--- a/server/src/monitor/netrec.c
+++ b/server/src/monitor/netrec.c
@@ -169,6 +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
+ * 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 --git a/server/src/monitor/netrec.h b/server/src/monitor/netrec.h
index 879fccd..7745ed5 100644
--- a/server/src/monitor/netrec.h
+++ b/server/src/monitor/netrec.h
@@ -16,5 +16,6 @@ double netrec_timeout(void); /* ms until the next tick, -1 when off *
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 */
#endif
diff --git a/server/src/ui/js_fw.c b/server/src/ui/js_fw.c
index 4576a57..fcd85d9 100644
--- a/server/src/ui/js_fw.c
+++ b/server/src/ui/js_fw.c
@@ -705,7 +705,7 @@ static JSValue f_update_lists(JSContext *c, JSValueConst t, int argc, JSValueCon
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];
+ const char *names[8] = { NULL };
int n = 0;
if (argc > 0 && JS_IsArray(c, argv[0])) {
for (uint32_t i = 0; i < 8; i++) {
diff --git a/server/src/ui/js_monitor.c b/server/src/ui/js_monitor.c
index 74c75c9..9675e00 100644
--- a/server/src/ui/js_monitor.c
+++ b/server/src/ui/js_monitor.c
@@ -45,6 +45,7 @@
#include <strings.h>
#include <signal.h>
#include <sys/stat.h>
+#include <time.h>
#include <unistd.h>
static uint64_t seq_sample, seq_procs, seq_conns, seq_detail, seq_temps;
@@ -454,7 +455,23 @@ static JSValue f_history_clear(JSContext *c, JSValueConst t, int argc, JSValueCo
return 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),
+ * 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 --git a/server/tests/fwrule_input_test.mjs b/server/tests/fwrule_input_test.mjs
index be62c11..72400f1 100644
--- a/server/tests/fwrule_input_test.mjs
+++ b/server/tests/fwrule_input_test.mjs
@@ -124,5 +124,25 @@ eq('toggle: own deny under a deny wildcard → update to allow', toggleOp(wild,
eq('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)
+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 --git a/server/tests/netmodel_test.mjs b/server/tests/netmodel_test.mjs
new file mode 100644
index 0000000..83e9c61
--- /dev/null
+++ b/server/tests/netmodel_test.mjs
@@ -0,0 +1,89 @@
+// netmodel_test.mjs — Monitor → Network's model (sdk/netmodel.js, 0.8.4): 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: 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 --git a/server/tests/run_suites.sh b/server/tests/run_suites.sh
index 978a88b..4ad9da6 100644
--- a/server/tests/run_suites.sh
+++ b/server/tests/run_suites.sh
@@ -165,6 +165,9 @@ EOF
# the overlay scroll bar's model (sdk/scrollbar.js): geometry, thumb hit-test and drag, fade timing
if have node; then run "scrollbar-model-test (sdk/scrollbar.js)" node tests/scrollbar_model_test.mjs
else skip "scrollbar-model-test" "node"; fi
+ # (0.8.4) 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() {