Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions bin/iak-network.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/usr/bin/env node
// SPDX-License-Identifier: AGPL-3.0-only
import {readFile} from 'node:fs/promises';
import {collectNetwork,publishNetwork} from '../src/network-collector.mjs';
const [configFile,action='collect']=process.argv.slice(2);
if(!configFile||!['collect','publish'].includes(action))throw Error('Usage: iak-network /absolute/config.json [collect|publish]');
const config=JSON.parse(await readFile(configFile,'utf8'));
const network=collectNetwork({peers:config.peers||[]});
console.log(JSON.stringify(action==='publish'?await publishNetwork(config,network):network,null,2));
42 changes: 42 additions & 0 deletions docs/network-collector.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Connection inventory collector (review draft)

`node bin/iak-network.mjs /absolute/config.json` collects only, with no API write.
Add `publish` to PATCH the `network` field of an existing device slot. Configure
`baseUrl` as the approved API endpoint (localhost or literal tailnet address), `userId`, `deviceId`, absolute `keyFile`,
and `peers` as `{id: existingPeerSlot, address: literalIPv4}` entries.

Linux reports OS interfaces, canonical IPv4 subnets, readable negotiated link
speeds and `ip -j route get` evidence. Missing commands/speeds remain unknown.
Tailscale never acquires a NIC throughput ceiling. macOS interface kind stays
unknown until a platform-specific inventory is added; it is not guessed Ethernet.
Remote interface names are not inferred. No traffic benchmark or listener starts.
There are no fixture measurements, rates or historical timestamps in the collector.

Publishing first reads the existing slot, preserves measured-transfer fields and
other network metadata, then patches only network. It requires an existing slot;
it never registers an identity. This read/merge/write can race another network
publisher: use a single owner until server-side field merge/versioning exists.
Peer route records refreshed by this collector do not replace actual bandwidth
measurements. Ongoing scheduling, HTTP-memory benchmarking and fleet installation
remain separate. This draft has not published to production.

Review revision: host addresses are omitted from reports, Tailscale /32 prefixes
are omitted, and only canonical physical subnet prefixes remain. Route changes
invalidate old throughput and mark its old route; measurements are retained only
when route and local interface match. Links absent from the current complete
collection are removed. Linux Thunderbolt is identified by name; InfiniBand and
unrecognized interface kinds remain unknown. Every interface and link is timestamped.

Real-host preflight: asus1's SSH environment has no `node` executable on PATH,
so the remote dry run did not execute. No runtime was installed. Deployment needs
a verified runtime path or an alternate collector bridge before publication.


