feat(router): confirm DexaFlow modes and expose the paired admin interface
This commit is contained in:
@@ -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))};
|
||||
}
|
||||
|
||||
@@ -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')<html.indexOf('SIM2'));
|
||||
const stale=renderToStaticMarkup(createElement(RouterObservation,{device:d,value:{available:true,fresh:false}}));
|
||||
assert.doesNotMatch(stale,/Активный канал|Прямой выход/);
|
||||
assert.match(stale,/Нет свежих данных/);
|
||||
});
|
||||
|
||||
test('compact router view retains three SIM rows without scales or summary',()=>{
|
||||
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(/<section /g)||[]).length,3);
|
||||
assert.doesNotMatch(html,/router-signal-scale|Прямой выход/);
|
||||
assert.match(html,/aria-label="SIM3 · Активный канал"/);
|
||||
assert.equal((html.match(/data-variant="indicator"/g)||[]).length,3);
|
||||
assert.ok(html.indexOf('SIM1')<html.indexOf('SIM2')&&html.indexOf('SIM2')<html.indexOf('SIM3'));
|
||||
});
|
||||
|
||||
@@ -91,8 +91,8 @@ test('physical SIM labels are a profile projection, never array order or model-n
|
||||
assert.deepEqual(simChannels(device).map(x=>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)')<html.indexOf('Ожидание отказа, с'));
|
||||
assert.ok(html.indexOf('(busy)')<html.indexOf('Восстановление соединения'));
|
||||
}
|
||||
});
|
||||
|
||||
test('policy progress follows receipts and never turns missing or fallback routes into success',async()=>{
|
||||
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"')<html.indexOf('Ожидание отказа, с'));
|
||||
if(pending){assert.doesNotMatch(html,/Не применён|Изменения ещё не применены/);assert.match(html,/disabled/);}
|
||||
}
|
||||
});
|
||||
test('receipts survive out-of-order snapshots without mixing devices, actions or old successes',async()=>{
|
||||
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);
|
||||
});
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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"`
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
@@ -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<RouterControl['action']|null>(null),[pending,setPending]=useState(''),[sending,setSending]=useState(false),[result,setResult]=useState<RouterReceipt|null>(null),[error,setError]=useState('');
|
||||
const [confirm,setConfirm]=useState<RouterControl['action']|null>(null),[pending,setPending]=useState(''),[sending,setSending]=useState(false),[results,setResults]=useState<Record<string,RouterReceipt>>({});
|
||||
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<typeof setTimeout>;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<RouterPolicy>){setPolicy(p=>({...p,...next}));setDirty(true);}
|
||||
function change(next:Partial<RouterPolicy>){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<string,string>={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&&<Description role="status">{controlMessage(receipt)}</Description>;
|
||||
}
|
||||
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 <div className="router-form">
|
||||
<SettingsCard title="Режим подключения" description={`Сейчас: ${mode.current}`}>
|
||||
<SettingsCard title="Режим подключения" description={`Текущий режим: ${mode.current}`} actions={<Button loading={actionPending('policy')} disabled={!enabled||!valid||staleDraft||!api.rights.includes('policy')} onClick={()=>setConfirm('policy')}>Применить</Button>}>
|
||||
<div className="router-form">
|
||||
{mode.message&&<Description role="status">{mode.message}</Description>}
|
||||
<FieldFrame label={dirty?'Новый режим':'Сохранённый режим'} hint={dirty?'Не применён':undefined}>
|
||||
<Select label={dirty?'Новый режим':'Сохранённый режим'} value={policy.mode} disabled={!enabled||!api.rights.includes('policy')} options={(['direct','vpn','aggregation','whitelist'] as const).map(mode=>({value:mode,label:modeLabel(mode)}))} onChange={mode=>change({mode:mode as RouterPolicy['mode'],preferred_sim:undefined})}/>
|
||||
<FieldFrame label={policyPending?'Режим подключения':dirty?'Новый режим':'Сохранённый режим'} hint={dirty&&!policyPending?'Не применён':undefined}>
|
||||
<Select label="Режим подключения" value={policy.mode} disabled={!enabled||!api.rights.includes('policy')} options={(['direct','vpn','aggregation','whitelist'] as const).map(mode=>({value:mode,label:modeLabel(mode)}))} onChange={mode=>change({mode:mode as RouterPolicy['mode'],preferred_sim:undefined})}/>
|
||||
</FieldFrame>
|
||||
{dirty&&<Description>Изменения ещё не применены. На роутере задано: {mode.configured}.</Description>}
|
||||
{feedback&&<div role="status" aria-live="polite"><StatusBadge tone={feedback.tone} pulse={feedback.busy}>{feedback.label}</StatusBadge><Description>{feedback.message}</Description></div>}
|
||||
{dirty&&!policyPending&&<Description>Изменения ещё не применены. На роутере задано: {mode.configured}.</Description>}
|
||||
{policy.mode==='direct'&&<Select label="Предпочтительная SIM" value={policy.preferred_sim??''} disabled={!enabled||!api.rights.includes('policy')} options={[{value:'',label:'Выберите SIM',disabled:true},...simChannels(device).map(s=>({value:`M${s.slot}`,label:`${s.label} (${s.detail}) · ${device.modems.find(m=>m.slot===s.slot)?.operator||'Оператор не определён'}`}))]} onChange={s=>change({preferred_sim:s as RouterPolicy['preferred_sim']})}/>}
|
||||
<Description>Автоматическим резервированием и возвратом на предпочтительную SIM управляет прошивка. Ограничение агрегации выбранным набором SIM этим API не поддерживается.</Description>
|
||||
{([['fail_seconds','Ожидание отказа, с',15,300],['recover_seconds','Ожидание восстановления, с',30,600],['min_vpn_seconds','Минимальное время VPN, с',60,900]] as const).map(([key,label,min,max])=><TextField key={key} label={label} type="number" min={min} max={max} step={1} value={policy[key]} disabled={!enabled||!api.rights.includes('policy')} onChange={e=>change({[key]:Number(e.target.value)})}/>)}
|
||||
{staleDraft&&<Description>Настройки роутера изменились во время редактирования. Обновите форму перед применением.</Description>}
|
||||
{staleDraft&&<Button disabled={busy} onClick={()=>setDirty(false)}>Обновить форму</Button>}
|
||||
<Button disabled={!enabled||!valid||staleDraft||!api.rights.includes('policy')} onClick={()=>setConfirm('policy')}>Применить</Button>
|
||||
{staleDraft&&!policyPending&&<Description>Настройки роутера изменились во время редактирования. Обновите форму перед применением.</Description>}
|
||||
{staleDraft&&!policyPending&&<Button disabled={busy} onClick={()=>setDirty(false)}>Обновить форму</Button>}
|
||||
</div>
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Восстановление соединения" description="Ручное действие штатного контроллера роутера. Успешное выполнение команды само по себе не подтверждает доступ в интернет.">
|
||||
<div className="router-form">
|
||||
<Select label="Действие" value={recovery} disabled={!enabled||!api.rights.includes('recovery')} options={[{value:'wan_reconnect',label:'Переподключить сотовый канал'},{value:'vpn_reconnect',label:'Переподключить VPN'},{value:'dns_restart',label:'Перезапустить DNS'}]} onChange={setRecovery}/>
|
||||
{recovery==='wan_reconnect'&&<Select label="SIM-карта" value={sim} disabled={!enabled||!api.rights.includes('recovery')} options={simChannels(device).map(s=>({value:`M${s.slot}`,label:`${s.label} (${s.detail})`}))} onChange={setSIM}/>}
|
||||
<Button disabled={!enabled||!api.rights.includes('recovery')} onClick={()=>setConfirm('recovery')}>Выполнить</Button>
|
||||
<Button loading={actionPending('recovery')} disabled={!enabled||!api.rights.includes('recovery')} onClick={()=>setConfirm('recovery')}>Выполнить</Button>
|
||||
{status('recovery')}
|
||||
</div>
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Диагностика" description="Проверка служб. Результаты относятся к моменту запуска проверки.">
|
||||
<Button disabled={!enabled||!api.rights.includes('diagnostics')} onClick={()=>setConfirm('diagnostics')}>Проверить роутер</Button>
|
||||
<Button loading={actionPending('diagnostics')} disabled={!enabled||!api.rights.includes('diagnostics')} onClick={()=>setConfirm('diagnostics')}>Проверить роутер</Button>
|
||||
{status('diagnostics')}
|
||||
<RouterDiagnostics device={device} value={value} transport={transport} visible={visible}/>
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Перезагрузка роутера" description="После загрузки будут показаны фактический режим и состояние каналов."><Button disabled={!enabled||!api.rights.includes('reboot')} onClick={()=>setConfirm('reboot')}>Перезагрузить роутер</Button></SettingsCard>
|
||||
{error&&<StatusBadge tone="warning">{error}</StatusBadge>}
|
||||
{receipt&&<StatusBadge tone={receipt.state==='complete'?'success':receipt.state==='error'||receipt.state==='unknown'?'warning':'neutral'}>{controlMessage(receipt)}</StatusBadge>}
|
||||
<SettingsCard title="Перезагрузка роутера" description="После загрузки будут показаны фактический режим и состояние каналов."><Button loading={actionPending('reboot')} disabled={!enabled||!api.rights.includes('reboot')} onClick={()=>setConfirm('reboot')}>Перезагрузить роутер</Button>{status('reboot')}</SettingsCard>
|
||||
<ConfirmationModal open={confirm!==null} title={labels[confirm??'']??''} description={confirmation} confirmLabel="Выполнить" cancelLabel="Отмена" onClose={()=>setConfirm(null)} onConfirm={send}/>
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ export function RouterDetails({device,value,transport,onClose,error,speedtest}:{
|
||||
{error&&<StatusBadge tone="warning">{error}</StatusBadge>}
|
||||
<SegmentedControl label="Сведения о роутере" value={section} items={speedtest?[...sections.slice(0,2),{value:'speedtest',label:'Замер скорости'},...sections.slice(2)]:sections} onChange={setSection}/>
|
||||
{section==='overview'&&<RouterOverview device={device} ready={ready} points={traffic}/>}
|
||||
<div hidden={section!=='control'}>{device.client_api?<ClientRouterControls device={device} value={value} transport={transport} ready={ready} visible={section==='control'}/>:<RouterControls device={device} value={value} transport={transport} ready={ready}/>}</div>
|
||||
<div hidden={section!=='control'}>{device.client_api?<ClientRouterControls key={`${value.runtime_id}:${device.id}`} device={device} value={value} transport={transport} ready={ready} visible={section==='control'}/>:<RouterControls device={device} value={value} transport={transport} ready={ready}/>}</div>
|
||||
<div hidden={section!=='speedtest'}>{speedtest}</div>
|
||||
{section==='signal'&&<>
|
||||
<RouterRadioHistory device={device} samples={radio}/>
|
||||
|
||||
@@ -7,7 +7,7 @@ import './router.css';
|
||||
|
||||
export function RouterEquipment({transport,renderSpeedtest}:{transport:RouterTransport;renderSpeedtest?:(device:RouterDevice,value:RouterSnapshot)=>ReactNode}){
|
||||
const {value,error}=useRouters(transport),[selected,setSelected]=useState<string|null>(null);
|
||||
const connected=visibleRouters(value?.items??[]);
|
||||
const connected=visibleRouters(value);
|
||||
const device=connected.find(d=>d.id===selected);
|
||||
if(!value||!connected.length)return null;
|
||||
return <>
|
||||
|
||||
@@ -5,7 +5,14 @@ import {useRouterRequest} from './useRouterRequest';
|
||||
export function RouterGeneral({device,value,transport}:{device:RouterDevice;value:RouterSnapshot;transport:RouterTransport}){
|
||||
const [name,setName]=useState(device.name??''),[address,setAddress]=useState(device.address);
|
||||
const [username,setUsername]=useState(device.web_username||'admin'),[password,setPassword]=useState(device.web_access?'':'admin');
|
||||
const [savingWeb,setSavingWeb]=useState(false);
|
||||
const [savingWeb,setSavingWeb]=useState(false),[adminError,setAdminError]=useState(''),[opening,setOpening]=useState(false);
|
||||
async function openAdmin(){
|
||||
const page=window.open('about:blank','_blank');if(page)page.opener=null;
|
||||
setOpening(true);setAdminError('');
|
||||
try{const result=await transport.openAdmin!(device.id);const url=new URL(result.url);if(url.protocol!=='http:'||url.hostname!=='127.0.0.1')throw new Error('Неверный адрес админки.');if(page)page.location.replace(url.href);else throw new Error('Разрешите открытие новой вкладки и повторите вход.');}
|
||||
catch(e){page?.close();setAdminError(e instanceof Error?e.message:'Не удалось открыть админку.');}
|
||||
finally{setOpening(false);}
|
||||
}
|
||||
const request=useRouterRequest(value,transport);
|
||||
const busy=request.busy||value.results.some(r=>r.state==='queued'||r.state==='applying');
|
||||
const enabled=value.available&&value.fresh!==false&&!!value.runtime_id&&!busy;
|
||||
@@ -25,7 +32,9 @@ export function RouterGeneral({device,value,transport}:{device:RouterDevice;valu
|
||||
<SettingsCard title="Админка Dexaflow" description={device.web_access?'Доступ сохранён. Пароль обратно не передаётся.':'Подключите админку для определения модели и физических SIM-разъёмов.'}>
|
||||
<div className="router-form">
|
||||
<TextField label="Адрес роутера" value={address} maxLength={45} disabled={busy} onChange={e=>setAddress(e.target.value)}/>
|
||||
<Description>{`http://${address}/cgi-bin/luci/dexaflow`}</Description>
|
||||
<Description>{`Адрес в сети борта: http://${address}/cgi-bin/luci/dexaflow`}</Description>
|
||||
{transport.openAdmin&&<Button disabled={!enabled||value.admin_version!==1||device.state!=='ready'||opening} loading={opening} onClick={()=>void openAdmin()}>Открыть админку через борт</Button>}
|
||||
{adminError&&<StatusBadge tone="warning">{adminError}</StatusBadge>}
|
||||
<TextField label="Логин" value={username} maxLength={64} disabled={busy} autoComplete="off" onChange={e=>setUsername(e.target.value)}/>
|
||||
<TextField label="Пароль админки" type="password" value={password} maxLength={256} disabled={busy} autoComplete="new-password" onChange={e=>setPassword(e.target.value)}/>
|
||||
<Button loading={request.busy&&savingWeb} disabled={!enabled||!address||!username||!password} onClick={()=>save(true)}>Подключить админку</Button>
|
||||
|
||||
@@ -18,7 +18,7 @@ export function RouterOverview({device,ready,points}:{device:RouterDevice;ready:
|
||||
const mode=routerMode(device,ready),selected=mode.activeSlot;
|
||||
const active=device.modems.find(m=>m.slot===selected);
|
||||
const verified=ready&&device.internet==='verified';
|
||||
const facts:[string,string][]=[['Роутер',device.address],['Адрес борта',device.local_ip],['Интерфейс борта',device.interface],['Внешний IP',device.public_ip],['Выбранный режим',modeLabel(device.selected_mode)],['Сохранённый режим',modeLabel(device.persisted_mode)],['После перезагрузки',device.reboot_resets===true?'Роутер сообщает о сбросе режима':device.reboot_resets===false?'Сброс режима не заявлен':'Нет сведений'],['Подтверждение VPN',device.vps_up==null?'Нет сведений':device.vps_up?'Доступен по данным роутера':'Недоступен по данным роутера'],['Прошивка',device.firmware],['Время работы',device.uptime==null?'Нет сведений':metric(device.uptime/3600,'ч')]];
|
||||
const facts:[string,string][]=[['Роутер',device.address],['Адрес борта',device.local_ip],['Интерфейс борта',device.interface],['Внешний IP',device.public_ip],['Выбранный режим',modeLabel(device.selected_mode)],['Сохранённый режим',modeLabel(device.persisted_mode)],['После перезагрузки',device.reboot_resets===true?'Роутер сообщает о сбросе режима':device.reboot_resets===false?'Сброс режима не заявлен':'Нет сведений'],['Сервер текущего режима',device.vps_up==null?'Нет сведений':device.vps_up?'Доступен по данным роутера':'Недоступен по данным роутера'],['Прошивка',device.firmware],['Время работы',device.uptime==null?'Нет сведений':metric(device.uptime/3600,'ч')]];
|
||||
return <div className="router-overview">
|
||||
<SettingsCard title={`Сейчас: ${mode.current}`} description={`${ready?'Задано':'Последний заданный режим'}: ${mode.configured}`} actions={<StatusBadge tone={verified?'success':ready?'warning':'neutral'}>{verified?'Интернет подтверждён':ready?'Интернет не подтверждён':'Нет свежих данных'}</StatusBadge>}>
|
||||
<div className="router-form">
|
||||
|
||||
@@ -2,10 +2,10 @@ import {Description,Tooltip} from '@nodedc/ui-react';
|
||||
import {metric} from './contracts';
|
||||
import {signalBands,signalLevel} from './overview';
|
||||
|
||||
export function RouterSignal({rsrp}:{rsrp:number|null|undefined}){
|
||||
export function RouterSignal({rsrp,compact=false}:{rsrp:number|null|undefined;compact?:boolean}){
|
||||
const level=signalLevel(rsrp);
|
||||
return <div className="router-signal">
|
||||
<div className="router-metric-line"><span>Сигнал</span><strong>{level==null?'—':metric(rsrp,'dBm')}</strong></div>
|
||||
{!compact&&<div className="router-metric-line"><span>Сигнал</span><strong>{level==null?'—':metric(rsrp,'dBm')}</strong></div>}
|
||||
<div className="router-signal-scale" role="group" aria-label={level==null?'Уровень сигнала неизвестен':`${signalBands[level].label} сигнал · RSRP ${metric(rsrp,'dBm')}`}>
|
||||
{signalBands.map((band,i)=>{
|
||||
const current=level===i,position=current?Math.max(0.12,Math.min(0.88,(rsrp!-band.min)/(band.max-band.min))):0;
|
||||
@@ -20,6 +20,6 @@ export function RouterSignal({rsrp}:{rsrp:number|null|undefined}){
|
||||
</Tooltip>;
|
||||
})}
|
||||
</div>
|
||||
<div className="router-scale-labels"><span>Слабый</span><span>Отличный</span></div>
|
||||
{!compact&&<div className="router-scale-labels"><span>Слабый</span><span>Отличный</span></div>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ export interface RouterIncident {sequence:number;at:number;boot_id:string;elapse
|
||||
export interface SpeedMeasurement {phase:'latency'|'download'|'upload'|'complete'|'cancelled'|'error';server_id:string;interface:string;started_at:number;finished_at?:number;sampled_at?:number;current_bps?:number;download_bps:number;upload_bps:number;latency_ms:number;jitter_ms:number;error?:string}
|
||||
export interface RouterReceipt {measurement?:SpeedMeasurement;at?:number;evidence?:EvidenceChunk;vendor_id?:string;operation_id:string;state:'queued'|'applying'|'complete'|'error'|'unknown';error?:string;device_id?:string;action?:string}
|
||||
export interface RouterSnapshot {
|
||||
admin_version?:number;
|
||||
speedtest_version?:number;
|
||||
read_version?:number;evidence?:EvidenceChunk|null;
|
||||
control_version?:number;available:boolean;fresh?:boolean;runtime_id?:string;observed_at?:number;received_at?:number;
|
||||
@@ -37,6 +38,7 @@ export interface RouterSnapshot {
|
||||
export interface RouterAccess {operation_id:string;runtime_id:string;device_id:string;deadline:number;username?:string;password?:string;model_id?:string;client_api?:{token:string;ca:string};settings?:{name:string;address:string;username:string;password:string}}
|
||||
export interface RouterControl {operation_id:string;runtime_id:string;device_id:string;deadline:number;action:'mode'|'reboot'|'policy'|'recovery'|'diagnostics';mode:'direct'|'aggregation'|'';slots:number[];policy?:RouterPolicy|null;recovery?:string;sim?:string;expected_boot_id?:string;expected_revision?:string}
|
||||
export interface RouterTransport {
|
||||
openAdmin?:(deviceID:string)=>Promise<{url:string}>;
|
||||
inspect?:(value:EvidenceRequest)=>Promise<RouterReceipt>;
|
||||
read:()=>Promise<RouterSnapshot>;
|
||||
control:(value:RouterControl)=>Promise<RouterReceipt>;
|
||||
@@ -68,4 +70,6 @@ export function simChannels(device:RouterDevice){
|
||||
return [1,2,3].map(slot=>({slot,sim:null,position:'',label:`Канал ${slot}`,detail:`M${slot}`}));
|
||||
}
|
||||
export function simLabel(device:RouterDevice,slot:number):string{return simChannels(device).find(s=>s.slot===slot)?.label||'Канал не определён';}
|
||||
export function visibleRouters(items:RouterDevice[]):RouterDevice[]{return items.filter(d=>d.attached??d.state!=='unreachable');}
|
||||
export function visibleRouters(value:RouterSnapshot|null,now=Date.now()):RouterDevice[]{
|
||||
return value?.items.filter(d=>d.attached!==false&&d.state!=='unreachable'&&routerFresh(value,d,now))??[];
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import type {RouterDevice,RouterReceipt,RouterSnapshot} from './contracts';
|
||||
import type {RouterControl,RouterDevice,RouterReceipt,RouterSnapshot,RouterTransport} from './contracts';
|
||||
import {routerMode} from './mode';
|
||||
export function controlBusy(result:RouterReceipt):boolean{return result.state==='queued'||result.state==='applying';}
|
||||
export function availableSlots(device:RouterDevice):number[]{return device.modems.filter(m=>m.radio!=='NOSIM'&&!!m.ip).map(m=>m.slot);}
|
||||
export function controlEnabled(value:RouterSnapshot,device:RouterDevice,ready:boolean):boolean{return ready&&value.control_version===1&&!!value.runtime_id&&!value.results.some(controlBusy)&&device.state==='ready';}
|
||||
export function controlMessage(result:RouterReceipt):string{
|
||||
if(result.state==='applying'&&result.error==='receipt_pending')return 'Ответ на отправку не получен. Проверяем результат; повторная команда не отправляется.';
|
||||
if(result.state==='queued')return 'Ожидание команды на борту…';
|
||||
if(result.state==='applying'&&['policy','recovery','diagnostics'].includes(result.action??''))return 'Ожидаем результат операции роутера…';
|
||||
if(result.state==='complete'&&result.action==='policy')return 'Политика сохранена и применена роутером. Фактический канал показан в обзоре.';
|
||||
@@ -10,5 +12,38 @@ export function controlMessage(result:RouterReceipt):string{
|
||||
if(result.state==='complete'&&result.action==='diagnostics')return 'Диагностика завершена.';
|
||||
if(result.state==='applying')return result.action==='reboot'?'Ожидание роутера после перезагрузки…':'Проверяем режим и выбранные SIM…';
|
||||
if(result.state==='complete')return result.action==='reboot'?'Перезагрузка подтверждена. Текущий режим показан в обзоре.':'Режим и выбранные SIM подтверждены роутером.';
|
||||
return ({router_conflict:'Состояние изменилось или роутер занят. Обновите настройки перед новой командой.',router_certificate_rejected:'Сертификат роутера не прошёл проверку.',expired:'Команда не выполнена: срок запроса истёк.',access_rejected:'Роутер отклонил доступ. Проверьте вкладку «Доступ».',router_unavailable:'Роутер недоступен.',storage_error:'Не удалось сохранить команду на борту.',sim_unavailable:'Выбранная SIM недоступна или ещё не получила IP-адрес.',router_busy:'Роутер занят переключением. Дождитесь обновления состояния.',command_rejected:'Роутер отклонил команду.',unsupported_response:'Прошивка не подтвердила совместимость команды.'} as Record<string,string>)[result.error??'']??'Результат не подтверждён. Проверьте текущее состояние перед новой командой.';
|
||||
return ({router_conflict:'Состояние изменилось или роутер занят. Обновите настройки перед новой командой.',router_certificate_rejected:'Сертификат роутера не прошёл проверку.',expired:'Команда не выполнена: срок запроса истёк.',access_rejected:'Роутер отклонил доступ. Проверьте вкладку «Доступ».',router_unavailable:'Роутер недоступен.',storage_error:'Не удалось сохранить команду на борту.',sim_unavailable:'Выбранная SIM недоступна или ещё не получила IP-адрес.',router_busy:'Роутер отклонил команду: занят другой операцией (busy). Дождитесь обновления состояния и повторите применение.',command_rejected:'Роутер отклонил команду.',unsupported_response:'Прошивка не подтвердила совместимость команды.'} as Record<string,string>)[result.error??'']??'Результат не подтверждён. Проверьте текущее состояние перед новой командой.';
|
||||
}
|
||||
|
||||
// Operation acknowledgement and the observed route are independent evidence.
|
||||
// A saved policy can still be waiting for its route or using a fallback.
|
||||
export function policyFeedback(device:RouterDevice,ready:boolean,receipt:RouterReceipt|null){
|
||||
const mode=routerMode(device,ready),busy=!!receipt&&controlBusy(receipt);
|
||||
if(receipt?.state==='error'||receipt?.state==='unknown')return {busy:false,tone:'warning' as const,label:receipt.state==='error'?'Настройки не применены':'Результат не подтверждён',message:controlMessage(receipt)};
|
||||
if(!ready)return {busy:false,tone:'warning' as const,label:'Нет свежих данных',message:busy?'Команда отправлена. Ожидаем связи с роутером для подтверждения результата.':mode.message};
|
||||
if(busy)return {busy:true,tone:'warning' as const,label:receipt.state==='queued'?'Команда отправлена':'Применяются настройки',message:receipt.error==='receipt_pending'?controlMessage(receipt):receipt.state==='queued'?'Ожидаем начала выполнения на борту.':'Роутер выполняет команду. Ожидаем подтверждения результата.'};
|
||||
if(mode.pending)return {busy:false,tone:'warning' as const,label:'Роутер применяет настройки',message:mode.message};
|
||||
if(mode.message)return {busy:false,tone:'warning' as const,label:'Проверьте текущий канал',message:mode.message};
|
||||
return receipt?.state==='complete'?{busy:false,tone:'success' as const,label:'Настройки применены',message:`Роутер подтвердил сохранение. Текущий режим: ${mode.current}.`}:null;
|
||||
}
|
||||
|
||||
// Snapshot results are not ordered. Inspection/speed-test receipts must never
|
||||
// replace a setting's outcome. A terminal receipt wins over an older snapshot
|
||||
// of that same operation, including after a lost HTTP response.
|
||||
export function latestControlReceipt(results:RouterReceipt[],deviceID:string,action:string,local?:RouterReceipt|null):RouterReceipt|null{
|
||||
const candidates=[...results,...(local?[local]:[])].filter(r=>r.device_id===deviceID&&r.action===action);
|
||||
return candidates.reduce<RouterReceipt|null>((best,next)=>{
|
||||
if(!best)return next;
|
||||
if(best.operation_id===next.operation_id){
|
||||
if(controlBusy(best)!==controlBusy(next))return controlBusy(best)?next:best;
|
||||
if(best.state==='queued'&&next.state==='applying')return next;
|
||||
if(next.state==='queued'&&best.state==='applying')return best;
|
||||
}
|
||||
return (next.at??0)>=(best.at??0)?next:best;
|
||||
},null);
|
||||
}
|
||||
|
||||
export async function sendControlOnce(transport:RouterTransport,command:RouterControl,initial:RouterReceipt):Promise<RouterReceipt>{
|
||||
try{return {...initial,...await transport.control(command)};}
|
||||
catch{return {...initial,state:'applying',error:'receipt_pending'};}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,13 @@ export function routerMode(device:RouterDevice,ready:boolean){
|
||||
else if(fallback){
|
||||
const prefix=canonicalMode(configuredMode)==='aggregation'&&canonicalMode(activeMode)!=='aggregation'?'Агрегация сейчас не используется. ':'';
|
||||
message=prefix+'По данным роутера включён резервный путь.';
|
||||
if(prefix&&activeSlot!=null){
|
||||
const operator=device.modems.find(m=>m.slot===activeSlot)?.operator;
|
||||
message=`Агрегация задана, но сейчас выход идёт через ${channel}${operator?` · ${operator}`:''}.`;
|
||||
if(details?.fallback_reason==='preferred_path_unavailable_observed_other_default_route'){
|
||||
message+=' Роутер сообщает, что путь агрегации недоступен.';
|
||||
}
|
||||
}
|
||||
const preferred=device.client_api?.policy?.preferred_sim;
|
||||
if(configuredMode==='direct'&&preferred&&/^M[1-3]$/.test(preferred))message+=` Предпочтительная SIM — ${simLabel(device,Number(preferred.slice(1)))}.`;
|
||||
}else if(mismatch)message='Заданный режим отличается от фактического. Причина не подтверждена.';
|
||||
|
||||
@@ -4,14 +4,15 @@ import type {RouterSnapshot,RouterTransport} from './contracts';
|
||||
export function useRouters(transport:RouterTransport){
|
||||
const [value,setValue]=useState<RouterSnapshot|null>(null),[error,setError]=useState('');
|
||||
useEffect(()=>{
|
||||
let active=true;let cadence=3000;let timer:ReturnType<typeof setTimeout>;
|
||||
let active=true;let lastData=0;let cadence=3000;let timer:ReturnType<typeof setTimeout>;
|
||||
setValue(null);setError('');
|
||||
async function poll(){
|
||||
try{const next=await transport.read();if(active){setValue(next);setError('');cadence=next.results.some(r=>r.action==='speedtest'&&(r.state==='queued'||r.state==='applying'))?1000:3000;}}
|
||||
try{const next=await transport.read();if(active){lastData=performance.now();setValue(next);setError('');cadence=next.results.some(r=>r.action==='speedtest'&&(r.state==='queued'||r.state==='applying'))?1000:3000;}}
|
||||
catch{if(active){setValue(previous=>previous?{...previous,fresh:false}:previous);setError('Не удалось обновить сведения о роутере.');}}
|
||||
finally{if(active)timer=setTimeout(()=>void poll(),cadence);}
|
||||
}
|
||||
void poll();return()=>{active=false;clearTimeout(timer);};
|
||||
const expiry=setInterval(()=>{if(performance.now()-lastData>=20000)setValue(previous=>previous?.fresh!==false&&previous?{...previous,fresh:false}:previous);},1000);
|
||||
void poll();return()=>{active=false;clearTimeout(timer);clearInterval(expiry);};
|
||||
},[transport]);
|
||||
return {value,error};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
"""Isolated loopback browser origin; no vendor JavaScript in the Core origin."""
|
||||
|
||||
import base64
|
||||
import http.cookies
|
||||
import secrets
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Any
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from .router_admin_transport import forward
|
||||
|
||||
|
||||
class Bridge(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
allow_reuse_address = False
|
||||
|
||||
def __init__(self, fleet: Any, vehicle: str, device: str, binding: str) -> None:
|
||||
self.fleet, self.vehicle, self.device, self.binding = fleet, vehicle, device, binding
|
||||
self.secret = secrets.token_urlsafe(32)
|
||||
self.last_used = time.monotonic()
|
||||
self.cookies: set[str] = set()
|
||||
self.slots = threading.BoundedSemaphore(8)
|
||||
super().__init__(("127.0.0.1", 0), Handler)
|
||||
self.origin = f"http://127.0.0.1:{self.server_port}"
|
||||
self.cookie = f"mc_router_{self.server_port}"
|
||||
self.timeout = 1
|
||||
threading.Thread(target=self.run, daemon=True, name="router-admin").start()
|
||||
|
||||
def run(self) -> None:
|
||||
try:
|
||||
while not self.fleet.stop.is_set() and time.monotonic() - self.last_used < 1800:
|
||||
self.handle_request()
|
||||
finally:
|
||||
self.server_close()
|
||||
|
||||
def process_request(
|
||||
self, request: socket.socket | tuple[bytes, socket.socket], address: Any
|
||||
) -> None:
|
||||
if not self.slots.acquire(blocking=False):
|
||||
self.shutdown_request(request)
|
||||
return
|
||||
super().process_request(request, address)
|
||||
|
||||
def process_request_thread(
|
||||
self, request: socket.socket | tuple[bytes, socket.socket], address: Any
|
||||
) -> None:
|
||||
try:
|
||||
super().process_request_thread(request, address)
|
||||
finally:
|
||||
self.slots.release()
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server: Bridge
|
||||
server_version = "MissionCore"
|
||||
|
||||
def log_message(self, *_: Any) -> None:
|
||||
pass # URLs, vendor cookies and form bodies must not enter access logs.
|
||||
|
||||
def setup(self) -> None:
|
||||
super().setup()
|
||||
self.connection.settimeout(15)
|
||||
|
||||
def do_GET(self) -> None:
|
||||
self.proxy()
|
||||
|
||||
def do_HEAD(self) -> None:
|
||||
self.proxy()
|
||||
|
||||
def do_POST(self) -> None:
|
||||
self.proxy()
|
||||
|
||||
def proxy(self) -> None:
|
||||
bridge = self.server
|
||||
if self.headers.get("Host") != urlsplit(bridge.origin).netloc:
|
||||
self.send_error(403)
|
||||
return
|
||||
parsed = urlsplit(self.path)
|
||||
if self.command == "GET" and parsed.path == "/_mission_core_open":
|
||||
launch_token = parse_qs(parsed.query).get("token", [""])[0]
|
||||
if not secrets.compare_digest(launch_token, bridge.secret):
|
||||
self.send_error(403)
|
||||
return
|
||||
# A 303 preserves the initiating Core origin in Fetch Metadata.
|
||||
# Commit this isolated origin before navigating to vendor content;
|
||||
# ordinary cross-origin/same-site requests remain forbidden.
|
||||
nonce = secrets.token_urlsafe(16)
|
||||
body = (
|
||||
'<!doctype html><meta charset="utf-8"><title>DexaFlow</title>'
|
||||
f'<script nonce="{nonce}">location.replace("/cgi-bin/luci/dexaflow")</script>'
|
||||
).encode()
|
||||
self.send_response(200)
|
||||
self.send_header(
|
||||
"Set-Cookie", f"{bridge.cookie}={bridge.secret}; HttpOnly; SameSite=Strict; Path=/"
|
||||
)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header(
|
||||
"Content-Security-Policy", f"default-src 'none'; script-src 'nonce-{nonce}'"
|
||||
)
|
||||
self.send_header("X-Frame-Options", "DENY")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
cookies = http.cookies.SimpleCookie()
|
||||
try:
|
||||
cookies.load(self.headers.get("Cookie", ""))
|
||||
except http.cookies.CookieError:
|
||||
self.send_error(403)
|
||||
return
|
||||
token = cookies.get(bridge.cookie)
|
||||
origin = self.headers.get("Origin")
|
||||
fetch = self.headers.get("Sec-Fetch-Site")
|
||||
if (
|
||||
not token
|
||||
or not secrets.compare_digest(token.value, bridge.secret)
|
||||
or (origin and origin != bridge.origin)
|
||||
or fetch not in (None, "same-origin", "none")
|
||||
or (self.command == "POST" and origin != bridge.origin)
|
||||
):
|
||||
self.send_error(403)
|
||||
return
|
||||
try:
|
||||
size = int(self.headers.get("Content-Length", "0"))
|
||||
if not 0 <= size <= 1048576 or self.headers.get("Transfer-Encoding"):
|
||||
raise ValueError("Запрос слишком большой.")
|
||||
headers = {
|
||||
k: self.headers[k]
|
||||
for k in ("Content-Type", "Accept", "Accept-Encoding")
|
||||
if k in self.headers
|
||||
}
|
||||
headers["Cookie"] = "; ".join(
|
||||
f"{k}={v.value}" for k, v in cookies.items() if k in bridge.cookies
|
||||
)
|
||||
status, response_headers, body = forward(
|
||||
bridge.fleet,
|
||||
bridge.vehicle,
|
||||
bridge.binding,
|
||||
bridge.device,
|
||||
{
|
||||
"method": self.command,
|
||||
"path": self.path,
|
||||
"headers": headers,
|
||||
"body": base64.b64encode(self.rfile.read(size)).decode(),
|
||||
},
|
||||
)
|
||||
bridge.last_used = time.monotonic()
|
||||
except Exception:
|
||||
self.send_error(502, "Router unavailable; reopen from Mission Core")
|
||||
return
|
||||
self.send_response(status)
|
||||
for key in ("Content-Type", "Content-Encoding", "Location", "Content-Disposition"):
|
||||
for value in response_headers.get(key, []):
|
||||
if "\r" not in value and "\n" not in value:
|
||||
self.send_header(key, value)
|
||||
for value in response_headers.get("Set-Cookie", []):
|
||||
cookie = http.cookies.SimpleCookie()
|
||||
try:
|
||||
cookie.load(value)
|
||||
for name, morsel in cookie.items():
|
||||
if name.startswith("mc_router_"):
|
||||
continue
|
||||
morsel["domain"] = ""
|
||||
morsel["path"] = "/"
|
||||
morsel["samesite"] = "Strict"
|
||||
bridge.cookies.add(name)
|
||||
self.send_header("Set-Cookie", morsel.OutputString())
|
||||
except http.cookies.CookieError:
|
||||
continue
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
self.send_header("X-Frame-Options", "DENY")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
if self.command != "HEAD":
|
||||
self.wfile.write(body)
|
||||
|
||||
|
||||
def open_admin(fleet: Any, vehicle: str, device: str) -> dict[str, str]:
|
||||
with fleet.lock:
|
||||
row = fleet.find(vehicle)
|
||||
view = fleet.routers.view(row)
|
||||
if (
|
||||
row["enrollment"] != "paired"
|
||||
or view.get("admin_version") != 1
|
||||
or not view.get("available")
|
||||
or view.get("fresh") is False
|
||||
or not any(
|
||||
d["id"] == device and d.get("attached") and d["state"] == "ready"
|
||||
for d in view.get("items", [])
|
||||
)
|
||||
):
|
||||
raise ValueError("Для входа нужны подключённые борт и роутер.")
|
||||
bridges = getattr(fleet, "_router_admin_bridges", {})
|
||||
bridges = {k: b for k, b in bridges.items() if b.fileno() >= 0}
|
||||
key = (vehicle, device, row["binding"]["binding_id"])
|
||||
bridge = bridges.get(key)
|
||||
if bridge is None:
|
||||
if len(bridges) >= 8:
|
||||
raise ValueError("Завершите неиспользуемые сеансы админки.")
|
||||
bridge = Bridge(fleet, *key)
|
||||
bridges[key] = bridge
|
||||
bridge.last_used = time.monotonic()
|
||||
fleet._router_admin_bridges = bridges
|
||||
return {"url": bridge.origin + "/_mission_core_open?token=" + bridge.secret}
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Bound Core-to-Node browser forwarding over the existing pinned mTLS listener."""
|
||||
|
||||
import base64
|
||||
import copy
|
||||
import http.client
|
||||
import json
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from .recovery import client_context, node_addresses
|
||||
from .trust import verify_node_certificate
|
||||
|
||||
|
||||
def forward(
|
||||
fleet: Any, vehicle: str, binding: str, device: str, request: dict[str, Any]
|
||||
) -> tuple[int, dict[str, list[str]], bytes]:
|
||||
with fleet.lock:
|
||||
row = copy.deepcopy(fleet.find(vehicle))
|
||||
snapshot = fleet.routers.view(row)
|
||||
if (
|
||||
row["enrollment"] != "paired"
|
||||
or row["binding"]["binding_id"] != binding
|
||||
or not snapshot.get("available")
|
||||
or snapshot.get("fresh") is False
|
||||
or not any(
|
||||
d["id"] == device and d.get("attached") and d["state"] == "ready"
|
||||
for d in snapshot.get("items", [])
|
||||
)
|
||||
):
|
||||
raise ValueError("Борт или роутер недоступен. Откройте админку заново из Core.")
|
||||
addresses = node_addresses(row) # type: ignore[no-untyped-call]
|
||||
# Reuse a bounded client certificate, never create one per asset request.
|
||||
cache = getattr(fleet, "_router_admin_tls", None)
|
||||
if cache is None or time.monotonic() > cache[1]:
|
||||
cache = (client_context(fleet.trust), time.monotonic() + 3600) # type: ignore[no-untyped-call]
|
||||
fleet._router_admin_tls = cache
|
||||
if not addresses:
|
||||
raise ValueError("Нет подтверждённого адреса борта.")
|
||||
connection = http.client.HTTPSConnection(addresses[0], 8781, timeout=12, context=cache[0])
|
||||
try:
|
||||
connection.connect()
|
||||
certificate = connection.sock.getpeercert(binary_form=True)
|
||||
if not isinstance(certificate, bytes):
|
||||
raise ValueError("Борт не подтвердил сертификат.")
|
||||
verify_node_certificate(certificate, row["node_id"])
|
||||
if request["method"] == "POST":
|
||||
connection.sock.settimeout(105)
|
||||
payload = {**request, "binding_id": binding, "device_id": device}
|
||||
connection.request(
|
||||
"POST", "/v1/router/admin", json.dumps(payload), {"Content-Type": "application/json"}
|
||||
)
|
||||
response = connection.getresponse()
|
||||
raw = response.read(12 * 1048576 + 1)
|
||||
if response.status != 200 or len(raw) > 12 * 1048576:
|
||||
raise ValueError("Борт не открыл админку. Проверьте связь и версию Node.")
|
||||
result = json.loads(raw)
|
||||
body = base64.b64decode(result["body"], validate=True)
|
||||
if not 100 <= result["status"] <= 599 or len(body) > 8 * 1048576:
|
||||
raise ValueError("Некорректный ответ админки.")
|
||||
return result["status"], result["headers"], body
|
||||
finally:
|
||||
connection.close()
|
||||
@@ -240,6 +240,7 @@ class Receipt(PublicModel):
|
||||
|
||||
class Snapshot(PublicModel):
|
||||
speedtest_version: Literal[0, 1] = 0
|
||||
admin_version: Literal[0, 1] = 0
|
||||
read_version: Literal[0, 1] = 0
|
||||
evidence: EvidenceChunk | None = None
|
||||
control_version: Literal[0, 1] = 0
|
||||
|
||||
@@ -41,7 +41,7 @@ class Routers:
|
||||
now - entry["created"] > 300 and entry["public"]["state"] == "applying"
|
||||
):
|
||||
entry["payload"] = None
|
||||
entry["public"] = {"operation_id": key[1], "state": "unknown"}
|
||||
entry["public"] = {**entry["public"], "state": "unknown"}
|
||||
|
||||
def view(self, row):
|
||||
self.prune()
|
||||
|
||||
@@ -21,6 +21,14 @@ def register(parent, local_operator):
|
||||
except PairingError:
|
||||
raise HTTPException(404, "Аппарат не найден.") from None
|
||||
|
||||
@parent.post("/{vehicle_id}/routers/{device_id}/admin")
|
||||
def admin(vehicle_id: str, device_id: str, fleet: Operator):
|
||||
from k1link.fleet.router_admin import open_admin
|
||||
try:
|
||||
return open_admin(fleet, vehicle_id, device_id)
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@parent.get("/{vehicle_id}/routers/journal")
|
||||
def export(vehicle_id: str, fleet: Operator):
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Isolated-origin bridge tests without a board, VPN or router."""
|
||||
|
||||
import http.client
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.fleet import router_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bridge(monkeypatch):
|
||||
calls = []
|
||||
|
||||
def forward(*args):
|
||||
calls.append(args[-1])
|
||||
return (
|
||||
200,
|
||||
{
|
||||
"Content-Type": ["text/plain"],
|
||||
"Set-Cookie": ["vendor=login; Domain=192.168.1.1; Path=/"],
|
||||
},
|
||||
b"ok",
|
||||
)
|
||||
|
||||
monkeypatch.setattr(router_admin, "forward", forward)
|
||||
fleet = SimpleNamespace(stop=threading.Event())
|
||||
server = router_admin.Bridge(fleet, "vehicle", "device", "binding")
|
||||
yield server, calls
|
||||
fleet.stop.set()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def call(server, method, path, headers=None):
|
||||
c = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=3)
|
||||
try:
|
||||
c.request(method, path, headers=headers or {})
|
||||
r = c.getresponse()
|
||||
return r.status, dict(r.getheaders()), r.read()
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
def test_launch_authorizes_only_its_isolated_origin(bridge):
|
||||
s, calls = bridge
|
||||
assert call(s, "GET", "/cgi-bin/luci/dexaflow")[0] == 403
|
||||
status, headers, body = call(s, "GET", "/_mission_core_open?token=" + s.secret)
|
||||
assert status == 200 and b'location.replace("/cgi-bin/luci/dexaflow")' in body
|
||||
assert "script-src 'nonce-" in headers["Content-Security-Policy"]
|
||||
assert s.secret.encode() not in body
|
||||
cookie = headers["Set-Cookie"].split(";")[0]
|
||||
status, headers, _ = call(s, "GET", "/cgi-bin/luci/dexaflow", {"Cookie": cookie})
|
||||
assert status == 200
|
||||
assert "Domain=" not in headers["Set-Cookie"]
|
||||
assert s.secret not in str(calls)
|
||||
assert (
|
||||
call(s, "POST", "/cgi-bin/dexaflow_auth", {"Cookie": cookie, "Origin": "http://evil.test"})[
|
||||
0
|
||||
]
|
||||
== 403
|
||||
)
|
||||
assert (
|
||||
call(s, "GET", "/cgi-bin/dexaflow_auth", {"Cookie": cookie, "Sec-Fetch-Site": "same-site"})[
|
||||
0
|
||||
]
|
||||
== 403
|
||||
)
|
||||
assert call(s, "GET", "/", {"Host": "evil.test", "Cookie": cookie})[0] == 403
|
||||
assert len(calls) == 1
|
||||
assert (
|
||||
call(
|
||||
s,
|
||||
"POST",
|
||||
"/cgi-bin/dexaflow_auth",
|
||||
{"Cookie": cookie + "; vendor=login; unrelated=secret", "Origin": s.origin},
|
||||
)[0]
|
||||
== 200
|
||||
)
|
||||
assert calls[-1]["headers"]["Cookie"] == "vendor=login"
|
||||
|
||||
|
||||
def test_no_arbitrary_destination_and_reuse_same_router(bridge):
|
||||
s, _ = bridge
|
||||
fleet = s.fleet
|
||||
fleet.lock = threading.RLock()
|
||||
fleet.find = lambda v: {"enrollment": "paired", "binding": {"binding_id": "binding"}}
|
||||
fleet.routers = SimpleNamespace(
|
||||
view=lambda row: {
|
||||
"available": True,
|
||||
"fresh": True,
|
||||
"admin_version": 1,
|
||||
"items": [{"id": "device", "attached": True, "state": "ready"}],
|
||||
}
|
||||
)
|
||||
fleet._router_admin_bridges = {("vehicle", "device", "binding"): s}
|
||||
result = router_admin.open_admin(fleet, "vehicle", "device")
|
||||
assert urlsplit(result["url"]).netloc == urlsplit(s.origin).netloc
|
||||
with pytest.raises(ValueError):
|
||||
router_admin.open_admin(fleet, "vehicle", "http://external.test")
|
||||
Reference in New Issue
Block a user