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.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:09:59 +03:00
parent 8b210258ca
commit 5d56237124
30 changed files with 3089 additions and 0 deletions
@@ -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))};
}
@@ -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 <RouterEquipment key={vehicleID} transport={transport}/>;
}
@@ -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(`<h2>SIM M${slot}</h2>`));
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/);
});
+56
View File
@@ -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))
}
@@ -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
}
}
+273
View File
@@ -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
}
}
@@ -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)
}
}
@@ -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, "<title>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)
}
@@ -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])
}
@@ -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
}
}
}
@@ -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
}
@@ -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
}
@@ -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 — вход</title><h1>Dexaflow Dashboard</h1>
<input name="user"><input name="password" type="password">
<script>const body = {action:'login'}; fetch('/cgi-bin/dexaflow_auth', {method:'POST',body});</script>`
func TestFamilyDiscoveryBeforeLogin(t *testing.T) {
for _, page := range []string{loginPageFixture, `<title>Dexaflow</title><script src="/dexaflow/app.js?v=1">`} {
if !familyPage(page) {
t.Fatal("supported authenticated or unauthenticated page missed")
}
}
for _, page := range []string{
`<title>Other router</title>Dexaflow /dexaflow/app.js`,
`<title>Dexaflow</title><input name="user"><input name="password">`,
strings.ReplaceAll(loginPageFixture, "'/cgi-bin/dexaflow_auth'", "'https://example.invalid/cgi-bin/dexaflow_auth'"),
strings.ReplaceAll(loginPageFixture, "action:'login'", "action:'other'"),
} {
if familyPage(page) {
t.Fatal("unconfirmed family accepted")
}
}
}
func TestSlowModemStatusAndCallerCancellation(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(2100 * time.Millisecond):
fmt.Fprint(w, `{"modems":[]}`)
case <-r.Context().Done():
}
}))
defer srv.Close()
a := testAPI(srv)
a.client.Timeout = 8 * time.Second
if _, err := a.request(context.Background(), "dexaflow_status", nil); err != nil {
t.Fatal("slow modem status treated as an unavailable router", err)
}
if _, err := a.request(context.Background(), "luci/dexaflow", nil); err == nil {
t.Fatal("slow discovery exceeded its short budget")
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
if _, err := a.request(ctx, "dexaflow_status", nil); err == nil {
t.Fatal("status ignored caller cancellation")
}
}
func TestRedirectBodyLimitAndLocalPin(t *testing.T) {
requests := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests++
switch r.URL.Path {
case "/cgi-bin/redirect":
http.Redirect(w, r, "/target", 302)
case "/cgi-bin/large":
fmt.Fprint(w, strings.Repeat("a", 262145))
default:
fmt.Fprint(w, `{"ok":true}`)
}
}))
defer srv.Close()
a := testAPI(srv)
if _, e := a.request(context.Background(), "redirect", nil); e == nil || requests != 1 {
t.Fatal("redirect followed")
}
if _, e := a.request(context.Background(), "large", nil); e == nil {
t.Fatal("oversize accepted")
}
a.check = func() bool { return false }
if e := a.login(context.Background(), credential{"operator", "synthetic-secret"}); e != errLink || requests != 2 {
t.Fatal("credential sent after link change")
}
}
func TestCollectorDiscoveryAuthorizationAndReplacement(t *testing.T) {
logged := false
logins := 0
s, m, i, me := fixture()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/cgi-bin/luci/dexaflow" {
if !logged {
fmt.Fprint(w, loginPageFixture)
} else {
fmt.Fprint(w, `<title>Dexaflow</title><script src="/dexaflow/app.js?v=1">`)
}
return
}
if r.URL.Path == "/cgi-bin/dexaflow_auth" && r.Method == "POST" {
_ = r.ParseForm()
if r.Form.Get("password") != "synthetic-secret" {
t.Error("unexpected password")
}
logged = true
logins++
json.NewEncoder(w).Encode(map[string]any{"ok": true})
return
}
if !logged {
w.WriteHeader(401)
return
}
value := map[string]any{"/cgi-bin/dexaflow_status": s, "/cgi-bin/dexaflow_manual": m, "/cgi-bin/dexaflow_internet": i, "/cgi-bin/dexaflow_auth": me}[r.URL.Path]
json.NewEncoder(w).Encode(value)
}))
defer srv.Close()
c := Open(t.TempDir())
mac := "02:00:00:00:00:01"
address := "192.168.50.1"
c.discover = func(context.Context, []Candidate) []Candidate {
return []Candidate{{Address: address, Interface: "eth0", LocalIP: "192.168.50.2"}}
}
c.neighbor = func(string, string) string { return mac }
c.client = func(Candidate) *api { return testAPI(srv) }
c.poll(context.Background())
snapshot := c.Snapshot()
if len(snapshot.Items) != 1 || snapshot.Items[0].State != "access_required" || logins != 0 {
t.Fatal("automatic login or missing discovery", snapshot)
}
cmd := Command{ID: "op_" + strings.Repeat("1", 32), RuntimeID: c.runtime, DeviceID: snapshot.Items[0].ID, Deadline: time.Now().Add(time.Minute).Unix(), Username: "operator", Password: "synthetic-secret"}
if err := c.Submit(cmd); err != nil {
t.Fatal(err)
}
if err := c.Submit(cmd); err != nil {
t.Fatal(err)
}
if len(c.commands) != 1 {
t.Fatal("duplicate delivery queued")
}
c.authorize(context.Background(), <-c.commands)
c.publish()
if c.Snapshot().Items[0].State != "ready" || logins != 1 {
t.Fatal("authorization failed", c.Snapshot())
}
raw, _ := json.Marshal(c.Snapshot())
if strings.Contains(string(raw), "synthetic-secret") {
t.Fatal("password leaked into public snapshot")
}
info, _ := os.Stat(c.path)
if info.Mode().Perm() != 0600 {
t.Fatal("insecure credential storage")
}
address = "192.168.50.3"
c.poll(context.Background())
if len(c.Snapshot().Items) != 1 {
t.Fatal("IP change duplicated router")
}
mac = "02:00:00:00:00:02"
logged = false
c.poll(context.Background())
if logins != 1 {
t.Fatal("replacement inherited credentials")
}
if len(c.Snapshot().Items) != 2 {
t.Fatal("replacement not discovered")
}
}
func TestJournalRotationRestartAndExpiry(t *testing.T) {
dir := t.TempDir()
c := Open(dir)
id := identity("02:00:00:00:00:01")
c.state.Records[id] = record{MAC: "02:00:00:00:00:01", Device: Device{ID: id, State: "ready"}}
for n := 0; n < 300; n++ {
c.event(id, "availability", 0, "ready", "unreachable")
}
c.persist()
c.publish()
if c.Snapshot().Journal.Dropped != 44 || len(c.Snapshot().Events) != 256 {
t.Fatal("journal unbounded")
}
restarted := Open(dir)
if restarted.runtime == c.runtime || len(restarted.Snapshot().Events) != 256 || restarted.Snapshot().Items[0].State != "unreachable" {
t.Fatal("restart lost events or revived stale state")
}
restarted.state.Events[0].At = time.Now().Add(-8 * 24 * time.Hour).Unix()
restarted.persist()
restarted.publish()
if len(restarted.Snapshot().Events) != 255 {
t.Fatal("expired event retained")
}
if err := restarted.Submit(Command{RuntimeID: c.runtime}); err == nil {
t.Fatal("prior runtime request accepted")
}
}
func TestSignalEventRequiresConsecutiveSamples(t *testing.T) {
c := Open(t.TempDir())
s, m, i, me := fixture()
d, _ := normalize(s, m, i, me)
d.ID = identity("02:00:00:00:00:01")
for n := 0; n < 2; n++ {
c.transitions(d, d)
}
if len(c.state.Events) != 0 {
t.Fatal("transient sample treated as incident")
}
c.transitions(d, d)
c.transitions(d, d)
if len(c.state.Events) != 1 || c.state.Events[0].Code != "signal_weak" {
t.Fatal("weak event not deduplicated")
}
strong, sinr := -90., 10.
next := d
next.Modems = append([]Modem{}, d.Modems...)
next.Modems[0].RSRP = &strong
next.Modems[0].SINR = &sinr
c.transitions(d, next)
if c.state.Events[1].Code != "signal_recovered" {
t.Fatal("recovery missing")
}
}
+123
View File
@@ -0,0 +1,123 @@
// Package routers owns bounded observation and explicit, allowlisted router commands.
// It never changes host networking or vehicle control.
package routers
import "time"
const Schema = "missioncore.routers/v1"
const maxDevices = 4
const maxEvents = 256
const retention = 7 * 24 * time.Hour
type Modem struct {
Slot int `json:"slot"`
Operator string `json:"operator"`
Connectivity string `json:"connectivity"`
Radio string `json:"radio"`
IP string `json:"ip"`
Technology string `json:"technology"`
Band string `json:"band"`
Bandwidth *float64 `json:"bandwidth"`
RSRP *float64 `json:"rsrp"`
RSRQ *float64 `json:"rsrq"`
SINR *float64 `json:"sinr"`
RSSI *float64 `json:"rssi"`
CellID string `json:"cell_id"`
PCI *float64 `json:"pci"`
DownKbps *float64 `json:"down_kbps"`
UpKbps *float64 `json:"up_kbps"`
}
type Device struct {
ID string `json:"id"`
Family string `json:"family"`
Identity string `json:"identity"`
Address string `json:"address"`
Interface string `json:"interface"`
LocalIP string `json:"local_ip"`
State string `json:"state"`
ObservedAt int64 `json:"observed_at"`
Firmware string `json:"firmware"`
Uptime *float64 `json:"uptime"`
SelectedMode string `json:"selected_mode"`
ActiveMode string `json:"active_mode"`
PersistedMode string `json:"persisted_mode"`
RebootResets *bool `json:"reboot_resets"`
ManualMode string `json:"manual_mode"`
ActiveSlots []int `json:"active_slots"`
ActiveWAN string `json:"active_wan"`
Internet string `json:"internet"`
PublicIP string `json:"public_ip"`
VPSUp *bool `json:"vps_up"`
RTT *float64 `json:"rtt_ms"`
DownKbps *float64 `json:"down_kbps"`
UpKbps *float64 `json:"up_kbps"`
Modems []Modem `json:"modems"`
}
type Event struct {
Sequence uint64 `json:"sequence"`
At int64 `json:"at"`
BootID string `json:"boot_id"`
ElapsedMS int64 `json:"elapsed_ms"`
DeviceID string `json:"device_id"`
Code string `json:"code"`
Slot int `json:"slot,omitempty"`
Before string `json:"before,omitempty"`
After string `json:"after,omitempty"`
}
type Journal struct {
First uint64 `json:"first_sequence"`
Last uint64 `json:"last_sequence"`
Dropped uint64 `json:"dropped"`
Limit int `json:"limit"`
RetentionDays int `json:"retention_days"`
Error bool `json:"error"`
}
type Result struct {
DeviceID string `json:"device_id,omitempty"`
Action string `json:"action,omitempty"`
ID string `json:"operation_id"`
State string `json:"state"`
Error string `json:"error,omitempty"`
}
type Snapshot struct {
ControlVersion int `json:"control_version"`
Schema string `json:"schema"`
RuntimeID string `json:"runtime_id"`
Available bool `json:"available"`
ObservedAt int64 `json:"observed_at"`
Items []Device `json:"items"`
Events []Event `json:"events"`
Journal Journal `json:"journal"`
Results []Result `json:"results"`
}
type Command struct {
Action string `json:"action,omitempty"`
Mode string `json:"mode,omitempty"`
Slots []int `json:"slots,omitempty"`
ID string `json:"operation_id"`
RuntimeID string `json:"runtime_id"`
DeviceID string `json:"device_id"`
Deadline int64 `json:"deadline"`
Username string `json:"username"`
Password string `json:"password"`
}
// Candidate is obtained solely from the physical, directly connected LAN.
// MAC is a local pin, not a cryptographic assertion about the manufacturer.
type Candidate struct{ Address, Interface, LocalIP, MAC string }
type credential struct{ Username, Password string }
type record struct {
Device Device
MAC string
Access *credential
Rejected bool
}
type state struct {
Schema string
Records map[string]record
Events []Event
Sequence uint64
Dropped uint64
}
+11
View File
@@ -0,0 +1,11 @@
import {RouterEquipment} from '../../../../packages/router-ui/src/RouterEquipment';
import type {RouterSnapshot,RouterTransport} from '../../../../packages/router-ui/src/contracts';
import {request} from './api';
const transport:RouterTransport={
control:value=>request('/api/routers/control','POST',value),
read:()=>request('/api/routers'),
authorize:value=>request('/api/routers/access','POST',value),
operation:async id=>(await request<RouterSnapshot>('/api/routers')).results.find(r=>r.operation_id===id)??{operation_id:id,state:'queued'},
};
export function NodeRouters(){return <RouterEquipment transport={transport}/>;}