Complete shared contour project linking and scoped application onboarding

This commit is contained in:
DCCONSTRUCTIONS
2026-10-01 14:47:07 +03:00
parent 1b3001dfa1
commit 5200159d0b
18 changed files with 883 additions and 75 deletions
+2 -2
View File
@@ -1287,12 +1287,12 @@ function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated,
}> }>
<form id="device-project-form" className="device-manager-form" onSubmit={submit}> <form id="device-project-form" className="device-manager-form" onSubmit={submit}>
<Select <Select
label="Контур проекта" label="Владелец проекта"
value={ownerRef} value={ownerRef}
options={ownerScopes.map((scope) => ({ options={ownerScopes.map((scope) => ({
value: scope.ownerRef, value: scope.ownerRef,
label: scope.displayName, label: scope.displayName,
description: scope.scopeKind === "company" ? "Коммерческий контур" : "Личный контур", description: scope.scopeKind === "company" ? "Компания" : "Личное пространство",
}))} }))}
onChange={setOwnerRef} onChange={setOwnerRef}
/> />
+1 -1
View File
@@ -82,7 +82,7 @@ export function B2AddDevice({ workspace, onClose, onCreated, onLegacy }: {
<Button disabled={!catalogReady || busy || !supportsB2Usb()} loading={reading} onClick={readUsb}><Icon name="refresh" />{preview ? 'Прочитать повторно' : 'Прочитать настройки по USB'}</Button> <Button disabled={!catalogReady || busy || !supportsB2Usb()} loading={reading} onClick={readUsb}><Icon name="refresh" />{preview ? 'Прочитать повторно' : 'Прочитать настройки по USB'}</Button>
</div> </div>
</SettingsCard> : <><TextField label="IMEI" value={imei} inputMode="numeric" maxLength={15} required disabled={busy} onChange={event => setImei(event.target.value.trim())} /><TextField label="ID трекера" value={number} inputMode="numeric" maxLength={10} required disabled={busy} onChange={event => setNumber(event.target.value.trim())} /></>} </SettingsCard> : <><TextField label="IMEI" value={imei} inputMode="numeric" maxLength={15} required disabled={busy} onChange={event => setImei(event.target.value.trim())} /><TextField label="ID трекера" value={number} inputMode="numeric" maxLength={10} required disabled={busy} onChange={event => setNumber(event.target.value.trim())} /></>}
{profile ? <p>Профиль сохранится в Device Core. Отправка настроек — в настройках устройства.</p> : null} {profile ? <p>Профиль сохранится на VPS. Отправка настроек трекеру — в настройках устройства.</p> : null}
</> : <SettingsCard title="Нет VPS для этого проекта"><p>{hosts.some(item => !item.reachable) ? 'Проверьте доступность VPS и связь контура с этим проектом.' : 'Подключите VPS и свяжите контур с этим проектом в разделе «Инфраструктура».'}</p></SettingsCard>} </> : <SettingsCard title="Нет VPS для этого проекта"><p>{hosts.some(item => !item.reachable) ? 'Проверьте доступность VPS и связь контура с этим проектом.' : 'Подключите VPS и свяжите контур с этим проектом в разделе «Инфраструктура».'}</p></SettingsCard>}
{!canRegister ? <p>Для регистрации устройства нужно право «Принятие устройства» в этом проекте.</p> : null} {!canRegister ? <p>Для регистрации устройства нужно право «Принятие устройства» в этом проекте.</p> : null}
{error ? <p role="alert">{error}</p> : null} {error ? <p role="alert">{error}</p> : null}
+83 -29
View File
@@ -19,13 +19,18 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
const [projects, setProjects] = useState<ProjectSummary[]>([]); const [projects, setProjects] = useState<ProjectSummary[]>([]);
const [expanded, setExpanded] = useState<string[]>([]), [keyRows, setKeyRows] = useState<string[]>([]); const [expanded, setExpanded] = useState<string[]>([]), [keyRows, setKeyRows] = useState<string[]>([]);
const [creating, setCreating] = useState(''), [name, setName] = useState(''); const [creating, setCreating] = useState(''), [name, setName] = useState('');
const [creationIntent, setCreationIntent] = useState<{ id: string; name: string } | null>(null); const [access, setAccess] = useState('read');
const [creationIntent, setCreationIntent] = useState<{ id: string; name: string; access: string } | null>(null);
const [newContour, setNewContour] = useState(false), [contourName, setContourName] = useState('');
const [targetProject, setTargetProject] = useState(project.projectRef);
const [contourIntent, setContourIntent] = useState<{ id: string; name: string; projectRef: string } | null>(null);
const [syncError, setSyncError] = useState('');
const [archiveConfirm, setArchiveConfirm] = useState(false); const [archiveConfirm, setArchiveConfirm] = useState(false);
const [issued, setIssued] = useState<{ applicationId: string; clientId: string; value: string } | null>(null); const [issued, setIssued] = useState<{ applicationId: string; clientId: string; value: string } | null>(null);
const [credentialRows, setCredentialRows] = useState<string[]>([]); const [credentialRows, setCredentialRows] = useState<string[]>([]);
const [confirm, setConfirm] = useState<{ action: string; fields: Record<string, unknown>; text: string } | null>(null); const [confirm, setConfirm] = useState<{ action: string; fields: Record<string, unknown>; text: string } | null>(null);
const request = <T,>(action: string, data: Record<string, unknown> = {}, requestId?: string) => b2Request<T>(project.projectRef, host.hostRef, action, data, requestId); const request = <T,>(action: string, data: Record<string, unknown> = {}, requestId?: string) => b2Request<T>(project.projectRef, host.hostRef, action, data, requestId);
const refresh = () => request<B2Status>('status').then(setStatus); const refresh = async () => { const value = await request<B2Status>('status'); setStatus(value); setSyncError(''); return value; };
useEffect(() => { useEffect(() => {
let active = true; let active = true;
Promise.all([request<B2Status>('status'), loadProjects()]).then(([value, available]) => { Promise.all([request<B2Status>('status'), loadProjects()]).then(([value, available]) => {
@@ -35,10 +40,25 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
}).catch((error) => { if (active) onError(error); }).finally(() => { if (active) setPending(''); }); }).catch((error) => { if (active) onError(error); }).finally(() => { if (active) setPending(''); });
return () => { active = false; }; return () => { active = false; };
}, [host.hostRef, project.projectRef]); }, [host.hostRef, project.projectRef]);
useEffect(() => {
if (pending) return;
let active = true, timer: number;
async function sync() {
try {
if (document.visibilityState === 'visible') {
const value = await request<B2Status>('status');
if (active) { setStatus(value); setSyncError(''); }
}
} catch { if (active) setSyncError('Не удалось обновить список VPS. Показаны последние полученные сведения.'); }
finally { if (active) timer = window.setTimeout(sync, 30000); }
}
timer = window.setTimeout(sync, 30000);
return () => { active = false; window.clearTimeout(timer); };
}, [host.hostRef, project.projectRef, pending]);
async function run(action: string, data: Record<string, unknown> = {}, requestId?: string) { async function run(action: string, data: Record<string, unknown> = {}, requestId?: string) {
setPending(action); setPending(action);
try { try {
const result = await request<{ connection?: { integration_id: string; client_id: string }; id?: string }>(action, data, requestId); const result = await request<{ connection?: { integration_id: string; client_id: string }; id?: string; contourId?: string }>(action, data, requestId);
if (result.connection) { if (result.connection) {
const { integration_id: applicationId, client_id: clientId } = result.connection; const { integration_id: applicationId, client_id: clientId } = result.connection;
setIssued({ applicationId, clientId, value: JSON.stringify(result.connection, null, 2) }); setIssued({ applicationId, clientId, value: JSON.stringify(result.connection, null, 2) });
@@ -48,10 +68,24 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
if (action === 'key-revoke' && issued?.clientId === data.clientId) setIssued(null); if (action === 'key-revoke' && issued?.clientId === data.clientId) setIssued(null);
if (action === 'application-delete' && issued?.applicationId === data.integrationId) setIssued(null); if (action === 'application-delete' && issued?.applicationId === data.integrationId) setIssued(null);
if (action === 'connect') { setConnection(''); setImportOpen(false); setSection('contours'); } if (action === 'connect') { setConnection(''); setImportOpen(false); setSection('contours'); }
if (action === 'contour-connect') {
setNewContour(false); setContourName(''); setContourIntent(null);
if (result.contourId) setExpanded(rows => [...new Set([...rows, result.contourId!])]);
}
setCreating(''); setName(''); setCreationIntent(null); setCreating(''); setName(''); setCreationIntent(null);
try { await refresh(); await onChanged(); } catch (error) { onError(error); } try { await refresh(); await onChanged(); } catch (error) { onError(error); }
return true; return true;
} catch (error) { onError(error); await refresh().catch(() => undefined); return false; } finally { setPending(''); } } catch (error) {
const value = await refresh().catch(() => null);
const recovered = action === 'application-connect' && requestId
? value?.applications?.find(app => app.key === 'app-' + requestId) : null;
if (recovered) {
setCreating(''); setName(''); setCreationIntent(null);
setKeyRows(rows => [...new Set([...rows, recovered.id])]);
onError(new Error('Приложение создано, но ключ не получен. Откройте его ключи и выпустите новый. Секрет повторно не показывается.'));
} else onError(error);
return false;
} finally { setPending(''); }
} }
const busy = Boolean(pending), canManage = status?.authority === 'host'; const busy = Boolean(pending), canManage = status?.authority === 'host';
const toggle = (items: string[], id: string) => items.includes(id) ? items.filter((value) => value !== id) : [...items, id]; const toggle = (items: string[], id: string) => items.includes(id) ? items.filter((value) => value !== id) : [...items, id];
@@ -80,6 +114,7 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
<dl className="b2-tracker-facts"><dt>Тип подключения</dt><dd>Прямая привязка Mission Core</dd><dt>ID приложения</dt><dd>{app.id}</dd></dl> <dl className="b2-tracker-facts"><dt>Тип подключения</dt><dd>Прямая привязка Mission Core</dd><dt>ID приложения</dt><dd>{app.id}</dd></dl>
<p>Это прежняя привязка сервера, без OAuth-ключа. Выпуск и отзыв ключей ниже относятся к приложениям API v2 и не изменяют эту привязку.</p> <p>Это прежняя привязка сервера, без OAuth-ключа. Выпуск и отзыв ключей ниже относятся к приложениям API v2 и не изменяют эту привязку.</p>
</> : <> </> : <>
<dl className="b2-tracker-facts"><dt>Доступ приложения</dt><dd>{Object.entries(app.grants).map(([contourId, grant]) => `${status?.contours?.find(contour => contour.id === contourId)?.name || contourId}: ${{ read: 'чтение', control: 'чтение и команды', manage: 'управление устройствами' }[grant] || grant}`).join('; ')}</dd></dl>
<ResourceList>{app.credentials.map((item) => { <ResourceList>{app.credentials.map((item) => {
const keyOpen = credentialRows.includes(item.client_id); const keyOpen = credentialRows.includes(item.client_id);
const secret = issued?.applicationId === app.id && issued.clientId === item.client_id ? issued : null; const secret = issued?.applicationId === app.id && issued.clientId === item.client_id ? issued : null;
@@ -107,11 +142,13 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
sections={[{ id: 'connection', label: 'Сервер' }, { id: 'contours', label: 'Контуры', disabled: !status?.connected }]} sections={[{ id: 'connection', label: 'Сервер' }, { id: 'contours', label: 'Контуры', disabled: !status?.connected }]}
activeSection={section} onSectionChange={setSection} onClose={onClose} activeSection={section} onSectionChange={setSection} onClose={onClose}
headerActions={<> headerActions={<>
{section === 'contours' && canManage ? <IconButton label="Создать контур VPS" disabled={busy} onClick={() => { setNewContour(true); setContourName(''); setTargetProject(project.projectRef); setContourIntent(null); }}><Icon name="plus" /></IconButton> : null}
{project.access.capabilities.includes('infrastructure.manage') ? <IconButton label={host.lifecycleState === 'suspended' ? 'Восстановить VPS' : 'Перенести VPS в архив'} disabled={busy} onClick={() => setArchiveConfirm(true)}><Icon name={host.lifecycleState === 'suspended' ? 'refresh' : 'trash'} /></IconButton> : null} {project.access.capabilities.includes('infrastructure.manage') ? <IconButton label={host.lifecycleState === 'suspended' ? 'Восстановить VPS' : 'Перенести VPS в архив'} disabled={busy} onClick={() => setArchiveConfirm(true)}><Icon name={host.lifecycleState === 'suspended' ? 'refresh' : 'trash'} /></IconButton> : null}
<IconButton label="Обновить состояние VPS" loading={pending === 'refresh'} disabled={busy} onClick={async () => { <IconButton label="Обновить состояние VPS" loading={pending === 'refresh'} disabled={busy} onClick={async () => {
setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); } setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); }
}}><Icon name="refresh" /></IconButton></>}> }}><Icon name="refresh" /></IconButton></>}>
<div className="b2-settings" aria-busy={busy}> <div className="b2-settings" aria-busy={busy}>
{syncError ? <p role="status">{syncError}</p> : null}
{section === 'connection' ? <> {section === 'connection' ? <>
<ResourceRow title={host.displayName} description={status?.endpoint} metadata="Подключение Device Core к серверу ARNavi" <ResourceRow title={host.displayName} description={status?.endpoint} metadata="Подключение Device Core к серверу ARNavi"
status={<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Доступен' : pending === 'load' ? 'Проверка…' : 'Не подключён'}</StatusBadge>} status={<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Доступен' : pending === 'load' ? 'Проверка…' : 'Не подключён'}</StatusBadge>}
@@ -127,43 +164,60 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
<div className="b2-actions"><Button disabled={busy} onClick={() => { setImportOpen(false); setConnection(''); }}>Отмена</Button><Button loading={pending === 'connect'} disabled={busy || !connection.trim()} onClick={() => void run('connect', { connection })}>{status?.connected ? 'Обновить доступ Device Core' : 'Подключить Device Core'}</Button></div> <div className="b2-actions"><Button disabled={busy} onClick={() => { setImportOpen(false); setConnection(''); }}>Отмена</Button><Button loading={pending === 'connect'} disabled={busy || !connection.trim()} onClick={() => void run('connect', { connection })}>{status?.connected ? 'Обновить доступ Device Core' : 'Подключить Device Core'}</Button></div>
</div></SettingsCard> : null} </div></SettingsCard> : null}
</> : null} </> : null}
{section === 'contours' ? <ResourceList>{projects.map((item) => { {section === 'contours' ? <>
const links = (status?.links || []).filter((link) => link.projectRef === item.projectRef); {newContour ? <SettingsCard title="Новый контур VPS" description="Создаётся на этом VPS и связывается с выбранным проектом Device Core."><div className="b2-settings">
const linked = links.length > 0, open = expanded.includes(item.projectRef); <TextField label="Название контура" value={contourName} disabled={busy || Boolean(contourIntent)} maxLength={160} autoFocus onChange={event => setContourName(event.target.value)} />
const apps = (status?.applications || []).filter((app) => app.authority !== 'host' && links.some((link) => app.grants[link.contourId])); <Select label="Проект Device Core" value={targetProject} disabled={busy || Boolean(contourIntent)} options={projects.filter(item => item.access.capabilities.includes('infrastructure.manage')).map(item => ({ value: item.projectRef, label: item.name }))} onChange={setTargetProject} />
const available = (status?.contours || []).filter((contour) => !status?.links?.some((link) => link.contourId === contour.id)); <div className="b2-actions"><Button disabled={busy} onClick={() => { setNewContour(false); setContourIntent(null); }}>Отмена</Button><Button disabled={busy || !contourName.trim() || !targetProject} loading={pending === 'contour-connect'} onClick={() => {
return <li key={item.projectRef} className="b2-disclosure"> const intent = contourIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: contourName.trim(), projectRef: targetProject };
<ResourceRow title={item.name} metadata={linked ? 'Контур VPS связан с проектом' : 'Проект Device Core'} setContourIntent(intent); void run('contour-connect', { name: intent.name, targetProjectRef: intent.projectRef }, intent.id);
actions={<> }}>{contourIntent ? 'Уточнить создание' : 'Создать контур'}</Button></div>
{open && linked && canManage ? <IconButton label={`Добавить приложение в ${item.name}`} disabled={busy} onClick={() => { setCreating(item.projectRef); setName(''); setCreationIntent(null); }}><Icon name="plus" /></IconButton> : null} </div></SettingsCard> : null}
<IconButton label={`Контур ${item.name}`} aria-expanded={open} aria-controls={`contour-${item.projectRef}`} onClick={() => setExpanded(toggle(expanded, item.projectRef))}><Icon name={open ? 'chevron-up' : 'chevron-down'} /></IconButton> {!status?.contours?.length && !busy ? <p>На VPS ещё нет контуров. Создайте первый кнопкой «+» в шапке настроек.</p> : null}
<ResourceList>{(status?.contours || []).map(contour => {
const links = (status?.links || []).filter(link => link.contourId === contour.id);
const open = expanded.includes(contour.id);
const apps = (status?.applications || []).filter(app => app.authority !== 'host' && app.grants[contour.id]);
const available = projects.filter(item => item.access.capabilities.includes('infrastructure.manage') && !links.some(link => link.projectRef === item.projectRef));
const projectNames = links.map(link => projects.find(item => item.projectRef === link.projectRef)?.name || 'Недоступный проект');
return <li key={contour.id} className="b2-disclosure">
<ResourceRow title={contour.name} metadata={links.length ? `Проекты: ${projectNames.join(', ')}` : 'Не связан с проектами Device Core'} actions={<>
{open && canManage ? <IconButton label={`Добавить приложение в ${contour.name}`} disabled={busy} onClick={() => { setCreating(contour.id); setName(''); setAccess('read'); setCreationIntent(null); }}><Icon name="plus" /></IconButton> : null}
<IconButton label={`Контур ${contour.name}`} aria-expanded={open} aria-controls={`contour-${contour.id}`} onClick={() => setExpanded(toggle(expanded, contour.id))}><Icon name={open ? 'chevron-up' : 'chevron-down'} /></IconButton>
</>} /> </>} />
{open ? <div id={`contour-${item.projectRef}`} className="b2-disclosure__body"> {open ? <div id={`contour-${contour.id}`} className="b2-disclosure__body">
{!linked ? <> <div className="b2-section-heading"><strong>Проекты Device Core</strong></div>
{canManage ? <Button disabled={busy} loading={pending === 'project-connect'} onClick={() => void run('project-connect', { targetProjectRef: item.projectRef })}>Подключить проект к VPS</Button> : null} <p>Связанные проекты видят один реестр устройств этого контура. Ключи внешних приложений управляются отдельно.</p>
{available.length ? <Select label="Связать с существующим контуром" value="" options={[{ value: '', label: 'Выбрать контур VPS' }, ...available.map((c) => ({ value: c.id, label: c.name }))]} onChange={(contourId) => { if (contourId) void run('link', { contourId, targetProjectRef: item.projectRef }); }} disabled={busy} /> : null} {links.length ? <ResourceList>{links.map(link => {
</> : <> const item = projects.find(value => value.projectRef === link.projectRef);
return <li key={link.projectRef}><ResourceRow title={item?.name || 'Недоступный проект'} actions={item?.access.capabilities.includes('infrastructure.manage') ? <IconButton label={`Отвязать проект ${item.name}`} disabled={busy} onClick={() => setConfirm({ action: 'unlink', fields: { contourId: contour.id, targetProjectRef: link.projectRef }, text: `Отвязать «${item.name}» от «${contour.name}»? Устройства перестанут отображаться в этом проекте. Контур, устройства и ключи внешних приложений сохранятся.` })}><Icon name="trash" /></IconButton> : undefined} /></li>;
})}</ResourceList> : null}
{available.length ? <Select label="Подключить проект к контуру" value="" disabled={busy || (links.length > 0 && !status?.sharedProjects)} options={[{ value: '', label: 'Выбрать проект Device Core' }, ...available.map(item => ({ value: item.projectRef, label: item.name }))]} onChange={projectRef => {
if (projectRef) setConfirm({ action: 'link', fields: { contourId: contour.id, targetProjectRef: projectRef }, text: `Подключить «${projects.find(item => item.projectRef === projectRef)?.name}» к «${contour.name}»? Участники проекта получат доступ к устройствам контура в пределах своих прав проекта.` });
}} /> : null}
{links.length > 0 && available.length > 0 && !status?.sharedProjects ? <p>Для подключения второго проекта нужна миграция общих контуров на сервере Device Core.</p> : null}
<div className="b2-section-heading"><strong>Приложения и ключи</strong></div> <div className="b2-section-heading"><strong>Приложения и ключи</strong></div>
<ResourceList>{apps.map(applicationRow)}</ResourceList> <ResourceList>{apps.map(applicationRow)}</ResourceList>
{!apps.length && creating !== item.projectRef ? <p>Ключи приложений ещё не выданы</p> : null} {!apps.length && creating !== contour.id ? <p>Ключи приложений ещё не выданы</p> : null}
{creating === item.projectRef ? <div className="b2-settings"> {creating === contour.id ? <div className="b2-settings">
<TextField label="Название приложения" autoFocus value={name} disabled={busy || Boolean(creationIntent)} maxLength={160} onChange={(event) => setName(event.target.value)} /> <TextField label="Название приложения" autoFocus value={name} disabled={busy || Boolean(creationIntent)} maxLength={160} onChange={event => setName(event.target.value)} />
<Select label="Доступ приложения" value={access} disabled={busy || Boolean(creationIntent)} options={[{ value: 'read', label: 'Чтение устройств и данных' }, { value: 'control', label: 'Чтение и команды' }, { value: 'manage', label: 'Управление устройствами контура' }]} onChange={setAccess} />
<div className="b2-actions"><Button disabled={busy} onClick={() => { setCreating(''); setCreationIntent(null); }}>Отмена</Button><Button loading={pending === 'application-connect'} disabled={busy || !name.trim()} onClick={() => { <div className="b2-actions"><Button disabled={busy} onClick={() => { setCreating(''); setCreationIntent(null); }}>Отмена</Button><Button loading={pending === 'application-connect'} disabled={busy || !name.trim()} onClick={() => {
const intent = creationIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: name.trim() }; const intent = creationIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: name.trim(), access };
setCreationIntent(intent); setCreationIntent(intent);
void run('application-connect', { name: intent.name, contourId: links[0].contourId }, intent.id); void run('application-connect', { name: intent.name, contourId: contour.id, access: intent.access }, intent.id);
}}>{creationIntent ? 'Уточнить создание' : 'Создать ключ'}</Button></div> }}>{creationIntent ? 'Уточнить создание' : 'Создать ключ'}</Button></div>
</div> : null} </div> : null}
</>} </div> : null}
</div> : null} </li>;
</li>; })}</ResourceList>
})}</ResourceList> : null} </> : null}
</div> </div>
</FeatureSettingsWindow> </FeatureSettingsWindow>
<ConfirmationModal open={archiveConfirm} title={host.lifecycleState === 'suspended' ? 'Восстановить VPS?' : 'Перенести VPS в архив?'} description={`${host.displayName}. Изменится только запись в этом проекте. Сервер, устройства и подключения других проектов сохранятся.`} confirmLabel={host.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'} cancelLabel="Отмена" onClose={() => setArchiveConfirm(false)} onConfirm={async () => { <ConfirmationModal open={archiveConfirm} title={host.lifecycleState === 'suspended' ? 'Восстановить VPS?' : 'Перенести VPS в архив?'} description={`${host.displayName}. Изменится только запись в этом проекте. Сервер, устройства и подключения других проектов сохранятся.`} confirmLabel={host.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'} cancelLabel="Отмена" onClose={() => setArchiveConfirm(false)} onConfirm={async () => {
if (busy) return; setPending('archive'); if (busy) return; setPending('archive');
try { await archiveHost(project.projectRef, host.hostRef, host.lifecycleState !== 'suspended'); setArchiveConfirm(false); await onChanged(); onClose(); } catch (error) { onError(error); } finally { setPending(''); } try { await archiveHost(project.projectRef, host.hostRef, host.lifecycleState !== 'suspended'); setArchiveConfirm(false); await onChanged(); onClose(); } catch (error) { onError(error); } finally { setPending(''); }
}} /> }} />
<ConfirmationModal open={Boolean(confirm)} title={confirm?.action === 'application-delete' ? 'Удалить приложение' : 'Ключ приложения'} description={confirm?.text} confirmLabel={confirm?.action === 'application-delete' ? 'Удалить приложение' : 'Подтвердить'} cancelLabel="Отмена" onClose={() => setConfirm(null)} onConfirm={async () => { if (confirm && !busy && await run(confirm.action, confirm.fields)) setConfirm(null); }} /> <ConfirmationModal open={Boolean(confirm)} title={confirm?.action === 'application-delete' ? 'Удалить приложение' : ['link', 'unlink'].includes(confirm?.action || '') ? 'Связь проекта и контура' : 'Ключ приложения'} description={confirm?.text} confirmLabel={confirm?.action === 'application-delete' ? 'Удалить приложение' : 'Подтвердить'} cancelLabel="Отмена" onClose={() => setConfirm(null)} onConfirm={async () => { if (confirm && !busy && await run(confirm.action, confirm.fields)) setConfirm(null); }} />
</>; </>;
} }
+2 -1
View File
@@ -2,6 +2,7 @@ export type B2Contour = { id: string; key: string; name: string; access?: string
export type B2Application = { id: string; key: string; name: string; authority: 'host' | 'contours'; export type B2Application = { id: string; key: string; name: string; authority: 'host' | 'contours';
grants: Record<string, string>; credentials: Array<{ client_id: string; enabled: boolean }> }; grants: Record<string, string>; credentials: Array<{ client_id: string; enabled: boolean }> };
export type B2Status = { connected: boolean; endpoint?: string; authority?: 'host' | 'contours'; export type B2Status = { connected: boolean; endpoint?: string; authority?: 'host' | 'contours';
sharedProjects?: boolean;
contours?: B2Contour[]; applications?: B2Application[]; contours?: B2Contour[]; applications?: B2Application[];
links?: Array<{ contourId: string; projectRef: string }> }; links?: Array<{ contourId: string; projectRef: string }> };
export type B2Device = { id: string; identifier: { masked: string }; name: string; active: boolean; number: number; contourId: string }; export type B2Device = { id: string; identifier: { masked: string }; name: string; active: boolean; number: number; contourId: string };
@@ -18,7 +19,7 @@ const messages: Record<string, string> = {
b2_access_denied: 'Ключ отозван или не даёт доступа к этому действию.', b2_access_denied: 'Ключ отозван или не даёт доступа к этому действию.',
b2_key_rejected: 'VPS не принял ключ подключения.', b2_key_rejected: 'VPS не принял ключ подключения.',
b2_conflict: 'На VPS уже есть запись с такими данными. Обновите список и проверьте результат.', b2_conflict: 'На VPS уже есть запись с такими данными. Обновите список и проверьте результат.',
b2_contour_already_linked: 'Этот контур уже связан с другим проектом.', b2_shared_projects_migration_required: 'На сервере Device Core ещё не установлена миграция общих контуров. До её установки контур можно связать только с одним проектом.',
b2_connection_identity_conflict: 'Этот хост уже подключён другим приложением или ключом сервера.', b2_connection_identity_conflict: 'Этот хост уже подключён другим приложением или ключом сервера.',
b2_certificate_mismatch: 'Сертификат VPS не соответствует ключу подключения.', b2_certificate_mismatch: 'Сертификат VPS не соответствует ключу подключения.',
b2_private_storage_unavailable: 'Закрытое хранилище ключей ещё не настроено на Device Core.', b2_private_storage_unavailable: 'Закрытое хранилище ключей ещё не настроено на Device Core.',
@@ -1,10 +1,10 @@
{ {
"version": "0.2.4", "version": "0.2.5",
"filename": "nodedc-arnavi-vps-0.2.4.pyz", "filename": "nodedc-arnavi-vps-0.2.5.pyz",
"sha256": "242b6e04f8d38711aa707da67e96f0a2374cbb25b7e79934a58367a34e9a20e6", "sha256": "d9a822ca7c2498841a6fd13fddac27da4fc22366931ba8980b97c66c159a383f",
"bytes": 16129185, "bytes": 16129246,
"sourceRepository": "https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS.git", "sourceRepository": "https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS.git",
"sourceCommit": "881f68dbad9f8fdde2f0f4693de549cff45cacfa", "sourceCommit": "193253dd48a1c6390ea4c5e500693123b88ce2ea",
"manifestSha256": "f23e6cf7048ce5e8d17720933a13c3bef5ee9b523c194b4f07f874f372a25484", "manifestSha256": "139a3c1d7f3e8266e2154586783133078311aa9dae76d74ed229aab16f816197",
"environment": "ubuntu-24.04-amd64" "environment": "ubuntu-24.04-amd64"
} }
@@ -0,0 +1,13 @@
{
"schemaVersion": "nodedc.device-b2-shared-contours.v1",
"releaseId": "device-b2-shared-contours-v1-20261001-001",
"baselineReleaseId": "device-core-release-v1-r37-1b3001dfa12598af28882232336d837514502718",
"baselineSha256": "fca735b4177ba5397e2af31520682aeb17670a8d38a19176be2c08f07f37dffe",
"files": {
"deployment/device-b2-shared-contours-v1.sql": "caff93f717bbd61ebaf8ffec0b9b2ad04885da22c4e332c1a4586e149faab57a",
"deployment/device-b2-shared-contours-v1.rollback.sql": "f862da8316695d162167bd1fa854edcbf10d82f57462e3021cf199e72ef16b4f"
},
"transition": "one-contour-many-projects",
"services": [],
"rollback": "refuse-multiple-projects;preserve-all-rows"
}
@@ -0,0 +1,20 @@
begin;
set local lock_timeout = '5s';
set local statement_timeout = '30s';
lock table device_b2_contour_links in access exclusive mode;
do $$
begin
if obj_description('device_b2_contour_links'::regclass) is distinct from 'nodedc.device-b2-shared-contours/v1'
or (select pg_get_constraintdef(oid) from pg_constraint
where conrelid='device_b2_contour_links'::regclass and contype='p')
is distinct from 'PRIMARY KEY (source_id, contour_id, project_id)' then
raise exception 'device_b2_shared_contours_rollback_predecessor_mismatch';
end if;
if exists(select 1 from device_b2_contour_links group by source_id,contour_id having count(*)>1) then
raise exception 'device_b2_shared_contours_rollback_would_lose_links';
end if;
end $$;
alter table device_b2_contour_links drop constraint device_b2_contour_links_pkey;
alter table device_b2_contour_links add primary key (source_id, contour_id);
comment on table device_b2_contour_links is 'nodedc.device-b2-foundation/v1';
commit;
@@ -0,0 +1,32 @@
begin;
set local lock_timeout = '5s';
set local statement_timeout = '30s';
-- Separate, versioned foundation transition. Never run from application startup.
-- Preserve every assignment; only the identity of an assignment becomes a triple.
lock table device_b2_contour_links in access exclusive mode;
create temporary table device_b2_links_before on commit drop as
select * from device_b2_contour_links;
do $$
begin
if obj_description('device_b2_contour_links'::regclass) is distinct from 'nodedc.device-b2-foundation/v1'
or (select pg_get_constraintdef(oid) from pg_constraint
where conrelid='device_b2_contour_links'::regclass and contype='p')
is distinct from 'PRIMARY KEY (source_id, contour_id)' then
raise exception 'device_b2_shared_contours_predecessor_mismatch';
end if;
end $$;
alter table device_b2_contour_links drop constraint device_b2_contour_links_pkey;
alter table device_b2_contour_links add primary key (source_id, contour_id, project_id);
comment on table device_b2_contour_links is 'nodedc.device-b2-shared-contours/v1';
do $$
begin
if exists(
(select * from device_b2_links_before except all select * from device_b2_contour_links)
union all
(select * from device_b2_contour_links except all select * from device_b2_links_before)
) then
raise exception 'device_b2_shared_contours_row_preservation_failed';
end if;
end $$;
commit;
+171
View File
@@ -0,0 +1,171 @@
# Device Core B2 user flow investigation
Date: 2026-10-01. Qualification of local sources, not a production release.
## Scope and conclusion
The requested flow is feasible after the local changes and the separately qualified
shared-contour schema transition: create a project, import a fresh VPS administrator
package, create a contour, issue independent application packages, register devices,
discover externally created contours, and bind multiple same-company projects to one
contour. Twenty bounded cross-system scenarios passed.
Two remaining delivery boundaries prevent describing the existing production product
as fully qualified from an empty Ubuntu machine to Mission Core:
1. The existing root deployment runner pins the B2 foundation schema. The new SQL
transition and rollback are local qualification inputs, **not registered deployment
artifacts**. A separate canonical runner extension, migration registration,
acceptance update and reviewed release are required. Never execute these SQL files
manually against production or from application startup.
2. Current Mission Core accepts the legacy MCV1 pairing format, not the new API v2
application JSON. The simulated external client exercises API v2; it does not prove
an existing Robot2B or Mission Core interface can import that file.
No production projects, contours, keys, devices, database migrations, VPS upgrades or
physical tracker commands were created or executed during this investigation.
## Findings and local corrections
- Settings previously rendered projects as contours and omitted unlinked external
VPS contours. They now render the authoritative VPS catalogue, display project
associations explicitly, and refresh every 30 seconds while the visible settings
window is open. A failed refresh identifies the displayed data as stale.
- A new contour can be created with a name and a selected Device Core project.
A stable request identity recovers uncertain responses without another contour.
- The old primary key `(source_id, contour_id)` and backend conflict rule prohibited
a second project. The separate forward transition uses
`(source_id, contour_id, project_id)` and preserves existing rows and foreign keys.
The old schema remains supported with an explicit migration-required error.
- Existing contours can be attached to another authorized project of the same owner
scope. A missing host view is created for that project. Unlink deletes only the
selected relationship. Cross-company assignment remains forbidden.
- Application creation selects the actual contour, no longer the first project link.
The UI offers read, control and manage, with read selected by default. An application
created before a lost key response is found by its stable identity; the UI directs
the operator to issue a replacement instead of pretending the secret is replayable.
- VPS v2 catalogue requests now reject a revoked domain client even if OAuth
introspection still accepts a cached access token. Previously the contour catalogue
could appear healthy but empty; protected fleet operations already denied access.
- Project creation calls the owning company/personal space “Владелец проекта”.
Device enrollment states that a stored profile still needs to be sent to hardware.
## Object and permission boundaries
A VPS contour is the device namespace on the server. A Device Core project is a local
workspace with its own members and capabilities. A v2 application is an independently
identified external consumer with contour grants and its own credentials/cursors.
External contours should appear in the administrative catalogue automatically, but
must not create Device Core projects, memberships or data grants automatically. Root
CLI or host-administrator credentials can create contours. An application's `manage`
grant manages devices inside its contour and does not confer VPS administration.
Multiple projects may share one contour after migration. They see the same device
identity, not copies. Project-local unlink/archive must not revoke external application
credentials or alter other projects. External applications can share a contour with
separate read/control/manage grants and independent event acknowledgments.
## Reproducible bounded qualification
From the Device Core repository:
```sh
node scripts/qualify-b2-user-flow.mjs \
/private/tmp/ndc-b2-sql-check/node_modules/@electric-sql/pglite/dist/index.js \
../NODEDC_MISSION_CORE_ARNAVI-VPS \
../outputs/device-flow-investigation-20261001/flow-report.json
```
PGlite 0.5.8 is an explicitly supplied test dependency outside the production
workspace. The VPS repository path is a qualification input, not a production
dependency. The script uses the existing VPS `.venv/bin/python3`.
Real components: PostgreSQL WASM SQL engine and all 17 Device Core migrations,
management repository, B2Infrastructure, private file vault, OAuth client library,
VPS SQLite Store, SharedAPI, management domain and CLI parser.
Simulated boundaries: OAuth provider, TLS network transport, root privilege and
hardware. No sockets are opened by the cross-system fixture. Three projects, three
external contours and two synthetic devices bound the scenario. Temporary database
and credential state is cleaned up; no exported secrets are written to the report.
The 20 cases include uncertain retries, old-schema rejection, migration preservation,
two-project visibility, unrelated-project denial, external CLI discovery, independent
applications and cursors, key rotation, lost issuance response, app deletion,
cross-company denial, project unlink, restart persistence, audit redaction, rollback
refusal when it would lose links, and lossless rollback/reapplication.
## Validation evidence
Evidence directory: `../outputs/device-flow-investigation-20261001/`.
- `flow-report.json`: 20/20 cross-system checks pass.
- `device-tests.log`: 303/303 Device Core tests pass.
- `vps-tests.log`: 317 VPS tests pass; one temporary loopback socket test is blocked
by the sandbox. `vps-network-check.log` confirms that test and the three new
revocation cases pass on the permitted rerun. All 318 cases are accounted for.
- Final TypeScript/Vite build passes. Node syntax check and `git diff --check` pass.
- Ruff passes on the modified VPS module and its new revocation tests.
- `ui-checks.txt`, `ui-contours.png`: real changed React settings component tested
in an isolated page with synthetic fetch responses. External discovery, shared
project labels, explicit linking, grant selection, nested key output, contour
creation and close behavior pass. This is not a production browser smoke test.
Base revisions before local changes:
- Device Core: `1b3001dfa12598af28882232336d837514502718`
- VPS: `5ff082144eb0d2b8ccb46d1d08ead6b52f1d2021`
- Mission Core, read only: `a78fdeae66287fa51f2888440d0f5abc0e70364b`
## Release and remaining acceptance
1. Register the new foundation transition and exact post-migration schema in the
canonical deployment runner; include plan/apply, backup, rollback and acceptance.
2. Release Device Core changes. Rebuild/version the VPS installer for the API
revocation fix; the currently advertised 0.2.4 installer does not contain it.
3. On an isolated Ubuntu Server 24.04 x86-64 host, qualify the actual installer,
OAuth service, certificate pinning, restart and uninstall/restore boundaries.
4. Repeat the browser flow against those released services and test an API v2
consumer. Keep legacy Mission Core MCV1 pairing until its v2 consumer is implemented.
The reverse schema transition deliberately refuses execution while a contour has
multiple project links. Do not delete assignments automatically to force rollback.
The private credential vault retains immutable historical files; cleanup of orphaned
or superseded secret files was not implemented in this investigation.
## Release preparation and partial activation, 2026-10-01
The shared-contour transition now has a fixed three-file descriptor, deterministic
builder, bounded SQL locks, transaction-local row-preservation proof, private table
backup, exact runtime/source acceptance and lossless automatic rollback in the
canonical Platform runner. It remains a separate administrative deployment; the
application does not migrate this schema at startup. The reverse transition refuses
to remove a second project binding. A table marker without its verified applied
archive is insufficient for subsequent application releases.
Runner source: Platform `27c1552`. Candidate 019 SHA-256:
`048b77d0ce97c2179f89bb1c64d4d9915525dfa5b1e71a63fae15450205efeb3`.
DCPLATFORM-21 design record: `c8f94c6a-7b57-4ae1-9463-425c5da5f3c6`.
At this checkpoint the Synology promotion/migration and Device Core UI release are
pending. Live r37 still has the old UI. Do not present the new UI as deployed.
The independent revocation fix is activated on ARNavi VPS **0.2.5**, source
`193253dd48a1c6390ea4c5e500693123b88ce2ea`, installer manifest
`139a3c1d7f3e8266e2154586783133078311aa9dae76d74ed229aab16f816197`.
The versioned installer returned healthy; read-only before/after proofs preserve
host, TLS, owner, devices, contours, applications and credentials. Packet count
advanced 5478→5482. The active legacy Mission Core consumer was updated for the
0.2.5 contract (`9761474`) through its canonical LaunchAgent; health accepted,
VPS state paired, version 0.2.5 and last_error null. No real device command or
production key mutation was used for acceptance.
New evidence directory: `../outputs/device-flow-release-20261001/`.
20/20 cross-system checks, 303/303 Device Core tests, 318/318 VPS tests, 75/75
Mission Core compatibility tests and production UI build pass. Platform regression
suite passed 173 cases; two additional backup/acceptance cases then passed in the
13-case focused shared-contour suite. Device artifact run reported 170 cases:
153 passed and 17 environment skips, plus one sandbox-blocked health fixture;
all four health fixture tests pass on the permitted local-listener rerun. New installer metadata
and SHA checks pass. This checkpoint does not add Mission Core API v2 import or
claim a clean Ubuntu installation/scale test.
+1 -1
View File
@@ -13,7 +13,7 @@
}, },
"platform": { "platform": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_PLATFORM.git", "url": "https://git.dcserve.ru/SILVER/NODEDC_PLATFORM.git",
"commit": "39a2239563de686d8a854627cae15339f1f2a4d9" "commit": "27c155276a703dd4fd39385011fc5e3f86afcae4"
} }
} }
} }
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""Deterministic data-only, exact shared-contour schema transition."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import tarfile
ROOT = Path(__file__).resolve().parents[2]
IDENTITY = 'device-b2-shared-contours-v1-20261001-001'
COMPONENT = 'device-b2-shared-contours'
DESCRIPTOR = 'deployment/device-b2-shared-contours-v1.json'
SQL = 'deployment/device-b2-shared-contours-v1.sql'
REVERSE = 'deployment/device-b2-shared-contours-v1.rollback.sql'
ENTRIES = (DESCRIPTOR, SQL, REVERSE)
HASHES = {
SQL: 'caff93f717bbd61ebaf8ffec0b9b2ad04885da22c4e332c1a4586e149faab57a',
REVERSE: 'f862da8316695d162167bd1fa854edcbf10d82f57462e3021cf199e72ef16b4f',
}
EXPECTED = {
'schemaVersion': 'nodedc.device-b2-shared-contours.v1', 'releaseId': IDENTITY,
'baselineReleaseId': 'device-core-release-v1-r37-1b3001dfa12598af28882232336d837514502718',
'baselineSha256': 'fca735b4177ba5397e2af31520682aeb17670a8d38a19176be2c08f07f37dffe',
'files': HASHES, 'transition': 'one-contour-many-projects', 'services': [],
'rollback': 'refuse-multiple-projects;preserve-all-rows',
}
def build(destination):
if any((ROOT / p).is_symlink() or not (ROOT / p).is_file() for p in ENTRIES):
raise ValueError('missing or unsafe transition source')
files = {p: (ROOT / p).read_bytes() for p in ENTRIES}
if json.loads(files[DESCRIPTOR]) != EXPECTED:
raise ValueError('shared contours descriptor mismatch')
if any(hashlib.sha256(files[p]).hexdigest() != sha for p, sha in HASHES.items()):
raise ValueError('shared contours SQL digest mismatch')
payload = {
'manifest.env': f'id={IDENTITY}\ncomponent={COMPONENT}\ntype=app-overlay\n'.encode(),
'files.txt': ('\n'.join(ENTRIES) + '\n').encode(),
**{'payload/' + p: value for p, value in files.items()},
}
destination = Path(destination)
destination.parent.mkdir(parents=True, exist_ok=True)
with destination.open('xb') as output:
with gzip.GzipFile(filename='', mode='wb', fileobj=output, mtime=0) as gz:
with tarfile.open(fileobj=gz, mode='w', format=tarfile.PAX_FORMAT) as archive:
for name, data in sorted(payload.items()):
member = tarfile.TarInfo(name)
member.size, member.mode, member.mtime = len(data), 0o644, 0
archive.addfile(member, io.BytesIO(data))
return {'component': COMPONENT, 'id': IDENTITY, 'artifact': str(destination),
'sha256': hashlib.sha256(destination.read_bytes()).hexdigest(), 'entries': ENTRIES,
'services': [], 'build': [], 'newPorts': False}
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--output', required=True)
print(json.dumps(build(parser.parse_args().output), indent=2))
@@ -0,0 +1,44 @@
import importlib.util
import json
from pathlib import Path
import shutil
import tarfile
import tempfile
import unittest
from unittest import mock
spec = importlib.util.spec_from_file_location('shared_builder', Path(__file__).with_name('build_device_b2_shared_contours.py'))
B = importlib.util.module_from_spec(spec)
spec.loader.exec_module(B)
class SharedContoursArtifact(unittest.TestCase):
def test_deterministic_data_only_exact_payload_no_overwrite(self):
with tempfile.TemporaryDirectory() as tmp:
first, second = Path(tmp)/'a.tgz', Path(tmp)/'b.tgz'
B.build(first); B.build(second)
self.assertEqual(first.read_bytes(), second.read_bytes())
with self.assertRaises(FileExistsError): B.build(first)
with tarfile.open(first) as archive:
self.assertEqual(set(archive.getnames()), {'manifest.env', 'files.txt', *('payload/'+p for p in B.ENTRIES)})
self.assertTrue(all(m.isfile() and m.mode == 0o644 for m in archive))
self.assertEqual(archive.extractfile('files.txt').read().decode().splitlines(), list(B.ENTRIES))
def test_mutated_forward_reverse_descriptor_and_symlink_rejected(self):
for name in B.ENTRIES:
for mode in ('changed', 'symlink'):
with self.subTest(name=name, mode=mode), tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)/'source'; (root/'deployment').mkdir(parents=True)
for p in B.ENTRIES: shutil.copyfile(B.ROOT/p, root/p)
if mode == 'symlink':
(root/name).unlink(); (root/name).symlink_to(B.ROOT/name)
elif name == B.DESCRIPTOR:
d = json.loads((root/name).read_text()); d['services'] = ['device-postgres']
(root/name).write_text(json.dumps(d))
else: (root/name).write_text('drop table device_b2_hosts;')
target = Path(tmp)/'bad.tgz'
with mock.patch.object(B, 'ROOT', root), self.assertRaises(ValueError): B.build(target)
self.assertFalse(target.exists())
if __name__ == '__main__': unittest.main()
+109
View File
@@ -0,0 +1,109 @@
"""Isolated domain bridge for qualification, never a deployed server.
Actual VPS SQLite, SharedAPI, CLI and permission code. OAuth provider and root
privilege are simulated; no network socket, production state or hardware.
Pass the independently checked-out VPS repository as argv[1].
"""
import base64
import contextlib
import io
import json
import sys
import tempfile
import uuid
from pathlib import Path
from unittest.mock import patch
from urllib.parse import urlsplit, unquote_plus
sys.path.insert(0, str(Path(sys.argv[1]).resolve() / "server"))
from ndc_vps import admin
from ndc_vps.access_admin import provision
from ndc_vps.contours import Conflict
from ndc_vps.host_management import HostManagement, bootstrap
from ndc_vps.service import Service
from ndc_vps.shared_api import SharedAPI
from ndc_vps.store import Store
class Provider:
def __init__(self):
self.clients, self.tokens = {}, {}
def create(self, client, *_):
secret = "synthetic-" + uuid.uuid4().hex
self.clients[client] = secret
return secret
def token(self, authorization):
client, secret = base64.b64decode(authorization.removeprefix("Basic ")).decode().split(":", 1)
client, secret = unquote_plus(client), unquote_plus(secret)
if self.clients.get(client) != secret:
raise ValueError(f"synthetic credential mismatch known={client in self.clients} secret_length={len(secret)}")
token = "synthetic-" + uuid.uuid4().hex
self.tokens[token] = client
return dict(access_token=token, token_type="Bearer", expires_in=300)
def authenticate(self, token):
if token not in self.tokens:
raise PermissionError
return self.tokens[token]
with tempfile.TemporaryDirectory(prefix="b2-flow-vps-") as temporary:
root = Path(temporary)
state = root / "state"
state.mkdir(mode=0o700)
exports = root / "exports"
exports.mkdir(mode=0o700)
(state / "host.json").write_text(json.dumps(dict(
host_id="vps_synthetic_flow", fingerprint="a" * 64,
endpoint="https://vps.example.invalid:19443", api_port=19443,
tracker=dict(host="vps.example.invalid", port=9922))))
store = Store(state)
store.contours.enable_fresh()
with store.db(write=True) as db:
db.execute("INSERT INTO state VALUES('b2_authority_v1',?)", (json.dumps(dict(admin_port=4445, public_port=4444)),))
provider = Provider()
administrator = bootstrap(store, "device-core-admin", "Device Core")
package = provision(store, provider, administrator, issuer=store.config["endpoint"])
service = Service(store)
api = SharedAPI(service, provider, HostManagement(store, provider))
for line in sys.stdin:
request = json.loads(line)
try:
kind = request["kind"]
if kind == "bootstrap":
result = package
elif kind == "http":
route = urlsplit(request["url"])
headers = request.get("headers", {})
if route.path == "/oauth2/token":
result = provider.token(headers["authorization"])
else:
result = api.dispatch(request["method"], route, request.get("body"), headers.get("authorization", "").removeprefix("Bearer "))
elif kind == "cli":
output = io.StringIO()
# Exercise the real parser and domain calls, with local root simulated.
args = ["--state", str(state), *request["args"]]
if request["args"][0] == "key-issue":
args += ["--output", str(exports / (uuid.uuid4().hex + ".json"))]
with patch.object(admin.os, "geteuid", return_value=0), patch.object(admin, "HydraAdmin", return_value=provider), contextlib.redirect_stdout(output):
admin.main(args)
result = json.loads(output.getvalue())
if "saved" in result:
result = json.loads(Path(result["saved"]).read_text())
elif kind == "append":
result = store.append(request["imei"], b"synthetic", [])
elif kind == "restart":
store = Store(state)
service = Service(store)
api = SharedAPI(service, provider, HostManagement(store, provider))
result = dict(ok=True)
else:
raise ValueError("fixture request")
response = dict(ok=True, result=result)
except (PermissionError, Conflict, ValueError) as error:
response = dict(ok=False, status=403 if isinstance(error, PermissionError) else 409 if isinstance(error, Conflict) else 400, error=type(error).__name__)
except Exception as error:
response = dict(ok=False, status=500, error=type(error).__name__, detail=str(error))
print(json.dumps(response), flush=True)
+244
View File
@@ -0,0 +1,244 @@
// Bounded cross-repository qualification on private temporary data, no sockets.
// node scripts/qualify-b2-user-flow.mjs <pglite-index.js> <VPS-repository> <report.json>
// PostgreSQL WASM + real Device Core repository + real VPS SQLite/API/CLI.
// OAuth provider, TLS transport, root privilege and hardware are simulated.
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { createInterface } from 'node:readline';
import { readFile, readdir, writeFile, mkdtemp, rm } from 'node:fs/promises';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { resolve, join } from 'node:path';
import { tmpdir } from 'node:os';
import { randomUUID, createHash } from 'node:crypto';
import { PostgresDeviceRepository } from '../services/device-control-core/src/postgres-repository.mjs';
import { normalizeManagementCommand } from '../services/device-control-core/src/project-management.mjs';
import { B2Infrastructure } from '../services/device-control-core/src/b2/infrastructure.mjs';
import { B2Secrets } from '../services/device-control-core/src/b2/vault.mjs';
import { createB2Client } from '../services/device-control-core/src/b2/connection.mjs';
const root = fileURLToPath(new URL('../', import.meta.url));
const vps = resolve(process.argv[3]);
const { PGlite } = await import(pathToFileURL(resolve(process.argv[2])));
const db = new PGlite();
const child = spawn(join(vps, '.venv/bin/python3'), [join(root, 'scripts/b2-flow-vps-fixture.py'), vps], { stdio: ['pipe', 'pipe', 'pipe'] });
const waiting = [];
let childError = '';
child.stderr.on('data', data => { childError += data; });
createInterface({ input: child.stdout }).on('line', line => waiting.shift()?.resolve(JSON.parse(line)));
child.on('exit', code => { for (const item of waiting.splice(0)) item.reject(Error(`VPS fixture exited ${code}: ${childError}`)); });
const bridge = body => new Promise((resolve, reject) => { waiting.push({ resolve, reject }); child.stdin.write(JSON.stringify(body) + '\n'); });
async function command(body) {
const result = await bridge(body);
assert.equal(result.ok, true, JSON.stringify({ status: result.status, error: result.error, detail: result.detail }));
return result.result;
}
const secretsRoot = await mkdtemp(join(tmpdir(), 'b2-flow-secrets-'));
const checks = [];
async function check(name, action) { await action(); checks.push({ name, result: 'pass' }); console.log('PASS ' + name); }
const pool = { connect: async () => ({ query: (...args) => db.query(...args), release() {} }), query: (...args) => db.query(...args), end: async () => {} };
const repository = new PostgresDeviceRepository({ pool });
const owner = { scopeKind: 'company', ownerRef: 'company:flow-fixture' };
const actor = { userRef: 'user:flow-owner', hubRole: 'owner', groupRefs: [], ownerScopes: [owner] };
const clientFactory = pkg => createB2Client(pkg, { fetchImpl: async (url, init) => {
const headers = Object.fromEntries(new Headers(init.headers));
const body = String(url).includes('/oauth2/token') ? null : init.body ? JSON.parse(init.body) : null;
const response = await bridge({ kind: 'http', url: String(url), method: init.method || 'GET', headers, body });
return new Response(JSON.stringify(response.ok ? response.result : { error: response.error }), {
status: response.ok ? 200 : response.status, headers: { 'content-type': 'application/json' },
});
} });
const service = new B2Infrastructure({ pool, secrets: new B2Secrets(secretsRoot), clientFactory });
const requestId = () => randomUUID().replaceAll('-', '');
async function management(commandKind, input, as = actor) {
const command = normalizeManagementCommand(commandKind, input);
return (await repository.executeManagementCommand({ actor: as, commandKind, command,
idempotencyKey: requestId(), requestDigest: 'sha256:' + createHash('sha256').update(JSON.stringify(command)).digest('hex') })).result;
}
const execute = (common, action, fields = {}, id = requestId(), as = actor) => service.execute(as, { ...common, action, ...fields }, id);
const cli = args => command({ kind: 'cli', args });
let projectA, projectB, projectC, host, contour, pkg, appA, appB, appClientA, appClientB, device;
let common, second, third;
try {
await check('fresh schema and project creation use the real management repository', async () => {
for (const name of (await readdir(join(root, 'services/device-control-core/migrations'))).filter(name => name.endsWith('.sql')).sort()) {
await db.exec(await readFile(join(root, 'services/device-control-core/migrations', name), 'utf8'));
}
await db.exec(await readFile(join(root, 'deployment/device-b2-foundation-v1.sql'), 'utf8'));
await management('owner_scope.ensure', { ...owner, displayName: 'Flow fixture' });
for (const [key, name] of [['first', 'Project A'], ['second', 'Project B'], ['unlinked', 'Project C']]) {
const value = await management('project.ensure', { ...owner, projectKey: key, name });
if (key === 'first') projectA = value.project.projectRef;
if (key === 'second') projectB = value.project.projectRef;
if (key === 'unlinked') projectC = value.project.projectRef;
}
assert.equal((await repository.listAccessibleProjects(actor)).length, 3);
});
await check('empty VPS registers through onboarding and repeated import reuses host', async () => {
pkg = await command({ kind: 'bootstrap' });
host = await execute({ projectRef: projectA }, 'register-host', { name: 'New ARNavi VPS', connection: pkg });
const repeated = await execute({ projectRef: projectA }, 'register-host', { name: 'New ARNavi VPS', connection: pkg });
assert.equal(repeated.hostRef, host.hostRef);
common = { projectRef: projectA, hostRef: host.hostRef };
const status = await execute(common, 'status');
assert.deepEqual(status.contours, []);
assert.equal(status.sharedProjects, false);
});
await check('new contour creates and binds with stable retry identity', async () => {
const id = requestId();
contour = (await execute(common, 'contour-connect', { name: 'Shared fleet', targetProjectRef: projectA }, id)).contourId;
assert.equal((await execute(common, 'contour-connect', { name: 'Shared fleet', targetProjectRef: projectA }, id)).contourId, contour);
assert.equal((await execute(common, 'status')).contours.length, 1);
});
await check('old schema refuses sharing explicitly and forward migration preserves old links', async () => {
await assert.rejects(execute(common, 'link', { contourId: contour, targetProjectRef: projectB }), /b2_shared_projects_migration_required/);
const before = (await db.query('select * from device_b2_contour_links')).rows;
await db.exec(await readFile(join(root, 'deployment/device-b2-shared-contours-v1.sql'), 'utf8'));
assert.deepEqual((await db.query('select * from device_b2_contour_links')).rows, before);
assert.equal((await execute(common, 'status')).sharedProjects, true);
});
await check('one contour links to two projects with separate host views and idempotent edges', async () => {
await execute(common, 'link', { contourId: contour, targetProjectRef: projectB });
await execute(common, 'link', { contourId: contour, targetProjectRef: projectB });
const links = (await execute(common, 'status')).links;
assert.equal(links.length, 2);
const view = (await db.query('select host_id from device_b2_host_views where project_id=$1', [projectB.slice(8)])).rows[0];
second = { projectRef: projectB, hostRef: 'host:' + view.host_id };
assert.notEqual(second.hostRef, common.hostRef);
assert.equal((await db.query('select * from device_b2_hosts')).rows.length, 1);
});
await check('unlinked project can add the shared VPS without seeing another fleet', async () => {
const other = await execute({ projectRef: projectC }, 'register-host', { name: 'Same VPS', connection: pkg });
third = { projectRef: projectC, hostRef: other.hostRef };
assert.deepEqual((await execute(third, 'inventory')).items, []);
});
await check('two independent application packages connect to the same contour', async () => {
appA = await execute(common, 'application-connect', { name: 'Partner management', contourId: contour, access: 'manage' });
appB = await execute(common, 'application-connect', { name: 'Partner observer', contourId: contour, access: 'read' });
assert.notEqual(appA.connection.client_id, appB.connection.client_id);
assert.notEqual(appA.id, appB.id);
appClientA = clientFactory(appA.connection); appClientB = clientFactory(appB.connection);
assert.deepEqual((await appClientA.call('/v2/contours')).items.map(item => item.id), [contour]);
assert.deepEqual((await appClientB.call('/v2/contours')).items.map(item => item.id), [contour]);
await assert.rejects(appClientA.call('/v2/management'), /b2_access_denied/);
await assert.rejects(execute(third, 'register-host', { name: 'Wrong role', connection: appA.connection }), /b2_host_management_required/);
});
await check('manual device enrollment works and duplicate retry creates no second device', async () => {
const options = await execute(common, 'enrollment-options');
assert.equal(options.hosts[0].contours[0].id, contour);
const fields = { contourId: contour, request: { action: 'register', name: 'Synthetic ARNavi B2', imei: '123456789012345', number: 1001 } };
device = await execute(common, 'enrollment', fields);
assert.deepEqual(await execute(common, 'enrollment', fields), device);
await assert.rejects(appClientB.call(`/v2/contours/${contour}/enrollment`, fields.request), /b2_access_denied/);
assert.equal((await appClientA.call(`/v2/contours/${contour}/devices`)).items.length, 1);
});
await check('both projects see the same device while an unlinked project sees none', async () => {
const a = await execute(common, 'inventory'), b = await execute(second, 'inventory'), c = await execute(third, 'inventory');
assert.equal(a.items[0].id, b.items[0].id);
assert.equal(a.items.length, 1); assert.equal(b.items.length, 1); assert.equal(c.items.length, 0);
assert.equal(JSON.stringify(a).includes('123456789012345'), false);
await assert.rejects(execute(third, 'enrollment', { contourId: contour, request: { action: 'catalog' } }), /b2_access_denied/);
});
await check('independent application cursors cannot consume or acknowledge each other', async () => {
const base = `/v2/contours/${contour}/subscriptions`;
const a = await appClientA.call(base, { stream: 'registry' });
const b = await appClientB.call(base, { stream: 'registry' });
assert.notEqual(a.id, b.id);
const first = await appClientA.call(`${base}/${a.id}`);
assert.ok(first.items.length > 0);
await appClientA.call(`${base}/${a.id}/ack`, { through: first.through });
assert.equal((await appClientA.call(`${base}/${a.id}`)).items.length, 0);
assert.equal((await appClientB.call(`${base}/${b.id}`)).items.length, first.items.length);
await assert.rejects(appClientB.call(`${base}/${a.id}`), /b2_access_denied/);
});
await check('external CLI contours appear in catalogue without automatic local access grants', async () => {
const before = (await repository.listAccessibleProjects(actor)).length;
for (let n = 1; n <= 3; n++) await cli(['contour-create', `external-${n}`, '--name', `External ${n}`]);
const status = await execute(common, 'status');
assert.equal(status.contours.length, 4);
assert.equal(status.links.length, 2);
assert.equal((await repository.listAccessibleProjects(actor)).length, before);
const external = status.contours.find(item => item.key === 'external-1');
await assert.rejects(appClientA.call(`/v2/contours/${external.id}/devices`), /b2_access_denied/);
await execute(common, 'link', { contourId: external.id, targetProjectRef: projectA });
assert.equal((await execute(common, 'enrollment-options')).hosts[0].contours.length, 2);
const application = await cli(['app-create', 'external-client', '--name', 'External client', '--grant', `${external.id}:manage`]);
const connection = await cli(['key-issue', application.id]);
const client = clientFactory(connection);
await client.call(`/v2/contours/${external.id}/enrollment`, { action: 'register', name: 'External B2', imei: '123456789012346', number: 1002 });
assert.equal((await execute(common, 'inventory')).items.length, 2);
assert.equal((await execute(second, 'inventory')).items.length, 1);
});
await check('rotation invalidates the old key and preserves application identity and fleet', async () => {
const replacement = await execute(common, 'key-issue', { integrationId: appA.id, replace: true });
await assert.rejects(appClientA.call('/v2/contours'), /b2_access_denied/);
appClientA = clientFactory(replacement.connection);
assert.equal(replacement.connection.integration_id, appA.id);
assert.equal((await appClientA.call(`/v2/contours/${contour}/devices`)).items.length, 1);
assert.equal((await appClientB.call(`/v2/contours/${contour}/devices`)).items.length, 1);
});
await check('lost key response is not replayed and explicit reissue recovers safely', async () => {
const id = requestId(), fields = { name: 'Lost response', contourId: contour, access: 'read' };
const first = await execute(common, 'application-connect', fields, id);
await assert.rejects(execute(common, 'application-connect', fields, id), /b2_conflict/);
const status = await execute(common, 'status');
assert.equal(status.applications.filter(app => app.id === first.id).length, 1);
const replacement = await execute(common, 'key-issue', { integrationId: first.id, replace: true });
await assert.rejects(clientFactory(first.connection).call('/v2/contours'), /b2_access_denied/);
assert.equal((await clientFactory(replacement.connection).call('/v2/contours')).items.length, 1);
});
await check('application deletion revokes access without deleting devices or other clients', async () => {
await execute(common, 'application-delete', { integrationId: appA.id });
await assert.rejects(appClientA.call('/v2/contours'), /b2_access_denied/);
assert.equal((await appClientB.call(`/v2/contours/${contour}/devices`)).items.length, 1);
assert.equal((await execute(second, 'inventory')).items.length, 1);
});
await check('cross-company assignment is rejected and cannot leak a host view', async () => {
const otherOwner = { scopeKind: 'company', ownerRef: 'company:foreign-fixture' };
const otherActor = { ...actor, ownerScopes: [owner, otherOwner] };
await management('owner_scope.ensure', { ...otherOwner, displayName: 'Foreign' }, otherActor);
const value = await management('project.ensure', { ...otherOwner, projectKey: 'foreign', name: 'Foreign project' }, otherActor);
await assert.rejects(execute(common, 'link', { contourId: contour, targetProjectRef: value.project.projectRef }, requestId(), otherActor), /b2_company_mismatch/);
assert.equal((await db.query('select * from device_b2_host_views where project_id=$1', [value.project.projectRef.slice(8)])).rows.length, 0);
});
await check('rollback refuses to discard multiple project bindings', async () => {
await assert.rejects(db.exec(await readFile(join(root, 'deployment/device-b2-shared-contours-v1.rollback.sql'), 'utf8')), /rollback_would_lose_links/);
await db.exec('rollback');
assert.equal((await execute(common, 'status')).links.filter(link => link.contourId === contour).length, 2);
});
await check('unlink is local to one project and leaves external keys and other project intact', async () => {
await execute(common, 'unlink', { contourId: contour, targetProjectRef: projectB });
await execute(common, 'unlink', { contourId: contour, targetProjectRef: projectB });
assert.equal((await execute(second, 'inventory')).items.length, 0);
assert.equal((await execute(common, 'inventory')).items.length, 2);
assert.equal((await appClientB.call(`/v2/contours/${contour}/devices`)).items.length, 1);
});
await check('VPS restart preserves contours devices credentials and project mappings', async () => {
await command({ kind: 'restart' });
assert.equal((await execute(common, 'status')).contours.length, 4);
assert.equal((await execute(common, 'inventory')).items.length, 2);
assert.equal((await appClientB.call(`/v2/contours/${contour}/devices`)).items.length, 1);
});
await check('audit and database metadata never contain exported credential secrets', async () => {
const audit = JSON.stringify((await db.query('select payload from device_audit_events')).rows);
const sources = JSON.stringify((await db.query('select * from device_b2_hosts')).rows);
for (const secret of [pkg.client_secret, appA.connection.client_secret, appB.connection.client_secret]) {
assert.equal(audit.includes(secret), false); assert.equal(sources.includes(secret), false);
}
});
await check('lossless rollback and reapplication preserve remaining associations', async () => {
const before = (await db.query('select * from device_b2_contour_links order by contour_id,project_id')).rows;
await db.exec(await readFile(join(root, 'deployment/device-b2-shared-contours-v1.rollback.sql'), 'utf8'));
await db.exec(await readFile(join(root, 'deployment/device-b2-shared-contours-v1.sql'), 'utf8'));
assert.deepEqual((await db.query('select * from device_b2_contour_links order by contour_id,project_id')).rows, before);
});
const report = { ok: true, checkedAt: new Date().toISOString(), checks, engine: 'PGlite PostgreSQL WASM and VPS SQLite',
real: ['Device Core management repository', 'B2Infrastructure', 'OAuth client library', 'VPS SharedAPI', 'VPS CLI parser and domain', 'credential issue/revoke domain', 'private file vault'],
simulated: ['OAuth provider', 'TLS transport', 'CLI root privilege', 'hardware'],
productionMutation: false, cleanUbuntuInstallation: false, boundedDevices: 2, boundedExternalContours: 3 };
await writeFile(resolve(process.argv[4]), JSON.stringify(report, null, 2) + '\n');
console.log(JSON.stringify({ ok: true, checks: checks.length }));
} finally {
child.stdin.end();
await new Promise(resolve => child.once('exit', resolve));
await db.close(); await rm(secretsRoot, { recursive: true, force: true });
}
@@ -22,6 +22,10 @@ export class B2Infrastructure {
this.pool = pool; this.secrets = secrets; this.clientFactory = clientFactory; this.pool = pool; this.secrets = secrets; this.clientFactory = clientFactory;
this.clients = new Map(); this.clients = new Map();
} }
async supportsSharedProjects(db) {
const row = (await db.query("select obj_description('device_b2_contour_links'::regclass) as marker")).rows[0];
return row?.marker === 'nodedc.device-b2-shared-contours/v1';
}
async clientFor(source) { async clientFor(source) {
// Private file refs are immutable. Re-importing/replacing a key creates a // Private file refs are immutable. Re-importing/replacing a key creates a
// new ref and therefore cannot reuse the previous OAuth token cache. // new ref and therefore cannot reuse the previous OAuth token cache.
@@ -272,44 +276,57 @@ export class B2Infrastructure {
fields(input, []); fields(input, []);
const value = source.authority === 'host' ? await remote.call('/v2/management') : await remote.call('/v2/contours'); const value = source.authority === 'host' ? await remote.call('/v2/management') : await remote.call('/v2/contours');
result = { connected: true, endpoint: source.endpoint, authority: source.authority, result = { connected: true, endpoint: source.endpoint, authority: source.authority,
sharedProjects: await this.supportsSharedProjects(db),
contours: value.contours || value.items, applications: value.applications || [], contours: value.contours || value.items, applications: value.applications || [],
links: links.map((link) => ({ contourId: link.contour_id, projectRef: `project:${link.project_id}` })) }; links: links.map((link) => ({ contourId: link.contour_id, projectRef: `project:${link.project_id}` })) };
} else if (action === 'link' || action === 'project-connect') { } else if (['link', 'unlink', 'project-connect', 'contour-connect'].includes(action)) {
fields(input, action === 'link' ? ['contourId', 'targetProjectRef'] : ['targetProjectRef']); fields(input, action === 'contour-connect' ? ['name', 'targetProjectRef'] : action === 'project-connect' ? ['targetProjectRef'] : ['contourId', 'targetProjectRef']);
const targetId = ref(input.targetProjectRef || input.projectRef, 'project'); const targetId = ref(input.targetProjectRef || input.projectRef, 'project');
const target = await findProjectWithCapability(db, actor, targetId, 'infrastructure.manage'); const target = await findProjectWithCapability(db, actor, targetId, 'infrastructure.manage');
if (target.owner_scope_id !== project.owner_scope_id) throw b2Error('b2_company_mismatch', 403); if (target.owner_scope_id !== project.owner_scope_id) throw b2Error('b2_company_mismatch', 403);
let contour; let contour;
if (action === 'project-connect') { if (action === 'unlink') {
if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403); contour = opaque(input.contourId);
const linked = links.filter((link) => link.project_id === targetId); await db.query('delete from device_b2_contour_links where source_id=$1 and contour_id=$2 and project_id=$3', [source.id, contour, targetId]);
if (linked.length > 1) throw b2Error('b2_conflict', 409); result = { linked: false, contourId: contour, projectRef: `project:${targetId}` };
// Stable project identity makes a retry recover the same contour. } else {
contour = linked[0]?.contour_id || (await remote.call('/v2/management/contours', { if (action === 'contour-connect') {
key: 'dc-' + targetId, name: target.name, if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403);
})).id; if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid');
} else contour = opaque(input.contourId); if (!/^[a-f0-9]{32}$/.test(requestId)) throw b2Error('b2_request_invalid');
const permitted = await remote.call('/v2/contours'); // Retry a lost response without creating another remote contour.
if (!permitted.items.some((item) => item.id === contour)) throw b2Error('b2_access_denied', 403); contour = (await remote.call('/v2/management/contours', { key: 'dc-' + requestId, name: input.name.trim() })).id;
const current = links.find((link) => link.contour_id === contour); } else if (action === 'project-connect') {
if (current && current.project_id !== targetId) throw b2Error('b2_contour_already_linked', 409); if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403);
await db.query(`insert into device_b2_contour_links(source_id,contour_id,project_id,owner_scope_id,created_by_ref) const linked = links.filter((link) => link.project_id === targetId);
values($1,$2,$3,$4,$5) on conflict(source_id,contour_id) do nothing`, if (linked.length > 1) throw b2Error('b2_conflict', 409);
[source.id, contour, targetId, project.owner_scope_id, actor.userRef]); // Stable project identity makes a retry recover the same contour.
if (targetId !== projectId) { contour = linked[0]?.contour_id || (await remote.call('/v2/management/contours', {
const related = (await db.query('select host_id from device_b2_host_views where source_id=$1 and project_id=$2', [source.id, targetId])).rows[0]; key: 'dc-' + targetId, name: target.name,
if (!related) { })).id;
const registered = await applyOntologyManagementCommand(db, { actor, commandKind: 'infrastructure_host.ensure', } else contour = opaque(input.contourId);
command: normalizeOntologyManagementCommand('infrastructure_host.ensure', { const permitted = await remote.call('/v2/contours');
projectRef: `project:${targetId}`, hostKey: `b2-${source.id}`, displayName: host.display_name, if (!permitted.items.some((item) => item.id === contour)) throw b2Error('b2_access_denied', 403);
providerRef: host.provider_ref, externalRef: source.remote_host_id, if (links.some((link) => link.contour_id === contour && link.project_id !== targetId)
managementCredentialRef: null, lifecycleState: 'active', && !await this.supportsSharedProjects(db)) throw b2Error('b2_shared_projects_migration_required', 409);
}) }); await db.query(`insert into device_b2_contour_links(source_id,contour_id,project_id,owner_scope_id,created_by_ref)
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id) values($1,$2,$3,$4,$5) on conflict do nothing`,
values($1,$2,$3,$4)`, [ref(registered.host.hostRef, 'host'), targetId, project.owner_scope_id, source.id]); [source.id, contour, targetId, project.owner_scope_id, actor.userRef]);
if (targetId !== projectId) {
const related = (await db.query('select host_id from device_b2_host_views where source_id=$1 and project_id=$2', [source.id, targetId])).rows[0];
if (!related) {
const registered = await applyOntologyManagementCommand(db, { actor, commandKind: 'infrastructure_host.ensure',
command: normalizeOntologyManagementCommand('infrastructure_host.ensure', {
projectRef: `project:${targetId}`, hostKey: `b2-${source.id}`, displayName: host.display_name,
providerRef: host.provider_ref, externalRef: source.remote_host_id,
managementCredentialRef: null, lifecycleState: 'active',
}) });
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id)
values($1,$2,$3,$4)`, [ref(registered.host.hostRef, 'host'), targetId, project.owner_scope_id, source.id]);
}
} }
result = { linked: true, contourId: contour, projectRef: `project:${targetId}` };
} }
result = { linked: true, contourId: contour, projectRef: `project:${targetId}` };
} else if (action === 'devices') { } else if (action === 'devices') {
fields(input, []); fields(input, []);
const contours = links.filter((link) => link.project_id === projectId); const contours = links.filter((link) => link.project_id === projectId);
@@ -331,13 +348,14 @@ export class B2Infrastructure {
key: input.key, name: input.name, grants: { [opaque(input.contourId)]: 'manage' }, key: input.key, name: input.name, grants: { [opaque(input.contourId)]: 'manage' },
}); });
} else if (action === 'application-connect') { } else if (action === 'application-connect') {
fields(input, ['name', 'contourId']); fields(input, ['name', 'contourId', 'access']);
if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid'); if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid');
const contour = opaque(input.contourId); const contour = opaque(input.contourId);
if (!links.some((link) => link.contour_id === contour)) throw b2Error('b2_access_denied', 403); const access = input.access ?? 'manage';
if (!['read', 'control', 'manage'].includes(access)) throw b2Error('b2_request_invalid');
if (!/^[a-f0-9]{32}$/.test(requestId)) throw b2Error('b2_request_invalid'); if (!/^[a-f0-9]{32}$/.test(requestId)) throw b2Error('b2_request_invalid');
const app = await remote.call('/v2/management/applications', { const app = await remote.call('/v2/management/applications', {
key: 'app-' + requestId, name: input.name.trim(), grants: { [contour]: 'manage' }, key: 'app-' + requestId, name: input.name.trim(), grants: { [contour]: access },
}); });
// The VPS reserves issuance before returning a one-time secret. If // The VPS reserves issuance before returning a one-time secret. If
// the response is lost, status exposes the app for explicit reissue. // the response is lost, status exposes the app for explicit reissue.
@@ -19,10 +19,11 @@ const actor = { userRef: 'user:operator', hubRole: 'owner', groupRefs: [], owner
const source = { id: '55555555-5555-4555-8555-555555555555', owner_scope_id: ownerId, const source = { id: '55555555-5555-4555-8555-555555555555', owner_scope_id: ownerId,
remote_host_id: pkg.host_id, endpoint: pkg.endpoint, fingerprint: pkg.fingerprint, remote_host_id: pkg.host_id, endpoint: pkg.endpoint, fingerprint: pkg.fingerprint,
integration_id: pkg.integration_id, authority: pkg.authority, secret_ref: 'private-ref' }; integration_id: pkg.integration_id, authority: pkg.authority, secret_ref: 'private-ref' };
function repository({ role = 'owner', links = [], otherOwner = ownerId } = {}) { function repository({ role = 'owner', links = [], otherOwner = ownerId, sharedProjects = true } = {}) {
const writes = []; const writes = [];
const db = { release() {}, async query(sql, values) { const db = { release() {}, async query(sql, values) {
if (['begin', 'commit', 'rollback'].includes(sql)) return { rows: [] }; if (['begin', 'commit', 'rollback'].includes(sql)) return { rows: [] };
if (sql.includes('obj_description')) return { rows: [{ marker: sharedProjects ? 'nodedc.device-b2-shared-contours/v1' : 'nodedc.device-b2-foundation/v1' }] };
if (sql.includes('from device_projects')) return { rows: [{ id: values[0], owner_scope_id: values[0] === projectId ? ownerId : otherOwner, if (sql.includes('from device_projects')) return { rows: [{ id: values[0], owner_scope_id: values[0] === projectId ? ownerId : otherOwner,
name: 'Test project', lifecycle_state: 'active', owner_lifecycle_state: 'active', scope_kind: 'company', owner_ref: 'company:example' }] }; name: 'Test project', lifecycle_state: 'active', owner_lifecycle_state: 'active', scope_kind: 'company', owner_ref: 'company:example' }] };
if (sql.includes('from device_project_grants')) return { rows: [{ id: 'grant', principal_kind: 'user', principal_ref: actor.userRef, if (sql.includes('from device_project_grants')) return { rows: [{ id: 'grant', principal_kind: 'user', principal_ref: actor.userRef,
@@ -231,10 +232,50 @@ test('application creation and issuance use one server-generated request identit
assert.equal(result.id, app); assert.equal(result.id, app);
assert.ok(result.connection); assert.ok(result.connection);
assert.equal(JSON.stringify(repo.writes).includes('synthetic'), false); assert.equal(JSON.stringify(repo.writes).includes('synthetic'), false);
await assert.rejects(service.execute(actor, { action: 'application-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'Other', contourId: 'f'.repeat(32) }, requestId), /b2_access_denied/); await assert.rejects(service.execute(actor, { action: 'application-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'Other', contourId: 'f'.repeat(32), access: 'host' }, requestId), /b2_request_invalid/);
assert.equal(calls.length, 2); assert.equal(calls.length, 2);
}); });
test('host catalogue includes external unlinked contours without creating local projects', async () => {
const repo = repository();
const contours = [{ id: 'a'.repeat(32), key: 'external', name: 'External fleet' }];
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ call: async () => ({ contours }) }) });
const result = await service.execute(actor, { action: 'status', projectRef: `project:${projectId}`, hostRef: `host:${hostId}` });
assert.deepEqual(result.contours, contours);
assert.deepEqual(result.links, []);
assert.equal(result.sharedProjects, true);
assert.deepEqual(repo.writes, []);
});
test('second project can share a contour after migration and old foundation fails explicitly', async () => {
for (const sharedProjects of [true, false]) {
const contour = 'c'.repeat(32);
const repo = repository({ sharedProjects, links: [{ contour_id: contour, project_id: otherProject }] });
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ call: async () => ({ items: [{ id: contour }] }) }) });
const result = service.execute(actor, { action: 'link', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, contourId: contour });
if (sharedProjects) {
assert.equal((await result).linked, true);
assert.equal(repo.writes.filter(item => item.sql.includes('device_b2_contour_links')).length, 1);
} else {
await assert.rejects(result, /b2_shared_projects_migration_required/);
assert.deepEqual(repo.writes, []);
}
}
});
test('new contour retries retain remote identity and authorize target before creation', async () => {
const contour = 'c'.repeat(32), calls = [], requestId = 'd'.repeat(32);
const repo = repository();
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ call: async (path, body) => {
calls.push({ path, body }); return path.endsWith('/management/contours') ? { id: contour } : { items: [{ id: contour }] };
} }) });
const input = { action: 'contour-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'New fleet' };
assert.equal((await service.execute(actor, input, requestId)).contourId, contour);
assert.equal((await service.execute(actor, input, requestId)).contourId, contour);
assert.equal(calls[0].body.key, calls[2].body.key);
assert.equal(calls[0].body.key, 'dc-' + requestId);
});
test('tracker settings keep project and contour authority across remote calls', async () => { test('tracker settings keep project and contour authority across remote calls', async () => {
const contour = 'c'.repeat(32), device = 'd'.repeat(32), calls = []; const contour = 'c'.repeat(32), device = 'd'.repeat(32), calls = [];
const repo = repository({ role: 'viewer' }); const db = await repo.pool.connect(); const repo = repository({ role: 'viewer' }); const db = await repo.pool.connect();