From 3ff43dd2af7a9eb681f5600d862aaf2ac82fee63 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Sat, 21 Nov 2026 20:58:25 +0300 Subject: [PATCH] feat(router): confirm DexaFlow modes and expose the paired admin interface --- apps/control-station/src/core/fleet/router.ts | 2 +- apps/control-station/test/routerMode.test.mjs | 34 ++- apps/control-station/test/routers.test.mjs | 77 ++++++- .../internal/node/pairing_recovery.go | 4 + apps/node-agent/internal/node/router_admin.go | 48 ++++ .../internal/node/router_admin_test.go | 65 ++++++ apps/node-agent/internal/routers/admin.go | 101 +++++++++ .../node-agent/internal/routers/admin_test.go | 17 ++ .../routers/client_api_confirmation_test.go | 52 +++++ .../internal/routers/client_api_control.go | 18 +- .../routers/client_api_observation.go | 38 +++- .../internal/routers/client_api_test.go | 68 ++++++ apps/node-agent/internal/routers/collector.go | 26 ++- .../node-agent/internal/routers/diagnostic.go | 161 ++++++++++++++ .../internal/routers/diagnostic_test.go | 64 ++++++ .../internal/routers/evidence_projection.go | 1 + apps/node-agent/internal/routers/inventory.go | 2 +- .../internal/routers/presence_test.go | 102 +++++++++ apps/node-agent/internal/routers/types.go | 1 + docs/node/26_ROUTER_OBSERVATION.md | 65 ++++++ docs/node/42_ROUTER_ADMIN_BRIDGE.md | 34 +++ .../router-ui/src/ClientRouterControls.tsx | 77 ++++--- packages/router-ui/src/RouterDetails.tsx | 2 +- packages/router-ui/src/RouterEquipment.tsx | 2 +- packages/router-ui/src/RouterGeneral.tsx | 13 +- packages/router-ui/src/RouterOverview.tsx | 2 +- packages/router-ui/src/RouterSignal.tsx | 6 +- packages/router-ui/src/contracts.ts | 6 +- packages/router-ui/src/control.ts | 39 +++- packages/router-ui/src/mode.ts | 7 + packages/router-ui/src/useRouters.ts | 7 +- src/k1link/fleet/router_admin.py | 210 ++++++++++++++++++ src/k1link/fleet/router_admin_transport.py | 62 ++++++ src/k1link/fleet/router_contracts.py | 1 + src/k1link/fleet/routers.py | 2 +- src/k1link/web/fleet_router_api.py | 8 + tests/test_router_admin.py | 101 +++++++++ 37 files changed, 1462 insertions(+), 63 deletions(-) create mode 100644 apps/node-agent/internal/node/router_admin.go create mode 100644 apps/node-agent/internal/node/router_admin_test.go create mode 100644 apps/node-agent/internal/routers/admin.go create mode 100644 apps/node-agent/internal/routers/admin_test.go create mode 100644 apps/node-agent/internal/routers/client_api_confirmation_test.go create mode 100644 apps/node-agent/internal/routers/diagnostic.go create mode 100644 apps/node-agent/internal/routers/diagnostic_test.go create mode 100644 apps/node-agent/internal/routers/presence_test.go create mode 100644 docs/node/42_ROUTER_ADMIN_BRIDGE.md create mode 100644 src/k1link/fleet/router_admin.py create mode 100644 src/k1link/fleet/router_admin_transport.py create mode 100644 tests/test_router_admin.py diff --git a/apps/control-station/src/core/fleet/router.ts b/apps/control-station/src/core/fleet/router.ts index f66f3af7..4a1bf0bf 100644 --- a/apps/control-station/src/core/fleet/router.ts +++ b/apps/control-station/src/core/fleet/router.ts @@ -3,5 +3,5 @@ import {fleetRequest} from './useFleet'; export function routerTransport(vehicleID:string):RouterTransport{ const base=`/${encodeURIComponent(vehicleID)}/routers`; - return {inspect:value=>fleetRequest(base+'/inspect','POST',value),control:value=>fleetRequest(base+'/control','POST',value),read:()=>fleetRequest(base),authorize:value=>fleetRequest(base+'/access','POST',value),operation:id=>fleetRequest(base+'/access/'+encodeURIComponent(id))}; + return {openAdmin:device=>fleetRequest(base+'/'+encodeURIComponent(device)+'/admin','POST',{}),inspect:value=>fleetRequest(base+'/inspect','POST',value),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/test/routerMode.test.mjs b/apps/control-station/test/routerMode.test.mjs index 64521727..ffb599e0 100644 --- a/apps/control-station/test/routerMode.test.mjs +++ b/apps/control-station/test/routerMode.test.mjs @@ -4,9 +4,10 @@ import {createServer} from './support/vite-server.mjs'; import {createElement} from 'react'; import {renderToStaticMarkup} from 'react-dom/server'; -let server,routerMode,RouterOverview,ClientRouterControls; +let server,routerMode,RouterOverview,ClientRouterControls,RouterObservation; before(async()=>{ server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}}); + ({RouterObservation}=await server.ssrLoadModule('/src/components/network/RouterObservation.tsx')); ({routerMode}=await server.ssrLoadModule('../../packages/router-ui/src/mode.ts')); ({RouterOverview}=await server.ssrLoadModule('../../packages/router-ui/src/RouterOverview.tsx')); ({ClientRouterControls}=await server.ssrLoadModule('../../packages/router-ui/src/ClientRouterControls.tsx')); @@ -29,10 +30,10 @@ test('configured aggregation with three online SIMs remains a direct fallback ob const d=device(),m=routerMode(d,true); assert.equal(m.configured,'Агрегация');assert.equal(m.current,'Прямой выход · SIM3'); assert.equal(m.activeSlot,1);assert.equal(m.fallback,true);assert.equal(m.mismatch,true); - assert.match(m.message,/Агрегация сейчас не используется/); + assert.match(m.message,/Агрегация задана, но сейчас выход идёт через SIM3/); const html=overview(d),form=controls(d); assert.match(html,/Сейчас: Прямой выход · SIM3/);assert.match(html,/Задано: Агрегация/); - assert.match(form,/Сейчас: Прямой выход · SIM3/);assert.match(form,/Сохранённый режим/); + assert.match(form,/Текущий режим: Прямой выход · SIM3/);assert.match(form,/Сохранённый режим/); assert.ok(form.includes(m.message));assert.ok(html.includes(m.message)); assert.equal((html.match(/текущий выход/g)||[]).length,1); assert.doesNotMatch(html,/· выбран|Одна SIM-карта/); @@ -66,7 +67,7 @@ test('pending, stale and strategy states do not masquerade as failed or active a assert.equal(stale.current,'Нет свежих данных');assert.equal(stale.activeSlot,null); assert.equal(stale.fallback,false);assert.equal(stale.pending,false); const html=overview(d,false),form=controls(d,false); - for(const x of [html,form])assert.match(x,/Сейчас: Нет свежих данных/); + assert.match(html,/Сейчас: Нет свежих данных/);assert.match(form,/Текущий режим: Нет свежих данных/); assert.doesNotMatch(html,/текущий выход|Сейчас: Прямой выход/); for(const configured of ['whitelist','auto']){ const m=routerMode({...d,selected_mode:configured,client_api:{...d.client_api,details:{pending:false,fallback:false}}},true); @@ -79,3 +80,28 @@ test('legacy adapters preserve explicit current WAN without claiming fallback',( assert.equal(routerMode(d,true).fallback,false); assert.equal(routerMode({...d,active_wan:''},true).activeSlot,null); }); + +test('aggregation fallback names the observed SIM and reported reason',()=>{const d=device();d.client_api.details.fallback_reason='preferred_path_unavailable_observed_other_default_route';const m=routerMode(d,true);assert.match(m.message,/Агрегация задана, но сейчас выход идёт через SIM3/);assert.match(m.message,/путь агрегации недоступен/);}); + +test('observation viewport renders three compact scales and only the effective exit',()=>{ + const d={...device(),state:'ready',attached:true,observed_at:Date.now()/1000}; + const html=renderToStaticMarkup(createElement(RouterObservation,{device:d,value:{available:true,fresh:true}})); + assert.equal((html.match(/router-signal-scale/g)||[]).length,3); + assert.equal((html.match(/aria-label="SIM3 · Активный канал"/g)||[]).length,1); + assert.doesNotMatch(html,/router-scale-labels|router-metric-line/); + assert.match(html,/Прямой выход · SIM3/); + assert.ok(html.indexOf('SIM1'){ + const d={...device(),state:'ready',attached:true,observed_at:Date.now()/1000}; + const html=renderToStaticMarkup(createElement(RouterObservation,{device:d,value:{available:true,fresh:true},compact:true})); + assert.equal((html.match(/
x.slot),[2,3,1]);assert.equal(simLabel(device,2),'SIM1'); assert.equal(simChannels({...device,slot_map:null})[0].label,'Канал 1'); assert.equal(routerName({...device,name:'My uplink'}),'My uplink'); - const connected={id:'a',attached:true,state:'ready'},saved={id:'b',attached:false,state:'unreachable'}; - assert.deepEqual(visibleRouters([saved,connected]),[connected]); + const connected={id:'a',attached:true,state:'ready',observed_at:100},saved={id:'b',attached:false,state:'unreachable',observed_at:100}; + assert.deepEqual(visibleRouters({available:true,items:[saved,connected]},110000),[connected]); }); test('Client API controls sort physical SIMs and preserve wire identifiers',async()=>{ const {ClientRouterControls}=await server.ssrLoadModule('../../packages/router-ui/src/ClientRouterControls.tsx'); @@ -135,3 +135,76 @@ test('signal scale exposes four keyboard targets, an honest current level and no const missing=renderToStaticMarkup(createElement(RouterSignal,{rsrp:null})); assert.doesNotMatch(missing,/class="router-signal-marker"/);assert.match(missing,/Уровень сигнала неизвестен/); }); + + +test('reopened controls retain the policy refusal above timers, despite newer inspections',async()=>{ + const {ClientRouterControls}=await server.ssrLoadModule('../../packages/router-ui/src/ClientRouterControls.tsx'); + const d={id:'x',state:'ready',active_mode:'direct',modems:[],client_api:{boot_id:'boot',revision:'r',rights:['policy','recovery'],policy:{mode:'aggregation',fail_seconds:60,recover_seconds:60,min_vpn_seconds:120},checks:[]}}; + const results=[{operation_id:'inspect',device_id:'x',action:'inspect',state:'complete',at:102},{operation_id:'policy',device_id:'x',action:'policy',state:'error',error:'router_busy',at:101}]; + const render=()=>renderToStaticMarkup(createElement(ClientRouterControls,{device:d,value:{control_version:1,runtime_id:'r',results},transport:{},ready:true})); + for(const html of [render(),render()]){ + assert.match(html,/busy/);assert.match(html,/Сохранённый режим/);assert.doesNotMatch(html,/Не применён|Политика сохранена и применена/); + assert.ok(html.indexOf('(busy)'){ + const {policyFeedback}=await server.ssrLoadModule('../../packages/router-ui/src/control.ts'); + const device={selected_mode:'aggregation',active_mode:'aggregation',modems:[],client_api:{policy:{mode:'aggregation'},details:{pending:false}}}; + const receipt={operation_id:'one',device_id:'x',action:'policy',state:'queued'}; + assert.match(policyFeedback(device,true,receipt).label,/Команда отправлена/); + assert.equal(policyFeedback(device,true,receipt).busy,true); + assert.match(policyFeedback(device,true,{...receipt,state:'applying'}).label,/Применяются/); + assert.equal(policyFeedback(device,true,{...receipt,state:'complete'}).tone,'success'); + assert.match(policyFeedback(device,true,{...receipt,state:'complete'}).message,/Агрегация/); + for(const state of ['error','unknown']){ + const result=policyFeedback(device,true,{...receipt,state,error:'router_busy'}); + assert.equal(result.busy,false);assert.equal(result.tone,'warning'); + } + const offline=policyFeedback(device,false,{...receipt,state:'applying'}); + assert.equal(offline.busy,false);assert.match(offline.label,/Нет свежих данных/); + const fallback={...device,active_mode:'direct',active_slots:[1],client_api:{...device.client_api,details:{fallback:true}}}; + assert.equal(policyFeedback(fallback,true,{...receipt,state:'complete'}).tone,'warning'); + assert.match(policyFeedback(fallback,true,{...receipt,state:'complete'}).message,/Агрегация задана, но сейчас выход идёт через/); + const settling={...device,client_api:{...device.client_api,details:{pending:true}}}; + assert.equal(policyFeedback(settling,true,{...receipt,state:'complete'}).tone,'warning'); + assert.equal(policyFeedback(device,false,{...receipt,state:'complete'}).tone,'warning'); +}); + +test('queued and applying policy show one canonical action loader and visible status after reopening',async()=>{ + const {ClientRouterControls}=await server.ssrLoadModule('../../packages/router-ui/src/ClientRouterControls.tsx'); + const device={id:'x',state:'ready',active_mode:'direct',modems:[],client_api:{boot_id:'b',revision:'r',rights:['policy','recovery','diagnostics','reboot'],policy:{mode:'aggregation',fail_seconds:60,recover_seconds:60,min_vpn_seconds:120},checks:[]}}; + for(const state of ['queued','applying','complete','error','unknown']){ + const results=[{operation_id:'one',device_id:'x',action:'policy',state,at:100,error:state==='error'?'router_busy':undefined}]; + const html=renderToStaticMarkup(createElement(ClientRouterControls,{device,value:{control_version:1,runtime_id:'r',results},transport:{},ready:true})); + const pending=['queued','applying'].includes(state); + assert.equal((html.match(/aria-busy="true"/g)||[]).length,pending?1:0); + assert.ok(html.indexOf('role="status"'){ + const {latestControlReceipt,controlMessage}=await server.ssrLoadModule('../../packages/router-ui/src/control.ts'); + const base={operation_id:'old',device_id:'a',action:'policy',state:'complete',at:100}; + const refused={...base,operation_id:'new',state:'error',error:'router_busy',at:102}; + const rows=[{...refused,device_id:'other',at:500},{...base,action:'inspect',at:600},refused,base]; + assert.deepEqual(latestControlReceipt(rows,'a','policy'),refused); + assert.deepEqual(latestControlReceipt([{...refused,state:'applying'}],'a','policy',refused),refused); + assert.deepEqual(latestControlReceipt([refused],'a','policy',{...refused,state:'queued',at:103}),refused); + assert.equal(latestControlReceipt(rows,'absent','policy'),null); + assert.match(controlMessage({state:'applying',error:'receipt_pending'}),/повторная команда не отправляется/); + assert.doesNotMatch(controlMessage({state:'unknown',action:'policy'}),/сохранена и применена/); +}); + +test('lost control response waits for the same receipt and never replays the write',async()=>{ + const {sendControlOnce,controlBusy}=await server.ssrLoadModule('../../packages/router-ui/src/control.ts'); + const initial={operation_id:'one',device_id:'router',action:'policy',state:'queued',at:100}; + let writes=0; + const uncertain=await sendControlOnce({control:async()=>{writes++;throw Error('response lost');}}, {operation_id:'one'},initial); + assert.equal(writes,1);assert.equal(uncertain.operation_id,'one');assert.equal(uncertain.error,'receipt_pending');assert.equal(controlBusy(uncertain),true); + const refused=await sendControlOnce({control:async()=>({operation_id:'one',state:'error',error:'router_busy'})},{operation_id:'one'},initial); + assert.equal(refused.action,'policy');assert.equal(controlBusy(refused),false); + const accepted=await sendControlOnce({control:async()=>({operation_id:'one',state:'queued'})},{operation_id:'one'},initial); + assert.equal(controlBusy(accepted),true); +}); diff --git a/apps/node-agent/internal/node/pairing_recovery.go b/apps/node-agent/internal/node/pairing_recovery.go index 1c395681..9c257e84 100644 --- a/apps/node-agent/internal/node/pairing_recovery.go +++ b/apps/node-agent/internal/node/pairing_recovery.go @@ -48,6 +48,10 @@ func recoveryPeer(state tls.ConnectionState, coreID string) bool { func (p *Pairing) recoveryHandler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v1/router/admin" { + p.routerAdmin(w, r) + return + } w.Header().Set("Cache-Control", "no-store") host, _, err := net.SplitHostPort(r.RemoteAddr) p.mu.Lock() diff --git a/apps/node-agent/internal/node/router_admin.go b/apps/node-agent/internal/node/router_admin.go new file mode 100644 index 00000000..d78bb3e7 --- /dev/null +++ b/apps/node-agent/internal/node/router_admin.go @@ -0,0 +1,48 @@ +package node + +import ( + "encoding/json" + "net" + "net/http" + "nodedc.local/mission-core/node-agent/internal/routers" + "time" +) + +func (p *Pairing) routerAdmin(w http.ResponseWriter, r *http.Request) { + host, _, err := net.SplitHostPort(r.RemoteAddr) + var body routers.AdminRequest + decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 2*1048576)) + decoder.DisallowUnknownFields() + if r.Method != "POST" || err != nil || r.TLS == nil || decoder.Decode(&body) != nil || !body.Valid() { + http.Error(w, "Invalid request", 400) + return + } + p.mu.Lock() + b := p.state.Binding + allowed := p.state.Phase == "paired" && b != nil && p.networkPeerLocked(host) && recoveryPeer(*r.TLS, b.CoreID) && body.BindingID == b.BindingID + collector := p.Routers + p.mu.Unlock() + if !allowed { + http.Error(w, "Binding unavailable", 403) + return + } + if collector == nil { + http.Error(w, "Router unavailable", 503) + return + } + if body.Method == "POST" { + // Extend only an authenticated admin request, not the shared listener. + if err := http.NewResponseController(w).SetWriteDeadline(time.Now().Add(100 * time.Second)); err != nil { + http.Error(w, "Router response deadline unavailable", 503) + return + } + } + result, err := collector.Admin(r.Context(), body) + if err != nil { + http.Error(w, "Router request failed", 502) + return + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + json.NewEncoder(w).Encode(result) +} diff --git a/apps/node-agent/internal/node/router_admin_test.go b/apps/node-agent/internal/node/router_admin_test.go new file mode 100644 index 00000000..dba9263a --- /dev/null +++ b/apps/node-agent/internal/node/router_admin_test.go @@ -0,0 +1,65 @@ +package node + +import ( + "crypto/tls" + "crypto/x509" + "encoding/json" + "net/http/httptest" + "nodedc.local/mission-core/node-agent/internal/routers" + "strings" + "testing" + "time" +) + +type adminDeadlineRecorder struct { + *httptest.ResponseRecorder + deadline time.Time +} + +func (w *adminDeadlineRecorder) SetWriteDeadline(t time.Time) error { w.deadline = t; return nil } + +func TestRouterAdminLongDeadlineRequiresAuthenticatedWrite(t *testing.T) { + p, client := recoveryFixture(t) + p.Routers = routers.Open(t.TempDir()) + cert, _ := x509.ParseCertificate(client.Certificate[0]) + for _, tc := range []struct { + binding, method string + status int + extended bool + }{ + {"old", "POST", 403, false}, + {p.state.Binding.BindingID, "GET", 502, false}, + {p.state.Binding.BindingID, "POST", 502, true}, + } { + body, _ := json.Marshal(map[string]any{"binding_id": tc.binding, "device_id": "router", "method": tc.method, "path": "/cgi-bin/dexaflow_manual"}) + r := httptest.NewRequest("POST", "/v1/router/admin", strings.NewReader(string(body))) + r.RemoteAddr = "100.64.10.5:42000" + r.TLS = &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{cert}}, PeerCertificates: []*x509.Certificate{cert}} + w := &adminDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()} + p.recoveryHandler().ServeHTTP(w, r) + if w.Code != tc.status || !w.deadline.IsZero() != tc.extended { + t.Fatalf("%s: code %d deadline %v", tc.method, w.Code, w.deadline) + } + if tc.extended && time.Until(w.deadline) < 90*time.Second { + t.Fatal("native command inherits the short shared-listener deadline") + } + } +} + +func TestRouterAdminRequiresCurrentBinding(t *testing.T) { + p, client := recoveryFixture(t) + body := map[string]any{"binding_id": "old", "device_id": "router", "method": "GET", "path": "/"} + if out := recoveryCall(p, client, "/v1/router/admin", body); out.Code != 403 { + t.Fatal(out.Code) + } + body["binding_id"] = p.state.Binding.BindingID + if out := recoveryCall(p, client, "/v1/router/admin", body); out.Code != 503 { + t.Fatal(out.Code) + } + if e := p.cancel(); e != nil { + t.Fatal(e) + } + if out := recoveryCall(p, client, "/v1/router/admin", body); out.Code != 403 { + t.Fatal(out.Code) + } +} diff --git a/apps/node-agent/internal/routers/admin.go b/apps/node-agent/internal/routers/admin.go new file mode 100644 index 00000000..c637cd59 --- /dev/null +++ b/apps/node-agent/internal/routers/admin.go @@ -0,0 +1,101 @@ +package routers + +// Browser forwarding is scoped to a freshly observed Ethernet router. It has +// no arbitrary destination, credential injection, redirects or host route edits. +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +type AdminRequest struct { + BindingID string `json:"binding_id"` + DeviceID string `json:"device_id"` + Method string `json:"method"` + Path string `json:"path"` + Headers map[string]string `json:"headers"` + Body []byte `json:"body"` +} +type AdminResponse struct { + Status int `json:"status"` + Headers map[string][]string `json:"headers"` + Body []byte `json:"body"` +} + +func (r AdminRequest) Valid() bool { + u, e := url.ParseRequestURI(r.Path) + return e == nil && strings.HasPrefix(r.Path, "/") && !strings.HasPrefix(r.Path, "//") && u.Host == "" && u.Scheme == "" && !strings.ContainsAny(r.Path, "\r\n\\") && len(r.Path) <= 8192 && len(r.Body) <= 1048576 && len(r.Headers) <= 8 && (r.Method == "GET" || r.Method == "POST" || r.Method == "HEAD") +} +func (c *Collector) Admin(ctx context.Context, in AdminRequest) (AdminResponse, error) { + if !in.Valid() { + return AdminResponse{}, errProtocol + } + var chosen *Device + for _, d := range c.Snapshot().Items { + if d.ID == in.DeviceID && d.Attached && d.Connection == "ethernet" && d.State == "ready" && time.Now().Unix()-d.ObservedAt < 40 { + copy := d + chosen = © + break + } + } + if chosen == nil { + return AdminResponse{}, errors.New("router not available") + } + d := chosen + candidate := Candidate{Address: d.Address, Interface: d.Interface, LocalIP: d.LocalIP, MAC: c.neighbor(d.Interface, d.Address)} + if candidate.MAC == "" { + return AdminResponse{}, errLink + } + a := newAPI(candidate) + a.client.Jar = nil + a.client.Timeout = 8 * time.Second + if in.Method == "POST" { + // Native mode changes and diagnostics synchronously wait for the router. + a.client.Timeout = 90 * time.Second + } + a.client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + defer a.client.CloseIdleConnections() + req, e := http.NewRequestWithContext(ctx, in.Method, "http://"+d.Address+in.Path, bytes.NewReader(in.Body)) + if e != nil { + return AdminResponse{}, e + } + for _, key := range []string{"Cookie", "Content-Type", "Accept", "Accept-Encoding"} { + if v := in.Headers[key]; len(v) <= 16384 { + req.Header.Set(key, v) + } + } + req.Header.Set("Origin", "http://"+d.Address) + req.Header.Set("Referer", "http://"+d.Address+"/cgi-bin/luci/dexaflow") + if !a.check() { + return AdminResponse{}, errLink + } + response, e := a.client.Do(req) + if e != nil { + return AdminResponse{}, e + } + defer response.Body.Close() + body, e := io.ReadAll(io.LimitReader(response.Body, 8*1048576+1)) + if e != nil || len(body) > 8*1048576 { + return AdminResponse{}, errProtocol + } + out := AdminResponse{Status: response.StatusCode, Body: body, Headers: map[string][]string{}} + for _, key := range []string{"Content-Type", "Content-Encoding", "Set-Cookie", "Location", "Content-Disposition"} { + values := response.Header.Values(key) + if key == "Location" && len(values) > 0 { + u, e := url.Parse(values[0]) + if e != nil || (u.Host != "" && u.Host != d.Address) { + return AdminResponse{}, errProtocol + } + values = []string{u.RequestURI()} + } + if len(values) > 0 { + out.Headers[key] = values + } + } + return out, nil +} diff --git a/apps/node-agent/internal/routers/admin_test.go b/apps/node-agent/internal/routers/admin_test.go new file mode 100644 index 00000000..16a3b445 --- /dev/null +++ b/apps/node-agent/internal/routers/admin_test.go @@ -0,0 +1,17 @@ +package routers + +import "testing" + +func TestAdminRequestRejectsDestinationEscapes(t *testing.T) { + for _, path := range []string{"https://other/", "//other/path", "/bad\nheader", "/back\\slash"} { + if (AdminRequest{Method: "GET", Path: path}).Valid() { + t.Fatal("accepted", path) + } + } + if !(AdminRequest{Method: "GET", Path: "/cgi-bin/luci/dexaflow?x=1"}).Valid() { + t.Fatal("native path rejected") + } + if (AdminRequest{Method: "CONNECT", Path: "/"}).Valid() { + t.Fatal("tunnel accepted") + } +} diff --git a/apps/node-agent/internal/routers/client_api_confirmation_test.go b/apps/node-agent/internal/routers/client_api_confirmation_test.go new file mode 100644 index 00000000..ad8c83dd --- /dev/null +++ b/apps/node-agent/internal/routers/client_api_confirmation_test.go @@ -0,0 +1,52 @@ +package routers + +import ( + "encoding/json" + "testing" +) + +func TestClientAPIConfirmationFollowsFreshActiveMode(t *testing.T) { + caps := []byte(`{"api_version":"1","schema_version":"1.1","rights":["read"]}`) + for _, tc := range []struct { + name, observed, effective string + wanVerified bool + server string + internet string + }{ + {"aggregation-with-inactive-vpn", `{"active":"aggregation","stale":false,"aggregate_checked":true,"aggregate_verified":true,"vpn_verified":false}`, "", false, "true", "verified"}, + {"aggregation-failed-vpn-healthy", `{"active":"aggregation","stale":false,"aggregate_checked":true,"aggregate_verified":false,"vpn_verified":true}`, "", true, "false", "unknown"}, + {"aggregation-not-checked", `{"active":"aggregation","stale":false,"aggregate_checked":false,"aggregate_verified":false}`, "", false, "null", "unknown"}, + {"aggregation-missing-proof", `{"active":"aggregation","stale":false}`, "", false, "null", "unknown"}, + {"aggregation-null-proof", `{"active":"aggregation","stale":false,"aggregate_verified":null}`, "", false, "null", "unknown"}, + {"aggregation-invalid-proof", `{"active":"aggregation","stale":false,"aggregate_verified":"true"}`, "", false, "null", "unknown"}, + {"aggregation-stale", `{"active":"aggregation","stale":true,"aggregate_verified":true}`, "", true, "null", "unknown"}, + {"freshness-missing", `{"active":"aggregation","aggregate_verified":true}`, "", true, "null", "unknown"}, + {"vpn-confirmed", `{"active":"vpn","stale":false,"aggregate_verified":false,"vpn_verified":true}`, "", false, "true", "verified"}, + {"vpn-failed-aggregation-healthy", `{"active":"vpn","stale":false,"aggregate_verified":true,"vpn_verified":false}`, "", true, "false", "unknown"}, + {"direct-does-not-inherit-server-proof", `{"active":"direct","stale":false,"aggregate_verified":true,"vpn_verified":true}`, "wan1", false, "null", "unknown"}, + {"direct-selected-wan-verified", `{"active":"direct","stale":false}`, "wan1", true, "null", "verified"}, + {"direct-other-wan-verified", `{"active":"direct","stale":false}`, "wan2", true, "null", "unknown"}, + {"direct-missing-effective-wan", `{"active":"direct","stale":false}`, "", true, "null", "unknown"}, + {"unknown-mode", `{"active":"future","stale":false,"aggregate_verified":true,"vpn_verified":true}`, "wan1", true, "null", "unknown"}, + } { + t.Run(tc.name, func(t *testing.T) { + var observed map[string]any + if err := json.Unmarshal([]byte(tc.observed), &observed); err != nil { + t.Fatal(err) + } + status := map[string]any{"boot_id": "synthetic-boot", "uptime": 100, "revision": "r1", "observed": observed, + "desired_policy": map[string]any{"mode": "aggregation"}, "persisted_policy": map[string]any{"mode": "aggregation"}, + "effective_wan": tc.effective, "vpn": map[string]any{"verified": false}, + "wan": []any{map[string]any{"slot": "M1", "wan": "wan1", "up": true, "internet_verified": tc.wanVerified}}, "modems": []any{}} + raw, _ := json.Marshal(status) + d, err := normalizeClientAPI(caps, raw) + if err != nil { + t.Fatal(err) + } + server, _ := json.Marshal(d.VPSUp) + if string(server) != tc.server || d.Internet != tc.internet { + t.Fatalf("server=%s internet=%s; want %s/%s", server, d.Internet, tc.server, tc.internet) + } + }) + } +} diff --git a/apps/node-agent/internal/routers/client_api_control.go b/apps/node-agent/internal/routers/client_api_control.go index af546822..16ae1d22 100644 --- a/apps/node-agent/internal/routers/client_api_control.go +++ b/apps/node-agent/internal/routers/client_api_control.go @@ -104,7 +104,7 @@ func (c *Collector) verifyClientControl(ctx context.Context, candidates []Candid result.VendorID = pending.OperationID c.results[pending.Command.ID] = result c.mu.Unlock() - c.event(pending.Command.DeviceID, code, 0, pending.Command.Action, "") + c.event(pending.Command.DeviceID, code, 0, pending.Command.Action, reason) c.clientControl = nil } if !time.Now().Before(pending.Until) { @@ -131,6 +131,7 @@ func (c *Collector) verifyClientControl(ctx context.Context, candidates []Candid ID string `json:"operation_id"` State string `json:"state"` Kind string `json:"kind"` + Error string `json:"error"` Result struct { Persisted *bool `json:"persisted"` Applied *bool `json:"applied"` @@ -148,7 +149,7 @@ func (c *Collector) verifyClientControl(ctx context.Context, candidates []Candid } finish("complete", "", "command_complete") case "failed": - finish("error", "command_rejected", "command_failed") + finish("error", clientOperationError(op.Error), "command_failed") case "interrupted", "unknown": finish("unknown", "confirmation_timeout", "command_unconfirmed") } @@ -161,3 +162,16 @@ func sameClientPolicy(a, b clientPolicy) bool { y, _ := json.Marshal(b) return string(x) == string(y) } + +// Only documented public codes may leave the vendor boundary. A failed async +// operation is not equivalent to an HTTP rejection of its initial request. +func clientOperationError(code string) string { + switch code { + case "busy": + return "router_busy" + case "revision_conflict", "superseded", "boot_id_mismatch": + return "router_conflict" + default: + return "command_rejected" + } +} diff --git a/apps/node-agent/internal/routers/client_api_observation.go b/apps/node-agent/internal/routers/client_api_observation.go index 5ba9c467..88d4b132 100644 --- a/apps/node-agent/internal/routers/client_api_observation.go +++ b/apps/node-agent/internal/routers/client_api_observation.go @@ -115,11 +115,21 @@ func normalizeClientAPI(capsRaw, statusRaw []byte) (Device, error) { d.ActiveMode = text(observed["active"]) d.ManualMode = d.SelectedMode d.ActiveWAN = text(status["effective_wan"]) - if observed["stale"] == false && (observed["aggregate_verified"] == true || observed["vpn_verified"] == true) { - d.Internet = "verified" + // Confirmation belongs to the observed path, never the configured policy or + // a different (possibly inactive) VPN. Missing/stale proof remains unknown. + if observed["stale"] == false { + switch d.ActiveMode { + case "aggregation": + if observed["aggregate_checked"] != false { + d.VPSUp = boolValue(observed["aggregate_verified"]) + } + case "vpn": + d.VPSUp = boolValue(observed["vpn_verified"]) + } + if d.VPSUp != nil && *d.VPSUp { + d.Internet = "verified" + } } - vpn := object(status["vpn"]) - d.VPSUp = boolValue(vpn["verified"]) recovery := object(status["recovery"]) detail.RecoveryPhase = text(recovery["phase"]) detail.RecoveryReason = text(recovery["reason_code"]) @@ -143,7 +153,8 @@ func normalizeClientAPI(capsRaw, statusRaw []byte) (Device, error) { } } detail.WAN = append(detail.WAN, clientWAN{Slot: slot, WAN: text(w["wan"]), Interface: text(w["interface"]), Up: boolValue(w["up"]), SIMPresent: boolValue(w["sim_present"]), ModemPresent: boolValue(w["modem_present"]), Registration: text(registration["registration_state"]), FailureReason: failure, Fresh: boolValue(registration["fresh"]), AgeSeconds: number(registration["age_s"], 0, 1e12), Traffic: readTraffic(w["traffic"]), ObservedUptime: number(w["observed_uptime"], 0, 1e12), SessionUptime: number(w["uptime_s"], 0, 1e12)}) - if observed["stale"] == false && w["internet_verified"] == true { + if observed["stale"] == false && d.ActiveMode == "direct" && d.ActiveWAN != "" && + (d.ActiveWAN == w["wan"] || d.ActiveWAN == w["slot"]) && w["internet_verified"] == true { d.Internet = "verified" } // A slot being up does not prove it participates in aggregation. Only a @@ -195,12 +206,18 @@ func (c *Collector) pollClientAPI(ctx context.Context, candidates []Candidate, s if candidate.Address == r.Device.Address && c.neighbor(candidate.Interface, candidate.Address) == r.MAC { handled[candidate.Address] = true seen[id] = true - r.Device.Attached = true - r.Device.Connection = "ethernet" - c.state.Records[id] = r if r.Rejected { - seen[id] = true - r.Device.ObservedAt = time.Now().Unix() + // A remembered ARP entry alone cannot prove current presence. + // Recheck the public panel without retrying rejected credentials. + old := r.Device + r.Device.Attached = c.client(candidate).family(ctx) + if r.Device.Attached { + r.Device.State = "access_rejected" + r.Device.ObservedAt = time.Now().Unix() + } else { + r.Device.State = "unreachable" + } + c.transitions(old, r.Device) c.state.Records[id] = r break } @@ -218,6 +235,7 @@ func (c *Collector) pollClientAPI(ctx context.Context, candidates []Candidate, s if err != nil && !(errors.As(err, &apiErr) && (apiErr.Status == 401 || apiErr.Status == 403)) { if seen[id] { r.Device.State = "unreachable" + r.Device.Attached = false c.state.Records[id] = r } delete(c.traffic, id) diff --git a/apps/node-agent/internal/routers/client_api_test.go b/apps/node-agent/internal/routers/client_api_test.go index cfe142be..bd23e982 100644 --- a/apps/node-agent/internal/routers/client_api_test.go +++ b/apps/node-agent/internal/routers/client_api_test.go @@ -306,3 +306,71 @@ func TestClientAPIControlAcceptedIsNotComplete(t *testing.T) { t.Fatal("operation verification failed") } } + +func TestClientPolicyAsyncOutcome(t *testing.T) { + for _, tc := range []struct { + name, state, code, wantState, wantError string + persisted, applied, observed bool + }{ + {"busy", "failed", "busy", "error", "router_busy", false, false, false}, + {"changed", "failed", "superseded", "error", "router_conflict", false, false, false}, + {"private-error", "failed", "secret-token-or-response", "error", "command_rejected", false, false, false}, + {"interrupted", "interrupted", "", "unknown", "confirmation_timeout", false, false, false}, + {"not-persisted", "succeeded", "", "applying", "", false, true, true}, + {"not-applied", "succeeded", "", "applying", "", true, false, true}, + {"stale-readback", "succeeded", "", "applying", "", true, true, false}, + {"confirmed", "succeeded", "", "complete", "", true, true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + var writes atomic.Int32 + a, ca := clientAPIFixture(t, func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/client/v1/status": + io.WriteString(w, `{"boot_id":"boot-1","revision":"r1"}`) + case "/api/client/v1/policy": + writes.Add(1) + w.WriteHeader(202) + io.WriteString(w, `{"operation_id":"policy-1","kind":"policy","state":"accepted"}`) + case "/api/client/v1/operations/policy-1": + json.NewEncoder(w).Encode(map[string]any{"operation_id": "policy-1", "kind": "policy", "state": tc.state, "error": tc.code, "result": map[string]bool{"persisted": tc.persisted, "applied": tc.applied}}) + default: + t.Error("unexpected path", r.URL.Path) + w.WriteHeader(404) + } + }) + c := Open(t.TempDir()) + candidate := Candidate{Address: "192.168.1.1", LocalIP: "192.168.1.2", Interface: "eth-test"} + c.discover = func(context.Context, []Candidate) []Candidate { return []Candidate{candidate} } + c.apiClient = func(Candidate, clientAPIAccess) (*clientAPI, error) { return a, nil } + expected := clientPolicy{Mode: "direct", PreferredSIM: "M1", AllowFallback: true, ReturnToPreferred: true, Persist: true, FailSeconds: 60, RecoverSeconds: 60, MinVPNSeconds: 120} + r := record{Device: Device{ID: a.identity, Address: candidate.Address, Interface: candidate.Interface, State: "ready", ClientAPI: &clientPublic{Rights: []string{"read", "policy"}}}, Access: &credential{ClientAPI: &clientAPIAccess{Token: "synthetic-private-key", CA: ca}}} + if tc.observed { + r.Device.ClientAPI.Policy = expected + } + c.state.Records[a.identity] = r + cmd := Command{ID: "op_0123456789abcdef0123456789abcdef", RuntimeID: c.runtime, DeviceID: a.identity, Action: "policy", ExpectedBootID: "boot-1", ExpectedRevision: "r1", Deadline: time.Now().Add(time.Minute).Unix(), Policy: &expected} + c.applyClientControl(context.Background(), cmd, r) + if writes.Load() != 1 || c.results[cmd.ID].State != "applying" { + t.Fatal("HTTP 202 was not pending", c.results[cmd.ID]) + } + c.verifyClientControl(context.Background(), []Candidate{candidate}) + result := c.results[cmd.ID] + if result.State != tc.wantState || result.Error != tc.wantError || writes.Load() != 1 { + t.Fatal("wrong terminal outcome or replay", result, writes.Load()) + } + if tc.wantState != "applying" { + if result.VendorID != "policy-1" { + t.Fatal("vendor correlation lost") + } + event := c.state.Events[len(c.state.Events)-1] + if event.After != tc.wantError { + t.Fatal("reason lost in journal", event) + } + c.verifyClientControl(context.Background(), []Candidate{candidate}) + if writes.Load() != 1 { + t.Fatal("terminal failure was retried") + } + } + }) + } +} diff --git a/apps/node-agent/internal/routers/collector.go b/apps/node-agent/internal/routers/collector.go index 9ee2542c..df815469 100644 --- a/apps/node-agent/internal/routers/collector.go +++ b/apps/node-agent/internal/routers/collector.go @@ -16,6 +16,13 @@ import ( ) type Collector struct { + devUntil atomic.Int64 + devSequence uint64 + devRows []DiagnosticEvent + devEventsAt map[string]time.Time + devSeen map[string]bool + devCursors map[string]string + devBoots map[string]string speedUpdates chan struct{} speedCancel context.CancelFunc speedOperation, speedDevice string @@ -86,6 +93,13 @@ func (c *Collector) Snapshot() Snapshot { data, _ := json.Marshal(c.view.Load().(Snapshot)) var s Snapshot _ = json.Unmarshal(data, &s) + for i := range s.Items { + age := time.Now().Unix() - s.Items[i].ObservedAt + if age >= 40 || age < -30 { + s.Items[i].Attached = false + s.Items[i].State = "unreachable" + } + } c.mu.Lock() s.Results = []Result{} for _, r := range c.results { @@ -151,7 +165,7 @@ func (c *Collector) Submit(cmd Command) error { } select { case c.commands <- cmd: - c.results[cmd.ID] = Result{ID: cmd.ID, DeviceID: cmd.DeviceID, Action: cmd.Action, State: "queued"} + c.results[cmd.ID] = Result{At: now.Unix(), ID: cmd.ID, DeviceID: cmd.DeviceID, Action: cmd.Action, State: "queued"} c.resultTimes[cmd.ID] = now return nil default: @@ -164,7 +178,7 @@ func (c *Collector) publish() { c.evidenceCache = nil c.evidence = nil } - s := Snapshot{SpeedtestVersion: 1, ReadVersion: 1, Evidence: c.evidence, 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}} + s := Snapshot{AdminVersion: 1, SpeedtestVersion: 1, ReadVersion: 1, Evidence: c.evidence, 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 } @@ -227,7 +241,13 @@ func (c *Collector) Run(ctx context.Context) { if c.blocked { return } + c.devEventsAt = map[string]time.Time{} + c.devSeen = map[string]bool{} + c.devCursors = map[string]string{} + c.devBoots = map[string]string{} c.poll(ctx) + diagnosticTicker := time.NewTicker(time.Second) + defer diagnosticTicker.Stop() ticker := time.NewTicker(10 * time.Second) defer ticker.Stop() for { @@ -249,6 +269,8 @@ func (c *Collector) Run(ctx context.Context) { c.applyControl(ctx, cmd) } c.publish() + case <-diagnosticTicker.C: + c.pollDiagnostic(ctx) case <-ticker.C: c.poll(ctx) } diff --git a/apps/node-agent/internal/routers/diagnostic.go b/apps/node-agent/internal/routers/diagnostic.go new file mode 100644 index 00000000..8d43fdc0 --- /dev/null +++ b/apps/node-agent/internal/routers/diagnostic.go @@ -0,0 +1,161 @@ +package routers + +// Opt-in, expiring DEV interest: GETs only, no modem commands or recovery jobs. +import ( + "context" + "encoding/json" + "errors" + "time" +) + +type DiagnosticEvent struct { + Sequence uint64 + DeviceID, Event, At string + Data map[string]any +} + +func (c *Collector) DiagnosticInterest() { + c.devUntil.Store(time.Now().Add(3 * time.Second).UnixNano()) +} +func (c *Collector) DiagnosticTail(after uint64) []DiagnosticEvent { + c.mu.Lock() + defer c.mu.Unlock() + out := []DiagnosticEvent{} + for _, row := range c.devRows { + if row.Sequence > after { + out = append(out, row) + } + } + return out +} +func (c *Collector) devRecord(id, event string, data map[string]any) { + raw, e := json.Marshal(data) + if e != nil { + return + } + if len(raw) > 6500 { + data = map[string]any{"state": "record_omitted", "reason": "size_bound", "bytes": len(raw)} + } + c.mu.Lock() + defer c.mu.Unlock() + c.devSequence++ + c.devRows = append(c.devRows, DiagnosticEvent{c.devSequence, id, event, time.Now().UTC().Format(time.RFC3339Nano), data}) + if len(c.devRows) > 128 { + c.devRows = c.devRows[len(c.devRows)-128:] + } +} +func diagnosticFields(source map[string]any, keys ...string) map[string]any { + out := map[string]any{} + for _, k := range keys { + if v, ok := source[k]; ok { + out[k] = v + } + } + return out +} +func (c *Collector) pollDiagnostic(ctx context.Context) { + if time.Now().UnixNano() > c.devUntil.Load() { + return + } + for id, r := range c.state.Records { + if r.Access == nil || r.Access.ClientAPI == nil || r.Rejected { + continue + } + if !r.Device.Attached { + continue + } + a, e := c.apiClient(Candidate{Address: r.Device.Address, Interface: r.Device.Interface, LocalIP: r.Device.LocalIP}, *r.Access.ClientAPI) + if e != nil || a.identity != id { + continue + } + call, cancel := context.WithTimeout(ctx, 650*time.Millisecond) + raw, _, e := a.readResource(call, "status", "", "", 0) + cancel() + if e != nil { + c.devRecord(id, "router_sample", map[string]any{"state": "read_failed"}) + continue + } + projected, e := projectEvidence("status", raw, r.Access.ClientAPI.Token) + var safe struct { + Data map[string]any `json:"data"` + } + if e != nil || json.Unmarshal(projected, &safe) != nil { + c.devRecord(id, "router_sample", map[string]any{"state": "unsupported_response"}) + continue + } + d := safe.Data + if c.devCursors == nil { + c.devCursors = map[string]string{} + c.devBoots = map[string]string{} + } + if boot, ok := d["boot_id"].(string); ok && c.devBoots[id] != boot { + c.devBoots[id] = boot + delete(c.devCursors, id) + } + summary := diagnosticFields(d, "boot_id", "uptime", "revision", "clock_quality", "firmware_version", "desired_policy", "persisted_policy", "observed", "effective_wan", "recovery", "traffic", "vpn") + summary["state"] = "read" + summary["sample_interval_s"] = 1 + summary["slot_map"] = r.Device.SlotMap + c.devRecord(id, "router_sample", summary) + for _, kind := range []string{"wan", "modems"} { + rows, _ := d[kind].([]any) + for i, row := range rows { + if i >= 8 { + break + } + v, _ := row.(map[string]any) + if v == nil { + continue + } + c.devRecord(id, "router_"+kind, map[string]any{"boot_id": d["boot_id"], "router_uptime": d["uptime"], "sample": v}) + } + } + // Preserve vendor-origin event times; repeated tail reads are deduplicated. + if time.Since(c.devEventsAt[id]) < 5*time.Second { + continue + } + c.devEventsAt[id] = time.Now() + call, cancel = context.WithTimeout(ctx, 650*time.Millisecond) + raw, _, e = a.readResource(call, "events", "", c.devCursors[id], 50) + cancel() + if e != nil { + var apiErr *clientAPIError + if errors.As(e, &apiErr) && (apiErr.Status == 400 || apiErr.Status == 409 || apiErr.Status == 410 || apiErr.Status == 422) && c.devCursors[id] != "" { + delete(c.devCursors, id) + c.devRecord(id, "router_event_cursor_reset", map[string]any{"state": "cursor_rejected", "http_status": apiErr.Status}) + } + c.devRecord(id, "router_events_unavailable", map[string]any{"state": "read_failed"}) + continue + } + projected, e = projectEvidence("events", raw, r.Access.ClientAPI.Token) + if e != nil || json.Unmarshal(projected, &safe) != nil { + continue + } + if cursor, ok := safe.Data["cursor"].(string); ok && len(cursor) <= 512 { + c.devCursors[id] = cursor + } + rows, _ := safe.Data["events"].([]any) + if len(rows) >= 50 && c.devCursors[id] != "" { + // Catch up one bounded page per poll, without blocking other work. + c.devEventsAt[id] = time.Now().Add(-4 * time.Second) + } + c.devRecord(id, "router_event_page", map[string]any{"events": len(rows), "cursor_present": c.devCursors[id] != "", "page_full": len(rows) >= 50, "router_boot_id": d["boot_id"]}) + for _, row := range rows { + v, _ := row.(map[string]any) + if v == nil { + continue + } + value := diagnosticFields(v, "sequence", "source", "boot", "boot_id", "clock_quality", "epoch", "at", "at_utc", "observed_utc", "uptime", "topic", "category", "code", "recorded_code", "action", "recorded_action", "state", "reason", "operation_id", "initiator_kind", "actor_inferred", "causal_link_proven", "slot") + keyBytes, _ := json.Marshal(value) + key := id + string(keyBytes) + if c.devSeen[key] { + continue + } + if len(c.devSeen) >= 256 { + c.devSeen = map[string]bool{} + } + c.devSeen[key] = true + c.devRecord(id, "router_event", value) + } + } +} diff --git a/apps/node-agent/internal/routers/diagnostic_test.go b/apps/node-agent/internal/routers/diagnostic_test.go new file mode 100644 index 00000000..11e91422 --- /dev/null +++ b/apps/node-agent/internal/routers/diagnostic_test.go @@ -0,0 +1,64 @@ +package routers + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + "testing" + "time" +) + +func TestDiagnosticRouterReadsExpireAndPreserveSourceTimes(t *testing.T) { + calls := 0 + eventCalls := 0 + a, _ := clientAPIFixture(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + if r.Method != "GET" { + t.Fatal("DEV mutated router") + } + if r.URL.Path == "/api/client/v1/status" { + io.WriteString(w, `{"boot_id":"boot-a","uptime":120,"clock_quality":"unverified","token":"secret","desired_policy":{"mode":"direct"},"observed":{"active":"direct"},"modems":[{"slot":"M1","operator":"Carrier","imei":"secret","radio":{"rsrp_dbm":-90,"age_s":12}}]}`) + } else if r.URL.Path == "/api/client/v1/events" { + eventCalls++ + if eventCalls > 1 && r.URL.Query().Get("after") != "next-page" { + t.Fatal("event cursor did not advance") + } + io.WriteString(w, `{"cursor":"next-page","events":[{"sequence":5,"boot_id":"boot-a","at_utc":"2026-11-13T10:00:00Z","code":"modem_connected","password":"secret"}]}`) + } else { + t.Error("unexpected resource", r.URL.Path) + } + }) + c := Open(t.TempDir()) + id := a.identity + c.state.Records[id] = record{Device: Device{ID: id, Attached: true, State: "ready"}, Access: &credential{ClientAPI: &clientAPIAccess{Token: "secret"}}} + c.apiClient = func(Candidate, clientAPIAccess) (*clientAPI, error) { return a, nil } + c.devEventsAt = map[string]time.Time{} + c.devSeen = map[string]bool{} + c.pollDiagnostic(context.Background()) + if calls != 0 { + t.Fatal("inactive source performed I/O") + } + c.DiagnosticInterest() + c.pollDiagnostic(context.Background()) + first := c.DiagnosticTail(0) + if len(first) != 4 { + t.Fatal(len(first)) + } + data, _ := json.Marshal(first) + if strings.Contains(string(data), "secret") || !strings.Contains(string(data), "2026-11-13T10:00:00Z") || !strings.Contains(string(data), `"age_s":12`) { + t.Fatal(string(data)) + } + c.devEventsAt[id] = time.Time{} + c.pollDiagnostic(context.Background()) + if len(c.DiagnosticTail(first[len(first)-1].Sequence)) != 3 { + t.Fatal("vendor event repeated") + } + c.devUntil.Store(time.Now().Add(-time.Second).UnixNano()) + before := calls + c.pollDiagnostic(context.Background()) + if calls != before { + t.Fatal("interest did not expire") + } +} diff --git a/apps/node-agent/internal/routers/evidence_projection.go b/apps/node-agent/internal/routers/evidence_projection.go index 1b4535dc..ecbb1421 100644 --- a/apps/node-agent/internal/routers/evidence_projection.go +++ b/apps/node-agent/internal/routers/evidence_projection.go @@ -12,6 +12,7 @@ import ( // are omitted, never forwarded as telemetry or interpreted as instructions. // Dynamic vendor dictionaries, credentials and request bodies are not admitted. var evidenceFields = strings.Fields(` + at at_utc timestamp timestamp_utc new_probe_started active_modem_query network_command_sent external_probe_started_by_get vpn_auto chain expression_types oif fwmark dstlen iif network_registration_scope request expected_boot_id deadline_uptime report shared_component_version shared_queue operation operation_id kind state accepted_boot_id accepted_uptime accepted_utc updated_utc actor result diff --git a/apps/node-agent/internal/routers/inventory.go b/apps/node-agent/internal/routers/inventory.go index f6d427b8..d279936b 100644 --- a/apps/node-agent/internal/routers/inventory.go +++ b/apps/node-agent/internal/routers/inventory.go @@ -70,7 +70,7 @@ func applyInventory(d *Device, status map[string]any) { func (c *Collector) decorate(r *record, candidate Candidate) { r.Device.Name = r.Name - r.Device.Attached = true + r.Device.Attached = r.Device.State != "unreachable" r.Device.Connection = "ethernet" r.Device.WebUsername = "" if r.WebAccess != nil { diff --git a/apps/node-agent/internal/routers/presence_test.go b/apps/node-agent/internal/routers/presence_test.go new file mode 100644 index 00000000..dbb3a2b4 --- /dev/null +++ b/apps/node-agent/internal/routers/presence_test.go @@ -0,0 +1,102 @@ +package routers + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" +) + +func TestPresenceExpiresWithoutDiscardingInstanceSettings(t *testing.T) { + c := Open(t.TempDir()) + c.state.Records["a"] = record{Name: "Saved name", Device: Device{ID: "a", State: "ready", Attached: true, ObservedAt: time.Now().Add(-time.Minute).Unix()}} + c.state.Records["b"] = record{Device: Device{ID: "b", State: "ready", Attached: true, ObservedAt: time.Now().Unix()}} + c.publish() + s := c.Snapshot() + if s.Items[0].Attached || s.Items[0].State != "unreachable" || !s.Items[1].Attached { + t.Fatal("fresh heartbeat revived an expired instance", s.Items) + } + if c.state.Records["a"].Name != "Saved name" || len(c.state.Records) != 2 { + t.Fatal("presence expiry discarded enrollment") + } +} + +func TestDecoratingUnreachableRouterCannotRestorePresence(t *testing.T) { + c := Open(t.TempDir()) + r := record{Device: Device{State: "unreachable"}} + c.decorate(&r, Candidate{}) + if r.Device.Attached { + t.Fatal("decoration changed failed observation into attachment") + } +} + +func TestRememberedARPDoesNotKeepFailedClientAPIConnected(t *testing.T) { + a, ca := clientAPIFixture(t, func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "unavailable", http.StatusServiceUnavailable) + }) + c := Open(t.TempDir()) + candidate := Candidate{Address: "192.168.1.1", Interface: "test-lan", MAC: "02:00:00:00:00:01"} + c.discover = func(context.Context, []Candidate) []Candidate { return []Candidate{candidate} } + c.neighbor = func(string, string) string { return candidate.MAC } + c.apiClient = func(Candidate, clientAPIAccess) (*clientAPI, error) { return a, nil } + c.client = func(Candidate) *api { t.Fatal("failed paired device must not become another instance"); return nil } + c.state.Records[a.identity] = record{MAC: candidate.MAC, Access: &credential{ClientAPI: &clientAPIAccess{Token: "synthetic", CA: ca}}, Device: Device{ID: a.identity, Address: candidate.Address, State: "ready", Attached: true, ObservedAt: time.Now().Unix()}} + c.poll(context.Background()) + d := c.Snapshot().Items[0] + if d.Attached || d.State != "unreachable" || len(c.state.Records) != 1 { + t.Fatal("remembered ARP revived failed API", d) + } +} + +func TestTwoRoutersDisconnectAndReturnIndependently(t *testing.T) { + online := map[string]*atomic.Bool{"192.168.20.1": {}, "192.168.30.1": {}} + servers := map[string]*httptest.Server{} + for address := range online { + address := address + online[address].Store(true) + servers[address] = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !online[address].Load() { + http.Error(w, "unavailable", http.StatusServiceUnavailable) + return + } + fmt.Fprint(w, loginPageFixture) + })) + defer servers[address].Close() + } + c := Open(t.TempDir()) + c.discover = func(context.Context, []Candidate) []Candidate { + return []Candidate{{Address: "192.168.20.1", Interface: "eth0"}, {Address: "192.168.30.1", Interface: "eth1"}} + } + c.neighbor = func(_, address string) string { + if address == "192.168.20.1" { + return "02:00:00:00:00:01" + } + return "02:00:00:00:00:02" + } + c.client = func(candidate Candidate) *api { return testAPI(servers[candidate.Address]) } + c.poll(context.Background()) + first := c.Snapshot() + if len(first.Items) != 2 || !first.Items[0].Attached || !first.Items[1].Attached { + t.Fatal("multiple instances were collapsed", first.Items) + } + online["192.168.20.1"].Store(false) + c.poll(context.Background()) + count := 0 + for _, d := range c.Snapshot().Items { + if d.Attached { + count++ + } + } + if count != 1 { + t.Fatal("disconnect affected the wrong instance", count) + } + online["192.168.20.1"].Store(true) + c.poll(context.Background()) + last := c.Snapshot() + if len(last.Items) != 2 || !last.Items[0].Attached || !last.Items[1].Attached || last.Items[0].ID != first.Items[0].ID || last.Items[1].ID != first.Items[1].ID { + t.Fatal("reconnect lost identity or created duplicates", last.Items) + } +} diff --git a/apps/node-agent/internal/routers/types.go b/apps/node-agent/internal/routers/types.go index 46a89870..75ffba66 100644 --- a/apps/node-agent/internal/routers/types.go +++ b/apps/node-agent/internal/routers/types.go @@ -106,6 +106,7 @@ type Result struct { } type Snapshot struct { SpeedtestVersion int `json:"speedtest_version"` + AdminVersion int `json:"admin_version"` ReadVersion int `json:"read_version"` Evidence *EvidenceChunk `json:"evidence,omitempty"` ControlVersion int `json:"control_version"` diff --git a/docs/node/26_ROUTER_OBSERVATION.md b/docs/node/26_ROUTER_OBSERVATION.md index 95b26f6b..f0deb91d 100644 --- a/docs/node/26_ROUTER_OBSERVATION.md +++ b/docs/node/26_ROUTER_OBSERVATION.md @@ -684,3 +684,68 @@ Codex2026-11-10/vpn/work/router-observation-122-*.json и cleanup.json. Регрессии: `test/routerMode.test.mjs` проверяет заданную агрегацию с прямым резервом и тремя активными SIM, физическое соответствие каналов, неизвестное состояние, pending, stale и совместимость прежнего адаптера. + + +## Результат команды Client API — 13.11.2026, Node 0.8.53-137 + +HTTP 202 означает ожидание. Для policy успех требует `persisted=true`, +`applied=true` и совпадения прочитанной policy с отправленной. Асинхронный +`failed/error=busy` проецируется в `router_busy`, конфликт ревизии/замещение — +в `router_conflict`; неизвестный текст прошивки не переносится в публичный +ответ. Причина и vendor operation ID остаются в результате, причина — в журнале. + +Core и локальный Node используют одну форму. Результат расположен под кнопкой +своего действия. После повторного открытия он восстанавливается из ограниченных +квитанций Node (до 32, очистка при запросах спустя 10 минут); журнал событий +имеет отдельное хранение. Read-only inspect не заменяет результат изменения. +Черновик отмечен как неприменённый, а конфликт revision/boot требует обновления +формы. Смена runtime/устройства сбрасывает локальный черновик. + +Потеря ответа запускает только чтение результата того же operation ID, без +повторной записи. Известный терминальный отказ не запускает лишнее ожидание. +При `busy` повторное применение остаётся явным действием пользователя; новый +запрос имеет новый ID и проверку актуальной ревизии. Автоматического обхода +блокировок DexaFlow или собственного контроллера переключения SIM нет. + +Пакет 136 обновил backend, но финальная сверка выявила старый встроенный Node UI; +его заменил 137. `repack_runtime.py` теперь сверяет собранный `ui/dist` с +`web/dist` и проверяет index/entry JS непосредственно в ELF перед выпуском. +Проверка отклоняет как несинхронизированную папку, так и ранее скомпилированный +бинарник. Локальный HTTP UI борта проверяется по хешам после установки. + +## Observatory router viewport (2026-11-13) + +Operator job: monitor the actual cellular path during manual control without leaving +the observation deck. The user requested a Banana Pi viewport. Reuse the existing +dockable ObservationDeck panel (domain content in an admitted composition); opening +the Fleet router dialog was rejected because it hides the driving context. No new +navigation or shared visual primitive is introduced. + +The viewport reads the selected vehicle's existing router snapshot and creates one +panel per discovered device identity. Three SIM channels use the physical slot map, +RouterSignal, compact Description/StatusBadge and the existing panel header. Actual mode comes +from routerMode; configured mode is not evidence of the live path. Signals are never +shown as current when the snapshot, device, or per-modem radio evidence is stale. +Offline panels show an explicit unavailable state; no controls change routing, SIMs, +or motion. Hide, dock, maximize, keyboard and saved layouts use the existing deck. +Acceptance: direct/aggregation/fallback/unknown, stale/absent/reconnected, multiple +devices, SIM ordering, compact/narrow layout and DEV independence. + +### Field evidence, 2026-11-13 15:33–15:37 MSK + +A complete DEV capture (23,928 records, no storage drops) separates network loss +from motor faults: 3,160 VESC samples had fault_code=0 and no CAN bridge error; +local delivery median/p95/max was 1/2/9 ms. At 15:36:06 the Node exhausted the +350 ms command-stream deadline; receipt resumed after an 874 ms gap. Core kept +sending datagrams during that interval (maximum sending gap 61 ms). Telemetry +round trips reached 1.30 s while endpoint processing remained around 1 ms. The +stop/recovery UI follows these expired command/telemetry observations; camera +health does not own the motor lease. This establishes a delivery-path problem, +not which of LTE, router or overlay VPN caused it. Do not relax safety deadlines +to hide the symptom. Raw evidence is private in .runtime/dev-router-observation-20261113. + +DEV restart no longer requires downloading the previous operator-host capture. +The server retains the current bounded capture and three completed bounded +captures in RAM; the logs window selects their exports. Board close acknowledgement +is still required before starting another writer. Full board files remain on the +board. RAM captures expire on Core restart; the UI states this retention limit. diff --git a/docs/node/42_ROUTER_ADMIN_BRIDGE.md b/docs/node/42_ROUTER_ADMIN_BRIDGE.md new file mode 100644 index 00000000..68741a0d --- /dev/null +++ b/docs/node/42_ROUTER_ADMIN_BRIDGE.md @@ -0,0 +1,34 @@ +# Router administration through the board + +The General tab's “Открыть админку через борт” action creates an isolated browser +origin on the operator's loopback interface. It uses the already paired Core–Node +mTLS channel on port 8781 and the currently acknowledged provider address. It +does not require SSH credentials, static board addresses, a new VPN route or a +new board listener. The direct LAN address remains separately labelled. + +Node131 advertises admin_version=1. Older Nodes without this capability cannot enable the action. The +Node validates the current Core certificate, pairing and private channel on each +request, then resolves only a fresh, attached Ethernet router from its collector. +The existing on-link route, source-address and neighbour checks bind forwarding +to that router. No client-selected destination or port is accepted. Vendor login +is performed by the user; stored collector credentials are not injected. + +Core creates up to eight isolated loopback sessions, with eight requests per +session, one MiB request bodies, eight MiB responses and bounded timeouts. Vendor +JavaScript never shares the Core page origin. A private launch token establishes +an HttpOnly, SameSite=Strict session cookie. A nonce-restricted bootstrap commits +the isolated origin before navigating to vendor content; direct cross-origin +and same-site requests remain blocked. Host, Origin and Fetch Metadata +checks reject foreign origins; only vendor-issued cookie names reach the router. +Logs omit URLs, cookies and form bodies. Idle sessions close after 30 minutes; +all sessions close when Core stops. The stable entry is the action in General; +the temporary browser address can change after a Core restart. + +The forwarding adapter supports ordinary GET/HEAD/POST administration and +same-router redirects. Native POST commands may take up to 90 seconds; their +authenticated response deadline is extended without changing the shared listener. +No write is automatically retried after a timeout or lost connection. GET/HEAD +requests retain an eight-second router timeout. It is not a general proxy, +file-upload transport or firmware-update mechanism: oversized requests fail +closed. Node and Core packages include the same implementation. The selected +Ethernet/Wi-Fi route and aggregation policy are not changed by opening a page. diff --git a/packages/router-ui/src/ClientRouterControls.tsx b/packages/router-ui/src/ClientRouterControls.tsx index 73b493c0..dc3a56f7 100644 --- a/packages/router-ui/src/ClientRouterControls.tsx +++ b/packages/router-ui/src/ClientRouterControls.tsx @@ -3,7 +3,7 @@ import {useEffect,useRef,useState} from 'react'; import {Button,ConfirmationModal,Description,FieldFrame,Select,SettingsCard,StatusBadge,TextField} from '@nodedc/ui-react'; import {simChannels,simLabel,modeLabel,type RouterControl,type RouterDevice,type RouterPolicy,type RouterReceipt,type RouterSnapshot,type RouterTransport} from './contracts'; import {routerMode} from './mode'; -import {controlBusy,controlEnabled,controlMessage} from './control'; +import {controlBusy,controlEnabled,controlMessage,latestControlReceipt,policyFeedback,sendControlOnce} from './control'; export function ClientRouterControls({device,value,transport,ready,visible=true}:{device:RouterDevice;value:RouterSnapshot;transport:RouterTransport;ready:boolean;visible?:boolean}){ const api=device.client_api!,mode=routerMode(device,ready); @@ -11,70 +11,95 @@ export function ClientRouterControls({device,value,transport,ready,visible=true} const [draftVersion,setDraftVersion]=useState({boot:api.boot_id,revision:api.revision}); const staleDraft=dirty&&(draftVersion.boot!==api.boot_id||draftVersion.revision!==api.revision); const [recovery,setRecovery]=useState('wan_reconnect'),[sim,setSIM]=useState(`M${simChannels(device)[0].slot}`); - const [confirm,setConfirm]=useState(null),[pending,setPending]=useState(''),[sending,setSending]=useState(false),[result,setResult]=useState(null),[error,setError]=useState(''); + const [confirm,setConfirm]=useState(null),[pending,setPending]=useState(''),[sending,setSending]=useState(false),[results,setResults]=useState>({}); + const submitted=useRef<{id:string;policy:RouterPolicy}|null>(null); + function remember(receipt:RouterReceipt){setResults(previous=>({...previous,[receipt.action!]:receipt}));} const active=useRef(true);useEffect(()=>{active.current=true;return()=>{active.current=false;};},[]); - const remote=value.results.find(r=>r.device_id===device.id&&controlBusy(r)); - const busy=sending||!!pending||!!remote,enabled=controlEnabled(value,device,ready)&&!busy; + const observed=value.results.map(r=>{ + const local=results[r.action??'']; + return local?.operation_id===r.operation_id?latestControlReceipt([r],device.id,r.action!,local)??r:r; + }); + const remote=observed.find(r=>r.device_id===device.id&&controlBusy(r)); + const busy=sending||!!pending||!!remote,enabled=controlEnabled({...value,results:observed},device,ready)&&!busy; + // Reopening the window resumes receipt reads, never the setting write. + useEffect(()=>{if(!pending&&!sending&&remote){remember(remote);setPending(remote.operation_id);}},[remote?.operation_id,pending,sending]); useEffect(()=>{if(!dirty&&!busy){setPolicy(api.policy);setDraftVersion({boot:api.boot_id,revision:api.revision});}},[api.boot_id,api.revision,dirty,busy]); useEffect(()=>{ if(!pending)return; + const action=Object.keys(results).find(key=>results[key].operation_id===pending)!; let stopped=false;let timer:ReturnType;const end=Date.now()+300000; async function poll(){ - try{const next=await transport.operation(pending);if(stopped)return;setResult(next); - if(!controlBusy(next)){setPending('');if(next.state==='complete')setDirty(false);return;} + try{const next=await transport.operation(pending);if(stopped)return;remember({...results[action],error:undefined,...next,action,device_id:device.id}); + if(!controlBusy(next)){setPending('');return;} }catch{/* Poll a receipt, never repeat the write. */} if(stopped)return; - if(Date.now()>=end){setResult({operation_id:pending,state:'unknown'});setPending('');return;} + if(Date.now()>=end){remember({...results[action],state:'unknown',error:'confirmation_timeout'});setPending('');return;} timer=setTimeout(()=>void poll(),2000); } void poll();return()=>{stopped=true;clearTimeout(timer);}; },[pending,transport]); - function change(next:Partial){setPolicy(p=>({...p,...next}));setDirty(true);} + function change(next:Partial){submitted.current=null;setPolicy(p=>({...p,...next}));setDirty(true);} const valid=(policy.mode!=='direct'||!!policy.preferred_sim)&&Number.isInteger(policy.fail_seconds)&&policy.fail_seconds>=15&&policy.fail_seconds<=300&&Number.isInteger(policy.recover_seconds)&&policy.recover_seconds>=30&&policy.recover_seconds<=600&&Number.isInteger(policy.min_vpn_seconds)&&policy.min_vpn_seconds>=60&&policy.min_vpn_seconds<=900; const labels:Record={policy:'Применить настройки',recovery:'Выполнить восстановление',diagnostics:'Запустить диагностику',reboot:'Перезагрузить роутер'}; async function send(){ if(!confirm||!enabled||!value.runtime_id||!api.rights.includes(confirm)||(confirm==='policy'&&(!valid||staleDraft))){setConfirm(null);return;} - const action=confirm;setConfirm(null);setSending(true);setError('');setResult(null); + const action=confirm;setConfirm(null);setSending(true); const id='op_'+crypto.randomUUID().replaceAll('-',''); + // Client API v1 requires these flags; firmware owns the fallback behavior. const nextPolicy:RouterPolicy={mode:policy.mode,allow_fallback:true,return_to_preferred:true,persist:true,fail_seconds:policy.fail_seconds,recover_seconds:policy.recover_seconds,min_vpn_seconds:policy.min_vpn_seconds,...(policy.mode==='direct'?{preferred_sim:policy.preferred_sim}:{})}; const command:RouterControl={operation_id:id,runtime_id:value.runtime_id,device_id:device.id,deadline:Math.floor(Date.now()/1000)+85,action,mode:'',slots:[],expected_boot_id:action==='policy'?draftVersion.boot:api.boot_id,expected_revision:action==='policy'?draftVersion.revision:api.revision,policy:action==='policy'?nextPolicy:null,recovery:action==='recovery'?recovery:'',sim:action==='recovery'&&recovery==='wan_reconnect'?sim:''}; - try{const receipt=await transport.control(command);if(active.current)setResult(receipt);} - catch(e){if(active.current)setError(e instanceof Error?e.message:'Не удалось получить ответ на команду.');} - finally{if(active.current){setSending(false);setPending(id);}} + const initial:RouterReceipt={operation_id:id,device_id:device.id,action,state:'queued',at:Date.now()/1000}; + remember(initial); + if(action==='policy')submitted.current={id,policy:nextPolicy}; + const receipt=await sendControlOnce(transport,command,initial); + if(active.current){remember(receipt);setSending(false);if(controlBusy(receipt))setPending(id);} + } + const policyReceipt=latestControlReceipt(value.results,device.id,'policy',results.policy); + const policyPending=!!policyReceipt&&controlBusy(policyReceipt); + const feedback=policyFeedback(device,ready,dirty&&!policyPending&&!submitted.current?null:policyReceipt); + const actionPending=(action:string)=>{const r=latestControlReceipt(value.results,device.id,action,results[action]);return ready&&!!r&&controlBusy(r);}; + useEffect(()=>{ + const sent=submitted.current; + if(sent&&policyReceipt?.operation_id===sent.id&&policyReceipt.state==='complete'&& + Object.entries(sent.policy).every(([key,val])=>api.policy[key as keyof RouterPolicy]===val)){ + setDirty(false);submitted.current=null; + } + },[policyReceipt,api.policy]); + function status(action:string){ + const receipt=latestControlReceipt(value.results,device.id,action,results[action]); + return receipt&&{controlMessage(receipt)}; } - const receipt=remote?.action==='inspect'?result:remote??result; const recoveryName={wan_reconnect:'Переподключить сотовый канал',vpn_reconnect:'Переподключить VPN',dns_restart:'Перезапустить DNS'}[recovery]??''; const confirmation=confirm==='policy'?`${modeLabel(policy.mode)}${policy.mode==='direct'?` · ${simLabel(device,Number(policy.preferred_sim?.slice(1)))}`:''}. Настройки сохранятся после перезагрузки; соединения через роутер могут прерваться.`:confirm==='recovery'?`${recoveryName}${recovery==='wan_reconnect'?` · ${simLabel(device,Number(sim.slice(1)))}`:''}. Текущие соединения могут прерваться.`:confirm==='reboot'?'Связь через этот роутер временно прервётся.':'Будет выполнена проверка служб роутера без переключения режима.'; return
- + setConfirm('policy')}>Применить}>
- {mode.message&&{mode.message}} - - ({value:mode,label:modeLabel(mode)}))} onChange={mode=>change({mode:mode as RouterPolicy['mode'],preferred_sim:undefined})}/> - {dirty&&Изменения ещё не применены. На роутере задано: {mode.configured}.} + {feedback&&
{feedback.label}{feedback.message}
} + {dirty&&!policyPending&&Изменения ещё не применены. На роутере задано: {mode.configured}.} {policy.mode==='direct'&& {recovery==='wan_reconnect'&&