From b9d9231d6c31c6bb6e4b283ca71bcb7cc2d56c53 Mon Sep 17 00:00:00 2001 From: Petrus Pennanen Date: Sun, 22 Nov 2026 17:16:54 +0100 Subject: [PATCH 1/4] Collect live interface and route evidence for fleet connection reports --- bin/iak-network.mjs | 9 ++++++ docs/network-collector.md | 21 ++++++++++++++ src/network-collector.mjs | 51 +++++++++++++++++++++++++++++++++ test/network-collector.test.mjs | 17 +++++++++++ 4 files changed, 98 insertions(+) create mode 100644 bin/iak-network.mjs create mode 100644 docs/network-collector.md create mode 100644 src/network-collector.mjs create mode 100644 test/network-collector.test.mjs diff --git a/bin/iak-network.mjs b/bin/iak-network.mjs new file mode 100644 index 0000000..4acb7a9 --- /dev/null +++ b/bin/iak-network.mjs @@ -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)); diff --git a/docs/network-collector.md b/docs/network-collector.md new file mode 100644 index 0000000..41a47d4 --- /dev/null +++ b/docs/network-collector.md @@ -0,0 +1,21 @@ +# 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 https://groupmind.one/api/v1, `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. diff --git a/src/network-collector.mjs b/src/network-collector.mjs new file mode 100644 index 0000000..c1ae723 --- /dev/null +++ b/src/network-collector.mjs @@ -0,0 +1,51 @@ +// 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':/^(wl|wifi)/.test(name)?'wifi':'ethernet'; + 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: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;} + 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=>({...old.find(o=>o.peer_id===r.peer_id),...r})); + for(const link of old)if(!links.some(l=>l.peer_id===link.peer_id))links.push(link); + return {...previous,...collected,links}; +} +export async function publishNetwork(c, collected, {fetchImpl=fetch}={}) { + if(c.baseUrl!=='https://groupmind.one/api/v1')throw Error('Unsupported publish destination'); + 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,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,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}; +} diff --git a/test/network-collector.test.mjs b/test/network-collector.test.mjs new file mode 100644 index 0000000..40103d2 --- /dev/null +++ b/test/network-collector.test.mjs @@ -0,0 +1,17 @@ +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',measurement}]},{interfaces:[],links:[{peer_id:'m5',route:'tailscale'}]});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']); +}); From 3e2949af5e5d9109b587e93cc702064ab118d6da Mon Sep 17 00:00:00 2001 From: Petrus Pennanen Date: Sun, 22 Nov 2026 17:26:41 +0100 Subject: [PATCH 2/4] Invalidate stale path measurements and omit host addresses from reports --- docs/network-collector.md | 11 +++++++++++ src/network-collector.mjs | 14 ++++++++++---- test/network-collector.test.mjs | 16 +++++++++++++++- 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/docs/network-collector.md b/docs/network-collector.md index 41a47d4..186fdb7 100644 --- a/docs/network-collector.md +++ b/docs/network-collector.md @@ -19,3 +19,14 @@ 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. diff --git a/src/network-collector.mjs b/src/network-collector.mjs index c1ae723..f4e664d 100644 --- a/src/network-collector.mjs +++ b/src/network-collector.mjs @@ -11,9 +11,9 @@ export function collectNetwork({peers=[], interfaces=networkInterfaces(), os=pla 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':/^(wl|wifi)/.test(name)?'wifi':'ethernet'; + 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: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}); + 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];}),measured_at:measuredAt}); } const links=[]; for(const peer of peers) { @@ -29,8 +29,14 @@ export function collectNetwork({peers=[], interfaces=networkInterfaces(), os=pla 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=>({...old.find(o=>o.peer_id===r.peer_id),...r})); - for(const link of old)if(!links.some(l=>l.peer_id===link.peer_id))links.push(link); + 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.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}={}) { diff --git a/test/network-collector.test.mjs b/test/network-collector.test.mjs index 40103d2..ce9a609 100644 --- a/test/network-collector.test.mjs +++ b/test/network-collector.test.mjs @@ -7,7 +7,7 @@ test('collects actual route/interface evidence without inventing throughput',()= }); 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',measurement}]},{interfaces:[],links:[{peer_id:'m5',route:'tailscale'}]});assert.deepEqual(n.links[0].measurement,measurement); + 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]})); @@ -15,3 +15,17 @@ test('peer names cannot inject commands or resolve arbitrary hostnames',()=>{ 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 host addresses are omitted',()=>{ + 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.equal(n.interfaces[0].addresses,undefined);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/); +}); From 590a62a2c8027ca3d366d8897489defaff05a189 Mon Sep 17 00:00:00 2001 From: Petrus Pennanen Date: Sun, 22 Nov 2026 17:26:58 +0100 Subject: [PATCH 3/4] Compare retained measurements against their recorded route --- src/network-collector.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/network-collector.mjs b/src/network-collector.mjs index f4e664d..c697985 100644 --- a/src/network-collector.mjs +++ b/src/network-collector.mjs @@ -32,7 +32,7 @@ export function mergeNetwork(previous={}, collected) { 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.route===r.route && prior.local_interface===r.local_interface; + 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}; }); From 59f4b7cfe5667bc1d67d78e29d3d93364ead6550 Mon Sep 17 00:00:00 2001 From: Petrus Pennanen Date: Sun, 22 Nov 2026 17:36:44 +0100 Subject: [PATCH 4/4] Support authorized host addresses and configured local API targets --- docs/network-collector.md | 12 +++++++++++- src/network-collector.mjs | 13 +++++++++---- test/network-collector.test.mjs | 9 +++++++-- 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/docs/network-collector.md b/docs/network-collector.md index 186fdb7..9a392c1 100644 --- a/docs/network-collector.md +++ b/docs/network-collector.md @@ -2,7 +2,7 @@ `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 https://groupmind.one/api/v1, `userId`, `deviceId`, absolute `keyFile`, +`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 @@ -30,3 +30,13 @@ unrecognized interface kinds remain unknown. Every interface and link is timesta 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. diff --git a/src/network-collector.mjs b/src/network-collector.mjs index c697985..a63b450 100644 --- a/src/network-collector.mjs +++ b/src/network-collector.mjs @@ -13,7 +13,7 @@ export function collectNetwork({peers=[], interfaces=networkInterfaces(), os=pla 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];}),measured_at:measuredAt}); + 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) { @@ -40,18 +40,23 @@ export function mergeNetwork(previous={}, collected) { return {...previous,...collected,links}; } export async function publishNetwork(c, collected, {fetchImpl=fetch}={}) { - if(c.baseUrl!=='https://groupmind.one/api/v1')throw Error('Unsupported publish destination'); + 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,signal:AbortSignal.timeout(15000)}); + 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,body:JSON.stringify({network}),signal:AbortSignal.timeout(15000)}); + 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}; } diff --git a/test/network-collector.test.mjs b/test/network-collector.test.mjs index ce9a609..64d90cb 100644 --- a/test/network-collector.test.mjs +++ b/test/network-collector.test.mjs @@ -18,8 +18,8 @@ test('network prefixes are canonical rather than host CIDRs',()=>{ 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 host addresses are omitted',()=>{ - 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.equal(n.interfaces[0].addresses,undefined);assert.deepEqual(n.interfaces[2].networks,[]); +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'); @@ -29,3 +29,8 @@ test('publisher patches only network on an existing slot and rejects absent slot 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/); +});