Current authorized target plan: Petrus approved host addresses on 22 Nov; the
collector now includes them. The configured base URL may target localhost or a
literal Tailscale IPv4, including local asus3, with an /api/v1 suffix. Redirects
are rejected to avoid credential forwarding. Fleet publication is intended for
the local installation; the room remains on groupmind.one. No write has occurred.
The local asus3 stack is on an older separate Groupmind.one checkout and lacks
today's FleetConnections source; API compatibility/update requires review before
using the collector against it.
62 changes: 62 additions & 0 deletions src/network-collector.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// SPDX-License-Identifier: AGPL-3.0-only
import { networkInterfaces, platform } from 'node:os';
import { readFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { isIP } from 'node:net';
const run = (bin,args) => {try{return execFileSync(bin,args,{encoding:'utf8',timeout:3000,stdio:['ignore','pipe','ignore']});}catch{return '';}};
const speed = name => {try{const n=Number(readFileSync(`/sys/class/net/${name}/speed`,'utf8'));return n>0?n:null;}catch{return null;}};
export function collectNetwork({peers=[], interfaces=networkInterfaces(), os=platform(), command=run, readSpeed=speed, measuredAt=new Date().toISOString()}={}) {
const inventory=[];
for (const [name, addresses] of Object.entries(interfaces)) {
const ipv4=(addresses||[]).filter(a=>!a.internal && (a.family==='IPv4'||a.family===4));
if(!ipv4.length || /^(docker|veth|br-|lo$|virbr|vmnet)/.test(name))continue;
const tailscale=ipv4.some(a=>a.address.startsWith('100.') && +a.address.split('.')[1]>=64 && +a.address.split('.')[1]<=127);
let kind=tailscale?'tailscale':/^thunderbolt/.test(name)?'thunderbolt':/^(wl|wifi)/.test(name)?'wifi':/^(eth|en)/.test(name)?'ethernet':'unknown';
if(os==='darwin'&&!tailscale)kind='unknown'; // No guessed Wi-Fi/Thunderbolt kind on macOS.
inventory.push({name,kind,speed_mbps:tailscale?null:os==='linux'?readSpeed(name):null,networks:tailscale?[]:ipv4.flatMap(a=>{ const parts=(a.cidr||'').split('/'),prefix=Number(parts[1]);if(parts.length!==2||!Number.isInteger(prefix)||prefix<0||prefix>32)return [];const value=a.address.split('.').reduce((n,b)=>(n*256+Number(b))>>>0,0),mask=prefix===0?0:(0xffffffff << (32-prefix))>>>0;const net=(value&mask)>>>0;return [[24,16,8,0].map(shift=>(net>>>shift)&255).join('.')+'/'+prefix];}),addresses:ipv4.map(a=>a.address),measured_at:measuredAt});
}
const links=[];
for(const peer of peers) {
if(!/^[a-zA-Z0-9_-]+$/.test(peer.id||'') || isIP(peer.address)!==4)throw Error('Peer requires slot id and literal IPv4');
if(os!=='linux')continue;
const output=command('ip',['-j','route','get',peer.address]);let route;
try{route=JSON.parse(output)[0];}catch{continue;}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Distinguish failed route collection from removed links

When ip is missing, times out, or returns malformed output, run returns an empty string and this catch silently omits the configured peer. mergeNetwork then treats the result as a complete inventory, and publishNetwork patches away the peer's existing link and independent transfer measurement. Thus a temporary collection failure permanently deletes previously collected data even though the peer is still configured. Track collection failures and either abort publication or preserve the affected records, while still removing peers genuinely absent from the configuration.

Useful? React with 👍 / 👎.

const iface=inventory.find(i=>i.name===route?.dev);if(!iface)continue;
links.push({peer_id:peer.id,local_interface:iface.name,remote_interface:null,route:iface.kind==='tailscale'?'tailscale':'lan',observed_at:measuredAt,evidence:'ip-route-get'});
}
return {interfaces:inventory,links,collected_at:measuredAt,collector:'iak-network-v1'};
}
export function mergeNetwork(previous={}, collected) {
// Preserve independent measured transfers; route collection is not a bandwidth test.
const old=Array.isArray(previous.links)?previous.links:[];
const links=collected.links.map(r=>{
const prior=old.find(o=>o.peer_id===r.peer_id);
if(!prior?.measurement)return r;
const samePath=(prior.measurement_route||prior.route)===r.route && prior.local_interface===r.local_interface;
if(!samePath)return {...r,measurement_stale:true,previous_measurement_route:prior.measurement_route||prior.route||'unknown'};
return {...r,measurement:prior.measurement,measurement_route:prior.measurement_route||prior.route};
});
// A collection is a complete current route inventory, not an append-only log.
return {...previous,...collected,links};
}
export async function publishNetwork(c, collected, {fetchImpl=fetch}={}) {
const target=new URL(c.baseUrl);
const host=target.hostname;
const tailnet=isIP(host)===4 && host.startsWith('100.') && +host.split('.')[1]>=64 && +host.split('.')[1]<=127;
const local=['localhost','127.0.0.1','[::1]'].includes(host);
if (!['http:','https:'].includes(target.protocol) || target.username || target.password || target.search || target.hash || (!tailnet&&!local&&c.baseUrl!=='https://groupmind.one/api/v1')) throw Error('Unsupported publish destination');
if (!target.pathname.endsWith('/api/v1')) throw Error('API base path must end in /api/v1');
for(const k of ['userId','deviceId'])if(!/^[a-zA-Z0-9_-]+$/.test(c[k]||''))throw Error('Invalid intent identifier');
const key=(await import('node:fs/promises')).readFile;
const token=(await key(c.keyFile,'utf8')).trim();
const headers={Authorization:`Bearer ${token}`,'Content-Type':'application/json','Cache-Control':'no-cache'};
const endpoint=`${c.baseUrl}/intent/${encodeURIComponent(c.userId)}`;
const existing=await fetchImpl(endpoint,{headers,redirect:'error',signal:AbortSignal.timeout(15000)});
if(!existing.ok)throw Error(`Intent read HTTP ${existing.status}`);
const intent=await existing.json(),slot=intent.devices?.[c.deviceId];
if(!slot)throw Error('Existing device slot required; collector does not invent fleet identities');
const network=mergeNetwork(slot.network,collected);
const response=await fetchImpl(`${endpoint}/${encodeURIComponent(c.deviceId)}`,{method:'PATCH',headers,redirect:'error',body:JSON.stringify({network}),signal:AbortSignal.timeout(15000)});
if(!response.ok)throw Error(`Intent publish HTTP ${response.status}`);
return {deviceId:c.deviceId,interfaces:network.interfaces.length,links:network.links.length};
}
36 changes: 36 additions & 0 deletions test/network-collector.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import test from 'node:test';import assert from 'node:assert/strict';
import {collectNetwork,mergeNetwork} from '../src/network-collector.mjs';
const interfaces={eth0:[{family:'IPv4',internal:false,address:'10.2.0.1',cidr:'10.2.0.1/24'}],tailscale0:[{family:'IPv4',internal:false,address:'100.64.2.1',cidr:'100.64.2.1/32'}],docker0:[{family:'IPv4',internal:false,address:'172.17.0.1'}]};
test('collects actual route/interface evidence without inventing throughput',()=>{
const n=collectNetwork({interfaces,os:'linux',readSpeed:()=>25000,peers:[{id:'m5',address:'100.88.157.24'}],command:()=>JSON.stringify([{dev:'tailscale0'}])});
assert.equal(n.interfaces.length,2);assert.equal(n.interfaces[1].speed_mbps,null);assert.equal(n.links[0].route,'tailscale');assert.equal(n.links[0].remote_interface,null);assert.equal(n.links[0].measurement,undefined);
});
test('route refresh preserves independent measured transfers',()=>{
const measurement={kind:'http-memory',bytes:1024,seconds:1,measured_at:'2026-11-22T00:00:00Z'};
const n=mergeNetwork({links:[{peer_id:'m5',route:'tailscale',local_interface:'tailscale0',measurement}]},{interfaces:[],links:[{peer_id:'m5',route:'tailscale',local_interface:'tailscale0'}]});assert.deepEqual(n.links[0].measurement,measurement);
});
test('peer names cannot inject commands or resolve arbitrary hostnames',()=>{
for(const peer of [{id:'x',address:'$(bad)'},{id:'x;bad',address:'1.2.3.4'}])assert.throws(()=>collectNetwork({interfaces,os:'linux',peers:[peer]}));
});
test('network prefixes are canonical rather than host CIDRs',()=>{
const n=collectNetwork({interfaces,os:'linux',readSpeed:()=>null});assert.deepEqual(n.interfaces[0].networks,['10.2.0.0/24']);
});
test('route changes invalidate old throughput and removed peers disappear',()=>{
const n=mergeNetwork({links:[{peer_id:'m5',route:'lan',local_interface:'eth0',measurement:{kind:'http-memory'}},{peer_id:'gone'}]},{interfaces:[],links:[{peer_id:'m5',route:'tailscale',local_interface:'tailscale0'}]});assert.equal(n.links.length,1);assert.equal(n.links[0].measurement,undefined);assert.equal(n.links[0].measurement_stale,true);
});
test('special interfaces are not labelled Ethernet and authorized host addresses are retained',()=>{
const i={ib0:interfaces.eth0,thunderbolt0:interfaces.eth0,tailscale0:interfaces.tailscale0};const n=collectNetwork({interfaces:i,os:'linux',readSpeed:()=>null});assert.equal(n.interfaces[0].kind,'unknown');assert.equal(n.interfaces[1].kind,'thunderbolt');assert.deepEqual(n.interfaces[0].addresses,['10.2.0.1']);assert.deepEqual(n.interfaces[2].networks,[]);
});
test('publisher patches only network on an existing slot and rejects absent slots',async t=>{
const {mkdtemp,writeFile,rm}=await import('node:fs/promises');const {tmpdir}=await import('node:os');const {join}=await import('node:path');const {publishNetwork}=await import('../src/network-collector.mjs');
const dir=await mkdtemp(join(tmpdir(),'iak-net-'));t.after(()=>rm(dir,{recursive:true,force:true}));const keyFile=join(dir,'key');await writeFile(keyFile,'private-test-key');
const c={baseUrl:'https://groupmind.one/api/v1',userId:'petrus',deviceId:'asus1',keyFile};let patched;
await publishNetwork(c,{interfaces:[],links:[]},{fetchImpl:async(u,o)=>{if(o.method==='PATCH'){patched=JSON.parse(o.body);return {ok:true};}return {ok:true,json:async()=>({devices:{asus1:{name:'keep',network:{note:'preserved'}}}})};}});
assert.deepEqual(Object.keys(patched),['network']);assert.equal(patched.network.note,'preserved');
await assert.rejects(publishNetwork(c,{interfaces:[],links:[]},{fetchImpl:async()=>({ok:true,json:async()=>({devices:{}})})}),/Existing device slot required/);
});
test('publisher allows explicit local API targets and rejects arbitrary destinations',async()=>{
const {publishNetwork}=await import('../src/network-collector.mjs');
for(const baseUrl of ['https://evil.example/api/v1','http://100.128.1.2/api/v1','http://user:pass@127.0.0.1/api/v1','http://127.0.0.1/api/v1?token=x'])await assert.rejects(publishNetwork({baseUrl},{interfaces:[],links:[]}),/Unsupported publish destination/);
await assert.rejects(publishNetwork({baseUrl:'http://100.111.140.100:3005/api/v1'},{interfaces:[],links:[]}),/Invalid intent identifier/);
});
Loading