diff --git a/apps/device-manager/src/DeviceInventoryView.tsx b/apps/device-manager/src/DeviceInventoryView.tsx index 77b3262..e27d877 100644 --- a/apps/device-manager/src/DeviceInventoryView.tsx +++ b/apps/device-manager/src/DeviceInventoryView.tsx @@ -31,6 +31,8 @@ import type { SessionView, } from "./types"; +import { B2TrackerSettings } from "./b2/B2TrackerSettings"; +import type { TrackerRef } from "./b2/tracker"; import { useB2Inventory } from "./b2/useB2Inventory"; export type DeviceInventoryDetailState = { @@ -60,6 +62,7 @@ export function DeviceInventoryView({ onError: (reason: unknown) => void; onDetailChange: (detail: DeviceInventoryDetailState | null) => void; }) { + const [tracker, setTracker] = useState<{ device: TrackerRef; projectRef: string; section: string } | null>(null); const b2 = useB2Inventory(workspace.project.projectRef, workspace); const [typeFilter, setTypeFilter] = useState("all"); const [archiveTarget, setArchiveTarget] = useState(null); @@ -115,6 +118,7 @@ export function DeviceInventoryView({ const count = workspace.devices.filter((device) => !['suspended', 'retired'].includes(device.lifecycleState)).length + (b2.data?.items.length || 0); return (
+ {tracker && tracker.projectRef===workspace.project.projectRef ? setTracker(null)} onError={onError} onChanged={onPoll} canConfigure={canConfigure} canCommand={workspace.project.access.capabilities.includes('command.dispatch')} /> : null} {selectedDevice && detail ? onDetailChange(null)} /> : null} { if (!archiving) setArchiveTarget(null); }} onConfirm={async () => { @@ -161,7 +165,7 @@ export function DeviceInventoryView({ {statusFilter !== 'pending' ? {remoteRows.map((device) =>
  • } title={device.name || `ARNavi B2 · ${device.number}`} metadata={`ARNavi B2 · ${device.number} · IMEI ${device.identifier.masked}`} description={device.hostName} - status={{device.active ? 'Зарегистрирован на VPS' : 'Отключён на VPS'}} />
  • )} + actions={<>setTracker({device,projectRef:workspace.project.projectRef,section:'commands'})}>setTracker({device,projectRef:workspace.project.projectRef,section:'identity'})}>} />)} {deviceRows.map(({ device, online, lastSeenAt }) =>
  • } title={device.displayName} metadata={`${profileLabel(workspace, device)} · ${deviceIdentifierDisplayValue(device) || 'IMEI не назначен'}`} description={lastSeenAt ? formatDate(lastSeenAt) : undefined} diff --git a/apps/device-manager/src/DeviceManagerApp.tsx b/apps/device-manager/src/DeviceManagerApp.tsx index 1583785..20e968f 100644 --- a/apps/device-manager/src/DeviceManagerApp.tsx +++ b/apps/device-manager/src/DeviceManagerApp.tsx @@ -237,6 +237,7 @@ export function DeviceManagerApp() { useEffect(() => { applyNodedcTheme(document.documentElement, { theme: presentation.environment.theme, + appearance: "mission", accent: hexToRgb(presentation.environment.accentHex), }); }, [presentation.environment.accentHex, presentation.environment.theme]); diff --git a/apps/device-manager/src/b2/B2HostSettings.tsx b/apps/device-manager/src/b2/B2HostSettings.tsx index 507dd33..a819054 100644 --- a/apps/device-manager/src/b2/B2HostSettings.tsx +++ b/apps/device-manager/src/b2/B2HostSettings.tsx @@ -74,7 +74,7 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: return <> { setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); } diff --git a/apps/device-manager/src/b2/B2TrackerSettings.tsx b/apps/device-manager/src/b2/B2TrackerSettings.tsx new file mode 100644 index 0000000..ba696e9 --- /dev/null +++ b/apps/device-manager/src/b2/B2TrackerSettings.tsx @@ -0,0 +1,144 @@ +import { useEffect, useRef, useState } from 'react'; +import { Button, FeatureSettingsWindow, Icon, IconButton, ResourceList, ResourceRow, Select, SettingsCard, StatusBadge, Switch, TextField, Window } from '@nodedc/ui-react'; +import { trackerRequest, newIntent, operationName, stateName, formatTime, type TrackerRef, type TrackerState, type Policy, type Operation } from './tracker'; +import { B2RequestError } from './api'; +import './b2.css'; + +type Props = { projectRef:string;device:TrackerRef;initialSection?:string;onClose:()=>void;onError:(error:unknown)=>void;onChanged:()=>Promise;canConfigure:boolean;canCommand:boolean }; +export function B2TrackerSettings({projectRef,device,initialSection='identity',onClose,onError,onChanged,canConfigure,canCommand}:Props) { + const [section,setSection]=useState(initialSection==='commands'?'commands':'identity'); + const [data,setData]=useState(null), [name,setName]=useState(device.name); + const [policy,setPolicy]=useState({parameters:{},connectivity:{mode:'preserve'}}); + const [profile,setProfile]=useState(''),[profileName,setProfileName]=useState(''),[profileOpen,setProfileOpen]=useState(false); + const [busy,setBusy]=useState('load'),[dirty,setDirty]=useState(false),[commandsOpen,setCommandsOpen]=useState(initialSection==='commands'); + const [bootstrapFirmware,setBootstrapFirmware]=useState(''),[bootstrapPassword,setBootstrapPassword]=useState(''); + const profileIntent=useRef|null>(null); + const [latest,setLatest]=useState(null); + const request=(body:Record)=>trackerRequest(projectRef,device,body); + const alive=useRef(true), intent=useRef<{action:string;request:Record}|null>(null); + const file=useRef(null); + useEffect(()=>{ + alive.current=true; + request({action:'state'}).then(value=>{if(alive.current){setData(value);setLatest(value.latest_operation);setName(value.name);setPolicy(value.policy);}}).catch(onError).finally(()=>{if(alive.current)setBusy('');}); + return()=>{alive.current=false;}; + },[device.id,projectRef]); + async function refresh() { const next=await request({action:'state'}); if(alive.current){setData(next);setLatest(next.latest_operation);} return next; } + useEffect(()=>{ + if(!latest || !['queued','dispatched'].includes(latest.state))return; + let active=true; + const timer=setTimeout(async()=>{try {const result=await request<{items:Operation[]}>({action:'journal'});const item=result.items.find(row=>row.id===latest.id);if(active&&item){setLatest(item);if(!['queued','dispatched'].includes(item.state))await refresh();}}catch(error){if(active)onError(error);}},3000); + return()=>{active=false;clearTimeout(timer);}; + },[latest]); + const edit=(value:Policy)=>{setPolicy(value);setDirty(true);}; + async function run(label:string,work:()=>Promise) {setBusy(label);try{await work();}catch(error){onError(error);}finally{if(alive.current)setBusy('');}} + async function save() { + if(!data)return 0; + const result=await request<{revision:number}>({action:'save',revision:data.revision,name,policy}); + setData({...data,revision:result.revision,name,policy});setDirty(false);await onChanged();return result.revision; + } + async function operation(action:'read'|'apply') { + if(!data)return; + const pending=intent.current; + if(pending && pending.action!==action)throw new Error('Сначала уточните результат предыдущей отправки.'); + if(!pending){ + const revision=action==='apply'&&dirty?await save():data.revision; + intent.current={action,request:{action,id:newIntent(),...(action==='apply'?{revision,expected_sha256:data.observed?.sha256}:!data.observed?{bootstrap:{firmware:bootstrapFirmware,password:bootstrapPassword}}:{})}}; + } + try {const result=await request(intent.current!.request);intent.current=null;setBootstrapPassword('');setLatest(result);} catch(error) {if(error instanceof B2RequestError&&error.rejected)intent.current=null;throw error;} + } + const groupNames=[...new Set(data?.fields.map(field=>field.group)||[])]; + const pending=Boolean(latest&&['queued','dispatched'].includes(latest.state)); + const disabled=Boolean(busy)||pending||!canConfigure; + const connected=Boolean(data?.last_seen_at && Date.now()/1000-data.last_seen_at<120); + async function uploadFirmware(value:File) { + if(!/\.dfw$/i.test(value.name)||value.size>4*1024*1024||!value.size)throw new Error('Выберите непустой файл .dfw до 4 МБ.'); + const bytes=new Uint8Array(await value.arrayBuffer()); + const digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),n=>n.toString(16).padStart(2,'0')).join(''); + for(let offset=0;offset[]=[];let offset=0,size=1,filename='firmware.dfw'; + while(offset({action:'firmware-download',digest,offset});size=result.size;filename=result.filename;const bytes=Uint8Array.from(atob(result.chunk),c=>c.charCodeAt(0));if(!bytes.length)throw new Error('Неполный файл прошивки');chunks.push(bytes);offset+=bytes.length;} + const blob=new Blob(chunks);const actual=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',await blob.arrayBuffer())),n=>n.toString(16).padStart(2,'0')).join(''); + if(actual!==digest)throw new Error('Контрольная сумма файла не совпала'); + const url=URL.createObjectURL(blob),link=document.createElement('a');link.href=url;link.download=filename;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000); + } + return <> + ({id:group,label:group,group:index===0?'Параметры профиля':undefined}))]} + activeSection={section} onSectionChange={setSection} onClose={onClose} + headerActions={void run('refresh',async()=>{await refresh();})}>} + footer={section!=='commands'&§ion!=='firmware'?<>:undefined}> +
    + {connected?'Передаёт данные на VPS':data?'Нет свежих данных':'Загрузка…'} + {data&§ion!=='commands'&§ion!=='firmware'? +
    + {data.observed?`Последнее чтение: ${formatTime(data.observed.received_at)}`:'Настройки трекера ещё не прочитаны'} + {latest?{stateName(latest.state)}:null}{pending?Задание сохранено на VPS. Окно можно закрыть.:null} + + {!data.observed?<>({value:item.id,label:item.name}))]} onChange={id=>{setProfile(id);const selected=data.profiles.find(item=>item.id===id);if(selected)edit(structuredClone(selected.policy));}} /> +
    Модель
    ARNavi B2 · 231
    Номер
    {data.number}
    IMEI
    {data.identifier}
    Прошивка
    {data.firmware||'Не прочитана'}
    Последние данные
    {formatTime(data.last_seen_at)}
    + :null} + {section==='connection'&&data?<> + {[1,2].map(slot=>Интернет:undefined}> +
    {data.sims[String(slot)]?.identifier||'Нет сведений о карте'}
    Регистрация
    {({0:'Не обнаружена',1:'В домашней сети',2:'Поиск сети',3:'Отказ регистрации',4:'Нет сведений',5:'Роуминг'} as Record)[data.cellular.status?.sim_states[String(slot)]??4]}
    Сигнал
    {data.cellular.networks?.[String(slot)]?.signal!=null?`${data.cellular.networks[String(slot)].signal} / 31`:'—'}
    Наблюдение
    {formatTime(data.cellular.measured_at)}
    APN
    {(slot===1?data.observed?.apn1:data.observed?.apn2)||'Автоматически'}
    + edit({...policy,connectivity:{...policy.connectivity,mode}})} options={[{value:'preserve',label:'Сохранить режим трекера'},{value:'native',label:'Автоматический режим без заданного APN'},{value:'both',label:'Автоматический режим — сохранить APN'},{value:'sim1',label:'Только SIM1'},{value:'sim2',label:'Только SIM2'}]} /> +
    + edit({...policy,endpoint:checked?{slot:1,host:data.observed?.servers[0]?.host||'',port:data.observed?.servers[0]?.port||9922}:null})} /> + {policy.endpoint?<>edit({...policy,endpoint:{...policy.endpoint!,host:event.target.value}})} />edit({...policy,endpoint:{...policy.endpoint!,port:Number(event.target.value)}})} />{const selected=event.target.files?.[0];event.target.value='';if(selected)void run('firmware',()=>uploadFirmware(selected));}} /> + {data.firmwares.map(item=>
  • void run('firmware',()=>downloadFirmware(item.sha256))}>} />
  • )}
    + {!data.firmwares.length?Нет сохранённых файлов:null} + :null} +
    + + {commandsOpen?setCommandsOpen(false)} onError={onError} />:null} + setProfileOpen(false)} footer={}>setProfileName(event.target.value)} /> + ; +} + +const presets=[{id:'position',label:'Запросить координаты',command:{kind:'request-position'}},{id:'restart',label:'Перезапустить B2',command:{kind:'restart'}},...[4,5,6].flatMap(pin=>[...([true,false] as const).map(enabled=>({id:`pin${pin}-${enabled}`,label:`${enabled?'Включить':'Выключить'} выход PIN${pin}`,command:{kind:'set-output',pin,enabled}})),{id:`pin${pin}-pulse`,label:`Импульс PIN${pin} · 5 с`,command:{kind:'pulse-output',pin,seconds:5}}])]; +function B2CommandWindow({projectRef,device,data,canCommand,onClose,onError}:{projectRef:string;device:TrackerRef;data:TrackerState|null;canCommand:boolean;onClose:()=>void;onError:(error:unknown)=>void}) { + const [filter,setFilter]=useState('all'); + const [selection,setSelection]=useState('position'),[rows,setRows]=useState([]),[before,setBefore]=useState(null),[busy,setBusy]=useState(false),[details,setDetails]=useState([]),[history,setHistory]=useState>({}); + const intent=useRef|null>(null),alive=useRef(true); + const request=(body:Record)=>trackerRequest(projectRef,device,body); + async function refresh(append=false) {const result=await request<{items:Operation[];before:number|null}>({action:'journal',...(append&&before?{before}:{})});if(alive.current){setRows(old=>append?[...old,...result.items]:result.items);setBefore(result.before);}} + useEffect(()=>{alive.current=true;void refresh().catch(onError);return()=>{alive.current=false;};},[]); + useEffect(()=>{if(!rows.some(row=>['queued','dispatched'].includes(row.state)))return;const timer=setTimeout(()=>void refresh().catch(onError),3000);return()=>clearTimeout(timer);},[rows]); + const selected=presets.find(item=>item.id===selection)!; + const pin='pin' in selected.command?selected.command.pin:null; + const available=data?.capabilities.configuration&&(!pin||data.observed?.output_modes[String(pin)]===1); + async function send(command:Record=selected.command) {setBusy(true);try {intent.current ||= {action:'command',id:newIntent(),command};await request(intent.current);intent.current=null;await refresh();}catch(error){if(error instanceof B2RequestError&&error.rejected)intent.current=null;onError(error);}finally{setBusy(false);}} + return void refresh().catch(onError)}>}> +
    +
    {rows.filter(row=>filter==='all'||(filter==='pending')===['queued','dispatched'].includes(row.state)).map(row=>
  • {stateName(row.state)}} actions={<>{canCommand&&row.repeatable&&row.command?{const preset=presets.find(item=>JSON.stringify(item.command)===JSON.stringify(row.command));if(preset)setSelection(preset.id);void send(row.command);}}>:null}{setDetails(old=>old.includes(row.id)?old.filter(id=>id!==row.id):[...old,row.id]);void request({action:'attempts',operation:row.id}).then(value=>setHistory(old=>({...old,[row.id]:value}))).catch(onError);}}>{canCommand&&['queued','dispatched'].includes(row.state)?void request({action:'cancel',operation:row.id,kind:row.kind}).then(()=>refresh()).catch(onError)}>:null}} /> + {details.includes(row.id)?
    Попытки
    {row.attempt_count??0}
    Отправлена
    {formatTime(row.dispatched_at)}
    Ответ
    {formatTime(row.received_at||row.delivered_at||row.verified_at)}
    Результат
    {stateName(row.state)}
    ID
    {row.id}
    :null} +
  • )}
    {!rows.length?Команд пока нет:null}{before?:null} +
    + ; +} +function AttemptRows({value}:{value:unknown}) { const items=(value as {items?:Operation[]}|undefined)?.items;return items?.length?{items.map((item,index)=>
  • {stateName(item.state)}} />
  • )}
    :null; } diff --git a/apps/device-manager/src/b2/api.ts b/apps/device-manager/src/b2/api.ts index 1f18bc6..1575d08 100644 --- a/apps/device-manager/src/b2/api.ts +++ b/apps/device-manager/src/b2/api.ts @@ -6,6 +6,10 @@ export type B2Status = { connected: boolean; endpoint?: string; authority?: 'hos links?: Array<{ contourId: string; projectRef: string }> }; export type B2Device = { id: string; identifier: { masked: string }; name: string; active: boolean; number: number; contourId: string }; const messages: Record = { + b2_settings_revision_changed: 'Настройки изменились. Обновите сведения о трекере перед отправкой.', + b2_settings_initial_read_required: 'Сначала прочитайте настройки трекера через VPS.', + b2_settings_sim_observation_required: 'Нет свежих данных выбранной SIM. Дождитесь регистрации карты и обновите сведения.', + b2_request_invalid: 'Проверьте параметры: VPS отклонил запрос.', b2_infrastructure_unavailable: 'Подключение ARNavi пока не настроено на сервере Device Core.', b2_host_unavailable: 'VPS не отвечает. Проверьте доступность сервера.', b2_host_not_connected: 'Сначала подключите VPS.', @@ -20,6 +24,9 @@ const messages: Record = { b2_company_mismatch: 'Выберите проект той же компании.', device_owner_scope_access_denied: 'Настройки общего VPS доступны администратору компании.', }; +export class B2RequestError extends Error { + constructor(message: string, public readonly rejected: boolean) { super(message); } +} export async function b2Request(projectRef: string, hostRef: string, action: string, fields: Record = {}, requestId = crypto.randomUUID().replaceAll('-', '')): Promise { const response = await fetch('/api/device-manager/b2/infrastructure', { method: 'POST', credentials: 'same-origin', @@ -27,6 +34,6 @@ export async function b2Request(projectRef: string, hostRef: string, action: body: JSON.stringify({ projectRef, hostRef, action, ...fields }), }); const body = await response.json().catch(() => null); - if (!response.ok || body?.ok !== true) throw new Error(messages[body?.error] || 'Не удалось выполнить действие на VPS. Обновите сведения о подключении.'); + if (!response.ok || body?.ok !== true) throw new B2RequestError(messages[body?.error] || 'Не удалось выполнить действие на VPS. Обновите сведения о подключении.', response.status >= 400 && response.status < 500); return body.result as T; } diff --git a/apps/device-manager/src/b2/b2.css b/apps/device-manager/src/b2/b2.css index 43ff73b..82adcc1 100644 --- a/apps/device-manager/src/b2/b2.css +++ b/apps/device-manager/src/b2/b2.css @@ -6,3 +6,8 @@ .b2-disclosure { display: grid; gap: var(--nodedc-space-2); } .b2-disclosure__body { display: grid; gap: var(--nodedc-space-3); padding: var(--nodedc-space-2) var(--nodedc-space-3) var(--nodedc-space-4); } .b2-section-heading { display: flex; align-items: center; justify-content: space-between; gap: var(--nodedc-space-3); font-size: var(--nodedc-font-size-sm); } + +.b2-tracker-form { display: grid; min-width: 0; gap: 1rem; } +.b2-tracker-facts { display: grid; grid-template-columns: minmax(8rem, 1fr) minmax(0, 2fr); gap: .65rem 1rem; margin: 0; font-size: var(--nodedc-font-size-sm); } +.b2-tracker-facts dt { color: var(--nodedc-text-muted); } +.b2-tracker-facts dd { margin: 0; overflow-wrap: anywhere; } diff --git a/apps/device-manager/src/b2/tracker.ts b/apps/device-manager/src/b2/tracker.ts new file mode 100644 index 0000000..7757391 --- /dev/null +++ b/apps/device-manager/src/b2/tracker.ts @@ -0,0 +1,21 @@ +import { b2Request, type B2Device } from './api'; +export type TrackerRef = B2Device & { hostRef: string; hostName: string }; +export type Policy = { parameters: Record; connectivity: { mode: string; apn1?: string; apn2?: string; preset1?: string; preset2?: string }; endpoint?: { host: string; port: number; slot: number } | null }; +export type Operation = { command?:Record;repeatable?:boolean;number?:number; id: string; kind: string; state: string; runtime_phase?: string; reason?: string; sequence?: number; created_at?: number; received_at?: number; dispatched_at?: number; verified_at?: number; delivered_at?: number; attempt_count?: number; roundtrip_seconds?: number; delivery_seconds?: number; stop_requested?: boolean }; +export type TrackerState = { id: string; name: string; number: number; identifier: string; revision: number; firmware: string | null; policy: Policy; + observed: { sha256: string; received_at: number; parameters: Record; servers: Array<{slot:number;host:string;port:number}>; apn1:string;apn2:string;internet_mode:string;output_modes:Record } | null; + carrier_presets: Array<{id:string;label:string;apn:string}>; + cellular: {measured_at?:number;status?:{sim_states:Record};networks?:Record}; + fields: Array<{id:string;label:string;group:string;minimum:number;maximum:number}>; + profiles: Array<{id:string;name:string;policy:Policy}>; + firmwares: Array<{sha256:string;filename:string;bytes:number;complete:boolean;added_at:number}>; + latest_operation:Operation|null; last_seen_at: number | null; modem: {active_sim:number;measured_at:number} | null; sims: Record; + capabilities: {configuration:boolean;firmware_archive:boolean;firmware_install:boolean}; +}; +export function trackerRequest(projectRef: string, device: TrackerRef, request: Record) { + return b2Request(projectRef,device.hostRef,'tracker',{contourId:device.contourId,deviceId:device.id,request}); +} +export const newIntent = () => crypto.randomUUID().replaceAll('-',''); +export const operationName = (kind: string, command?:Record) => command?.pin ? `${kind==='pulse-output'?'Импульс':command.enabled?'Включить':'Выключить'} PIN${command.pin}${kind==='pulse-output'?` · ${command.seconds} с`:''}` : ({'request-position':'Запросить координаты',restart:'Перезапустить B2','read-configuration':'Прочитать настройки','configure-all':'Применить настройки','select-sim':'Изменить режим SIM','set-output':'Переключить выход','pulse-output':'Импульс выхода'}[kind] || 'Операция B2'); +export const stateName = (state: string) => ({queued:'Ожидает связи',dispatched:'Отправляется',observed:'Настройки прочитаны',verified:'Подтверждено чтением',confirmed:'Получен ответ',delivered:'Доставлено',restarted:'Связь восстановлена',stopped:'Остановлено',rejected:'Отклонено',uncertain:'Результат не подтверждён',unconfirmed:'Ответ не получен',not_applied:'Не применено',failed:'Ошибка'}[state] || state); +export const formatTime = (value?: number | null) => value ? new Date(value*1000).toLocaleString('ru-RU') : '—'; diff --git a/docs/MISSION_UI_PARITY.md b/docs/MISSION_UI_PARITY.md new file mode 100644 index 0000000..bdc846b --- /dev/null +++ b/docs/MISSION_UI_PARITY.md @@ -0,0 +1,42 @@ +# Device Core · Mission Core visual reference + +Reference inspected in the running Mission Core on 2026-09-30: environment +settings; VPS settings; B2 identity, connection, commands, firmware and every +profile section. The actual application is authoritative for appearance; its +rover domain is not imported into Device Core. + +The shared `appearance: "mission"` profile lives in Design Guideline/ui-core. +Device Core applies it on documentElement so portals inherit it. Existing Window, +FeatureSettingsWindow, SettingsCard, ResourceRow, Select, Button and StatusBadge +remain the component source. No application-local replica of the modal is added. + +Reference measurements in dark mode: modal rgba(15,15,17,.97), radius28px, +plain avatar, selected navigation rgba(247,248,244,.14), control height46px, +settings-card padding16px, status dot6.72px. The material rim and gradient are +removed from this opt-in profile. Light mode keeps the same neutral hierarchy. +Other applications retain their previous appearance unless opting in. + +| Surface | Device Core behavior | +| --- | --- | +| B2 inventory | terminal and gear at right; no redundant registered badge | +| B2 settings | persistent left navigation, identity, connection, commands, firmware,86parameters | +| VPS settings | same window; project contours expand inline; refresh at top | +| Keys | application belongs to expanded project contour; server generates identity | +| Project switch | retained active application section; no foreign project device window | +| Product model | company/project permissions remain Device Core's | +| Overview | existing yellow video retained | + +Network settings go through the VPS product API documented in the server repo's +TRACKER_SETTINGS_API.md. The backend checks capability, linked project/contour and +server identity. Unknown/private configuration records and recovery endpoint are +preserved. Saving a portable profile is separate from applying it to a tracker. + +The web app has no connection to the operator's local USB. USB provisioning stays +in local Mission Core; new network-reachable devices support initial config read +with their installed firmware and configuration password. Firmware controls match +the reference archive/import/download scope; no network flashing is advertised. + +Validation: Device Core TypeScript/production build,286server/application tests, +15B2permission/transport tests; VPS298tests; Mission Core71compatibility tests. +Live deployment and UI acceptance are recorded in Ops MISSIONCOR-86 after release; +these local results are not a production acceptance claim. diff --git a/infra/ci/sources.lock.json b/infra/ci/sources.lock.json index f18548a..1573003 100644 --- a/infra/ci/sources.lock.json +++ b/infra/ci/sources.lock.json @@ -5,7 +5,7 @@ "dependencies": { "NODEDC_DESIGN_GUIDELINE": { "url": "https://git.dcserve.ru/SILVER/NODEDC_DESIGN_GUIDELINE.git", - "commit": "2d23a0262e869adb4c6850abdc353c71facc2ca4" + "commit": "a6e6c8f2d9c3de8d98b60c30da6a70d9538c1ef2" }, "NODEDC_LAUNCHER": { "url": "https://git.dcserve.ru/SILVER/NODEDC_LAUNCHER.git", diff --git a/services/device-control-core/src/b2/connection.mjs b/services/device-control-core/src/b2/connection.mjs index ffbbcc5..1959e15 100644 --- a/services/device-control-core/src/b2/connection.mjs +++ b/services/device-control-core/src/b2/connection.mjs @@ -149,7 +149,9 @@ export function createB2Client(input, { fetchImpl } = {}) { const value = await res.json().catch(() => null); if (!res.ok) { if (res.status === 401 || res.status === 403) { token = null; throw b2Error('b2_access_denied', 403); } + if (res.status === 409 && ['settings_revision_changed', 'settings_initial_read_required', 'settings_sim_observation_required'].includes(value?.error)) throw b2Error('b2_' + value.error, 409); if (res.status === 409) throw b2Error('b2_conflict', 409); + if (res.status === 400) throw b2Error('b2_request_invalid', 400); throw b2Error('b2_host_request_failed', 502); } if (!value || typeof value !== 'object') throw b2Error('b2_response_invalid', 502); diff --git a/services/device-control-core/src/b2/infrastructure.mjs b/services/device-control-core/src/b2/infrastructure.mjs index 906cdc6..23f7e1a 100644 --- a/services/device-control-core/src/b2/infrastructure.mjs +++ b/services/device-control-core/src/b2/infrastructure.mjs @@ -70,8 +70,43 @@ export class B2Infrastructure { })); return { items: results.flatMap((result) => result.items), hosts: results.map((result) => result.host) }; } + async tracker(actor, input) { + fields(input, ['contourId', 'deviceId', 'request']); + const projectId = ref(input.projectRef, 'project'), hostId = ref(input.hostRef, 'host'); + const contourId = opaque(input.contourId), deviceId = opaque(input.deviceId); + const request = input.request; + const permissions = { + state: 'configuration.read', journal: 'audit.read', attempts: 'audit.read', + 'firmware-download': 'configuration.read', 'firmware-upload': 'configuration.manage', + save: 'configuration.manage', 'profile-save': 'configuration.manage', + read: 'command.dispatch', apply: 'configuration.manage', command: 'command.dispatch', cancel: 'command.dispatch', + }; + if (!request || typeof request !== 'object' || !permissions[request.action]) throw b2Error('b2_request_invalid'); + const db = await this.pool.connect(); + let source; + try { + await db.query('begin'); + await findProjectWithCapability(db, actor, projectId, permissions[request.action]); + if (request.action === 'apply') await findProjectWithCapability(db, actor, projectId, 'command.dispatch'); + source = (await db.query(`select s.* from device_b2_hosts s + join device_b2_host_views v on v.source_id=s.id + join device_b2_contour_links l on l.source_id=s.id and l.project_id=v.project_id + join device_infrastructure_hosts h on h.id=v.host_id and h.project_id=v.project_id + where v.host_id=$1 and v.project_id=$2 and l.contour_id=$3 and h.lifecycle_state='active'`, + [hostId, projectId, contourId])).rows[0]; + if (!source) throw b2Error('b2_access_denied', 403); + await db.query('commit'); + } catch (error) { await db.query('rollback'); throw error; } finally { db.release(); } + const remote = await this.clientFor(source); + const identity = await remote.call('/v2/identity'); + if (identity.host_id !== source.remote_host_id) throw b2Error('b2_host_identity_mismatch'); + // VPS checks the device's actual contour as well; a forged device ID cannot + // borrow the host administrator credential from another project. + return remote.call(`/v2/contours/${contourId}/devices/${deviceId}/settings`, request); + } async execute(actor, input, requestId) { if (input.action === 'inventory') return this.inventory(actor, input); + if (input.action === 'tracker') return this.tracker(actor, input); const projectId = ref(input.projectRef, 'project'); const hostId = ref(input.hostRef, 'host'); const action = input.action; diff --git a/services/device-control-core/test/b2-infrastructure.test.mjs b/services/device-control-core/test/b2-infrastructure.test.mjs index 4f10111..d900394 100644 --- a/services/device-control-core/test/b2-infrastructure.test.mjs +++ b/services/device-control-core/test/b2-infrastructure.test.mjs @@ -234,3 +234,33 @@ test('application creation and issuance use one server-generated request identit await assert.rejects(service.execute(actor, { action: 'application-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'Other', contourId: 'f'.repeat(32) }, requestId), /b2_access_denied/); assert.equal(calls.length, 2); }); + +test('tracker settings keep project and contour authority across remote calls', async () => { + const contour = 'c'.repeat(32), device = 'd'.repeat(32), calls = []; + const repo = repository({ role: 'viewer' }); const db = await repo.pool.connect(); + let released = false; const original = db.query; + db.release = () => { released = true; }; + db.query = async (sql, values) => { + if (sql.includes('from device_b2_hosts')) { + assert.match(sql, /l.project_id=v.project_id/); + assert.match(sql, /h.lifecycle_state='active'/); + assert.deepEqual(values, [hostId, projectId, contour]); + return { rows: [source] }; + } + return original(sql, values); + }; + const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) { + assert.equal(released, true); calls.push({path,body}); + return path === '/v2/identity' ? {host_id:pkg.host_id} : {revision:1}; + } }) }); + const input = {action:'tracker',projectRef:`project:${projectId}`,hostRef:`host:${hostId}`,contourId:contour,deviceId:device,request:{action:'state'}}; + assert.deepEqual(await service.execute({...actor,hubRole:'member'},input), {revision:1}); + assert.equal(calls[1].path, `/v2/contours/${contour}/devices/${device}/settings`); + for (const action of ['save','apply','read','command','cancel','firmware-upload','profile-save']) { + await assert.rejects(service.execute({...actor,hubRole:'member'},{...input,request:{action}})); + } + assert.equal(calls.length,2); + db.query = async (sql,values) => sql.includes('from device_b2_hosts') ? {rows:[]} : original(sql,values); + await assert.rejects(service.execute(actor,input), /b2_access_denied/); + assert.equal(calls.length,2); +});