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}>
<Select
label="Контур проекта"
label="Владелец проекта"
value={ownerRef}
options={ownerScopes.map((scope) => ({
value: scope.ownerRef,
label: scope.displayName,
description: scope.scopeKind === "company" ? "Коммерческий контур" : "Личный контур",
description: scope.scopeKind === "company" ? "Компания" : "Личное пространство",
}))}
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>
</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())} /></>}
{profile ? <p>Профиль сохранится в Device Core. Отправка настроек — в настройках устройства.</p> : null}
{profile ? <p>Профиль сохранится на VPS. Отправка настроек трекеру — в настройках устройства.</p> : null}
</> : <SettingsCard title="Нет VPS для этого проекта"><p>{hosts.some(item => !item.reachable) ? 'Проверьте доступность VPS и связь контура с этим проектом.' : 'Подключите VPS и свяжите контур с этим проектом в разделе «Инфраструктура».'}</p></SettingsCard>}
{!canRegister ? <p>Для регистрации устройства нужно право «Принятие устройства» в этом проекте.</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 [expanded, setExpanded] = useState<string[]>([]), [keyRows, setKeyRows] = useState<string[]>([]);
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 [issued, setIssued] = useState<{ applicationId: string; clientId: string; value: string } | null>(null);
const [credentialRows, setCredentialRows] = useState<string[]>([]);
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 refresh = () => request<B2Status>('status').then(setStatus);
const refresh = async () => { const value = await request<B2Status>('status'); setStatus(value); setSyncError(''); return value; };
useEffect(() => {
let active = true;
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(''); });
return () => { active = false; };
}, [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) {
setPending(action);
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) {
const { integration_id: applicationId, client_id: clientId } = result.connection;
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 === 'application-delete' && issued?.applicationId === data.integrationId) setIssued(null);
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);
try { await refresh(); await onChanged(); } catch (error) { onError(error); }
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 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>
<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) => {
const keyOpen = credentialRows.includes(item.client_id);
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 }]}
activeSection={section} onSectionChange={setSection} onClose={onClose}
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}
<IconButton label="Обновить состояние VPS" loading={pending === 'refresh'} disabled={busy} onClick={async () => {
setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); }
}}><Icon name="refresh" /></IconButton></>}>
<div className="b2-settings" aria-busy={busy}>
{syncError ? <p role="status">{syncError}</p> : null}
{section === 'connection' ? <>
<ResourceRow title={host.displayName} description={status?.endpoint} metadata="Подключение Device Core к серверу ARNavi"
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></SettingsCard> : null}
</> : null}
{section === 'contours' ? <ResourceList>{projects.map((item) => {
const links = (status?.links || []).filter((link) => link.projectRef === item.projectRef);
const linked = links.length > 0, open = expanded.includes(item.projectRef);
const apps = (status?.applications || []).filter((app) => app.authority !== 'host' && links.some((link) => app.grants[link.contourId]));
const available = (status?.contours || []).filter((contour) => !status?.links?.some((link) => link.contourId === contour.id));
return <li key={item.projectRef} className="b2-disclosure">
<ResourceRow title={item.name} metadata={linked ? 'Контур VPS связан с проектом' : 'Проект Device Core'}
actions={<>
{open && linked && canManage ? <IconButton label={`Добавить приложение в ${item.name}`} disabled={busy} onClick={() => { setCreating(item.projectRef); setName(''); setCreationIntent(null); }}><Icon name="plus" /></IconButton> : 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>
{section === 'contours' ? <>
{newContour ? <SettingsCard title="Новый контур VPS" description="Создаётся на этом VPS и связывается с выбранным проектом Device Core."><div className="b2-settings">
<TextField label="Название контура" value={contourName} disabled={busy || Boolean(contourIntent)} maxLength={160} autoFocus onChange={event => setContourName(event.target.value)} />
<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} />
<div className="b2-actions"><Button disabled={busy} onClick={() => { setNewContour(false); setContourIntent(null); }}>Отмена</Button><Button disabled={busy || !contourName.trim() || !targetProject} loading={pending === 'contour-connect'} onClick={() => {
const intent = contourIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: contourName.trim(), projectRef: targetProject };
setContourIntent(intent); void run('contour-connect', { name: intent.name, targetProjectRef: intent.projectRef }, intent.id);
}}>{contourIntent ? 'Уточнить создание' : 'Создать контур'}</Button></div>
</div></SettingsCard> : null}
{!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">
{!linked ? <>
{canManage ? <Button disabled={busy} loading={pending === 'project-connect'} onClick={() => void run('project-connect', { targetProjectRef: item.projectRef })}>Подключить проект к VPS</Button> : null}
{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}
</> : <>
{open ? <div id={`contour-${contour.id}`} className="b2-disclosure__body">
<div className="b2-section-heading"><strong>Проекты Device Core</strong></div>
<p>Связанные проекты видят один реестр устройств этого контура. Ключи внешних приложений управляются отдельно.</p>
{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>
<ResourceList>{apps.map(applicationRow)}</ResourceList>
{!apps.length && creating !== item.projectRef ? <p>Ключи приложений ещё не выданы</p> : null}
{creating === item.projectRef ? <div className="b2-settings">
<TextField label="Название приложения" autoFocus value={name} disabled={busy || Boolean(creationIntent)} maxLength={160} onChange={(event) => setName(event.target.value)} />
{!apps.length && creating !== contour.id ? <p>Ключи приложений ещё не выданы</p> : null}
{creating === contour.id ? <div className="b2-settings">
<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={() => {
const intent = creationIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: name.trim() };
const intent = creationIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: name.trim(), access };
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>
</div> : null}
</>}
</div> : null}
</li>;
})}</ResourceList> : null}
</div> : null}
</li>;
})}</ResourceList>
</> : null}
</div>
</FeatureSettingsWindow>
<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');
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';
grants: Record<string, string>; credentials: Array<{ client_id: string; enabled: boolean }> };
export type B2Status = { connected: boolean; endpoint?: string; authority?: 'host' | 'contours';
sharedProjects?: boolean;
contours?: B2Contour[]; applications?: B2Application[];
links?: Array<{ contourId: string; projectRef: 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_key_rejected: 'VPS не принял ключ подключения.',
b2_conflict: 'На VPS уже есть запись с такими данными. Обновите список и проверьте результат.',
b2_contour_already_linked: 'Этот контур уже связан с другим проектом.',
b2_shared_projects_migration_required: 'На сервере Device Core ещё не установлена миграция общих контуров. До её установки контур можно связать только с одним проектом.',
b2_connection_identity_conflict: 'Этот хост уже подключён другим приложением или ключом сервера.',
b2_certificate_mismatch: 'Сертификат VPS не соответствует ключу подключения.',
b2_private_storage_unavailable: 'Закрытое хранилище ключей ещё не настроено на Device Core.',
@@ -1,10 +1,10 @@
{
"version": "0.2.4",
"filename": "nodedc-arnavi-vps-0.2.4.pyz",
"sha256": "242b6e04f8d38711aa707da67e96f0a2374cbb25b7e79934a58367a34e9a20e6",
"bytes": 16129185,
"version": "0.2.5",
"filename": "nodedc-arnavi-vps-0.2.5.pyz",
"sha256": "d9a822ca7c2498841a6fd13fddac27da4fc22366931ba8980b97c66c159a383f",
"bytes": 16129246,
"sourceRepository": "https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS.git",
"sourceCommit": "881f68dbad9f8fdde2f0f4693de549cff45cacfa",
"manifestSha256": "f23e6cf7048ce5e8d17720933a13c3bef5ee9b523c194b4f07f874f372a25484",
"sourceCommit": "193253dd48a1c6390ea4c5e500693123b88ce2ea",
"manifestSha256": "139a3c1d7f3e8266e2154586783133078311aa9dae76d74ed229aab16f816197",
"environment": "ubuntu-24.04-amd64"
}