feat(routers): add observed router inventory and scoped controls
Separate router discovery, evidence and authorized control from device runtime. Add Node/Core contracts and reusable operator surfaces.
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,SettingsCard,StatusBadge,TextField} from '@nodedc/ui-react';
|
||||
import type {RouterDevice,RouterSnapshot,RouterTransport} from './contracts';
|
||||
|
||||
const errors:Record<string,string>={access_rejected:'Роутер отклонил доступ. Проверьте имя и пароль.',router_unavailable:'Роутер недоступен. Дождитесь подключения.',expired:'Срок запроса истёк. Повторите после обновления состояния.',unsupported_response:'Не удалось прочитать совместимый ответ роутера.',storage_error:'Не удалось сохранить доступ на борту.'};
|
||||
|
||||
export function RouterAccess({device,value,transport,fresh}:{device:RouterDevice;value:RouterSnapshot;transport:RouterTransport;fresh:boolean}){
|
||||
const [username,setUsername]=useState(''),[password,setPassword]=useState(''),[pending,setPending]=useState(''),[message,setMessage]=useState(''),[sending,setSending]=useState(false);
|
||||
const busy=sending||!!pending;
|
||||
const active=useRef(true);
|
||||
useEffect(()=>{active.current=true;return()=>{active.current=false;};},[]);
|
||||
useEffect(()=>{
|
||||
if(!pending)return;
|
||||
let stopped=false;let timer:ReturnType<typeof setTimeout>;const end=Date.now()+95000;
|
||||
async function poll(){
|
||||
try{const result=await transport.operation(pending);if(stopped)return;
|
||||
if(result.state!=='queued'){setPending('');setMessage(result.state==='complete'?'Доступ сохранён на борту.':errors[result.error??'']??'Подтверждение не получено. Обновите состояние перед повтором.');return;}
|
||||
}catch{/* A lost response is not proof that authorization failed. */}
|
||||
if(stopped)return;
|
||||
if(Date.now()>=end){setPending('');setMessage('Подтверждение не получено. Обновите состояние перед повтором.');return;}
|
||||
timer=setTimeout(()=>void poll(),2000);
|
||||
}
|
||||
void poll();return()=>{stopped=true;clearTimeout(timer);};
|
||||
},[pending,transport]);
|
||||
async function authorize(){
|
||||
if(!value.runtime_id)return;
|
||||
const id='op_'+crypto.randomUUID().replaceAll('-','');const secret=password;setPassword('');setSending(true);setMessage('');
|
||||
try{await transport.authorize({operation_id:id,runtime_id:value.runtime_id,device_id:device.id,deadline:Math.floor(Date.now()/1000)+85,username,password:secret});}
|
||||
catch{if(active.current)setMessage('Подтверждаем результат отправки.');}
|
||||
finally{if(active.current){setSending(false);setPending(id);}}
|
||||
}
|
||||
return <SettingsCard title="Доступ к роутеру" description="Имя и пароль сохраняются только на бортовом компьютере. Доступ к админке передаётся по локальному соединению с роутером.">
|
||||
<div className="router-form">
|
||||
<p>Устройство привязано к локальному сетевому адресу оборудования. Криптографическая идентификация этой прошивкой не подтверждена.</p>
|
||||
<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={busy} disabled={!fresh||busy||!username||!password} onClick={()=>void authorize()}>Предоставить доступ</Button>
|
||||
{message&&<StatusBadge tone="neutral">{message}</StatusBadge>}
|
||||
</div>
|
||||
</SettingsCard>;
|
||||
}
|
||||
Reference in New Issue
Block a user