From 5d562371243698b7c00bcd3ecffd624460649ae5 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Thu, 29 Oct 2026 09:09:59 +0300 Subject: [PATCH] feat(routers): add observed router inventory and scoped controls Separate router discovery, evidence and authorized control from device runtime. Add Node/Core contracts and reusable operator surfaces. --- apps/control-station/src/core/fleet/router.ts | 7 + .../workspaces/fleet/router/VehicleRouter.tsx | 8 + apps/control-station/test/routers.test.mjs | 75 ++++ apps/node-agent/internal/node/routers.go | 56 +++ apps/node-agent/internal/routers/collector.go | 352 +++++++++++++++++ apps/node-agent/internal/routers/control.go | 273 +++++++++++++ .../internal/routers/control_test.go | 162 ++++++++ apps/node-agent/internal/routers/dexaflow.go | 276 ++++++++++++++ apps/node-agent/internal/routers/discovery.go | 113 ++++++ apps/node-agent/internal/routers/events.go | 55 +++ apps/node-agent/internal/routers/profile.go | 25 ++ apps/node-agent/internal/routers/profile.json | 16 + .../internal/routers/routers_test.go | 273 +++++++++++++ apps/node-agent/internal/routers/types.go | 123 ++++++ apps/node-agent/ui/src/NodeRouters.tsx | 11 + docs/node/26_ROUTER_OBSERVATION.md | 360 ++++++++++++++++++ packages/router-ui/src/RouterAccess.tsx | 41 ++ packages/router-ui/src/RouterControls.tsx | 62 +++ packages/router-ui/src/RouterDetails.tsx | 46 +++ packages/router-ui/src/RouterEquipment.tsx | 19 + packages/router-ui/src/RouterOverview.tsx | 78 ++++ packages/router-ui/src/contracts.ts | 40 ++ packages/router-ui/src/control.ts | 10 + packages/router-ui/src/overview.ts | 39 ++ packages/router-ui/src/router.css | 39 ++ packages/router-ui/src/useRouters.ts | 17 + src/k1link/fleet/router_contracts.py | 95 +++++ src/k1link/fleet/routers.py | 154 ++++++++ src/k1link/web/fleet_router_api.py | 63 +++ tests/fleet/test_routers.py | 201 ++++++++++ 30 files changed, 3089 insertions(+) create mode 100644 apps/control-station/src/core/fleet/router.ts create mode 100644 apps/control-station/src/workspaces/fleet/router/VehicleRouter.tsx create mode 100644 apps/control-station/test/routers.test.mjs create mode 100644 apps/node-agent/internal/node/routers.go create mode 100644 apps/node-agent/internal/routers/collector.go create mode 100644 apps/node-agent/internal/routers/control.go create mode 100644 apps/node-agent/internal/routers/control_test.go create mode 100644 apps/node-agent/internal/routers/dexaflow.go create mode 100644 apps/node-agent/internal/routers/discovery.go create mode 100644 apps/node-agent/internal/routers/events.go create mode 100644 apps/node-agent/internal/routers/profile.go create mode 100644 apps/node-agent/internal/routers/profile.json create mode 100644 apps/node-agent/internal/routers/routers_test.go create mode 100644 apps/node-agent/internal/routers/types.go create mode 100644 apps/node-agent/ui/src/NodeRouters.tsx create mode 100644 docs/node/26_ROUTER_OBSERVATION.md create mode 100644 packages/router-ui/src/RouterAccess.tsx create mode 100644 packages/router-ui/src/RouterControls.tsx create mode 100644 packages/router-ui/src/RouterDetails.tsx create mode 100644 packages/router-ui/src/RouterEquipment.tsx create mode 100644 packages/router-ui/src/RouterOverview.tsx create mode 100644 packages/router-ui/src/contracts.ts create mode 100644 packages/router-ui/src/control.ts create mode 100644 packages/router-ui/src/overview.ts create mode 100644 packages/router-ui/src/router.css create mode 100644 packages/router-ui/src/useRouters.ts create mode 100644 src/k1link/fleet/router_contracts.py create mode 100644 src/k1link/fleet/routers.py create mode 100644 src/k1link/web/fleet_router_api.py create mode 100644 tests/fleet/test_routers.py diff --git a/apps/control-station/src/core/fleet/router.ts b/apps/control-station/src/core/fleet/router.ts new file mode 100644 index 00000000..b805a114 --- /dev/null +++ b/apps/control-station/src/core/fleet/router.ts @@ -0,0 +1,7 @@ +import type {RouterTransport} from '../../../../../packages/router-ui/src/contracts'; +import {fleetRequest} from './useFleet'; + +export function routerTransport(vehicleID:string):RouterTransport{ + const base=`/${encodeURIComponent(vehicleID)}/routers`; + return {control:value=>fleetRequest(base+'/control','POST',value),read:()=>fleetRequest(base),authorize:value=>fleetRequest(base+'/access','POST',value),operation:id=>fleetRequest(base+'/access/'+encodeURIComponent(id))}; +} diff --git a/apps/control-station/src/workspaces/fleet/router/VehicleRouter.tsx b/apps/control-station/src/workspaces/fleet/router/VehicleRouter.tsx new file mode 100644 index 00000000..ff060449 --- /dev/null +++ b/apps/control-station/src/workspaces/fleet/router/VehicleRouter.tsx @@ -0,0 +1,8 @@ +import {useMemo} from 'react'; +import {RouterEquipment} from '../../../../../../packages/router-ui/src/RouterEquipment'; +import {routerTransport} from '../../../core/fleet/router'; + +export function VehicleRouter({vehicleID}:{vehicleID:string}){ + const transport=useMemo(()=>routerTransport(vehicleID),[vehicleID]); + return ; +} diff --git a/apps/control-station/test/routers.test.mjs b/apps/control-station/test/routers.test.mjs new file mode 100644 index 00000000..cc83cd91 --- /dev/null +++ b/apps/control-station/test/routers.test.mjs @@ -0,0 +1,75 @@ +import assert from 'node:assert/strict'; +import {before,after,test} from 'node:test'; +import {createServer} from './support/vite-server.mjs'; +import {createElement} from 'react'; +import {renderToStaticMarkup} from 'react-dom/server'; +let server,routerFresh,routerLabel,metric,collectTraffic,trafficPath,trafficRate,signalFraction,modemLabel; +before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});({routerFresh,routerLabel,metric}=await server.ssrLoadModule('../../packages/router-ui/src/contracts.ts'));({collectTraffic,trafficPath,trafficRate,signalFraction,modemLabel}=await server.ssrLoadModule('../../packages/router-ui/src/overview.ts'));}); +after(async()=>{await server?.close();}); +test('fresh board heartbeat cannot revive stale radio data',()=>{ + const state={available:true,fresh:true},device={state:'ready',observed_at:100}; + assert.equal(routerFresh(state,device,110000),true); + assert.equal(routerFresh(state,device,141000),false); + assert.equal(routerLabel(state,device,141000),'Нет свежих данных'); + assert.equal(routerFresh({...state,fresh:false},device,110000),false); +}); +test('missing radio sample is not displayed as zero or antenna health',()=>{ + assert.equal(metric(null,'dB'),'Нет сведений'); + assert.equal(metric(0,'dB'),'0 dB'); + assert.equal(metric(-113,'dBm'),'-113 dBm'); +}); +test('overview distinguishes absent SIM, unavailable observations and missing measurements',()=>{ + assert.equal(modemLabel({radio:'NOSIM'},true),'SIM не установлена'); + assert.equal(modemLabel({radio:'NOSIM'},false),'Нет свежих данных'); + assert.equal(modemLabel(undefined,true),'Нет сведений'); + assert.equal(signalFraction(null),null); + assert.equal(trafficRate(null),'—'); + assert.equal(trafficRate(0),'0 кбит/с'); + assert.equal(trafficRate(1500),'1,5 Мбит/с'); +}); +test('live graph deduplicates repeated snapshots and never invents zero traffic on loss',()=>{ + const device={observed_at:100,down_kbps:20,up_kbps:null}; + const first=collectTraffic({key:'',day:0,points:[]},'a',device,true,100); + assert.deepEqual(first.points,[{at:100,down:20,up:null}]); + assert.equal(collectTraffic(first,'a',device,true,103).points.length,1); + assert.equal(collectTraffic(first,'a',{...device,observed_at:110},false,110).points.length,1); + assert.deepEqual(collectTraffic(first,'a',device,false,401).points,[]); + assert.deepEqual(collectTraffic(first,'new-runtime',device,false,110).points,[]); + assert.deepEqual(collectTraffic(first,'a',device,false,86401).points,[]); +}); +test('traffic lines retain gaps and keep missing upload separate from recorded download',()=>{ + const p=[{at:100,down:20,up:2},{at:110,down:21,up:null},{at:120,down:22,up:3},{at:200,down:23,up:4}]; + assert.equal((trafficPath(p,'down',0,200,30).match(/M/g)||[]).length,2); + assert.equal((trafficPath(p,'up',0,200,30).match(/M/g)||[]).length,3); + assert.equal(trafficPath([{at:100,down:null,up:null}],'down',0,200,30),''); +}); +test('overview renders three slots without implying internet or traffic from unknown samples',async()=>{ + const {RouterOverview}=await server.ssrLoadModule('../../packages/router-ui/src/RouterOverview.tsx'); + const device={active_mode:'direct',active_wan:'wan1',internet:'unknown',address:'192.168.100.1',modems:[{slot:1,operator:'Test carrier',radio:'OK',connectivity:'online',rsrp:-96,technology:'lte',band:'B40',down_kbps:null,up_kbps:null},{slot:2,radio:'NOSIM'}],down_kbps:null,up_kbps:null}; + const html=renderToStaticMarkup(createElement(RouterOverview,{device,ready:true,points:[{at:100,down:null,up:null},{at:110,down:null,up:null}]})); + for(const slot of [1,2,3])assert.match(html,new RegExp(`

SIM M${slot}

`)); + assert.match(html,/Интернет не подтверждён/); + assert.match(html,/SIM не установлена/); + assert.match(html,/Нет сведений/); + assert.match(html,/Ожидание следующего измерения для графика/); + assert.doesNotMatch(html,/0 кбит\/с/); +}); +test('router controls require fresh capable Node and block concurrent operations',async()=>{ + const {controlEnabled,availableSlots,controlMessage}=await server.ssrLoadModule('../../packages/router-ui/src/control.ts'); + const d={id:'router-test',state:'ready',modems:[{slot:1,radio:'OK',ip:'10.0.0.1'},{slot:2,radio:'NOSIM',ip:''}]}; + const s={control_version:1,runtime_id:'runtime',results:[]}; + assert.equal(controlEnabled(s,d,true),true); + assert.equal(controlEnabled({...s,control_version:0},d,true),false); + assert.equal(controlEnabled(s,d,false),false); + assert.equal(controlEnabled({...s,results:[{state:'applying'}]},d,true),false); + assert.deepEqual(availableSlots(d),[1]); + assert.match(controlMessage({state:'unknown'}),/не подтверждён/); + assert.match(controlMessage({state:'complete',action:'reboot'}),/Перезагрузка подтверждена/); +}); +test('control surface uses shared controls and does not claim support on old Node',async()=>{ + const {RouterControls}=await server.ssrLoadModule('../../packages/router-ui/src/RouterControls.tsx'); + const html=renderToStaticMarkup(createElement(RouterControls,{device:{id:'router-test',state:'ready',modems:[],active_mode:'direct'},value:{results:[]},transport:{},ready:true})); + assert.match(html,/требуется обновление Mission Core/); + assert.match(html,/Перезагрузить роутер/); + assert.match(html,/disabled/); +}); diff --git a/apps/node-agent/internal/node/routers.go b/apps/node-agent/internal/node/routers.go new file mode 100644 index 00000000..e77ad5e3 --- /dev/null +++ b/apps/node-agent/internal/node/routers.go @@ -0,0 +1,56 @@ +package node + +import ( + "encoding/json" + "net/http" + + "nodedc.local/mission-core/node-agent/internal/routers" +) + +func (p *Pairing) applyRouterCommands(raw json.RawMessage) { + if p.Routers == nil || len(raw) > 4096 { + return + } + var commands []routers.Command + if json.Unmarshal(raw, &commands) != nil || len(commands) > 2 { + return + } + for _, command := range commands { + _ = p.Routers.Submit(command) + } +} + +func (s *Server) routerRoutes(mux *http.ServeMux) { + mux.HandleFunc("GET /api/routers", func(w http.ResponseWriter, r *http.Request) { + if !s.authorized(w, r) { + return + } + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Content-Type", "application/json") + if s.Pairing == nil || s.Pairing.Routers == nil { + json.NewEncoder(w).Encode(map[string]any{"available": false, "items": []any{}}) + return + } + json.NewEncoder(w).Encode(s.Pairing.Routers.Snapshot()) + }) + submit := func(control bool) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !s.authorized(w, r) { + return + } + var command routers.Command + if !decode(w, r, &command) { + return + } + if (control != (command.Action != "")) || s.Pairing == nil || s.Pairing.Routers == nil || s.Pairing.Routers.Submit(command) != nil { + http.Error(w, "Router unavailable", http.StatusConflict) + return + } + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(routers.Result{ID: command.ID, State: "queued"}) + } + } + mux.HandleFunc("POST /api/routers/access", submit(false)) + mux.HandleFunc("POST /api/routers/control", submit(true)) +} diff --git a/apps/node-agent/internal/routers/collector.go b/apps/node-agent/internal/routers/collector.go new file mode 100644 index 00000000..af8adce4 --- /dev/null +++ b/apps/node-agent/internal/routers/collector.go @@ -0,0 +1,352 @@ +package routers + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "os" + "path/filepath" + "regexp" + "sort" + "sync" + "sync/atomic" + "time" +) + +type Collector struct { + path, runtime string + started time.Time + state state // Owned exclusively by Run, not by heartbeat or HTTP handlers. + storageError bool + control *verification + blocked bool + view atomic.Value + commands chan Command + mu sync.Mutex + results map[string]Result + resultTimes map[string]time.Time + clients map[string]*api + weak map[string]int + discover func(context.Context, []Candidate) []Candidate + client func(Candidate) *api + neighbor func(string, string) string +} + +func Open(root string) *Collector { + b := make([]byte, 16) + _, err := rand.Read(b) + c := &Collector{path: filepath.Join(root, "routers-v1.json"), runtime: hex.EncodeToString(b), started: time.Now(), + commands: make(chan Command, 4), results: map[string]Result{}, resultTimes: map[string]time.Time{}, clients: map[string]*api{}, weak: map[string]int{}, discover: discover, client: newAPI, neighbor: neighbor, + state: state{Schema: Schema, Records: map[string]record{}, Events: []Event{}}} + if err != nil || !profileValid() { + c.blocked = true + } + info, e := os.Lstat(c.path) + if e == nil { + if !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 || info.Size() > 524288 { + c.blocked = true + } else { + data, e := os.ReadFile(c.path) + if e != nil || json.Unmarshal(data, &c.state) != nil || c.state.Schema != Schema || c.state.Records == nil || len(c.state.Records) > maxDevices || len(c.state.Events) > maxEvents { + c.blocked = true + } + } + } else if !os.IsNotExist(e) { + c.blocked = true + } + if c.blocked { + c.state = state{Schema: Schema, Records: map[string]record{}, Events: []Event{}} + c.storageError = true + } + for id, r := range c.state.Records { + r.Device.State = "unreachable" + c.state.Records[id] = r + } + c.publish() + return c +} + +// A snapshot is immutable and copied before handing it to another component. +// Slow LAN requests or disk sync never hold the pairing/control mutex. +func (c *Collector) Snapshot() Snapshot { + data, _ := json.Marshal(c.view.Load().(Snapshot)) + var s Snapshot + _ = json.Unmarshal(data, &s) + return s +} + +var operationID = regexp.MustCompile(`^op_[0-9a-f]{32}$`) + +func (c *Collector) Submit(cmd Command) error { + now := time.Now() + if c.blocked || cmd.RuntimeID != c.runtime || !operationID.MatchString(cmd.ID) || cmd.Deadline <= now.Unix() || cmd.Deadline > now.Add(90*time.Second).Unix() || !validCommand(cmd) { + return errors.New("invalid_router_access_request") + } + c.mu.Lock() + _, duplicate := c.results[cmd.ID] + c.mu.Unlock() + if duplicate { + return nil + } + found := false + for _, d := range c.Snapshot().Items { + if d.ID == cmd.DeviceID && time.Now().Unix()-d.ObservedAt < 40 && ((cmd.Action == "" && (d.State == "access_required" || d.State == "access_rejected")) || d.State == "ready") { + found = true + } + } + if !found { + return errors.New("router_unavailable") + } + c.mu.Lock() + defer c.mu.Unlock() + for id, at := range c.resultTimes { + if now.Sub(at) > 10*time.Minute { + delete(c.results, id) + delete(c.resultTimes, id) + } + } + if _, exists := c.results[cmd.ID]; exists { + return nil + } + for _, result := range c.results { + if result.State == "queued" || result.State == "applying" { + return errors.New("router_requests_busy") + } + } + if len(c.results) >= 32 { + return errors.New("router_requests_busy") + } + select { + case c.commands <- cmd: + c.results[cmd.ID] = Result{ID: cmd.ID, DeviceID: cmd.DeviceID, Action: cmd.Action, State: "queued"} + c.resultTimes[cmd.ID] = now + return nil + default: + return errors.New("router_requests_busy") + } +} + +func (c *Collector) publish() { + s := Snapshot{ControlVersion: 1, Schema: Schema, RuntimeID: c.runtime, Available: !c.blocked, ObservedAt: time.Now().Unix(), Items: []Device{}, Events: append([]Event{}, c.state.Events...), Results: []Result{}, Journal: Journal{Last: c.state.Sequence, Dropped: c.state.Dropped, Limit: maxEvents, RetentionDays: 7, Error: c.storageError}} + if len(s.Events) > 0 { + s.Journal.First = s.Events[0].Sequence + } + for _, r := range c.state.Records { + s.Items = append(s.Items, r.Device) + } + sort.Slice(s.Items, func(i, j int) bool { return s.Items[i].ID < s.Items[j].ID }) + c.mu.Lock() + for _, r := range c.results { + s.Results = append(s.Results, r) + } + c.mu.Unlock() + c.view.Store(s) +} + +func (c *Collector) event(id, code string, slot int, before, after string) { + c.state.Sequence++ + c.state.Events = append(c.state.Events, Event{Sequence: c.state.Sequence, At: time.Now().Unix(), BootID: c.runtime, ElapsedMS: time.Since(c.started).Milliseconds(), DeviceID: id, Code: code, Slot: slot, Before: text(before), After: text(after)}) +} +func (c *Collector) persist() { + cutoff := time.Now().Add(-retention).Unix() + for len(c.state.Events) > 0 && (len(c.state.Events) > maxEvents || c.state.Events[0].At < cutoff) { + c.state.Events = c.state.Events[1:] + c.state.Dropped++ + } + data, err := json.Marshal(c.state) + if err != nil || len(data) > 524288 { + c.storageError = true + return + } + f, err := os.CreateTemp(filepath.Dir(c.path), ".router-*") + if err != nil { + c.storageError = true + return + } + defer os.Remove(f.Name()) + _, err = f.Write(data) + if err == nil { + err = f.Sync() + } + closeErr := f.Close() + if err == nil { + err = closeErr + } + if err == nil { + err = os.Rename(f.Name(), c.path) + } + if err == nil { + if dir, e := os.Open(filepath.Dir(c.path)); e == nil { + err = dir.Sync() + dir.Close() + } else { + err = e + } + } + c.storageError = err != nil +} + +func (c *Collector) Run(ctx context.Context) { + if c.blocked { + return + } + c.poll(ctx) + ticker := time.NewTicker(10 * time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case cmd := <-c.commands: + if cmd.Action == "" { + c.authorize(ctx, cmd) + } else { + c.applyControl(ctx, cmd) + } + c.publish() + case <-ticker.C: + c.poll(ctx) + } + } +} + +func (c *Collector) candidates(ctx context.Context) []Candidate { + var remembered []Candidate + for _, r := range c.state.Records { + remembered = append(remembered, Candidate{Address: r.Device.Address, Interface: r.Device.Interface}) + } + return c.discover(ctx, remembered) +} + +func (c *Collector) poll(ctx context.Context) { + seen := map[string]bool{} + for _, candidate := range c.candidates(ctx) { + if ctx.Err() != nil { + break + } + a := c.client(candidate) + if !a.family(ctx) { + continue + } + // The first bounded request resolves ARP without a subnet scan. + candidate.MAC = c.neighbor(candidate.Interface, candidate.Address) + if candidate.MAC == "" { + continue + } + id := identity(candidate.MAC) + seen[id] = true + r, exists := c.state.Records[id] + if !exists { + if len(c.state.Records) >= maxDevices { + continue + } + r = record{MAC: candidate.MAC, Device: Device{ID: id, Family: "DexaFlow", Identity: "local_mac", State: "access_required", Internet: "unknown", Modems: []Modem{}}} + c.event(id, "discovered", 0, "", "") + } + old := r.Device + if old.Address != candidate.Address || old.Interface != candidate.Interface || old.LocalIP != candidate.LocalIP { + delete(c.clients, id) + } + r.Device.Address, r.Device.Interface, r.Device.LocalIP = candidate.Address, candidate.Interface, candidate.LocalIP + if r.Access == nil || r.Rejected { + r.Device.State = "access_required" + if r.Rejected { + r.Device.State = "access_rejected" + } + r.Device.ObservedAt = time.Now().Unix() + } else { + a = c.clients[id] + if a == nil { + a = c.client(candidate) + c.clients[id] = a + } + d, err := a.read(ctx) + if errors.Is(err, errAccess) { + err = a.login(ctx, *r.Access) + if err == nil { + d, err = a.read(ctx) + } + } + if errors.Is(err, errAccess) { + r.Rejected = true + r.Device.State = "access_rejected" + delete(c.clients, id) + } else if errors.Is(err, errProtocol) { + r.Device.State = "incompatible" + } else if err != nil { + r.Device.State = "unreachable" + } else { + d.ID, d.Address, d.Interface, d.LocalIP = id, candidate.Address, candidate.Interface, candidate.LocalIP + d.ObservedAt = time.Now().Unix() + r.Device = d + } + } + c.transitions(old, r.Device) + c.state.Records[id] = r + } + for id, r := range c.state.Records { + if !seen[id] { + old := r.Device + r.Device.State = "unreachable" + c.transitions(old, r.Device) + c.state.Records[id] = r + } + } + c.verifyControl() + c.persist() + c.publish() +} + +func (c *Collector) authorize(ctx context.Context, cmd Command) { + ctx, cancel := context.WithDeadline(ctx, time.Unix(cmd.Deadline, 0)) + defer cancel() + result := Result{ID: cmd.ID, DeviceID: cmd.DeviceID, State: "error", Error: "router_unavailable"} + defer func() { c.mu.Lock(); c.results[cmd.ID] = result; c.mu.Unlock() }() + if cmd.Deadline <= time.Now().Unix() { + result.Error = "expired" + return + } + r, ok := c.state.Records[cmd.DeviceID] + if !ok { + return + } + for _, candidate := range c.candidates(ctx) { + if c.neighbor(candidate.Interface, candidate.Address) != r.MAC { + continue + } + candidate.MAC = r.MAC + a := c.client(candidate) + if !a.family(ctx) { + return + } + access := credential{Username: cmd.Username, Password: cmd.Password} + if err := a.login(ctx, access); err != nil { + result.Error = "access_rejected" + c.event(cmd.DeviceID, "access_rejected", 0, "", "") + c.persist() + return + } + d, err := a.read(ctx) + if err != nil { + result.Error = "unsupported_response" + return + } + d.ID, d.Address, d.Interface, d.LocalIP = cmd.DeviceID, candidate.Address, candidate.Interface, candidate.LocalIP + d.ObservedAt = time.Now().Unix() + before := r + r.Device, r.Access, r.Rejected = d, &access, false + c.state.Records[cmd.DeviceID] = r + c.event(cmd.DeviceID, "access_granted", 0, "", "") + c.persist() + if c.storageError { + c.state.Records[cmd.DeviceID] = before + result.Error = "storage_error" + return + } + c.clients[cmd.DeviceID] = a + result.State, result.Error = "complete", "" + return + } +} diff --git a/apps/node-agent/internal/routers/control.go b/apps/node-agent/internal/routers/control.go new file mode 100644 index 00000000..a1f08121 --- /dev/null +++ b/apps/node-agent/internal/routers/control.go @@ -0,0 +1,273 @@ +package routers + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net" + "net/url" + "regexp" + "slices" + "strings" + "time" +) + +// All commands are explicitly requested, runtime-bound and processed once. +// The result cache outlives the maximum admission deadline; a Node restart +// invalidates every previous runtime. No network write is retried automatically. +type verification struct { + command Command + started time.Time + until time.Time + uptime *float64 + manualMode string +} + +func validCommand(c Command) bool { + if c.Action == "" { + return c.Mode == "" && len(c.Slots) == 0 && len(c.Username) > 0 && len(c.Username) <= 64 && len(c.Password) > 0 && len(c.Password) <= 256 + } + if c.Username != "" || c.Password != "" { + return false + } + if c.Action == "reboot" { + return c.Mode == "" && len(c.Slots) == 0 + } + if c.Action != "mode" || (c.Mode != "direct" && c.Mode != "aggregation") || len(c.Slots) < 1 || len(c.Slots) > 3 || (c.Mode == "direct" && len(c.Slots) != 1) { + return false + } + seen := map[int]bool{} + for _, slot := range c.Slots { + if slot < 1 || slot > 3 || seen[slot] { + return false + } + seen[slot] = true + } + return true +} + +var deviceName = regexp.MustCompile(`^[a-zA-Z0-9_.:-]{1,32}$`) + +func manualSlots(m map[string]any) []int { + result := []int{} + modems, _ := m["modems"].([]any) + for _, raw := range modems { + modem, ok := raw.(map[string]any) + if !ok { + continue + } + for slot := 1; slot <= 3; slot++ { + if modem["slot"] != fmt.Sprintf("M%d", slot) { + continue + } + selected := false + switch m["mode"] { + case "direct": + selected = modem["wan"] == m["wan"] && m["wan"] == fmt.Sprintf("wan%d", slot) + case "glue": + selected = slices.Contains(strings.Split(text(m["allow"]), ","), text(modem["dev"])) && text(modem["dev"]) != "" + case "auto": + selected = modem["up"] == true + } + if selected && !slices.Contains(result, slot) { + result = append(result, slot) + } + } + } + slices.Sort(result) + return result +} + +// Resolve public slot numbers against the current vendor response. Never accept +// raw device names, endpoint paths or form fields supplied by an operator. +func controlForm(cmd Command, manual map[string]any) (url.Values, string, error) { + modems, ok := manual["modems"].([]any) + if !ok || len(modems) > 3 || manual["ok"] != true { + return nil, "", errProtocol + } + live := map[int]string{} + for _, raw := range modems { + m, ok := raw.(map[string]any) + if !ok { + return nil, "", errProtocol + } + for slot := 1; slot <= 3; slot++ { + if m["slot"] != fmt.Sprintf("M%d", slot) { + continue + } + if m["up"] != true || net.ParseIP(text(m["ip"])) == nil { + continue + } + dev := text(m["dev"]) + if m["wan"] != fmt.Sprintf("wan%d", slot) || !deviceName.MatchString(dev) || live[slot] != "" { + return nil, "", errProtocol + } + live[slot] = dev + } + } + selected := append([]int{}, cmd.Slots...) + slices.Sort(selected) + devices := []string{} + for _, slot := range selected { + if live[slot] == "" { + return nil, "", errors.New("sim_unavailable") + } + devices = append(devices, live[slot]) + } + if cmd.Mode == "direct" { + return url.Values{"mode": {"direct"}, "wan": {fmt.Sprintf("wan%d", selected[0])}}, "direct", nil + } + if len(selected) == len(live) { + return url.Values{"mode": {"auto"}}, "auto", nil + } + return url.Values{"mode": {"glue"}, "allow": {strings.Join(devices, ",")}}, "glue", nil +} + +func (c *Collector) setControlResult(cmd Command, state, reason string) { + c.mu.Lock() + c.results[cmd.ID] = Result{ID: cmd.ID, DeviceID: cmd.DeviceID, Action: cmd.Action, State: state, Error: reason} + c.mu.Unlock() +} + +func (c *Collector) applyControl(parent context.Context, cmd Command) { + result := "router_unavailable" + sent := false + defer func() { + if !sent { + c.setControlResult(cmd, "error", result) + } + }() + if time.Now().Unix() >= cmd.Deadline { + result = "expired" + return + } + ctx, cancel := context.WithDeadline(parent, time.Unix(cmd.Deadline, 0)) + defer cancel() + r, ok := c.state.Records[cmd.DeviceID] + if !ok || r.Access == nil || r.Rejected || r.Device.State != "ready" { + return + } + for _, candidate := range c.candidates(ctx) { + if c.neighbor(candidate.Interface, candidate.Address) != r.MAC { + continue + } + candidate.MAC = r.MAC + a := c.client(candidate) + if !a.family(ctx) { + return + } + if err := a.login(ctx, *r.Access); err != nil { + result = "access_rejected" + return + } + var uptime *float64 + form := url.Values{"confirm": {"1"}} + path := "dexaflow_reboot" + expected := "" + if cmd.Action == "mode" { + manual, err := a.json(ctx, "dexaflow_manual", nil) + if err != nil { + return + } + form, expected, err = controlForm(cmd, manual) + if err != nil { + if err.Error() == "sim_unavailable" { + result = "sim_unavailable" + } else { + result = "unsupported_response" + } + return + } + path = "dexaflow_manual" + } else { + status, err := a.json(ctx, "dexaflow_status", nil) + if err != nil { + return + } + uptime = number(status["uptime"], 0, 1e12) + if uptime == nil { + result = "unsupported_response" + return + } + } + // Persist intent before issuing the write. A crash cannot silently erase + // the attempted operation, and old runtimes cannot re-send it after boot. + c.event(cmd.DeviceID, "command_requested", 0, cmd.Action, cmd.Mode) + c.persist() + if c.storageError { + result = "storage_error" + return + } + if ctx.Err() != nil { + result = "expired" + return + } + start := time.Now() + data, writeErr := a.request(ctx, path, form) // Exactly ONE write, even on timeout. + if writeErr == nil && cmd.Action == "mode" { + var response map[string]any + if json.Unmarshal(data, &response) == nil && response["ok"] == false { + result = "command_rejected" + switch response["error"] { + case "busy": + result = "router_busy" + case "need_modem", "no_ip": + result = "sim_unavailable" + } + c.event(cmd.DeviceID, "command_failed", 0, cmd.Action, result) + c.persist() + return + } + } + if errors.Is(writeErr, errAccess) { + result = "access_rejected" + return + } + sent = true + c.control = &verification{command: cmd, started: start, until: start.Add(180 * time.Second), uptime: uptime, manualMode: expected} + c.clients[cmd.DeviceID] = a + c.setControlResult(cmd, "applying", "") + return + } +} + +func confirms(v *verification, d Device, now time.Time) bool { + if d.State != "ready" || d.ObservedAt <= v.started.Unix() { + return false + } + if v.command.Action == "reboot" { + // Uptime measures the router, not the Node. Missing samples and a reachable + // login page alone never count as a successful reboot. + return v.uptime != nil && d.Uptime != nil && *d.Uptime+15 < *v.uptime+now.Sub(v.started).Seconds() + } + if d.ManualMode != v.manualMode { + return false + } + want := append([]int{}, v.command.Slots...) + slices.Sort(want) + if !slices.Equal(d.ActiveSlots, want) { + return false + } + if v.command.Mode == "direct" { + return d.ActiveMode == "direct" && d.ActiveWAN == fmt.Sprintf("wan%d", want[0]) + } + return d.ActiveMode == "aggregation" +} + +func (c *Collector) verifyControl() { + v := c.control + if v == nil { + return + } + now := time.Now() + if r, ok := c.state.Records[v.command.DeviceID]; ok && confirms(v, r.Device, now) { + c.setControlResult(v.command, "complete", "") + c.event(v.command.DeviceID, "command_complete", 0, v.command.Action, v.command.Mode) + c.control = nil + } else if !now.Before(v.until) { + c.setControlResult(v.command, "unknown", "confirmation_timeout") + c.event(v.command.DeviceID, "command_unconfirmed", 0, v.command.Action, v.command.Mode) + c.control = nil + } +} diff --git a/apps/node-agent/internal/routers/control_test.go b/apps/node-agent/internal/routers/control_test.go new file mode 100644 index 00000000..22136e74 --- /dev/null +++ b/apps/node-agent/internal/routers/control_test.go @@ -0,0 +1,162 @@ +package routers + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func manualFixture() map[string]any { + return map[string]any{"ok": true, "mode": "direct", "persist": "direct", "wan": "wan1", "modems": []any{ + map[string]any{"slot": "M1", "wan": "wan1", "dev": "wwan0", "up": true, "ip": "10.1.0.2"}, + map[string]any{"slot": "M2", "wan": "wan2", "dev": "wwan1", "up": true, "ip": "10.2.0.2"}, + map[string]any{"slot": "M3", "wan": "wan3", "dev": "wwan2", "up": false, "ip": ""}, + }} +} +func TestControlFormUsesCurrentLiveSlotsOnly(t *testing.T) { + for _, test := range []struct { + cmd Command + form string + fail bool + }{ + {Command{Action: "mode", Mode: "direct", Slots: []int{2}}, "mode=direct&wan=wan2", false}, + {Command{Action: "mode", Mode: "aggregation", Slots: []int{2}}, "allow=wwan1&mode=glue", false}, + {Command{Action: "mode", Mode: "aggregation", Slots: []int{2, 1}}, "mode=auto", false}, + {Command{Action: "mode", Mode: "direct", Slots: []int{3}}, "", true}, + } { + if !validCommand(test.cmd) { + t.Fatal("valid command rejected") + } + form, _, err := controlForm(test.cmd, manualFixture()) + if (err != nil) != test.fail || (!test.fail && form.Encode() != test.form) { + t.Fatal(form, err) + } + } + for _, cmd := range []Command{{Action: "reboot", Slots: []int{1}}, {Action: "mode", Mode: "vpn", Slots: []int{1}}, {Action: "mode", Mode: "direct", Slots: []int{1, 2}}, {Action: "mode", Mode: "aggregation", Slots: []int{1, 1}}, {Action: "mode", Mode: "direct", Slots: []int{0}}, {Action: "reboot", Password: "secret"}} { + if validCommand(cmd) { + t.Fatal("invalid command accepted", cmd.Action) + } + } +} +func TestConfirmationRequiresActualModeAndRouterUptime(t *testing.T) { + now := time.Now() + up := 1000. + v := &verification{command: Command{Action: "mode", Mode: "direct", Slots: []int{1}}, manualMode: "direct", started: now.Add(-30 * time.Second)} + d := Device{State: "ready", ObservedAt: now.Unix(), SelectedMode: "direct", ActiveMode: "aggregation", ManualMode: "direct", PersistedMode: "direct", ActiveWAN: "wan1", ActiveSlots: []int{1}} + if confirms(v, d, now) { + t.Fatal("selected policy is not active path") + } + d.ActiveMode = "direct" + if !confirms(v, d, now) { + t.Fatal("matching readback missed") + } + d.PersistedMode = "auto" + if !confirms(v, d, now) { + t.Fatal("stored reboot policy is independent of active manual mode") + } + d.ActiveWAN = "wan2" + if confirms(v, d, now) { + t.Fatal("wrong SIM accepted") + } + v.command = Command{Action: "reboot"} + v.uptime = &up + next := 1030. + d.Uptime = &next + if confirms(v, d, now) { + t.Fatal("response alone is not a reboot") + } + next = 10. + if !confirms(v, d, now) { + t.Fatal("uptime reset missed") + } + d.State = "unreachable" + if confirms(v, d, now) { + t.Fatal("stale uptime accepted") + } +} +func TestCommandIsNotReplayedAfterAmbiguousWrite(t *testing.T) { + posts := 0 + s, _, i, me := fixture() + manual := manualFixture() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/cgi-bin/luci/dexaflow" { + w.Write([]byte(loginPageFixture)) + return + } + if r.URL.Path == "/cgi-bin/dexaflow_status" { + t.Error("mode command depends on unrelated slow radio statistics") + http.Error(w, "slow statistics", 503) + return + } + if r.Method == "POST" && r.URL.Path == "/cgi-bin/dexaflow_auth" { + w.Write([]byte(`{"ok":true}`)) + return + } + if r.Method == "POST" { + posts++ + w.Write([]byte(`incomplete response`)) + return + } + json.NewEncoder(w).Encode(map[string]any{"/cgi-bin/dexaflow_status": s, "/cgi-bin/dexaflow_manual": manual, "/cgi-bin/dexaflow_internet": i, "/cgi-bin/dexaflow_auth": me}[r.URL.Path]) + })) + defer srv.Close() + c := Open(t.TempDir()) + mac := "02:00:00:00:00:01" + id := identity(mac) + c.state.Records[id] = record{MAC: mac, Access: &credential{"operator", "synthetic"}, Device: Device{ID: id, State: "ready", ObservedAt: time.Now().Unix()}} + c.discover = func(context.Context, []Candidate) []Candidate { + return []Candidate{{Address: "192.168.50.1", Interface: "eth0", LocalIP: "192.168.50.2"}} + } + c.neighbor = func(string, string) string { return mac } + c.client = func(Candidate) *api { return testAPI(srv) } + c.publish() + cmd := Command{ID: "op_" + strings.Repeat("1", 32), RuntimeID: c.runtime, DeviceID: id, Deadline: time.Now().Add(time.Minute).Unix(), Action: "mode", Mode: "direct", Slots: []int{1}} + if err := c.Submit(cmd); err != nil { + t.Fatal(err) + } + c.applyControl(context.Background(), <-c.commands) + c.publish() + if c.Snapshot().Results[0].State != "applying" || posts != 1 { + t.Fatal("write not tracked", posts) + } + if err := c.Submit(cmd); err != nil || len(c.commands) != 0 { + t.Fatal("duplicate requeued", err) + } + other := cmd + other.ID = "op_" + strings.Repeat("2", 32) + if c.Submit(other) == nil { + t.Fatal("concurrent write accepted") + } + c.control.until = time.Now().Add(-time.Second) + c.verifyControl() + c.publish() + if c.Snapshot().Results[0].State != "unknown" || posts != 1 { + t.Fatal("unknown write retried") + } + c.persist() + restarted := Open(strings.TrimSuffix(c.path, "/routers-v1.json")) + if restarted.Submit(cmd) == nil { + t.Fatal("old runtime replay accepted") + } +} + +func TestInterruptedBodyIsTransportFailureNotUnsupportedFirmware(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(200) + w.Write([]byte(`{"modems":`)) + w.(http.Flusher).Flush() + <-r.Context().Done() + })) + defer srv.Close() + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + _, err := testAPI(srv).request(ctx, "dexaflow_status", nil) + if !errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errProtocol) { + t.Fatal("timeout classified as firmware incompatibility", err) + } +} diff --git a/apps/node-agent/internal/routers/dexaflow.go b/apps/node-agent/internal/routers/dexaflow.go new file mode 100644 index 00000000..a7d16503 --- /dev/null +++ b/apps/node-agent/internal/routers/dexaflow.go @@ -0,0 +1,276 @@ +package routers + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "net" + "net/http" + "net/http/cookiejar" + "net/url" + "strconv" + "strings" + "time" + "unicode" +) + +var errAccess = errors.New("access_required") +var errProtocol = errors.New("unsupported_response") +var errLink = errors.New("local_link_changed") + +type api struct { + client *http.Client + base string + check func() bool +} + +func newAPI(c Candidate) *api { + jar, _ := cookiejar.New(nil) + return &api{base: "http://" + c.Address + "/cgi-bin/", check: func() bool { + return c.MAC == "" || neighbor(c.Interface, c.Address) == c.MAC + }, client: &http.Client{ + Timeout: 35 * time.Second, Jar: jar, + CheckRedirect: func(*http.Request, []*http.Request) error { return errProtocol }, + Transport: &http.Transport{Proxy: nil, DisableKeepAlives: true, MaxResponseHeaderBytes: 16384, + DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { + local, ok := onLink(c.Interface, c.Address) + if !ok || local != c.LocalIP || address != net.JoinHostPort(c.Address, "80") { + return nil, errLink + } + var selected []route + if !commandJSON(ctx, []string{"-j", "-4", "route", "get", c.Address}, &selected) || len(selected) != 1 || selected[0].Dev != c.Interface || selected[0].Gateway != "" { + return nil, errLink + } + return (&net.Dialer{Timeout: time.Second, LocalAddr: &net.TCPAddr{IP: net.ParseIP(c.LocalIP)}}).DialContext(ctx, network, address) + }}, + }} +} + +func (a *api) request(ctx context.Context, path string, form url.Values) ([]byte, error) { + budget := 2 * time.Second + if path == "dexaflow_status" { + // The firmware gathers modem statistics synchronously (observed 3.8 s). + // Keep discovery/login fast while allowing this bounded read to finish. + budget = 8 * time.Second + } + if form != nil && path == "dexaflow_manual" { + budget = 30 * time.Second + } + ctx, cancel := context.WithTimeout(ctx, budget) + defer cancel() + if !a.check() { + return nil, errLink + } + method := http.MethodGet + var body io.Reader + if form != nil { + method = http.MethodPost + body = strings.NewReader(form.Encode()) + } + req, err := http.NewRequestWithContext(ctx, method, a.base+path, body) + if err != nil { + return nil, errProtocol + } + if form != nil { + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + response, err := a.client.Do(req) + if err != nil { + return nil, err + } + defer response.Body.Close() + if response.StatusCode == 401 || response.StatusCode == 403 { + return nil, errAccess + } + if response.StatusCode != 200 { + return nil, errProtocol + } + data, err := io.ReadAll(io.LimitReader(response.Body, 262145)) + if err != nil { + return nil, err + } + if len(data) > 262144 { + return nil, errProtocol + } + return data, nil +} + +func (a *api) family(ctx context.Context) bool { + data, err := a.request(ctx, "luci/dexaflow", nil) + return err == nil && familyPage(string(data)) +} + +func familyPage(page string) bool { + page = strings.ToLower(page) + if !strings.Contains(page, "dexaflow") { + return false + } + if strings.Contains(page, "/dexaflow/app.js") { + return true + } + // An unauthenticated gateway serves a separate login page without app.js. + // Identify that page before asking the operator for credentials; discovery + // itself must never try a password. This is a family marker, not attestation. + return strings.Contains(page, "dexaflow dashboard") && + strings.Contains(page, "'/cgi-bin/dexaflow_auth'") && + strings.Contains(page, "action:'login'") && + strings.Contains(page, `name="user"`) && + strings.Contains(page, `name="password"`) +} + +func (a *api) json(ctx context.Context, path string, form url.Values) (map[string]any, error) { + data, err := a.request(ctx, path, form) + if err != nil { + return nil, err + } + var value map[string]any + if json.Unmarshal(data, &value) != nil || value == nil { + return nil, errProtocol + } + if value["ok"] == false { + return nil, errAccess + } + return value, nil +} + +func (a *api) login(ctx context.Context, c credential) error { + result, err := a.json(ctx, "dexaflow_auth", url.Values{"action": {"login"}, "user": {c.Username}, "password": {c.Password}}) + if err != nil { + return err + } + if result["ok"] != true { + return errAccess + } + return nil +} + +// Explicit allowlists keep raw router responses, identifiers and credentials +// out of heartbeat payloads and incident history. Missing is never zero. +func text(v any) string { + s, ok := v.(string) + if !ok || len(s) > 128 { + return "" + } + return strings.Map(func(r rune) rune { + if unicode.IsControl(r) { + return -1 + } + return r + }, s) +} +func number(v any, low, high float64) *float64 { + f, ok := v.(float64) + if !ok || math.IsNaN(f) || math.IsInf(f, 0) || f < low || f > high { + return nil + } + return &f +} +func bandwidth(v any) *float64 { + // This firmware reports bandwidth as decimal text, unlike RSRP and PCI. + if s, ok := v.(string); ok { + if len(s) == 0 || len(s) > 16 { + return nil + } + parsed, err := strconv.ParseFloat(s, 64) + if err != nil { + return nil + } + v = parsed + } + return number(v, 0, 1000) +} +func boolean(v any) *bool { + b, ok := v.(bool) + if !ok { + return nil + } + return &b +} +func ip(v any) string { + p := net.ParseIP(text(v)) + if p == nil { + return "" + } + return p.String() +} +func mode(v any) string { + s := text(v) + switch s { + case "direct", "aggregation", "proxy", "whitelist", "vpn", "auto", "off", "glue", "vpnone": + return s + } + return "" +} + +func normalize(status, manual, internet, me map[string]any) (Device, error) { + modems, ok := status["modems"].([]any) + if !ok || len(modems) > 3 { + return Device{}, errProtocol + } + d := Device{Family: "DexaFlow", Identity: "local_mac", State: "ready", Internet: "unknown", Modems: []Modem{}, + Firmware: text(me["firmware"]), Uptime: number(status["uptime"], 0, 1e12), + SelectedMode: mode(internet["selected"]), ActiveMode: mode(internet["active"]), + ManualMode: mode(manual["mode"]), ActiveSlots: manualSlots(manual), PersistedMode: mode(manual["persist"]), RebootResets: boolean(manual["reboot_resets"]), ActiveWAN: text(manual["wan"]), + VPSUp: boolean(status["vps_up"]), RTT: number(status["ping"], 0, 60000), + DownKbps: number(status["dl_kbps"], 0, 1e9), UpKbps: number(status["ul_kbps"], 0, 1e9)} + // The vendor separates the selected policy, observed path and verification. + // An IP string or responsive LAN alone does not establish Internet access. + verified := internet["stale"] == false && ((d.ActiveMode == "aggregation" && internet["aggregate_verified"] == true) || (d.ActiveMode == "vpn" && internet["vpn_verified"] == true)) + if d.ActiveMode == "direct" && internet["stale"] == false { + if sims, ok := internet["sims"].([]any); ok { + for _, v := range sims { + if s, ok := v.(map[string]any); ok { + for slot := 1; slot <= 3; slot++ { + if d.ActiveWAN == fmt.Sprintf("wan%d", slot) && s["slot"] == fmt.Sprintf("M%d", slot) && s["state"] == "ok" && (s["cloudflare"] == true || s["google"] == true || s["kernel"] == true) { + verified = true + } + } + } + } + } + } + if verified { + d.Internet = "verified" + } + if status["public_ip_stale"] == false && text(status["public_ip_via"]) == d.ActiveMode && verified { + d.PublicIP = ip(status["public_ip"]) + } + seen := map[int]bool{} + for _, raw := range modems { + m, ok := raw.(map[string]any) + if !ok { + return Device{}, errProtocol + } + slot := number(m["slot"], 1, 3) + if slot == nil || *slot != math.Trunc(*slot) || seen[int(*slot)] { + return Device{}, errProtocol + } + seen[int(*slot)] = true + d.Modems = append(d.Modems, Modem{Slot: int(*slot), Operator: text(m["operator"]), Connectivity: text(m["connectivity"]), Radio: text(m["radio"]), IP: ip(m["ip"]), Technology: text(m["tech"]), Band: text(m["band"]), Bandwidth: bandwidth(m["bandwidth"]), + RSRP: number(m["rsrp"], -160, -20), RSRQ: number(m["rsrq"], -50, 20), SINR: number(m["sinr"], -40, 60), RSSI: number(m["rssi"], -160, 0), CellID: text(m["cell_id"]), PCI: number(m["pci"], 0, 1007), DownKbps: number(m["dl"], 0, 1e9), UpKbps: number(m["ul"], 0, 1e9)}) + } + return d, nil +} + +func (a *api) read(ctx context.Context) (Device, error) { + s, err := a.json(ctx, "dexaflow_status", nil) + if err != nil { + return Device{}, err + } + m, err := a.json(ctx, "dexaflow_manual", nil) + if err != nil { + return Device{}, err + } + i, err := a.json(ctx, "dexaflow_internet", nil) + if err != nil { + return Device{}, err + } + me, err := a.json(ctx, "dexaflow_auth?action=me", nil) + if err != nil { + return Device{}, err + } + return normalize(s, m, i, me) +} diff --git a/apps/node-agent/internal/routers/discovery.go b/apps/node-agent/internal/routers/discovery.go new file mode 100644 index 00000000..e2f1a903 --- /dev/null +++ b/apps/node-agent/internal/routers/discovery.go @@ -0,0 +1,113 @@ +package routers + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "net" + "os" + "os/exec" + "path/filepath" + "strings" + "time" +) + +type route struct { + Gateway string `json:"gateway"` + Dev string `json:"dev"` + PrefSrc string `json:"prefsrc"` +} + +func commandJSON(ctx context.Context, args []string, output any) bool { + ctx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + data, err := exec.CommandContext(ctx, "/usr/sbin/ip", args...).Output() + return err == nil && len(data) <= 65536 && json.Unmarshal(data, output) == nil +} + +func physical(name string) bool { + if name == "" || filepath.Base(name) != name { + return false + } + _, err := os.Stat(filepath.Join("/sys/class/net", name, "device")) + return err == nil +} + +func onLink(iface, address string) (string, bool) { + i, err := net.InterfaceByName(iface) + if err != nil || i.Flags&net.FlagUp == 0 { + return "", false + } + addrs, err := i.Addrs() + if err != nil { + return "", false + } + target := net.ParseIP(address) + if target == nil || target.To4() == nil || !target.IsPrivate() { + return "", false + } + for _, addr := range addrs { + ip, subnet, err := net.ParseCIDR(addr.String()) + if err == nil && ip.To4() != nil && !ip.Equal(target) && subnet.Contains(target) { + return ip.String(), true + } + } + return "", false +} + +// Discovery never scans subnets or follows a Tailscale/default VPN gateway. +// Remembered addresses are eligible only on a currently connected physical LAN. +func discover(ctx context.Context, remembered []Candidate) []Candidate { + var routes []route + if !commandJSON(ctx, []string{"-j", "-4", "route", "show", "table", "main"}, &routes) { + return nil + } + for _, r := range routes { + if r.Gateway != "" { + remembered = append(remembered, Candidate{Address: r.Gateway, Interface: r.Dev}) + } + } + seen := map[string]bool{} + var found []Candidate + for _, c := range remembered { + if len(found) >= maxDevices || seen[c.Address] || !physical(c.Interface) { + continue + } + local, ok := onLink(c.Interface, c.Address) + if !ok { + continue + } + var selected []route + if !commandJSON(ctx, []string{"-j", "-4", "route", "get", c.Address}, &selected) || len(selected) != 1 || selected[0].Dev != c.Interface || selected[0].Gateway != "" { + continue + } + c.LocalIP, c.MAC = local, neighbor(c.Interface, c.Address) + seen[c.Address] = true + found = append(found, c) + } + return found +} + +func neighbor(iface, ip string) string { + data, err := os.ReadFile("/proc/net/arp") + if err != nil || len(data) > 65536 { + return "" + } + for _, line := range strings.Split(string(data), "\n") { + f := strings.Fields(line) + if len(f) != 6 || f[0] != ip || f[5] != iface || f[2] != "0x2" { + continue + } + mac, err := net.ParseMAC(f[3]) + if err == nil && len(mac) == 6 && mac[0]&1 == 0 && f[3] != "00:00:00:00:00:00" { + return mac.String() + } + } + return "" +} + +func identity(mac string) string { + sum := sha256.Sum256([]byte("dexaflow:lan:" + mac)) + return "router_" + hex.EncodeToString(sum[:12]) +} diff --git a/apps/node-agent/internal/routers/events.go b/apps/node-agent/internal/routers/events.go new file mode 100644 index 00000000..dcb2f9de --- /dev/null +++ b/apps/node-agent/internal/routers/events.go @@ -0,0 +1,55 @@ +package routers + +import "fmt" + +func (c *Collector) transitions(old, next Device) { + if old.State != next.State { + c.event(next.ID, "availability", 0, old.State, next.State) + } + if old.Address != "" && old.Address != next.Address { + c.event(next.ID, "address_changed", 0, old.Address, next.Address) + } + if next.State != "ready" { + return + } + if old.Uptime != nil && next.Uptime != nil && *next.Uptime+5 < *old.Uptime { + c.event(next.ID, "router_restarted", 0, "", "") + } + if old.ActiveMode != "" && old.ActiveMode != next.ActiveMode { + c.event(next.ID, "mode_changed", 0, old.ActiveMode, next.ActiveMode) + } + if old.Internet != next.Internet { + c.event(next.ID, "internet_verification", 0, old.Internet, next.Internet) + } + if old.Firmware != "" && next.Firmware != "" && old.Firmware != next.Firmware { + c.event(next.ID, "firmware_changed", 0, old.Firmware, next.Firmware) + } + for _, m := range next.Modems { + for _, previous := range old.Modems { + if m.Slot == previous.Slot { + if m.Radio != previous.Radio || m.Connectivity != previous.Connectivity { + c.event(next.ID, "modem_state", m.Slot, previous.Radio+" / "+previous.Connectivity, m.Radio+" / "+m.Connectivity) + } + if m.Operator != previous.Operator { + c.event(next.ID, "operator_changed", m.Slot, previous.Operator, m.Operator) + } + } + } + // Three consecutive weak samples; recovery requires margin. No inference + // that a particular antenna connector is broken from modem-level signal. + key := fmt.Sprintf("%s:%d", next.ID, m.Slot) + weak := (m.RSRP != nil && *m.RSRP < -115) || (m.SINR != nil && *m.SINR < 0) + recovered := m.RSRP != nil && *m.RSRP > -110 && m.SINR != nil && *m.SINR > 3 + if weak && c.weak[key] < 3 { + c.weak[key]++ + if c.weak[key] == 3 { + c.event(next.ID, "signal_weak", m.Slot, "", "") + } + } else if recovered && c.weak[key] >= 3 { + c.weak[key] = 0 + c.event(next.ID, "signal_recovered", m.Slot, "", "") + } else if !weak && c.weak[key] < 3 { + c.weak[key] = 0 + } + } +} diff --git a/apps/node-agent/internal/routers/profile.go b/apps/node-agent/internal/routers/profile.go new file mode 100644 index 00000000..89b204a9 --- /dev/null +++ b/apps/node-agent/internal/routers/profile.go @@ -0,0 +1,25 @@ +package routers + +import ( + _ "embed" + "encoding/json" +) + +// The factory profile is embedded in the versioned Node package. A clean host +// needs no manually installed monitor, cron, secret file or network override. +// +//go:embed profile.json +var profileJSON []byte + +func profileValid() bool { + var p struct { + Schema string `json:"schema"` + Poll int `json:"poll_seconds"` + Devices int `json:"max_devices"` + Events int `json:"journal_events"` + Days int `json:"journal_days"` + Network bool `json:"network_changes"` + Router bool `json:"router_changes"` + } + return json.Unmarshal(profileJSON, &p) == nil && p.Schema == "missioncore.router-observation-profile/v1" && p.Poll == 10 && p.Devices == maxDevices && p.Events == maxEvents && p.Days == 7 && !p.Network && p.Router +} diff --git a/apps/node-agent/internal/routers/profile.json b/apps/node-agent/internal/routers/profile.json new file mode 100644 index 00000000..eb5edc3a --- /dev/null +++ b/apps/node-agent/internal/routers/profile.json @@ -0,0 +1,16 @@ +{ + "schema": "missioncore.router-observation-profile/v1", + "revision": "dexaflow-lan/3", + "adapter": "dexaflow-cgi/v1", + "discovery": "physical-private-ipv4-gateways", + "poll_seconds": 10, + "max_devices": 4, + "journal_events": 256, + "journal_days": 7, + "network_changes": false, + "router_changes": true, + "router_actions": ["mode", "reboot"], + "command_replay": false, + "credentials": "local-private-store", + "wifi_required": false +} diff --git a/apps/node-agent/internal/routers/routers_test.go b/apps/node-agent/internal/routers/routers_test.go new file mode 100644 index 00000000..5d3d6f91 --- /dev/null +++ b/apps/node-agent/internal/routers/routers_test.go @@ -0,0 +1,273 @@ +package routers + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/cookiejar" + "net/http/httptest" + "os" + "strings" + "testing" + "time" +) + +func fixture() (map[string]any, map[string]any, map[string]any, map[string]any) { + return map[string]any{"uptime": 100., "public_ip": "203.0.113.5", "public_ip_stale": false, "public_ip_via": "direct", "modems": []any{map[string]any{"slot": 1., "operator": "Test Mobile", "radio": "OK", "connectivity": "online", "rsrp": -113., "sinr": -2., "band": "B1"}, map[string]any{"slot": 2., "radio": "NOSIM", "rsrp": nil}}}, map[string]any{"wan": "wan1", "persist": "direct", "reboot_resets": true}, map[string]any{"selected": "aggregation", "active": "direct", "stale": false, "sims": []any{map[string]any{"slot": "M1", "state": "ok", "cloudflare": true}}}, map[string]any{"firmware": "test-1", "password": "must-not-escape", "code": "pairing-secret"} +} + +func TestNormalizedReadDoesNotInventSignalOrPolicy(t *testing.T) { + s, m, i, me := fixture() + s["modems"].([]any)[0].(map[string]any)["bandwidth"] = "15" + d, err := normalize(s, m, i, me) + if err != nil { + t.Fatal(err) + } + if d.SelectedMode != "aggregation" || d.ActiveMode != "direct" || d.Internet != "verified" || d.PublicIP == "" { + t.Fatal(d) + } + if d.Modems[1].RSRP != nil || d.Modems[0].RSRP == nil || *d.Modems[0].RSRP != -113 { + t.Fatal(d.Modems) + } + if d.Modems[0].Bandwidth == nil || *d.Modems[0].Bandwidth != 15 || d.Modems[1].Bandwidth != nil { + t.Fatal("firmware bandwidth text or missing value was misread") + } + for _, value := range []any{"", "unknown", "15 MHz", "NaN", "Inf", "-1", "1001"} { + if bandwidth(value) != nil { + t.Fatal("invalid bandwidth accepted", value) + } + } + raw, _ := json.Marshal(d) + if strings.Contains(string(raw), "secret") || strings.Contains(string(raw), "password") { + t.Fatal("private auth response escaped") + } + i["stale"] = true + d, _ = normalize(s, m, i, me) + if d.Internet != "unknown" || d.PublicIP != "" { + t.Fatal("stale Internet proof accepted") + } + s["modems"] = []any{map[string]any{"slot": 1.}, map[string]any{"slot": 1.}} + if _, e := normalize(s, m, i, me); e == nil { + t.Fatal("duplicate slots accepted") + } +} + +func testAPI(server *httptest.Server) *api { + jar, _ := cookiejar.New(nil) + client := server.Client() + client.Jar = jar + client.CheckRedirect = func(*http.Request, []*http.Request) error { return errProtocol } + return &api{base: server.URL + "/cgi-bin/", client: client, check: func() bool { return true }} +} + +const loginPageFixture = `<title>Dexaflow — вход

Dexaflow Dashboard

+ +` + +func TestFamilyDiscoveryBeforeLogin(t *testing.T) { + for _, page := range []string{loginPageFixture, `Dexaflow