Keep B2 client fixes and move VPS implementation to its standalone repository

This commit is contained in:
DCCONSTRUCTIONS
2026-09-29 12:41:21 +03:00
parent 03d44d0fb1
commit 6dd652f71e
85 changed files with 2201 additions and 9299 deletions
+5
View File
@@ -1,5 +1,10 @@
# NODEDC MISSION CORE # NODEDC MISSION CORE
ARNavi B2 VPS server development moved to
[NODEDC_MISSION_CORE_ARNAVI-VPS](https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS).
Mission Core retains its B2 client and existing pairing; see the
[repository boundary](docs/arnavi_b2/VPS_REPOSITORY_SPLIT_20260929.md).
NODEDC MISSION CORE is the vendor-neutral control, observation, mission-planning, NODEDC MISSION CORE is the vendor-neutral control, observation, mission-planning,
recording, and integration platform for NODEDC autonomous systems. This recording, and integration platform for NODEDC autonomous systems. This
repository is the canonical early-stage monorepo: it contains the Mission Core repository is the canonical early-stage monorepo: it contains the Mission Core
@@ -35,6 +35,14 @@ export function cellularNetworkLabel(value:CellularNetwork|undefined){
const name=cellularOperator(value); const name=cellularOperator(value);
return name?`${name} · ${code}`:`Оператор не определён · код ${code}`; return name?`${name} · ${code}`:`Оператор не определён · код ${code}`;
} }
export function cellularSlotDescription(telemetry:TrackerTelemetry|undefined,slot:'1'|'2',now=Date.now()/1000){
const view=cellularSlotView(telemetry,slot,now);
if(view.absent)return 'B2 не обнаружил карту. Вставленная резервная SIM может определиться при переходе на неё.';
const operator=cellularCardOperator(telemetry,slot);
if(operator)return operator;
if(view.current&&view.network?.mcc==null)return view.internet?'Интернет подключён. B2 ещё не передал код сети оператора.':'B2 ещё не передал код сети оператора.';
return cellularNetworkLabel(view.network);
}
export function cellularSlotView(telemetry:TrackerTelemetry|undefined,slot:'1'|'2',now=Date.now()/1000){ export function cellularSlotView(telemetry:TrackerTelemetry|undefined,slot:'1'|'2',now=Date.now()/1000){
const status=telemetry?.cellular?.status; const status=telemetry?.cellular?.status;
const current=!!telemetry?.online&&cellularFresh(status,now); const current=!!telemetry?.online&&cellularFresh(status,now);
@@ -2,11 +2,11 @@ import type {EquipmentCommand,EquipmentNetworkOperation,IndependentDevice} from
export interface CommandPreset {id:string;label:string;command:EquipmentCommand;wire:string;encoding:string;queue_seconds:number;confirmation:string;firmware:string;unavailable:string} export interface CommandPreset {id:string;label:string;command:EquipmentCommand;wire:string;encoding:string;queue_seconds:number;confirmation:string;firmware:string;unavailable:string}
export interface CommandEvent {state:string;attempt?:number;stage?:string;observed_at:number;occurred_at?:number;historical:boolean} export interface CommandEvent {state:string;attempt?:number;stage?:string;observed_at:number;occurred_at?:number;historical:boolean}
export interface CommandEntry extends Omit<EquipmentNetworkOperation,'scope'> {sequence?:number;reconcile_pending?:boolean;received_at?:number;vps_created_at?:number;scope:string;description:Partial<CommandPreset>;firmware?:string;queue_deadline?:number;finished_at?:number;updated_at?:number;reason?:string;events:CommandEvent[]} export interface CommandEntry extends Omit<EquipmentNetworkOperation,'scope'> {sequence?:number;delivered_at?:number;delivery_seconds?:number;reconcile_pending?:boolean;received_at?:number;vps_created_at?:number;scope:string;description:Partial<CommandPreset>;firmware?:string;queue_deadline?:number;finished_at?:number;updated_at?:number;reason?:string;events:CommandEvent[]}
export interface CommandRuntime {items:CommandEntry[];tracked_items:CommandEntry[];next_before:number|null;counts:Record<string,number>;catalog:CommandPreset[];device:IndependentDevice;capacity:number;durable_kinds?:string[]} export interface CommandRuntime {items:CommandEntry[];tracked_items:CommandEntry[];next_before:number|null;counts:Record<string,number>;catalog:CommandPreset[];device:IndependentDevice;capacity:number|null;durable_kinds?:string[]}
export const commandPending=(state:string)=>['waiting','submitting','queued','dispatched'].includes(state); export const commandPending=(state:string)=>['waiting','submitting','queued','dispatched'].includes(state);
export const commandTracked=(entry:CommandEntry)=>commandPending(entry.state)||entry.reconcile_pending===true; export const commandTracked=(entry:CommandEntry)=>commandPending(entry.state)||entry.reconcile_pending===true;
export const commandStatus=(state:string)=>({accepted:'Принято B2',stopped:'Повторы остановлены',attempt_started:'Начата попытка',waiting:'В очереди Core',submitting:'Передача на VPS',queued:'В очереди VPS',dispatched:'Отправлено B2',device_accepted:'Принято B2, выполняется',device_confirmed:'Подтверждено B2',device_rejected:'Отклонено B2',reconnected:'Связь после перезапуска подтверждена',expired:'Срок истёк',unconfirmed:'Нет подтверждения',uncertain:'Результат неизвестен',cancelled:'Отменено до отправки',rejected:'Отклонено',observed:'Прочитано',verified:'Настройки проверены',sim_selected:'SIM подключена',not_applied:'Не применено'} as Record<string,string>)[state]??'Неизвестный статус'; export const commandStatus=(state:string)=>({delivered:'Доставлено',accepted:'Принято B2',stopped:'Повторы остановлены',attempt_started:'Начата попытка',waiting:'В очереди Core',submitting:'Передача на VPS',queued:'В очереди VPS',dispatched:'Отправлено B2',device_accepted:'Принято B2, выполняется',device_confirmed:'Подтверждено B2',device_rejected:'Отклонено B2',reconnected:'Связь после перезапуска подтверждена',expired:'Срок истёк',unconfirmed:'Результат не подтверждён',uncertain:'Результат неизвестен',cancelled:'Отменено до отправки',rejected:'Отклонено',observed:'Прочитано',verified:'Настройки проверены',sim_selected:'SIM подключена',not_applied:'Не применено'} as Record<string,string>)[state]??'Неизвестный статус';
export const commandTone=(state:string):'success'|'warning'|'neutral'=>['accepted','device_confirmed','reconnected','observed','verified','sim_selected'].includes(state)?'success':['unconfirmed','uncertain','device_rejected','rejected','not_applied','expired'].includes(state)?'warning':'neutral'; export const commandTone=(state:string):'success'|'warning'|'neutral'=>['accepted','device_confirmed','reconnected','observed','verified','sim_selected'].includes(state)?'success':['unconfirmed','uncertain','device_rejected','rejected','not_applied','expired'].includes(state)?'warning':'neutral';
export const commandDate=(value?:number)=>value===undefined?'—':new Date(value*1000).toLocaleString('ru-RU'); export const commandDate=(value?:number)=>value===undefined?'—':new Date(value*1000).toLocaleString('ru-RU');
export const commandDuration=(value?:number)=>value===undefined?'—':`${value.toFixed(3)} с`; export const commandDuration=(value?:number)=>value===undefined?'—':`${value.toFixed(3)} с`;
@@ -15,10 +15,14 @@ export function mergeCommands(current:CommandEntry[],incoming:CommandEntry[]):Co
return [...values.values()].sort((a,b)=>(b.sequence??0)-(a.sequence??0)); return [...values.values()].sort((a,b)=>(b.sequence??0)-(a.sequence??0));
} }
export function commandReason(value:CommandEntry):string{ export function commandReason(value:CommandEntry):string{
return ({queue_deadline:'Время ожидания в Core истекло; передача на VPS не начиналась.',device_changed:'После постановки в очередь изменилось устройство или его привязка.',host_changed:'Изменилась привязка VPS.',operator_cancelled:'Оператор отменил команду до передачи на VPS.',historical_result_missing:'Окончательный результат этой старой операции не сохранился.'} as Record<string,string>)[value.reason??'']??''; if(value.reason==='pulse_result_unknown')return 'Импульс был отправлен, но доставка не подтверждена. Автоматический повтор может вызвать второй импульс. Проверьте результат перед повторной отправкой.';
if(value.state==='expired'&&value.vps_created_at&&!value.dispatched_at)return 'VPS не дождался готового соединения с B2 до истечения срока. Команда трекеру не отправлена.';
return ({settings_changed:'Настройки изменились после запроса повтора. Команда не отправлена.',queue_deadline:'Время ожидания в Core истекло; передача на VPS не начиналась.',device_changed:'После постановки в очередь изменилось устройство или его привязка.',host_changed:'Изменилась привязка VPS.',operator_cancelled:'Оператор отменил команду до передачи на VPS.',historical_result_missing:'Окончательный результат этой старой операции не сохранился.'} as Record<string,string>)[value.reason??'']??'';
} }
export function commandReceipt(value:CommandEntry):string{ export function commandReceipt(value:CommandEntry):string{
if(value.delivered_at!==undefined)return 'Доставка команды подтверждена. Это не подтверждение переключения контактов выхода.';
if(value.device_code===undefined&&value.description?.encoding?.includes('FC'))return 'Текстовый ответ B2 не содержит идентификатора команды. Исполнение по такому ответу подтвердить нельзя.';
if(value.device_code===undefined)return 'Ответ трекера не получен'; if(value.device_code===undefined)return 'Ответ трекера не получен';
return ({0:value.kind==='restart'?'B2 принял команду перезапуска':'B2 подтвердил команду без ошибки',1:'B2 не распознал команду',2:'Недостаточно аргументов',3:'Слишком много аргументов',4:'Некорректное значение аргумента',5:'B2 сообщил об ошибке выполнения',6:'B2 принял команду; требуется время на выполнение',7:'Очередь команд B2 заполнена',8:'Подключённое устройство недоступно',9:'Подключённое устройство не ответило'} as Record<number,string>)[value.device_code]??'Неизвестный ответ B2'; return ({0:value.kind==='restart'?'B2 принял команду перезапуска':'B2 подтвердил команду без ошибки',1:'B2 не распознал команду',2:'Недостаточно аргументов',3:'Слишком много аргументов',4:'Некорректное значение аргумента',5:'B2 сообщил об ошибке выполнения',6:'B2 принял команду; требуется время на выполнение',7:'Очередь команд B2 заполнена',8:'Подключённое устройство недоступно',9:'Подключённое устройство не ответило'} as Record<number,string>)[value.device_code]??'Неизвестный ответ B2';
} }
@@ -2,24 +2,24 @@ import {useCallback,useEffect,useRef,useState} from 'react';
import {equipmentRequest} from './equipment'; import {equipmentRequest} from './equipment';
import {commandTracked,mergeCommands,type CommandEntry,type CommandRuntime} from './commandRuntime'; import {commandTracked,mergeCommands,type CommandEntry,type CommandRuntime} from './commandRuntime';
type Intent={request_id:string;preset_id:string}; type Intent={request_id:string;preset_id?:string;repeat_of?:string};
export function useCommandRuntime(identifier:string){ export function useCommandRuntime(identifier:string){
const path=`/instances/${identifier}/commands`,key=`missioncore.command-intent.${identifier}`; const path=`/instances/${identifier}/commands`,key=`missioncore.command-intent.${identifier}`;
const [data,setData]=useState<CommandRuntime|null>(null),[items,setItems]=useState<CommandEntry[]>([]),[before,setBefore]=useState<number|null>(null),[error,setError]=useState(''),[activity,setActivity]=useState(''); const [data,setData]=useState<CommandRuntime|null>(null),[items,setItems]=useState<CommandEntry[]>([]),[before,setBefore]=useState<number|null>(null),[error,setError]=useState(''),[activity,setActivity]=useState('');
const alive=useRef(true),sending=useRef(false),first=useRef(true); const alive=useRef(true),sending=useRef(false),first=useRef(true);
const tracked=useRef<string[]>([]); const tracked=useRef<string[]>([]);
const [intent,setIntent]=useState<Intent|null>(()=>{try{const v=JSON.parse(localStorage.getItem(key)??'null');return v&&/^[a-f0-9]{32}$/.test(v.request_id)&&typeof v.preset_id==='string'?v:null;}catch{return null;}}); const [intent,setIntent]=useState<Intent|null>(()=>{try{const v=JSON.parse(localStorage.getItem(key)??'null');return v&&/^[a-f0-9]{32}$/.test(v.request_id)&&(typeof v.preset_id==='string'||typeof v.repeat_of==='string')?v:null;}catch{return null;}});
const accept=useCallback((value:CommandRuntime)=>{if(!alive.current)return;tracked.current=value.tracked_items.filter(commandTracked).map(item=>item.id).slice(0,32);setData(value);setItems(old=>mergeCommands(old,[...value.items,...value.tracked_items]));if(first.current){first.current=false;setBefore(value.next_before);}setError('');},[]); const accept=useCallback((value:CommandRuntime)=>{if(!alive.current)return;tracked.current=value.tracked_items.filter(commandTracked).map(item=>item.id).slice(0,32);setData(value);setItems(old=>mergeCommands(old,[...value.items,...value.tracked_items]));if(first.current){first.current=false;setBefore(value.next_before);}setError('');},[]);
const refresh=useCallback(async()=>{const query=new URLSearchParams();for(const id of tracked.current)query.append('tracked',id);accept(await equipmentRequest<CommandRuntime>(`${path}?${query}`));},[path,accept]); const refresh=useCallback(async()=>{const query=new URLSearchParams();for(const id of tracked.current)query.append('tracked',id);accept(await equipmentRequest<CommandRuntime>(`${path}?${query}`));},[path,accept]);
useEffect(()=>{alive.current=true;let timer:ReturnType<typeof setTimeout>;async function poll(){try{await refresh();}catch(e){if(alive.current)setError(e instanceof Error?e.message:'Журнал временно недоступен.');}finally{if(alive.current)timer=setTimeout(()=>void poll(),2000);}}void poll();return()=>{alive.current=false;clearTimeout(timer);};},[refresh]); useEffect(()=>{alive.current=true;let timer:ReturnType<typeof setTimeout>;async function poll(){try{await refresh();}catch(e){if(alive.current)setError(e instanceof Error?e.message:'Журнал временно недоступен.');}finally{if(alive.current)timer=setTimeout(()=>void poll(),2000);}}void poll();return()=>{alive.current=false;clearTimeout(timer);};},[refresh]);
useEffect(()=>{if(intent&&items.some(item=>item.id===intent.request_id)){localStorage.removeItem(key);setIntent(null);}},[items,intent,key]); useEffect(()=>{if(intent&&items.some(item=>item.id===intent.request_id)){localStorage.removeItem(key);setIntent(null);}},[items,intent,key]);
async function send(preset:string){ async function send(preset:string,repeatOf?:string){
if(sending.current)return;sending.current=true;setActivity('send');setError(''); if(sending.current)return;sending.current=true;setActivity(repeatOf?`repeat:${repeatOf}`:'send');setError('');
const request=intent??{request_id:crypto.randomUUID().replaceAll('-',''),preset_id:preset}; const request=intent??{request_id:crypto.randomUUID().replaceAll('-',''),...(repeatOf?{repeat_of:repeatOf}:{preset_id:preset})};
try{ try{
// Persist the request ID before HTTP. A lost reply/reopened window reuses it. // Persist the request ID before HTTP. A lost reply/reopened window reuses it.
localStorage.setItem(key,JSON.stringify(request));setIntent(request); localStorage.setItem(key,JSON.stringify(request));setIntent(request);
const response=await fetch(`/api/v1/fleet/equipment${path}`,{method:'POST',credentials:'same-origin',cache:'no-store',headers:{'Content-Type':'application/json'},body:JSON.stringify(request),signal:AbortSignal.timeout(15000)}); const response=await fetch(`/api/v1/fleet/equipment${path}${request.repeat_of?`/${request.repeat_of}/repeat`:''}`,{method:'POST',credentials:'same-origin',cache:'no-store',headers:{'Content-Type':'application/json'},body:JSON.stringify(request.repeat_of?{request_id:request.request_id}:request),signal:AbortSignal.timeout(15000)});
if(!response.ok){const value=await response.json().catch(()=>({}));if(response.status>=400&&response.status<500){localStorage.removeItem(key);if(alive.current)setIntent(null);}throw new Error(value.detail??'Ответ на отправку не получен. Уточните её с тем же ID.');} if(!response.ok){const value=await response.json().catch(()=>({}));if(response.status>=400&&response.status<500){localStorage.removeItem(key);if(alive.current)setIntent(null);}throw new Error(value.detail??'Ответ на отправку не получен. Уточните её с тем же ID.');}
localStorage.removeItem(key);if(alive.current)setIntent(null);await refresh(); localStorage.removeItem(key);if(alive.current)setIntent(null);await refresh();
}catch(e){if(alive.current)setError(e instanceof Error?e.message:'Ответ не получен. Уточните отправку с тем же ID.');} }catch(e){if(alive.current)setError(e instanceof Error?e.message:'Ответ не получен. Уточните отправку с тем же ID.');}
@@ -27,5 +27,5 @@ export function useCommandRuntime(identifier:string){
} }
async function cancel(id:string){setActivity(id);try{await equipmentRequest(`${path}/${id}/cancel`,'POST');await refresh();}catch(e){setError(e instanceof Error?e.message:'Отмена не подтверждена.');}finally{if(alive.current)setActivity('');}} async function cancel(id:string){setActivity(id);try{await equipmentRequest(`${path}/${id}/cancel`,'POST');await refresh();}catch(e){setError(e instanceof Error?e.message:'Отмена не подтверждена.');}finally{if(alive.current)setActivity('');}}
async function more(){if(before===null)return;setActivity('more');try{const value=await equipmentRequest<CommandRuntime>(`${path}?before=${before}`);if(alive.current){setItems(old=>mergeCommands(old,value.items));setBefore(value.next_before);}}catch(e){setError(e instanceof Error?e.message:'Не удалось прочитать историю.');}finally{if(alive.current)setActivity('');}} async function more(){if(before===null)return;setActivity('more');try{const value=await equipmentRequest<CommandRuntime>(`${path}?before=${before}`);if(alive.current){setItems(old=>mergeCommands(old,value.items));setBefore(value.next_before);}}catch(e){setError(e instanceof Error?e.message:'Не удалось прочитать историю.');}finally{if(alive.current)setActivity('');}}
return {data,items,before,error,setError,working:!!activity,activity,intent,send,cancel,more,refresh}; return {data,items,before,error,setError,working:!!activity,activity,intent,send,repeat:(id:string)=>send('',id),cancel,more,refresh};
} }
@@ -1,9 +1,9 @@
import {Button,ResourceList,ResourceRow,SettingsCard,StatusBadge} from '@nodedc/ui-react'; import {Button,Icon,IconButton,ResourceList,ResourceRow,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {commandPending,commandDate,commandDuration,commandReason,commandReceipt,commandEntryStatus,commandStatus,commandTone,type CommandEntry} from '../../../core/fleet/commandRuntime'; import {commandPending,commandDate,commandDuration,commandReason,commandReceipt,commandEntryStatus,commandStatus,commandTone,type CommandEntry} from '../../../core/fleet/commandRuntime';
import {useCommandAttempts} from '../../../core/fleet/useCommandAttempts'; import {useCommandAttempts} from '../../../core/fleet/useCommandAttempts';
export function CommandHistory({identifier,items,selected,onSelect,onCancel,working,cancelling}:{identifier:string;items:CommandEntry[];selected:string;onSelect:(id:string)=>void;onCancel:(id:string)=>void;working:boolean;cancelling:string}){ export function CommandHistory({identifier,items,selected,onSelect,onCancel,onRepeat,working,cancelling}:{identifier:string;items:CommandEntry[];selected:string;onSelect:(id:string)=>void;onCancel:(id:string)=>void;onRepeat:(id:string)=>void;working:boolean;cancelling:string}){
return <ResourceList aria-label="Журнал команд B2">{items.map(item=><li key={item.id}><ResourceRow title={item.description.label??'Операция B2'} description={commandDate(item.created_at)} metadata={`${item.durable?`Попыток: ${item.attempt_count??0} · `:''}Отправлено: ${commandDate(item.dispatched_at)} · Ответ: ${commandDuration(item.roundtrip_seconds)}`} status={<StatusBadge tone={commandTone(item.state)}>{commandEntryStatus(item)}</StatusBadge>} actions={<><Button aria-pressed={item.id===selected} onClick={()=>onSelect(item.id===selected?'':item.id)}>Подробнее</Button>{(item.state==='waiting'||item.durable&&commandPending(item.state))&&<Button loading={cancelling===item.id} disabled={working||item.stop_requested} onClick={()=>onCancel(item.id)}>{item.state==='waiting'?'Отменить':item.stop_requested?'Остановка повторов':'Остановить повторы'}</Button>}</>}/>{item.id===selected&&<CommandDetails key={item.id} identifier={identifier} current={item}/>}</li>)}</ResourceList>; return <ResourceList aria-label="Журнал команд B2">{items.map(item=><li key={item.id}><ResourceRow title={item.description.label??'Операция B2'} description={commandDate(item.created_at)} metadata={`${item.durable?`Попыток: ${item.attempt_count??0} · `:''}Отправлено: ${commandDate(item.dispatched_at)} · Ответ: ${commandDuration(item.roundtrip_seconds)}`} status={<StatusBadge tone={commandTone(item.state)}>{commandEntryStatus(item)}</StatusBadge>} actions={<><Button aria-pressed={item.id===selected} onClick={()=>onSelect(item.id===selected?'':item.id)}>Подробнее</Button><IconButton label={`Повторить: ${item.description.label??'Операция B2'}`} title={commandPending(item.state)?'Дождитесь завершения операции':'Отправить ещё раз'} loading={cancelling===`repeat:${item.id}`} disabled={working||commandPending(item.state)} onClick={()=>onRepeat(item.id)}><Icon name="refresh"/></IconButton>{(item.state==='waiting'||item.durable&&commandPending(item.state))&&<Button loading={cancelling===item.id} disabled={working||item.stop_requested} onClick={()=>onCancel(item.id)}>{item.state==='waiting'?'Отменить':item.stop_requested?'Остановка повторов':'Остановить повторы'}</Button>}</>}/>{item.id===selected&&<CommandDetails key={item.id} identifier={identifier} current={item}/>}</li>)}</ResourceList>;
} }
function CommandDetails({identifier,current}:{identifier:string;current:CommandEntry}){ function CommandDetails({identifier,current}:{identifier:string;current:CommandEntry}){
@@ -14,6 +14,7 @@ function CommandDetails({identifier,current}:{identifier:string;current:CommandE
<div><dt>Принято Core</dt><dd>{commandDate(current.created_at)}</dd></div> <div><dt>Принято Core</dt><dd>{commandDate(current.created_at)}</dd></div>
{current.durable?<><div><dt>Попыток</dt><dd>{current.attempt_count??0}</dd></div>{current.attempt_expires_at!==undefined&&<div><dt>Срок текущей попытки</dt><dd>{commandDate(current.attempt_expires_at)}</dd></div>}</>:<><div><dt>Срок отправки из Core</dt><dd>{commandDate(current.queue_deadline)}</dd></div><div><dt>Срок ожидания ответа</dt><dd>{commandDate(current.expires_at)}</dd></div></>} {current.durable?<><div><dt>Попыток</dt><dd>{current.attempt_count??0}</dd></div>{current.attempt_expires_at!==undefined&&<div><dt>Срок текущей попытки</dt><dd>{commandDate(current.attempt_expires_at)}</dd></div>}</>:<><div><dt>Срок отправки из Core</dt><dd>{commandDate(current.queue_deadline)}</dd></div><div><dt>Срок ожидания ответа</dt><dd>{commandDate(current.expires_at)}</dd></div></>}
<div><dt>Отправлено B2</dt><dd>{commandDate(current.dispatched_at)}</dd></div><div><dt>Ответ B2</dt><dd>{commandDate(current.received_at)}</dd></div> <div><dt>Отправлено B2</dt><dd>{commandDate(current.dispatched_at)}</dd></div><div><dt>Ответ B2</dt><dd>{commandDate(current.received_at)}</dd></div>
{current.delivered_at!==undefined&&<div><dt>Доставка подтверждена</dt><dd>{commandDate(current.delivered_at)} · {commandDuration(current.delivery_seconds)}</dd></div>}
{current.device_accepted_at!==undefined&&<div><dt>Принято B2</dt><dd>{commandDate(current.device_accepted_at)}</dd></div>} {current.device_accepted_at!==undefined&&<div><dt>Принято B2</dt><dd>{commandDate(current.device_accepted_at)}</dd></div>}
{current.scope==='command'&&<div><dt>Результат B2</dt><dd>{commandReceipt(current)}</dd></div>} {current.scope==='command'&&<div><dt>Результат B2</dt><dd>{commandReceipt(current)}</dd></div>}
<div><dt>До ответа</dt><dd>{commandDuration(current.roundtrip_seconds)}</dd></div> <div><dt>До ответа</dt><dd>{commandDuration(current.roundtrip_seconds)}</dd></div>
@@ -1,5 +1,5 @@
import {SettingsCard,StatusBadge} from '@nodedc/ui-react'; import {SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {cellularCardOperator,cellularFresh,cellularNetworkLabel,cellularSimLabel,cellularSlotView} from '../../../core/fleet/cellular'; import {cellularFresh,cellularSlotDescription,cellularSimLabel,cellularSlotView} from '../../../core/fleet/cellular';
import type {EquipmentObservation} from '../../../core/fleet/equipment'; import type {EquipmentObservation} from '../../../core/fleet/equipment';
import type {TrackerTelemetry} from '../../../core/fleet/vps'; import type {TrackerTelemetry} from '../../../core/fleet/vps';
@@ -11,7 +11,7 @@ export function EquipmentCellular({telemetry,observed}:{telemetry?:TrackerTeleme
const view=cellularSlotView(telemetry,slot),network=view.network; const view=cellularSlotView(telemetry,slot),network=view.network;
const fresh=!!telemetry?.online&&cellularFresh(network); const fresh=!!telemetry?.online&&cellularFresh(network);
const apn=slot==='1'?observed.configuration.apn1:observed.configuration.apn2; const apn=slot==='1'?observed.configuration.apn1:observed.configuration.apn2;
return <SettingsCard key={slot} title={`SIM ${slot}`} description={view.absent?'B2 не обнаружил карту. Вставленная резервная SIM может определиться при переходе на неё.':cellularCardOperator(telemetry,slot)??cellularNetworkLabel(network)} actions={<StatusBadge tone={view.internet?'success':'neutral'}>{view.role}</StatusBadge>}> return <SettingsCard key={slot} title={`SIM ${slot}`} description={cellularSlotDescription(telemetry,slot)} actions={<StatusBadge tone={view.internet?'success':'neutral'}>{view.role}</StatusBadge>}>
<dl className="fleet-facts"> <dl className="fleet-facts">
<div><dt>Регистрация</dt><dd>{cellularSimLabel(status?.sim_states[slot])}</dd></div> <div><dt>Регистрация</dt><dd>{cellularSimLabel(status?.sim_states[slot])}</dd></div>
{!view.absent&&network&&<> {!view.absent&&network&&<>
@@ -19,13 +19,14 @@ export function EquipmentCommandWindow({device,telemetry,onClose}:{device:Indepe
{data&&<> {data&&<>
<SettingsCard title="Отправить команду" description={`B2 · ПО ${data.device.observed.firmware}`}> <SettingsCard title="Отправить команду" description={`B2 · ПО ${data.device.observed.firmware}`}>
<Select label="Команда" value={runtime.intent?.preset_id??preset} options={data.catalog.map(value=>({value:value.id,label:value.label,disabled:!!value.unavailable}))} disabled={runtime.working||!!runtime.intent} onChange={setPreset}/> <Select label="Команда" value={runtime.intent?.preset_id??preset} options={data.catalog.map(value=>({value:value.id,label:value.label,disabled:!!value.unavailable}))} disabled={runtime.working||!!runtime.intent} onChange={setPreset}/>
{chosen&&<><dl className="fleet-facts"><div><dt>{chosen.encoding} · тело</dt><dd><code>{chosen.wire}</code></dd></div></dl><p>{chosen.confirmation} {data.durable_kinds?.includes(chosen.command.kind)?'Задание сохраняется до результата или остановки повторов. При потере связи VPS уточняет результат и повторяет неподтверждённые попытки.':`Ожидание отправки: до ${chosen.queue_seconds} с. Отправленная команда автоматически не повторяется.`}{chosen.encoding.includes('FC')&&' Пароль скрыт.'}</p>{chosen.unavailable&&<p>{chosen.unavailable}</p>}</>} {runtime.intent?.repeat_of&&<p>Повтор: {runtime.items.find(item=>item.id===runtime.intent?.repeat_of)?.description.label??'операция из журнала'}. Уточните отправку, чтобы получить результат принятия команды.</p>}
<WindowFooterActions><Button loading={runtime.activity==='send'} disabled={runtime.working||(!runtime.intent&&(!chosen||!!chosen.unavailable||pending>=data.capacity))} onClick={()=>void runtime.send(preset)}>{runtime.intent?'Уточнить отправку':'Отправить'}</Button></WindowFooterActions> {chosen&&!runtime.intent?.repeat_of&&<><dl className="fleet-facts"><div><dt>{chosen.encoding} · тело</dt><dd><code>{chosen.wire}</code></dd></div></dl><p>{chosen.confirmation} {data.durable_kinds?.includes(chosen.command.kind)?(chosen.command.kind==='pulse-output'?'Задание ждёт отправки до отмены. После отправки импульс автоматически не повторяется при неизвестном результате.':chosen.command.kind==='set-output'?'Задание ждёт связи и отправки до отмены. При неподтверждённой доставке повторяется установка того же состояния.':'Задание сохраняется до результата или остановки повторов. При потере связи VPS уточняет результат и повторяет неподтверждённые попытки.'):`Ожидание отправки: до ${chosen.queue_seconds} с. Отправленная команда автоматически не повторяется.`}{chosen.encoding.includes('FC')&&' Пароль скрыт.'}</p>{chosen.unavailable&&<p>{chosen.unavailable}</p>}</>}
<WindowFooterActions><Button loading={runtime.activity==='send'} disabled={runtime.working||(!runtime.intent&&(!chosen||!!chosen.unavailable||(data.capacity!==null&&pending>=data.capacity)))} onClick={()=>void runtime.send(preset)}>{runtime.intent?'Уточнить отправку':'Отправить'}</Button></WindowFooterActions>
</SettingsCard> </SettingsCard>
<SettingsCard title="Журнал операций" description={`Незавершённых: ${pending} · Вместимость очереди: ${data.capacity}`}> <SettingsCard title="Журнал операций" description={`Незавершённых: ${pending}${data.capacity===null?' · Задания сохранены':` · Вместимость очереди: ${data.capacity}`}`}>
<Select label="Показать операции" value={filter} onChange={setFilter} options={[{value:'all',label:'Все операции'},{value:'active',label:'В очереди и выполняются'},{value:'finished',label:'Завершённые'}]}/> <Select label="Показать операции" value={filter} onChange={setFilter} options={[{value:'all',label:'Все операции'},{value:'active',label:'В очереди и выполняются'},{value:'finished',label:'Завершённые'}]}/>
{!items.length&&<p>{runtime.items.length?'В загруженной части истории таких операций нет.':'Команд пока нет.'}</p>} {!items.length&&<p>{runtime.items.length?'В загруженной части истории таких операций нет.':'Команд пока нет.'}</p>}
<CommandHistory identifier={device.id} items={items} selected={selected} onSelect={setSelected} onCancel={id=>void runtime.cancel(id)} working={runtime.working} cancelling={runtime.activity}/> <CommandHistory identifier={device.id} items={items} selected={selected} onSelect={setSelected} onCancel={id=>void runtime.cancel(id)} onRepeat={id=>void runtime.repeat(id)} working={runtime.working||!!runtime.intent} cancelling={runtime.activity}/>
{runtime.before!==null&&<WindowFooterActions><Button loading={runtime.activity==='more'} disabled={runtime.working} onClick={()=>void runtime.more()}>Загрузить предыдущие</Button></WindowFooterActions>} {runtime.before!==null&&<WindowFooterActions><Button loading={runtime.activity==='more'} disabled={runtime.working} onClick={()=>void runtime.more()}>Загрузить предыдущие</Button></WindowFooterActions>}
</SettingsCard> </SettingsCard>
</>} </>}
@@ -28,7 +28,7 @@ export function EquipmentFirmware({device}:{device:IndependentDevice}){
<input ref={picker} type="file" accept=".dfw" hidden aria-label="Файл прошивки .dfw" onChange={e=>{const file=e.target.files?.[0];e.target.value='';if(file)void add(file);}}/> <input ref={picker} type="file" accept=".dfw" hidden aria-label="Файл прошивки .dfw" onChange={e=>{const file=e.target.files?.[0];e.target.value='';if(file)void add(file);}}/>
<Button icon={<Icon name="upload"/>} loading={uploading} disabled={uploading||downloading} onClick={()=>picker.current?.click()}>Добавить файл .dfw</Button> <Button icon={<Icon name="upload"/>} loading={uploading} disabled={uploading||downloading} onClick={()=>picker.current?.click()}>Добавить файл .dfw</Button>
<LoadingRegion loading={loading} label="Читаем архив прошивок"> <LoadingRegion loading={loading} label="Читаем архив прошивок">
{loadError?<><p>{loadError}</p><Button onClick={()=>setReload(value=>value+1)}>Повторить загрузку</Button></>:catalog?.items.length?<> {loadError?<><p>{loadError}</p><Button onClick={()=>setReload(value=>value+1)}>Повторить загрузку</Button></>:catalog?.items.length?<div className="fleet-form">
<Select label="Файл прошивки" value={selected} onChange={setSelected} disabled={uploading||downloading} options={catalog.items.map(image=>({value:image.id,label:image.version?`${image.version} · ${image.filename}`:image.filename}))}/> <Select label="Файл прошивки" value={selected} onChange={setSelected} disabled={uploading||downloading} options={catalog.items.map(image=>({value:image.id,label:image.version?`${image.version} · ${image.filename}`:image.filename}))}/>
{item&&<> {item&&<>
<StatusBadge tone="neutral">{item.source==='manufacturer'?'Файл производителя':'Файл пользователя · совместимость не проверена'}</StatusBadge> <StatusBadge tone="neutral">{item.source==='manufacturer'?'Файл производителя':'Файл пользователя · совместимость не проверена'}</StatusBadge>
@@ -36,7 +36,7 @@ export function EquipmentFirmware({device}:{device:IndependentDevice}){
<Button icon={<Icon name="download"/>} loading={downloading} disabled={uploading||downloading} onClick={()=>void download()}>Скачать файл</Button> <Button icon={<Icon name="download"/>} loading={downloading} disabled={uploading||downloading} onClick={()=>void download()}>Скачать файл</Button>
</>} </>}
{recordedVersion&&!catalog.items.some(image=>image.source==='manufacturer'&&image.version===recordedVersion)&&<p>Образ считанной версии {recordedVersion} в архиве не найден. Сохранённые настройки не являются копией прошивки.</p>} {recordedVersion&&!catalog.items.some(image=>image.source==='manufacturer'&&image.version===recordedVersion)&&<p>Образ считанной версии {recordedVersion} в архиве не найден. Сохранённые настройки не являются копией прошивки.</p>}
</>:<p>Файлов прошивок пока нет. Добавьте файл .dfw с компьютера.</p>} </div>:<p>Файлов прошивок пока нет. Добавьте файл .dfw с компьютера.</p>}
</LoadingRegion> </LoadingRegion>
</SettingsCard> </SettingsCard>
<ToastStack items={error?[{id:'firmware-error',title:error,tone:'error',durationMs:null}]:notice?[{id:'firmware-saved',title:notice,tone:'success'}]:[]} onDismiss={()=>{setError('');setNotice('');}}/> <ToastStack items={error?[{id:'firmware-error',title:error,tone:'error',durationMs:null}]:notice?[{id:'firmware-saved',title:notice,tone:'success'}]:[]} onDismiss={()=>{setError('');setNotice('');}}/>
@@ -15,8 +15,8 @@ export function EquipmentInternet({telemetry,observed,presets,value,onChange,dis
const targeted=String(connection.sim_slot??1)===slot; const targeted=String(connection.sim_slot??1)===slot;
const apn=connection.strategy==='sim'&&targeted?connection.apn??current:connection.strategy==='operator'&&targeted?presets.find(p=>p.id===connection.preset_id)?.apn??current:connection.strategy==='manual'?(slot==='1'?connection.apn1:connection.apn2):current; const apn=connection.strategy==='sim'&&targeted?connection.apn??current:connection.strategy==='operator'&&targeted?presets.find(p=>p.id===connection.preset_id)?.apn??current:connection.strategy==='manual'?(slot==='1'?connection.apn1:connection.apn2):current;
return <SettingsCard title="Интернет"><div className="fleet-form"> return <SettingsCard title="Интернет"><div className="fleet-form">
<Select label="SIM для интернета" value={slot} options={[{value:'',label:'Выберите режим SIM',disabled:true},{value:'native',label:'Обе SIM — без заданного APN'},{value:'both',label:'Обе SIM — сохранить APN'},...options.map(option=>({...option,label:`Только ${option.label}`}))]} disabled={disabled} onChange={next=>onChange(['both','native'].includes(next)?allowBothInternetSims(value,next==='native'):selectInternetSim(value,Number(next)))}/> <Select label="SIM для интернета" value={slot} options={[{value:'',label:'Выберите режим SIM',disabled:true},{value:'native',label:'Автоматический режим — без заданного APN'},{value:'both',label:'Автоматический режим — с сохранением APN'},...options.map(option=>({...option,label:`Только ${option.label}`}))]} disabled={disabled} onChange={next=>onChange(['both','native'].includes(next)?allowBothInternetSims(value,next==='native'):selectInternetSim(value,Number(next)))}/>
<p>{slot==='native'?'Оба слота разрешены. APN, логин и пароль обеих SIM будут очищены; B2 попробует подключиться без них. Для тарифов со специальным APN сохраните текущие параметры. После применения B2 перезапустится, результат проверим по новой связи.':slot==='both'?'B2 сможет использовать любую из установленных SIM. APN обеих карт сохранятся. Одновременно работает одна SIM; срок автоматического переключения не гарантирован. После сохранения B2 перезапустится.':'Выберите одну SIM для принудительного подключения или разрешите обе. При выборе одной интернет на другой запрещается. Если выбранная SIM не подключится, для восстановления может потребоваться USB.'}</p> <p>{slot==='native'?'Оба слота разрешены: B2 сам выбирает SIM для интернета. APN, логин и пароль обеих SIM будут очищены; подключение возможно, если оператор разрешает доступ без них. После сохранения B2 перезапустится.':slot==='both'?'Оба слота разрешены: B2 сам выбирает SIM для интернета. Текущие APN, логин и пароль каждой SIM сохранятся. Одновременно интернет работает через одну карту. После сохранения B2 перезапустится.':'Выберите одну SIM для принудительного подключения или автоматический режим. При выборе одной интернет на другой запрещается. Если выбранная SIM не подключится, для восстановления может потребоваться USB.'}</p>
{!!options.length&&(!telemetry?.online||!cellularFresh(telemetry.cellular?.status))&&<p>Показаны последние обнаруженные SIM. Ожидаем обновления связи с B2.</p>} {!!options.length&&(!telemetry?.online||!cellularFresh(telemetry.cellular?.status))&&<p>Показаны последние обнаруженные SIM. Ожидаем обновления связи с B2.</p>}
{slot&&!both?<> {slot&&!both?<>
<Switch label="Подбирать интернет для этой карты" checked={automatic} disabled={disabled} onChange={checked=>onChange({...value,connectivity:{strategy:'sim',sim_slot:Number(slot),activate:true,automatic:checked,apn:checked?null:apn,apn1:'',apn2:'',preset_id:null}})}/> <Switch label="Подбирать интернет для этой карты" checked={automatic} disabled={disabled} onChange={checked=>onChange({...value,connectivity:{strategy:'sim',sim_slot:Number(slot),activate:true,automatic:checked,apn:checked?null:apn,apn1:'',apn2:'',preset_id:null}})}/>
@@ -23,7 +23,7 @@ export function EquipmentSettings({device,model,hosts,telemetry,vehicles,profile
useEffect(()=>{if(!networkPending)return;let active=true;let timer:ReturnType<typeof setTimeout>;async function poll(){try{const value=await equipmentRequest<{items:IndependentDevice[]}>('/instances');const current=value.items.find(d=>d.id===device.id);if(active&&current)onObserved(current);}catch{/* Keep the pending operation visible; the VPS owns its bounded expiry. */}finally{if(active)timer=setTimeout(()=>void poll(),3000);}}timer=setTimeout(()=>void poll(),3000);return()=>{active=false;clearTimeout(timer);};},[device.id,networkPending,onObserved]); useEffect(()=>{if(!networkPending)return;let active=true;let timer:ReturnType<typeof setTimeout>;async function poll(){try{const value=await equipmentRequest<{items:IndependentDevice[]}>('/instances');const current=value.items.find(d=>d.id===device.id);if(active&&current)onObserved(current);}catch{/* Keep the pending operation visible; the VPS owns its bounded expiry. */}finally{if(active)timer=setTimeout(()=>void poll(),3000);}}timer=setTimeout(()=>void poll(),3000);return()=>{active=false;clearTimeout(timer);};},[device.id,networkPending,onObserved]);
const observed=device.observed; const observed=device.observed;
const secondary=observed.configuration.servers.find(s=>s.slot===2); const secondary=observed.configuration.servers.find(s=>s.slot===2);
const fullSettings=hosts.some(h=>h.state==='paired'&&h.vehicle_ids.includes(device.vehicle_id)&&['0.1.15','0.1.16','0.1.17','0.1.18','0.1.19','0.1.20','0.1.21','0.1.22','0.1.23','0.1.24','0.1.25','0.1.26','0.1.27','0.1.28','0.1.29','0.1.30','0.1.31','0.1.32','0.1.33','0.1.34','0.1.35','0.1.36','0.1.37','0.1.38','0.1.39','0.1.40','0.1.41'].includes(h.status?.version??'')&&h.status?.tracker.host===secondary?.host&&h.status?.tracker.port===secondary?.port); const fullSettings=hosts.some(h=>h.state==='paired'&&h.vehicle_ids.includes(device.vehicle_id)&&['0.1.15','0.1.16','0.1.17','0.1.18','0.1.19','0.1.20','0.1.21','0.1.22','0.1.23','0.1.24','0.1.25','0.1.26','0.1.27','0.1.28','0.1.29','0.1.30','0.1.31','0.1.32','0.1.33','0.1.34','0.1.35','0.1.36','0.1.37','0.1.38','0.1.39','0.1.40','0.1.41','0.1.42','0.1.43'].includes(h.status?.version??'')&&h.status?.tracker.host===secondary?.host&&h.status?.tracker.port===secondary?.port);
const supported=observed.supported_profile_fields??Object.keys(device.settings.parameters); const supported=observed.supported_profile_fields??Object.keys(device.settings.parameters);
const fields=model.fields.filter(f=>supported.includes(f.key)); const fields=model.fields.filter(f=>supported.includes(f.key));
const validation=policyError(settings,fields)||(selectSim&&settings.connectivity.strategy==='sim'&&!cellularSimCurrent(telemetry,settings.connectivity.sim_slot??1)?'Ожидаем свежие данные выбранной SIM перед отправкой настроек.':''); const validation=policyError(settings,fields)||(selectSim&&settings.connectivity.strategy==='sim'&&!cellularSimCurrent(telemetry,settings.connectivity.sim_slot??1)?'Ожидаем свежие данные выбранной SIM перед отправкой настроек.':'');
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs'; import {readFileSync} from 'node:fs';
import ts from 'typescript'; import ts from 'typescript';
const code=ts.transpileModule(readFileSync(new URL('../src/core/fleet/cellular.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText; const code=ts.transpileModule(readFileSync(new URL('../src/core/fleet/cellular.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText;
const {cellularFresh,cellularNetworkLabel,cellularSimLabel,cellularModemLabel,cellularSlotView,cellularSimOptions,cellularSimCurrent}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64')); const {cellularSlotDescription,cellularFresh,cellularNetworkLabel,cellularSimLabel,cellularModemLabel,cellularSlotView,cellularSimOptions,cellularSimCurrent}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
test('SIM freshness rejects old, future and missing observations independently',()=>{ test('SIM freshness rejects old, future and missing observations independently',()=>{
assert.equal(cellularFresh(undefined,100),false); assert.equal(cellularFresh(undefined,100),false);
assert.equal(cellularFresh({measured_at:11},100),true); assert.equal(cellularFresh({measured_at:11},100),true);
@@ -79,3 +79,13 @@ test('qualified card home operator follows current binding even when serving MNC
t.sim_identity.slots['2'].binding_current=false; t.sim_identity.slots['2'].binding_current=false;
assert.equal(cellularSimOptions(t,101)[1].label,'SIM 2 (оператор не определён)'); assert.equal(cellularSimOptions(t,101)[1].label,'SIM 2 (оператор не определён)');
}); });
test('connected SIM with missing MCC is distinguished from an absent SIM',()=>{
const telemetry={online:true,cellular:{status:{measured_at:100,active_sim:1,gsm_state:4,sim_states:{1:1,2:1}},networks:{1:{measured_at:100,mcc:null,mnc:1,signal:18}}}};
assert.equal(cellularSlotDescription(telemetry,'1',100),'Интернет подключён. B2 ещё не передал код сети оператора.');
telemetry.cellular.networks[1].mcc=250;
assert.equal(cellularSlotDescription(telemetry,'1',100),'МТС · 250-01');
telemetry.cellular.status.sim_states[1]=0;
assert.match(cellularSlotDescription(telemetry,'1',100),/B2 не обнаружил карту/);
});
@@ -52,3 +52,21 @@ test('durable jobs show recovery independently of a single attempt and stop requ
assert.equal(commandPending('accepted'),false); assert.equal(commandPending('accepted'),false);
assert.equal(commandPending('stopped'),false); assert.equal(commandPending('stopped'),false);
}); });
test('text output receipt does not falsely claim no response when it cannot correlate SERV OK',()=>{
const text={kind:'pulse-output',state:'unconfirmed',description:{encoding:'INTERNAL · FC'}};
assert.match(commandReceipt(text),/не содержит идентификатора команды/);
assert.doesNotMatch(commandReceipt(text),/Ответ трекера не получен/);
assert.equal(commandStatus('unconfirmed'),'Результат не подтверждён');
});
test('text transport completion releases queue without claiming execution',()=>{
const delivered={kind:'set-output',state:'delivered',delivered_at:100,delivery_seconds:1.5,description:{encoding:'INTERNAL · FC'}};
assert.equal(commandPending(delivered.state),false);
assert.equal(commandStatus(delivered.state),'Доставлено');
assert.equal(commandTone(delivered.state),'neutral');
assert.match(commandReceipt(delivered),/Доставка команды подтверждена/);
assert.match(commandReceipt(delivered),/не подтверждение переключения/);
});
-447
View File
@@ -1,447 +0,0 @@
# NODE.DC Mission VPS Host 0.1.41
Version 0.1.41 completes the extracted transport observation batch before a
socket closure cancels its sender. Closing a stream can no longer abandon a
pending observation commit. All monitoring commands now wait for device input
on their selected socket no older than five seconds, as configuration commands
already did. Empty send queues alone are insufficient evidence of a live path.
The pending intent and original attempt deadlines are preserved; device input
wakes the sender without an extra probing command. This mitigates stale-stream
dispatch but does not guarantee delivery on a cellular network.
Version 0.1.40 persists command transport observations separately from B2
execution: prepared, written, TCP acknowledged, or unconfirmed with a reason.
The Linux send-queue watchdog records when the complete command prefix was
acknowledged; it never promotes the command to executed. Socket closure, expiry
and process restart preserve uncertainty. Observations are available on command
and operation APIs and attempt history, including late observations after a
device reply. No payload, password, modem address or SIM identity is logged.
Existing deadlines, retry policy and Core-to-VPS polling direction are unchanged.
Version 0.1.39 adds engineering-only `probe-diagnostic-mode` (INTERNAL
SERVER_COM `01 00`) for model 231 / firmware 0.01. A separately armed,
authenticated observation ID is mandatory; exactly one command may consume
each observation. Dispatch is restricted to an existing admitted connection,
expires within three seconds, and is never replayed across reconnect/restart.
Closing the observation prevents a queued dispatch. There is no raw-command
input and this action is absent from the operator catalogue/durable operations.
The 180-second lease bounds capture/dispatch, **not** the device's mode lifetime.
A token receipt does not establish a mode change or fresh SIM identity.
Physical qualification and termination semantics are recorded separately.
Version 0.1.35 publishes imported state with a single same-filesystem rename.
A failed staging copy cannot expose a partial host identity, and restoration
does not need a second full-size journal copy.
Version 0.1.34 adds portable, quiesced state export and empty-host import.
The source stays fenced across service/OS restarts. TLS identity, ownership,
registered devices and the entire durable journal move together. Import uses
the exact matching installer and preserves the configured endpoint.
Version 0.1.33 makes service-code directory traversal independent of the root
installer caller's umask. Private credentials and state retain their restricted
permissions. It otherwise preserves the 0.1.32 durable maintenance runtime.
Version 0.1.31 accepts matching binary command token receipts through either
admitted monitoring connection of the same B2, including a reconnected stream.
ACK (code 6) remains distinct from a final result. Text replies, revoked devices,
unknown sessions and other trackers cannot confirm a binary command.
Version 0.1.30 resumes only independent readback of a committed `configure-all`
image after a VPS process restart or a new B2 connection, preserving its ID, target, original
deadline and stage pacing. No image, SIM switch, restart or output action replays.
Fresh readback can establish the target, the predecessor or an unknown image;
an unavailable device still ends with an uncertain outcome. This is recovery of
verification, not proof that the B2 modem can recover autonomously.
Version 0.1.29 additionally defers configuration commands on a silent monitoring
stream until the B2 sends fresh input (within five monotonic seconds). A drained
TCP queue alone does not prove a live cellular path. The original operation
deadline is retained; dispatched stages never replay. Position/output command
policy is unchanged. This is a transport admission guard, not a cellular latency
guarantee.
Version 0.1.28 answers the observed empty HTTP opcode-7 request with current Unix
UTC seconds from the owner's VPS, using the reference-qualified u32be envelope.
Only an admitted model-231/0.01 identity with an active matching modem peer can
receive it. It does not change settings, complete an operation or extend its
deadline. The host clock must be correct. Device dialogue/repeated configuration
acceptance is recorded separately; a clock response alone is not that acceptance.
Version 0.1.27 admits a new command only when the selected Linux socket has
no unacknowledged kernel bytes or pending asyncio bytes. Among eligible streams
the most recently active one wins. Blocked streams cannot steal a command from
a drained stream; deadlines remain unchanged and dispatched commands never
replay. Transport readiness does not confirm execution.
Version 0.1.26 adds immutable request deadlines for idempotent Core delivery,
a durable bounded wait for undispatched position requests, and event-driven idle
senders. Terminal operation history is indexed out of the packet/dispatch path.
Commands already dispatched to a tracker are never automatically replayed.
The engineering `qualify_faults.py` harness checks crash recovery, lost HTTP
responses, immutable expiry and no replay using the installed package with
temporary SQLite and loopback sockets. It does not use production state or
physical hardware. See [fault qualification](../../docs/arnavi_b2/FAULT_RECOVERY_20260927.md).
Version 0.1.25 bounds command bytes in the Linux TCP queue to the earlier of
the operation deadline and 30 seconds after dispatch. HTTP settings replies
have a 12-second transport bound, capped by the operation deadline. Monotonic
watchdogs account for both asyncio and kernel buffers; abortive close prevents
queued data from lingering after disconnect. TCP acknowledgement only releases
the transport watchdog, never confirms device execution. Interrupted or expired
actions are never replayed. Already received commands cannot be cancelled.
Version 0.1.24 adds exclusive SIM selection on qualified B2 model 231 / firmware
0.01: fresh configuration preflight, one image write, exact readback, one restart,
and fresh type-1 DS2 evidence of GPRS on the requested SIM over a new connection.
The operation has a 360-second bound. Field 72 bits 10/20 prohibit data on the
other SIM; this is not automatic failover. APNs and access credentials are kept
unless explicitly edited. Interrupted writes/restarts are never replayed.
Full cellular-only physical qualification is recorded separately in the ledger.
Version 0.1.23 retains the independently registered numeric-ID reply, but removes
the experimental empty settings response: physical 0.1.22 evidence showed an
ID/settings loop, not completion. A settings image is still sent only during
an explicit, bounded write. Startup qualification remains open.
Version 0.1.22 qualifies the continuous startup exchange: reply with the
independently enrolled numeric device ID, then an empty settings response when
no explicit image write is pending. Numeric IDs are immutable per IMEI and
never inferred from its digits. Unknown IDs and unadmitted peers fail closed.
An explicit pending write retains its single-image dispatch/readback contract.
Physical qualification of the combined exchange is required before publication.
Version 0.1.21 admits the captured ten-byte command-1 response in a one-shot
engineering lease. Its four-byte payload equals the independently known device
ID. Product behavior is unchanged pending a fresh, unchanged device upload.
Version 0.1.20 admits one exact empty reply to the observed empty command-1
request in the engineering observation lease. This follows the physical 2→1
transition after an empty command-2 reply. No firmware image can be supplied,
and normal product parsing remains closed until the exchange is qualified.
Version 0.1.19 admits one exact, zero-payload command-2 response only in
the bounded engineering observation lease for no-image-response qualification.
No product-channel behavior changes before physical verification.
Version 0.1.18 adds an engineering-only binary encoding of the documented
read-only settings upload request (0109), to qualify post-restart behavior.
It does not change the qualified product settings transport or retry writes.
Version 0.1.17 adds the qualified-model restart request (B2 manual §10, binary
0107). Dispatch expires after three seconds; the request is never replayed.
A token ACK is recorded separately. Only fresh type-1 telemetry measured after
dispatch on a newly opened connection records return, with a 180-second deadline.
This is observed network return, not proof of a hardware power cycle. Old sessions,
archive packets and replies alone cannot complete the operation.
Version 0.1.16 spaces full-configuration stages and successive operations by
15 seconds after each HTTP image exchange. The bench sometimes ignored a new
SERV request shortly after an upload despite TCP acknowledgment. This pacing
does not affect position/output commands or replay a settings write.
Version 0.1.15 adds complete configuration reads and profile writes on the
qualified B2 model 231 / firmware 0.01 HTTP settings channel. It reads the
current image before writing, requires an exact predecessor, preserves recovery
channels, sends the image once and verifies by an independent full readback.
Command-5 ACK is the captured seven-byte response with payload 01. Restart or
timeout after dispatch does not silently replay a write. No manufacturer API
is contacted by this runtime.
Version 0.1.14 chooses the active TCP session with the most recent incoming data
for command dispatch. A half-open predecessor left by a device configuration
reload cannot take a new command while a fresher session exists. It also allows
a bounded engineering upload-ACK qualification using the observed reply-envelope
structure, matching the complete validated upload body. Up to 64 observation
leases are retained (four 16-KiB captures each); raw evidence remains private.
Version 0.1.13 qualifies the observed configuration reply framing with the
shared B2 CRC/TLV codec. An engineering observation lease can serve a validated
configuration once to a byte-identical admitted B2 settings request. Explicit
close disarms the lease while retaining evidence. This is a real write path:
prepare an exact baseline and rollback image and verify a fresh device upload;
dispatch alone never establishes successful application. No vendor HTTP calls.
Version 0.1.12 additionally permits the documented `SERV*1.8` configuration
download request for protocol qualification. It can apply a configuration from
the device's configured endpoint; that endpoint must be owned and its payload
qualified before use. The current observation lease serves only a captured
identity answer, never a configuration. No firmware/erase/reset commands exist.
Version 0.1.11 adds an engineering-only, allowlisted B2 settings upload request
(`SERV*1.9`), preserving active-session expiry and no replay. It also permits one
captured seven-byte configuration identity answer to the exact corresponding
21-byte request, under an authenticated 180-second observation lease. The device
must be admitted; expiry, byte mismatch, duplicate HTTP framing and repeat
dispatch fail closed. This is bounded protocol qualification, not a general
proxy or full configuration support. The service never contacts a vendor.
Version 0.1.10 adds explicit `set-output` using the B2 manual section 10 FC
command `password*SERV*8.PIN.STATE`. PIN4..6 only, strict boolean `enabled`,
model 231 / firmware 0.01, instance password required. This sets a persistent
output state; it is not a timed pulse or a physical-contact confirmation.
It uses the existing active-session, three-second dispatch expiry and no-replay
contract. Unknown fields and arbitrary commands are rejected. Bench operators
must verify manual output mode and deliberately restore the observed baseline.
Version 0.1.9 adds the documented FC text encoding for the same bounded
`pulse-output` operation: PIN4..6, 1..5 seconds, model 231 / firmware 0.01.
An explicit `encoding: text` requires the instance's six-digit password; the
generated command remains private. No arbitrary text is accepted. This format
has no token-correlated confirmation: the receipt stays unconfirmed even when
unrelated token or text replies arrive. Dispatch still requires a current
session and expires after three seconds; commands never replay after restart.
A text PIN5 pulse produced an operator- and subsequently camera-observed LED
on/off transition. Earlier binary PIN4/PIN5 pulses had no visible effect.
A token ACK alone is not relay feedback; other outputs require qualification.
Headless receiver owned by Mission Core, independently of any rover's onboard PC.
Supported installation profile: **Ubuntu Server 24.04 amd64, Python 3.12,
OpenSSL 3, systemd**. Other OS/architectures fail preflight. No pip, Docker, GUI,
Node.js, compiler or vendor cloud is required. Minimal images missing OS
prerequisites are rejected with the missing capability; no blind system repair.
## Reproduce
From this repository:
```sh
.venv/bin/python scripts/build_vps_host.py --output /tmp/ndc-mission-vps.tar
```
The builder produces both a `.tar` engineering archive and a single `.pyz`
operator installer. Mission Core serves an explicitly published, checksum-verified
`.pyz` in Equipment → root plus → VPS Host ARNavi. The same window contains the
supported OS, installation instructions and pairing-key field. The installer
carries no tracker identities, SIM data, address, keys or private evidence.
Copy the downloaded file to the VPS and run:
```sh
sudo python3 ndc-mission-vps.pyz --host trackers.example.org
```
Use the actual downloaded filename. Omitting `--host` prompts for the public
address. The wrapper runs the same preflight/plan/apply engine, with an exact
plan digest; it does not require a separate installer GUI. The engineering tar
retains the explicit plan/apply interface:
```sh
python3 ndc-mission-vps/install.py plan --host trackers.example.org
python3 ndc-mission-vps/install.py apply --host trackers.example.org --expect PLAN_SHA256
```
Run apply as root. The exact current plan hash is required. DNS/IP is an install
parameter, never source code. Use stable DNS so a VPS migration does not require
rewriting thousands of trackers. Default ports: TCP 9922 (B2 INTERNAL), TLS 19443
(Mission Core). Cloud firewall must allow these exact ports. The installer preserves existing services, including DeviceCore on 443/9921.
For the detected legacy NODE.DC `nodedc_b2_vps` nftables policy it adds two
comment-owned allow rules and a persistent include, checks predecessor hashes,
and records a bounded rollback. It never flushes rules. Unknown firewall
policies remain external and require public endpoint acceptance.
Existing listener/foreign installation conflicts stop first install.
Installation paths:
- `/opt/nodedc-mission-vps/current`: immutable release selected by content digest.
- **`/opt/nodedc-mission-vps/connect.key`**: fixed root-level pairing file,
symlink to protected state; read as root.
- `/var/lib/ndc-mission-vps`: host identity, TLS key, owner and durable journal,
mode 0700, files 0600, owned by dedicated system user `ndc-mission-vps`.
- `/etc/systemd/system/ndc-mission-vps.service`: versioned managed system unit.
Open an apparatus → Equipment → top plus → VPS Host ARNavi. Paste the key, choose a
name and served apparatuses. It expires after 24 hours and is consumed once.
The same VPS appears under every assigned rover. To attach an existing VPS to
another rover, choose it in the connection dialog, or change the host's apparatus
list in settings. One host retains one identity and one Mission Core owner.
An unused expired key can be renewed with the shipped CLI:
```sh
cd /opt/nodedc-mission-vps/current
sudo -u ndc-mission-vps /usr/bin/python3 -m ndc_vps invitation
```
Paired hosts cannot silently regenerate/reassign ownership. Back up the whole
private state directory and Mission Core fleet state. A new host has a new key.
An update retains the same identity and queue. Applying the current release is
a health-checking no-op. Failed updates restore the previous release and unit.
Explicit rollback preserves private state and the journal:
```sh
python3 ndc-mission-vps/install.py rollback --host trackers.example.org --expect INSTALLED_ARTIFACT_DIGEST
```
For the first release rollback disables the new service; it does not delete
identities, evidence or any unrelated service. Schema v1 updates are additive;
a future incompatible migration must supply its own reversible migration.
## Clean product reinstallation
```sh
sudo python3 ndc-mission-vps.pyz --host trackers.example.org --fresh
```
This explicitly replaces this product's installation and identity. First the
installer stops its own unit and creates a private, hash-recorded backup under
`/var/backups/ndc-mission-vps/`. It preserves original application/state trees,
then installs empty product state and creates a new pairing key. A failed fresh
installation restores the backup and health-checks the old service. Foreign
services and unrelated files are preserved. This is not an OS reimage.
In the Core admission form select the previous record under «После переустановки»
and paste the new key. Replacement is explicit: duplicate live host records at
the same endpoint are refused. The former record and telemetry journal remain
in private history; only the newly paired identity is synchronized.
To restore a selected backup with the same installer:
```sh
sudo python3 ndc-mission-vps.pyz --host trackers.example.org --restore /var/backups/ndc-mission-vps/BACKUP_ID
```
After a successful new pairing, restoring the server alone does not restore the
Core's host registration. Restore a matching private Core fleet backup as part
of disaster recovery; do not substitute identities or disclose tokens manually.
## Publish qualified downloads
The operator runtime keeps installers under its private fleet root, outside Git.
Publishing a release only changes the download; it never installs on a board or
VPS. Run the publisher with the exact SHA from the accepted build receipt:
```sh
.venv/bin/python scripts/publish_fleet_installer.py \
--fleet-root /path/to/operator/fleet --kind vps-arnavi \
--file /path/to/qualified-vps.pyz --version 0.1.3 --sha256 ACCEPTED_SHA256
```
For the onboard computer use `--kind node` and the version/SHA of the already
qualified owner installer. Copy the finished installer back from the build host
before publishing it. A source-build bundle is not an owner installer. Publishing
the Node archive does not update the board. Catalog and download endpoints verify
size and SHA; a missing or changed archive is unavailable instead of silently
falling back to an older build.
## Tracker admission and delivery
Register/read a B2 over USB in Mission Core, select the registered VPS in its
connection settings, save, then apply over USB. Slot 2 is initially proposed to
preserve an existing slot 1. Profiles contain common settings, not IMEI/ICCID,
SIM phone number or assignment. Firmware-qualified writer performs backup,
identity/config preconditions, acknowledgement and independent readback.
Core synchronizes an allowlist of registered IMEIs assigned to that host's
apparatuses and configured endpoint. Unknown devices receive no telemetry ACK.
**IMEI is a claimed identity, not cryptographic tracker authentication**: legacy
INTERNAL is plaintext. For untrusted deployments use an operator private APN or
network protection; this release does not claim end-to-end tracker encryption.
VPS ACKs a B2 package only after a SQLite FULL commit. Core pulls a bounded batch,
stores raw evidence, derives valid coordinates and advances its cursor in the
same transaction, then acknowledges the VPS queue. Replays are idempotent;
package sequence reuse cannot replace content. Header-time and package ACKs
follow the published INTERNAL framing. No arbitrary tracker command API exists.
The authenticated VPS API also qualifies the allowlisted, read-only `GETP`
command over an existing tracker TCP session. Commands have durable IDs and
bounded expiry; a dispatched command is never automatically replayed after a
restart. A text response means `reply_received`, not «settings applied».
Version 0.1.6 adds the bounded `configure-server1` operation for B2 model 231 /
firmware 0.01. Fresh GETP must match the expected primary endpoint and show this
VPS as the secondary server. Only documented SETP #1 host/port is changed; a
separate GETP must verify the endpoint and preservation of every other group.
Operations bind to one TCP session, reject stale/duplicate responses, expire
after 120 seconds and never replay writes after restart. Reversal is a separate
preconditioned operation. FC has no correlation token: timestamp/session checks
bound freshness but do not create cryptographic command attribution.
Device clock skew is bounded to 10 seconds behind / 5 seconds ahead of VPS time;
successive operation stages require strictly increasing device timestamps.
After a dispatched SETP the host waits at least 15 seconds before its separate
GETP. Only this read may bind to a new TCP session after tracker reconnection;
SET P is never resent. Verification also runs when SETP's acknowledgement is lost.
The 0.1.4 experiment stopped before writing because its timestamp comparison
incorrectly required synchronized clocks; the measured B2 was about 4 s behind.
Full profiles, APN/active-channel migration, other server slots and disabling the
vendor configurator remain unqualified. The authenticated API is private: raw
GETP replies contain credentials and must never be proxied into the browser.
See [network configuration audit](../../docs/arnavi_b2/NETWORK_CONFIGURATION.md).
The VPS queue has a 512 MiB budget and preserves a 256 MiB disk reserve. When
full/unwritable it withholds ACK, never drops unconsumed packages. Receipts retain
retransmission deduplication for seven days. Core must remain available often
enough to drain the queue. Capacity for thousands of simultaneously active
trackers has **not** been load-qualified; the first profile caps 256 connections
and service memory at 192 MiB. Scale/retention qualification is a separate gate.
Core API uses TLS 1.3 with certificate fingerprint verified **before** sending a
pairing secret or bearer token. Invitation is obtained through the owner's SSH
channel. DNS resolves only to public IPv4. Redirects/ambient HTTP proxies are
not followed. Node's private-network pairing contract is unchanged.
Coordinates are derived from valid packet tags. Missing/invalid/zero coordinates
are not invented. Device measurement time and reception time remain separate;
an older replay cannot move the map backwards in time. UI shows freshness and
last contact, independently of the onboard computer.
## Acceptance boundary
`tests/test_vps_host.py` covers framing, partial TCP reads, checksum rejection,
one-time enrollment, retry identity, admission, durable delivery, deduplication,
Core cursor transaction, stale data and shared rover reassignment. Hardware and
operator VPS acceptance are recorded separately in a private deployment ledger.
A successful install on the existing Ubuntu VPS is not clean-image qualification.
## Portable transfer to a clean VPS
Use the same qualified installer file on both hosts. Upgrade the source to it
first. Then on the source:
```sh
sudo python3 ndc-mission-vps.pyz --export-state /root/mission-vps-state.tar.gz
```
This stops this service and persistently fences it before taking the snapshot.
The source remains stopped, including after reboot. Export prints the archive's
SHA-256. The archive contains credentials and the SQLite journal: keep it private
and transfer it through the owner's SSH channel together with the installer.
No executable, system unit, account ID or firewall configuration crosses hosts.
A failure after fencing leaves the source stopped and preserves its state.
On the clean supported Ubuntu VPS:
```sh
sudo python3 ndc-mission-vps.pyz --import-state /root/mission-vps-state.tar.gz --sha256 ARCHIVE_SHA256
```
Import checks the exact archive SHA, complete file manifest, matching installer
release, TLS key/certificate identity and SQLite integrity before installation.
Existing product paths are refused. It creates the system account, code and unit
through the same installer and verifies service health. TLS identity and Core
pairing survive; commands retain IDs, attempts, deadlines and stop markers.
The normal runtime reconciles interrupted attempts; a snapshot is not proof of
tracker execution. No old live TCP session is restored.
Keep the existing DNS name and ports, then direct that DNS name to the target
after its health and external reachability checks. For an endpoint configured
as a literal IP, this operation alone does not migrate Core or tracker addresses;
a transferable IP or a separately verified endpoint change is required. Provider
firewalls and DNS changes require their owner's controls/API and are not inferred
from guest installation success. The receiving installation needs 2.25 GiB of
free staging space; portable state is capped at 2 GiB.
To abandon migration, **stop the target first**, then explicitly resume the source:
```sh
sudo python3 ndc-mission-vps.pyz --resume-source
```
The source cannot observe the target across an outage. The installer therefore
never resumes it automatically. Retain the private archive and exact installer
for recovery. Do not run both identities simultaneously. A stale archive also
cannot contain commands or confirmations recorded after its snapshot.
-95
View File
@@ -1,95 +0,0 @@
"""Bounded migration of the observed NODE.DC B2 nftables policy; no flush."""
import hashlib
import json
import subprocess
from pathlib import Path
CONFIG = Path("/etc/nftables.conf")
FRAGMENT = Path("/etc/nftables.d/ndc-mission-vps.nft")
BACKUP = Path("/opt/nodedc-mission-vps/firewall-before.json")
INCLUDE = 'include "/etc/nftables.d/ndc-mission-vps.nft"'
MARKER = "ndc-mission-vps-v1"
def run(*args, **kwargs):
return subprocess.run(args, check=True, capture_output=True, **kwargs)
def plan():
if not CONFIG.exists() or "table inet nodedc_b2_vps" not in CONFIG.read_text():
# A clean host can use its own provider firewall. Unknown local policies
# are not rewritten; public endpoint acceptance remains mandatory.
return {"mode": "external", "config_sha256": None}
live = json.loads(run("nft", "-j", "list", "chain", "inet", "nodedc_b2_vps", "input").stdout)
chain = next(x["chain"] for x in live["nftables"] if "chain" in x)
if chain.get("policy") != "drop" or chain.get("hook") != "input":
raise ValueError("unsupported legacy firewall policy")
if FRAGMENT.exists() and MARKER not in FRAGMENT.read_text():
raise ValueError("foreign firewall fragment conflict")
return {
"mode": "nodedc-b2-v1",
"config_sha256": hashlib.sha256(CONFIG.read_bytes()).hexdigest(),
}
def rules(api, tracker):
return (
f"add rule inet nodedc_b2_vps input tcp dport {api} ct state new "
f'limit rate 600/minute burst 128 packets accept comment "{MARKER}-api"\n'
f"add rule inet nodedc_b2_vps input tcp dport {tracker} ct state new "
f'limit rate 600/minute burst 128 packets accept comment "{MARKER}-tracker"\n'
)
def removal():
live = json.loads(run("nft", "-j", "list", "chain", "inet", "nodedc_b2_vps", "input").stdout)
commands = []
for item in live["nftables"]:
rule = item.get("rule", {})
if rule.get("comment") in (MARKER + "-api", MARKER + "-tracker"):
commands.append(f"delete rule inet nodedc_b2_vps input handle {int(rule['handle'])}\n")
return "".join(commands)
def apply(proposal, api, tracker, atomic):
if proposal["mode"] != "nodedc-b2-v1":
return False
if plan() != proposal:
raise ValueError("firewall changed after plan")
content = rules(api, tracker)
if INCLUDE in CONFIG.read_text():
if not FRAGMENT.exists() or FRAGMENT.read_text() != content:
raise ValueError("managed firewall drift")
# Reconcile only our named live rules if nftables was reloaded.
run("nft", "-f", "-", input=(removal() + content).encode())
return False
original = CONFIG.read_text()
desired = original.rstrip() + "\n\n" + INCLUDE + "\n"
backup = {
"before": original,
"after_sha256": hashlib.sha256(desired.encode()).hexdigest(),
"fragment_sha256": hashlib.sha256(content.encode()).hexdigest(),
}
atomic(BACKUP, json.dumps(backup).encode())
FRAGMENT.parent.mkdir(mode=0o755, exist_ok=True)
# Validate the live transaction before modifying persistent files.
run("nft", "-c", "-f", "-", input=(removal() + content).encode())
atomic(FRAGMENT, content.encode(), 0o644)
atomic(CONFIG, desired.encode(), 0o644)
run("nft", "-f", "-", input=(removal() + content).encode())
return True
def rollback(atomic):
record = json.loads(BACKUP.read_text())
if (
hashlib.sha256(CONFIG.read_bytes()).hexdigest() != record["after_sha256"]
or hashlib.sha256(FRAGMENT.read_bytes()).hexdigest() != record["fragment_sha256"]
):
raise ValueError("firewall changed; rollback will not overwrite foreign edits")
commands = removal()
if commands:
run("nft", "-f", "-", input=commands.encode())
atomic(CONFIG, record["before"].encode(), 0o644)
FRAGMENT.unlink()
-429
View File
@@ -1,429 +0,0 @@
#!/usr/bin/env python3
"""Versioned Ubuntu 24.04 amd64 installer. Run plan, then apply its exact digest."""
import argparse
import hashlib
import json
import os
import platform
import pwd
import re
import shutil
import socket
import ssl
import subprocess
import sys
import time
import uuid
from pathlib import Path
import firewall
ROOT = Path("/opt/nodedc-mission-vps")
STATE = Path("/var/lib/ndc-mission-vps")
UNIT = Path("/etc/systemd/system/ndc-mission-vps.service")
USER = "ndc-mission-vps"
SOURCE = Path(__file__).resolve().parent
SERVICE = """# Managed by NODE.DC Mission VPS installer v1
[Unit]
Description=NODE.DC Mission VPS Host
After=network-online.target
Wants=network-online.target
ConditionPathExists=!/opt/nodedc-mission-vps/migration-fence.json
[Service]
Type=simple
User=ndc-mission-vps
Group=ndc-mission-vps
WorkingDirectory=/opt/nodedc-mission-vps/current
ExecStart=/usr/bin/python3 -m ndc_vps serve
Restart=on-failure
RestartSec=5
UMask=0077
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/var/lib/ndc-mission-vps
MemoryMax=192M
TasksMax=96
LimitNOFILE=2048
[Install]
WantedBy=multi-user.target
"""
def run(*args, **kwargs):
return subprocess.run(args, check=True, capture_output=True, **kwargs)
def digest():
manifest = json.loads((SOURCE / "manifest.json").read_text())
for name, expected in manifest["files"].items():
if name.startswith("/") or ".." in Path(name).parts:
raise ValueError("invalid manifest")
if hashlib.sha256((SOURCE / name).read_bytes()).hexdigest() != expected:
raise ValueError("artifact integrity mismatch")
return hashlib.sha256((SOURCE / "manifest.json").read_bytes()).hexdigest()
def predecessor():
return os.readlink(ROOT / "current") if (ROOT / "current").is_symlink() else None
def plan(args):
osrelease = dict(
line.split("=", 1)
for line in Path("/etc/os-release").read_text().splitlines()
if "=" in line
)
if (
osrelease.get("ID", "").strip('"') != "ubuntu"
or osrelease.get("VERSION_ID", "").strip('"') != "24.04"
or platform.machine() != "x86_64"
):
raise ValueError("supported environment: Ubuntu Server 24.04 amd64 only")
if sys.version_info[:2] != (3, 12):
raise ValueError("Python 3.12 required")
for command in ("openssl", "systemctl", "useradd", "runuser"):
if not shutil.which(command):
raise ValueError("missing OS prerequisite: " + command)
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.-]{0,48}", args.host):
raise ValueError("public DNS name or IPv4 required (max 49 characters for B2)")
if UNIT.exists() and "Managed by NODE.DC Mission VPS installer v1" not in UNIT.read_text():
raise ValueError("foreign service conflict")
if ROOT.exists() and not (ROOT / "installed.json").exists():
raise ValueError("foreign installation root conflict")
if STATE.exists() and not (STATE / "host.json").exists():
raise ValueError("foreign state directory conflict")
if (ROOT / "migration-fence.json").exists():
raise ValueError("source fenced for migration; resume explicitly only with target stopped")
old = predecessor()
for port in (args.api_port, args.tracker_port):
if port < 1024 or port > 65535:
raise ValueError("ports must be 1024..65535")
if not old:
with socket.socket() as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("0.0.0.0", port))
if args.api_port == args.tracker_port:
raise ValueError("ports must differ")
configuration = {
"public_host": args.host,
"api_port": args.api_port,
"tracker": {"host": args.host, "port": args.tracker_port},
}
if STATE.exists():
existing = json.loads((STATE / "host.json").read_text())
if any(existing[key] != val for key, val in configuration.items()):
raise ValueError(
"endpoint migration requires a separate planned operation; use stable DNS"
)
data = {
"schema": "missioncore.vps-install-plan/v1",
"firewall": firewall.plan(),
"artifact": digest(),
"previous": old,
"configuration": configuration,
"unit_sha256": hashlib.sha256(UNIT.read_bytes()).hexdigest() if UNIT.exists() else None,
"environment": "ubuntu-24.04-amd64",
"service": str(UNIT),
"root": str(ROOT),
"key_file": str(ROOT / "connect.key"),
}
data["plan_sha256"] = hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()
return data
def atomic(path, value, mode=0o600):
temporary = path.with_name(path.name + ".new")
temporary.write_bytes(value)
temporary.chmod(mode)
os.replace(temporary, path)
def select_release(release):
temporary = ROOT / ".current"
temporary.unlink(missing_ok=True)
temporary.symlink_to(release)
os.replace(temporary, ROOT / "current")
def healthy():
for _ in range(20):
if subprocess.run(["systemctl", "is-active", "--quiet", "ndc-mission-vps"]).returncode == 0:
try:
config = json.loads((STATE / "host.json").read_text())
ctx = ssl.create_default_context(cafile=str(STATE / "tls.crt"))
ctx.check_hostname = False
with (
socket.create_connection(("127.0.0.1", config["api_port"]), 2) as sock,
ctx.wrap_socket(sock) as secure,
):
secure.sendall(b"GET /health HTTP/1.1\r\nHost: localhost\r\n\r\n")
if b"200 Result" in secure.recv(4096):
return
except OSError:
pass
time.sleep(0.5)
raise ValueError("service health check failed")
def apply(args, proposal):
if os.geteuid() != 0 or args.expect != proposal["plan_sha256"]:
raise ValueError("root and exact current plan digest required")
old = proposal["previous"]
installed = ROOT / "installed.json"
if (
old
and Path(old).name == proposal["artifact"]
and installed.exists()
and json.loads(installed.read_text()).get("status") == "healthy"
):
healthy()
print(json.dumps({"status": "already_current", "artifact": proposal["artifact"]}))
return
release = ROOT / "releases" / proposal["artifact"]
ROOT.mkdir(mode=0o755, exist_ok=True)
(ROOT / "releases").mkdir(mode=0o755, exist_ok=True)
# mkdir's mode is filtered by the caller's umask. The unprivileged service
# must traverse these owned code directories even under root's umask 0077.
ROOT.chmod(0o755)
(ROOT / "releases").chmod(0o755)
old_unit = UNIT.read_bytes() if UNIT.exists() else None
# Pre-create the ownership record: a failed first install can be inspected/retried.
if not (ROOT / "installed.json").exists():
atomic(
ROOT / "installed.json",
json.dumps({"schema": "missioncore.vps-install/v1", "status": "preparing"}).encode(),
)
try:
pwd.getpwnam(USER)
except KeyError:
run("useradd", "--system", "--home-dir", str(STATE), "--shell", "/usr/sbin/nologin", USER)
user = pwd.getpwnam(USER)
if not release.exists():
shutil.copytree(SOURCE, release, ignore=shutil.ignore_patterns("__pycache__"))
release.chmod(0o755)
for item in release.rglob("*"):
item.chmod(0o755 if item.is_dir() else 0o644)
if not STATE.exists():
STATE.mkdir(mode=0o700)
configuration = proposal["configuration"].copy()
run(
"openssl",
"req",
"-x509",
"-newkey",
"ed25519",
"-nodes",
"-days",
"3650",
"-subj",
"/CN=NODE.DC Mission VPS Host",
"-keyout",
str(STATE / "tls.key"),
"-out",
str(STATE / "tls.crt"),
)
certificate = ssl.PEM_cert_to_DER_cert((STATE / "tls.crt").read_text())
fingerprint = hashlib.sha256(certificate).hexdigest()
configuration.update(
fingerprint=fingerprint,
host_id="vps_" + fingerprint,
endpoint=f"https://{args.host}:{args.api_port}",
)
atomic(STATE / "host.json", json.dumps(configuration, indent=2).encode())
os.chown(STATE, user.pw_uid, user.pw_gid)
for item in STATE.iterdir():
item.chmod(0o600)
os.chown(item, user.pw_uid, user.pw_gid)
if not (ROOT / "connect.key").is_symlink():
(ROOT / "connect.key").symlink_to(STATE / "connect.key")
firewall_added = False
try:
firewall_added = firewall.apply(
proposal["firewall"], args.api_port, args.tracker_port, atomic
)
select_release(release)
if not (STATE / "connect.key").exists():
run(
"runuser",
"-u",
USER,
"--",
"/usr/bin/python3",
"-m",
"ndc_vps",
"invitation",
cwd=release,
)
atomic(UNIT, SERVICE.encode(), 0o644)
run("systemctl", "daemon-reload")
run("systemctl", "enable", "ndc-mission-vps.service")
run("systemctl", "restart", "ndc-mission-vps.service")
healthy()
atomic(
ROOT / "installed.json",
json.dumps(
{
**proposal,
"status": "healthy",
"firewall_added": firewall_added,
"installed_at": time.time(),
},
indent=2,
).encode(),
)
print(
json.dumps(
{
"status": "healthy",
"artifact": proposal["artifact"],
"key_file": str(ROOT / "connect.key"),
}
)
)
except Exception:
if firewall_added:
firewall.rollback(atomic)
if old:
select_release(old)
if old_unit:
atomic(UNIT, old_unit, 0o644)
run("systemctl", "daemon-reload")
run("systemctl", "restart", "ndc-mission-vps.service")
healthy()
else:
subprocess.run(
["systemctl", "disable", "--now", "ndc-mission-vps.service"], capture_output=True
)
raise
def rollback(args):
record = json.loads((ROOT / "installed.json").read_text())
if os.geteuid() != 0 or args.expect != record["artifact"]:
raise ValueError("root and installed artifact digest required")
if record.get("firewall_added"):
firewall.rollback(atomic)
previous = record["previous"]
if previous:
path = Path(previous)
if path.parent != ROOT / "releases" or not path.is_dir():
raise ValueError("previous release unavailable")
select_release(path)
run("systemctl", "restart", "ndc-mission-vps.service")
healthy()
else:
run("systemctl", "disable", "--now", "ndc-mission-vps.service")
# Preserve state, keys and journal even when uninstalling the first release.
atomic(ROOT / "installed.json", json.dumps({**record, "status": "rolled_back"}).encode())
print(json.dumps({"status": "rolled_back", "state_preserved": True}))
BACKUPS = Path("/var/backups/ndc-mission-vps")
def restore(backup):
if os.geteuid() != 0 or backup.parent != BACKUPS or backup.is_symlink():
raise ValueError("root and an installer-owned backup required")
if (ROOT / "migration-fence.json").exists():
raise ValueError("source fenced for migration")
record = json.loads((backup / "backup.json").read_text())
if record.get("schema") != "missioncore.vps-backup/v1":
raise ValueError("invalid backup")
# Verify before stopping anything. Never overwrite a foreign service.
if UNIT.exists() and "Managed by NODE.DC Mission VPS installer v1" not in UNIT.read_text():
raise ValueError("foreign service conflict")
for name, expected in record["files"].items():
file = backup / name
if ".." in Path(name).parts or file.is_symlink():
raise ValueError("invalid backup file")
if hashlib.sha256(file.read_bytes()).hexdigest() != expected:
raise ValueError("backup integrity mismatch")
run("systemctl", "stop", "ndc-mission-vps.service")
recovery = backup / ("replaced-" + uuid.uuid4().hex)
recovery.mkdir(mode=0o700)
for name, target in (("root", ROOT), ("state", STATE), ("unit", UNIT)):
if target.exists():
shutil.move(str(target), recovery / name)
source = backup / name
if source.is_dir():
shutil.copytree(source, target, symlinks=True)
else:
shutil.copy2(source, target)
user = pwd.getpwnam(USER)
os.chown(STATE, user.pw_uid, user.pw_gid)
for file in STATE.iterdir():
os.chown(file, user.pw_uid, user.pw_gid)
run("systemctl", "daemon-reload")
run("systemctl", "enable", "ndc-mission-vps.service")
run("systemctl", "restart", "ndc-mission-vps.service")
healthy()
print(json.dumps({"status": "restored", "backup": str(backup)}))
def fresh(args, proposal):
if os.geteuid() != 0 or args.expect != proposal["plan_sha256"] or not proposal["previous"]:
raise ValueError("fresh replacement requires an exact plan of an installed product")
BACKUPS.mkdir(mode=0o700, parents=True, exist_ok=True)
backup = BACKUPS / (time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) + "-" + uuid.uuid4().hex[:8])
backup.mkdir(mode=0o700)
run("systemctl", "stop", "ndc-mission-vps.service")
try:
for name, path in (("root", ROOT), ("state", STATE)):
shutil.copytree(path, backup / name, symlinks=True)
shutil.copy2(UNIT, backup / "unit")
files = {
str(p.relative_to(backup)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in backup.rglob("*")
if p.is_file() and not p.is_symlink()
}
atomic(
backup / "backup.json",
json.dumps(
{
"schema": "missioncore.vps-backup/v1",
"created_at": time.time(),
"monotonic": time.monotonic(),
"files": files,
}
).encode(),
)
except Exception:
run("systemctl", "start", "ndc-mission-vps.service")
raise
try:
# Complete verified private copy exists; move original trees too, never wildcard-delete.
shutil.move(str(ROOT), backup / "original-root")
shutil.move(str(STATE), backup / "original-state")
shutil.move(str(UNIT), backup / "original-unit")
new_plan = plan(args)
args.expect = new_plan["plan_sha256"]
apply(args, new_plan)
except Exception:
restore(backup)
raise
print(json.dumps({"status": "fresh_install", "backup": str(backup)}))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("action", choices=("plan", "apply", "rollback"))
parser.add_argument("--host", required=True)
parser.add_argument("--api-port", type=int, default=19443)
parser.add_argument("--tracker-port", type=int, default=9922)
parser.add_argument("--expect")
args = parser.parse_args()
try:
if args.action == "rollback":
rollback(args)
else:
proposal = plan(args)
if args.action == "plan":
print(json.dumps(proposal, indent=2))
else:
apply(args, proposal)
except Exception as error:
print("Installation stopped: " + str(error), file=sys.stderr)
sys.exit(1)
-3
View File
@@ -1,3 +0,0 @@
"""Headless NODE.DC Mission VPS Host; Python 3.12 standard library only."""
VERSION = "0.1.41"
-19
View File
@@ -1,19 +0,0 @@
import argparse
import asyncio
import json
from .service import Service
from .store import Store
parser = argparse.ArgumentParser()
parser.add_argument("action", choices=("serve", "invitation", "status"))
parser.add_argument("--state", default="/var/lib/ndc-mission-vps")
args = parser.parse_args()
store = Store(args.state)
if args.action == "serve":
asyncio.run(Service(store).run())
elif args.action == "invitation":
store.invitation()
print("Invitation ready in /opt/nodedc-mission-vps/connect.key (valid 24 hours).")
else:
print(json.dumps(store.status()))
-120
View File
@@ -1,120 +0,0 @@
"""B2 manual §10 + INTERNAL SERVER_COM token envelope; no arbitrary commands."""
import re
import secrets
KINDS = {
"request-position",
"restart",
"pulse-output",
"set-output",
"upload-configuration",
"download-configuration",
"probe-diagnostic-mode",
}
def prepare(body):
if body.get("model") != 231 or body.get("firmware") != "0.01":
raise ValueError("unqualified action firmware")
allowed = {"id", "imei", "kind", "model", "firmware"}
if body["kind"] == "probe-diagnostic-mode":
# INTERNAL SERVER_COM 01 00. Engineering qualification only: neither
# a SIM read nor a promise about this firmware's mode/termination.
# Admission additionally requires an explicit live observation lease.
allowed.add("observation_id")
if not isinstance(body.get("observation_id"), str) or not re.fullmatch(
r"[a-f0-9]{32}", body["observation_id"]
):
raise ValueError("diagnostic probe requires observation")
command = b"\x01\x00"
elif body["kind"] == "request-position":
command = b"\x01\x01"
elif body["kind"] == "restart":
# B2 manual §10. A token receipt is not proof of a completed restart.
command = b"\x01\x07"
elif body["kind"] == "upload-configuration" and body.get("encoding") == "binary":
# Documented read-only counterpart to SERV*1.9; no image is written.
allowed.add("encoding")
command = b"\x01\x09"
elif body["kind"] in ("upload-configuration", "download-configuration"):
allowed.add("password")
password = body.get("password")
if not isinstance(password, str) or not re.fullmatch(r"[0-9]{6}", password):
raise ValueError("invalid password")
if set(body) - allowed:
raise ValueError("unknown action fields")
# B2 manual §10: synchronize with the configured web endpoint. Download
# may apply settings: the endpoint owns staged data and readback checks.
number = 9 if body["kind"] == "upload-configuration" else 8
return {"encoding": "text", "binary": f"{password}*SERV*1.{number}".encode().hex()}
elif body["kind"] == "set-output":
allowed |= {"pin", "enabled", "encoding", "password"}
pin = body.get("pin")
enabled = body.get("enabled")
if type(pin) is not int or pin not in (4, 5, 6):
raise ValueError("unsupported output")
if type(enabled) is not bool:
raise ValueError("enabled must be boolean")
if body.get("encoding", "text") != "text":
raise ValueError("set-output requires text encoding")
password = body.get("password")
if not isinstance(password, str) or not re.fullmatch(r"[0-9]{6}", password):
raise ValueError("invalid password")
if set(body) - allowed:
raise ValueError("unknown action fields")
# B2 manual section 10: explicit, persistent low-side output state.
# The caller must request both transitions; there is no implicit retry.
return {
"encoding": "text",
"binary": f"{password}*SERV*8.{pin}.{int(enabled)}".encode("ascii").hex(),
}
elif body["kind"] == "pulse-output":
allowed |= {"pin", "seconds", "encoding"}
pin, seconds = body["pin"], body["seconds"]
if type(pin) is not int or pin not in (4, 5, 6):
raise ValueError("unsupported output")
if type(seconds) is not int or not 1 <= seconds <= 5:
raise ValueError("pulse must be 1..5 seconds")
command = bytes((0x18, pin, 0, seconds))
encoding = body.get("encoding", "binary")
if encoding not in ("binary", "text"):
raise ValueError("unsupported action encoding")
if encoding == "text":
allowed.add("password")
password = body.get("password")
if not isinstance(password, str) or not re.fullmatch(r"[0-9]{6}", password):
raise ValueError("invalid password")
if set(body) - allowed:
raise ValueError("unknown action fields")
# B2 manual §10: FC text has no token envelope. A reply to an
# unrelated command must never turn this into confirmed actuation.
return {
"encoding": "text",
"binary": f"{password}*SERV*24.{pin}.0.{seconds}".encode("ascii").hex(),
}
else:
raise ValueError("unsupported action")
if set(body) - allowed:
raise ValueError("unknown action fields")
result = {"token": secrets.randbits(32), "binary": command.hex()}
if body["kind"] == "probe-diagnostic-mode":
result["observation_id"] = body["observation_id"]
return result
def frame(value):
if value.get("encoding") == "text":
raw = bytes.fromhex(value["binary"])
return bytes((0x7B, len(raw), 0xFC, sum(raw) % 256)) + raw + b"}"
raw = b"\xff" + value["token"].to_bytes(4, "little") + bytes.fromhex(value["binary"])
return bytes((0x7B, len(raw), 0xFF, sum(raw) % 256)) + raw + b"}"
def confirmations(raw):
offset = 2
while offset < len(raw) - 1:
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
if raw[offset] == 9 and size == 5:
yield raw[offset + 7], int.from_bytes(raw[offset + 8 : offset + 12], "little")
offset += size + 8
-585
View File
@@ -1,585 +0,0 @@
"""Durable allowlisted B2 operations; no firmware or arbitrary text commands."""
import hashlib
import json
import math
import re
import time
from . import actions, configuration, full_configuration, restart, sim_guard, sim_selection
from .delivery import MAX_DELIVERY_SECONDS
from .observation import Observation
from .transport_evidence import TransportEvidence
from .web_protocol import decode_request, numeric_id_reply, time_reply
COMMAND_SESSION_MAX_IDLE = 5
CONFIGURATION_KINDS = full_configuration.KINDS | {
"read-settings",
"configure-server1",
"upload-configuration",
"download-configuration",
}
def frame(text):
raw = text.encode("cp1251")
if not 1 <= len(raw) <= 255:
raise ValueError("command length")
return bytes((0x7B, len(raw), 0xFC, sum(raw) % 256)) + raw + b"}"
class Commands:
def __init__(self, store):
self.store = store
self.transport = TransportEvidence(store)
self.sim_guard = sim_guard.SimGuard(store)
self.sessions = {}
self.session_started = {}
self.session_activity = {}
self.session_peers = {}
self.session_ready = {}
with store.db() as db:
db.execute(
"CREATE TABLE IF NOT EXISTS commands(id TEXT PRIMARY KEY, imei TEXT NOT NULL, "
"digest TEXT NOT NULL, body TEXT NOT NULL)"
)
db.execute(
"CREATE INDEX IF NOT EXISTS commands_active "
"ON commands(imei,json_extract(body,'$.state'))"
)
# Effectful stages never replay. A committed full-image write may
# resume its independent readback within the original deadline.
for identifier, body in db.execute(
"SELECT id,body FROM commands "
"WHERE json_extract(body,'$.state') IN ('queued','dispatched')"
).fetchall():
value = json.loads(body)
value = self.settle(db, identifier, value)
if self.verification_recoverable(value):
self.recover_verification(value)
db.execute(
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
)
elif (
value["kind"] in actions.KINDS - {"request-position"}
and value["state"] == "queued"
):
value.update(state="expired", reason="host_restarted")
db.execute(
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
)
elif (
value["state"] == "dispatched"
or value.get("stage") in ("write", "verify", "restart")
and value["state"] == "queued"
):
value.update(state="uncertain", reason="host_restarted")
db.execute(
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
)
@staticmethod
def verification_recoverable(value):
return (
value["kind"] == "configure-all"
and value.get("stage") == "verify"
and bool(value.get("write_reply_sent_at"))
and value["state"] in ("queued", "dispatched")
)
@staticmethod
def recover_verification(value):
value.update(
state="queued",
recovery_verification=True,
recovery_at=time.time(),
recovery_count=value.get("recovery_count", 0) + 1,
not_before=max(value.get("not_before", 0), value.get("dispatched_at", 0) + 15),
)
value.pop("session", None)
def submit(self, body):
# The original absolute deadline survives a lost HTTP reply and retry.
# Keep it in the idempotency digest, outside the device command payload.
original = body
body = dict(body)
not_after = body.pop("not_after", None)
if not_after is not None and (
type(not_after) not in (int, float) or not math.isfinite(not_after) or not_after <= 0
):
raise ValueError("invalid command deadline")
identifier, imei = body["id"], body["imei"]
kind = body["kind"]
password = body.get("password", "")
if (
not re.fullmatch(r"[a-f0-9]{32}", identifier)
or kind
not in actions.KINDS | full_configuration.KINDS | {"read-settings", "configure-server1"}
or not self.store.admitted(imei)
):
raise ValueError("unsupported command")
if kind not in actions.KINDS and not re.fullmatch(r"[0-9]{6}", password):
raise ValueError("invalid password")
allowed = {"id", "imei", "password", "kind"}
details = {}
if kind in actions.KINDS:
details = actions.prepare(body)
allowed = set(body)
elif kind in full_configuration.KINDS:
details = full_configuration.prepare(body)
allowed = set(body)
elif kind == "configure-server1":
allowed |= {"expected", "target", "model", "firmware"}
if body.get("model") != 231 or body.get("firmware") != "0.01":
raise ValueError("unqualified firmware")
details = {
"expected": configuration.endpoint(body["expected"]),
"target": configuration.endpoint(body["target"]),
"stage": "preflight",
}
if set(body) - allowed:
raise ValueError("unknown command fields")
payload = password + "*GETP"
digest = hashlib.sha256(json.dumps(original, sort_keys=True).encode()).hexdigest()
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
previous = db.execute(
"SELECT digest,body FROM commands WHERE id=?", (identifier,)
).fetchone()
if previous:
if previous[0] != digest:
raise ValueError("idempotency conflict")
value = self.public(self.settle(db, identifier, json.loads(previous[1])))
value["transport"] = self.transport.read(db, identifier)
return value
if not_after is not None and not_after > time.time() + 600:
raise ValueError("command deadline too distant")
expired = not_after is not None and not_after <= time.time()
if (
not expired
and kind in (actions.KINDS | full_configuration.KINDS) - {"request-position"}
and not self.sessions.get(imei)
):
raise ValueError("device has no active session")
last_configuration_at = 0
for (encoded,) in db.execute("SELECT body FROM commands WHERE imei=?", (imei,)):
pending = json.loads(encoded)
if pending["kind"] in full_configuration.KINDS:
last_configuration_at = max(
last_configuration_at,
pending.get("configuration_received_at", 0),
pending.get("write_reply_sent_at", 0),
)
if not expired and self.active(db, imei):
raise ValueError("command already pending")
value = {
"id": identifier,
"kind": kind,
**details,
"state": "queued",
"payload": payload,
"password": password,
"created_at": time.time(),
"expires_at": time.time() + 120,
"replies": [],
"response_hashes": [],
}
if kind in actions.KINDS:
value.update(expires_at=time.time() + 30, dispatch_deadline=time.time() + 3)
if kind == "request-position":
# A read may wait for reconnection until its original expiry.
# Once dispatched it is never replayed, even after a crash.
value["dispatch_deadline"] = value["expires_at"]
if kind == "restart":
value["expires_at"] = time.time() + 180
value["allowed_sessions"] = list(self.sessions.get(imei, ()))
value.pop("payload")
value.pop("password")
elif kind in full_configuration.KINDS:
value["expires_at"] = time.time() + (360 if kind == "select-sim" else 180)
value["not_before"] = last_configuration_at + 15
if not_after is not None:
value["expires_at"] = min(value["expires_at"], not_after)
if "dispatch_deadline" in value:
value["dispatch_deadline"] = min(value["dispatch_deadline"], not_after)
if expired:
value.update(state="expired", reason="request_deadline")
elif kind == "probe-diagnostic-mode":
lease_end = Observation.diagnostic_lease(
db, value["observation_id"], identifier, bind_imei=imei
)
value["expires_at"] = min(value["expires_at"], lease_end)
value["dispatch_deadline"] = min(value["dispatch_deadline"], lease_end)
db.execute(
"INSERT INTO commands VALUES(?,?,?,?)",
(identifier, imei, digest, json.dumps(value)),
)
return self.public(value)
def settle(self, db, identifier, value):
state = self.public(value)["state"]
if state != value["state"]:
value = {**value, "state": state}
db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier))
return value
def active(self, db, imei):
# Terminal history never enters the per-packet/per-session hot path.
rows = db.execute(
"SELECT id,body FROM commands WHERE imei=? "
"AND json_extract(body,'$.state') IN ('queued','dispatched') ORDER BY rowid",
(imei,),
).fetchall()
result = []
for identifier, encoded in rows:
value = self.settle(db, identifier, json.loads(encoded))
if value["state"] in ("queued", "dispatched"):
result.append((identifier, value))
return result
def wait_delay(self, imei):
with self.store.db() as db:
# Idle senders sleep until admission, a packet or a new command.
# Active staged operations retain their existing bounded timers.
return 1 if self.active(db, imei) else None
@staticmethod
def public(value):
value = dict(value)
if (
value["state"] == "queued"
and value.get("dispatch_deadline", float("inf")) < time.time()
):
value["state"] = "expired"
if value["expires_at"] < time.time() and value["state"] in ("queued", "dispatched"):
value["state"] = (
"uncertain"
if value.get("write_reply_sent_at") or value.get("stage") == "restart"
else "expired"
if value["state"] == "queued"
else "unconfirmed"
)
hidden = {
"payload",
"password",
"before",
"after",
"response_hashes",
"session",
"binary",
"token",
"allowed_sessions",
"restart_sessions",
"target_configuration",
"before_configuration",
"sim_guard",
}
return {**{k: v for k, v in value.items() if k not in hidden}, "transport": []}
def get(self, identifier):
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT body FROM commands WHERE id=?", (identifier,)).fetchone()
if not row:
raise ValueError("unknown command")
value = self.public(self.settle(db, identifier, json.loads(row[0])))
value["transport"] = self.transport.read(db, identifier)
return value
def take(self, imei, session="test"):
delivery = self.take_delivery(imei, session)
return delivery[0] if delivery else None
def take_delivery(self, imei, session, *, with_receipt=False):
# A configuration reload can leave half-open old sockets beside the new
# live ones. Never let whichever sender wakes first steal the command.
active = tuple(self.sessions.get(imei, ()))
eligible = [s for s in active if self.session_ready.get((imei, s), True)]
if active and session not in eligible:
return None
observed = [s for s in eligible if (imei, s) in self.session_activity]
if observed and session != max(
observed, key=lambda s: (self.session_activity.get((imei, s), 0), s)
):
return None
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
for identifier, value in self.active(db, imei):
if (
self.verification_recoverable(value)
and value["state"] == "dispatched"
and session != value.get("session")
and self.session_started.get((imei, session), 0) > value.get("monotonic", 0)
):
# A new B2 connection can outlive a half-open predecessor.
# Only the independent read migrates, never the image write.
self.recover_verification(value)
db.execute(
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
)
if (
value["state"] == "queued"
and value.get("dispatch_deadline", float("inf")) < time.time()
):
value["state"] = "expired"
db.execute(
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
)
continue
if (
value["kind"] == "configure-server1"
and value.get("stage") == "write"
and value["state"] == "dispatched"
and time.time() - value["dispatched_at"] >= 15
):
# SETP may reconnect before its reply. Read-only verification can
# move to a new TCP session; the write itself is never resent.
value.update(stage="verify", state="queued")
value.pop("session", None)
if (
value["state"] != "queued"
or value["expires_at"] < time.time()
or value.get("not_before", 0) > time.time()
):
continue
if value.get("session") and value["session"] != session:
continue
if (
value["kind"] in actions.KINDS - {"request-position"}
and session not in value["allowed_sessions"]
):
continue
if value["kind"] == "request-position" and session not in active:
continue
if value["kind"] in CONFIGURATION_KINDS and active:
last_input = self.session_activity.get((imei, session))
if last_input is None or not (
0 <= time.monotonic() - last_input <= COMMAND_SESSION_MAX_IDLE
):
# A drained but silent TCP stream may already be dead.
# Await fresh device input; retain the original deadline
# and never replay a previously dispatched stage.
continue
if not self.store.admitted(imei):
return None
if value["kind"] == "probe-diagnostic-mode":
try:
Observation.diagnostic_lease(db, value["observation_id"], identifier)
except ValueError:
value.update(state="expired", reason="observation_closed")
db.execute(
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
)
continue
if value.get("sim_guard") and value.get("stage") in ("write", "restart"):
guard = self.sim_guard.check(imei, value["sim_guard"], db=db)
if guard != "matched":
if guard == "changed":
value.update(state="rejected", reason="sim_card_changed")
db.execute(
"UPDATE commands SET body=? WHERE id=?",
(json.dumps(value), identifier),
)
continue
value.update(
state="dispatched",
dispatched_at=time.time(),
monotonic=time.monotonic(),
session=session,
)
restarting = value["kind"] == "restart" or (
value["kind"] == "select-sim" and value.get("stage") == "restart"
)
if restarting:
value["restart_sessions"] = list(self.sessions.get(imei, ()))
if value["kind"] == "configure-server1":
value["payload"] = configuration.payload(value)
if value["stage"] == "write":
value["write_dispatched_at"] = time.time()
elif value["kind"] in full_configuration.KINDS and not restarting:
value["payload"] = full_configuration.payload(value)
db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier))
data = (
actions.frame(value)
if value["kind"] in actions.KINDS or restarting
else frame(value["payload"])
)
deadline = value["monotonic"] + min(
MAX_DELIVERY_SECONDS, max(0, value["expires_at"] - value["dispatched_at"])
)
if with_receipt:
ticket = self.transport.prepare(db, identifier, value.get("stage", "execute"))
return data, deadline, ticket
return data, deadline
return None
def web_receive(self, raw, peer, *, with_deadline=False):
"""Qualified B2 HTTP channel, scoped to an admitted active modem peer."""
expires = time.time() + 12
def result(reply):
if reply is None or not with_deadline:
return reply
return reply, time.monotonic() + max(0, expires - time.time())
imei, command, payload = decode_request(raw)
if not self.store.admitted(imei) or not any(
self.session_peers.get((imei, s)) == peer for s in tuple(self.sessions.get(imei, ()))
):
return None
reply = bytes.fromhex("5b00030006025d") if command == 6 else None
if command == 1:
number = self.store.numeric_id(imei)
return result(numeric_id_reply(number) if number is not None else None)
if command == 7:
# A clock request is independent of a settings transaction. It
# cannot advance its stage, confirm a write or extend its deadline.
return result(time_reply(int(time.time())))
if command == 5:
reply = bytes.fromhex("5b00030005015d")
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
for identifier, value in self.active(db, imei):
if (
value["kind"] not in full_configuration.KINDS
or value["state"] != "dispatched"
or value["expires_at"] <= time.time()
):
continue
if command == 5 and value["stage"] in ("preflight", "verify"):
full_configuration.upload(value, payload)
elif command == 2 and value["stage"] == "write":
guard = self.sim_guard.check(imei, value.get("sim_guard"), db=db)
if guard != "matched":
# No image bytes leave the process for a missing/replaced card.
value.update(
state="rejected" if guard == "changed" else "unconfirmed",
reason="sim_card_changed"
if guard == "changed"
else "sim_identity_unavailable",
)
reply = None
else:
reply = full_configuration.download(value)
else:
continue
expires = min(expires, value["expires_at"])
db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier))
break
return result(reply)
def receive(self, imei, raw, session="test"):
self.sim_guard.observe(imei, raw)
self.receive_actions(imei, raw, session)
started = self.session_started.get((imei, session))
if started is not None:
with self.store.db(write=True) as db:
for identifier, value in self.active(db, imei):
matched = (
self.sim_guard.check(
imei, value.get("sim_guard"), after=value.get("dispatched_at"), db=db
)
== "matched"
)
if (
restart.observe(value, raw, session, started)
or matched
and sim_selection.observe(value, raw, session, started)
):
if value.get("sim_guard") and value["state"] == "sim_selected":
value["sim_guard_verified"] = True
db.execute(
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
)
# Preserve text response evidence privately, never interpret receipt as settings applied.
offset, replies = 2, []
while offset < len(raw) - 1:
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
if raw[offset] == 3:
replies.append(
(
int.from_bytes(raw[offset + 3 : offset + 7], "little"),
raw[offset + 7 : offset + 7 + size].decode("cp1251", errors="replace"),
)
)
offset += size + 8
if not replies:
return
with self.store.db(write=True) as db:
for identifier, value in self.active(db, imei):
if (
value["kind"] in actions.KINDS | full_configuration.KINDS
or value["state"] != "dispatched"
or value["expires_at"] < time.time()
or value.get("session") != session
):
continue
accepted = []
for measured, reply in replies:
digest = hashlib.sha256(f"{measured}:{reply}".encode()).hexdigest()
if (
# This B2 timestamps text about 4 s behind the VPS clock.
# Bound skew and require strictly newer evidence at every stage.
measured < int(value["dispatched_at"]) - 10
or measured > time.time() + 5
or measured <= value.get("last_response_measured", 0)
or digest in value.get("response_hashes", [])
):
continue
value.setdefault("response_hashes", []).append(digest)
if value["kind"] == "configure-server1":
if configuration.response(value, reply, self.store.config["tracker"]):
accepted.append(reply)
break # Never use two messages from one packet for separate stages.
elif reply.startswith("#1="):
accepted.append(reply)
if not accepted:
continue
value["last_response_measured"] = measured
if value["kind"] == "read-settings":
value.update(state="reply_received", replies=accepted)
elif value["stage"] == "verify" and value["state"] == "queued":
value.pop("session", None)
value["not_before"] = max(
value.get("not_before", 0), value["write_dispatched_at"] + 15
)
value.update(received_at=time.time())
db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier))
def receive_actions(self, imei, raw, session):
replies = list(actions.confirmations(raw))
# B2 publishes the same token receipt through both monitoring streams.
# Correlate the device and token, not the socket that carried the request.
# Text commands still have no such correlation and are excluded below.
if (
not replies
or session not in self.sessions.get(imei, ())
or not self.store.admitted(imei)
):
return
with self.store.db(write=True) as db:
for identifier, value in self.active(db, imei):
if (
value["kind"] not in actions.KINDS
or value.get("encoding") == "text"
or value["state"] != "dispatched"
or value["expires_at"] < time.time()
):
continue
for code, token in replies:
if token != value["token"] or code > 9:
continue
value.update(
received_at=time.time(),
roundtrip_seconds=time.monotonic() - value["monotonic"],
device_code=code,
reply_via_alternate_session=session != value.get("session"),
)
if code == 6 or value["kind"] == "restart" and code == 0:
value.setdefault("device_accepted_at", time.time())
else:
value["state"] = "device_confirmed" if code == 0 else "device_rejected"
db.execute(
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
)
break
-85
View File
@@ -1,85 +0,0 @@
"""B2 231 / 0.01: documented SETP #1 only, with a surviving secondary uplink.
Never translate USB field numbers into SETP groups. No generic command escape.
GETP contains secrets; only the explicit endpoint projection may reach Core UI.
"""
import re
import time
def endpoint(value):
if not isinstance(value, dict) or set(value) != {"host", "port"}:
raise ValueError("invalid endpoint")
host, port = value["host"], value["port"]
if (
not isinstance(host, str)
or not 1 <= len(host) <= 32
or not re.fullmatch(r"[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*", host)
or type(port) is not int
or not 1 <= port <= 65535
):
raise ValueError("invalid endpoint")
return {"host": host, "port": port}
def groups(reply):
if not isinstance(reply, str) or not reply.startswith("#") or len(reply) > 4096:
raise ValueError("invalid GETP")
result = {}
for part in reply.split("#")[1:]:
key, sep, value = part.partition("=")
if not sep or not key.isdecimal() or key in result:
raise ValueError("invalid GETP group")
result[key] = value
if not {"1", "2", "5", "7", "26"} <= result.keys():
raise ValueError("incomplete GETP")
return result
def server(value):
parts = value.split(",")
# Preserve the undocumented fifth value, accept only the qualified empty form.
if len(parts) != 5 or parts[2:] != ["0", "0", ""]:
raise ValueError("unsupported server settings")
return endpoint({"host": parts[0], "port": int(parts[1])})
def response(operation, reply, tracker):
"""Advance only from complete, scoped read evidence. Caller persists atomically."""
try:
actual = groups(reply)
primary, secondary = server(actual["1"]), server(actual["26"])
except (ValueError, KeyError):
return False
stage = operation["stage"]
if stage == "preflight":
if primary != operation["expected"] or secondary != endpoint(tracker):
operation.update(state="rejected", reason="configuration_changed")
elif primary == operation["target"]:
operation.update(state="verified", verified_at=time.time(), server1=primary)
else:
operation.update(before=actual, stage="write", state="queued")
elif stage == "write":
# SETP acknowledgement is never enough: issue a separate GETP after a drain interval.
operation.update(stage="verify", state="queued", not_before=time.time() + 3)
elif stage == "verify":
before = operation["before"]
preserved = {k: v for k, v in actual.items() if k != "1"} == {
k: v for k, v in before.items() if k != "1"
}
operation["after"] = actual
if primary == operation["target"] and preserved:
operation.update(state="verified", verified_at=time.time(), server1=primary)
elif actual == before:
operation.update(state="not_applied", reason="settings_unchanged")
else:
operation.update(state="uncertain", reason="readback_mismatch")
return True
def payload(operation):
if operation["stage"] == "write":
target = operation["target"]
return f"{operation['password']}*SETP*#1={target['host']},{target['port']}"
return operation["password"] + "*GETP"
-109
View File
@@ -1,109 +0,0 @@
"""Bound the lifetime of command bytes in a Linux TCP send queue.
TCP acknowledgement is transport evidence only, never command confirmation.
All writes on the guarded stream must pass through write(), including ACKs.
"""
import asyncio
import fcntl
import socket
import struct
import sys
import termios
import time
from collections import deque
MAX_DELIVERY_SECONDS = 30
def queued_bytes(sock):
if sys.platform != "linux":
# Production is qualified on Ubuntu only. Other platforms conservatively
# retain the deadline, without claiming TCP acknowledgement evidence.
return None
return struct.unpack("i", fcntl.ioctl(sock, termios.TIOCOUTQ, struct.pack("i", 0)))[0]
class Delivery:
def __init__(self, writer):
self.writer = writer
self.sock = writer.get_extra_info("socket")
# Also abort queued kernel data on EOF, task cancellation and shutdown.
# transport.abort() alone discards only asyncio's own write buffer.
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
if sys.platform == "linux":
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT, 30000)
self.written = 0
self.pending = deque()
self.timer = None
def ready(self):
"""Do not enqueue a new command behind an unacknowledged stream prefix.
This is Linux transport admission, not device execution confirmation.
Non-Linux engineering tests retain their conservative expiry watchdog.
"""
if self.writer.is_closing() or self.writer.transport.get_write_buffer_size():
return False
try:
queued = queued_bytes(self.sock)
return queued is None or queued == 0
except OSError:
return False
def write(self, data, deadline=None, observe=None):
started = time.monotonic()
def note(phase, reason=None):
if observe is not None:
observe(phase, time.time(), time.monotonic() - started, reason)
if deadline is not None and deadline <= time.monotonic():
note("unconfirmed", "expired_before_write")
self.abort()
raise TimeoutError("command delivery expired before write")
try:
self.writer.write(data)
except (OSError, RuntimeError):
note("unconfirmed", "write_failed")
raise
note("written")
self.written += len(data)
if deadline is not None:
self.pending.append((self.written, deadline, note))
self.check()
def check(self):
self.cancel_timer()
if not self.pending:
return
if self.writer.is_closing():
self.abort()
return
try:
queued = queued_bytes(self.sock)
if queued is not None:
acknowledged = self.written - queued - self.writer.transport.get_write_buffer_size()
while self.pending and self.pending[0][0] <= acknowledged:
self.pending.popleft()[2]("tcp_acknowledged")
if self.pending:
remaining = min(deadline for _, deadline, _ in self.pending) - time.monotonic()
if remaining <= 0:
self.abort("delivery_deadline")
else:
self.timer = asyncio.get_running_loop().call_later(
min(0.25, remaining), self.check
)
except OSError:
self.abort("socket_error")
def cancel_timer(self):
if self.timer is not None:
self.timer.cancel()
self.timer = None
def abort(self, reason="connection_closed"):
self.cancel_timer()
while self.pending:
self.pending.popleft()[2]("unconfirmed", reason)
self.writer.transport.abort()
-113
View File
@@ -1,113 +0,0 @@
"""Whole-image B2 transactions: fresh preflight, one write, independent readback."""
import hashlib
import re
import time
from . import sim_guard, sim_selection
from .usb_protocol import decode_configuration
from .web_protocol import settings_reply
KINDS = {"read-configuration", "configure-all", "select-sim"}
def prepare(body):
allowed = {"id", "imei", "kind", "password", "model", "firmware"}
if body.get("model") != 231 or body.get("firmware") != "0.01":
raise ValueError("unqualified configuration firmware")
result = {"stage": "preflight"}
if body["kind"] in ("configure-all", "select-sim"):
allowed |= {"expected_sha256", "target_configuration"}
if not re.fullmatch(r"[a-f0-9]{64}", body["expected_sha256"]):
raise ValueError("invalid predecessor")
raw = bytes.fromhex(body["target_configuration"])
config = decode_configuration(raw)
settings_reply(config) # transport-size admission, without a write
result.update(expected_sha256=body["expected_sha256"], target_configuration=raw.hex())
if "sim_guard" in body:
allowed.add("sim_guard")
result["sim_guard"] = sim_guard.prepare(body["sim_guard"])
if body["kind"] != "select-sim" or body.get("sim_slot") != result["sim_guard"]["slot"]:
raise ValueError("SIM guard requires exclusive selection of the same slot")
if body["kind"] == "select-sim":
allowed |= {"sim_slot", "sim_policy"}
mask = (1 << 10) | (1 << 20)
policy = body.get("sim_policy", "exclusive")
if policy == "both":
if "sim_slot" in body or config.integer(72, 4) & mask:
raise ValueError("both SIMs must be permitted without an exclusive slot")
result["sim_policy"] = policy
elif policy == "exclusive":
slot = body.get("sim_slot")
if type(slot) is not int or slot not in (1, 2):
raise ValueError("invalid SIM slot")
if config.integer(72, 4) & mask != 1 << (20 if slot == 1 else 10):
raise ValueError("SIM flags do not match requested slot")
result["sim_slot"] = slot
else:
raise ValueError("invalid SIM policy")
if set(body) - allowed:
raise ValueError("unknown configuration fields")
return result
def payload(value):
number = 8 if value["stage"] == "write" else 9
return value["password"] + f"*SERV*1.{number}"
def upload(value, raw):
config = decode_configuration(raw)
digest = hashlib.sha256(raw).hexdigest()
value.update(
configuration=raw.hex(), configuration_sha256=digest, configuration_received_at=time.time()
)
if value["kind"] == "read-configuration":
value.update(state="observed", verified_at=time.time())
elif value["stage"] == "preflight":
value["before_configuration"] = raw.hex()
target = decode_configuration(bytes.fromhex(value["target_configuration"]))
# Preserve every unknown field and the recovery channels. Core controls
# the reviewed profile fields; network migration of these requires its
# own destination-admission transaction, not a blind full-image write.
critical = (3, 4, 5, 8, 70, 71)
if (
digest != value["expected_sha256"]
or [r.number for r in config.records] != [r.number for r in target.records]
or any(config.value(n) != target.value(n) for n in critical)
):
value.update(state="rejected", reason="configuration_predecessor_mismatch")
elif raw.hex() == value["target_configuration"]:
value.update(state="verified", verified_at=time.time(), unchanged=True)
if value["kind"] == "select-sim":
sim_selection.queue_restart(value)
else:
value.update(state="queued", stage="write", not_before=time.time() + 15)
value.pop("session", None)
elif value["stage"] == "verify":
state = (
"verified"
if raw.hex() == value["target_configuration"]
else "not_applied"
if raw.hex() == value["before_configuration"]
else "uncertain"
)
value.update(state=state, verified_at=time.time())
if state == "verified" and value["kind"] == "select-sim":
sim_selection.queue_restart(value)
def download(value):
"""Call only inside the durable transaction, before writing the HTTP socket."""
if value.get("write_reply_sent_at"):
return None
raw = settings_reply(decode_configuration(bytes.fromhex(value["target_configuration"])))
value.update(
write_reply_sent_at=time.time(),
write_reply_sha256=hashlib.sha256(raw).hexdigest(),
stage="verify",
state="queued",
not_before=time.time() + 15,
)
value.pop("session", None)
return raw
-246
View File
@@ -1,246 +0,0 @@
"""Explicit, bounded interoperability evidence on the owned socket.
Disabled unless the authenticated owner arms a 180-second lease. Unknown traffic
is never treated as telemetry. A captured identity reply may be replayed once,
only to the byte-identical request of an admitted device. No vendor connection.
"""
import hashlib
import json
import re
import time
from .web_protocol import decode_request, decode_settings_reply
class Observation:
@staticmethod
def diagnostic_lease(db, identifier, command_id, *, bind_imei=None):
"""One fixed diagnostic command per explicitly armed evidence window.
Expiry bounds our dispatch/capture, not the device's service mode.
No repeated toggle, arbitrary payload, or automatic device restart.
"""
if not db.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='observations'"
).fetchone():
raise ValueError("diagnostic observation unavailable")
row = db.execute("SELECT body FROM observations WHERE id=?", (identifier,)).fetchone()
if not row:
raise ValueError("diagnostic observation unavailable")
value = json.loads(row[0])
if value["expires_at"] <= time.time() or value.get("reference"):
raise ValueError("diagnostic observation unavailable")
bound = value.get("diagnostic_command_id")
if bound not in (None, command_id) or bind_imei is None and bound != command_id:
raise ValueError("diagnostic observation already used")
if bind_imei is not None:
value.update(diagnostic_command_id=command_id, diagnostic_imei=bind_imei)
db.execute("UPDATE observations SET body=? WHERE id=?", (json.dumps(value), identifier))
return value["expires_at"]
def __init__(self, store):
self.store = store
with store.db() as db:
db.execute("CREATE TABLE IF NOT EXISTS observations(id TEXT PRIMARY KEY, body TEXT)")
db.execute(
"CREATE TABLE IF NOT EXISTS observation_data(lease TEXT, sequence INTEGER, "
"raw BLOB, metadata TEXT, PRIMARY KEY(lease,sequence))"
)
def arm(self, body):
if set(body) not in ({"id"}, {"id", "reference"}) or not re.fullmatch(
r"[a-f0-9]{32}", body["id"]
):
raise ValueError("invalid observation")
reference = body.get("reference")
if "reference" in body:
if not isinstance(reference, dict) or set(reference) != {"request", "response"}:
raise ValueError("invalid reference")
request = bytes.fromhex(reference["request"])
response = bytes.fromhex(reference["response"])
imei, command, _ = decode_request(request, observe_empty_check=True)
if not self.store.admitted(imei):
raise ValueError("unqualified reference exchange")
if command == 6 and response == bytes.fromhex("5b00030006025d"):
pass
elif command == 1 and (
response == bytes.fromhex("5b000200015d")
or (
len(response) == 10
and response[:5] == bytes.fromhex("5b00060001")
and response[-1:] == b"]"
and int.from_bytes(response[5:9], "big") > 0
)
):
# The captured four-byte response equals the bench's numeric
# device ID. Qualify its exact replay once; no image payload.
pass
elif command == 2:
if response != bytes.fromhex("5b000200025d"):
decode_settings_reply(response)
# Bounded qualification of a zero-payload no-image response.
# Not admitted in the normal product channel until physically
# verified; no CRC image or device configuration is supplied.
elif command == 5 and response == bytes.fromhex("5b00030005015d"):
# Byte-exact command-5 reply captured from the manufacturer
# for the owner-approved return of its own configuration.
pass
else:
raise ValueError("unqualified reference exchange")
now = time.time()
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
if db.execute("SELECT 1 FROM observations WHERE id=?", (body["id"],)).fetchone():
previous = json.loads(
db.execute(
"SELECT body FROM observations WHERE id=?", (body["id"],)
).fetchone()[0]
)
if previous.get("reference") != reference:
raise ValueError("observation idempotency conflict")
return self.get(body["id"])
if any(
json.loads(r[0])["expires_at"] > now
for r in db.execute("SELECT body FROM observations")
):
raise ValueError("observation already armed")
if db.execute("SELECT COUNT(*) FROM observations").fetchone()[0] >= 64:
raise ValueError("observation evidence capacity reached")
value = {"id": body["id"], "created_at": now, "expires_at": now + 180}
if reference is not None:
value["reference"] = reference
db.execute("INSERT INTO observations VALUES(?,?)", (body["id"], json.dumps(value)))
return self.get(body["id"])
def get(self, identifier):
with self.store.db() as db:
row = db.execute("SELECT body FROM observations WHERE id=?", (identifier,)).fetchone()
if not row:
raise ValueError("unknown observation")
value = json.loads(row[0])
value.pop("reference", None)
value.pop("diagnostic_imei", None)
value["captures"] = [
json.loads(r[0])
for r in db.execute(
"SELECT metadata FROM observation_data WHERE lease=? ORDER BY sequence",
(identifier,),
)
]
return value
def close(self, identifier):
"""Disarm without deleting private evidence or retrying a dispatch."""
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT body FROM observations WHERE id=?", (identifier,)).fetchone()
if not row:
raise ValueError("unknown observation")
value = json.loads(row[0])
value["expires_at"] = min(value["expires_at"], time.time())
db.execute("UPDATE observations SET body=? WHERE id=?", (json.dumps(value), identifier))
return self.get(identifier)
def reply(self, ticket, raw):
"""Persist one dispatch before writing, including across service restarts."""
request = http_body(raw)
if request is None:
return None
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT body FROM observations WHERE id=?", (ticket[0],)).fetchone()
if not row:
return None
value = json.loads(row[0])
reference = value.get("reference")
if (
not reference
or value["expires_at"] <= time.time()
or value.get("reply_dispatched_at")
or request != bytes.fromhex(reference["request"])
or not self.store.admitted(str(int.from_bytes(request[4:12], "little")))
or not db.execute(
"SELECT 1 FROM observation_data WHERE lease=? AND sequence=?", ticket
).fetchone()
):
return None
response = bytes.fromhex(reference["response"])
value.update(
reply_dispatched_at=time.time(),
reply_monotonic=time.monotonic(),
reply_sha256=hashlib.sha256(response).hexdigest(),
reply_sequence=ticket[1],
)
db.execute("UPDATE observations SET body=? WHERE id=?", (json.dumps(value), ticket[0]))
return response
def claim(self):
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
for identifier, body in db.execute("SELECT id,body FROM observations"):
if json.loads(body)["expires_at"] <= time.time():
continue
sequence = db.execute(
"SELECT COUNT(*) FROM observation_data WHERE lease=?", (identifier,)
).fetchone()[0]
if sequence >= 4:
return None
metadata = {
"sequence": sequence,
"started_at": time.time(),
"monotonic": time.monotonic(),
"state": "receiving",
}
db.execute(
"INSERT INTO observation_data VALUES(?,?,?,?)",
(identifier, sequence, b"", json.dumps(metadata)),
)
return identifier, sequence
return None
def finish(self, ticket, raw, events):
if len(raw) > 16384:
raise ValueError("observation limit")
with self.store.db() as db:
row = db.execute(
"SELECT metadata FROM observation_data WHERE lease=? AND sequence=?", ticket
).fetchone()
if not row:
raise ValueError("unknown capture")
value = json.loads(row[0])
value.update(
state="captured",
completed_at=time.time(),
bytes=len(raw),
sha256=hashlib.sha256(raw).hexdigest(),
events=events,
)
db.execute(
"UPDATE observation_data SET raw=?,metadata=? WHERE lease=? AND sequence=?",
(raw, json.dumps(value), *ticket),
)
def http_body(raw):
"""First complete, bounded B2 POST only; reject ambiguous HTTP framing."""
header, separator, body = raw.partition(b"\r\n\r\n")
if not separator or len(header) > 2048:
return None
lines = header.split(b"\r\n")
if lines[0] != b"POST /c/index.php HTTP/1.1":
return None
headers = {}
for line in lines[1:]:
key, colon, value = line.partition(b":")
key = key.lower()
if not colon or key in headers:
return None
headers[key] = value.strip()
size = headers.get(b"content-length", b"")
if b"transfer-encoding" in headers or not size.isdigit():
return None
size = int(size)
if not 1 <= size <= 16384 or len(body) < size:
return None
return bytes(body[:size])
-492
View File
@@ -1,492 +0,0 @@
"""Durable tracker-maintenance intents; bounded attempts belong to Commands.
An outage ends an attempt, not its owning intent. No downstream output action
is admitted here. State changes reconcile the actual B2 image before retrying.
"""
import hashlib
import json
import re
import threading
import time
import uuid
from . import actions, full_configuration, sim_selection
KINDS = {"request-position", "restart", "read-configuration", "configure-all", "select-sim"}
PENDING = {"queued", "dispatched"}
RETRY = {"expired", "unconfirmed", "uncertain", "not_applied"}
FACTS = {
"transport",
"stage",
"dispatched_at",
"received_at",
"device_accepted_at",
"device_code",
"roundtrip_seconds",
"reconnected_at",
"reconnect_seconds",
"verified_at",
"configuration",
"configuration_sha256",
"configuration_received_at",
"write_reply_sent_at",
"active_sim",
"telemetry_measured_at",
"unchanged",
"sim_guard_verified",
}
class Operations:
def __init__(self, store, commands):
self.store, self.commands = store, commands
# Only local SQLite work under this lock; never sockets, sleeps or device I/O.
self.lock = threading.RLock()
with store.db() as db:
db.executescript("""
CREATE TABLE IF NOT EXISTS operations(
seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT UNIQUE NOT NULL,
imei TEXT NOT NULL,state TEXT NOT NULL,digest TEXT NOT NULL,body TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS operations_pending ON operations(imei,state,seq);
CREATE TABLE IF NOT EXISTS operation_attempts(
operation TEXT NOT NULL,number INTEGER NOT NULL,id TEXT UNIQUE NOT NULL,
body TEXT NOT NULL,PRIMARY KEY(operation,number));
CREATE TABLE IF NOT EXISTS operation_modem(
imei TEXT PRIMARY KEY,body TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS operation_stops(id TEXT PRIMARY KEY,kind TEXT NOT NULL);
""")
def save(self, value):
with self.store.db() as db:
encoded = json.dumps(value)
db.execute(
"UPDATE operations SET state=?,body=? WHERE id=? AND body<>?",
(value["state"], encoded, value["id"], encoded),
)
def submit(self, body):
body = dict(body)
if (
not re.fullmatch(r"[a-f0-9]{32}", body.get("id", ""))
or body.get("kind") not in KINDS
or not self.store.admitted(body.get("imei"))
):
raise ValueError("unsupported operation")
if body["kind"] in full_configuration.KINDS:
if not re.fullmatch(r"[0-9]{6}", body.get("password", "")):
raise ValueError("invalid password")
full_configuration.prepare(body)
else:
actions.prepare(body)
digest = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
with self.lock, self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
stopped = db.execute(
"SELECT kind FROM operation_stops WHERE id=?", (body["id"],)
).fetchone()
if stopped:
return {
"id": body["id"],
"kind": stopped[0],
"state": "stopped",
"durable": True,
"runtime_phase": "stopped",
"stop_requested": True,
"attempt_count": 0,
}
old = db.execute(
"SELECT digest,body FROM operations WHERE id=?", (body["id"],)
).fetchone()
if old:
if old[0] != digest:
raise ValueError("idempotency conflict")
return self.public(json.loads(old[1]))
count = db.execute(
"SELECT count(*) FROM operations WHERE imei=? AND state IN ('queued','dispatched')",
(body["imei"],),
).fetchone()[0]
if count >= 32:
raise ValueError("operation queue full")
value = {
"id": body["id"],
"imei": body["imei"],
"kind": body["kind"],
"request": body,
"created_at": time.time(),
"state": "queued",
"runtime_phase": "waiting-link",
"attempt_count": 0,
"next_attempt_at": 0,
"phase": "execute",
"result": {},
}
db.execute(
"INSERT INTO operations(id,imei,state,digest,body) VALUES(?,?,?,?,?)",
(body["id"], body["imei"], value["state"], digest, json.dumps(value)),
)
return self.public(value)
@staticmethod
def public(value):
result = {k: v for k, v in value.get("result", {}).items() if k in FACTS}
result.update(
{
k: value[k]
for k in (
"id",
"kind",
"state",
"created_at",
"attempt_count",
"runtime_phase",
"next_attempt_at",
"stop_requested",
"reason",
)
if k in value
}
)
result["durable"] = True
if value.get("attempt"):
result["attempt_id"] = value["attempt"]["id"]
result["attempt_expires_at"] = value["attempt"]["not_after"]
return result
def pending(self, imei):
with self.store.db() as db:
return (
db.execute(
"SELECT 1 FROM operations WHERE imei=? AND state IN "
"('queued','dispatched') LIMIT 1",
(imei,),
).fetchone()
is not None
)
def fresh(self, imei):
return any(
0 <= time.monotonic() - self.commands.session_activity.get((imei, s), 0) <= 30
for s in tuple(self.commands.sessions.get(imei, ()))
)
def wait_delay(self, imei):
with self.store.db() as db:
row = db.execute(
"SELECT body FROM operations WHERE imei=? AND state IN "
"('queued','dispatched') ORDER BY seq LIMIT 1",
(imei,),
).fetchone()
if not row:
return None
value = json.loads(row[0])
if value.get("attempt"):
return 1
return max(1, value["next_attempt_at"] - time.time()) if self.fresh(imei) else None
def get(self, identifier):
with self.store.db() as db:
row = db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()
if not row:
with self.store.db() as db:
stopped = db.execute(
"SELECT kind FROM operation_stops WHERE id=?", (identifier,)
).fetchone()
if stopped:
return {
"id": identifier,
"kind": stopped[0],
"state": "stopped",
"durable": True,
"runtime_phase": "stopped",
"stop_requested": True,
"attempt_count": 0,
}
raise ValueError("unknown operation")
self.advance(json.loads(row[0])["imei"])
with self.store.db() as db:
value = json.loads(
db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()[0]
)
result = self.public(value)
attempt = value.get("attempt", value.get("result", {})).get("id")
if attempt:
result["transport"] = self.commands.transport.read(db, attempt)
return result
def cancel(self, identifier, kind=None):
if not re.fullmatch(r"[a-f0-9]{32}", identifier):
raise ValueError("invalid operation identity")
with self.lock, self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()
if not row:
if kind not in KINDS:
raise ValueError("unknown operation")
db.execute("INSERT OR IGNORE INTO operation_stops VALUES(?,?)", (identifier, kind))
return {
"id": identifier,
"kind": kind,
"state": "stopped",
"durable": True,
"runtime_phase": "stopped",
"stop_requested": True,
"attempt_count": 0,
}
value = json.loads(row[0])
if value["state"] in PENDING:
value["stop_requested"] = True
if not value.get("attempt"):
value.update(state="stopped", runtime_phase="stopped")
db.execute(
"UPDATE operations SET state=?,body=? WHERE id=?",
(value["state"], json.dumps(value), identifier),
)
return self.get(identifier)
def history(self, identifier, before=2**63 - 1):
with self.store.db() as db:
rows = db.execute(
"SELECT number,body FROM operation_attempts WHERE operation=? "
"AND number<? ORDER BY number DESC LIMIT 21",
(identifier, before),
).fetchall()
items = [json.loads(r[1]) for r in rows[:20]]
for item in items:
# Transport observations may be persisted just after the device
# reply already completed this attempt. Read their current facts.
item["transport"] = self.commands.transport.read(db, item["id"])
return {
"items": items,
"next_before": rows[19][0] if len(rows) > 20 else None,
}
def note_attempt(self, value, result):
item = {k: result[k] for k in FACTS - {"configuration"} if k in result}
item.update(
id=value["attempt"]["id"],
number=value["attempt_count"],
phase=value["phase"],
state=result["state"],
)
with self.store.db() as db:
old = db.execute(
"SELECT body FROM operation_attempts WHERE id=?", (item["id"],)
).fetchone()
if old:
previous = json.loads(old[0])
previous.pop("observed_at", None)
if previous == item:
return
item["observed_at"] = time.time()
db.execute(
"INSERT INTO operation_attempts VALUES(?,?,?,?) ON CONFLICT(operation,number) "
"DO UPDATE SET body=excluded.body",
(value["id"], value["attempt_count"], item["id"], json.dumps(item)),
)
def observe(self, imei, raw):
offset = 2
while offset < len(raw) - 1:
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
payload = raw[offset + 7 : offset + 7 + size]
if raw[offset] == 1 and 0 <= time.time() - measured <= 30:
for index in range(0, len(payload) - 4, 5):
if payload[index] != 99:
continue
ds2 = int.from_bytes(payload[index + 1 : index + 5], "little")
value = {
"active_sim": 1 + ((ds2 >> 5) & 1),
"gprs": (ds2 >> 2) & 7,
"measured_at": measured,
}
with self.store.db() as db:
db.execute(
"INSERT INTO operation_modem VALUES(?,?) ON CONFLICT(imei) "
"DO UPDATE SET body=excluded.body WHERE "
"json_extract(excluded.body, '$.measured_at') >= "
"json_extract(operation_modem.body, '$.measured_at')",
(imei, json.dumps(value)),
)
offset += size + 8
def selected(self, value):
if (
self.commands.sim_guard.check(
value["imei"], value["request"].get("sim_guard"), after=value["created_at"]
)
!= "matched"
):
return None
with self.store.db() as db:
row = db.execute(
"SELECT body FROM operation_modem WHERE imei=?", (value["imei"],)
).fetchone()
data = json.loads(row[0]) if row else {}
return (
data
if sim_selection.matches(value["request"], data.get("active_sim"))
and data.get("gprs") == 4
and data.get("measured_at", 0) > value["created_at"]
and 0 <= time.time() - data["measured_at"] <= 30
else None
)
def reconcile(self, value, result):
request = value["request"]
digest = result.get("configuration_sha256")
target = hashlib.sha256(bytes.fromhex(request["target_configuration"])).hexdigest()
if digest == target:
if value["kind"] == "configure-all":
value.update(state="verified", runtime_phase="complete", result=result)
elif selected := self.selected(value):
value.update(
state="sim_selected",
runtime_phase="complete",
result={
**result,
"active_sim": selected["active_sim"],
"telemetry_measured_at": selected["measured_at"],
"sim_guard_verified": bool(request.get("sim_guard")),
},
)
else:
value.update(phase="execute", retry_predecessor=target)
elif digest == request["expected_sha256"]:
value.update(phase="execute", retry_predecessor=digest)
else:
value.update(
state="rejected",
reason="configuration_conflict",
runtime_phase="complete",
result=result,
)
def advance(self, imei):
with self.lock:
with self.store.db() as db:
row = db.execute(
"SELECT body FROM operations WHERE imei=? AND state IN "
"('queued','dispatched') ORDER BY seq LIMIT 1",
(imei,),
).fetchone()
if not row:
return
value = json.loads(row[0])
if not self.store.admitted(imei):
value.update(state="rejected", reason="device_revoked", runtime_phase="complete")
self.save(value)
return
if value.get("attempt"):
# Idempotent submission covers a crash before/after attempt admission.
# Read first: the accepted attempt may have completed while Core was away.
try:
result = self.commands.get(value["attempt"]["id"])
except ValueError:
if value.get("stop_requested"):
value.pop("attempt", None)
value.update(state="stopped", runtime_phase="stopped")
self.save(value)
return
try:
result = self.commands.submit(value["attempt"])
except ValueError:
return # A legacy operation/session admission still owns the channel.
value["result"] = result
self.note_attempt(value, result)
if result["state"] in PENDING:
value.update(
state=result["state"],
runtime_phase="checking-result"
if value["phase"] == "inspect"
else "executing",
)
self.save(value)
return
if value["phase"] == "inspect" and result["state"] == "observed":
self.reconcile(value, result)
elif result["state"] in {
"device_confirmed",
"observed",
"verified",
"sim_selected",
"reconnected",
}:
value.update(state=result["state"], runtime_phase="complete")
elif (
value["kind"] == "restart"
and result.get("device_code") == 0
and result.get("device_accepted_at")
):
value.update(state="accepted", runtime_phase="complete")
elif (
result["state"] in RETRY
or result.get("device_code") == 7
or result.get("reason") == "configuration_predecessor_mismatch"
):
if value["kind"] in {"configure-all", "select-sim"}:
value["phase"] = "inspect"
else:
value.update(state=result["state"], runtime_phase="complete")
if result.get("reason") == "sim_card_changed":
value["reason"] = "sim_card_changed"
value.pop("attempt", None)
if value["state"] in PENDING:
value.update(
state="stopped" if value.get("stop_requested") else "queued",
runtime_phase="stopped" if value.get("stop_requested") else "retry-wait",
next_attempt_at=time.time()
+ min(300, 5 * 2 ** min(value["attempt_count"] - 1, 6)),
)
self.save(value)
return
if value.get("stop_requested"):
value.update(state="stopped", runtime_phase="stopped")
self.save(value)
return
if value["next_attempt_at"] > time.time():
return
if not self.fresh(imei):
if value["runtime_phase"] != "waiting-link":
value.update(runtime_phase="waiting-link")
self.save(value)
return
if value["phase"] == "execute" and value["request"].get("sim_guard"):
guard = self.commands.sim_guard.check(imei, value["request"]["sim_guard"])
if guard != "matched":
if guard == "changed":
value.update(
state="rejected", runtime_phase="complete", reason="sim_card_changed"
)
else:
value.update(runtime_phase="waiting-identity")
self.save(value)
return
attempt = {**value["request"], "id": uuid.uuid4().hex}
if value["phase"] == "inspect":
attempt = {
k: v
for k, v in attempt.items()
if k in {"id", "imei", "password", "model", "firmware"}
}
attempt["kind"] = "read-configuration"
elif value.get("retry_predecessor"):
attempt["expected_sha256"] = value["retry_predecessor"]
lifetime = (
360
if attempt["kind"] == "select-sim"
else 30
if attempt["kind"] == "request-position"
else 180
)
attempt["not_after"] = time.time() + lifetime
value.update(
attempt=attempt,
attempt_count=value["attempt_count"] + 1,
result={},
runtime_phase="checking-result" if value["phase"] == "inspect" else "executing",
)
# The plan is durable before the attempt's separate transaction.
self.save(value)
self.advance(imei)
-30
View File
@@ -1,30 +0,0 @@
"""Observe return after a restart request without claiming CPU/power-cycle proof."""
import time
def observe(value, raw, session, started):
if (
value.get("kind") != "restart"
or value["state"] != "dispatched"
or value["expires_at"] < time.time()
or session in value["restart_sessions"]
or started <= value["monotonic"]
):
return False
# Only type-1 telemetry measured after dispatch establishes fresh return.
# A new header, old archive, text reply or token ACK cannot complete this.
offset = 2
while offset < len(raw) - 1:
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
if raw[offset] == 1 and value["dispatched_at"] < measured <= time.time() + 5:
value.update(
state="reconnected",
reconnected_at=time.time(),
reconnect_seconds=time.monotonic() - value["monotonic"],
telemetry_measured_at=measured,
)
return True
offset += size + 8
return False
-402
View File
@@ -1,402 +0,0 @@
"""Bounded asyncio TCP receiver and pinned-TLS API; no shell/device control API."""
import asyncio
import json
import sqlite3
import ssl
import time
import uuid
from contextlib import suppress
from urllib.parse import parse_qs, urlsplit
from . import arnavi
from .commands import COMMAND_SESSION_MAX_IDLE, Commands
from .delivery import Delivery
from .observation import Observation, http_body
from .operations import Operations
class Service:
def __init__(self, store):
self.store = store
self.connections = 0
self.commands = Commands(store)
self.operations = Operations(store, self.commands)
self.observation = Observation(store)
self.wake = {}
async def tracker(self, reader, writer):
self.connections += 1
session = uuid.uuid4().hex
sender = None
delivery = None
imei = None
try:
if self.connections > 256:
return
async with asyncio.timeout(10):
header = await reader.readexactly(10)
if header[:2] != b"\xff\x23":
if (
not await self.observe_configuration(reader, header, writer)
and header == b"POST /c/in"
):
delivery = Delivery(writer)
await self.configuration_http(reader, writer, header, delivery)
return
imei = arnavi.identity(header)
if not await asyncio.to_thread(self.store.admitted, imei):
return
delivery = Delivery(writer)
self.commands.sessions.setdefault(imei, set()).add(session)
self.commands.session_started[imei, session] = time.monotonic()
self.commands.session_activity[imei, session] = time.monotonic()
self.commands.session_peers[imei, session] = writer.get_extra_info("peername")[0]
self.commands.session_ready[imei, session] = False
delivery.write(arnavi.header_ack(int(time.time())))
await writer.drain()
sender = asyncio.create_task(self.send_commands(imei, writer, session, delivery))
buffer = b""
while True:
async with asyncio.timeout(180):
chunk = await reader.read(min(4096, arnavi.MAX_PACKAGE - len(buffer)))
if not chunk:
return
buffer += chunk
while buffer:
parsed = arnavi.parse_package(buffer)
if parsed is None:
break
length, packets = parsed
self.commands.session_activity[imei, session] = time.monotonic()
await asyncio.to_thread(
self.accept_package, imei, buffer[:length], packets, session
)
self.notify(imei)
delivery.write(arnavi.package_ack(buffer[1]))
await writer.drain()
buffer = buffer[length:]
except (
ValueError,
KeyError,
OSError,
sqlite3.Error,
TimeoutError,
asyncio.IncompleteReadError,
asyncio.LimitOverrunError,
):
pass # Deliberately no raw identity/data/credentials in logs.
finally:
if imei:
self.commands.sessions.get(imei, set()).discard(session)
self.commands.session_started.pop((imei, session), None)
self.commands.session_activity.pop((imei, session), None)
self.commands.session_peers.pop((imei, session), None)
self.commands.session_ready.pop((imei, session), None)
if not self.commands.sessions.get(imei):
self.commands.sessions.pop(imei, None)
if sender:
sender.cancel()
await asyncio.gather(sender, return_exceptions=True)
self.connections -= 1
if delivery:
delivery.abort()
else:
writer.close()
def accept_package(self, imei, raw, packets, session):
# Core may fetch/ack packages concurrently. Publish the packet and its
# command evidence together before either Core or B2 can consume it.
with self.store.packet_transaction():
self.store.append(imei, raw, packets)
self.commands.receive(imei, raw, session)
self.operations.observe(imei, raw)
async def observe_configuration(self, reader, header, writer=None):
ticket = await asyncio.to_thread(self.observation.claim)
if ticket is None:
return False
raw = bytearray(header)
events = [
{"offset": 0, "bytes": len(header), "at": time.time(), "monotonic": time.monotonic()}
]
try:
async with asyncio.timeout(8):
while len(raw) < 16384:
chunk = await reader.read(min(4096, 16384 - len(raw)))
if not chunk:
break
events.append(
{
"offset": len(raw),
"bytes": len(chunk),
"at": time.time(),
"monotonic": time.monotonic(),
}
)
raw.extend(chunk)
if writer is not None:
reply = await asyncio.to_thread(self.observation.reply, ticket, bytes(raw))
if reply is not None:
writer.write(
b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n"
+ f"Content-Length: {len(reply)}\r\n".encode()
+ b"Connection: keep-alive\r\n\r\n"
+ reply
)
await writer.drain()
except (TimeoutError, OSError):
pass
finally:
await asyncio.to_thread(self.observation.finish, ticket, bytes(raw), events)
return True
async def configuration_http(self, reader, writer, initial, delivery):
if initial != b"POST /c/in":
return
peer = writer.get_extra_info("peername")[0]
for _ in range(8):
async with asyncio.timeout(12):
header = initial + await reader.readuntil(b"\r\n\r\n")
initial = b""
if len(header) > 2048:
return
lengths = [
line.split(b":", 1)[1].strip()
for line in header.split(b"\r\n")
if line.lower().startswith(b"content-length:")
]
if len(lengths) != 1 or not lengths[0].isdigit():
return
size = int(lengths[0])
if not 20 <= size <= 16384:
return
body = http_body(header + await reader.readexactly(size))
if body is None:
return
response = await asyncio.to_thread(
self.commands.web_receive, body, peer, with_deadline=True
)
self.notify(str(int.from_bytes(body[4:12], "little")))
if response is None:
return
reply, deadline = response
delivery.write(
b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n"
+ f"Content-Length: {len(reply)}\r\n".encode()
+ b"Connection: keep-alive\r\n\r\n"
+ reply,
deadline,
)
await writer.drain()
async def send_commands(self, imei, writer, session, delivery):
event = asyncio.Event()
observations = []
def observe(ticket, phase, at, elapsed, reason):
# The socket timer never opens SQLite or waits for filesystem I/O.
observations.append((ticket, phase, at, elapsed, reason))
event.set()
async def persist():
if observations:
batch = observations[:]
observations.clear()
commit = asyncio.create_task(
asyncio.to_thread(self.commands.transport.record, batch)
)
try:
await asyncio.shield(commit)
except asyncio.CancelledError:
# EOF cancels this sender. Finish the extracted batch before
# the finally block records closure of its remaining bytes.
await commit
raise
self.wake.setdefault(imei, set()).add(event)
try:
while not writer.is_closing():
event.clear()
await persist()
last_input = self.commands.session_activity.get((imei, session))
self.commands.session_ready[imei, session] = (
delivery.ready()
and last_input is not None
and 0 <= time.monotonic() - last_input <= COMMAND_SESSION_MAX_IDLE
)
await asyncio.to_thread(self.operations.advance, imei)
dispatch = await asyncio.to_thread(
self.commands.take_delivery, imei, session, with_receipt=True
)
if dispatch:
data, deadline, ticket = dispatch
delivery.write(
data,
deadline,
lambda phase, at, elapsed, reason, ticket=ticket: observe(
ticket, phase, at, elapsed, reason
),
)
await writer.drain()
await persist()
delay = await asyncio.to_thread(self.commands.wait_delay, imei)
operation_delay = await asyncio.to_thread(self.operations.wait_delay, imei)
delay = (
min(d for d in (delay, operation_delay) if d is not None)
if (delay is not None or operation_delay is not None)
else None
)
with suppress(TimeoutError):
await asyncio.wait_for(event.wait(), delay)
finally:
self.wake.get(imei, set()).discard(event)
if not self.wake.get(imei):
self.wake.pop(imei, None)
delivery.abort()
await persist()
def notify(self, imei):
for event in self.wake.get(imei, ()):
event.set()
async def api(self, reader, writer):
status, value = 400, {"error": "invalid_request"}
try:
async with asyncio.timeout(15):
header = await reader.readuntil(b"\r\n\r\n")
if len(header) > 8192:
raise ValueError
lines = header.decode("ascii").split("\r\n")
method, target, _ = lines[0].split(" ")
headers = dict(line.lower().split(": ", 1) for line in lines[1:] if line)
size = int(headers.get("content-length", "0"))
if not 0 <= size <= 1024 * 1024 or "transfer-encoding" in headers:
raise ValueError
payload = await reader.readexactly(size) if size else b"{}"
body = json.loads(payload)
route = urlsplit(target)
token = headers.get("authorization", "").removeprefix("bearer ")
# Header values must retain case for bearer credentials.
for line in lines[1:]:
if line.lower().startswith("authorization: bearer "):
token = line[len("authorization: bearer ") :]
if method == "GET" and route.path == "/health":
value = {"ok": True, "service": "ndc-mission-vps-host"}
elif method == "POST" and route.path == "/v1/pair":
value = await asyncio.to_thread(self.store.pair, body)
else:
if not await asyncio.to_thread(self.store.authorize, token):
raise PermissionError
if method == "GET" and route.path == "/v1/status":
value = await asyncio.to_thread(self.store.status)
elif method == "PUT" and route.path == "/v1/devices":
await asyncio.to_thread(self.store.set_devices, body["items"])
value = {"ok": True}
elif method == "GET" and route.path == "/v1/packets":
after = int(parse_qs(route.query).get("after", ["0"])[0])
value = await asyncio.to_thread(self.store.fetch, max(0, after))
elif method == "POST" and route.path == "/v1/commands":
if await asyncio.to_thread(self.operations.pending, body["imei"]):
raise ValueError("durable operation owns device queue")
value = await asyncio.to_thread(self.commands.submit, body)
self.notify(body["imei"])
elif method == "POST" and route.path == "/v1/operations":
value = await asyncio.to_thread(self.operations.submit, body)
self.notify(body["imei"])
elif (
method == "POST"
and route.path.startswith("/v1/operations/")
and route.path.endswith("/cancel")
):
value = await asyncio.to_thread(
self.operations.cancel, route.path.split("/")[-2], body.get("kind")
)
elif (
method == "GET"
and route.path.startswith("/v1/operations/")
and route.path.endswith("/attempts")
):
before = int(parse_qs(route.query).get("before", [str(2**63 - 1)])[0])
value = await asyncio.to_thread(
self.operations.history, route.path.split("/")[-2], before
)
elif method == "GET" and route.path.startswith("/v1/operations/"):
value = await asyncio.to_thread(
self.operations.get, route.path.rsplit("/", 1)[1]
)
elif method == "POST" and route.path == "/v1/configuration-observations":
value = await asyncio.to_thread(self.observation.arm, body)
elif (
method == "POST"
and route.path.startswith("/v1/configuration-observations/")
and route.path.endswith("/close")
):
value = await asyncio.to_thread(
self.observation.close, route.path.split("/")[-2]
)
elif method == "GET" and route.path.startswith(
"/v1/configuration-observations/"
):
value = await asyncio.to_thread(
self.observation.get, route.path.rsplit("/", 1)[1]
)
elif method == "GET" and route.path.startswith("/v1/commands/"):
value = await asyncio.to_thread(
self.commands.get, route.path.rsplit("/", 1)[1]
)
elif method == "POST" and route.path == "/v1/ack":
if type(body["through"]) is not int or body["through"] < 0:
raise ValueError
await asyncio.to_thread(self.store.acknowledge, body["through"])
value = {"ok": True}
else:
raise ValueError
status = 200
except PermissionError:
status, value = 403, {"error": "not_authorized"}
except (
ValueError,
KeyError,
TypeError,
UnicodeError,
asyncio.IncompleteReadError,
asyncio.LimitOverrunError,
TimeoutError,
):
pass
except (OSError, sqlite3.Error):
status, value = 503, {"error": "storage_unavailable"}
try:
payload = json.dumps(value).encode()
writer.write(
(
f"HTTP/1.1 {status} Result\r\nContent-Type: application/json\r\n"
f"Content-Length: {len(payload)}\r\nConnection: close\r\n"
"Cache-Control: no-store\r\n\r\n"
).encode()
+ payload
)
await writer.drain()
except OSError:
pass
finally:
writer.close()
async def run(self):
tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
tls.minimum_version = ssl.TLSVersion.TLSv1_3
tls.load_cert_chain(self.store.root / "tls.crt", self.store.root / "tls.key")
api = await asyncio.start_server(
self.api,
"0.0.0.0",
self.store.config["api_port"],
ssl=tls,
ssl_handshake_timeout=8,
limit=8192,
)
tracker = await asyncio.start_server(
self.tracker, "0.0.0.0", self.store.config["tracker"]["port"]
)
async with api, tracker:
await asyncio.gather(api.serve_forever(), tracker.serve_forever())
-83
View File
@@ -1,83 +0,0 @@
"""Durable firmware SID bindings, checked at the last configuration write boundary."""
import json
import re
import time
from .sim_network import binding, decode_pairs, merge
def prepare(value):
if (
not isinstance(value, dict)
or set(value) != {"slot", "sid"}
or type(value["slot"]) is not int
or value["slot"] not in (1, 2)
or not isinstance(value["sid"], str)
or not re.fullmatch(r"89[0-9]{18}", value["sid"])
):
raise ValueError("invalid SIM identity guard")
return dict(value)
class SimGuard:
def __init__(self, store):
self.store = store
with store.db() as db:
db.execute(
"CREATE TABLE IF NOT EXISTS sim_bindings(imei TEXT PRIMARY KEY,body TEXT NOT NULL)"
)
def observe(self, imei, raw):
# Called only for validated INTERNAL frames in the packet commit transaction.
with self.store.db(write=True) as db:
old = db.execute("SELECT body FROM sim_bindings WHERE imei=?", (imei,)).fetchone()
value = json.loads(old[0]) if old else None
offset, now = 2, time.time()
while offset < len(raw) - 1:
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
payload = raw[offset + 7 : offset + 7 + size]
if raw[offset] == 1:
tags = {}
for i in range(0, len(payload) - 4, 5):
tags.setdefault(payload[i], set()).add(payload[i + 1 : i + 5])
status = {}
if len(tags.get(99, ())) == 1:
ds = int.from_bytes(next(iter(tags[99])), "little")
status = {"sim_states": {"1": (ds >> 6) & 7, "2": (ds >> 9) & 7}}
value = merge(
value,
{
"measured_at": measured,
"cellular": {"status": status},
"sim_identifiers": decode_pairs(tags),
},
host_id="local",
sequence=0,
received=now,
tracker=imei,
)
offset += size + 8
if value:
db.execute(
"INSERT OR REPLACE INTO sim_bindings VALUES(?,?)", (imei, json.dumps(value))
)
def check(self, imei, guard, *, after=None, db=None):
if guard is None:
return "matched"
if db is None:
with self.store.db() as connection:
return self.check(imei, guard, after=after, db=connection)
row = db.execute("SELECT body FROM sim_bindings WHERE imei=?", (imei,)).fetchone()
value = json.loads(row[0]) if row else None
sid = binding(value, str(guard["slot"]), now=time.time())
if sid is None:
return "waiting"
if sid != guard["sid"]:
return "changed"
observed = value["slots"][str(guard["slot"])]["observation"]
if after is not None and observed["measured_at"] <= after:
return "waiting"
return "matched"
-55
View File
@@ -1,55 +0,0 @@
"""SIM permissions: verified flags, one restart, fresh modem evidence."""
import time
from . import actions
def matches(value, slot):
return (
type(slot) is int
and slot in (1, 2)
and (value.get("sim_policy") == "both" or slot == value.get("sim_slot"))
)
def queue_restart(value):
value.update(actions.prepare({"kind": "restart", "model": 231, "firmware": "0.01"}))
value.update(stage="restart", state="queued", not_before=time.time())
value.pop("session", None)
def observe(value, raw, session, started):
if (
value.get("kind") != "select-sim"
or value.get("stage") != "restart"
or value["state"] != "dispatched"
or value["expires_at"] <= time.time()
or session in value["restart_sessions"]
or started <= value["monotonic"]
):
return False
# Validated INTERNAL packages only. ACKs, archives, old sockets, old and
# future measurements, and GPRS on the wrong SIM cannot confirm selection.
offset = 2
while offset < len(raw) - 1:
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
payload = raw[offset + 7 : offset + 7 + size]
if raw[offset] == 1 and value["dispatched_at"] < measured <= time.time() + 5:
for index in range(0, len(payload) - 4, 5):
if payload[index] != 99:
continue
ds2 = int.from_bytes(payload[index + 1 : index + 5], "little")
slot = 1 + ((ds2 >> 5) & 1)
if matches(value, slot) and (ds2 >> 2) & 7 == 4:
value.update(
state="sim_selected",
active_sim=slot,
verified_at=time.time(),
telemetry_measured_at=measured,
reconnect_seconds=time.monotonic() - value["monotonic"],
)
return True
offset += size + 8
return False
-262
View File
@@ -1,262 +0,0 @@
"""Durable receiver journal. Acknowledgements follow SQLite FULL commits."""
import base64
import hashlib
import hmac
import json
import os
import secrets
import sqlite3
import threading
import time
from contextlib import contextmanager
from pathlib import Path
def private_write(path, data):
temporary = path.with_name(path.name + ".new")
with open(temporary, "wb") as stream:
os.chmod(temporary, 0o600)
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
fd = os.open(path.parent, os.O_RDONLY)
try:
os.fsync(fd)
finally:
os.close(fd)
class Store:
def __init__(self, root):
self.root = Path(root)
self.config = json.loads((self.root / "host.json").read_text())
self.path = self.root / "journal.sqlite3"
self._packet = threading.local()
with self.db() as db:
db.executescript("""
CREATE TABLE IF NOT EXISTS state(key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS devices(imei TEXT PRIMARY KEY, instance TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS device_ids(
imei TEXT PRIMARY KEY, number INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS packages(id INTEGER PRIMARY KEY AUTOINCREMENT,
imei TEXT NOT NULL, instance TEXT NOT NULL, digest TEXT UNIQUE NOT NULL,
received REAL NOT NULL, raw BLOB NOT NULL, packets TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS receipts(digest TEXT PRIMARY KEY, at REAL NOT NULL);
""")
self.path.chmod(0o600)
@contextmanager
def db(self, *, write=False):
# Packet consumers run together on one worker thread. No partial
# receipt or modem state may become visible to Core or the sender.
current = getattr(self._packet, "connection", None)
if current is not None:
yield current
return
connection = sqlite3.connect(self.path, timeout=10)
try:
connection.execute("PRAGMA synchronous=FULL")
with connection:
if write:
connection.execute("BEGIN IMMEDIATE")
yield connection
finally:
connection.close()
@contextmanager
def packet_transaction(self):
"""Synchronous packet ingestion only: no sockets, awaits or API work."""
if getattr(self._packet, "connection", None) is not None:
raise RuntimeError("nested packet transaction")
with self.db(write=True) as connection:
self._packet.connection = connection
try:
yield
finally:
del self._packet.connection
def invitation(self):
secret = secrets.token_urlsafe(32)
expires = int(time.time()) + 86400
with self.db() as db:
if db.execute("SELECT 1 FROM state WHERE key='owner'").fetchone():
raise ValueError("host already paired; restore its Core identity instead")
db.execute(
"INSERT OR REPLACE INTO state VALUES('invitation',?)",
(
json.dumps(
{"hash": hashlib.sha256(secret.encode()).hexdigest(), "expires_at": expires}
),
),
)
code = {
"schema": "missioncore.vps-pairing/v1",
"host_id": self.config["host_id"],
"endpoint": self.config["endpoint"],
"fingerprint": self.config["fingerprint"],
"secret": secret,
"expires_at": expires,
}
encoded = "MCV1." + base64.urlsafe_b64encode(json.dumps(code).encode()).decode().rstrip("=")
private_write(self.root / "connect.key", (encoded + "\n").encode())
def pair(self, body):
core, token, secret = body["core_id"], body["token"], body["secret"]
if not all(isinstance(v, str) and 32 <= len(v) <= 100 for v in (core, token, secret)):
raise ValueError("invalid pairing")
digest = hashlib.sha256(token.encode()).hexdigest()
with self.db() as db:
db.execute("BEGIN IMMEDIATE")
current = db.execute("SELECT value FROM state WHERE key='owner'").fetchone()
if current:
owner = json.loads(current[0])
if owner["core_id"] != core or not hmac.compare_digest(owner["token"], digest):
raise PermissionError("already paired")
else:
row = db.execute("SELECT value FROM state WHERE key='invitation'").fetchone()
invite = json.loads(row[0]) if row else {}
if invite.get("expires_at", 0) <= time.time() or not hmac.compare_digest(
invite.get("hash", ""), hashlib.sha256(secret.encode()).hexdigest()
):
raise PermissionError("invalid invitation")
db.execute(
"INSERT INTO state VALUES('owner',?)",
(json.dumps({"core_id": core, "token": digest}),),
)
db.execute("DELETE FROM state WHERE key='invitation'")
private_write(
self.root / "connect.key", b"PAIRED: key consumed; use the connected Mission Core.\n"
)
return self.status()
def authorize(self, token):
with self.db() as db:
row = db.execute("SELECT value FROM state WHERE key='owner'").fetchone()
return bool(
row
and hmac.compare_digest(
json.loads(row[0])["token"], hashlib.sha256(token.encode()).hexdigest()
)
)
def status(self):
from . import VERSION
with self.db() as db:
count, latest = db.execute("SELECT COUNT(*),MAX(received) FROM packages").fetchone()
devices = db.execute("SELECT COUNT(*) FROM devices").fetchone()[0]
return {
"schema": "missioncore.vps-host/v1",
"host_id": self.config["host_id"],
"version": VERSION,
"tracker": self.config["tracker"],
"pending_packages": count,
"last_packet_at": latest,
"devices": devices,
"capabilities": [
"arnavi-b2-internal",
"arnavi-b2-durable-operations-v1",
"arnavi-b2-sim-guard-v1",
],
}
def set_devices(self, items):
if not isinstance(items, list) or len(items) > 10000:
raise ValueError("invalid devices")
rows, identities = [], []
for item in items:
imei, instance = item["imei"], item["instance_id"]
if (
not isinstance(imei, str)
or not imei.isascii()
or not imei.isdigit()
or len(imei) != 15
):
raise ValueError("invalid identity")
if not isinstance(instance, str) or len(instance) != 32:
raise ValueError("invalid instance")
rows.append((imei, instance))
if "device_id" in item:
number = item["device_id"]
if type(number) is not int or not 1 <= number <= 0xFFFFFFFF:
raise ValueError("invalid numeric device identity")
identities.append((imei, number))
if len({r[0] for r in rows}) != len(rows):
raise ValueError("duplicate identity")
with self.db() as db:
db.execute("BEGIN IMMEDIATE")
for imei, number in identities:
previous = db.execute(
"SELECT number FROM device_ids WHERE imei=?", (imei,)
).fetchone()
if previous and previous[0] != number:
raise ValueError("numeric device identity conflict")
db.execute("INSERT OR IGNORE INTO device_ids VALUES(?,?)", (imei, number))
db.execute("DELETE FROM devices")
db.executemany("INSERT INTO devices VALUES(?,?)", rows)
def numeric_id(self, imei):
with self.db() as db:
row = db.execute(
"SELECT number FROM device_ids JOIN devices USING(imei) WHERE imei=?", (imei,)
).fetchone()
return row[0] if row else None
def admitted(self, imei):
with self.db() as db:
row = db.execute("SELECT instance FROM devices WHERE imei=?", (imei,)).fetchone()
return row[0] if row else None
def append(self, imei, raw, packets):
# Reserve disk for system services. Refuse ACK when durable storage cannot accept data.
if os.statvfs(self.root).f_bavail * os.statvfs(self.root).f_frsize < 256 * 1024**2:
raise OSError("journal storage reserve")
digest = hashlib.sha256(imei.encode() + raw).hexdigest()
with self.db(write=True) as db:
device = db.execute("SELECT instance FROM devices WHERE imei=?", (imei,)).fetchone()
if not device:
raise PermissionError("device not admitted")
if db.execute("SELECT 1 FROM receipts WHERE digest=?", (digest,)).fetchone():
return
# Fixed 512 MiB journal budget; backpressure, never drop unacknowledged data.
pages = db.execute("PRAGMA page_count").fetchone()[0]
free = db.execute("PRAGMA freelist_count").fetchone()[0]
page_size = db.execute("PRAGMA page_size").fetchone()[0]
if (pages - free) * page_size > 512 * 1024**2:
raise OSError("journal full")
db.execute(
"INSERT OR IGNORE INTO packages(imei,instance,digest,received,raw,packets) "
"VALUES(?,?,?,?,?,?)",
(imei, device[0], digest, time.time(), raw, json.dumps(packets)),
)
def fetch(self, after):
with self.db() as db:
rows = db.execute(
"SELECT id,instance,digest,received,raw,packets FROM packages "
"WHERE id>? ORDER BY id LIMIT 20",
(after,),
).fetchall()
return {
"items": [
{
"id": r[0],
"instance_id": r[1],
"digest": r[2],
"received_at": r[3],
"raw": base64.b64encode(r[4]).decode(),
}
for r in rows
]
}
def acknowledge(self, through):
with self.db() as db:
db.execute(
"INSERT OR IGNORE INTO receipts SELECT digest,received FROM packages WHERE id<=?",
(through,),
)
db.execute("DELETE FROM packages WHERE id<=?", (through,))
db.execute("DELETE FROM receipts WHERE at<?", (time.time() - 7 * 86400,))
@@ -1,71 +0,0 @@
"""Private-free transport observations, independent of device execution state."""
import json
import time
import uuid
class TransportEvidence:
def __init__(self, store):
self.store = store
with store.db(write=True) as db:
db.execute(
"CREATE TABLE IF NOT EXISTS command_transport("
"seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT UNIQUE NOT NULL,"
"command TEXT NOT NULL,state TEXT NOT NULL,body TEXT NOT NULL)"
)
db.execute(
"CREATE INDEX IF NOT EXISTS transport_command ON command_transport(command,seq)"
)
db.execute("CREATE INDEX IF NOT EXISTS transport_pending ON command_transport(state)")
# A process crash cannot tell us whether buffered bytes reached B2.
# It must never synthesize a TCP ACK or alter command retry policy.
for identifier, body in db.execute(
"SELECT id,body FROM command_transport WHERE state IN ('prepared','written')"
).fetchall():
value = json.loads(body)
value.update(state="unconfirmed", reason="host_restarted", closed_at=time.time())
db.execute(
"UPDATE command_transport SET state=?,body=? WHERE id=?",
(value["state"], json.dumps(value), identifier),
)
@staticmethod
def prepare(db, command, stage):
value = dict(id=uuid.uuid4().hex, stage=stage, state="prepared", prepared_at=time.time())
db.execute(
"INSERT INTO command_transport(id,command,state,body) VALUES(?,?,?,?)",
(value["id"], command, value["state"], json.dumps(value)),
)
return value["id"]
def record(self, events):
with self.store.db(write=True) as db:
for identifier, phase, at, elapsed, reason in events:
row = db.execute(
"SELECT body FROM command_transport WHERE id=?", (identifier,)
).fetchone()
if not row or phase not in {"written", "tcp_acknowledged", "unconfirmed"}:
continue
value = json.loads(row[0])
if value["state"] in {"tcp_acknowledged", "unconfirmed"}:
continue
if phase == "written":
value.setdefault("written_at", at)
elif phase == "tcp_acknowledged":
value.update(tcp_acknowledged_at=at, tcp_ack_seconds=elapsed)
else:
value.update(closed_at=at, reason=reason)
value["state"] = phase
db.execute(
"UPDATE command_transport SET state=?,body=? WHERE id=?",
(phase, json.dumps(value), identifier),
)
@staticmethod
def read(db, command):
rows = db.execute(
"SELECT body FROM command_transport WHERE command=? ORDER BY seq DESC LIMIT 32",
(command,),
).fetchall()
return [json.loads(row[0]) for row in reversed(rows)]
-92
View File
@@ -1,92 +0,0 @@
"""Single-file headless installer entry point, using the same plan/apply engine."""
import argparse
import fcntl
import importlib.util
import json
import os
import sys
import tempfile
import zipfile
from pathlib import Path
def main():
parser = argparse.ArgumentParser(
description="Install VPS Host ARNavi on Ubuntu Server 24.04 amd64"
)
parser.add_argument("--host", help="Public DNS name or IPv4 of this VPS")
actions = parser.add_mutually_exclusive_group()
actions.add_argument(
"--fresh", action="store_true", help="Back up and replace this product installation"
)
actions.add_argument("--restore", help="Restore the private backup created by --fresh")
actions.add_argument("--export-state", help="Stop and fence this VPS; export private state")
actions.add_argument("--import-state", help="Restore exported state on an empty Ubuntu VPS")
actions.add_argument(
"--resume-source",
action="store_true",
help="Cancel migration fencing; target must already be stopped",
)
parser.add_argument("--sha256", help="Required SHA-256 of --import-state archive")
args = parser.parse_args()
if os.geteuid() != 0:
parser.error("Run: sudo python3 " + Path(sys.argv[0]).name)
# Serialize all owner installer actions, including crash recovery/migration.
with open("/run/lock/ndc-mission-vps-installer.lock", "a") as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
parser.error("Another VPS installer operation is running")
with tempfile.TemporaryDirectory(prefix="ndc-vps-install-") as directory:
with zipfile.ZipFile(sys.argv[0]) as archive:
for name in archive.namelist():
if name.startswith("payload/"):
relative = Path(name).relative_to("payload")
if ".." in relative.parts:
raise ValueError("Invalid installer payload")
target = Path(directory) / relative
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(archive.read(name))
sys.path.insert(0, directory)
spec = importlib.util.spec_from_file_location(
"installer", Path(directory) / "install.py"
)
engine = importlib.util.module_from_spec(spec)
spec.loader.exec_module(engine)
if args.export_state or args.import_state or args.resume_source:
import portable_state
if args.export_state:
portable_state.export_state(engine, Path(args.export_state))
elif args.import_state:
if args.host or not args.sha256:
parser.error("Import preserves the endpoint; provide --sha256, not --host")
portable_state.import_state(engine, Path(args.import_state), args.sha256)
else:
portable_state.resume_source(engine)
return
if args.restore:
engine.restore(Path(args.restore))
return
host = args.host or input("Public DNS name or IPv4 of this VPS: ").strip()
options = argparse.Namespace(host=host, api_port=19443, tracker_port=9922, expect=None)
proposal = engine.plan(options)
print(
json.dumps(
{k: proposal[k] for k in ("environment", "configuration", "artifact")}, indent=2
)
)
options.expect = proposal["plan_sha256"]
if args.fresh:
engine.fresh(options, proposal)
else:
engine.apply(options, proposal)
print(
"VPS Host ARNavi ready. Copy the key from "
"/opt/nodedc-mission-vps/connect.key into Mission Core."
)
if __name__ == "__main__":
main()
-311
View File
@@ -1,311 +0,0 @@
"""Private, quiesced state transfer. Code and system configuration come from the installer."""
import argparse
import hashlib
import json
import os
import re
import shutil
import sqlite3
import ssl
import subprocess
import tarfile
import tempfile
import time
import uuid
from pathlib import Path
SCHEMA = "missioncore.vps-portable-state/v1"
FILES = {"host.json", "tls.crt", "tls.key", "connect.key", "journal.sqlite3"}
MAX_BYTES = 2 * 1024**3
SERVICE = "ndc-mission-vps.service"
def sha(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def sync_directory(path):
fd = os.open(path, os.O_RDONLY)
try:
os.fsync(fd)
finally:
os.close(fd)
def durable_json(path, value):
temporary = path.with_name(path.name + ".new")
with temporary.open("wb") as stream:
temporary.chmod(0o600)
stream.write(json.dumps(value, sort_keys=True, indent=2).encode())
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
sync_directory(path.parent)
def options(config):
return argparse.Namespace(
host=config["public_host"],
api_port=config["api_port"],
tracker_port=config["tracker"]["port"],
expect=None,
)
def check_state(state):
config = json.loads((state / "host.json").read_text())
fingerprint = hashlib.sha256(
ssl.PEM_cert_to_DER_cert((state / "tls.crt").read_text())
).hexdigest()
if config["fingerprint"] != fingerprint or config["host_id"] != "vps_" + fingerprint:
raise ValueError("state TLS identity mismatch")
if (
config["endpoint"] != f"https://{config['public_host']}:{config['api_port']}"
or config["tracker"]["host"] != config["public_host"]
):
raise ValueError("inconsistent state endpoints")
cert = subprocess.run(
["openssl", "x509", "-in", str(state / "tls.crt"), "-pubkey", "-noout"],
capture_output=True,
check=True,
).stdout
key = subprocess.run(
["openssl", "pkey", "-in", str(state / "tls.key"), "-pubout"],
capture_output=True,
check=True,
).stdout
if cert != key:
raise ValueError("state private key mismatch")
with sqlite3.connect((state / "journal.sqlite3").as_uri() + "?mode=ro", uri=True) as db:
if db.execute("PRAGMA integrity_check").fetchall() != [("ok",)]:
raise ValueError("state journal integrity failure")
# Enforce the known state boundary without rewriting its IDs or deadlines.
for table in (
"state",
"devices",
"packages",
"receipts",
"commands",
"operations",
"operation_attempts",
"operation_stops",
):
db.execute(f'SELECT COUNT(*) FROM "{table}"').fetchone()
return config
def export_state(engine, destination):
if os.geteuid() != 0:
raise ValueError("root required")
destination = destination.absolute()
if destination.exists() or destination.is_symlink() or not destination.parent.is_dir():
raise ValueError("new archive path in an existing directory required")
config = json.loads((engine.STATE / "host.json").read_text())
proposal = engine.plan(options(config))
if not proposal["previous"] or Path(proposal["previous"]).name != proposal["artifact"]:
raise ValueError("install this exact release before exporting its state")
if (
"ConditionPathExists=!/opt/nodedc-mission-vps/migration-fence.json"
not in engine.UNIT.read_text()
):
raise ValueError("installed service has no persistent migration fence")
engine.healthy()
allowed = FILES | {"journal.sqlite3-wal", "journal.sqlite3-shm", "journal.sqlite3-journal"}
if any(
p.name not in allowed or p.is_symlink() or not p.is_file() for p in engine.STATE.iterdir()
):
raise ValueError("unrecognized private state; export refuses to omit it")
required = sum((engine.STATE / name).stat().st_size for name in FILES)
if (
required > MAX_BYTES
or shutil.disk_usage(destination.parent).free < required * 2 + 256 * 1024**2
):
raise ValueError("insufficient archive space or state exceeds portable limit")
fence = engine.ROOT / "migration-fence.json"
record = {
"schema": SCHEMA,
"migration_id": uuid.uuid4().hex,
"created_at": time.time(),
"monotonic": time.monotonic(),
"artifact": proposal["artifact"],
"status": "quiescing",
}
# Persistent unit condition blocks manual/automatic starts and host reboots.
# Failure after this point stays fenced; the operator can explicitly resume.
durable_json(fence, record)
engine.run("systemctl", "stop", SERVICE)
active = subprocess.run(["systemctl", "is-active", SERVICE], capture_output=True).stdout.strip()
if active not in (b"inactive", b"failed"):
raise ValueError("source did not stop; migration remains fenced")
with tempfile.TemporaryDirectory(prefix=".ndc-vps-export-", dir=destination.parent) as work:
work = Path(work)
state = work / "state"
state.mkdir(mode=0o700)
for name in FILES - {"journal.sqlite3"}:
shutil.copyfile(engine.STATE / name, state / name)
(state / name).chmod(0o600)
with (
sqlite3.connect(
(engine.STATE / "journal.sqlite3").as_uri() + "?mode=ro", uri=True
) as src,
sqlite3.connect(state / "journal.sqlite3") as dst,
):
src.backup(dst)
(state / "journal.sqlite3").chmod(0o600)
check_state(state)
record.update(
status="source_fenced",
files={
"state/" + name: {
"sha256": sha(state / name),
"size": (state / name).stat().st_size,
}
for name in sorted(FILES)
},
)
durable_json(work / "manifest.json", record)
archive = work / "state.tar.gz"
with tarfile.open(archive, "w:gz", format=tarfile.USTAR_FORMAT) as tar:
for name in ["manifest.json", *record["files"]]:
info = tar.gettarinfo(work / name, arcname=name)
info.mode = 0o600
info.mtime = int(info.mtime)
info.uid = info.gid = 0
info.uname = info.gname = ""
with (work / name).open("rb") as stream:
tar.addfile(info, stream)
archive.chmod(0o600)
with archive.open("rb") as stream:
os.fsync(stream.fileno())
# Atomic publication without ever overwriting an existing backup.
os.link(archive, destination)
sync_directory(destination.parent)
digest = sha(destination)
durable_json(fence, {**record, "archive_sha256": digest})
print(
json.dumps(
{
"status": "source_fenced",
"archive": str(destination),
"sha256": digest,
"migration_id": record["migration_id"],
}
)
)
def unpack(archive, expected, directory, artifact):
if not re.fullmatch(r"[a-f0-9]{64}", expected) or archive.is_symlink() or not archive.is_file():
raise ValueError("regular archive and exact SHA-256 required")
if archive.stat().st_size > MAX_BYTES or sha(archive) != expected:
raise ValueError("archive digest or size mismatch")
expected_names = {"manifest.json"} | {"state/" + name for name in FILES}
seen, total = set(), 0
# Never extract paths/links/modes supplied by an archive or deserialize code.
with tarfile.open(archive, "r:gz") as tar:
for member in tar:
if (
member.name not in expected_names
or member.name in seen
or not member.isfile()
or member.pax_headers
):
raise ValueError("invalid portable archive member")
total += member.size
limit = MAX_BYTES if member.name == "state/journal.sqlite3" else 1024 * 1024
if member.size > limit or total > MAX_BYTES:
raise ValueError("portable archive size limit")
seen.add(member.name)
target = directory / member.name
target.parent.mkdir(mode=0o700, exist_ok=True)
with target.open("xb") as stream, tar.extractfile(member) as source:
target.chmod(0o600)
shutil.copyfileobj(source, stream, 1024 * 1024)
if seen != expected_names:
raise ValueError("incomplete portable archive")
record = json.loads((directory / "manifest.json").read_text())
if (
record.get("schema") != SCHEMA
or record.get("status") != "source_fenced"
or record.get("artifact") != artifact
or set(record.get("files", {})) != expected_names - {"manifest.json"}
):
raise ValueError("archive requires its exact installer release and complete manifest")
for name, item in record["files"].items():
if item != {"sha256": sha(directory / name), "size": (directory / name).stat().st_size}:
raise ValueError("state integrity mismatch")
return record, check_state(directory / "state")
def import_state(engine, archive, expected):
if os.geteuid() != 0:
raise ValueError("root required")
for path in (engine.ROOT, engine.STATE, engine.UNIT):
if path.exists() or path.is_symlink():
raise ValueError("portable import requires an empty product installation")
if shutil.disk_usage(engine.STATE.parent).free < MAX_BYTES + 256 * 1024**2:
raise ValueError("portable import requires 2.25 GiB free staging space")
with tempfile.TemporaryDirectory(prefix=".ndc-vps-import-", dir=engine.STATE.parent) as work:
work = Path(work)
record, config = unpack(archive, expected, work, engine.digest())
args = options(config)
proposal = engine.plan(args) # OS, prerequisites, ports and firewall, before mutation.
args.expect = proposal["plan_sha256"]
# Install this shipped code and unit, creating the target's system account.
# Only identity/journal state crosses hosts; no old executable/unit/firewall does.
staged_state = work / "state"
staged_state.chmod(0o700)
for path in staged_state.iterdir():
with path.open("rb") as stream:
os.fsync(stream.fileno())
sync_directory(staged_state)
# Same-filesystem rename publishes all state at once. A failed copy
# must not leave a partial identity or require twice the journal space.
os.rename(staged_state, engine.STATE)
sync_directory(engine.STATE.parent)
engine.apply(args, proposal)
durable_json(
engine.ROOT / "imported-state.json",
{
"schema": SCHEMA,
"migration_id": record["migration_id"],
"archive_sha256": expected,
"imported_at": time.time(),
"endpoint_preserved": True,
},
)
print(
json.dumps(
{
"status": "imported",
"identity_preserved": True,
"migration_id": record["migration_id"],
"endpoint_preserved": True,
}
)
)
def resume_source(engine):
if os.geteuid() != 0:
raise ValueError("root required")
fence = engine.ROOT / "migration-fence.json"
record = json.loads(fence.read_text())
if record.get("schema") != SCHEMA or record.get("artifact") != engine.digest():
raise ValueError("source fence requires the same installer")
fence.unlink()
sync_directory(fence.parent)
try:
engine.run("systemctl", "start", SERVICE)
engine.healthy()
except Exception:
durable_json(fence, record)
engine.run("systemctl", "stop", SERVICE)
raise
durable_json(
engine.ROOT / "migration-cancelled.json",
{"migration_id": record["migration_id"], "resumed_at": time.time()},
)
print(json.dumps({"status": "source_resumed", "migration_id": record["migration_id"]}))
-100
View File
@@ -1,100 +0,0 @@
"""Bounded HTTP clock exchange over real loopback streams; no physical B2."""
import asyncio
import json
import tempfile
import time
from pathlib import Path
from ndc_vps.commands import frame
from ndc_vps.service import Service
from ndc_vps.store import Store
from ndc_vps.web_protocol import time_reply
async def qualify():
with tempfile.TemporaryDirectory(prefix="ndc-vps-clock-") as directory:
root = Path(directory)
(root / "host.json").write_text(
json.dumps(
{"host_id": "vps_" + "a" * 64, "tracker": {"host": "example.org", "port": 9922}}
)
)
store = Store(root)
imei = "123456789012345"
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
service = Service(store)
server = await asyncio.start_server(service.tracker, "127.0.0.1", 0)
writers = []
try:
port = server.sockets[0].getsockname()[1]
monitor, writer = await asyncio.open_connection("127.0.0.1", port)
writers.append(writer)
writer.write(b"\xff\x23" + int(imei).to_bytes(8, "little"))
await writer.drain()
assert (await monitor.readexactly(9))[0] == 0x7B
reader, writer = await asyncio.open_connection("127.0.0.1", port)
writers.append(writer)
request = (
b"[\x01\x00\x0f"
+ int(imei).to_bytes(8, "little")
+ bytes.fromhex("0001e7020000075d")
)
for _ in range(2):
before = int(time.time())
writer.write(b"POST /c/index.php HTTP/1.1\r\nContent-Length: 20\r\n\r\n" + request)
await writer.drain()
header = await reader.readuntil(b"\r\n\r\n")
assert header.startswith(b"HTTP/1.1 200 OK\r\n")
assert b"Content-Length: 10\r\n" in header
body = await reader.readexactly(10)
seconds = int.from_bytes(body[5:9], "big")
assert before <= seconds <= int(time.time())
assert body == time_reply(seconds)
with store.db() as db:
assert db.execute("SELECT COUNT(*) FROM commands").fetchone()[0] == 0
session = next(iter(service.commands.sessions[imei]))
service.commands.session_activity[imei, session] = time.monotonic() - 20
original = service.commands.submit(
{"id": "d" * 32, "imei": imei, "kind": "read-settings", "password": "123456"}
)
service.notify(imei)
await asyncio.sleep(0.1)
assert service.commands.get("d" * 32)["state"] == "queued"
# A real incoming telemetry frame wakes the waiting sender.
data = int(time.time()).to_bytes(4, "little") + b"\x63\0\0\0\0"
writers[0].write(b"[\x01\x01\x05\0" + data + bytes([sum(data) % 256]) + b"]")
await writers[0].drain()
expected = frame("123456*GETP")
received = await monitor.readexactly(len(expected) + 4)
assert received in (b"{\x00\x01}" + expected, expected + b"{\x00\x01}")
receipt = service.commands.get("d" * 32)
assert receipt["state"] == "dispatched"
assert receipt["expires_at"] == original["expires_at"]
assert service.commands.take(imei, session) is None
finally:
server.close()
for writer in writers:
writer.close()
await asyncio.gather(
*(writer.wait_closed() for writer in writers), return_exceptions=True
)
for _ in range(30):
if service.connections == 0:
break
await asyncio.sleep(0.01)
assert service.connections == 0 and not service.wake
await server.wait_closed()
return {
"ok": True,
"clock_replies": 2,
"same_http_connection": True,
"clock_commands_created": 0,
"stale_configuration_deferred": True,
"fresh_packet_dispatched_once": True,
"physical_devices_used": False,
}
if __name__ == "__main__":
print(json.dumps(asyncio.run(asyncio.wait_for(qualify(), 8)), sort_keys=True))
-117
View File
@@ -1,117 +0,0 @@
"""Bounded Linux loopback qualification; no tracker, firewall or service changes.
Run with the unpacked release's Python. Two ephemeral local TCP connections,
at most 64 KiB synthetic data, no dependencies or persistent state.
"""
import asyncio
import json
import socket
import sys
import time
import uuid
from datetime import UTC, datetime
from ndc_vps import VERSION
from ndc_vps.delivery import Delivery, queued_bytes
async def qualify(blocked):
loop = asyncio.get_running_loop()
accepted = loop.create_future()
finished = asyncio.Event()
handler_done = asyncio.Event()
async def handler(reader, writer):
accepted.set_result(writer)
try:
await finished.wait()
finally:
writer.transport.abort()
handler_done.set()
server = await asyncio.start_server(handler, "127.0.0.1", 0)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024)
client.setblocking(False)
guard = None
try:
await loop.sock_connect(client, server.sockets[0].getsockname())
writer = await asyncio.wait_for(accepted, 2)
sock = writer.get_extra_info("socket")
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 4096)
aborted = []
class ObservedDelivery(Delivery):
def abort(self, reason="connection_closed"):
aborted.append(time.monotonic())
super().abort(reason)
guard = ObservedDelivery(writer)
assert guard.ready()
started = time.monotonic()
deadline = started + 0.75
payload = b"x" * (65536 if blocked else 12)
guard.write(payload, deadline)
if not blocked:
assert await asyncio.wait_for(loop.sock_recv(client, 12), 1) == payload
await asyncio.sleep(0.15)
kernel = queued_bytes(sock)
buffered = writer.transport.get_write_buffer_size()
if blocked:
assert kernel > 0, "The peer did not actually block TCP delivery"
assert not guard.ready(), "An unacknowledged prefix must block a new command"
else:
assert guard.ready(), "A fully acknowledged stream should accept a new command"
await asyncio.sleep(0.85)
if blocked:
assert writer.is_closing() and sock.fileno() == -1
assert aborted and 0 <= aborted[0] - deadline < 0.25
reset = False
async with asyncio.timeout(2):
try:
while await loop.sock_recv(client, 4096):
pass
except ConnectionResetError:
reset = True
assert reset, "Expected abortive close, not graceful buffered delivery"
else:
assert not writer.is_closing() and not aborted and not guard.pending
return {
"case": "blocked-receiver" if blocked else "transport-ack-without-device-reply",
"bytes": len(payload),
"kernel_queued_before_deadline": kernel,
"asyncio_queued_before_deadline": buffered,
"deadline_seconds": deadline - started,
"abort_seconds": aborted[0] - started if aborted else None,
"peer_reset": reset if blocked else False,
"passed": True,
}
finally:
if guard:
guard.abort()
client.close()
finished.set()
if accepted.done():
await asyncio.wait_for(handler_done.wait(), 2)
server.close()
await server.wait_closed()
async def main():
assert sys.platform == "linux", "Qualify on the supported Linux host"
result = {
"session_id": str(uuid.uuid4()),
"version": VERSION,
"started_utc": datetime.now(UTC).isoformat(),
"monotonic": time.monotonic(),
"cases": [],
}
for blocked in (False, True):
result["cases"].append(await qualify(blocked))
result["completed_utc"] = datetime.now(UTC).isoformat()
print(json.dumps(result, indent=2))
if __name__ == "__main__":
asyncio.run(main())
-286
View File
@@ -1,286 +0,0 @@
"""Crash and response-loss qualification on isolated loopback sockets and SQLite.
Uses the installed ndc_vps package unchanged. One synthetic tracker at a time,
no production database, TLS endpoint, firewall, physical device or service change.
The internal HTTP loopback harness does not qualify production TLS transport.
"""
import asyncio
import hashlib
import json
import os
import struct
import sys
import tempfile
import time
import uuid
from datetime import UTC, datetime
from pathlib import Path
from ndc_vps import VERSION
from ndc_vps.service import Service
from ndc_vps.store import Store
IMEI = "123456789012345"
TOKEN = "synthetic-owner-token-" + "a" * 32
def initialize(root):
(root / "host.json").write_text(
json.dumps(
{
"host_id": "vps_" + "a" * 64,
"tracker": {"host": "synthetic.example", "port": 9922},
}
)
)
store = Store(root)
store.set_devices([{"imei": IMEI, "instance_id": "c" * 32}])
with store.db() as db:
db.execute(
"INSERT INTO state VALUES('owner',?)",
(
json.dumps(
{
"core_id": "synthetic",
"token": hashlib.sha256(TOKEN.encode()).hexdigest(),
}
),
),
)
return store
async def child(root):
service = Service(Store(root))
api = await asyncio.start_server(service.api, "127.0.0.1", 0)
tracker = await asyncio.start_server(service.tracker, "127.0.0.1", 0)
print(
json.dumps(
{"api": api.sockets[0].getsockname()[1], "tracker": tracker.sockets[0].getsockname()[1]}
),
flush=True,
)
async with api, tracker:
await asyncio.gather(api.serve_forever(), tracker.serve_forever())
class Harness:
def __init__(self, root):
self.root, self.process, self.peer = root, None, None
self.store = initialize(root)
self.frames = []
async def start(self):
self.process = await asyncio.create_subprocess_exec(
sys.executable,
str(Path(__file__).resolve()),
"--child",
str(self.root),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
line = await asyncio.wait_for(self.process.stdout.readline(), 8)
if not line:
raise RuntimeError((await self.process.stderr.read()).decode())
self.ports = json.loads(line)
async def stop(self):
if self.peer:
self.peer[1].transport.abort()
self.peer = None
if self.process and self.process.returncode is None:
self.process.kill() # Deliberately no graceful drain or in-memory handoff.
await asyncio.wait_for(self.process.wait(), 5)
async def restart(self):
await self.stop()
await self.start()
def body(self, **extra):
return {
"id": uuid.uuid4().hex,
"imei": IMEI,
"kind": "request-position",
"model": 231,
"firmware": "0.01",
"not_after": time.time() + 15,
**extra,
}
async def http(self, method, path, body=None, *, loss=None):
reader, writer = await asyncio.open_connection("127.0.0.1", self.ports["api"])
data = json.dumps(body or {}).encode()
header = (
f"{method} {path} HTTP/1.1\r\nHost: localhost\r\n"
f"Authorization: Bearer {TOKEN}\r\nContent-Length: {len(data)}\r\n\r\n"
).encode()
try:
writer.write(header + (data[:-4] if loss == "before-body" else data))
await writer.drain()
if loss == "before-body":
return None
if loss == "after-commit":
async with asyncio.timeout(3):
while True:
with self.store.db() as db:
exists = db.execute(
"SELECT 1 FROM commands WHERE id=?", (body["id"],)
).fetchone()
if exists:
return None # The client intentionally never observes the HTTP result.
await asyncio.sleep(0.02)
raw = await asyncio.wait_for(reader.read(), 4)
head, payload = raw.split(b"\r\n\r\n", 1)
return int(head.split()[1]), json.loads(payload)
finally:
writer.transport.abort()
async def get(self, body):
status, result = await self.http("GET", "/v1/commands/" + body["id"])
assert status == 200, result
return result
async def submit(self, body, **kwargs):
value = await self.http("POST", "/v1/commands", body, **kwargs)
if value is not None:
assert value[0] == 200, value
return value[1]
async def connect(self):
if self.peer:
self.peer[1].transport.abort()
self.peer = await asyncio.open_connection("127.0.0.1", self.ports["tracker"])
self.peer[1].write(b"\xff\x23" + int(IMEI).to_bytes(8, "little"))
await self.peer[1].drain()
assert len(await asyncio.wait_for(self.peer[0].readexactly(9), 2)) == 9
async def frame(self):
first = await asyncio.wait_for(self.peer[0].readexactly(4), 3)
raw = first + await asyncio.wait_for(self.peer[0].readexactly(first[1] + 1), 2)
assert raw[0] == 0x7B and raw[-1] == 0x7D
self.frames.append(raw)
return raw
async def no_frame(self):
try:
data = await asyncio.wait_for(self.peer[0].read(1), 0.35)
except TimeoutError:
return
raise AssertionError(f"Unexpected data or connection loss: {data.hex()}")
async def reply(self, frame):
payload = struct.pack("<I", int(time.time())) + b"\0" + frame[5:9]
raw = b"[\x01\x09\x05\0" + payload + bytes([sum(payload) % 256]) + b"]"
self.peer[1].write(raw)
await self.peer[1].drain()
assert await asyncio.wait_for(self.peer[0].readexactly(4), 2) == b"{\0\x01}"
async def qualify():
result = {
"session_id": uuid.uuid4().hex,
"version": VERSION,
"started_utc": datetime.now(UTC).isoformat(),
"monotonic": time.monotonic(),
"physical_devices_used": False,
"production_state_used": False,
"cases": [],
}
with tempfile.TemporaryDirectory(prefix="ndc-vps-faults-") as name:
harness = Harness(Path(name))
await harness.start()
try:
# Lost upload before any accepted operation.
body = harness.body()
await harness.submit(body, loss="before-body")
status, _ = await harness.http("GET", "/v1/commands/" + body["id"])
assert status == 400
await harness.submit(body)
await harness.connect()
await harness.reply(await harness.frame())
assert (await harness.get(body))["state"] == "device_confirmed"
result["cases"].append({"name": "lost-request-retry-same-id", "passed": True})
# Lose HTTP result, then kill the process with a durable queued read.
await harness.restart()
body = harness.body()
await harness.submit(body, loss="after-commit")
await harness.restart()
queued = await harness.submit(body)
assert queued["state"] == "queued" and queued["expires_at"] == body["not_after"]
await harness.connect()
frame = await harness.frame()
await harness.submit(body)
await harness.no_frame()
await harness.reply(frame)
assert (await harness.get(body))["state"] == "device_confirmed"
result["cases"].append({"name": "lost-http-response-crash-queued-read", "passed": True})
# No tracker until after the original deadline, even across SIGKILL.
await harness.restart()
body = harness.body(not_after=time.time() + 0.8)
await harness.submit(body)
await harness.restart()
await asyncio.sleep(max(0, body["not_after"] - time.time()) + 0.1)
await harness.connect()
await harness.no_frame()
assert (await harness.submit(body))["state"] == "expired"
result["cases"].append({"name": "offline-expiry-not-extended-by-crash", "passed": True})
# TCP accepted the bytes; no command ACK. The runtime must not say success.
body = harness.body(not_after=time.time() + 0.8)
await harness.submit(body)
await harness.frame()
await asyncio.sleep(max(0, body["not_after"] - time.time()) + 0.1)
assert (await harness.get(body))["state"] == "unconfirmed"
await harness.restart()
await harness.connect()
await harness.no_frame()
assert (await harness.submit(body))["state"] == "unconfirmed"
result["cases"].append({"name": "tcp-ack-without-command-reply", "passed": True})
# Effect bytes were received by the synthetic peer; crash before a reply.
body = harness.body(kind="set-output", pin=4, enabled=True, password="123456")
await harness.submit(body)
frame = await harness.frame()
assert frame[2] == 0xFC and b"*SERV*8.4.1" in frame
await harness.restart()
await harness.connect()
assert (await harness.submit(body))["state"] == "uncertain"
await harness.no_frame()
result["cases"].append({"name": "dispatched-output-crash-no-replay", "passed": True})
# A fresh independent read still works on the same identity after recovery.
body = harness.body()
await harness.submit(body)
await harness.reply(await harness.frame())
assert (await harness.get(body))["state"] == "device_confirmed"
with harness.store.db() as db:
assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
assert db.execute("SELECT COUNT(*) FROM commands").fetchone()[0] == 6
assert (
db.execute("SELECT instance FROM devices WHERE imei=?", (IMEI,)).fetchone()[0]
== "c" * 32
)
result["cases"].append(
{"name": "identity-and-history-survive-recovery", "passed": True}
)
assert len(harness.frames) == 5
result["received_command_frames"] = len(harness.frames)
finally:
await harness.stop()
result.update(
completed_utc=datetime.now(UTC).isoformat(),
elapsed_seconds=time.monotonic() - result["monotonic"],
ok=True,
)
return result
if __name__ == "__main__":
os.umask(0o077)
if len(sys.argv) == 3 and sys.argv[1] == "--child":
asyncio.run(child(Path(sys.argv[2])))
else:
print(json.dumps(asyncio.run(qualify()), indent=2))
-95
View File
@@ -1,95 +0,0 @@
"""Durable intent versus attempts over real isolated sockets and hard process loss."""
import asyncio
import json
import tempfile
import time
import uuid
from datetime import UTC, datetime
from pathlib import Path
from ndc_vps import VERSION
from qualify_faults import Harness
async def qualify():
result = {
"session_id": uuid.uuid4().hex,
"version": VERSION,
"started_utc": datetime.now(UTC).isoformat(),
"monotonic": time.monotonic(),
"physical_devices_used": False,
"production_state_used": False,
}
with tempfile.TemporaryDirectory(prefix="ndc-vps-operations-") as name:
h = Harness(Path(name))
await h.start()
try:
body = h.body()
body.pop("not_after")
async def get():
status, value = await h.http("GET", "/v1/operations/" + body["id"])
assert status == 200, value
return value
# Truncated client request admits nothing. Stable ID recovers admission.
await h.http("POST", "/v1/operations", body, loss="before-body")
assert (await h.http("GET", "/v1/operations/" + body["id"]))[0] == 400
assert (await h.http("POST", "/v1/operations", body))[0] == 200
await h.restart()
assert (await get())["attempt_count"] == 0
await h.connect()
first = await h.frame()
assert (await get())["state"] == "dispatched"
# Lose response, hard kill VPS. The user job survives its uncertain attempt.
await h.restart()
pending = await get()
assert pending["state"] == "queued" and pending["attempt_count"] == 1
await asyncio.sleep(max(0, pending["next_attempt_at"] - time.time()) + 0.1)
await h.connect()
second = await h.frame()
assert first[5:9] != second[5:9]
await h.reply(first) # Delayed receipt must not finish a newer attempt.
assert (await get())["state"] == "dispatched"
await h.reply(second)
confirmed = await get()
assert confirmed["state"] == "device_confirmed" and confirmed["attempt_count"] == 2
await h.no_frame()
await h.restart()
assert await get() == confirmed
assert (await h.http("POST", "/v1/operations", body))[1] == confirmed
status, history = await h.http("GET", "/v1/operations/" + body["id"] + "/attempts")
assert status == 200 and len(history["items"]) == 2
assert [i["state"] for i in history["items"]] == ["device_confirmed", "uncertain"]
# Cancellation arriving before a delayed POST survives a crash as a tombstone.
stopped = {**body, "id": uuid.uuid4().hex}
await h.http(
"POST", "/v1/operations/" + stopped["id"] + "/cancel", {"kind": stopped["kind"]}
)
await h.restart()
assert (await h.http("POST", "/v1/operations", stopped))[1]["state"] == "stopped"
with h.store.db() as db:
assert db.execute("SELECT count(*) FROM operations").fetchone()[0] == 1
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 2
result.update(
passed=True,
attempts=2,
intents=1,
hard_restart_recovery=True,
late_receipt_isolated=True,
cancelled_post_not_admitted=True,
elapsed_seconds=time.monotonic() - result["monotonic"],
)
return result
finally:
await h.stop()
async def main():
async with asyncio.timeout(25):
print(json.dumps(await qualify(), indent=2))
if __name__ == "__main__":
asyncio.run(main())
-82
View File
@@ -1,82 +0,0 @@
"""Two real loopback streams, one synthetic B2, no physical commands or state."""
import asyncio
import json
import struct
import tempfile
import time
import uuid
from datetime import UTC, datetime
from pathlib import Path
from ndc_vps import VERSION
from qualify_faults import Harness
async def qualify():
result = {
"session_id": uuid.uuid4().hex,
"version": VERSION,
"started_utc": datetime.now(UTC).isoformat(),
"monotonic": time.monotonic(),
"physical_devices_used": False,
"production_state_used": False,
}
with tempfile.TemporaryDirectory(prefix="ndc-vps-receipts-") as name:
harness = Harness(Path(name))
alternate = None
await harness.start()
try:
await harness.connect()
alternate = harness.peer
harness.peer = None # Keep the first monitoring stream open.
await harness.connect()
body = harness.body()
await harness.submit(body)
wire = await harness.frame() # Most recently active stream wins dispatch.
async def reply(code):
data = struct.pack("<I", int(time.time())) + bytes((code,)) + wire[5:9]
alternate[1].write(b"[\x01\x09\x05\0" + data + bytes([sum(data) % 256]) + b"]")
await alternate[1].drain()
assert await asyncio.wait_for(alternate[0].readexactly(4), 2) == b"{\0\x01}"
await reply(6)
accepted = await harness.get(body)
assert accepted["state"] == "dispatched" and accepted["device_code"] == 6
assert accepted["reply_via_alternate_session"] is True
await reply(0)
confirmed = await harness.get(body)
assert confirmed["state"] == "device_confirmed"
assert confirmed["device_accepted_at"] == accepted["device_accepted_at"]
await reply(5) # A duplicate cannot downgrade a committed result.
assert await harness.get(body) == confirmed
await harness.no_frame()
alternate[1].transport.abort()
alternate = None
await harness.restart()
assert await harness.get(body) == confirmed
with harness.store.db() as db:
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 1
result.update(
passed=True,
sends=len(harness.frames),
alternate_stream_confirmed=True,
ack_not_final=True,
result_survived_sigkill=True,
elapsed_seconds=time.monotonic() - result["monotonic"],
)
return result
finally:
if alternate:
alternate[1].transport.abort()
await harness.stop()
async def main():
async with asyncio.timeout(20):
print(json.dumps(await qualify(), indent=2))
if __name__ == "__main__":
asyncio.run(main())
-158
View File
@@ -1,158 +0,0 @@
"""SIGKILL during full-image verification; isolated synthetic B2 and SQLite."""
import asyncio
import hashlib
import json
import os
import tempfile
import time
import uuid
from datetime import UTC, datetime
from pathlib import Path
from ndc_vps import VERSION
from ndc_vps.commands import frame
from ndc_vps.usb_protocol import Configuration, Setting
from ndc_vps.web_protocol import decode_settings_reply
from qualify_faults import IMEI, Harness
async def web(harness, opcode, payload=b""):
data = int(IMEI).to_bytes(8, "little") + bytes.fromhex("0001e7020000")
data += bytes([opcode]) + payload
body = b"[\x01" + len(data).to_bytes(2, "big") + data + b"]"
reader, writer = await asyncio.open_connection("127.0.0.1", harness.ports["tracker"])
try:
writer.write(
b"POST /c/index.php HTTP/1.1\r\n"
+ f"Content-Length: {len(body)}\r\n\r\n".encode()
+ body
)
await writer.drain()
try:
header = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), 3)
except asyncio.IncompleteReadError as error:
assert not error.partial
return None
except ConnectionResetError:
return None # Linux abortive close when no settings image is authorized.
size = next(
int(line.split(b":")[1])
for line in header.split(b"\r\n")
if line.lower().startswith(b"content-length:")
)
return await asyncio.wait_for(reader.readexactly(size), 3)
finally:
writer.transport.abort()
async def stage(harness, body, expected):
pending = await harness.get(body)
await asyncio.sleep(max(0, pending.get("not_before", 0) - time.time()) + 0.05)
# Fresh telemetry wakes the sender after stage pacing, as in production.
data = int(time.time()).to_bytes(4, "little") + b"\x63\0\0\0\0"
harness.peer[1].write(b"[\x01\x01\x05\0" + data + bytes([sum(data) % 256]) + b"]")
await harness.peer[1].drain()
assert await asyncio.wait_for(harness.peer[0].readexactly(4), 3) == b"{\0\x01}"
assert await harness.frame() == frame("123456*SERV*1." + str(expected))
async def qualify():
start = time.monotonic()
result = {
"session_id": uuid.uuid4().hex,
"started_utc": datetime.now(UTC).isoformat(),
"started_monotonic": start,
"version": VERSION,
"physical_devices_used": False,
"production_state_used": False,
}
before = Configuration(
tuple(
Setting(n, v)
for n, v in (
(3, b"example.org"),
(4, b"\x26\xc2"),
(5, b"123456"),
(8, b"\0"),
(70, b"example.org"),
(71, b"\x26\xc2"),
(25, b"\0\x0f"),
(222, b"opaque"),
)
)
)
target = Configuration(
tuple(Setting(r.number, b"\0\x10" if r.number == 25 else r.value) for r in before.records)
)
with tempfile.TemporaryDirectory(prefix="ndc-vps-recovery-") as name:
harness = Harness(Path(name))
await harness.start()
try:
await harness.connect()
body = harness.body(
kind="configure-all",
password="123456",
not_after=time.time() + 150,
expected_sha256=hashlib.sha256(before.encode()).hexdigest(),
target_configuration=target.encode().hex(),
)
accepted = await harness.submit(body)
assert await harness.frame() == frame("123456*SERV*1.9")
assert await web(harness, 5, before.encode()) == bytes.fromhex("5b00030005015d")
await stage(harness, body, 8)
assert decode_settings_reply(await web(harness, 2)).encode() == target.encode()
await harness.restart() # image received, readback not yet dispatched
pending = await harness.get(body)
assert pending["state"] == "queued" and pending["recovery_count"] == 1
assert pending["expires_at"] == accepted["expires_at"]
await harness.connect()
assert await web(harness, 2) is None # never re-serve the settings image
await stage(harness, body, 9)
await harness.restart() # readback sent, but no result yet
pending = await harness.submit(body) # same immutable operation
assert pending["state"] == "queued" and pending["recovery_count"] == 2
assert pending["expires_at"] == accepted["expires_at"]
await harness.connect()
assert await web(harness, 2) is None
await stage(harness, body, 9)
# B2-side reconnect after a read dispatch, with the VPS still alive.
await harness.connect()
pending = await harness.get(body)
assert pending["expires_at"] == accepted["expires_at"]
await stage(harness, body, 9)
assert await web(harness, 2) is None
assert await web(harness, 5, target.encode()) == bytes.fromhex("5b00030005015d")
final = await harness.get(body)
assert final["state"] == "verified" and final["recovery_verification"]
assert final["configuration"] == target.encode().hex()
await harness.restart()
assert await harness.get(body) == final
await harness.connect()
await harness.no_frame()
assert len(harness.frames) == 5
assert harness.frames.count(frame("123456*SERV*1.8")) == 1
with harness.store.db() as db:
assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 1
result.update(
ok=True,
crashes_during_operation=2,
image_writes=1,
independent_readbacks_sent=3,
tracker_reconnects_during_verification=1,
original_deadline_preserved=True,
durable_final_result=True,
command_rows=1,
)
finally:
await harness.stop()
result.update(
completed_utc=datetime.now(UTC).isoformat(), elapsed_seconds=time.monotonic() - start
)
return result
if __name__ == "__main__":
os.umask(0o077)
print(json.dumps(asyncio.run(asyncio.wait_for(qualify(), 80)), indent=2))
-131
View File
@@ -1,131 +0,0 @@
"""Bounded release self-check on isolated synthetic state; no physical tracker."""
import asyncio
import json
import struct
import tempfile
import time
from pathlib import Path
from ndc_vps.commands import Commands
from ndc_vps.service import Service
from ndc_vps.store import Store
async def qualify():
started = time.monotonic()
with tempfile.TemporaryDirectory(prefix="ndc-vps-runtime-") as directory:
root = Path(directory)
(root / "host.json").write_text(
json.dumps(
{
"host_id": "vps_" + "a" * 64,
"tracker": {"host": "synthetic.example", "port": 9922},
}
)
)
store = Store(root)
imei = "123456789012345"
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
body = {
"id": "a" * 32,
"imei": imei,
"kind": "request-position",
"model": 231,
"firmware": "0.01",
"not_after": time.time() + 20,
}
commands = Commands(store)
first = commands.submit(body)
commands = Commands(store)
assert commands.get(body["id"])["state"] == "queued"
assert commands.submit(body) == first
commands.sessions[imei] = {"new"}
wire = commands.take(imei, "new")
assert wire and commands.take(imei, "new") is None
data = struct.pack("<I", int(time.time())) + b"\0" + wire[5:9]
reply = b"[\x01\x09\x05\0" + data + bytes([sum(data) % 256]) + b"]"
commands.sessions[imei].add("second-monitoring-stream")
commands.receive(imei, reply, "second-monitoring-stream")
assert commands.submit(body)["state"] == "device_confirmed"
assert commands.take(imei, "new") is None
assert Commands(store).get(body["id"])["state"] == "device_confirmed"
with store.db() as db:
assert db.execute("SELECT COUNT(*) FROM commands").fetchone()[0] == 1
plan = db.execute(
"EXPLAIN QUERY PLAN SELECT id,body FROM commands WHERE imei=? "
"AND json_extract(body,'$.state') IN ('queued','dispatched') ORDER BY rowid",
(imei,),
).fetchall()
assert any("USING INDEX commands_active" in r[-1] for r in plan)
effect = {**body, "id": "b" * 32, "kind": "pulse-output", "pin": 4, "seconds": 1}
commands.submit(effect)
assert commands.take(imei, "new")
commands = Commands(store)
commands.sessions[imei] = {"after-crash"}
assert commands.submit(effect)["state"] == "uncertain"
assert commands.take(imei, "after-crash") is None
late = {**effect, "id": "d" * 32, "not_after": time.time() - 1}
assert commands.submit(late)["state"] == "expired"
assert commands.take(imei, "after-crash") is None
assert commands.wait_delay(imei) is None
service = Service(store)
service.commands.sessions[imei] = {"idle"}
original = service.commands.take_delivery
polls = []
written = asyncio.Event()
frames = []
def take(*args):
polls.append(time.monotonic())
return original(*args)
service.commands.take_delivery = take
class Writer:
def is_closing(self):
return False
async def drain(self):
pass
class Delivery:
def ready(self):
return True
def write(self, data, deadline):
frames.append(data)
written.set()
def abort(self):
pass
task = asyncio.create_task(service.send_commands(imei, Writer(), "idle", Delivery()))
try:
await asyncio.sleep(1.1)
assert len(polls) == 1
service.commands.submit({**body, "id": "f" * 32})
service.notify(imei)
await asyncio.wait_for(written.wait(), 1)
assert len(frames) == 1
finally:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
assert not service.wake
return {
"ok": True,
"monotonic_seconds": time.monotonic() - started,
"queued_read_survived_restart": True,
"duplicate_post_single_operation": True,
"dispatched_effect_not_replayed": True,
"expired_effect_not_dispatched": True,
"active_query_uses_index": True,
"idle_checks_over_1_second": 1,
"new_command_woke_idle_sender": True,
"physical_devices_used": False,
}
if __name__ == "__main__":
print(json.dumps(asyncio.run(qualify()), sort_keys=True))
@@ -0,0 +1,77 @@
# B2: PIN delivery, history repeat and post-boot SIM network codes
Date: 2026-09-28. Core base: `03d44d0`. VPS Host: **0.1.42**.
## Corrected delivery window
VPS sender admission requires device input no older than 5 seconds. The live B2
reported approximately every 15 seconds. Output requests previously expired in
3 seconds, often before the next eligible input. The inspected expired PIN4
request had no dispatch or transport record: it never reached the tracker.
PIN4–6 output/pulse requests now wait up to 30 seconds on their admitted original
connection, with total expiry capped at 60 seconds and the original Core request
deadline. All existing freshness, session, output-mode and firmware guards remain.
A dispatched output is never retried automatically or replayed across reconnect
or process restart. Other action deadlines are unchanged. The 3-second output
windows described in older runtime documents are superseded by this release.
A separate old PIN5 pulse was written to TCP but expired without transport ACK.
This is distinct from queue expiry; neither establishes electrical actuation.
## Explicit repeat
Each history row has a canonical circular refresh action after Details. An
in-flight row is disabled. Each deliberate repeat creates a fresh intent, while
retries after a lost HTTP response reuse the persisted request ID. The normal
Core FIFO, identity/firmware checks and output-mode checks still apply.
Settings/SIM repeats recover their intended target from revision history, not
from the transport outbox (which is deleted after acknowledgement). Changed
settings, device/host identity, card-bound automatic access or missing old
parameters reject the repeat explicitly. Current settings are never silently
substituted for a different historical action. A queued repeat also checks its
plan fingerprint immediately before starting.
## Current physical evidence
A repeat of a historical configuration read succeeded via the product UI, with
one attempt and 207 records returned. After explicit owner authorization, one
PIN4 five-second pulse was dispatched 0.772 seconds after Core acceptance; TCP
acknowledged it in 1.505 seconds. A `SERV OK` text packet was also received.
FC replies have no command token. They do not establish correlated execution or
contact position. Telemetry before/after the pulse showed PIN4 off, but did not
sample the five-second interval. Electrical switching remains unproved. The UI
now says “Результат не подтверждён”; the FC explanation no longer falsely states
that no device reply was received at all.
## SIM evidence and presentation
The owner's complete power cycle changed fresh DS2 to both SIMs registered,
GPRS on SIM1. From 20:18:55 through 20:25:10 Moscow time, raw TAG8 carried MCC=0,
MNC=1 despite registration and working GPRS. At 20:25:25 it became 250-01 (MTS),
before this code/deployment. SIM2 reported 250-02 (MegaFon).
Missing MCC is distinguished from absent SIM and disconnected internet. The UI
states that internet is connected but B2 has not supplied the operator network
code; it never guesses a carrier from MNC alone. The reason for delayed MCC and
hot insertion detection remains a firmware/modem investigation, not a proven
Core decoder defect. Firmware was not changed.
## Validation and release
250 focused backend/VPS tests passed across two non-overlapping test selections;
1017 frontend tests, architecture/type checks and production build passed. After
the FC copy refinement, 16 focused frontend tests and a new build passed. Two
independent VPS builds matched. Core remains healthy on 8000; no backend on 8765.
The exact installer was applied with its reviewed plan and automatic health
rollback, then published to the operator's existing installer catalog. Previous
release, credentials and state were preserved; VPN/routing were unchanged.
- PYZ SHA-256: `b1eac7ccc68f165a26838e8c01cd5ab630087df2783d8c6079dab057a5e98c9e`
- Release SHA-256: `62c4d4cc32f8ed2f20efba5af4c528be6d5ad7d9bd047774c54df139b20635e9`
Private command identities and redacted live receipts are retained in the local
`outputs/arnavi-sim-investigation-20260928` follow-up report/evidence.
@@ -0,0 +1,124 @@
# Durable manual commands and protocol ACK handoff
Date: 2026-09-28. Installed VPS Host: **0.1.43**. This supersedes the
queue-lifetime conclusions in `COMMAND_DELIVERY_AND_REPLAY_20260928.md`.
## Faults established
The user's second failure was not solved by 0.1.42's 3 → 30 second dispatch
window. Core PIN4-on and PIN6-pulse jobs expired behind another operation and
never reached VPS. Two later off jobs reached VPS but never dispatched. A
separate PIN4-on reached a socket but had no TCP ACK before its transport bound.
These are three distinct failure stages; the earlier fix was incomplete.
A bounded passive VPS capture showed fresh B2 packages followed by our own
four-byte protocol ACK, with TCP acknowledgement sometimes delayed about
17 seconds. The sender checked for an empty queue after writing that ACK,
so this very exchange could exclude itself from command admission. Commands
were additionally bound to the sockets present at submission, although mobile
reconnection could replace them before their first dispatch.
FC output commands have no transaction token. Waiting a minute for a token
receipt that cannot arrive blocked Core's next jobs until their 30-second
queue deadlines expired. Packet size did not explain these application gates.
## New runtime contract
- A manual command is committed to SQLite before acceptance. Its job has no
queue expiry; offline waiting and process restart preserve its identity.
- Scheduler-v2 removes the old 32-job admission ceiling. The backlog stays on
disk; Core prepares up to 16 and polls up to 8 per pass, and history is paged.
This is not a claim of unlimited disk capacity or billion-job throughput.
- Private Core dispatch bodies survive lost HTTP replies unchanged. Multiple
jobs reach VPS independently of the device's current settings/position row.
Terminal jobs remove their private dispatch body while keeping public history.
- Manual jobs have priority over background reads between exchanges. An unsent
background read can yield. A dispatched exchange or settings write is not
interrupted. Each priority class preserves order, independently per tracker.
- Attempts keep bounded TCP lifetimes; an expired **unsent attempt** retries
under the same persistent job. Such expiry does not erase the job.
- Explicit output-level assignments may retry the same desired state. A pulse
with uncertain dispatch is retained as unconfirmed and requires an explicit
repeat; B2's FC protocol cannot deduplicate it or guarantee exactly-once effect.
- An exact freshly generated ACK tail may precede a command for five seconds,
only if its whole predecessor stream was drained. Another write revokes this
handoff. Older blocked prefixes, command bytes, stale input and revoked devices
remain excluded. A never-dispatched attempt may use a new admitted socket.
- A text output finishes as neutral `delivered` when TCP delivery is observed.
It releases the queue without claiming device execution or contact position.
Cancellation records a durable stop/tombstone and cancels an unsent attempt;
it cannot retract bytes already sent to the device.
## Physical check
Through the product's repeat buttons, three new OFF jobs were accepted within
0.544 seconds at 21:23:09 Moscow time. They were dispatched FIFO to the real B2:
| Output | Dispatch (MSK) | TCP ACK latency | Attempts | Final state |
| --- | --- | ---: | ---: | --- |
| PIN4 off | 21:23:19.981 | 8.271 s | 1 | delivered |
| PIN5 off | 21:23:29.271 | 1.253 s | 1 | delivered |
| PIN6 off | 21:23:31.419 | 1.756 s | 1 | delivered |
All three had completed by 21:23:33.177. Subsequent fresh TAG6 samples report
all three outputs false. They establish reported logical OFF states, not a
measured transition or external relay contacts. Old expired history was retained
and was not automatically replayed. No SIM, APN, firmware or device settings write
was performed in this increment.
Automatic approval review initially blocked a further pulse. The owner then
explicitly authorized as many tests as needed on all outputs. Four five-second
pulses (PIN6, PIN5, PIN4, PIN6 again) were dispatched once each and delivered in
2.256, 1.505, 1.504 and 0.752 seconds. Each isolated test interval contains a real
type-3 `SERV OK` response from B2, arriving 2.039, 1.517, 2.047 and 0.667 seconds
after dispatch. This is distinct from TCP ACK. The text lacks a transaction ID
and PIN, so it is observational evidence, not a generic per-job correlation rule.
PIN4 TAG6 samples show false → true → false. PIN5's short active interval was not
sampled; the subsequent state is false. PIN6 remained true beyond five seconds
in both tests and changed to false after explicit OFF. The documented command
was used unchanged (`SERV*24.6.0.5`). PIN6 timer/report behavior is a reproducible
open device-level issue, not successful pulse-duration acceptance. The owner
explicitly retained physical relay/LED verification; no contact claim is made.
One PIN6 OFF lost its first transport receipt; the same durable job retried and
completed on attempt two. Both OFF attempts have observed `SERV OK` responses,
illustrating why a state assignment can safely repeat while a pulse cannot.
All test jobs and subsequent operator OFF jobs finished; the latest sampled
PIN4/5/6 states are false. Raw package hashes, UTC/monotonic snapshot times,
redacted text replies and separate job identities are retained in private evidence.
## Validation and limits
- 262 focused backend/VPS regression cases passed, including new durable output,
cancellation, restart, lost HTTP response and independent job projection tests.
- 80 persisted jobs survive the old 32-job threshold and a simulated week offline.
- 100 synthetic device identities: one offline job stays queued while the other
99 finish independently; these outcomes survive runtime reconstruction.
This is a deterministic functional test, not 100 real cellular links or a
throughput, tail-latency, soak or resource-capacity qualification.
- 30 relevant frontend/architecture cases, TypeScript and production build pass.
- Staged release on the real Ubuntu VPS: three FIFO output frames through
isolated actual Linux loopback sockets in 2.660 seconds, one attempt each;
no production state/devices involved. Transport ACK and blocked-stream abort
qualifiers pass (0.751 s observed abort for a synthetic 0.750 s bound).
- Two independent builder outputs match. Ruff and diff whitespace checks pass.
- Core remains healthy at 8000; real B2 telemetry and VPS connectivity continue.
Further scaling acceptance requires real or representative concurrent sessions,
long-duration operation, backlog/reconnect bursts, resource measurements and
operator latency criteria. A working single-device exchange is not that gate.
## Installed artifact
- TAR: `96d40b3c4f88f4e78084b685c88de2c932c8578157cadb48aff4bfb3c5ac4194`
- PYZ: `0d1134574adf1f118c39ca4568dda556a24a6ab701d7f5c014b542268e3df0bd`
- Manifest/release: `a8aa2779b33315616cc591282d4840983d52c88ffbee7c8ed1d1657b4fb9599b`
- Exact plan: `e13022c830ac1d13f8d9a49a40cdaf20018e4b49c4a4c9511249f0cfc67aa3ec`
The canonical artifact installer returned healthy and retained 0.1.42 for rollback.
The same accepted PYZ is published to Core's operator catalog. VPN routes,
endpoint ports, identity files and firewall ownership are unchanged. Source work
remains uncommitted. Private IDs/timestamps and redacted output evidence are in
`outputs/arnavi-sim-investigation-20260928/command-runtime-evidence.json` outside
this repository.
@@ -0,0 +1,93 @@
# B2 231 / 0.06 — физическая проверка совместимости
Официальный образ установлен 28.09.2026 20:53:58 UTC после отдельного явного
принятия владельцем риска отсутствия отката на 0.01. Источник, SHA и процедура
в [исследовании горячей вставки](HOT_SIM_REINITIALIZATION_20260928.md).
## Подтверждённое поведение
- USB I7 → настройки → I7 подтверждает модель 231 / 0.06. Все старые 207
значений сохранены; USB возвращает ещё 13 новых полей, всего 220.
- При первой сетевой выгрузке после обновления устройство прислало старый
сохранённый образ из 207 полей, SHA
`624d6b44636c196079c0845d96369d74c90ca4736a75c4729c8f44482e99e383`.
Это отличается от расширенного USB-ответа, SHA
`6ef29781f3161405cb0e9fe4836cef8df2ef8038516d8e3ef26f4121dea08d1d`.
Эти два представления не объявляются побайтно одинаковыми; перед сетевой
записью нужен свежий сетевой predecessor, уже требуемый транзакцией.
- HTTP-запрос: 964 байта, payload 944, opcode5, metadata `0006e7020000`.
Старый декодер принимал только `0001e7020000` и закономерно отклонял 0.06.
Поддержаны ровно две наблюдённые metadata; другие версии/модели отклоняются.
Приватный серверный capture SHA
`117f79f7efdd5bcdba0afb5e52f616e0a7a5f909739fa4025a046f8f8a24c341`.
- Запрос позиции через очередь: token-correlated final code0, 1.712с.
- PIN5 pulse5с: транспортный delivered, 1.757с. Физический результат реле
не подтверждён этим измерением.
- Restart через очередь, уже с metadata 0.06 в Core/VPS: свежие данные по
новому соединению, одна попытка, 41.838с.
- Непрерывный hot-cycle SIM2: fallback на SIM1 состоялся; возвращённая SIM2
оставалась0 не менее120с после ответа владельца. Горячая вставка не исправлена.
## Изменения интеграции
Core передаёт фактически прочитанную версию0.06 вместо константы0.01.
VPS0.1.44 принимает наблюдённый HTTP-конверт и существующие команды для0.06.
Экспериментальный diagnostic-mode не получил автоматического разрешения0.06.
USB-запись полного профиля остаётся квалифицированной только для0.01;
чтение и официальный загрузчик — отдельные механизмы.
Изменены web_protocol.py, equipment_actions.py, equipment_network.py,
allowlists версии VPS в equipment_bootstrap.py/equipment_command_runtime.py,
VPS actions.py/full_configuration.py/commands.py и версия сервиса.
Добавлен tests/test_b2_firmware006.py: фактическая версия в плане, сохранение
неизвестных записей/порядка, точные разрешённые headers, отказ другим версиям
и diagnostic-mode.
Регрессии: 229 выбранных Python cases; один loopback case потребовал повторного
запуска вне sandbox из-за запрета bind и прошёл. После дополнения version
allowlists повторены 69 bootstrap/network/runtime cases. Ruff passed.
Frontend не менялся в этом приращении.
Установщик0.1.44 SHA
`f57f7e21f6e9f80772c9a46785825cfce0845e847e3954879a23b5f48e1757eb`;
manifest `53e8e1a9fe96daaf208b54691e524cf0f6e47597a97842b5956b783261141396`.
Штатный installer plan/apply вернул healthy, исходные paired state/БД/endpoint
сохранены. Core8000 обновлён через штатный launchd; USB-inspect обновил
карточку до0.06. Приватное состояние не редактировалось SQL-командами.
## Проверка сетевой записи
Первое чтение через0.1.44 получило исходные207полей. Следующий configure-all
не прошёл preflight за150с; write_reply_sent_at отсутствует, USB-образ не
изменился. Исследовательский job штатно остановлен, желаемый интервал Core
возвращён15с. Это не успешная запись и не доказательство невозможности записи.
Повтор после подтверждённого restart с непрерывным180с USB-журналом
`network006log-ad60aff5791e4725bdabf70c417c438e` дошёл до реальной записи16с.
Независимый сетевой readback вернул220полей вместо переданных207. Все207
целевых значений совпали, добавлены только46–49/240–248; интервал16с.
SHA-256 фактического readback
`29466f12e058dc5a1be977f7ca3b4b584434ed5129d5c15b832d6acea6338a04`.
Это первая материализация новых defaults прошивкой в сохранённом образе.
Строгая проверка корректно дала uncertain; её не ослабляли для выдачи успеха.
Последующее проверочное чтение было штатно остановлено, без повторной записи
неполного207-полевого образа.
После свежего USB-inspect220полей через штатный Core выполнена отдельная
сетевая транзакция восстановления15с. Сессия
`restore-settings006-5b8b701a21d34f44a8d40adb36978d87`: configure-all,
verified, одна попытка, полный независимый readback220полей совпал с исходным
USB-baseline0.06 `6ef29781f3161405cb0e9fe4836cef8df2ef8038516d8e3ef26f4121dea08d1d`.
Таким образом все старые и новые значения восстановлены точно. Первое
сохранение после миграции207→220 нельзя объявлять обычным точным byte-roundtrip
старого сохранённого файла; последующая запись полного220-полевого образа
прошла строгую проверку без изменений алгоритма сравнения.
Финальный независимый USB-снимок
`arnavi-read-015c53e0d72a4fd1a1476d5f6807b730`: FW0.06,220полей, тот же
исходный SHA, обеSIM=1, active2/GPRS4. Последняя проверка через обновлённые
Core и VPS0.1.44, уже с метаданными0.06 в реестре: position final code0 за
0.837с, PIN5 pulse5с delivered за1.254с, по одной попытке. Сессия
`actions006-5a9073bebd3f42879301cb08a882fcce`.
Горячая вставка остаётся непринятой. Нормализация конфигурации и успешные
сетевые команды не исправляют отсутствие повторной инициализации SIM.
@@ -1,5 +1,12 @@
# Граница прошивки и серверного рантайма # Граница прошивки и серверного рантайма
Обновление 29.09.2026 МСК: после явного согласия владельца на риск B2 обновлён
по USB с 0.01 до официальной 0.06. Все прежние параметры сохранены. Горячая
вставка SIM2 повторно не обнаружилась; факт обновления не закрыл проблему.
Подробности и непрерывный физический опыт:
[HOT_SIM_REINITIALIZATION_20260928.md](HOT_SIM_REINITIALIZATION_20260928.md).
Ниже сохранена исходная граница исследования до этого эксперимента.
Уточнение владельца 28.09.2026: перед дальнейшей автоматизацией проверить, Уточнение владельца 28.09.2026: перед дальнейшей автоматизацией проверить,
не пытаемся ли мы серверной конструкцией переопределить алгоритм самой B2. не пытаемся ли мы серверной конструкцией переопределить алгоритм самой B2.
@@ -0,0 +1,93 @@
# Попытка получить код B2 через USB-загрузчик, 29.09.2026
Владелец ранее разрешил изменение прошивки, включая риск потери устройства
и отсутствие возврата к 0.01. Повторное разрешение на B2 не требуется.
Эта проверка продолжает поиск собственного исправления горячего обнаружения
SIM; установка официальной 0.06 уже была проверена и проблему не устранила.
## Метод и границы
Статический анализ официального Configurator 251111 не выявил декодер DFW
в просмотренном пути загрузки. Из встроенного ZIP извлечён перечень 51 файла:
драйверы AT32, SIMCom, MediaTek, STM и установщик драйверов. Исходников B2
или дополнительного исполняемого образа там не найдено. EXE не запускался.
Образы 0.05 и 0.06 содержат 1840 общих уникальных выровненных блоков по
16 байт. Энтропия 0.06 — 7.99889 бит/байт; условная энтропия по позиции
байта modulo16 — примерно 7.977–7.982. Это признаки непрозрачного контейнера,
совместимые с блочным шифрованием, но не доказательство AES или конкретного
алгоритма. Ключ, декодер и валидный исполняемый образ пока не получены.
В 07:25:30.587 UTC одной штатной командой `>D 3;0` B2 переведён в загрузчик.
USB сменился на AT32 Mass Storage, VID/PID 2e3c:5730; диск LOADER_231
сопоставлен с устройством через IORegistry и sessionID. Во время работы
загрузчика обычная телеметрия трекера отсутствовала.
Обычному процессу macOS отказала в чтении raw-диска (errno13), а sudo без
пароля был недоступен. Владелец сам выполнил подготовленный ограниченный
скрипт с sudo в Terminal. Пароль в чат не передавался. Скрипт проверил
текущий USB sessionID, VID/PID, внешний USB-диск и имя тома; открыл его
только O_RDONLY и читал блоками по 512 байт. Никаких записей этим скриптом
не выполнялось. При этом смонтированный macOS том уже содержал .fseventsd:
нельзя утверждать, что ОС вообще не писала файловые метаданные.
Чтение: 07:29:29.922–07:29:34.360 UTC, **1032704 байта**, SHA-256
`bdf637bc47193f73e3dee9bc2ce0d3c8d313e0671428f95d97006b5306878207`.
Хэш независимо пересчитан после ответа владельца и совпал.
Размер был взят из diskutil TotalSize (размер файловой системы);
полный размер носителя Size/IOKitSize — 1045504 байта. Последние 12800 байт
не прочитаны. Поэтому это не полный дамп носителя и тем более не доказанная
резервная копия Flash MCU.
## Что реально найдено
- FAT-заголовок, таблицы, корневая запись LOADER_231 и метаданные macOS.
- По смещению **18432** — **все 157760 байт** официального `231-0.06.dfw`,
побайтно равные исходному файлу, SHA-256
`36135a214f62bfeac7f049fdedb1cb7c717b676cfe6027f7c72a026c39988625`.
Это содержимое существовало до повторной записи прошивки в этом опыте.
- Область от 176640 до конца прочитанной части заполнена FF. Среди
просмотренных слов не найдено кандидата на векторную таблицу Cortex-M
с SP в диапазоне 0x20000000–0x20080000 и Thumb handler в
0x08000000–0x08400000. Эвристика не является универсальным доказательством
отсутствия кода; читаемый исполняемый образ данным способом не получен.
Для сравнения прочитан официальный пример Artery
[virtual_msc_iap / flash_fat16.c](https://github.com/ArteryTek/AT32F403A_407_Firmware_Library/blob/master/project/at_start_f403a/examples/usb_device/virtual_msc_iap/src/flash_fat16.c).
В этом примере чтение обслуживается виртуальными FAT-структурами и нулями;
сам факт появления USB-диска не означает доступ к коду MCU. Реальный B2
отдаёт другое содержимое, включая DFW, поэтому переносить реализацию этого
примера на B2 нельзя. Точная модель MCU не установлена; пример или его
загрузчик на трекер не устанавливались.
## Восстановление и проверка
После сохранения образа в 07:34:58.167–07:35:01.079 UTC в тот же
квалифицированный LOADER_231 однократно записан исходный официальный 0.06:
157760 байт, запись и fsync завершены, автоматических повторов не было.
B2 сам вернулся в обычный USB-режим.
USB-снимок `arnavi-read-f60191abcda840ec9414cbdf955cfacd` подтвердил 0.06,
все **220** прежних настроек и прежний SHA-256:
`6ef29781f3161405cb0e9fe4836cef8df2ef8038516d8e3ef26f4121dea08d1d`.
Последнее DS2: SIM1=1, SIM2=1, active1, GPRS4. Независимая свежая телеметрия
через собственный VPS0.1.46 принята Core в 07:38:25.396 UTC: тот же статус,
сети МТС250-01 и МегаФон250-02. Core8000 operational=true.
USB-дескрипторы закрыты; трекер не оставлен в загрузчике.
Новых изменений Core/VPS в этом опыте нет. Приватный образ, квитанции,
конфигурация и манифест SHA находятся вне Git в
`outputs/arnavi-sim-investigation-20260928/firmware-patch-20260929`.
## Вывод и следующий технический барьер
Разрешение на модификацию есть. Получение кода через исследованную область
USB-диска не удалось: найдена копия уже доступного контейнера обновления.
Исправление алгоритма SIM требует исходников/SDK, декодирования DFW либо
другого подтверждённого доступа к исполняемой памяти/модему. Ни один такой
путь пока не квалифицирован. Аппаратные измерения и USB-UART владелец
исключил из доступных средств. Запрос производителю подготовлен отдельно,
но не отправлен.
Собственный патч прошивки не создан и не установлен. Горячая вставка
остаётся неисправленной; обе SIM после перезапуска не являются её приёмкой.
@@ -0,0 +1,566 @@
# Повторное обнаружение резервной SIM под питанием
2026-09-28. B2, модель 231, плата 231_V1.03 (прочитана владельцем), ПО 0.01;
VPS Host 0.1.43; штатный Core на 8000.
Продолжение проверки владельца: SIM2 МегаФон извлечена и возвращена при
работающей МТС SIM1, но снова не появилась в интерфейсе. Исходники прошивки
контроллера и модема недоступны; код Mission Core и VPS прочитан.
## Установленные факты до вмешательства
- Свежие INTERNAL-пакеты самого B2 более часа передавали SIM1=1, SIM2=0,
active=1, GPRS=4. В предыдущем свежем наблюдении обе карты были
зарегистрированы в 18:00:02 UTC. Это не зависший интерфейс.
- TAG99 декодирован согласно таблице производителя: состояние SIM2 занимает
биты 9–11; 0 означает, что устройство не обнаружило карту. Из этой величины
нельзя заключать, что оператор физически оставил слот пустым.
- После подключения USB без изменения внешнего питания снято пассивное
окно 19:27:12–19:27:57 UTC и штатные I7 → чтение настроек → I7.
USB DS2 совпал с сетевым статусом. Чтение не восстановило SIM2.
- Запреты GPRS обоих слотов сняты; поля 67/68/69 и 89/90/91 пусты.
SHA-256 конфигурации:
`624d6b44636c196079c0845d96369d74c90ca4736a75c4729c8f44482e99e383`.
- B2 продолжал посылать модему AT+CSQDS. Отдельные ненулевые значения RSSI
второго слота не являются доказательством готовности SIM или регистрации.
Старый SID в I7 также не доказывает новое обнаружение карты.
## Один штатный перезапуск без записи конфигурации
Создана одна операция `71d03fd40f7340389d691b722911692f`, preset `restart`.
Очередь зарегистрировала две попытки; отправка подтверждённой попытки —
19:29:34.102 UTC. Новых команд переключения слота, APN, выходов или прошивки нет.
В 19:29:39.986 USB переопределился; открытый читатель штатно сохранил принятые
байты и завершился с `usb_io_error_6`. Поток самого запуска в этом сеансе не
записан. Повторное открытие нового USB-сеанса выполнено в 19:30:57, поэтому
не заявляется непрерывная запись перезагрузки модема.
Первый пакет, сообщающий обе регистрации и GPRS=4, получен VPS в
19:30:26.692 UTC, измерен B2 в 19:30:17 UTC. От отправки перезапуска до
получения такого пакета — 52.590 с. Активна SIM2; сеть МегаФон 250-02,
SIM1 зарегистрирована в МТС 250-01. Снова поступили сетевые SID.
Операция завершилась `reconnected`.
Повторное USB-чтение 19:30:57–19:31:27 подтвердило обе регистрации и
побайтово прежнюю конфигурацию. Карты между чтениями не переставлялись.
**Вывод:** программная переинициализация B2 восстанавливает обнаружение
этой SIM2. Проблема локализована в обработке горячей вставки на стороне
устройства; интерфейс и VPS отражали его реальный отчёт. Это ещё не
разделяет алгоритм контроллера, прошивку модема и сигнал обнаружения разъёма.
Перезапуск — проверенное восстановление, а не исправление горячего обнаружения.
## Контроль извлечения резервной SIM1
После восстановления активной стала SIM2. Владелец подтвердил извлечение
теперь резервной МТС SIM1, сохраняя USB и внешнее питание. Пассивная запись
19:32:05–19:35:05 UTC содержит:
| Получение по USB, UTC | Наблюдение |
| --- | --- |
| 19:34:13.886 | Модем: `+CPIN: NOT READY` |
| 19:34:15.938 | B2 DS2: SIM1=0, SIM2=1, active=2, GPRS=4 |
| 19:34:19.743 | Модем: `+CREG: 0` |
Сетевой пакет с тем же состоянием измерен в 19:34:17 UTC. Передача через
SIM2 сохранилась. Подтверждение владельца об обратной установке МТС записано
в 19:38:55.621 UTC. Последующее пассивное окно 19:39:16–19:40:46 UTC снова
содержит только SIM1=0, SIM2=1, active=2, GPRS=4, без новых событий регистрации.
Конфигурация осталась прежней. Таким образом, через 111 секунд после
регистрации подтверждения владельца новая готовность SIM1 не наблюдалась.
Точное физическое время установки неизвестно. Между двумя USB-окнами есть
разрыв 19:38:26–19:39:16; непрерывная запись самого момента вставки не
получена, поэтому отсутствие события в этих файлах не доказывает, что модем
никогда его не отправлял.
Симптом воспроизведён для резервной МТС SIM1 при активном МегаФоне SIM2,
то есть он не ограничен одной картой МегаФон или вторым слотом. Перед
восстановлением создана отдельная штатная операция перезапуска
`4201ca66b2e3431ea933022d2f55dac6`; запись настроек не выполнялась.
## Восстановление и записанный запуск модема
Восстановительная команда отправлена с первой попытки в 19:41:35.803 UTC,
завершилась `reconnected`. Ограниченный наблюдатель после переопределения
USB открыл новый сеанс в 19:41:42.809 UTC и снял 90 секунд запуска. Он не
отправляет перезапуски, AT-команды или настройки; после пассивного окна
выполнены только I7 → чтение настроек → I7.
- 19:41:47.796 UTC: модем `+CPIN: READY` для SIM1.
- 19:41:48.815 UTC: `+CPINDS: READY` для SIM2.
- Получены обе полные согласованные последовательности CCID → SID → IMSI
с домашними сетями 25001 и 25002; исходные идентификаторы остаются приватными.
- DS2 последовательно показал поиск сети обеими картами, регистрацию обеих,
затем GPRS=4 через SIM1 в 19:42:33.090 UTC.
- USB-конфигурация по SHA-256 совпала с состоянием до всех опытов.
- Итоговое свежее измерение 19:43:31 UTC, полученное VPS в 19:43:35.655:
обе SIM зарегистрированы, SIM1 МТС активна, SIM2 МегаФон в резерве.
Это вторая успешная программная переинициализация в данном приращении,
теперь после воспроизведения на другом слоте. Точный механизм повторного
обнаружения без перезапуска остаётся не установлен. В начале записанного
запуска отсутствуют команды CSDT/CSMINS, но это не доказывает состояние их
сохранённых параметров внутри модема.
## Граница исправления
Не добавлены автоматические перезапуски по состоянию 0: внешнему серверу
неизвестно, пуст слот физически или вставленная карта не распознана.
Такой перезапуск по таймеру регулярно прерывал бы исправный основной канал.
Не подставлены вымышленные «обнаружена» и оператор из устаревшего SID.
В просмотренных командах B2 не квалифицирован повторный опрос резервного
слота без перезапуска. [Руководство SIMCom](https://simcom.ee/documents/SIM800/SIM800%20Series_AT%20Command%20Manual_V1.10.pdf)
описывает AT+CSDT/CSMINS для некоторых модемов,
но применимость к установленной модели, разводке детектора и доступный
проброс AT через B2 не установлены. Эти команды не отправлялись.
Новые версии B2 0.05/0.06 не имеют подтверждённого исправления этой проблемы
в изученном описании; обновление не выполнялось.
Приватные исходные потоки, UTC/monotonic, хеши, журнал перезапуска и обезличенный
сводный файл находятся в `outputs/arnavi-sim-investigation-20260928/` соседнего
операторского каталога. Исходные идентификаторы карт и логи в Git не внесены.
## Приоритет владельца и дополнительная проверка доступа к модему
Владелец назначил горячее обнаружение вставленной SIM задачей номер один.
Требуемый результат: при работающей основной SIM повторно установленная
резервная карта обнаруживается автоматически, получает свежую идентичность
и регистрацию; основной канал продолжает работу. Текущий результат остаётся
отрицательным. Восстановление обеих карт перезапуском этот пункт не закрывает.
Официальный Configurator 251111 исследован статически, без запуска EXE.
SHA-256: `f79af698160ce6009c58608ec5511fab1680eea472ba9d689835fb032f2fc6ec`.
Обработчик терминала `btn_SendClick` по адресу 0x77744c дописывает CRLF и
вызывает отправку 0x78aa08. Это доказывает наличие отправки строки в USB,
но само по себе не доказывает проброс этой строки внутреннему модему B2.
В просмотренных строках/обработчиках не найден квалифицированный путь
AT passthrough или команда повторной инициализации только резервной SIM.
Для проверки прямого пути выполнен один ограниченный читающий запрос `ATI`
с CRLF. Руководство SIMCom V1.10, раздел 2.2.9, определяет его как запрос
идентификации продукта с режимом NO_SAVE. Запрос не меняет настройки модема.
Сессия: `modem-identity-probe-fe25ce0e614940719b54865c77170416`.
- USB-идентичность и конфигурация прочитаны до и после; совпали полностью.
- Единственная отправка: 2026-09-28 19:56:04.024 UTC, 5 байт.
- До отправки записаны 2 секунды потока, после — 10 секунд. Поток продолжался;
приняты DS2 и штатный обмен B2 с модемом. Ответ модели на ATI не получен,
эхо ATI отсутствует. Из отрицательного результата нельзя заключать, что
иной поддержанный производителем путь AT не существует.
- SHA-256 приватного потока:
`6ac457d9f3c9b6b8b20a8657b7710293d296a2900516fb96669c65a92ead156e`.
- Не отправлялись escape-последовательности, варианты префиксов,
переключение SIM, CSDT/CSMINS, перезапуск или запись конфигурации/прошивки.
- В свежем сетевом измерении 19:58:00 UTC обе SIM зарегистрированы,
активна SIM1 МТС; SIM2 МегаФон в резерве. Это состояние после ранее
выполненного восстановления, а не результат горячего обнаружения.
## Что нужно установить для исправления
[SIM868 Series Hardware Design V1.07](https://simcom.ee/documents/SIM868/SIM868_Series_Hardware_Design_V1.07.pdf),
раздел 5.8, описывает линии SIM1_DET/SIM2_DET и включение hot plug через
AT+CSDT. Схема с отдельным контактом обнаружения отличается от схемы,
где этот сигнал не используется. [FAQ SIMCom](https://www.simcom.com/questions_related_to_network.html)
также связывает горячую вставку с аппаратным детектором и настройками модема.
Это сведения о семействе модулей, **не подтверждение разводки или настройки
конкретного B2**. На имеющихся фотографиях маркировка модуля обрезана.
Владелец прочитал единственную видимую маркировку платы: **231_V1.03**;
это ревизия B2, а не идентификация внутреннего модема. Точная модель модема
и версия его внутреннего ПО остаются не прочитаны.
Открыты три конкретных вопроса: подключены ли детекторы держателей в этой
ревизии B2, включена ли обработка вставки в модеме, обрабатывает ли её
контроллер B2. Извлечение, сопровождаемое CPIN NOT READY, не отвечает на них:
потеря связи с уже работающей картой и обнаружение новой карты — разные события.
Параметр APN определяет доступ в сеть после обнаружения SIM; его изменение
не подтверждает и не исправляет отсутствие события вставки.
Подготовленный технический запрос производителю (не отправлен): для B2
model 231 / PCB 231_V1.03 / FW 0.01 подтвердить поддержку горячей вставки неактивной SIM,
разводку SIM1_DET/SIM2_DET в ревизии платы, штатный способ прочитать состояние
детектора/настройки модема через USB или TCP и команду повторной инициализации
одного слота без сброса активного GPRS. Если требуется новая прошивка — указать
версию с этим исправлением, порядок проверки и поддержанный возврат на 0.01.
Воспроизведение есть на обоих слотах: извлечение определяется, возврат нет;
перезапуск без изменения настроек возвращает обе регистрации.
Приёмка исправления требует непрерывной записи момента извлечения/возврата,
свежих CPIN/CCID/IMSI и DS2/TAG99, сохранения основного канала и неизменных APN.
Повторить сценарий для обоих слотов и для другой карты в освобождённом слоте;
не считать старый SID или ненулевой RSSI доказательством обнаружения.
Затем отдельно проверить переход на новую резервную SIM после потери основной.
Ни один из этих пунктов пока не отмечен выполненным для исправленного механизма.
## Дополнительные пути диагностики
Повторный поиск 2026-09-28 не установил готовую команду горячего переопроса.
Команды устройства, его настройки и прошивка в этом приращении не изменялись.
1. **Список команд официального web-конфигуратора.** В публичном JavaScript
`https://ws.arusnavi.ru/js/index.01d2841b.js` список загружается отдельным
GET `/api/v1/devices/{deviceId}/commands`; сами команды не зашиты в этот
клиентский файл. Это оставшийся конкретный источник, если устройство
уже доступно в легитимной учётной записи владельца. Доступность команды
переопроса SIM не подтверждена. Авторизация не обходилась, устройство
не регистрировалось и никакие команды этого API не отправлялись.
`startServiceSession` запускает чтение сервисного журнала; просмотренный
компонент не предоставляет произвольную AT-консоль. IAB не загрузил
сайт по тайм-ауту; публичный JS получен напрямую через en0.
2. **Настройки обнаружения самого модема.** При квалифицированном доступе
полезны читающие `ATI`, `AT+CSDT?`, `AT+CSMINS?`, `AT+CDSDS?`:
идентификация, включение детектора, состояние вставки и состояние слотов.
Это кандидаты из руководств SIMCom, не список команд, уже проверенных
на B2. Ранее отправленный голый ATI не открыл такой доступ. Другие
перечисленные запросы не отправлялись. Общий CFUN/reset прерывает
радиоканал и не равнозначен требуемому восстановлению резервного слота.
3. **Непрерывный захват вставки и электрический детектор.** В предыдущем
опыте есть разрыв USB-записи вокруг подтверждения возврата SIM1.
Следующая проверка должна покрывать момент вставки без разрыва и
различать событие модема, ответ контроллера и сетевой TAG99. Если
программное событие не наблюдается, нужно подтвердить подключение
контакта детектора по схеме именно 231_V1.03; фотография платы и факт
обнаружения извлечения этого не доказывают. Неизвестные контакты платы
не замыкались и инструкции по подключению к ним не выдавались.
4. **Прошивка производителя.** Найденные 0.05/0.06 остаются кандидатами
для проверки после подтверждения исправления/совместимости и возврата.
Статический анализ Configurator 251111 показал чтение блоков `.dfw`
из файлового потока для отправки загрузчику. В просмотренном пути не
найден декодер образа. Образ 0.05 имеет высокую энтропию и не дал
читаемых строк кода; это не доказывает конкретный алгоритм шифрования.
Исполняемый файл конфигуратора не запускался, прошивка не загружалась.
Дополнительно исключён найденный в EXE `Bridge` (0x6a6614): это один
из типов внешних датчиков рядом с LLS/Escort/Thermo, не мост к модему.
Публичный каталог 8888 содержит Windows-версию. Позже по точной ссылке
из авторизованного кабинета найдена отдельная официальная страница
`http://app.arusnavi.ru/mapp_ru.html`: Device Configurator Mobile
20210624, USB/BlueTooth, журнал и список команд. Прямой AT-доступ или
горячее обнаружение SIM в описании не заявлены. Ссылка производителя
ведёт на `TrackerConfigurator_v20210624.apk` (8.8 MB) в Google Drive;
скачивание вернуло страницу предупреждения, APK не получен и не запускался.
Это другое приложение, чем Arnavi Sensor Configurator из Google Play,
предназначенный для BLE-датчиков.
Пересмотр сохранённых USB-потоков: в окне 19:39:16–19:40:46 UTC после
возврата SIM1 есть 23 запроса `AT+CSQDS`, но нет видимых запросов
CPIN/CCID/CIMI/CSDT/CSMINS. При восстановительном запуске есть выбор
слотов `AT+CDSDS=1,0`/`2,0`, чтение CCID/CIMI обоих и `AT+CREGDS?`.
Это наблюдение конкретных окон, не доказательство отсутствия алгоритма
во всей прошивке и не доказательство исправности аппаратного детектора.
При контрольном чтении журнала в 20:21:20 UTC обнаружен новый переход:
последнее измерение обеих регистраций — 20:01:00 UTC, первое SIM2=0 —
20:01:15 UTC, получено VPS в 20:01:18.729. В 20:21:12 UTC SIM1=1,
SIM2=0, active=1, GPRS=4. Владелец подтвердил, что обе карты физически
вставлены. Действия непосредственно перед переходом не установлены;
эпизод не назван самопроизвольным сбоем.
Новое USB-окно 20:22:38.888–20:23:24.236 UTC, сессия
`arnavi-read-63b80018a73e49dfbf95a8442b751850`, подтвердило то же состояние.
12716 байт; 14 запросов CSQDS, без видимых запросов переинициализации SIM.
SHA-256 потока `994554af9b81a05f37ef92d9d9b3e226b60a000782f1f4e407e763a2b3940be4`.
Конфигурация совпала с исходной. Сохранены 45 секунд пассивного потока и
I7 → настройки → I7; порт закрыт. Последующая запись локального кэша
получила ошибку относительного пути, исправлена обработкой уже сохранённых
файлов по абсолютному пути, без повторного обращения к устройству.
Core `/api/health` operational=true после чтения.
Владелец подтвердил наличие B2 в официальной учётной записи и открыл её
в Arc. Продолжение чтения каталога выполняется через эту авторизованную
страницу; пароль не запрашивался и не извлекался.
В доступном владельцу интерфейсе прочитаны паспорт, удалённая отладка,
системные и SIM-настройки. Удалённая отладка содержит кнопку начала
сеанса и журнал, без поля отправки AT. Сеанс не запускался. Раздел SIM
содержит обычные APN/GPRS/PIN/роуминг/баланс, без горячего переопроса.
Сохранённые APN в web-карточке отличаются от фактически прочитанных
пустых APN B2; серверная карточка не использовалась как свидетельство
текущей конфигурации. Сохранение или загрузка этих настроек не выполнялись.
Компонент динамического каталога команд относится к разделу Monitoring.
В меню этой учётной записи он не показан. Один прямой GET каталога
с известным из карточки идентификатором через новую вкладку Arc оставил
пустую страницу; читаемый ответ и HTTP-статус не получены. Это не
доказательство отсутствия команды или отказа 403. Флаги доступа и токены
не изменялись/не извлекались, альтернативные ID не перебирались.
Временная вкладка закрыта, исходная страница пользователя сохранена.
Дополнительное непрерывное USB-окно 20:32:32.197–20:35:32.551 UTC:
`arnavi-read-dbb62d1ad6fc453a9bb443dde2375f79`, 180 секунд наблюдения,
затем штатное чтение I7 → настройки → I7. Во всём потоке SIM1=1,
SIM2=0, active=1, GPRS=4; 42 CSQDS, нет видимых CPIN/CSMINS/CREG
событий. Конфигурация неизменна. SHA-256 потока:
`7a7ec8a04689245116fe7393464827d95c93e77560a9aa37db6678e83dc7cc38`.
Владелец подтвердил возврат МегаФона в SIM2 на границе завершения окна;
точное физическое время не сообщено. Поэтому это окно не выдано за
доказанный непрерывный захват самого события вставки. Нет оснований
считать отсутствие CPIN/CSMINS доказательством отсутствия электрического
сигнала детектора. Читатель штатно завершился и закрыл порт.
Итог поиска: доступны USB-журнал, сервисный журнал производителя и
конфигураторы; подтверждённой команды повторной инициализации резервной
SIM без потери активного GPRS пока нет. Для следующего диагностического
уровня нужен поддержанный доступ к AT-модему (сначала только чтение
его модели, CSDT/CSMINS/CDSDS), либо подтверждение разводки детектора
и исправления прошивки от производителя. Ни возможность команды из
общего руководства SIMCom, ни наличие Android-конфигуратора не означают,
что нужный путь уже доступен на этом B2.
## Официальная 0.06: установка и контроль 20:49–20:56 UTC
Владелец явно разрешил любые действия с этим B2, включая прошивку. После
двух отказов автоматической проверки он отдельно подтвердил установку
официальной 0.06 без резервного исполняемого образа 0.01, принимая риск
невозможности отката и повреждения. Третья попытка была разрешена.
Предыдущие ограничения на запись прошивки в этом исследовании этим
указанием отменены для конкретного трекера; переписка с третьими лицами
и изменения других устройств не разрешались.
Перед переходом сохранены I7 → настройки → I7. Модель 231, версия 0.01,
207 записей, SHA-256 конфигурации
`624d6b44636c196079c0845d96369d74c90ca4736a75c4729c8f44482e99e383`.
Сессия `loader-69addf72b74747679672b4c0026c0f4c`: в 20:49:36.174 UTC
однократно отправлены 8 байт `>D 3;0\r\n`, штатная команда
`act_UpdateSoftLocal` официального Configurator 251111. Последовал разрыв
старого последовательного USB-интерфейса. Новый USB 2e3c:5720
`AT32 Mass Storage` содержал единственный внешний диск `LOADER_231`.
Связь диска с USB-устройством проверена по IORegistry перед записью;
до команды внешних физических дисков не было.
20:53:55.544–20:53:58.466 UTC в корень этого накопителя однократно
скопирован и синхронизирован `231-0.06.dfw`, 157760 байт, SHA-256
`36135a214f62bfeac7f049fdedb1cb7c717b676cfe6027f7c72a026c39988625`.
Источник — ранее проверенная строка B2 в официальном авторизованном
каталоге; это не образ другой модели. Загрузчик сам вернулся в обычный
USB-режим. Повторное чтение `arnavi-read-246ea4024cf74facb677958612e12be4`
подтвердило модель 231 / **ПО 0.06**.
Новая конфигурация содержит 220 записей. Все прежние 207 значений совпали
побайтно; добавлены поля 46–49 и 240–248. SHA-256 нового полного образа:
`6ef29781f3161405cb0e9fe4836cef8df2ef8038516d8e3ef26f4121dea08d1d`.
Настройки серверов, SIM/APN, пароля и выходов не изменялись.
VPS получил телеметрию после обновления; обе SIM зарегистрированы.
В 20:55:54 UTC USB DS2: GPRS=4, active=2, SIM1=1, SIM2=1.
Core `/api/health` operational=true. Это подтверждение установки и
восстановления связи, **не подтверждение исправления горячей вставки**.
В 20:55:54 UTC начата пассивная непрерывная запись `hot-006-sim1`;
никаких команд в этом окне не отправляется. Максимум 20 минут, завершение
через 120 секунд после подтверждения владельцем возврата МТС в SIM1.
Активная SIM2 остаётся на месте. Ожидается физический цикл владельца.
Окно намеренно остаётся открытым до ответа, чтобы не повторить прежний
дефект эксперимента, когда подтверждение пришло на границе короткой записи.
Дополнение к предыдущему поиску: официальный Android APK 20210624 всё же
получен через обычную форму загрузки Google Drive, указанную производителем.
9227317 байт, SHA-256
`d56008bd3076746f552337ebd3943c28c7998b3e83821b6290d6e63292e111d2`.
Приложение не устанавливалось/не запускалось. В 17 DEX статически найдены
основные команды D0/D1/D2/D3/D4/D8/D15/D18/I0, но не отдельная команда
горячего переопроса или строки CSDT/CSMINS. Отсутствие строк само по себе
не доказывает отсутствия скрытого механизма.
Программные разрешения записи/команд Mission Core ранее квалифицированы
только для 0.01. Успешное чтение конфигурации и телеметрии 0.06 не является
основанием автоматически объявить квалифицированными все записи новой
версии; актуализация этой границы требует отдельной проверки протокола.
## Физический цикл на 0.06: проблема повторилась
Владелец уточнил: по ошибке извлечена активная МегаФон SIM2, а не резервная
МТС SIM1. Название сессии `hot-006-sim1` оставлено неизменным как исходный
идентификатор, но фактический сценарий — извлечение SIM2, автоматический
переход на SIM1, возврат SIM2. Запись началась до извлечения и без разрывов
охватывает весь цикл и 120 секунд после подтверждения возврата.
- 20:55:54.279 UTC: обе регистрации=1, active2, GPRS4.
- 20:58:02.430: SIM2=0, active1, GPRS2.
- 20:58:47.350: GPRS3, active1.
- 20:58:52.341: GPRS4, active1; переход занял 49.910 секунды между этими
наблюдениями, не точное время от механического извлечения.
- 20:59:57.168: получено подтверждение владельца «Вернул.» для МегаФона SIM2.
- До конца окна 21:01:57.419: SIM2 остаётся=0, SIM1=1/active1/GPRS4.
32807 байт, SHA-256
`bf96df9180c008962c47844dd9135726440673e7b46165b106eee4cfcb560142`.
Ни одной отправленной команды в окне. Последний сетевой пакет на момент
контрольного чтения: измерен 21:01:43, получен 21:01:56.550 UTC, тот же
SIM1=1/SIM2=0/active1/GPRS4. Старые SID-теги датированы запуском 20:54:42
и не являются обнаружением после возврата.
**Официальная 0.06 не устранила проблему в этом воспроизведении.**
Переключение при потере активной SIM работает; повторная инициализация
возвращённой карты при сохранении активной другой SIM не подтверждена.
Состояние сообщает сам B2 по двум каналам, не только UI/Core.
На 0.06 по умолчанию подробный AT-трафик в USB не выводился. Проверена
штатная кнопка Configurator `btnShowEnterClick`, VA 0x77a138: D9;1 включает
подробный журнал, D9;0 выключает. В отдельном ограниченном опыте появились
AT+CSQDS/CIPSEND/CIPRXGET. После выключения настройки побайтно прежние.
Повторён один читающий ATI с включённым журналом: ни эха ATI, ни модели
модема/Revision не получено; настройки прежние. Это не AT-порт модема по
наблюдённому поведению; произвольная команда CSDT не отправлялась.
Отдельная проверка штатной очереди после обновления (реальная USB-версия
0.06, сохранённая версия в реестре в этот момент ещё 0.01): запрос позиции
получил token-correlated final code0 за 1.712с; один PIN5 pulse5с получил
транспортный результат delivered за 1.757с. Сессия
`actions006-ecdd2af131b94d58b556153e14b45117`. Физическое положение реле
этим не подтверждается. Метаданные реестра/firmware guards проверяются
отдельно перед обновлением; legacy label не выдаётся за аппаратную версию.
## Заключительный срез после обновления интеграции
Core и собственный VPS0.1.44 получили поддержку наблюдённого конверта0.06;
карточка устройства обновлена штатным USB-inspect. Прочитаны и восстановлены
настройки через VPS с точным совпадением полного220-полевого образа0.06.
Выявлена отдельная нормализация при первом сохранении после обновления:
прошивка добавляет13полей в старый207-полевой файл. Она не замаскирована под
успешный byte-readback; подробный опыт и восстановление описаны в
[FIRMWARE_006_ACCEPTANCE_20260929.md](FIRMWARE_006_ACCEPTANCE_20260929.md).
Финальный USB-снимок `arnavi-read-015c53e0d72a4fd1a1476d5f6807b730`
подтверждает FW0.06, обеSIM зарегистрированы, активнаSIM2, GPRS4;
все220значений равны снимку сразу после обновления. Последняя проверка
очереди с корректной версией0.06: позиция final code0 за0.837с, PIN5 pulse5с
delivered за1.254с. USB-читатели и исследовательские jobs завершены.
**Главный результат остаётся открытым:** горячая вставка SIM2 воспроизведена
как неработающая и на0.06. Перезапуск восстановил обе карты, но не является
решением. Доступного через исследованные интерфейсы AT-переопроса SIM пока
нет. Следующий обоснованный шаг — сервисный доступ к модему/его hot-plug
настройке и проверка разводки детектора на PCB231_V1.03, либо исправление
производителя. Полные исходники/SDK B2 и проверенная команда такого доступа
в найденных официальных материалах отсутствуют. Это предел найденных
средств, не доказательство принципиальной невозможности доработки.
## 29.09: SIM868E, SERV1.2 и непрерывный цикл резервной SIM1
Фото владельца от 09:34 МСК однозначно показывает **SIMCom SIM868E**.
Это уточняет прежний раздел с обрезанной маркировкой; версия внутреннего ПО
модема по фотографии не установлена. Плата по-прежнему 231_V1.03, B2 — 0.06.
Владелец подтвердил номер назначения диагностического SMS (единственный
заданный телефон, окончание1197) и разрешил сообщение; остальные четыре
поля телефонов пусты. Полный номер, пароль и идентификаторы остались в
приватном evidence, не в этом отчёте.
Дополнительный штатный USB I0 квалифицирован по Configurator251111:
периодический опрос 0x78492a→0x78aa08, литерал0x784a0c. Он вернул
статистику и состояние, но не открыл AT-консоль. Сессия
`read-i0-637b02a35cf74fb4bb13588e1a6208a9`,2458байт, настройки неизменны.
Поля MD0..4 относятся к серверам/счётчикам; это не версия модема.
B2manual§10 описывает SERV1.2/0102 как информационный SMS, а общий
INTERNAL/SMS_COM — как повторный запрос ICCID. Реальное поведение проверено
отдельно, без предположения, что общая таблица означает поддержку B2.
- USB-текст, обеSIM зарегистрированы:
`serv12-0fb444ca2fe14913b2ee5f895bfae6f1`. После отправки по USB появился
**информационный ответ FW/IMEI/VIN/BAT**, но не CPIN/CCID/CIMI/CMGS.
Первоначальный краткий разбор по AT-командам не отметил этот ответ;
повторный разбор установил его прямо с rx-offset171, сразу после команды.
Не следует описывать этот опыт как полностью проигнорированную команду.
- TCP-текст:
`serv12-tcp-cb22a14c09404d4ca2b0beda90a5bb11`,06:48:54.907UTC.
В USB видны входящий FC-пакет и информационный ответ FW/IMEI/VIN/BAT
внутри исходящего INTERNAL packet3. Переопроса SIM нет. VPS завершил
транспортное наблюдение unconfirmed/delivery_deadline, что не отменяет
независимого USB-доказательства получения и обработки команды.
9031байт, SHA `e0e8ffec52e749a03003496c35f192c43d9cb1c67a35f9df620645d92e9e4498`.
- TCP-бинарный01 02 в документированном FF/token-конверте:
`serv12-binary-49ea7d33af004698b6f0b3ba7364e909`,06:53:42.028UTC.
7384байт, SHA `c4d3aaf090305bf10dad27076255053680e9beb910ddb48883f2f6d15e8fb4a4`.
Нет нового чтения SIM или CMGS; в этом окне подтверждение команды не получено.
Эти три опыта выполнялись при обеих зарегистрированных SIM и сами по себе
не исключали условный переопрос только отсутствующего слота. Поэтому выполнен
новый физический цикл с непрерывным D9-журналом:
`hot-serv12-46f557a0e6394ccf9e72881005949888`.
- 06:56:47.888UTC: SIM1=1, SIM2=1, active2, GPRS4.
- 06:57:47.779: после извлечения МТС SIM1=0; SIM2/active2/GPRS4 сохранены.
- 06:58:45.660: зафиксирован ответ владельца о возврате МТС. Это время
подтверждения, а не точный момент механического замыкания контактов.
- После 30с пассивного наблюдения SIM1=0. В06:59:22.454 отправлен один
TCP-текстовый SERV1.2; после45с SIM1 остаётся0.
- В07:00:22.875 отправлен один01 02 с новым токеном и новым observation lease.
VPS получил **device_confirmed, device_code0**; TCPACK0.502с.
Через45с SIM1 всё ещё0, SIM2=1/active2/GPRS4.
- За весь журнал нет CPIN/CCID/CIMI/CSDT/CSMINS/CDSDS/CMGS.
Присутствуют CSQDS и обмен TCP. Настройки побайтно прежние.
35823байта, SHA `b2f91918b47c670022b12f7681237f9c60a1107c75e94ffbac04a4946c22cae3`.
Успешный code0 подтверждает реакцию B2 на команду, **не восстановление SIM**.
В опыте нет признака отправленного SMS; получение сообщения телефоном не
заявляется. Извлечение и возврат зарегистрированы одним потоком без разрыва.
Для контролируемой проверки установлен собственный VPS0.1.46 (после0.1.45).
Engineering-only probe-sim-info принимает только фиксированные SERV1.2 или
0102 для231/0.06, требует sms_destination_confirmed=true, свежий эксклюзивный
observation lease и не воспроизводится после reconnect/restart. Это не новая
пользовательская команда и не автоматический SIM-poll. Ограничение окна
этого опыта не меняет бессрочное ожидание обычных ручных durable jobs.
Изменены actions.py,commands.py,__init__.py,allowlists в equipment_bootstrap.py,
equipment_command_runtime.py,equipment_network.py; добавлены проверки SMS
разрешения, точных кадров, истечения/закрытия lease, эксклюзивности и no-replay.
18целевых проверок прошли; исходные235регрессионных случаев прошли с отдельным
повтором одного localhost/socket case вне sandbox. Дополнительно69проверок
bootstrap/network/runtime прошли. Ruff passed.
Установщик0.1.46 SHA
`a1d0337cfa73b296e000fe7408b1a098b59462ec1dd1f23c028e5b00c22af6a0`,
manifest `40d19ad34a3096d18aafe471647854ca3d44fc364f68c18fa054863f190a4652`.
Штатный plan/apply вернулhealthy; paired state/БД/endpoint сохранены.
Маршрут — en0, без изменения VPN. Core8000 перезапущен штатным launchd.
Статический анализ самого официального0.06:157760байт, энтропия7.99889бит/байт,
нет читаемых AT/командных строк; начальные128смещений не дали zlib-потока.
Есть повторения16-байтовых блоков, но этого недостаточно для утверждения
конкретного алгоритма шифрования. Исполняемый код из DFW не извлечён;
исходники прошивки не выдаются за прочитанные. В проверенных путях Windows
Configurator присутствуют D0/D1/D2/D3/D4/D8/D9/D15/D18 и I0/I7, отдельный
переопрос SIM или AT-мост не установлен. Скрытый механизм этим не исключён.
Владелец исключил мультиметр/USB-UART из доступных методов. Аппаратная
прозвонка не является следующим обязательством владельца. На текущем
документированном USB/TCP-интерфейсе не установлен способ послать CSDT?
непосредственно SIM868E. Нельзя достоверно разделить разводку DET, настройки
внутреннего модема и обработчик B2 без такого доступа либо данных производителя.
Случайные D-команды, патч неизвестного DFW и периодический полный restart
не добавлялись как мнимое исправление горячей вставки.
Последний контроль в неисправном состоянии — **прямой USB SERV1.2**,
сессия `serv12-758f60a2e52f4dc6a3237b6222cad1c5`: получен один ответ
FW/IMEI/VIN/BAT; весь DS2 остаётся SIM1=0/SIM2=1/active2/GPRS4.
За35с после команды нет CPIN/CCID/CIMI/CDSDS/CMGS, настройки прежние.
4957байт, SHA `a5ec5e146fe0f11fbb34da900ac7fb1b2d7a69616527ebb0bae565ccb4daf0df`.
Таким образом отрицательный результат этого кандидата подтверждён и без
сетевой доставки. Подготовлен [точный запрос производителю](VENDOR_HOT_SIM_REPRO_20260929.md),
не отправлен. Горячая вставка остаётся открытым вопросом.
Восстановление: одна штатная операция restart через Core, две попытки в
журнале, итог reconnected. Между зарегистрированной отправкой и
восстановлением связи39.876с. Следующая position получила device_confirmed
code0 за0.925с, одна попытка. Сессия
`recovery-hot-serv12-3e4e2eec49b34dbba90231f540199ac4`.
Финальный USB-снимок `arnavi-read-24cb7b967d864778a768b9fe9ffa5fa6`:0.06, SIM1=1/SIM2=1/active2/GPRS4;
исходный SHA всех220настроек совпадает. Core8000 operational=true,
VPS/health отвечает; наблюдения закрыты, временные USB-процессы завершены.
Это восстановление после опыта, не исправление горячей вставки.
## 29.09: чтение диска загрузчика для поиска кода прошивки
После уточнения владельцем уже выданного разрешения проверен следующий
программный путь: чтение LOADER_231. В прочитанных 1032704 байтах по смещению
18432 найдена точная копия официального DFW0.06. Читаемого исполняемого кода
для собственного патча не получено. Это не backup Flash MCU; последние
12800 байт полного носителя не прочитаны. Метод, хэши и границы:
[FIRMWARE_READBACK_20260929.md](FIRMWARE_READBACK_20260929.md).
B2 выведен из загрузчика одной повторной записью исходного официального0.06.
USB подтвердил прежний SHA всех220настроек, SIM1=1/SIM2=1/active1/GPRS4;
свежая телеметрия пришла через VPS в07:38:25.396UTC. Core8000 operational=true.
Исследовательские USB-процессы закрыты. Разрешение менять прошивку есть;
технический барьер — доступ к её коду/формату или к управлению модемом.
Собственный патч не установлен, горячая вставка не исправлена.
@@ -6,7 +6,7 @@
## Поведение продукта ## Поведение продукта
В существующем разделе «Сервер и связь» добавлен режим В существующем разделе «Сервер и связь» добавлен режим
**«Обе SIM — без заданного APN»**. Его можно применять через VPS и сохранять **«Автоматический режим — без заданного APN»**. Его можно применять через VPS и сохранять
в обычный профиль для первоначальной настройки следующего B2 по USB. в обычный профиль для первоначальной настройки следующего B2 по USB.
- `connectivity.strategy=native` очищает поля 67/68/69 и 89/90/91 целиком, - `connectivity.strategy=native` очищает поля 67/68/69 и 89/90/91 целиком,
@@ -15,7 +15,7 @@
профилем. Отсутствующие обязательные поля отклоняют подготовку целиком. профилем. Отсутствующие обязательные поля отклоняют подготовку целиком.
- Это явное действие пользователя. Чтение конфигурации, появление неизвестной - Это явное действие пользователя. Чтение конфигурации, появление неизвестной
SIM или сохранение прочих параметров сами по себе не включают данный режим. SIM или сохранение прочих параметров сами по себе не включают данный режим.
- Прежний `both` отображается как «Обе SIM — сохранить APN» и не очищает - Прежний `both` отображается как «Автоматический режим — с сохранением APN» и не очищает
параметры специальных/корпоративных тарифов. Старые профили не мигрируются. параметры специальных/корпоративных тарифов. Старые профили не мигрируются.
- Одиночные варианты подписаны «Только SIM …»: они по-прежнему реализуют - Одиночные варианты подписаны «Только SIM …»: они по-прежнему реализуют
исключительный выбор и запрещают интернет другой SIM. Они не представлены исключительный выбор и запрещают интернет другой SIM. Они не представлены
@@ -102,3 +102,14 @@ TypeScript и production build. Канонический Core оставлен
и таблице SERVER_COM не установлена подходящая команда предпочтения. и таблице SERVER_COM не установлена подходящая команда предпочтения.
Пост производителя об изменениях APN прошивки 0.43 относится к L1/L2/A1/A2/A3, Пост производителя об изменениях APN прошивки 0.43 относится к L1/L2/A1/A2/A3,
а не B2, поэтому не используется как основание менять прошивку этого трекера. а не B2, поэтому не используется как основание менять прошивку этого трекера.
По уточнению владельца названия обоих режимов заменены на «Автоматический
режим». Пояснение `both` теперь прямо говорит о сохранении текущих APN,
логина и пароля каждой SIM; `native` — об их очистке. Поведение записи и
перезапуска не менялось. Операторы в вариантах «Только SIM 1/2» по-прежнему
вычисляются из подтверждённых наблюдений. Проверены архитектурные ограничения,
1019 frontend unit tests, typecheck, production build и меню на каноническом
8000. Выбор и запись настроек при визуальной проверке не выполнялись.
Последующее [исследование горячей вставки и восстановления перезапуском](HOT_SIM_REINITIALIZATION_20260928.md)
отдельно фиксирует границу автоматического обнаружения резервной карты.
+1 -1
View File
@@ -21,7 +21,7 @@
| TCP и слабый канал | `TRANSPORT_EVIDENCE_20260928.md`, `COMMUNICATION_LIMITS.md` | | TCP и слабый канал | `TRANSPORT_EVIDENCE_20260928.md`, `COMMUNICATION_LIMITS.md` |
| Identity SIM | `SIM_OBSERVATION_RUNTIME_20260928.md`, `NETWORK_SIM_IDENTITY_20260928.md`, `HOT_SIM_IDENTITY_AND_QUEUE_20260928.md` | | Identity SIM | `SIM_OBSERVATION_RUNTIME_20260928.md`, `NETWORK_SIM_IDENTITY_20260928.md`, `HOT_SIM_IDENTITY_AND_QUEUE_20260928.md` |
| Привязанный к карте доступ | `CARD_ACCESS_APPLICATION_20260928.md` | | Привязанный к карте доступ | `CARD_ACCESS_APPLICATION_20260928.md` |
| Горячая замена / пустой APN | `NATIVE_SIM_EXPERIMENT_20260928.md`, `MTS_SLOT1_EMPTY_APN_20260928.md` | | Горячая замена / пустой APN | `NATIVE_SIM_EXPERIMENT_20260928.md`, `MTS_SLOT1_EMPTY_APN_20260928.md`, `HOT_SIM_REINITIALIZATION_20260928.md` |
| Текущий native UI | `NATIVE_INTERNET_POLICY_20260928.md` | | Текущий native UI | `NATIVE_INTERNET_POLICY_20260928.md` |
| Предпочтение и резерв | `SIM_PREFERENCE_AND_FALLBACK_20260928.md` | | Предпочтение и резерв | `SIM_PREFERENCE_AND_FALLBACK_20260928.md` |
| Firmware archive / отсутствие backup0.01 | `FIRMWARE_SETTINGS_20260928.md`, `FIRMWARE_BASELINE_20260928.md` | | Firmware archive / отсутствие backup0.01 | `FIRMWARE_SETTINGS_20260928.md`, `FIRMWARE_BASELINE_20260928.md` |
@@ -0,0 +1,51 @@
# B2: возврат SIM под питанием не запускает повторную инициализацию
Технический запрос подготовлен 29.09.2026. **Не отправлен.**
Устройство ARNavi B2, модель231, PCB231_V1.03, модемSIMCom SIM868E
(подтверждён фотографией). На исходной прошивке0.01 и после установки
официальной0.06 воспроизводится отсутствие горячего обнаружения SIM.
Интернет настроен автоматически через обеSIM, APN пусты; запрета GPRS
для слотов нет. SIM1 — МТС, SIM2 — МегаФон.
После включения обеSIM обнаружены и зарегистрированы. При активнойSIM2
извлекаем резервнуюSIM1 на10с: B2 сообщает SIM1=0, ИнтернетSIM2 продолжает
работать. ВозвращаемSIM1 без изменения питания/USB: статус остаётся0.
Та же проблема ранее воспроизведена дляSIM2 после автоматического перехода
наSIM1. Полный перезапуск B2 восстанавливает обе карты без перестановки
и изменения конфигурации.
Воспроизведение29.09 записано непрерывно поUSB с D9;1 до извлечения:
09:57:47МСК SIM1→0; в09:58:45 получено подтверждение возврата;
до конца окна10:01 SIM1=0/activeSIM2/GPRS4. В этом состоянии проверены
SERV1.2 поTCP и двоичный01 02 в FF/token-конверте. Для двоичного запроса
получен подтверждённый ответ устройства code0, но SIM1 осталась0.
Затем SERV1.2 напрямую поUSB вернул FW/IMEI/VIN/BAT; SIM1 по-прежнему0.
В логе после команд нет CPIN/CCID/CIMI/CDSDS и попытки CMGS.
Конфигурация до/после опытов совпадает побайтно. D9;0 восстановлен.
Нужны ответы применительно именно к231_V1.03/SIM868E:
1. Поддерживается ли горячая вставка резервной SIM этой ревизией, подключены
ли SIM1_DET/SIM2_DET и какой полярности сигнал ожидает модем?
2. Включается ли обнаружение вставки командой AT+CSDT в штатной инициализации?
Каким документированным USB/TCP-запросом B2 прочитать CSDT?/CSMINS?
и точную версию внутреннего ПО SIM868E?
3. Есть ли сервисная команда переинициализации одного слота или только
модема, сохраняющая работу контроллера? Если прерывается активный GPRS,
просим указать это отдельно и дать ожидаемое время восстановления.
4. Для каких моделей/прошивок строка INTERNAL/SMS_COM «SERV1.2 — повторный
запрос ICCID» применима? В B2manual§10 у той же команды другая семантика.
5. Есть ли исправление прошивки после0.06 или диагностическая сборка B2,
которая повторно инициализирует возвращённую карту без общего restart?
Критерий приёмки: новая карта обнаруживается и регистрируется после вставки
в резервный слот без перезагрузки контроллера; исправная активнаяSIM
продолжает передавать данные. Затем проходит автоматический переход на
обнаруженную резервнуюSIM при потере основной. Требуется повторить для
обоих слотов. Старый SID/RSSI и подтверждение получения команды не считаем
доказательством нового обнаружения.
Подробный журнал: [HOT_SIM_REINITIALIZATION_20260928.md](HOT_SIM_REINITIALIZATION_20260928.md).
Идентификаторы, номера телефонов, пароли и полные сырые логи в этот запрос
не включены.
@@ -0,0 +1,32 @@
# Отдельный репозиторий VPS
С 29.09.2026 серверная реализация, установщик, сборщик и серверные проверки
живут в [NODEDC_MISSION_CORE_ARNAVI-VPS](https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS).
Папка `apps/vps-host` и серверные сборочные скрипты удалены из этого рабочего
дерева. Действующий VPS и pairing не переустанавливаются при переносе кода.
В Mission Core остаются UI, реестр оборудования, USB-подготовка, профили,
протокольный клиент и его локальные данные. Связь с VPS остаётся прежней.
Mission Core не импортирует код нового репозитория, не требует его рядом и
не запускает серверные тесты. Установщик сервера продолжает публиковаться
через существующий `scripts/publish_fleet_installer.py` после отдельной приёмки.
Для разработки сервера выполняйте команды из README его репозитория.
Старые датированные документы с `apps/vps-host` фиксируют прежнее размещение.
Проверяемый контракт клиента — `tests/fixtures/arnavi_vps/client-v1.json`.
Он содержит синтетические запросы, точные wire vectors и хеши codec 0.1.46.
Сервер экспортирует его командой:
```sh
uv run python scripts/export_client_contract.py --output contracts/client-v1.json
```
Эта команда выполняется **в репозитории VPS**. Клиент обновляет свою копию
контракта явно после проверки совместимости. Рабочая сборка Mission Core
не подхватывает произвольное содержимое sibling checkout. Серверные тесты
проверяют соответствие fixture своему runtime; клиентские — своим запросам,
подписям команд и протокольным модулям.
Многоклиентские контуры и OAuth находятся в плане дальнейшей реализации.
Они не объявляются внедрёнными фактом разделения исходников.
@@ -1,5 +1,9 @@
# ARNavi VPS сервер — руководство передачи реализации # ARNavi VPS сервер — руководство передачи реализации
> С 29.09.2026 сервер вынесен в [отдельный репозиторий](https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS).
> Этот документ сохраняет срез 28.09; актуальные пути сборки и граница клиента —
> в [описании переноса](../arnavi_b2/VPS_REPOSITORY_SPLIT_20260929.md).
Актуальный срез: 28.09.2026, VPS Host **0.1.41**, B2 **231 / 0.01**. Актуальный срез: 28.09.2026, VPS Host **0.1.41**, B2 **231 / 0.01**.
Документ описывает работающий код и доказанные границы. Ранние отчёты в Документ описывает работающий код и доказанные границы. Ранние отчёты в
`docs/vps_host/` и `docs/arnavi_b2/` сохраняют историю своих версий; при `docs/vps_host/` и `docs/arnavi_b2/` сохраняют историю своих версий; при
+4 -95
View File
@@ -1,97 +1,6 @@
# Clean Ubuntu installation and recovery — VPS Host 0.1.33 # Серверная документация перенесена
> Subsequent release 0.1.35 adds [qualified portable state transfer](PORTABLE_STATE_20260927.md). История приёмки сохранена в отдельном репозитории:
> The results and remaining gates below describe the earlier 0.1.33 acceptance. [CLEAN_INSTALLATION_20260927](https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS/src/branch/main/docs/history/CLEAN_INSTALLATION_20260927.md).
Owner objective: a downloadable installer must provision the declared bare OS, Текущее разделение ответственности: [VPS repository split](../arnavi_b2/VPS_REPOSITORY_SPLIT_20260929.md).
generate a pairing key, run the receiver and retain durable state through
recovery. Updating the previously prepared production VPS is a separate check.
## Artifact and environment
- Installer version: **0.1.33**.
- Installer SHA-256: `994a6b011bb51feaff8daa97d1854f0f2e1928f8472883d3b910f3cc8b43bb5e`.
- Payload manifest SHA-256: `798375cdbee0de2ab78b23bc2380e8139039e7b7c2deb50f43d7d725ed620a40`.
- Two source builds produced identical `.tar` and `.pyz` artifacts.
- Official [Ubuntu Noble release image](https://cloud-images.ubuntu.com/releases/noble/release/):
`ubuntu-24.04-server-cloudimg-amd64-root.tar.xz`, checked against the published
SHA256SUMS. Image SHA-256:
`820311e238ea34d76a8ca2643d6c01065212e9417109e7397d70472a236df261`.
- Guest reports Ubuntu 24.04.5 LTS, amd64, Python 3.12. The accepted product
environment remains Ubuntu Server 24.04 amd64, not arbitrary Linux.
The clean image ran on the owned VPS in separate mount, PID, network, UTS, IPC
and cgroup namespaces, using the host kernel. It had only loopback networking,
256 MiB memory and a 35% CPU limit. The production service, network and state
were not mounted into the guest. No package installation, copied dependency,
pre-existing product account, product state or prepared application environment
was supplied. This is clean-userspace dependency closure, not a second VM,
different-kernel or cloud-provider firewall test.
`scripts/qualify_vps_clean_host.py` owns the temporary substrate and cleanup.
`scripts/qualify_vps_clean_client.py` pairs a synthetic Core through the actual
TLS API and submits one operation for one synthetic offline tracker. These
engineering scripts are not included in the shipped product payload.
## Failure found and correction
The old installer relied on the caller's umask when creating its public code
directories. With root's umask 0077, the service account could not traverse
`/opt/nodedc-mission-vps` and `releases`; first installation failed while
generating the invitation. Version 0.1.33 explicitly sets those two owned code
directories to 0755. Credentials, state and private evidence remain restricted.
A regression checks service-code traversal and secret permissions under 0077.
Earlier failed test-substrate starts are retained: the namespace guest needed
`pivot_root`, a traversable guest root, and time to finish its stock first-boot
network wait before measuring product installation. No product OS repair was
performed manually. The final run used a freshly extracted image and the
unchanged accepted 0.1.33 installer.
## Passed acceptance
| Check | Result |
| --- | --- |
| First installation on clean image | Service active and enabled; key generated |
| Listeners | TCP 19443 and 9922 listening |
| Key admission | Synthetic Core paired through TLS API; device registered |
| Repeated installer | `already_current`; four identity/key files unchanged |
| Service restart | Same owner authenticates; original queued operation retained |
| `--fresh` | Private backup created; replacement obtains a new TLS identity |
| `--restore` | Original four identity/key files restored byte for byte |
| Restored API/runtime | Same owner token, device registration and pending job usable |
| Production upgrade 0.1.32 → 0.1.33 | SQLite backup; four identity files preserved; active service |
| Installed payload | All 27 files match accepted manifest |
| Mission Core download | Exact accepted 0.1.33 checksum; Node remains 0.8.45-1 |
| Actual B2 after upgrade | Position command token-confirmed, code 0, one attempt, 0.637 s |
The first Core command admission after the host upgrade was rejected before
creating a job because of a stale release allowlist. The Core and frontend
admission lists were updated together; runtime acceptance now runs against both
0.1.32 and the actual current source release. The canonical Core was restarted
through its managed installer after SQLite backups and passed health acceptance.
Temporary systemd units were verified inactive; all test root filesystems and
image copies were removed. Approximately 4.3 GB of disk remained free. Private
evidence was downloaded, hashed and retained under session
`acceptance-e7e12e66a51b4510a2fd5b1a7cc3a93d`. Archive SHA-256:
`8e324d80dcbb275e40f855158e20a37d7834eebe9329079429a97ce1ec8ad7e0`.
## Limits and next gates
- The tested clean Ubuntu has no blocking local firewall policy. The installer
also handles the existing named NODE.DC nftables policy. It does not rewrite
arbitrary foreign firewall rules or a provider's external security group.
Public reachability of both ports still needs verification on a new provider.
- Recovery here is from `--fresh`'s backup in the same OS environment. A portable
export/import onto another bare VPS, with a missing service account or changed
endpoint, is **not yet qualified**. A fresh installation creates a new server
identity; it does not automatically recreate an old paired server.
- Keep a stable DNS endpoint for migration where available. Endpoint migration
remains explicitly rejected by the current installer rather than silently
leaving trackers or the paired Core pointing at the old server.
- This is not a thousand-device capacity result. The available Worker 006 was
unreachable; no load test ran on the Mac or the production VPS.
- [Physical SIM and settings results](../arnavi_b2/SIM_INTENT_AND_CONFIGURATION_CYCLE_20260927.md)
separately record the failed SIM-2 return and successful owner-approved USB
recovery. They do not establish automatic SIM fallback or full vendor parity.
+4 -206
View File
@@ -1,208 +1,6 @@
# VPS Host admission and tracker map # Серверная документация перенесена
> Historical implementation ledger. For the current 0.1.41 architecture, История приёмки сохранена в отдельном репозитории:
> installation, runtime/recovery and accepted limits, start with [IMPLEMENTATION](https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS/src/branch/main/docs/history/IMPLEMENTATION.md).
> [the VPS handoff](../handoff/ARNAVI_VPS_SERVER_20260928.md) and
> [the B2 handoff](../handoff/ARNAVI_B2_TRACKER_20260928.md).
> Release statements below retain their original qualification date.
[Подтверждения B2 и граница рантайма, Host 0.1.31](../arnavi_b2/TRACKER_CONFIRMATIONS_20260927.md) Текущее разделение ответственности: [VPS repository split](../arnavi_b2/VPS_REPOSITORY_SPLIT_20260929.md).
Historical incremental release: **0.1.38**, adding card-bound configuration guards
and verified per-card access in Core. See
[physical acceptance and remaining limits](../arnavi_b2/CARD_ACCESS_APPLICATION_20260928.md).
Release **0.1.37** added explicit permission for both SIMs
with full readback and fresh GPRS after restart. Atomic packet/receipt persistence
from 0.1.36 is retained. See [both-SIM policy](../arnavi_b2/BOTH_SIM_POLICY_20260927.md).
The exact published installer SHA-256 is
`140a54c608a6e9c71663cc9435c7ffab12bba6c5277fc78c6d9daa59da19e002`.
See [packet and command-result durability](../arnavi_b2/PACKET_COMMIT_20260927.md),
[portable transfer acceptance and limits](PORTABLE_STATE_20260927.md),
[prior clean installation](CLEAN_INSTALLATION_20260927.md),
[durable maintenance](../arnavi_b2/DURABLE_MAINTENANCE_20260927.md), and
[physical settings/SIM results](../arnavi_b2/SIM_INTENT_AND_CONFIGURATION_CYCLE_20260927.md).
Historical release acceptance below retains its original scope. Complete vendor
parity, remote SIM fallback, provider/DNS changes and a real literal-IP endpoint
migration are not claimed.
Owner surface decision: extend the existing apparatus Equipment top-level plus.
Options are onboard computer, ARNavi B2 and VPS Host. A VPS is shared across
apparatuses and is not a child of an onboard PC. The existing Node enrollment
remains private-LAN only. A dedicated VPS workspace/new navigation root is not
needed: host admission/settings fit the existing equipment form and settings
window. No new shared visual primitive was introduced.
The root plus now renders the selected type's fields in one dialog. Both Node
and VPS sections provide the locally published installer, accepted version and
exact OS profile before the pairing field. Shared Window footer actions align
to the trailing edge. The role is labelled VPS Host ARNavi; macOS interface names
are exposed as hardware labels only inside optional VPN connection settings.
## Owned modules
- `apps/vps-host/`: headless standard-library runtime and exact-plan installer.
- `scripts/build_vps_host.py`: deterministic payload; exact vendor decoder is
bundled from `src/k1link/device_plugins/arnavi_b2/internal.py`.
- `fleet/vps_transport.py`: public endpoint validation, TLS pin and local network
interface selection. macOS IP_BOUND_IF scopes a physical-interface choice to
the single VPS socket; it changes no OS routes or VPN configuration. Other OS
profiles use their system routing.
- `fleet/vps_hosts.py`: shared identity/assignments, private token, durable cursor
and tracker positions. Tracker ownership remains in EquipmentStore.
- `web/vps_host_api.py`: loopback operator admission, host settings and telemetry.
- `core/fleet/vps.ts`: browser contract and bounded polling lifecycle.
- `workspaces/fleet/equipment/VPSHostSettings.tsx`: key/host selector, name,
current connection, shared vehicle assignments, real sync status.
- `workspaces/fleet/observation/ObservationMap.tsx`: real source projections in
the existing Cesium renderer, no simulated movement or fabricated location.
## State and authority
New key → pending durable Core credentials → pinned TLS pairing → paired.
A network failure after remote consumption can retry with the same persisted
credentials. Another Core/token cannot reuse the invitation. Each VPS accepts
one Core owner. TLS identity and private journal survive code update/rollback.
Core periodically synchronizes registered B2 identities whose selected server
matches that VPS and whose vehicle is assigned to it. The receiver rejects
unknown identities. A policy save is not a device apply. USB apply uses existing
qualified transaction/readback. First packet proves uplink; GNSS data proves a
position; each has an independent age. Old replay never replaces a newer fix.
The source's last known position is retained with its time when offline.
A VPS can serve multiple vehicles; a vehicle can own multiple independent
trackers. Reassignment modifies registry ownership, not tracker identity, SIM
or firmware. Host settings are one shared record with optimistic revision.
## Reproduction and limits
Installation, key path, backups, rollback, queue limits and the supported OS
profile are documented in [`apps/vps-host/README.md`](../../apps/vps-host/README.md).
The source tree contains no deployed address, real IMEI, SIM phone number, key,
GPS coordinates or private capture. Those live in operator state/evidence.
The available Ubuntu VPS qualified first installation, upgrade, real rollback,
reapplication, no-op reapplication, systemd health and independent TLS connection.
The actual USB B2 with an MTS SIM qualified writing a second INTERNAL server,
independent readback, receiving real telemetry and showing GNSS on the rover
observation map while the onboard PC is offline. UI qualification includes the
root chooser, host key form, host settings, normal/expanded map and Escape.
Private deployment ledger records exact artifacts, times and device receipts.
Version 0.1.3 additionally qualified the actual Core download checksum, clean
product replacement with backup, automatic restoration after installation
failure, explicit old-record replacement using the new key through the UI,
fresh B2 telemetry and no-op reapplication. The existing Node 0.8.45-1 installer
was copied from its accepted build host and published without updating the board.
Not claimed: clean-image/other-distribution qualification, thousand-device load,
cryptographic device authentication, arbitrary remote B2 configuration, or
removal of the existing vendor configuration channel. Existing Gelios server
was retained in slot 1 during acceptance; own VPS was added in slot 2.
## Network endpoint control — Host 0.1.6
The subsequent qualification replaced the primary Gelios endpoint with the
owner's VPS from Core's settings window. The old secondary owner channel remains
configured. Saving the endpoint starts a durable bounded operation; fresh GETP,
one SETP #1 and an independent readback distinguish intent from confirmation.
Core also exposes read-only endpoint inspection through VPS. Reconnection and
missing write acknowledgement do not cause a second write. The real reversal
experiment restored the entire initial configuration byte for byte.
Admission now includes observed/confirmed prior endpoints, so saving a desired
address cannot remove the old uplink prematurely. Remote scope is only primary
host/port on the qualified B2 firmware. Full-profile support, vendor-channel
removal and fleet-scale qualification remain open. See
[network configuration](../arnavi_b2/NETWORK_CONFIGURATION.md).
## Accepted network settings and restart increment — Host 0.1.23
The 0.1.6 limitations above describe that release's acceptance, not the current
runtime. Both monitoring destinations and the B2 configuration endpoint now use
the owned VPS. Host 0.1.23 supports full configuration reads, reviewed profile
writes with independent readback, position/output commands and bounded remote
restart observation, with no runtime vendor API calls. Core synchronizes the
numeric device ID already read during enrollment; conflicting identity changes
are rejected and there is no vendor registration dependency.
The initial bootstrap clears only the documented startup-check bit. On the bench
this allowed a full 207-record read after a remote restart, byte-identical to the
new target. Existing periodic polling is preserved; background no-update behavior
is not yet qualified. See [autonomy acceptance](../arnavi_b2/AUTONOMY_AND_COMMANDS.md)
for the exact physical results and remaining scope. Do not interpret complete
image transport as proof of all CAN/peripheral/firmware operations.
The operator download is the exact qualified immutable 0.1.23 `.pyz`, SHA-256
`97abb7a869f86debe885e5130dd14791ac7ed0dfea99f9ee75c64bfb229559d0`.
Repeated source build matched the installed artifact and manifest; existing host
identity, credentials and journal were retained. The onboard Node installer was
not changed and no onboard update was performed in this increment.
### 0.1.24: exclusive B2 SIM selection
The same downloadable headless installer now carries durable `select-sim`:
configuration preflight/write/readback, one restart and measured DS2 return on
the requested SIM. No new port, vendor dependency, system package, identity or
permission is introduced. The existing Ubuntu Server 24.04 amd64 installation
is upgraded in place; paired identity/state and rollback release are preserved.
The mode disables data on the other SIM, and the operator is told this before
saving. A failed/uncertain operation is never silently retried.
### 0.1.25: bound Linux TCP delivery, preserve uncertain outcomes
`ndc_vps/delivery.py` tracks byte frontiers for every guarded stream write and
releases a command's deadline only when the kernel and asyncio queues establish
TCP acknowledgement. Monotonic timers abort queued delivery at the earlier of
operation expiry and 30 seconds after dispatch (12 seconds for HTTP replies).
Per-socket zero linger prevents queued data surviving handler close; user timeout
provides an additional Linux bound. No global sysctl/firewall changes. The service
keeps separate application confirmation and never replays a dispatched action.
The shipped `qualify_delivery.py` uses two bounded loopback connections and no
tracker or service changes. On Linux 6.8.0-137-generic its blocked receiver reset
at 0.751091 seconds for a 0.750-second deadline; healthy acknowledged data did not
close the stream. Physical B2 qualification demonstrated the real 30-second
failure cutoff without USB; no successful execution is claimed for that sample.
See `docs/arnavi_b2/COMMUNICATION_LIMITS.md` for evidence and limitations.
Session: `delivery-a8d26be666ec4dd182f46a4db8d0c566`. Repeated builds matched:
installer SHA-256 `c4af2b646cd4463490a329b10abcb09828a97aea2c688cd76dee2fe105d45ee1`,
manifest SHA-256 `68365a1ea42b09dafe353c030a79fb7669fb7631c728ff45e5dc23b15307aad8`.
Applied through the existing `.pyz` installer, preserving all four identity/key
files and the durable journal. The same artifact is published for download in
Core. 154 targeted backend cases, 1004 frontend cases, architecture, typecheck and
production build passed. This is an update on the existing supported VPS, not a
new clean-OS acceptance or proof of deterministic actuator latency.
### 0.1.26: durable Core delivery and idle runtime
Core now persists a private transactional outbox before submitting to this host
version. Ambiguous HTTP completion first resolves the original ID; unresolved
submission retries the identical body/ID/absolute deadline with bounded backoff.
VPS deduplicates the ID and admits expired requests as terminal records without
dispatch. A never-dispatched position request may survive VPS restart and await
reconnection within its original 30-second lifetime. Dispatched actions still
never replay, and effectful operations retain live-session admission.
The host indexes unfinished commands rather than reading complete history in
packet/sender hot paths. Idle senders wait for events; active staged operations
retain bounded timers. This is not fleet-scale qualification: the existing
256-connection limit and finite receiver storage remain unchanged.
The shipped `qualify_runtime.py` passed on the existing Ubuntu VPS in 1.144 s
using synthetic state only. 204 focused backend and 1004 frontend cases passed,
as did lint, architecture, typecheck and build. Three indoor real B2 requests
were confirmed in 0.887–2.224 s. Each repeated Core submission retained the same
operation; capture proves one application frame per operation, including one
TCP retransmission. No tracker settings, outputs, restart or USB serial use.
Session `runtime-b54eb15f6b1e48d09c687801f7347617`; identical repeated builds and
downloaded installer SHA-256:
`2433f50ea14b7459f59a8fe1191ff0cb7a197e201b4e7230b651915b43661a50`.
Installed with the product installer, all four identity/key files preserved,
service active and Core UI accepts 0.1.26. Node installer remains 0.8.45-1.
See [runtime contract](../arnavi_b2/WEAK_LINK_RUNTIME.md) and
[indoor/outdoor evidence](../arnavi_b2/INDOOR_OUTDOOR_COMPARISON_20260927.md).
+4 -137
View File
@@ -1,139 +1,6 @@
# Portable VPS state — installer 0.1.35 # Серверная документация перенесена
The transfer unit is one VPS identity and its entire private journal. It includes История приёмки сохранена в отдельном репозитории:
TLS identity, Core ownership, registered devices, telemetry/receipt sequencing, [PORTABLE_STATE_20260927](https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS/src/branch/main/docs/history/PORTABLE_STATE_20260927.md).
maintenance intents, attempt history and stop markers. It excludes executable
code, system accounts, unit files, firewall configuration and live TCP sessions.
## Operator procedure Текущее разделение ответственности: [VPS repository split](../arnavi_b2/VPS_REPOSITORY_SPLIT_20260929.md).
Use the exact same qualified `.pyz` on the source and target. First upgrade the
source through that installer. On the source:
```sh
sudo python3 mission-core-vps-install.pyz --export-state /root/mission-vps-state.tar.gz
```
Export stops this service and writes a persistent migration fence before taking
a consistent SQLite snapshot. It prints the archive's SHA-256. The archive is
private mode 0600 and contains keys/tokens; transfer it through the owner's SSH
channel, together with the installer. A failure after fencing does not silently
restart the source. Its original state remains available.
On an empty Ubuntu Server 24.04 amd64 installation:
```sh
sudo python3 mission-core-vps-install.pyz --import-state /root/mission-vps-state.tar.gz --sha256 ARCHIVE_SHA256
```
Import checks the complete fixed file set, exact archive and installer digests,
TLS key/certificate identity and SQLite integrity before publishing state. It
rejects links, path traversal, extra/duplicate/missing members and foreign product
paths. A same-filesystem rename exposes the complete state atomically, avoiding
a second full-size journal copy. The installer creates code, the system account
and the service itself, then checks health. No operator-written service file,
chmod, copied runtime or package installation is required on the qualified image.
Keep the original endpoint and ports. For a DNS endpoint, arrange the DNS move
and test public reachability of both ports. Import preserves the TLS identity,
so the existing Core credentials continue to work. A literal-IP endpoint needs
that IP reassigned or a separate, verified Core/tracker endpoint change; state
transfer does not rewrite remote trackers. The current physical test contour
uses a literal IP, so an actual address migration has not been performed.
To cancel migration, stop the target first, then run on the source:
```sh
sudo python3 mission-core-vps-install.pyz --resume-source
```
The source cannot independently prove that a disconnected target is stopped.
Do not run both copies simultaneously. A previously exported archive also cannot
contain operations accepted after its snapshot. Retain the archive and its exact
installer as a pair, along with the corresponding Mission Core fleet state.
## Recovery semantics
- The queued operation keeps its ID, desired parameters, ordering and history.
- A dispatched attempt without a confirmed result is reconciled by the existing
runtime. It is not relabelled as successful because an archive was restored.
- A retry uses the original intent and a new attempt; terminal results and stop
markers remain in the journal. Original deadlines are not extended by copying.
- Live TCP sessions and their liveness are never restored; new tracker input is
required by the existing dispatch policy.
- Only the source snapshot is authoritative during transfer. This is planned
migration/recovery, not automatic multi-host failover or synchronous replication.
## Reproducible artifact
- Final installer: `vps-host-0.1.35.pyz`.
- SHA-256: `3ed73ffe6b015cc1c39fa5dbcaeb869b8df832ceed2f764fafd06d11de9426ea`.
- Payload manifest: `7ff98f60b943b81703873d09ef79cda65be2b4f94872dfbf6b7ac44570ffb78e`.
- Tar SHA-256: `e6bc8c19d005355edae6469bb24717a98d921254ea19b25040c6ee064b700c76`.
- Two independent source builds produced identical archives.
- Candidate 0.1.34 is retained separately; it was never published or installed
on the working VPS. Version 0.1.35 additionally makes state publication atomic.
## Acceptance
Final 0.1.35 passed both clean-image runs and the working-host upgrade.
Private evidence session:
`vps-portable-b9714da04a334ceea0f335cb8b31caf1`.
Unit checks exercise preservation of a dispatched attempt, a queued successor,
a stopped-before-submit marker and full database contents. Restoring the runtime
retains one interrupted attempt, leaves its parent intent queued, preserves the
stopped marker and has no copied live sessions. Failure before state publication
leaves no target identity; failure during service installation leaves a complete
verified state that the same installer can resume without generating new keys.
The clean-image substrate uses the official Ubuntu 24.04.5 amd64 root image,
SHA-256 `820311e238ea34d76a8ca2643d6c01065212e9417109e7397d70472a236df261`.
Each guest has separate mount, PID, network, UTS, IPC and cgroup namespaces,
loopback only, 256 MiB memory and 35% CPU. Guests run sequentially. This qualifies
clean userspace and service-account creation with the actual installer. It does
not qualify another kernel/hypervisor, provider security groups or public DNS.
Portable state is limited to 2 GiB; import requires 2.25 GiB free staging space.
Unknown firewall policies and provider rules remain external. Physical SIM
fallback, a blank B2 enrollment using a sound USB cable, and Worker 006 scale
tests remain separate gates.
### Observed results
| Check | Result |
| --- | --- |
| Clean source installation | Active/enabled service, generated key, ports 19443/9922 |
| Synthetic Core admission | Prior token authenticates; device registered; one offline intent queued |
| Repeated install, restart, fresh/restore | Identity and pending job retained where expected |
| Export fencing | Service start and ordinary installer cannot bypass the fence |
| Explicit abort | Source resumes with same credentials; a new export can be produced |
| Empty second Ubuntu import | Service user created by installer; prior four key/identity files exact |
| Restored API and restart | Same owner, registered device and queued operation, attempt count zero |
| Working VPS 0.1.33 → 0.1.35 | Backup before upgrade; four identity files unchanged; service healthy |
| Installed manifest | All 28 files match accepted release |
| Real-state export/resume | 658,955-byte private archive; source resumed; total 0.990 s |
| Real B2 after resume | Request-position confirmed, code 0, one attempt, 0.831750 s |
| Core journal | Same confirmation visible; zero pending operations |
| Download from Core | Exact accepted installer hash; UI shows 0.1.35 |
| Local validation | 108 distinct focused Python tests, 24 frontend tests, production build passed |
The reference to 108 Python cases includes the additional archive-size guard
test and the two publication-failure cases; repeat runs are not counted twice.
The frontend retains its existing large-chunk warning; no map/renderer work is
included. The onboard installer remains 0.8.45-1 and no board update ran.
The actual private recovery files are retained on the owner's VPS under `/root`:
`ndc-mission-vps-recovery-0.1.35.pyz` and the session-named `*-state.tar.gz`.
The archive is also saved in the private local evidence session as
`production-state.private.tar.gz`, SHA-256
`1c0b4e2a6abe95d8b26c691b1a788dd08e38e5866ac361d3d8349766b762e162`.
This is a snapshot; the source has been explicitly resumed. Stop the source
before restoring it elsewhere, and prefer a fresh export for a planned move.
All four temporary guest units (candidate 0.1.34 and final 0.1.35, source/target)
were verified stopped. Their root filesystems and Ubuntu image copies were
removed after archiving evidence; approximately 4.32 GB remained free. Private
qualification archive SHA-256:
`cbf876da07cb987115d88ef93d19232232445ac32d1b1cc1160e2b01d9325571`.
The actual production service and canonical Core on 127.0.0.1:8000 remain active.
-94
View File
@@ -1,94 +0,0 @@
#!/usr/bin/env python3
"""Build a dependency-free, content-addressed VPS release; no private state."""
import argparse
import hashlib
import json
import shutil
import tarfile
import tempfile
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def build(output):
with tempfile.TemporaryDirectory() as directory:
release = Path(directory) / "ndc-mission-vps"
shutil.copytree(
ROOT / "apps/vps-host", release, ignore=shutil.ignore_patterns("__pycache__", "*.pyc")
)
shutil.copyfile(
ROOT / "src/k1link/device_plugins/arnavi_b2/internal.py", release / "ndc_vps/arnavi.py"
)
for name in ("usb_protocol.py", "web_protocol.py", "sim_network.py"):
shutil.copyfile(
ROOT / "src/k1link/device_plugins/arnavi_b2" / name, release / "ndc_vps" / name
)
files = {
str(p.relative_to(release)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in sorted(release.rglob("*"))
if p.is_file()
}
(release / "manifest.json").write_text(
json.dumps(
{
"schema": "missioncore.vps-release/v1",
"environment": "ubuntu-24.04-amd64",
"files": files,
},
sort_keys=True,
indent=2,
)
+ "\n"
)
output = Path(output)
output.parent.mkdir(parents=True, exist_ok=True)
with tarfile.open(output, "w") as archive:
for file in sorted(release.rglob("*")):
info = archive.gettarinfo(
file, arcname="ndc-mission-vps/" + str(file.relative_to(release))
)
info.uid = info.gid = info.mtime = 0
info.uname = info.gname = ""
info.mode = 0o755 if file.is_dir() else 0o644
if file.is_file():
with file.open("rb") as stream:
archive.addfile(info, stream)
else:
archive.addfile(info)
installer = output.with_suffix(".pyz")
with zipfile.ZipFile(installer, "w", compression=zipfile.ZIP_DEFLATED) as archive:
content = {"__main__.py": (release / "owner_entry.py").read_bytes()}
content.update(
{
"payload/" + str(p.relative_to(release)): p.read_bytes()
for p in sorted(release.rglob("*"))
if p.is_file()
}
)
for name, value in sorted(content.items()):
info = zipfile.ZipInfo(name, date_time=(2026, 1, 1, 0, 0, 0))
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o100644 << 16
archive.writestr(info, value)
print(
json.dumps(
{
"artifact": str(output),
"installer": str(installer),
"installer_sha256": hashlib.sha256(installer.read_bytes()).hexdigest(),
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
"manifest_sha256": hashlib.sha256(
(release / "manifest.json").read_bytes()
).hexdigest(),
}
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--output", required=True)
build(parser.parse_args().output)
-69
View File
@@ -1,69 +0,0 @@
#!/usr/bin/env python3
"""Guest-only synthetic client for the isolated clean-host installer check."""
import base64
import http.client
import json
import os
import secrets
import ssl
import sys
from pathlib import Path
os.umask(0o077)
state = Path("/var/lib/ndc-mission-vps")
context = ssl.create_default_context(cafile=str(state / "tls.crt"))
context.check_hostname = False # This exact generated certificate is the only CA.
credentials = Path("/acceptance-client.json")
def request(method, path, body=None, token=None):
connection = http.client.HTTPSConnection("127.0.0.1", 19443, context=context, timeout=10)
headers = {"Content-Type": "application/json"}
if token:
headers["Authorization"] = "Bearer " + token
connection.request(method, path, json.dumps(body or {}), headers)
response = connection.getresponse()
value = json.loads(response.read())
connection.close()
assert response.status == 200, response.status
return value
if sys.argv[1] == "seed":
encoded = (state / "connect.key").read_text().strip().removeprefix("MCV1.")
invitation = json.loads(base64.urlsafe_b64decode(encoded + "=" * (-len(encoded) % 4)))
client = {
"core_id": "e" * 32,
"token": secrets.token_urlsafe(32),
"secret": invitation["secret"],
}
paired = request("POST", "/v1/pair", client)
client["host_id"] = paired["host_id"]
credentials.write_text(json.dumps(client))
request(
"PUT",
"/v1/devices",
{"items": [{"imei": "123456789012345", "instance_id": "a" * 32}]},
client["token"],
)
operation = request(
"POST",
"/v1/operations",
{
"id": "b" * 32,
"kind": "request-position",
"imei": "123456789012345",
"model": 231,
"firmware": "0.01",
},
client["token"],
)
assert operation["state"] == "queued" and operation["attempt_count"] == 0
else:
client = json.loads(credentials.read_text())
status = request("GET", "/v1/status", token=client["token"])
assert status["host_id"] == client["host_id"] and status["devices"] == 1
operation = request("GET", "/v1/operations/" + "b" * 32, token=client["token"])
assert operation["state"] == "queued" and operation["attempt_count"] == 0
print(json.dumps({"paired_identity": True, "device_registered": True, "queued_job_retained": True}))
-339
View File
@@ -1,339 +0,0 @@
#!/usr/bin/env python3
"""Owned server-only clean Ubuntu userspace acceptance in private namespaces.
Requires an official SHA256-verified Ubuntu Server 24.04 root tar and the shipped
installer. Does not install packages on the host or share its network/services.
This qualifies clean userspace, not a provider firewall or a different kernel.
"""
import argparse
import hashlib
import json
import os
import shutil
import subprocess
import tarfile
import time
from pathlib import Path
def run(*argv, **kwargs):
return subprocess.run(argv, check=True, capture_output=True, text=True, **kwargs)
def main():
p = argparse.ArgumentParser()
p.add_argument("--stage", type=Path, required=True)
p.add_argument("--installer", type=Path, required=True)
p.add_argument("--image-sha256", required=True)
p.add_argument("--client", type=Path, required=True)
p.add_argument("--reuse-uninstalled-image", action="store_true")
mode = p.add_mutually_exclusive_group()
mode.add_argument("--migration-export", action="store_true")
mode.add_argument("--migration-import", type=Path)
p.add_argument("--state-sha256")
p.add_argument("--client-credentials", type=Path)
args = p.parse_args()
stage = args.stage.resolve()
if (
os.geteuid() != 0
or stage.parent != Path("/tmp")
or not stage.name.startswith("ndc-vps-clean-")
):
raise ValueError("root and an owned temporary stage required")
os.umask(0o077)
image = stage / "ubuntu-24.04-server-cloudimg-amd64-root.tar.xz"
with image.open("rb") as f:
if hashlib.file_digest(f, "sha256").hexdigest() != args.image_sha256:
raise ValueError("image digest mismatch")
root = stage / "rootfs"
if not args.reuse_uninstalled_image:
if shutil.disk_usage(stage).free < 2 * 1024**3:
raise ValueError("insufficient bounded staging disk")
root.mkdir(mode=0o755)
with tarfile.open(image) as tar:
for member in tar:
if member.name.startswith("/") or ".." in Path(member.name).parts:
raise ValueError("unsafe image path")
run("tar", "-xJf", str(image), "-C", str(root), timeout=120)
elif not root.is_dir():
raise ValueError("uninstalled image root missing")
# The enclosing evidence stage is private, but the guest's / must be
# traversable by its own service accounts. Tar may omit a root entry.
root.chmod(0o755)
assert not (root / "opt/nodedc-mission-vps").exists()
assert not (root / "var/lib/ndc-mission-vps").exists()
shutil.copyfile(args.installer, root / "installer.pyz")
shutil.copyfile(args.client, root / "acceptance-client.py")
if args.migration_import:
shutil.copyfile(args.migration_import, root / "portable-state.tar.gz")
shutil.copyfile(args.client_credentials, root / "acceptance-client.json")
# The following is the container substrate only. Product services, firewall,
# credentials, accounts and application paths are exclusively installer-owned.
script = stage / "init.sh"
script.write_text("""#!/bin/sh
set -eux
mount --make-rprivate /
R="$1"
mount --bind "$R" "$R"
mount -t proc proc "$R/proc"
mount -t sysfs sysfs "$R/sys"
mount -t cgroup2 cgroup2 "$R/sys/fs/cgroup"
mount -t tmpfs -o mode=755 tmpfs "$R/run"
mount -t tmpfs -o mode=755 tmpfs "$R/dev"
touch "$R/dev/console"
mount --bind "$2" "$R/dev/console"
for node in null zero random urandom tty; do
touch "$R/dev/$node"
mount --bind "/dev/$node" "$R/dev/$node"
done
mkdir -p "$R/dev/pts" "$R/dev/shm"
mount -t devpts devpts "$R/dev/pts"
mount -t tmpfs tmpfs "$R/dev/shm"
ln -s /proc/self/fd "$R/dev/fd"
ip link set lo up
hostname ndc-vps-clean
mkdir -p "$R/.old-root"
cd "$R"
pivot_root . .old-root
cd /
umount -l /.old-root
rmdir /.old-root
exec env container=other SYSTEMD_LOG_TARGET=console SYSTEMD_LOG_LEVEL=debug /sbin/init
""")
script.chmod(0o700)
unit = stage.name[:90]
results = {
"utc": time.time(),
"monotonic": time.monotonic(),
"image_sha256": args.image_sha256,
"installer_sha256": hashlib.sha256(args.installer.read_bytes()).hexdigest(),
"scope": "isolated clean Ubuntu userspace; host kernel shared",
}
try:
run(
"systemd-run",
"--quiet",
"--collect",
"--unit",
unit,
"--property=MemoryMax=256M",
"--property=CPUQuota=35%",
"--property=TasksMax=160",
"--property=TimeoutStopSec=5s",
"--property=RuntimeMaxSec=900",
"--property=Delegate=yes",
"--property=StandardOutput=append:" + str(stage / "console.log"),
"--property=StandardError=append:" + str(stage / "console.log"),
"--service-type=exec",
"unshare",
"--mount",
"--pid",
"--fork",
"--kill-child",
"--uts",
"--ipc",
"--net",
"--cgroup",
str(script),
str(root),
str(stage / "console.log"),
)
pid = None
for _ in range(30):
parent = run("systemctl", "show", unit, "--property=MainPID", "--value").stdout.strip()
if parent != "0":
children = Path(f"/proc/{parent}/task/{parent}/children").read_text().split()
if children:
candidate = children[0]
if Path(f"/proc/{candidate}/comm").read_text().strip() == "systemd":
pid = candidate
break
time.sleep(1)
if pid is None:
raise ValueError("isolated systemd did not start")
for namespace in ("mnt", "net", "pid", "uts", "ipc", "cgroup"):
assert os.readlink(f"/proc/{pid}/ns/{namespace}") != os.readlink(
f"/proc/1/ns/{namespace}"
), namespace
def inside(*command, timeout=120):
return run(
"nsenter",
"--target",
pid,
"--mount",
"--uts",
"--ipc",
"--net",
"--pid",
"--cgroup",
"--root",
"--wd",
*command,
timeout=timeout,
)
# Real host OS release, Python and product installation with no apt/pip.
results["os"] = inside("cat", "/etc/os-release").stdout
# A stock cloud image waits for a provider NIC during its first boot.
# This isolated guest deliberately has only loopback; let that existing
# OS wait expire before timing the product installer.
print(json.dumps({"phase": "waiting_for_guest_boot", "utc": time.time()}), flush=True)
for _ in range(90):
jobs = inside("systemctl", "list-jobs", "--no-pager", "--no-legend").stdout
if not jobs.strip():
break
time.sleep(2)
(stage / "boot-jobs.log").write_text(jobs)
print(json.dumps({"phase": "install", "utc": time.time()}), flush=True)
if args.migration_import:
result = inside(
"python3",
"/installer.pyz",
"--import-state",
"/portable-state.tar.gz",
"--sha256",
args.state_sha256,
timeout=240,
)
(stage / "import.stdout").write_text(result.stdout)
results["import"] = json.loads(
inside("python3", "/acceptance-client.py", "check").stdout
)
results["service"] = inside("systemctl", "is-active", "ndc-mission-vps").stdout.strip()
results["enabled"] = inside("systemctl", "is-enabled", "ndc-mission-vps").stdout.strip()
state = root / "var/lib/ndc-mission-vps"
with tarfile.open(args.migration_import) as archive:
for name in ("host.json", "tls.key", "tls.crt", "connect.key"):
assert (
archive.extractfile("state/" + name).read() == (state / name).read_bytes()
)
results["restored_identity_exact"] = True
results["listeners"] = inside("ss", "-lnt").stdout
assert ":19443" in results["listeners"] and ":9922" in results["listeners"]
inside("systemctl", "restart", "ndc-mission-vps")
inside("python3", "/installer.pyz", "--host", "trackers.example.test")
inside("python3", "/acceptance-client.py", "check")
results.update(status="passed", restored_restart_accepted=True)
print(json.dumps(results), flush=True)
return
result = inside("python3", "/installer.pyz", "--host", "trackers.example.test", timeout=240)
(stage / "install.stdout").write_text(result.stdout)
results["service"] = inside("systemctl", "is-active", "ndc-mission-vps").stdout.strip()
results["enabled"] = inside("systemctl", "is-enabled", "ndc-mission-vps").stdout.strip()
results["pairing"] = json.loads(inside("python3", "/acceptance-client.py", "seed").stdout)
before = {
name: hashlib.sha256((root / "var/lib/ndc-mission-vps" / name).read_bytes()).hexdigest()
for name in ("host.json", "tls.crt", "tls.key", "connect.key")
}
result = inside("python3", "/installer.pyz", "--host", "trackers.example.test")
(stage / "repeat.stdout").write_text(result.stdout)
assert "already_current" in result.stdout
after = {
name: hashlib.sha256((root / "var/lib/ndc-mission-vps" / name).read_bytes()).hexdigest()
for name in before
}
assert before == after
results["repeat_preserves_identity"] = True
results["listeners"] = inside("ss", "-lnt").stdout
assert ":19443" in results["listeners"] and ":9922" in results["listeners"]
inside("systemctl", "restart", "ndc-mission-vps")
inside("python3", "/installer.pyz", "--host", "trackers.example.test")
inside("python3", "/acceptance-client.py", "check")
results["restart_accepted"] = True
result = inside("python3", "/installer.pyz", "--host", "trackers.example.test", "--fresh")
(stage / "fresh.stdout").write_text(result.stdout)
backups = list((root / "var/backups/ndc-mission-vps").glob("*/backup.json"))
assert len(backups) == 1
assert (
hashlib.sha256((root / "var/lib/ndc-mission-vps/tls.crt").read_bytes()).hexdigest()
!= before["tls.crt"]
)
backup = "/" + str(backups[0].parent.relative_to(root))
result = inside(
"python3", "/installer.pyz", "--host", "trackers.example.test", "--restore", backup
)
(stage / "restore.stdout").write_text(result.stdout)
for name, digest in before.items():
assert (
hashlib.sha256((root / "var/lib/ndc-mission-vps" / name).read_bytes()).hexdigest()
== digest
)
results["restore"] = json.loads(inside("python3", "/acceptance-client.py", "check").stdout)
results["restore_identity_exact"] = True
if args.migration_export:
result = inside("python3", "/installer.pyz", "--export-state", "/portable-state.tar.gz")
(stage / "export.stdout").write_text(result.stdout)
receipt = json.loads(result.stdout)
assert receipt["status"] == "source_fenced"
inside("systemctl", "start", "ndc-mission-vps")
state = inside(
"systemctl", "show", "ndc-mission-vps", "--property=ActiveState", "--value"
)
assert state.stdout.strip() == "inactive"
# A subsequent installer must not bypass the persistent fence.
try:
inside("python3", "/installer.pyz", "--host", "trackers.example.test")
except subprocess.CalledProcessError:
pass
else:
raise AssertionError("normal installer bypassed source fencing")
results["source_fence_blocks_restart_and_install"] = True
shutil.copyfile(root / "portable-state.tar.gz", stage / "portable-state.private.tar.gz")
shutil.copyfile(
root / "acceptance-client.json", stage / "client-credentials.private.json"
)
results["state_sha256"] = receipt["sha256"]
# Exercise explicit abort before making the final transferable snapshot.
inside("python3", "/installer.pyz", "--resume-source")
inside("python3", "/acceptance-client.py", "check")
inside("python3", "/installer.pyz", "--export-state", "/portable-state-final.tar.gz")
shutil.copyfile(
root / "portable-state-final.tar.gz", stage / "portable-state.private.tar.gz"
)
results["state_sha256"] = hashlib.sha256(
(stage / "portable-state.private.tar.gz").read_bytes()
).hexdigest()
results["explicit_resume_accepted"] = True
results["status"] = "passed"
print(json.dumps(results), flush=True)
except Exception as exc:
if isinstance(exc, (subprocess.CalledProcessError, subprocess.TimeoutExpired)):
for name, value in (("stdout", exc.stdout), ("stderr", exc.stderr)):
(stage / ("failed." + name)).write_bytes(
value.encode() if isinstance(value, str) else value or b""
)
results.update(status="failed", error=type(exc).__name__ + ": " + str(exc))
(stage / "unit.log").write_text(
subprocess.run(
["journalctl", "-u", unit, "--no-pager", "-n", "120"],
capture_output=True,
text=True,
).stdout
)
raise
finally:
try:
subprocess.run(["systemctl", "stop", unit], capture_output=True, timeout=15)
except subprocess.TimeoutExpired:
subprocess.run(
["systemctl", "kill", "--kill-whom=all", "--signal=SIGKILL", unit],
capture_output=True,
timeout=10,
)
(stage / "result.json").write_text(json.dumps(results, indent=2))
print(
json.dumps(
{
"stage": str(stage),
"status": results.get("status"),
"temporary_unit_stopped": True,
}
),
flush=True,
)
if __name__ == "__main__":
main()
@@ -1,4 +1,4 @@
"""B2 231/0.01 configuration HTTP payloads, observed 2026-09-26. """B2 231/0.01 and 0.06 configuration HTTP payloads, observed 2026-09-26/28.
The HTTP transport is separate from INTERNAL. Unknown commands and firmware The HTTP transport is separate from INTERNAL. Unknown commands and firmware
fail closed. Parsing upload evidence is not proof that a write was applied. fail closed. Parsing upload evidence is not proof that a write was applied.
@@ -7,7 +7,9 @@ fail closed. Parsing upload evidence is not proof that a write was applied.
from .usb_protocol import Configuration, ProtocolError, decode_configuration from .usb_protocol import Configuration, ProtocolError, decode_configuration
MAX_BODY = 16384 MAX_BODY = 16384
QUALIFIED_METADATA = bytes.fromhex("0001e7020000") QUALIFIED_METADATA = frozenset(
bytes.fromhex(value) for value in ("0001e7020000", "0006e7020000")
)
def decode_request(raw: bytes, *, observe_empty_check: bool = False) -> tuple[str, int, bytes]: def decode_request(raw: bytes, *, observe_empty_check: bool = False) -> tuple[str, int, bytes]:
@@ -16,7 +18,7 @@ def decode_request(raw: bytes, *, observe_empty_check: bool = False) -> tuple[st
or raw[:2] != b"[\x01" or raw[:2] != b"[\x01"
or raw[-1:] != b"]" or raw[-1:] != b"]"
or int.from_bytes(raw[2:4], "big") != len(raw) - 5 or int.from_bytes(raw[2:4], "big") != len(raw) - 5
or raw[12:18] != QUALIFIED_METADATA or raw[12:18] not in QUALIFIED_METADATA
): ):
raise ProtocolError("unsupported_web_request") raise ProtocolError("unsupported_web_request")
imei = str(int.from_bytes(raw[4:12], "little")) imei = str(int.from_bytes(raw[4:12], "little"))
+2 -2
View File
@@ -8,7 +8,7 @@ KINDS = {"request-position", "pulse-output", "set-output", "restart"}
def plan(equipment: EquipmentStore, row: Document, command: Document) -> Document: def plan(equipment: EquipmentStore, row: Document, command: Document) -> Document:
if row["model_id"] != "arnavi-b2" or row["observed"]["firmware"] != "0.01": if row["model_id"] != "arnavi-b2" or row["observed"]["firmware"] not in ("0.01", "0.06"):
raise EquipmentError("Команды для этой версии устройства не проверены.") raise EquipmentError("Команды для этой версии устройства не проверены.")
kind = command.get("kind") kind = command.get("kind")
if kind not in KINDS: if kind not in KINDS:
@@ -41,6 +41,6 @@ def plan(equipment: EquipmentStore, row: Document, command: Document) -> Documen
**private, **private,
"imei": row["identity_key"], "imei": row["identity_key"],
"model": 231, "model": 231,
"firmware": "0.01", "firmware": row["observed"]["firmware"],
"secondary": {"host": config.text(3), "port": config.integer(4, 2)}, "secondary": {"host": config.text(3), "port": config.integer(4, 2)},
} }
+5
View File
@@ -58,6 +58,11 @@ def apply(hosts, identifier, revision):
"0.1.39", "0.1.39",
"0.1.40", "0.1.40",
"0.1.41", "0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
) )
or time.time() - host["last_sync_at"] > 30 or time.time() - host["last_sync_at"] > 30
): ):
@@ -34,7 +34,7 @@ def presets() -> list[Document]:
"command": {"kind": "set-output", "pin": pin, "enabled": enabled}, "command": {"kind": "set-output", "pin": pin, "enabled": enabled},
"wire": f"••••••*SERV*8.{pin}.{int(enabled)}", "wire": f"••••••*SERV*8.{pin}.{int(enabled)}",
"encoding": "INTERNAL · FC", "encoding": "INTERNAL · FC",
"queue_seconds": 3, "queue_seconds": 30,
"confirmation": "Текстовая команда без токена. " "confirmation": "Текстовая команда без токена. "
"Ответ не доказывает положение контактов реле.", "Ответ не доказывает положение контактов реле.",
} }
@@ -46,7 +46,7 @@ def presets() -> list[Document]:
"command": {"kind": "pulse-output", "pin": pin, "seconds": 5}, "command": {"kind": "pulse-output", "pin": pin, "seconds": 5},
"wire": f"••••••*SERV*24.{pin}.0.5", "wire": f"••••••*SERV*24.{pin}.0.5",
"encoding": "INTERNAL · FC", "encoding": "INTERNAL · FC",
"queue_seconds": 3, "queue_seconds": 30,
"confirmation": "Текстовая команда без токена. " "confirmation": "Текстовая команда без токена. "
"Ответ не доказывает положение контактов реле.", "Ответ не доказывает положение контактов реле.",
} }
@@ -0,0 +1,149 @@
"""Independent durable command jobs; settings revisions do not own their queue."""
import http.client
import json
import time
from . import equipment_actions, equipment_operations
from . import equipment_command_journal as journal
from .independent_equipment import EquipmentError
from .vps_transport import request
CAPABILITY = "arnavi-b2-command-scheduler-v2"
def supported(host):
return CAPABILITY in (host or {}).get("status", {}).get("capabilities", [])
def initialize(db):
db.execute(
"CREATE TABLE IF NOT EXISTS command_dispatch("
"id TEXT PRIMARY KEY,body TEXT NOT NULL,accepted INTEGER NOT NULL DEFAULT 0,"
"next_poll REAL NOT NULL DEFAULT 0)"
)
def prepare(hosts, identifier, value):
from .equipment_command_runtime import guard, source
with hosts.equipment.db() as db:
db.execute("BEGIN IMMEDIATE")
current = json.loads(
db.execute("SELECT body FROM command_journal WHERE id=?", (value["id"],)).fetchone()[0]
)
if current["state"] != "waiting":
return
row = hosts.equipment._find(db, "instances", identifier)
if guard(row) != current["guard"]:
journal.finish(db, identifier, current, "rejected", "device_changed")
return
host = source(hosts, row)
if not host or host["id"] != current["host_id"] or not supported(host):
return
try:
body = equipment_actions.plan(hosts.equipment, row, current["command"])
except EquipmentError:
journal.finish(db, identifier, current, "rejected", "device_changed")
return
body.pop("secondary")
body.update(id=value["id"], priority="manual")
db.execute(
"INSERT INTO command_dispatch(id,body) VALUES(?,?)", (value["id"], json.dumps(body))
)
current.update(state="submitting", runtime_phase="reconciling")
journal.capture(db, {**row, "network_operation": current})
def project(hosts, identifier, value, result):
if (
result.get("id") != value["id"]
or result.get("kind") != value["kind"]
or result.get("durable") is not True
):
raise ValueError("durable command identity mismatch")
allowed_states = {
"queued",
"dispatched",
"delivered",
"device_confirmed",
"device_rejected",
"reconnected",
"accepted",
"unconfirmed",
"uncertain",
"rejected",
"stopped",
}
if result.get("state") not in allowed_states:
raise ValueError("invalid durable command outcome")
if result["state"] == "delivered" and (
value["kind"] not in {"set-output", "pulse-output"}
or type(result.get("delivered_at")) not in (int, float)
):
raise ValueError("output transport receipt missing")
with hosts.equipment.db() as db:
db.execute("BEGIN IMMEDIATE")
row = hosts.equipment._find(db, "instances", identifier)
current = json.loads(
db.execute("SELECT body FROM command_journal WHERE id=?", (value["id"],)).fetchone()[0]
)
if current["state"] not in journal.PENDING:
return
equipment_operations.project(current, result)
current.update(
{
k: v
for k, v in result.items()
if k in journal.FIELDS and k not in {"created_at", "command", "host_id", "scope"}
}
)
current["vps_created_at"] = result.get("created_at", current["created_at"])
journal.capture(db, {**row, "network_operation": current})
if current["state"] not in journal.PENDING:
db.execute("DELETE FROM command_dispatch WHERE id=?", (value["id"],))
else:
db.execute("UPDATE command_dispatch SET accepted=1 WHERE id=?", (value["id"],))
def pump(hosts):
# Bounded batches, persisted rows: backlog size does not become RAM usage.
with hosts.equipment.db() as db:
waiting = db.execute(
"SELECT instance,body FROM command_journal WHERE state='waiting' "
"AND json_extract(body,'$.detached')=1 ORDER BY seq LIMIT 16"
).fetchall()
for identifier, encoded in waiting:
prepare(hosts, identifier, json.loads(encoded))
with hosts.equipment.db() as db:
jobs = db.execute(
"SELECT j.instance,j.body,d.body,d.accepted FROM command_dispatch d "
"JOIN command_journal j ON j.id=d.id WHERE d.next_poll<=? "
"AND j.state IN ('submitting','queued','dispatched') "
"ORDER BY d.next_poll,j.seq LIMIT 8",
(time.time(),),
).fetchall()
owners = {h["id"]: h for h in hosts.rows() if h["state"] == "paired"}
for identifier, encoded, body, accepted in jobs:
value = json.loads(encoded)
with hosts.equipment.db() as db:
db.execute(
"UPDATE command_dispatch SET next_poll=? WHERE id=?", (time.time() + 2, value["id"])
)
host = owners.get(value["host_id"])
if not host or not supported(host):
continue
try:
if value.get("stop_requested"):
result = request(
host, "POST", f"/v1/operations/{value['id']}/cancel", {"kind": value["kind"]}
)
elif accepted:
result = request(host, "GET", f"/v1/operations/{value['id']}")
else:
result = request(host, "POST", "/v1/operations", json.loads(body))
project(hosts, identifier, value, result)
except (OSError, ValueError, http.client.HTTPException):
# The same persisted ID and body survive both outage and lost reply.
# An unknown HTTP outcome never authorizes a fresh tracker command.
continue
+12 -2
View File
@@ -41,10 +41,16 @@ FIELDS = {
"recovery_at", "recovery_at",
"recovery_count", "recovery_count",
"recovery_verification", "recovery_verification",
"delivered_at",
"delivery_seconds",
"reason",
} }
def initialize(db): def initialize(db):
from .equipment_command_dispatch import initialize as initialize_dispatch
initialize_dispatch(db)
db.executescript(""" db.executescript("""
CREATE TABLE IF NOT EXISTS command_journal(seq INTEGER PRIMARY KEY AUTOINCREMENT, CREATE TABLE IF NOT EXISTS command_journal(seq INTEGER PRIMARY KEY AUTOINCREMENT,
id TEXT UNIQUE NOT NULL, instance TEXT NOT NULL, id TEXT UNIQUE NOT NULL, instance TEXT NOT NULL,
@@ -159,7 +165,11 @@ def finish(db, instance, value, state, reason):
def public(value): def public(value):
return {k: v for k, v in value.items() if k not in {"guard", "digest", "preset_id"}} return {
k: v
for k, v in value.items()
if k not in {"guard", "digest", "preset_id", "network_intent", "detached"}
}
def listing(equipment, identifier, before=None, limit=25, tracked=()): def listing(equipment, identifier, before=None, limit=25, tracked=()):
@@ -185,7 +195,7 @@ def listing(equipment, identifier, before=None, limit=25, tracked=()):
"(state IN ('waiting','submitting','queued','dispatched') " "(state IN ('waiting','submitting','queued','dispatched') "
"OR id IN (SELECT id FROM command_result_probes WHERE instance=? " "OR id IN (SELECT id FROM command_result_probes WHERE instance=? "
"ORDER BY rowid DESC LIMIT 32) " "ORDER BY rowid DESC LIMIT 32) "
f"OR id IN ({placeholders})) ORDER BY seq DESC", f"OR id IN ({placeholders})) ORDER BY seq DESC LIMIT 64",
(identifier, identifier, *tracked), (identifier, identifier, *tracked),
).fetchall() ).fetchall()
return { return {
@@ -0,0 +1,120 @@
"""An explicit repeat creates a new intent; an HTTP retry keeps that intent's ID."""
import hashlib
import json
import re
import time
from . import equipment_command_journal as journal
from .equipment_command_catalog import presets
from .equipment_command_runtime import CAPACITY, enqueue, guard, source
from .equipment_network import plan
from .equipment_operations import supported
from .independent_equipment import EquipmentError
def fingerprint(equipment, row, intent):
body = plan(equipment, row, intent["read_only"], True, select_sim=intent["select_sim"])
return hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
def repeat(hosts, identifier, original_id, request_id):
if not re.fullmatch(r"[a-f0-9]{32}", request_id):
raise EquipmentError("Некорректный идентификатор запроса.")
equipment = hosts.equipment
with equipment.db() as db:
found = db.execute(
"SELECT body FROM command_journal WHERE instance=? AND id=?",
(identifier, original_id),
).fetchone()
if not found:
raise EquipmentError("Операция не найдена.")
original = json.loads(found[0])
if original["state"] in journal.PENDING:
raise EquipmentError("Дождитесь завершения этой операции.")
preset = next((p for p in presets() if p["command"] == original.get("command")), None)
if preset:
# Revalidate firmware/output mode and use a new original deadline.
return enqueue(hosts, identifier, request_id, preset["id"])
if original["kind"] not in {"read-configuration", "configure-all", "select-sim"}:
raise EquipmentError("Для этой старой операции не сохранились параметры повтора.")
digest = hashlib.sha256(f"{identifier}:repeat:{original_id}".encode()).hexdigest()
with equipment.db() as db:
db.execute("BEGIN IMMEDIATE")
old = db.execute("SELECT body FROM command_journal WHERE id=?", (request_id,)).fetchone()
if old:
value = json.loads(old[0])
if value.get("digest") != digest:
raise EquipmentError("Этот ID уже принадлежит другой команде.")
return journal.public(value)
row = equipment._find(db, "instances", identifier)
host = source(hosts, row)
if (
not host
or host["id"] != original.get("host_id")
or not supported(host, original["kind"])
):
raise EquipmentError("Изменилась привязка VPS или версия устройства.")
previous_row = row if row.get("network_operation", {}).get("id") == original_id else None
if previous_row is None:
saved = db.execute(
"SELECT body FROM history WHERE instance_id=? AND "
"json_extract(body,'$.network_operation.id')=? ORDER BY revision DESC LIMIT 1",
(identifier, original_id),
).fetchone()
previous_row = json.loads(saved[0]) if saved else None
if not previous_row or guard(previous_row) != guard(row):
raise EquipmentError("Устройство или параметры этой старой операции изменились.")
previous = previous_row["network_operation"]
intent = {
"read_only": original["kind"] == "read-configuration",
"select_sim": original["kind"] == "select-sim",
}
current = plan(equipment, row, intent["read_only"], True, select_sim=intent["select_sim"])
# Repeat precisely the reviewed configuration, with a newly read baseline.
# The outbox is deleted on acknowledgement; immutable revision history
# retains the target digest without copying private wire data into the UI.
if not intent["read_only"]:
digest_now = hashlib.sha256(bytes.fromhex(current["target_configuration"])).hexdigest()
if digest_now != previous.get("target_configuration_sha256") or any(
current.get(key) != previous.get(key) for key in ("kind", "sim_slot", "sim_policy")
):
raise EquipmentError(
"Настройки изменились. Откройте настройки устройства "
"и примените нужные значения."
)
if previous.get("automatic_card") or row["settings"]["connectivity"].get("automatic"):
raise EquipmentError(
"Повторите выбор SIM в настройках, чтобы проверить установленную карту."
)
count = db.execute(
"SELECT count(*) FROM command_journal WHERE instance=? "
"AND state IN ('waiting','submitting','queued','dispatched')",
(identifier,),
).fetchone()[0]
if count >= CAPACITY:
raise EquipmentError(
"Очередь устройства заполнена (32 операции). Дождитесь завершения."
)
now = time.time()
intent["fingerprint"] = fingerprint(equipment, row, intent)
value = {
"id": request_id,
"digest": digest,
"repeat_of": original_id,
"host_id": host["id"],
"guard": guard(row),
"firmware": row["observed"]["firmware"],
"command": None,
"kind": original["kind"],
"scope": original["scope"],
"description": original["description"],
"network_intent": intent,
"durable": True,
"state": "waiting",
"created_at": now,
"events": [{"state": "waiting", "observed_at": now, "historical": False}],
}
journal.put(db, identifier, value)
hosts.command_wake.set()
return journal.public(value)
+42 -5
View File
@@ -5,8 +5,8 @@ import json
import re import re
import time import time
from . import equipment_command_dispatch, equipment_operations
from . import equipment_command_journal as journal from . import equipment_command_journal as journal
from . import equipment_operations
from .equipment_command_catalog import catalog from .equipment_command_catalog import catalog
from .independent_equipment import EquipmentError from .independent_equipment import EquipmentError
@@ -73,6 +73,11 @@ def enqueue(hosts, identifier, request_id, preset_id):
"0.1.39", "0.1.39",
"0.1.40", "0.1.40",
"0.1.41", "0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
}: }:
raise EquipmentError("Подключите проверенную версию VPS Host с поддержкой очереди.") raise EquipmentError("Подключите проверенную версию VPS Host с поддержкой очереди.")
count = db.execute( count = db.execute(
@@ -80,7 +85,7 @@ def enqueue(hosts, identifier, request_id, preset_id):
"('waiting','submitting','queued','dispatched')", "('waiting','submitting','queued','dispatched')",
(identifier,), (identifier,),
).fetchone()[0] ).fetchone()[0]
if count >= CAPACITY: if count >= CAPACITY and not equipment_command_dispatch.supported(host):
raise EquipmentError( raise EquipmentError(
"Очередь устройства заполнена (32 операции). Дождитесь завершения." "Очередь устройства заполнена (32 операции). Дождитесь завершения."
) )
@@ -101,13 +106,22 @@ def enqueue(hosts, identifier, request_id, preset_id):
"scope": "command", "scope": "command",
"created_at": now, "created_at": now,
"queue_deadline": now + selected["queue_seconds"], "queue_deadline": now + selected["queue_seconds"],
"expires_at": now + (180 if preset_id == "restart" else 30), "expires_at": now
+ (
180
if preset_id == "restart"
else 60
if selected["command"]["kind"] in {"set-output", "pulse-output"}
else 30
),
"events": [{"state": "waiting", "observed_at": now, "historical": False}], "events": [{"state": "waiting", "observed_at": now, "historical": False}],
} }
if equipment_operations.supported(host, value["kind"]): if equipment_operations.supported(host, value["kind"]):
value["durable"] = True value["durable"] = True
value.pop("queue_deadline") value.pop("queue_deadline")
value.pop("expires_at") value.pop("expires_at")
if equipment_command_dispatch.supported(host):
value["detached"] = True
journal.put(db, identifier, value) journal.put(db, identifier, value)
hosts.command_wake.set() hosts.command_wake.set()
return journal.public(value) return journal.public(value)
@@ -124,6 +138,12 @@ def cancel(equipment, identifier, request_id, hosts=None):
value = json.loads(found[0]) value = json.loads(found[0])
if value["state"] == "cancelled": if value["state"] == "cancelled":
return journal.public(value) return journal.public(value)
if value.get("detached") and value["state"] in {"submitting", "queued", "dispatched"}:
value["stop_requested"] = True
journal.put(db, identifier, value)
if hosts is not None:
hosts.command_wake.set()
return journal.public(value)
if value.get("durable") and value["state"] in {"submitting", "queued", "dispatched"}: if value.get("durable") and value["state"] in {"submitting", "queued", "dispatched"}:
row = equipment._find(db, "instances", identifier) row = equipment._find(db, "instances", identifier)
op = row.get("network_operation", {}) op = row.get("network_operation", {})
@@ -144,10 +164,12 @@ def cancel(equipment, identifier, request_id, hosts=None):
def pump(hosts): def pump(hosts):
from .equipment_network import PENDING, start from .equipment_network import PENDING, start
equipment_command_dispatch.pump(hosts)
equipment = hosts.equipment equipment = hosts.equipment
with equipment.db() as db: with equipment.db() as db:
rows = db.execute( rows = db.execute(
"SELECT instance,body FROM command_journal WHERE state='waiting' ORDER BY seq" "SELECT instance,body FROM command_journal WHERE state='waiting' "
"AND coalesce(json_extract(body,'$.detached'),0)=0 ORDER BY seq LIMIT 64"
).fetchall() ).fetchall()
visited = set() visited = set()
for identifier, body in rows: for identifier, body in rows:
@@ -168,6 +190,12 @@ def pump(hosts):
if guard(row) != value["guard"]: if guard(row) != value["guard"]:
journal.finish(db, identifier, value, "rejected", "device_changed") journal.finish(db, identifier, value, "rejected", "device_changed")
continue continue
if intent := value.get("network_intent"):
from .equipment_command_repeat import fingerprint
if fingerprint(equipment, row, intent) != intent["fingerprint"]:
journal.finish(db, identifier, value, "rejected", "settings_changed")
continue
if identifier in visited: if identifier in visited:
continue continue
visited.add(identifier) visited.add(identifier)
@@ -181,7 +209,16 @@ def pump(hosts):
if time.time() - (host.get("last_sync_at") or 0) > 30: if time.time() - (host.get("last_sync_at") or 0) > 30:
continue continue
try: try:
start(hosts, identifier, row["revision"], command=value["command"], queued_job=value) intent = value.get("network_intent", {})
start(
hosts,
identifier,
row["revision"],
read_only=intent.get("read_only", False),
select_sim=intent.get("select_sim", False),
command=value["command"],
queued_job=value,
)
except EquipmentError: except EquipmentError:
# A concurrent config/USB change or an expired/cancelled intent is # A concurrent config/USB change or an expired/cancelled intent is
# re-evaluated on the next tick; never manufacture a new ID. # re-evaluated on the next tick; never manufacture a new ID.
+66 -4
View File
@@ -24,6 +24,7 @@ if TYPE_CHECKING:
PENDING = {"submitting", "queued", "dispatched"} PENDING = {"submitting", "queued", "dispatched"}
TERMINAL = { TERMINAL = {
"delivered",
"verified", "verified",
"observed", "observed",
"rejected", "rejected",
@@ -54,7 +55,7 @@ def plan(
select_sim: bool = False, select_sim: bool = False,
automatic_access: Document | None = None, automatic_access: Document | None = None,
) -> Document: ) -> Document:
if row["model_id"] != "arnavi-b2" or row["observed"]["firmware"] != "0.01": if row["model_id"] != "arnavi-b2" or row["observed"]["firmware"] not in ("0.01", "0.06"):
raise EquipmentError("Сетевая запись для этой модели или версии ПО не проверена.") raise EquipmentError("Сетевая запись для этой модели или версии ПО не проверена.")
config = decode_configuration( config = decode_configuration(
(equipment.root / "evidence" / row["evidence_id"] / "configuration.bin").read_bytes() (equipment.root / "evidence" / row["evidence_id"] / "configuration.bin").read_bytes()
@@ -65,7 +66,7 @@ def plan(
body = { body = {
"kind": "read-configuration" if read_only else "configure-all", "kind": "read-configuration" if read_only else "configure-all",
"model": 231, "model": 231,
"firmware": "0.01", "firmware": row["observed"]["firmware"],
"imei": row["identity_key"], "imei": row["identity_key"],
"password": config.text(5), "password": config.text(5),
"secondary": {"host": config.text(3), "port": config.integer(4, 2)}, "secondary": {"host": config.text(3), "port": config.integer(4, 2)},
@@ -137,7 +138,7 @@ def plan(
return { return {
"kind": "configure-server1", "kind": "configure-server1",
"model": 231, "model": 231,
"firmware": "0.01", "firmware": row["observed"]["firmware"],
"imei": row["identity_key"], "imei": row["identity_key"],
"password": config.text(5), "password": config.text(5),
"expected": {"host": config.text(1), "port": config.integer(2, 2)}, "expected": {"host": config.text(1), "port": config.integer(2, 2)},
@@ -185,6 +186,11 @@ def start(
or queued_job["command"] != command or queued_job["command"] != command
): ):
raise EquipmentError("Операция отменена, просрочена или устройство изменилось.") raise EquipmentError("Операция отменена, просрочена или устройство изменилось.")
if intent := queued_job.get("network_intent"):
from .equipment_command_repeat import fingerprint
if fingerprint(equipment, row, intent) != intent["fingerprint"]:
raise EquipmentError("Настройки изменились после запроса повтора.")
if ( if (
queued_job is None queued_job is None
and previous.get("requested_revision") == revision and previous.get("requested_revision") == revision
@@ -238,6 +244,11 @@ def start(
"0.1.39", "0.1.39",
"0.1.40", "0.1.40",
"0.1.41", "0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
) )
) )
automatic_access = None automatic_access = None
@@ -303,7 +314,18 @@ def start(
assert body is not None assert body is not None
if body.get("sim_policy") == "both" and source.get("status", {}).get( if body.get("sim_policy") == "both" and source.get("status", {}).get(
"version" "version"
) not in {"0.1.37", "0.1.38", "0.1.39", "0.1.40", "0.1.41"}: ) not in {
"0.1.37",
"0.1.38",
"0.1.39",
"0.1.40",
"0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
}:
raise EquipmentError("Для разрешения обеих SIM установите актуальный VPS Host.") raise EquipmentError("Для разрешения обеих SIM установите актуальный VPS Host.")
if body["kind"] == "select-sim" and source.get("status", {}).get("version") not in { if body["kind"] == "select-sim" and source.get("status", {}).get("version") not in {
"0.1.24", "0.1.24",
@@ -324,6 +346,11 @@ def start(
"0.1.39", "0.1.39",
"0.1.40", "0.1.40",
"0.1.41", "0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
}: }:
raise EquipmentError("Для смены SIM установите актуальный VPS Host.") raise EquipmentError("Для смены SIM установите актуальный VPS Host.")
else: else:
@@ -370,6 +397,11 @@ def start(
"0.1.39", "0.1.39",
"0.1.40", "0.1.40",
"0.1.41", "0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
), ),
"request-position": ( "request-position": (
"0.1.8", "0.1.8",
@@ -406,6 +438,11 @@ def start(
"0.1.39", "0.1.39",
"0.1.40", "0.1.40",
"0.1.41", "0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
), ),
"pulse-output": ( "pulse-output": (
"0.1.9", "0.1.9",
@@ -441,6 +478,11 @@ def start(
"0.1.39", "0.1.39",
"0.1.40", "0.1.40",
"0.1.41", "0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
), ),
"set-output": ( "set-output": (
"0.1.10", "0.1.10",
@@ -475,6 +517,11 @@ def start(
"0.1.39", "0.1.39",
"0.1.40", "0.1.40",
"0.1.41", "0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
), ),
} }
if source.get("status", {}).get("version") not in versions[command["kind"]]: if source.get("status", {}).get("version") not in versions[command["kind"]]:
@@ -519,6 +566,11 @@ def start(
"0.1.39", "0.1.39",
"0.1.40", "0.1.40",
"0.1.41", "0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
) )
for h in (source, target) for h in (source, target)
): ):
@@ -601,6 +653,11 @@ def start(
"0.1.39", "0.1.39",
"0.1.40", "0.1.40",
"0.1.41", "0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
} }
if durable_delivery: if durable_delivery:
lifetime = ( lifetime = (
@@ -608,6 +665,8 @@ def start(
if body["kind"] == "select-sim" if body["kind"] == "select-sim"
else 180 else 180
if full or body["kind"] == "restart" if full or body["kind"] == "restart"
else 60
if body["kind"] in {"set-output", "pulse-output"}
else 30 else 30
if command is not None if command is not None
else 120 else 120
@@ -769,6 +828,7 @@ def record(
return return
if op.get("scope") == "command": if op.get("scope") == "command":
if result["state"] not in PENDING | { if result["state"] not in PENDING | {
"delivered",
"device_confirmed", "device_confirmed",
"device_rejected", "device_rejected",
"reconnected", "reconnected",
@@ -799,6 +859,8 @@ def record(
"reconnected_at", "reconnected_at",
"reconnect_seconds", "reconnect_seconds",
"telemetry_measured_at", "telemetry_measured_at",
"delivered_at",
"delivery_seconds",
): ):
value = result.get(key) value = result.get(key)
if type(value) in (int, float) and math.isfinite(value) and value >= 0: if type(value) in (int, float) and math.isfinite(value) and value >= 0:
+24 -3
View File
@@ -20,12 +20,24 @@ ATTEMPT_FACTS = {
"stage", "stage",
"queue_seconds", "queue_seconds",
"attempt_expires_at", "attempt_expires_at",
"delivered_at",
"delivery_seconds",
} }
KINDS = {"request-position", "restart", "read-configuration", "configure-all", "select-sim"} KINDS = {
"request-position",
"restart",
"read-configuration",
"configure-all",
"select-sim",
"set-output",
"pulse-output",
}
def supported(host, kind): def supported(host, kind):
if kind in {"set-output", "pulse-output"}:
return "arnavi-b2-command-scheduler-v2" in host.get("status", {}).get("capabilities", [])
return kind in KINDS and "arnavi-b2-durable-operations-v1" in host.get("status", {}).get( return kind in KINDS and "arnavi-b2-durable-operations-v1" in host.get("status", {}).get(
"capabilities", [] "capabilities", []
) )
@@ -61,8 +73,17 @@ def project(op, result):
op["runtime_phase"] = phase op["runtime_phase"] = phase
if result.get("stop_requested") is True: if result.get("stop_requested") is True:
op["stop_requested"] = True op["stop_requested"] = True
if result.get("reason") == "sim_card_changed": if result.get("reason") in {
op["reason"] = "sim_card_changed" "sim_card_changed",
"delivery_deadline",
"connection_closed",
"host_restarted",
"socket_error",
"write_failed",
"expired_before_write",
"pulse_result_unknown",
}:
op["reason"] = result["reason"]
def disconnected(equipment, identifier, operation_id): def disconnected(equipment, identifier, operation_id):
+3
View File
@@ -361,10 +361,13 @@ class VPSHosts:
self.command_wake.wait(1 if pending else 5) self.command_wake.wait(1 if pending else 5)
def _runtime_tick(self, next_sync: dict[str, float]) -> bool: def _runtime_tick(self, next_sync: dict[str, float]) -> bool:
from . import equipment_command_dispatch
from .equipment_command_runtime import pump from .equipment_command_runtime import pump
from .equipment_network import refresh from .equipment_network import refresh
with self.lock: with self.lock:
with suppress(OSError, ValueError, KeyError, sqlite3.Error, http.client.HTTPException):
equipment_command_dispatch.pump(self)
for row in self.rows(): for row in self.rows():
if self.stop.is_set(): if self.stop.is_set():
break break
+17 -1
View File
@@ -201,6 +201,7 @@ def command_runtime(
tracked: Annotated[list[str] | None, Query(max_length=32)] = None, tracked: Annotated[list[str] | None, Query(max_length=32)] = None,
) -> Document: ) -> Document:
from k1link.fleet.equipment_command_catalog import catalog from k1link.fleet.equipment_command_catalog import catalog
from k1link.fleet.equipment_command_dispatch import supported as scheduler_supported
from k1link.fleet.equipment_command_journal import listing from k1link.fleet.equipment_command_journal import listing
from k1link.fleet.equipment_command_runtime import source from k1link.fleet.equipment_command_runtime import source
from k1link.fleet.equipment_operations import KINDS, supported from k1link.fleet.equipment_operations import KINDS, supported
@@ -215,7 +216,7 @@ def command_runtime(
**listing(equipment, identifier, before, tracked=tracked or ()), **listing(equipment, identifier, before, tracked=tracked or ()),
"device": equipment.public(row), "device": equipment.public(row),
"catalog": catalog(equipment, row), "catalog": catalog(equipment, row),
"capacity": 32, "capacity": None if scheduler_supported(host) else 32,
"durable_kinds": sorted(k for k in KINDS if supported(host or {}, k)), "durable_kinds": sorted(k for k in KINDS if supported(host or {}, k)),
} }
@@ -244,6 +245,21 @@ def cancel_command(identifier: str, request_id: str, response: Response, fleet:
) )
class RepeatCommandRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
request_id: str = Field(pattern=r"^[a-f0-9]{32}$")
@router.post("/instances/{identifier}/commands/{original_id}/repeat")
def repeat_command(
identifier: str, original_id: str, body: RepeatCommandRequest, response: Response, fleet: Fleet
) -> Document:
from k1link.fleet.equipment_command_repeat import repeat
from k1link.web.vps_host_api import store
return action(response, lambda: repeat(store(fleet), identifier, original_id, body.request_id))
@router.get("/instances/{identifier}/commands/{request_id}/attempts") @router.get("/instances/{identifier}/commands/{request_id}/attempts")
def command_attempts( def command_attempts(
identifier: str, identifier: str,
+327
View File
@@ -0,0 +1,327 @@
{
"cases": [
{
"preset": "position",
"request": {
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "request-position",
"model": 231
},
"wire_hex": "0101"
},
{
"preset": "restart",
"request": {
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "restart",
"model": 231
},
"wire_hex": "0107"
},
{
"preset": "pin4-on",
"request": {
"enabled": true,
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 4
},
"wire_hex": "3132333435362a534552562a382e342e31"
},
{
"preset": "pin4-off",
"request": {
"enabled": false,
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 4
},
"wire_hex": "3132333435362a534552562a382e342e30"
},
{
"preset": "pin4-pulse",
"request": {
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "pulse-output",
"model": 231,
"password": "123456",
"pin": 4,
"seconds": 5
},
"wire_hex": "3132333435362a534552562a32342e342e302e35"
},
{
"preset": "pin5-on",
"request": {
"enabled": true,
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 5
},
"wire_hex": "3132333435362a534552562a382e352e31"
},
{
"preset": "pin5-off",
"request": {
"enabled": false,
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 5
},
"wire_hex": "3132333435362a534552562a382e352e30"
},
{
"preset": "pin5-pulse",
"request": {
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "pulse-output",
"model": 231,
"password": "123456",
"pin": 5,
"seconds": 5
},
"wire_hex": "3132333435362a534552562a32342e352e302e35"
},
{
"preset": "pin6-on",
"request": {
"enabled": true,
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 6
},
"wire_hex": "3132333435362a534552562a382e362e31"
},
{
"preset": "pin6-off",
"request": {
"enabled": false,
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 6
},
"wire_hex": "3132333435362a534552562a382e362e30"
},
{
"preset": "pin6-pulse",
"request": {
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "pulse-output",
"model": 231,
"password": "123456",
"pin": 6,
"seconds": 5
},
"wire_hex": "3132333435362a534552562a32342e362e302e35"
},
{
"preset": "position",
"request": {
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "request-position",
"model": 231
},
"wire_hex": "0101"
},
{
"preset": "restart",
"request": {
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "restart",
"model": 231
},
"wire_hex": "0107"
},
{
"preset": "pin4-on",
"request": {
"enabled": true,
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 4
},
"wire_hex": "3132333435362a534552562a382e342e31"
},
{
"preset": "pin4-off",
"request": {
"enabled": false,
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 4
},
"wire_hex": "3132333435362a534552562a382e342e30"
},
{
"preset": "pin4-pulse",
"request": {
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "pulse-output",
"model": 231,
"password": "123456",
"pin": 4,
"seconds": 5
},
"wire_hex": "3132333435362a534552562a32342e342e302e35"
},
{
"preset": "pin5-on",
"request": {
"enabled": true,
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 5
},
"wire_hex": "3132333435362a534552562a382e352e31"
},
{
"preset": "pin5-off",
"request": {
"enabled": false,
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 5
},
"wire_hex": "3132333435362a534552562a382e352e30"
},
{
"preset": "pin5-pulse",
"request": {
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "pulse-output",
"model": 231,
"password": "123456",
"pin": 5,
"seconds": 5
},
"wire_hex": "3132333435362a534552562a32342e352e302e35"
},
{
"preset": "pin6-on",
"request": {
"enabled": true,
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 6
},
"wire_hex": "3132333435362a534552562a382e362e31"
},
{
"preset": "pin6-off",
"request": {
"enabled": false,
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 6
},
"wire_hex": "3132333435362a534552562a382e362e30"
},
{
"preset": "pin6-pulse",
"request": {
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "pulse-output",
"model": 231,
"password": "123456",
"pin": 6,
"seconds": 5
},
"wire_hex": "3132333435362a534552562a32342e362e302e35"
}
],
"codec_sha256": {
"arnavi.py": "10c0f1bd41c5fd2c89349d3f668c38c88bec36773e7529d138f9c91e1a124136",
"sim_network.py": "9984645831cbd777275a06d54e6a2633537b69ef04281c4e3eb87d0f559c3f44",
"usb_protocol.py": "b2f067c4a443bcd9535a094bc119b8d1e2fd1ecf09a4812c3c49a7f31dfb1073",
"web_protocol.py": "f9c3eba194144e6cc839e80997917967b8075bdbc866fdbefa6929b55cd27c86"
},
"schema": "nodedc.arnavi-client-contract/v1",
"server_version": "0.1.46",
"synthetic_only": true
}
+16
View File
@@ -0,0 +1,16 @@
"""Pinned public protocol vectors replace imports of the extracted VPS server."""
import hashlib
import json
from pathlib import Path
def test_client_codecs_match_the_qualified_server_contract():
root = Path(__file__).resolve().parents[1]
contract = json.loads((root / "tests/fixtures/arnavi_vps/client-v1.json").read_text())
assert contract["schema"] == "nodedc.arnavi-client-contract/v1"
assert contract["synthetic_only"] is True
for server_name, digest in contract["codec_sha256"].items():
name = "internal.py" if server_name == "arnavi.py" else server_name
path = root / "src/k1link/device_plugins/arnavi_b2" / name
assert hashlib.sha256(path.read_bytes()).hexdigest() == digest
+1 -66
View File
@@ -1,13 +1,11 @@
"""Card identity, three-field APN overlay and the last network write boundary.""" """Card identity, three-field APN overlay and the last network write boundary."""
import json import json
import time
import pytest import pytest
from test_b2_cellular_telemetry import package, status from test_b2_cellular_telemetry import status
from test_b2_sim_identity import CARD_A, CARD_B, IMEI, capture, exchange from test_b2_sim_identity import CARD_A, CARD_B, IMEI, capture, exchange
from test_b2_sim_network import AT, tags, update from test_b2_sim_network import AT, tags, update
from test_vps_host import full_context, reach_sim_restart, sim_context, store # noqa: F401
from k1link.device_plugins.arnavi_b2 import profiles, sim_access from k1link.device_plugins.arnavi_b2 import profiles, sim_access
from k1link.device_plugins.arnavi_b2.sim_network import binding from k1link.device_plugins.arnavi_b2.sim_network import binding
@@ -95,66 +93,3 @@ def test_automatic_overlay_replaces_apn_and_credentials_only_for_selected_sim():
assert all(desired.value(n) == config.value(n) for n in (67, 68, 69, 222)) assert all(desired.value(n) == config.value(n) for n in (67, 68, 69, 222))
assert desired.integer(72, 4) == 1 << 10 assert desired.integer(72, 4) == 1 << 10
assert not profiles.portable(desired)["connectivity"]["automatic"] assert not profiles.portable(desired)["connectivity"]["automatic"]
def guarded(context):
command, body, _, _, _, now = context
body["sim_guard"] = {"slot": 2, "sid": CARD_A[1]}
command.sim_guard.observe(body["imei"], package(int(now[0]), tags(2, CARD_A[1]) + status()))
return command, body, now
def test_card_swap_after_dispatch_prevents_http_configuration_write(sim_context): # noqa: F811
command, body, now = guarded(sim_context)
_, _, before, _, wire, _ = sim_context
command.submit(body)
command.session_activity[body["imei"], "live"] = time.monotonic()
assert command.take(body["imei"], "live")
command.web_receive(wire(5, before.encode()), "192.0.2.1")
now[0] += 16
command.session_activity[body["imei"], "live"] = time.monotonic()
assert command.take(body["imei"], "live")
command.sim_guard.observe(body["imei"], package(int(now[0]), tags(2, CARD_B[1]) + status()))
assert command.web_receive(wire(2), "192.0.2.1") is None
result = command.get(body["id"])
assert result["state"] == "rejected" and result["reason"] == "sim_card_changed"
assert "write_reply_sent_at" not in result and "sim_guard" not in result
def test_gprs_without_new_card_identity_cannot_confirm_automatic_access(sim_context): # noqa: F811
command, body, now = guarded(sim_context)
reach_sim_restart(sim_context)
assert command.take(body["imei"], "live")
now[0] += 2
command.session_started[body["imei"], "new"] = time.monotonic()
now[0] += 1
command.receive(body["imei"], package(int(now[0]), status()), "new")
assert command.get(body["id"])["state"] == "dispatched"
now[0] += 1
command.receive(body["imei"], package(int(now[0]), tags(2, CARD_A[1]) + status()), "new")
result = command.get(body["id"])
assert result["state"] == "sim_selected" and result["sim_guard_verified"] is True
def test_guard_and_waiting_intent_survive_vps_restart(sim_context): # noqa: F811
from ndc_vps.commands import Commands
from ndc_vps.operations import Operations
command, body, now = guarded(sim_context)
runtime = Operations(command.store, command)
runtime.submit(body)
command.sim_guard.observe(body["imei"], package(int(now[0] + 1), status(second=0)))
now[0] += 2
command.session_activity[body["imei"], "live"] = time.monotonic()
runtime.advance(body["imei"])
assert runtime.get(body["id"])["runtime_phase"] == "waiting-identity"
assert runtime.get(body["id"])["attempt_count"] == 0
restored = Operations(command.store, Commands(command.store))
restored.commands.sessions[body["imei"]] = {"new"}
restored.commands.session_activity[body["imei"], "new"] = time.monotonic()
restored.commands.sim_guard.observe(
body["imei"], package(int(now[0]), tags(2, CARD_B[1]) + status())
)
assert restored.get(body["id"])["state"] == "rejected"
assert restored.get(body["id"])["reason"] == "sim_card_changed"
assert restored.get(body["id"])["attempt_count"] == 0
-51
View File
@@ -1,17 +1,9 @@
"""Both-SIM permission is not a promise of priority or automatic failover.""" """Both-SIM permission is not a promise of priority or automatic failover."""
import hashlib
import json import json
import pytest import pytest
from test_equipment_network import context, full_core_context # noqa: F401 from test_equipment_network import context, full_core_context # noqa: F401
from test_vps_host import ( # noqa: F401
full_context,
reach_sim_restart,
sim_context,
sim_packet,
store,
)
from k1link.device_plugins.arnavi_b2 import profiles from k1link.device_plugins.arnavi_b2 import profiles
from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, Setting from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, Setting
@@ -37,49 +29,6 @@ def test_both_permission_preserves_apns_passwords_and_other_flags(flags):
profiles.Policy(connectivity={"strategy": "both", "apn": "conflict"}) profiles.Policy(connectivity={"strategy": "both", "apn": "conflict"})
def both_context(source):
command, body, before, target, wire, now = source
# Existing exclusive target becomes the predecessor; remove its prohibition.
body.pop("sim_slot")
body.update(
sim_policy="both",
expected_sha256=hashlib.sha256(target.encode()).hexdigest(),
target_configuration=before.encode().hex(),
)
return command, body, target, before, wire, now
@pytest.mark.parametrize("slot", [1, 2])
def test_both_requires_readback_then_fresh_gprs_on_new_session(sim_context, slot): # noqa: F811
command, body, before, target, wire, now = both_context(sim_context)
reach_sim_restart((command, body, before, target, wire, now))
assert command.take(body["imei"], "live")[-3:-1] == b"\x01\x07"
now[0] += 10
command.receive(body["imei"], sim_packet(now[0], slot=slot), "live")
assert command.get(body["id"])["state"] == "dispatched"
command.session_started[body["imei"], "new"] = now[0] - 1700000000
now[0] += 1
command.receive(body["imei"], sim_packet(now[0], slot=slot, gsm=3), "new")
assert command.get(body["id"])["state"] == "dispatched"
command.receive(body["imei"], sim_packet(now[0], slot=slot), "new")
result = command.get(body["id"])
assert result["state"] == "sim_selected" and result["active_sim"] == slot
assert result["sim_policy"] == "both"
@pytest.mark.parametrize("bad", ["slot", "flags", "policy"])
def test_vps_rejects_contradictory_both_request(sim_context, bad): # noqa: F811
command, body, before, _, _, _ = both_context(sim_context)
if bad == "slot":
body["sim_slot"] = 1
elif bad == "flags":
body["target_configuration"] = before.encode().hex()
else:
body["sim_policy"] = "preferred"
with pytest.raises(ValueError):
command.submit(body)
@pytest.mark.parametrize("slot", [1, 2]) @pytest.mark.parametrize("slot", [1, 2])
def test_core_both_receipt_accepts_either_real_slot_and_no_configuration_only_success( def test_core_both_receipt_accepts_either_real_slot_and_no_configuration_only_success(
full_core_context, # noqa: F811 full_core_context, # noqa: F811
+51
View File
@@ -0,0 +1,51 @@
"""Synthetic 0.06 compatibility: keep unknown fields and reject unobserved versions."""
# ruff: noqa: F811 -- imported pytest fixtures are injected by parameter name.
import pytest
from test_equipment_network import context, full_core_context # noqa: F401
from k1link.device_plugins.arnavi_b2.usb_protocol import ProtocolError, decode_configuration
from k1link.device_plugins.arnavi_b2.web_protocol import decode_request
from k1link.fleet import equipment_actions, equipment_network
from k1link.fleet.independent_equipment import EquipmentError
def test_core_propagates_actual_firmware_and_preserves_unknown_config(full_core_context):
equipment, _, row, config = full_core_context
row["observed"]["firmware"] = "0.06"
action = equipment_actions.plan(equipment, row, {"kind": "request-position"})
assert action["firmware"] == "0.06"
planned = equipment_network.plan(equipment, row, full=True)
assert planned["firmware"] == "0.06"
target = decode_configuration(bytes.fromhex(planned["target_configuration"]))
assert target.integer(25, 2) == 16
assert target.value(222) == config.value(222)
assert [r.number for r in target.records] == [r.number for r in config.records]
row["observed"]["firmware"] = "0.07"
with pytest.raises(EquipmentError):
equipment_actions.plan(equipment, row, {"kind": "request-position"})
with pytest.raises(EquipmentError):
equipment_network.plan(equipment, row, full=True)
@pytest.mark.parametrize(
"metadata,accepted",
[
("0001e7020000", True),
("0006e7020000", True),
("0007e7020000", False),
("0006e7030000", False),
("0006e7020001", False),
],
)
def test_web006_upload_keeps_crc_image(metadata, accepted, full_core_context):
*_, config = full_core_context
payload = config.encode()
body = int("123456789012345").to_bytes(8, "little")
body += bytes.fromhex(metadata) + b"\x05" + payload
frame = b"[\x01" + len(body).to_bytes(2, "big") + body + b"]"
if accepted:
assert decode_request(frame)[1:] == (5, payload)
else:
with pytest.raises(ProtocolError):
decode_request(frame)
+3 -10
View File
@@ -63,18 +63,11 @@ def test_initial_usb_apply_rejects_unowned_or_incompatible_destination(case):
def test_initial_usb_apply_accepts_current_shipped_host(): def test_initial_usb_apply_accepts_current_shipped_host():
import ast import json
from pathlib import Path from pathlib import Path
# Read the shipped artifact's version without importing its hardware service. source = Path(__file__).resolve().parent / "fixtures/arnavi_vps/client-v1.json"
source = Path(__file__).resolve().parents[1] / "apps/vps-host/ndc_vps/__init__.py" version = json.loads(source.read_text())["server_version"]
module = ast.parse(source.read_text())
version = next(
ast.literal_eval(n.value)
for n in module.body
if isinstance(n, ast.Assign)
and any(isinstance(t, ast.Name) and t.id == "VERSION" for t in n.targets)
)
hosts, _, host = context() hosts, _, host = context()
host["status"]["version"] = version host["status"]["version"] = version
assert apply(hosts, "device", 1) == {"ok": True} assert apply(hosts, "device", 1) == {"ok": True}
+125
View File
@@ -0,0 +1,125 @@
"""Persisted independent jobs: lost HTTP replies, cancellation and large queues."""
# ruff: noqa: F811
import json
import time
import pytest
from test_equipment_network import context # noqa: F401
from k1link.fleet import equipment_command_dispatch as dispatch
from k1link.fleet import equipment_command_journal as journal
from k1link.fleet import equipment_command_runtime as runtime
from k1link.fleet.independent_equipment import EquipmentStore
@pytest.fixture
def ready(context):
equipment, hosts, row = context
for host in hosts.rows():
host["status"]["version"] = "0.1.43"
host["status"]["capabilities"] = [dispatch.CAPABILITY, "arnavi-b2-durable-operations-v1"]
hosts.save(host)
return equipment, hosts, row
def test_outage_and_restart_keep_exact_job_body_and_id_without_deadline(ready, monkeypatch):
equipment, hosts, row = ready
created = runtime.enqueue(hosts, row["id"], "1" * 32, "pin4-off")
assert created["durable"] and "expires_at" not in created and "queue_deadline" not in created
sent = []
def lost(host, method, path, body=None):
sent.append((method, path, body))
raise OSError("reply lost")
monkeypatch.setattr(dispatch, "request", lost)
runtime.pump(hosts)
assert sent[0][0:2] == ("POST", "/v1/operations")
assert sent[0][2]["priority"] == "manual"
assert "not_after" not in sent[0][2]
hosts.equipment = EquipmentStore(equipment.root.parent, {})
later = time.time() + 86400
monkeypatch.setattr(time, "time", lambda: later)
runtime.pump(hosts)
assert sent[1] == sent[0]
assert journal.listing(hosts.equipment, row["id"])["items"][0]["state"] == "submitting"
assert "password" not in json.dumps(journal.listing(hosts.equipment, row["id"]))
def test_all_jobs_reach_vps_despite_pending_background_and_results_project_by_id(
ready, monkeypatch
):
equipment, hosts, row = ready
with equipment.db() as db:
current = equipment._find(db, "instances", row["id"])
current["network_operation"] = {
"id": "background",
"state": "queued",
"kind": "request-position",
}
db.execute("update instances set body=? where id=?", (json.dumps(current), row["id"]))
for n, preset in enumerate(("pin4-off", "pin5-off", "pin4-on")):
runtime.enqueue(hosts, row["id"], f"{n:032x}", preset)
requests = {}
def send(host, method, path, body=None):
if method == "POST":
requests[body["id"]] = body
return dict(id=body["id"], kind=body["kind"], state="queued", durable=True)
identifier = path.rsplit("/", 1)[1]
return dict(
id=identifier,
kind=requests[identifier]["kind"],
state="delivered",
durable=True,
delivered_at=time.time(),
delivery_seconds=1,
attempt_count=1,
)
monkeypatch.setattr(dispatch, "request", send)
runtime.pump(hosts)
assert len(requests) == 3
later = time.time() + 3
monkeypatch.setattr(time, "time", lambda: later)
runtime.pump(hosts)
entries = journal.listing(equipment, row["id"])["items"]
assert all(x["state"] == "delivered" and x["delivered_at"] == later for x in entries)
with equipment.db() as db:
assert (
equipment._find(db, "instances", row["id"])["network_operation"]["id"] == "background"
)
assert db.execute("select count(*) from command_dispatch").fetchone()[0] == 0
def test_cancel_after_lost_admission_sends_tombstone_not_another_command(ready, monkeypatch):
equipment, hosts, row = ready
runtime.enqueue(hosts, row["id"], "1" * 32, "pin5-pulse")
monkeypatch.setattr(dispatch, "request", lambda *a, **k: (_ for _ in ()).throw(OSError()))
runtime.pump(hosts)
runtime.cancel(equipment, row["id"], "1" * 32, hosts)
later = time.time() + 3
monkeypatch.setattr(time, "time", lambda: later)
seen = []
def stop(host, method, path, body=None):
seen.append((method, path, body))
return dict(
id="1" * 32, kind="pulse-output", state="stopped", durable=True, stop_requested=True
)
monkeypatch.setattr(dispatch, "request", stop)
runtime.pump(hosts)
assert seen[0][1].endswith("/cancel")
assert journal.listing(equipment, row["id"])["items"][0]["state"] == "stopped"
def test_v2_queue_exceeds_old_limit_but_history_response_stays_bounded(ready):
equipment, hosts, row = ready
for n in range(80):
runtime.enqueue(hosts, row["id"], f"{n:032x}", "pin4-off")
response = journal.listing(equipment, row["id"])
assert response["counts"]["waiting"] == 80
assert len(response["items"]) == 25
assert len(response["tracked_items"]) <= 64
+48
View File
@@ -0,0 +1,48 @@
"""Repeat history after transport outbox cleanup; never replay changed settings."""
import json
import pytest
from test_equipment_network import context, full_core_context # noqa: F401
from k1link.fleet import equipment_command_journal as journal
from k1link.fleet import equipment_command_runtime as runtime
from k1link.fleet import equipment_network as network
from k1link.fleet.equipment_command_repeat import repeat
from k1link.fleet.independent_equipment import EquipmentError
@pytest.mark.parametrize("read_only", [True, False])
def test_repeat_network_intent_after_outbox_cleanup(full_core_context, monkeypatch, read_only): # noqa: F811
equipment, hosts, row, _ = full_core_context
for host in hosts.rows():
host["status"].update(version="0.1.42", capabilities=["arnavi-b2-durable-operations-v1"])
hosts.save(host)
sent = []
def send(host, method, path, body=None):
sent.append(body)
return {"id": body["id"], "kind": body["kind"], "state": "rejected", "durable": True}
monkeypatch.setattr(network, "request", send)
original = network.start(hosts, row["id"], row["revision"], read_only)["network_operation"]
with equipment.db() as db:
assert db.execute("SELECT count(*) FROM network_outbox").fetchone()[0] == 0
repeated = repeat(hosts, row["id"], original["id"], "f" * 32)
assert repeated["state"] == "waiting"
assert "network_intent" not in repeated
assert repeat(hosts, row["id"], original["id"], "f" * 32) == repeated
runtime.pump(hosts)
assert len(sent) == 2 and sent[0]["kind"] == sent[1]["kind"]
assert sent[0]["id"] != sent[1]["id"]
if not read_only:
assert sent[0]["target_configuration"] == sent[1]["target_configuration"]
with equipment.db() as db:
current = equipment._find(db, "instances", row["id"])
current["settings"]["parameters"]["25"] += 1
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(current), row["id"]))
with pytest.raises(EquipmentError, match="Настройки изменились"):
repeat(hosts, row["id"], original["id"], "a" * 32)
assert all(
"network_intent" not in item for item in journal.listing(equipment, row["id"])["items"]
)
+34 -7
View File
@@ -210,7 +210,7 @@ def test_catalog_and_history_never_expose_password(ready, monkeypatch):
public = json.dumps([values, journal.listing(equipment, row["id"])], ensure_ascii=False) public = json.dumps([values, journal.listing(equipment, row["id"])], ensure_ascii=False)
assert "123456" not in public and '"password"' not in public and "identity_key" not in public assert "123456" not in public and '"password"' not in public and "identity_key" not in public
assert "••••••*SERV*8.4.1" in public assert "••••••*SERV*8.4.1" in public
assert value["description"]["queue_seconds"] == 3 assert value["description"]["queue_seconds"] == 30
def test_tracker_acceptance_is_persisted_but_does_not_finish_intent(ready, monkeypatch): def test_tracker_acceptance_is_persisted_but_does_not_finish_intent(ready, monkeypatch):
@@ -375,24 +375,51 @@ def test_runtime_api_rejects_foreign_origin_and_arbitrary_command(ready):
def test_preview_matches_actual_qualified_vps_payload(ready): def test_preview_matches_actual_qualified_vps_payload(ready):
import importlib.util
from pathlib import Path from pathlib import Path
from k1link.fleet.equipment_actions import plan from k1link.fleet.equipment_actions import plan
equipment, _, row = ready equipment, _, row = ready
path = Path(__file__).resolve().parents[1] / "apps/vps-host/ndc_vps/actions.py" fixture = Path(__file__).resolve().parent / "fixtures/arnavi_vps/client-v1.json"
spec = importlib.util.spec_from_file_location("qualified_b2_actions", path) contract = json.loads(fixture.read_text())
module = importlib.util.module_from_spec(spec) cases = {
spec.loader.exec_module(module) case["preset"]: case
for case in contract["cases"]
if case["request"]["firmware"] == row["observed"]["firmware"]
}
for preset in catalog(equipment, row): for preset in catalog(equipment, row):
if preset["unavailable"]: if preset["unavailable"]:
continue continue
body = plan(equipment, row, preset["command"]) body = plan(equipment, row, preset["command"])
body.pop("secondary") body.pop("secondary")
body["id"] = "1" * 32 body["id"] = "1" * 32
wire = bytes.fromhex(module.prepare(body)["binary"]) case = cases[preset["id"]]
assert body == case["request"]
wire = bytes.fromhex(case["wire_hex"])
if preset["encoding"].endswith("FC"): if preset["encoding"].endswith("FC"):
assert wire.decode().replace("123456", "••••••") == preset["wire"] assert wire.decode().replace("123456", "••••••") == preset["wire"]
else: else:
assert wire.hex(" ").upper() == preset["wire"] assert wire.hex(" ").upper() == preset["wire"]
def test_manual_repeat_uses_new_id_and_preserves_http_idempotency(ready, monkeypatch):
from k1link.fleet.equipment_command_repeat import repeat
equipment, hosts, row = ready
original = runtime.enqueue(hosts, row["id"], "1" * 32, "position")
runtime.cancel(equipment, row["id"], original["id"])
repeated = repeat(hosts, row["id"], original["id"], "2" * 32)
assert repeated["state"] == "waiting" and repeated["id"] != original["id"]
assert repeat(hosts, row["id"], original["id"], "2" * 32) == repeated
with pytest.raises(EquipmentError, match="завершения"):
repeat(hosts, row["id"], repeated["id"], "3" * 32)
assert len(journal.listing(equipment, row["id"])["items"]) == 2
assert not {"guard", "digest", "network_intent"} & repeated.keys()
def test_repeat_missing_history_is_rejected(ready):
from k1link.fleet.equipment_command_repeat import repeat
_, hosts, row = ready
with pytest.raises(EquipmentError, match="не найдена"):
repeat(hosts, row["id"], "f" * 32, "a" * 32)
+1 -1
View File
@@ -739,7 +739,7 @@ def test_outbox_backoff_expiry_and_credentials_never_enter_public_history(contex
assert '"password"' not in "".join(r[0] for r in db.execute("SELECT body FROM history")) assert '"password"' not in "".join(r[0] for r in db.execute("SELECT body FROM history"))
network.refresh(hosts, host) network.refresh(hosts, host)
assert sum(c.args[1] == "POST" for c in calls.call_args_list) == 1 assert sum(c.args[1] == "POST" for c in calls.call_args_list) == 1
now[0] += 31 now[0] += 61
network.refresh(hosts, host) network.refresh(hosts, host)
assert sum(c.args[1] == "POST" for c in calls.call_args_list) == 1 assert sum(c.args[1] == "POST" for c in calls.call_args_list) == 1
now[0] += 40 now[0] += 40
+2 -9
View File
@@ -1,6 +1,5 @@
"""Core/VPS ownership survives lost HTTP, restarts and per-attempt timeouts.""" """Core/VPS ownership survives lost HTTP, restarts and per-attempt timeouts."""
import ast
import json import json
import time import time
from pathlib import Path from pathlib import Path
@@ -16,14 +15,8 @@ from k1link.fleet.independent_equipment import EquipmentStore
def shipped_version(): def shipped_version():
source = Path(__file__).resolve().parents[1] / "apps/vps-host/ndc_vps/__init__.py" source = Path(__file__).resolve().parent / "fixtures/arnavi_vps/client-v1.json"
module = ast.parse(source.read_text()) return json.loads(source.read_text())["server_version"]
return next(
ast.literal_eval(n.value)
for n in module.body
if isinstance(n, ast.Assign)
and any(isinstance(t, ast.Name) and t.id == "VERSION" for t in n.targets)
)
@pytest.fixture(params=sorted({"0.1.32", shipped_version()})) @pytest.fixture(params=sorted({"0.1.32", shipped_version()}))
-93
View File
@@ -1,93 +0,0 @@
"""B2 token receipts can return through either admitted monitoring connection."""
import struct
import time
import pytest
from test_vps_host import store # noqa: F401
def receipt(token, code=0):
data = struct.pack("<I", int(time.time())) + bytes((code,)) + token
return b"[\x01\x09\x05\0" + data + bytes([sum(data) % 256]) + b"]"
@pytest.fixture
def pending(store): # noqa: F811
from ndc_vps.commands import Commands
commands = Commands(store)
imei = "123456789012345"
other = "123456789012346"
store.set_devices(
[
{"imei": imei, "instance_id": "a" * 32},
{"imei": other, "instance_id": "b" * 32},
]
)
commands.sessions[imei] = {"primary", "secondary"}
commands.sessions[other] = {"another-tracker"}
body = {
"id": "c" * 32,
"imei": imei,
"kind": "request-position",
"model": 231,
"firmware": "0.01",
}
commands.submit(body)
raw = commands.take(imei, "primary")
return commands, imei, other, body, raw[5:9]
def test_second_stream_receipt_confirms_once_without_resending(pending):
commands, imei, _, body, token = pending
commands.receive(imei, receipt(token), "secondary")
confirmed = commands.get(body["id"])
assert confirmed["state"] == "device_confirmed" and confirmed["device_code"] == 0
assert commands.take(imei, "secondary") is None
commands.receive(imei, receipt(token, 5), "primary")
assert commands.get(body["id"]) == confirmed
assert type(commands)(commands.store).get(body["id"]) == confirmed
def test_ack_is_not_completion_and_first_acceptance_survives_duplicate(pending):
commands, imei, _, body, token = pending
commands.receive(imei, receipt(token, 6), "secondary")
accepted = commands.get(body["id"])
assert accepted["state"] == "dispatched" and accepted["device_code"] == 6
assert accepted["device_accepted_at"] > 0
commands.receive(imei, receipt(token, 6), "primary")
assert commands.get(body["id"])["device_accepted_at"] == accepted["device_accepted_at"]
commands.receive(imei, receipt(token, 5), "secondary")
assert commands.get(body["id"])["state"] == "device_rejected"
@pytest.mark.parametrize("source", ["unknown-session", "wrong-token", "other-tracker", "closed"])
def test_unrelated_receipt_never_completes_command(pending, source):
commands, imei, other, body, token = pending
session = "secondary"
if source == "unknown-session":
session = "unadmitted"
elif source == "wrong-token":
token = bytes(value ^ 255 for value in token)
elif source == "other-tracker":
imei, session = other, "another-tracker"
else:
commands.sessions[imei].remove(session)
commands.receive(imei, receipt(token), session)
assert commands.get(body["id"])["state"] == "dispatched"
def test_new_connection_can_deliver_exact_receipt_without_replay(pending):
commands, imei, _, body, token = pending
commands.sessions[imei] = {"reconnected"}
commands.receive(imei, receipt(token), "reconnected")
assert commands.get(body["id"])["state"] == "device_confirmed"
assert commands.take(imei, "reconnected") is None
def test_revoked_device_receipt_is_not_accepted(pending):
commands, imei, _, body, token = pending
commands.store.set_devices([])
commands.receive(imei, receipt(token), "secondary")
assert commands.get(body["id"])["state"] == "dispatched"
File diff suppressed because it is too large Load Diff
-60
View File
@@ -1,60 +0,0 @@
"""The service account must traverse installer code under a restrictive umask."""
import importlib.util
import json
import os
import sys
from pathlib import Path
from types import SimpleNamespace
def test_clean_install_under_private_umask_keeps_code_accessible(tmp_path, monkeypatch):
source = Path(__file__).resolve().parents[1] / "apps/vps-host"
monkeypatch.syspath_prepend(str(source))
spec = importlib.util.spec_from_file_location("vps_install_permissions", source / "install.py")
installer = importlib.util.module_from_spec(spec)
spec.loader.exec_module(installer)
root, state, unit = tmp_path / "product", tmp_path / "state", tmp_path / "service"
payload = tmp_path / "payload"
payload.mkdir()
(payload / "entry.py").write_text("# synthetic service payload\n")
for name, value in (("ROOT", root), ("STATE", state), ("UNIT", unit), ("SOURCE", payload)):
monkeypatch.setattr(installer, name, value)
# A clean install's credential generation is not relevant to access modes.
monkeypatch.setattr(installer.pwd, "getpwnam", lambda _: SimpleNamespace(pw_uid=1, pw_gid=1))
monkeypatch.setattr(installer.os, "chown", lambda *args: None)
monkeypatch.setattr(installer.ssl, "PEM_cert_to_DER_cert", lambda _: b"test cert")
monkeypatch.setattr(installer.firewall, "apply", lambda *args: False)
monkeypatch.setattr(installer, "healthy", lambda: None)
def run(*args, **kwargs):
if args[0] == "openssl":
(state / "tls.key").write_text("private test key")
(state / "tls.crt").write_text("test certificate")
if args[0] == "runuser":
for directory in (root, root / "releases", kwargs["cwd"]):
assert directory.stat().st_mode & 0o777 == 0o755
assert state.stat().st_mode & 0o777 == 0o700
assert (state / "tls.key").stat().st_mode & 0o777 == 0o600
(state / "connect.key").write_text("test invitation")
monkeypatch.setattr(installer, "run", run)
monkeypatch.setattr(installer.os, "geteuid", lambda: 0)
proposal = {
"previous": None,
"plan_sha256": "plan",
"artifact": "release",
"configuration": {"public_host": "test.example", "api_port": 19443},
"firewall": {"mode": "external"},
}
previous = os.umask(0o077)
try:
installer.apply(
SimpleNamespace(expect="plan", host="test.example", api_port=19443, tracker_port=9922),
proposal,
)
finally:
os.umask(previous)
sys.modules.pop("firewall", None)
assert json.loads((root / "installed.json").read_text())["status"] == "healthy"
assert (root / "installed.json").stat().st_mode & 0o777 == 0o600
-379
View File
@@ -1,379 +0,0 @@
"""Persistent maintenance intent recovery, isolated per tracker, no output actions."""
import json
import struct
import time
import pytest
from test_vps_host import full_context, store # noqa: F401
@pytest.fixture
def runtime(store, monkeypatch): # noqa: F811
from ndc_vps.commands import Commands
from ndc_vps.operations import Operations
now = [1800000000.0]
monkeypatch.setattr(time, "time", lambda: now[0])
monkeypatch.setattr(time, "monotonic", lambda: now[0] - 1700000000)
body = {
"id": "a" * 32,
"imei": "123456789012345",
"kind": "request-position",
"model": 231,
"firmware": "0.01",
}
store.set_devices([{"imei": body["imei"], "instance_id": "c" * 32}])
return Operations(store, Commands(store)), body, now
def connect(ops, body, session="live"):
ops.commands.sessions[body["imei"]] = {session}
ops.commands.session_activity[body["imei"], session] = time.monotonic()
ops.commands.session_started[body["imei"], session] = time.monotonic()
def reply(ops, body, raw, code=0):
payload = struct.pack("<I", int(time.time())) + bytes([code]) + raw[5:9]
ops.commands.receive(
body["imei"], b"[\x01\x09\x05\0" + payload + bytes([sum(payload) % 256]) + b"]", "live"
)
def restored(ops):
return type(ops)(ops.store, type(ops.commands)(ops.store))
def test_offline_intent_survives_time_restart_duplicate_submit_and_cancel(runtime):
ops, body, now = runtime
first = ops.submit(body)
now[0] += 86400
ops = restored(ops)
assert ops.submit(body)["id"] == first["id"]
assert ops.get(body["id"])["state"] == "queued"
assert ops.get(body["id"])["attempt_count"] == 0
with pytest.raises(ValueError, match="conflict"):
ops.submit({**body, "kind": "restart"})
assert ops.cancel(body["id"])["state"] == "stopped"
connect(ops, body)
assert restored(ops).get(body["id"])["state"] == "stopped"
assert ops.commands.take(body["imei"], "live") is None
def test_late_transport_observation_is_visible_after_operation_completed(runtime):
ops, body, now = runtime
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
raw, _, ticket = ops.commands.take_delivery(body["imei"], "live", with_receipt=True)
reply(ops, body, raw)
assert ops.get(body["id"])["state"] == "device_confirmed"
assert ops.get(body["id"])["transport"][0]["state"] == "prepared"
ops.commands.transport.record([
(ticket, "written", now[0], 0, None),
(ticket, "tcp_acknowledged", now[0] + .5, .5, None),
])
result = ops.get(body["id"])
assert result["state"] == "device_confirmed"
assert result["transport"][0]["tcp_ack_seconds"] == .5
assert ops.history(body["id"])["items"][0]["transport"] == result["transport"]
assert restored(ops).get(body["id"])["transport"] == result["transport"]
def test_lost_tracker_reply_has_new_attempt_same_intent_and_complete_history(runtime):
ops, body, now = runtime
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
first = ops.commands.take(body["imei"], "live")
now[0] += 31
assert ops.get(body["id"])["state"] == "queued"
assert ops.get(body["id"])["attempt_count"] == 1
ops = restored(ops)
now[0] += 5
connect(ops, body)
ops.advance(body["imei"])
second = ops.commands.take(body["imei"], "live")
assert first[5:9] != second[5:9]
reply(ops, body, first) # Old attempt cannot confirm the new one.
assert ops.get(body["id"])["state"] == "dispatched"
reply(ops, body, second)
assert ops.get(body["id"])["state"] == "device_confirmed"
assert ops.get(body["id"])["attempt_count"] == 2
assert [x["state"] for x in ops.history(body["id"])["items"]] == [
"device_confirmed",
"unconfirmed",
]
assert restored(ops).get(body["id"])["state"] == "device_confirmed"
with ops.store.db() as db:
assert db.execute("SELECT count(*) FROM operations").fetchone()[0] == 1
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 2
def test_vps_crash_after_dispatch_resumes_intent_not_old_attempt(runtime):
ops, body, now = runtime
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
assert ops.commands.take(body["imei"], "live")
ops = restored(ops)
assert ops.get(body["id"])["state"] == "queued"
now[0] += 5
connect(ops, body)
ops.advance(body["imei"])
raw = ops.commands.take(body["imei"], "live")
reply(ops, body, raw)
assert ops.get(body["id"])["state"] == "device_confirmed"
assert len(ops.history(body["id"])["items"]) == 2
def test_vps_crash_before_attempt_admission_and_cancellation_race(runtime, monkeypatch):
ops, body, _ = runtime
ops.submit(body)
connect(ops, body)
def crash(*args):
raise RuntimeError("simulated process loss")
monkeypatch.setattr(ops.commands, "submit", crash)
with pytest.raises(RuntimeError):
ops.advance(body["imei"])
ops = restored(ops)
assert ops.cancel(body["id"])["state"] == "stopped"
with ops.store.db() as db:
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 0
def test_cancel_before_lost_post_arrives_is_a_persisted_tombstone(runtime):
ops, body, _ = runtime
assert ops.cancel(body["id"], body["kind"])["state"] == "stopped"
ops = restored(ops)
connect(ops, body)
assert ops.submit(body)["state"] == "stopped"
assert ops.commands.take(body["imei"], "live") is None
def test_offline_tracker_does_not_block_another_and_fifo_is_per_imei(runtime):
ops, first, _ = runtime
second = {**first, "id": "b" * 32, "imei": "123456789012346"}
ops.store.set_devices(
[
{"imei": first["imei"], "instance_id": "c" * 32},
{"imei": second["imei"], "instance_id": "d" * 32},
]
)
ops.submit(first)
ops.submit(second)
ops.submit({**second, "id": "e" * 32})
connect(ops, second)
ops.advance(first["imei"])
ops.advance(second["imei"])
raw = ops.commands.take(second["imei"], "live")
assert ops.get("e" * 32)["attempt_count"] == 0
reply(ops, second, raw)
assert ops.get(second["id"])["state"] == "device_confirmed"
assert ops.get(first["id"])["attempt_count"] == 0
assert ops.get("e" * 32)["attempt_count"] == 1
@pytest.mark.parametrize(
"code,expected", [(1, "device_rejected"), (5, "device_rejected"), (7, "queued")]
)
def test_permanent_rejection_and_device_queue_backpressure_differ(runtime, code, expected):
ops, body, _ = runtime
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
reply(ops, body, ops.commands.take(body["imei"], "live"), code)
assert ops.get(body["id"])["state"] == expected
def test_restart_accepted_by_b2_never_replayed_when_return_evidence_missing(runtime):
ops, body, now = runtime
body["kind"] = "restart"
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
reply(ops, body, ops.commands.take(body["imei"], "live"))
now[0] += 181
assert ops.get(body["id"])["state"] == "accepted"
assert ops.get(body["id"])["attempt_count"] == 1
@pytest.mark.parametrize("observed", ["target", "before", "divergent"])
def test_uncertain_write_reads_state_before_any_retry(full_context, observed): # noqa: F811
from ndc_vps.operations import Operations
from ndc_vps.usb_protocol import Configuration, Setting
commands, body, before, target, wire, now = full_context
ops = Operations(commands.store, commands)
ops.submit(body)
ops.advance(body["imei"])
assert b"SERV*1.9" in commands.take(body["imei"], "live")
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
now[0] += 15
assert b"SERV*1.8" in commands.take(body["imei"], "live")
assert commands.web_receive(wire(2), "192.0.2.1")
now[0] += 181
assert ops.get(body["id"])["runtime_phase"] == "retry-wait"
now[0] += 5
commands.session_activity[body["imei"], "live"] = time.monotonic()
ops.advance(body["imei"])
assert b"SERV*1.9" in commands.take(body["imei"], "live")
image = (
target
if observed == "target"
else before
if observed == "before"
else Configuration(
tuple(
Setting(r.number, b"\x00\x11" if r.number == 25 else r.value)
for r in before.records
)
)
)
commands.web_receive(wire(5, image.encode()), "192.0.2.1")
result = ops.get(body["id"])
assert (
result["state"]
== {"target": "verified", "before": "queued", "divergent": "rejected"}[observed]
)
assert result["attempt_count"] == 2
assert "123456" not in json.dumps(ops.history(body["id"]))
with commands.store.db() as db:
images = sum(
bool(json.loads(r[0]).get("write_reply_sent_at"))
for r in db.execute("SELECT body FROM commands")
)
assert images == 1
def test_cancelled_inflight_keeps_final_receipt_but_stops_unknown_retry(runtime):
ops, body, now = runtime
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
wire = ops.commands.take(body["imei"], "live")
assert ops.cancel(body["id"])["stop_requested"]
now[0] += 31
result = ops.get(body["id"])
assert result["state"] == "stopped" and result["attempt_count"] == 1
connect(ops, body)
reply(ops, body, wire)
assert ops.get(body["id"])["state"] == "stopped"
assert ops.commands.take(body["imei"], "live") is None
def test_repeated_reads_crash_plan_after_admission_reuses_child(runtime, monkeypatch):
ops, body, _ = runtime
ops.submit(body)
connect(ops, body)
original = ops.commands.submit
def admitted(body):
original(body)
raise RuntimeError("crash after commit")
monkeypatch.setattr(ops.commands, "submit", admitted)
with pytest.raises(RuntimeError):
ops.advance(body["imei"])
ops = restored(ops)
connect(ops, body)
assert ops.get(body["id"])["attempt_count"] == 1
wire = ops.commands.take(body["imei"], "live")
reply(ops, body, wire)
assert ops.get(body["id"])["state"] == "device_confirmed"
with ops.store.db() as db:
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 1
def test_old_image_read_allows_fresh_preflight_before_second_write(full_context): # noqa: F811
from ndc_vps.operations import Operations
commands, body, before, target, wire, now = full_context
ops = Operations(commands.store, commands)
ops.submit(body)
ops.advance(body["imei"])
commands.take(body["imei"], "live")
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
now[0] += 15
commands.take(body["imei"], "live")
assert commands.web_receive(wire(2), "192.0.2.1")
now[0] += 181
ops.get(body["id"])
now[0] += 5
commands.session_activity[body["imei"], "live"] = time.monotonic()
ops.advance(body["imei"])
commands.take(body["imei"], "live")
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
assert ops.get(body["id"])["state"] == "queued"
now[0] += 15
ops.advance(body["imei"])
assert b"SERV*1.9" in commands.take(body["imei"], "live")
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
now[0] += 15
assert b"SERV*1.8" in commands.take(body["imei"], "live")
assert commands.web_receive(wire(2), "192.0.2.1")
now[0] += 15
assert b"SERV*1.9" in commands.take(body["imei"], "live")
commands.web_receive(wire(5, target.encode()), "192.0.2.1")
assert ops.get(body["id"])["state"] == "verified"
assert ops.get(body["id"])["attempt_count"] == 3
@pytest.mark.parametrize("both", [False, True])
def test_sim_recovery_reads_target_and_fresh_modem_without_second_restart(full_context, both): # noqa: F811
import hashlib
from ndc_vps.operations import Operations
from ndc_vps.usb_protocol import Configuration, Setting
from test_vps_host import sim_packet
commands, body, before, _, wire, now = full_context
before = Configuration(
before.records + (Setting(72, (2072 | (1 << 20) if both else 2072).to_bytes(4, "big")),)
)
target = Configuration(
tuple(
Setting(
r.number,
(2072 | (0 if both else 1 << 10)).to_bytes(4, "big") if r.number == 72 else r.value,
)
for r in before.records
)
)
body.update(
kind="select-sim",
sim_slot=2,
expected_sha256=hashlib.sha256(before.encode()).hexdigest(),
target_configuration=target.encode().hex(),
)
if both:
body.pop("sim_slot")
body["sim_policy"] = "both"
ops = Operations(commands.store, commands)
ops.submit(body)
ops.advance(body["imei"])
commands.take(body["imei"], "live")
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
now[0] += 15
commands.take(body["imei"], "live")
commands.web_receive(wire(2), "192.0.2.1")
now[0] += 15
commands.take(body["imei"], "live")
commands.web_receive(wire(5, target.encode()), "192.0.2.1")
assert commands.take(body["imei"], "live")[-3:-1] == b"\x01\x07"
now[0] += 361
ops.get(body["id"])
now[0] += 5
commands.session_activity[body["imei"], "live"] = time.monotonic()
ops.advance(body["imei"])
assert b"SERV*1.9" in commands.take(body["imei"], "live")
ops.observe(body["imei"], sim_packet(now[0], slot=2))
ops.observe(
body["imei"], sim_packet(now[0] - 1, slot=1)
) # delayed older sample cannot downgrade
commands.web_receive(wire(5, target.encode()), "192.0.2.1")
result = ops.get(body["id"])
assert result["state"] == "sim_selected" and result["active_sim"] == 2
assert result["attempt_count"] == 2 and commands.take(body["imei"], "live") is None
-208
View File
@@ -1,208 +0,0 @@
"""A tracker packet and the command evidence it carries have one commit boundary."""
import asyncio
import sqlite3
import subprocess
import sys
import time
from pathlib import Path
import pytest
from test_vps_command_receipts import receipt
from test_vps_host import store # noqa: F401
@pytest.mark.parametrize("failure", ["before-receipt", "after-receipt", None])
def test_packet_command_and_ack_share_commit_boundary(store, monkeypatch, failure): # noqa: F811
from ndc_vps.commands import Commands
from ndc_vps.service import Service
service = Service(store)
commands = service.commands
imei = "123456789012345"
store.set_devices([{"imei": imei, "instance_id": "a" * 32}])
commands.sessions[imei] = {"outbound"}
body = {
"id": "c" * 32,
"imei": imei,
"kind": "request-position",
"model": 231,
"firmware": "0.01",
}
commands.submit(body)
outgoing = commands.take(imei, "outbound")
raw = receipt(outgoing[5:9])
def failed(*args):
raise OSError("simulated failure inside receive pipeline")
if failure == "before-receipt":
monkeypatch.setattr(commands, "receive", failed)
elif failure == "after-receipt":
monkeypatch.setattr(service.operations, "observe", failed)
class Writer:
closed = False
def __init__(self):
self.writes = []
def get_extra_info(self, name):
return ("192.0.2.1", 12345)
def is_closing(self):
return self.closed
def write(self, data):
if data == b"{\x00\x01}":
# Check from a separate connection exactly when the ACK leaves.
assert commands.get(body["id"])["state"] == "device_confirmed"
assert len(store.fetch(0)["items"]) == 1
self.writes.append(data)
async def drain(self):
pass
def close(self):
self.closed = True
class Delivery:
def __init__(self, writer):
self.writer = writer
def ready(self):
return True
def write(self, data, *args):
self.writer.write(data)
def abort(self):
self.writer.close()
monkeypatch.setattr("ndc_vps.service.Delivery", Delivery)
async def exchange():
reader = asyncio.StreamReader()
reader.feed_data(b"\xff\x23" + int(imei).to_bytes(8, "little") + raw)
reader.feed_eof()
writer = Writer()
await service.tracker(reader, writer)
assert writer.closed and service.connections == 0
return writer.writes
writes = asyncio.run(exchange())
if failure:
assert b"{\x00\x01}" not in writes
assert store.fetch(0)["items"] == []
assert commands.get(body["id"])["state"] == "dispatched"
else:
assert writes[-1] == b"{\x00\x01}"
store.acknowledge(store.fetch(0)["items"][0]["id"])
assert store.fetch(0)["items"] == []
assert Commands(store).get(body["id"])["state"] == "device_confirmed"
def test_sqlite_failure_does_not_leave_partial_modem_or_command_evidence(store): # noqa: F811
from ndc_vps.service import Service
from test_vps_host import sim_packet
service = Service(store)
imei = "123456789012345"
store.set_devices([{"imei": imei, "instance_id": "a" * 32}])
raw = sim_packet(time.time(), slot=2)
with pytest.raises(sqlite3.OperationalError), store.packet_transaction():
store.append(imei, raw, [])
service.operations.observe(imei, raw)
with store.db() as db:
db.execute("INSERT INTO missing_table VALUES(1)")
assert store.fetch(0)["items"] == []
with store.db() as db:
assert db.execute("SELECT count(*) FROM operation_modem").fetchone()[0] == 0
# The failed scope must not leak its connection into the next packet.
with store.packet_transaction():
store.append(imei, raw, [])
service.operations.observe(imei, raw)
assert len(store.fetch(0)["items"]) == 1
with store.db() as db:
assert db.execute("SELECT count(*) FROM operation_modem").fetchone()[0] == 1
@pytest.mark.parametrize("committed", [False, True])
def test_process_loss_cannot_split_packet_and_durable_operation_result(store, committed): # noqa: F811
from ndc_vps import store as store_module
from ndc_vps.service import Service
# os._exit skips Python context-manager cleanup, as a process crash would.
script = """
import os, sys, time, struct
sys.path.insert(0, sys.argv[1])
from ndc_vps.store import Store
from ndc_vps.service import Service
service = Service(Store(sys.argv[2]))
imei = '123456789012345'
service.store.set_devices([{'imei': imei, 'instance_id': 'a'*32}])
body = {'id':'c'*32, 'imei':imei, 'kind':'request-position', 'model':231, 'firmware':'0.01'}
commands = service.commands
commands.sessions[imei] = {'live'}
commands.session_activity[imei,'live'] = time.monotonic()
service.operations.submit(body)
service.operations.advance(imei)
outgoing = commands.take(imei, 'live')
data = struct.pack('<I', int(time.time())) + b'\\0' + outgoing[5:9]
raw = b'[\\x01\\x09\\x05\\0' + data + bytes([sum(data)%256]) + b']'
with service.store.packet_transaction():
service.store.append(imei, raw, [])
commands.receive(imei, raw, 'live')
service.operations.observe(imei, raw)
if sys.argv[3] == 'before':
os._exit(77)
os._exit(77)
"""
process = subprocess.run(
[
sys.executable,
"-c",
script,
str(Path(store_module.__file__).parents[1]),
str(store.root),
"after" if committed else "before",
],
capture_output=True,
timeout=10,
)
assert process.returncode == 77, process.stderr.decode()
recovered = Service(store)
result = recovered.operations.get("c" * 32)
assert result["state"] == ("device_confirmed" if committed else "queued")
assert result["attempt_count"] == 1
assert len(store.fetch(0)["items"]) == int(committed)
with store.db() as db:
assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 1
def test_other_worker_cannot_observe_uncommitted_packet(store): # noqa: F811
import threading
from concurrent.futures import ThreadPoolExecutor
from test_vps_host import package
imei = "123456789012345"
store.set_devices([{"imei": imei, "instance_id": "a" * 32}])
written, release = threading.Event(), threading.Event()
def ingest():
with store.packet_transaction():
store.append(imei, package(), [])
written.set()
assert release.wait(5)
with ThreadPoolExecutor(max_workers=1) as worker:
pending = worker.submit(ingest)
try:
assert written.wait(5)
assert store.fetch(0)["items"] == []
finally:
release.set()
pending.result(timeout=5)
assert len(store.fetch(0)["items"]) == 1
-284
View File
@@ -1,284 +0,0 @@
"""State migration retains durable identities/history and fails before foreign mutations."""
import gzip
import hashlib
import importlib.util
import io
import json
import sqlite3
import ssl
import subprocess
import tarfile
from pathlib import Path
from types import SimpleNamespace
import pytest
from test_vps_host import store # noqa: F401
@pytest.fixture
def migration(store, monkeypatch, tmp_path): # noqa: F811
source = Path(__file__).resolve().parents[1] / "apps/vps-host/portable_state.py"
spec = importlib.util.spec_from_file_location("portable_state_test", source)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
state = store.root
subprocess.run(
[
"openssl",
"req",
"-x509",
"-newkey",
"rsa:2048",
"-nodes",
"-days",
"1",
"-subj",
"/CN=synthetic",
"-keyout",
str(state / "tls.key"),
"-out",
str(state / "tls.crt"),
],
capture_output=True,
check=True,
)
fingerprint = hashlib.sha256(
ssl.PEM_cert_to_DER_cert((state / "tls.crt").read_text())
).hexdigest()
config = {
**store.config,
"host_id": "vps_" + fingerprint,
"fingerprint": fingerprint,
"public_host": "example.org",
}
(state / "host.json").write_text(json.dumps(config))
store.config = config
store.invitation()
from ndc_vps.commands import Commands
from ndc_vps.operations import Operations
commands = Commands(store)
ops = Operations(store, commands)
imei = "123456789012345"
store.set_devices([{"imei": imei, "instance_id": "a" * 32}])
body = {
"id": "b" * 32,
"imei": imei,
"kind": "request-position",
"model": 231,
"firmware": "0.01",
}
ops.submit(body)
commands.sessions[imei] = {"old"}
commands.session_activity[imei, "old"] = module.time.monotonic()
commands.session_started[imei, "old"] = module.time.monotonic()
ops.advance(imei)
assert commands.take(imei, "old")
ops.submit({**body, "id": "c" * 32})
ops.cancel("d" * 32, "request-position")
root = tmp_path / "source"
root.mkdir()
unit = tmp_path / "unit"
unit.write_text("ConditionPathExists=!/opt/nodedc-mission-vps/migration-fence.json")
artifact = "e" * 64
proposal = {"previous": "/releases/" + artifact, "artifact": artifact, "plan_sha256": "plan"}
running = [True]
def run(*args):
if args[1] == "stop":
running[0] = False
elif args[1] == "start":
assert not (root / "migration-fence.json").exists()
running[0] = True
real_run = subprocess.run
def inspect(*args, **kwargs):
if args[0][0] == "systemctl":
return SimpleNamespace(stdout=b"active" if running[0] else b"inactive")
return real_run(*args, **kwargs)
monkeypatch.setattr(module.subprocess, "run", inspect)
monkeypatch.setattr(module.os, "geteuid", lambda: 0)
engine = SimpleNamespace(
ROOT=root,
STATE=state,
UNIT=unit,
run=run,
plan=lambda _: proposal,
digest=lambda: artifact,
healthy=lambda: None,
)
return module, engine, store, ops, tmp_path, running
def export(migration):
m, engine, _, _, tmp, running = migration
archive = tmp / "private-state.tar.gz"
m.export_state(engine, archive)
assert archive.stat().st_mode & 0o777 == 0o600
assert not running[0] and (engine.ROOT / "migration-fence.json").exists()
return archive
def test_archive_preserves_database_identity_attempts_stop_markers_and_recovery(migration):
m, engine, original, ops, tmp, _ = migration
before = {name: m.sha(engine.STATE / name) for name in m.FILES - {"journal.sqlite3"}}
archive = export(migration)
unpacked = tmp / "unpacked"
unpacked.mkdir()
m.unpack(archive, m.sha(archive), unpacked, engine.digest())
for name, digest in before.items():
assert m.sha(unpacked / "state" / name) == digest
with original.db() as a, sqlite3.connect(unpacked / "state/journal.sqlite3") as b:
assert list(a.iterdump()) == list(b.iterdump())
from ndc_vps.commands import Commands
from ndc_vps.operations import Operations
from ndc_vps.store import Store
restored_store = Store(unpacked / "state")
restored = Operations(restored_store, Commands(restored_store))
assert restored.get("b" * 32)["id"] == "b" * 32
assert restored.get("b" * 32)["state"] == "queued"
assert restored.get("b" * 32)["attempt_count"] == 1
assert restored.get("c" * 32)["attempt_count"] == 0
assert restored.history("b" * 32)["items"][0]["state"] == "uncertain"
body = {
"id": "d" * 32,
"imei": "123456789012345",
"kind": "request-position",
"model": 231,
"firmware": "0.01",
}
assert restored.submit(body)["state"] == "stopped"
assert not restored.commands.sessions # Never copy stale TCP-session liveness.
@pytest.mark.parametrize(
"variant",
["traversal", "absolute", "link", "duplicate", "extra", "missing", "oversize", "corrupt"],
)
def test_invalid_archive_rejected_without_product_mutation(migration, variant):
m, engine, _, _, tmp, _ = migration
original = export(migration)
archive = tmp / "invalid.tar.gz"
with (
tarfile.open(original) as source,
tarfile.open(archive, "w:gz", format=tarfile.USTAR_FORMAT) as dst,
):
for info in source:
if variant == "missing" and info.name == "state/connect.key":
continue
data = source.extractfile(info).read()
if variant == "corrupt" and info.name == "state/connect.key":
data = b"changed"
info.size = len(data)
dst.addfile(info, io.BytesIO(data))
if variant not in ("missing", "corrupt"):
name = {
"traversal": "../escaped",
"absolute": "/escaped",
"link": "state/host.json",
"duplicate": "state/host.json",
"extra": "extra",
"oversize": "manifest.json",
}[variant]
extra = tarfile.TarInfo(name)
if variant == "link":
extra.type, extra.linkname = tarfile.SYMTYPE, "/etc/passwd"
dst.addfile(extra)
destination = tmp / "target"
destination.mkdir()
with pytest.raises(ValueError):
m.unpack(archive, m.sha(archive), destination, engine.digest())
assert not (tmp / "escaped").exists()
def test_checksum_and_release_mismatch_rejected_before_state_use(migration):
m, engine, _, _, tmp, _ = migration
archive = export(migration)
target = tmp / "target"
target.mkdir()
with pytest.raises(ValueError, match="digest"):
m.unpack(archive, "0" * 64, target, engine.digest())
assert not list(target.iterdir())
with pytest.raises(ValueError, match="exact installer"):
m.unpack(archive, m.sha(archive), target, "f" * 64)
def test_archive_size_limit_is_checked_before_reading_large_member(migration):
m, engine, _, _, tmp, _ = migration
archive = tmp / "oversized.tar.gz"
info = tarfile.TarInfo("state/journal.sqlite3")
info.size = m.MAX_BYTES + 1
# Header only: this must be rejected without allocating or reading 2 GiB.
with gzip.open(archive, "wb") as stream:
stream.write(info.tobuf(format=tarfile.USTAR_FORMAT))
target = tmp / "target"
target.mkdir()
with pytest.raises(ValueError, match="size limit"):
m.unpack(archive, m.sha(archive), target, engine.digest())
assert not list(target.iterdir())
def test_export_failure_keeps_source_fenced_until_explicit_resume(migration, monkeypatch):
m, engine, _, _, tmp, running = migration
monkeypatch.setattr(m, "check_state", lambda _: (_ for _ in ()).throw(ValueError("broken")))
with pytest.raises(ValueError, match="broken"):
m.export_state(engine, tmp / "failed.tar.gz")
assert not running[0]
assert not (tmp / "failed.tar.gz").exists()
assert (engine.ROOT / "migration-fence.json").exists()
m.resume_source(engine)
assert running[0] and not (engine.ROOT / "migration-fence.json").exists()
def test_import_never_overwrites_existing_installation(migration):
m, engine, _, _, tmp, _ = migration
with pytest.raises(ValueError, match="empty product"):
m.import_state(engine, tmp / "does-not-exist", "0" * 64)
def test_existing_export_path_does_not_stop_source(migration):
m, engine, _, _, tmp, running = migration
existing = tmp / "existing"
existing.write_bytes(b"keep")
with pytest.raises(ValueError, match="new archive"):
m.export_state(engine, existing)
assert running[0] and existing.read_bytes() == b"keep"
@pytest.mark.parametrize("failure", ["before_publish", "after_publish"])
def test_failed_import_exposes_no_partial_identity(migration, monkeypatch, failure):
m, source, _, _, tmp, _ = migration
archive = export(migration)
target = SimpleNamespace(**vars(source))
target.ROOT, target.STATE, target.UNIT = (
tmp / "target",
tmp / "target-state",
tmp / "target-unit",
)
original_rename = m.os.rename
def rename(old, new):
assert set(p.name for p in old.iterdir()) == m.FILES
assert not new.exists()
if failure == "before_publish":
raise OSError("simulated publication failure")
return original_rename(old, new)
def apply(*args):
assert m.check_state(target.STATE)["host_id"] == m.check_state(source.STATE)["host_id"]
raise OSError("simulated service installation failure")
target.apply = apply
monkeypatch.setattr(m.os, "rename", rename)
with pytest.raises(OSError, match="simulated"):
m.import_state(target, archive, m.sha(archive))
if failure == "before_publish":
assert not target.STATE.exists()
else:
assert set(p.name for p in target.STATE.iterdir()) == m.FILES
assert m.check_state(target.STATE)["host_id"] == m.check_state(source.STATE)["host_id"]
assert not list(tmp.glob(".ndc-vps-import-*"))