Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3a48b80c8 | ||
|
|
56ca94d242 | ||
|
|
64624293a8 | ||
|
|
24d01fc813 | ||
|
|
332e097116 |
@@ -205,6 +205,14 @@ export function resolveRequiredGroups(data, user) {
|
||||
groupNames.add(platformGroups.taskManagerAdmin);
|
||||
groupNames.add(platformGroups.taskManagerUser);
|
||||
addGroups(groupNames, resolveEngineRoleGroups("member"));
|
||||
// The platform super-admin is the default owner of every internally
|
||||
// registered service. This also keeps the Authentik view consistent with
|
||||
// the Launcher control-plane grants (including Module Foundry).
|
||||
for (const service of data.services) {
|
||||
if (service.authentikGroupName) {
|
||||
groupNames.add(service.authentikGroupName);
|
||||
}
|
||||
}
|
||||
return [...groupNames];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveRequiredGroups } from "./authentik-sync.mjs";
|
||||
|
||||
const user = {
|
||||
id: "user_device_engineer",
|
||||
email: "engineer@example.test",
|
||||
name: "Device Engineer",
|
||||
globalStatus: "active",
|
||||
};
|
||||
const client = { id: "client_dctouch", status: "active" };
|
||||
const membership = {
|
||||
id: "membership_device_engineer",
|
||||
clientId: client.id,
|
||||
userId: user.id,
|
||||
role: "member",
|
||||
status: "active",
|
||||
};
|
||||
const service = {
|
||||
id: "service_device_core_contract",
|
||||
slug: "device-core",
|
||||
status: "active",
|
||||
authentikApplicationSlug: "device-core",
|
||||
authentikGroupName: "nodedc:device-core:access",
|
||||
};
|
||||
|
||||
function data(grants = [], exceptions = []) {
|
||||
return {
|
||||
users: [user],
|
||||
clients: [client],
|
||||
memberships: [membership],
|
||||
groups: [],
|
||||
services: [service],
|
||||
grants,
|
||||
exceptions,
|
||||
};
|
||||
}
|
||||
|
||||
describe("generic service Authentik group projection", () => {
|
||||
it("projects the service group only after an effective grant", () => {
|
||||
const withoutGrant = resolveRequiredGroups(data(), user);
|
||||
const withGrant = resolveRequiredGroups(
|
||||
data([
|
||||
{
|
||||
id: "grant_device_core_dctouch",
|
||||
serviceId: service.id,
|
||||
targetType: "client",
|
||||
targetId: client.id,
|
||||
appRole: "admin",
|
||||
status: "active",
|
||||
},
|
||||
]),
|
||||
user
|
||||
);
|
||||
|
||||
expect(withoutGrant).not.toContain("nodedc:device-core:access");
|
||||
expect(withGrant).toContain("nodedc:device-core:access");
|
||||
});
|
||||
|
||||
it("does not project the group when a deny exception wins", () => {
|
||||
const groups = resolveRequiredGroups(
|
||||
data(
|
||||
[
|
||||
{
|
||||
id: "grant_device_core_dctouch",
|
||||
serviceId: service.id,
|
||||
targetType: "client",
|
||||
targetId: client.id,
|
||||
appRole: "admin",
|
||||
status: "active",
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
id: "deny_device_core_engineer",
|
||||
serviceId: service.id,
|
||||
userId: user.id,
|
||||
type: "deny",
|
||||
},
|
||||
]
|
||||
),
|
||||
user
|
||||
);
|
||||
|
||||
expect(groups).not.toContain("nodedc:device-core:access");
|
||||
});
|
||||
});
|
||||
+290
-42
@@ -107,6 +107,40 @@ const bimViewerDefaultGrants = [
|
||||
updatedAt: "2026-06-18T00:00:00.000Z",
|
||||
},
|
||||
];
|
||||
const moduleFoundryService = {
|
||||
id: "service_module_foundry",
|
||||
slug: "module-foundry",
|
||||
title: "MODULE FOUNDRY",
|
||||
subtitle: "Конфигурация платформенных модулей",
|
||||
description: "Сборка приложений NODE.DC из утверждённых страниц, визуальных профилей и онтологических сущностей.",
|
||||
fullDescription:
|
||||
"Module Foundry — внутренний контур для конфигурации модулей NODE.DC. В первой версии доступ открывается только через Launcher; самостоятельной регистрации, публичного входа и многопользовательского владения проектами нет.",
|
||||
url: "https://foundry.nodedc.ru",
|
||||
launchUrl: "https://foundry.nodedc.ru",
|
||||
logoutUrl: "https://foundry.nodedc.ru/auth/logout",
|
||||
accentColor: "#F12F92",
|
||||
fallbackGradient: "linear-gradient(132deg, rgba(241, 47, 146, 0.8), rgba(67, 19, 58, 0.92) 48%, #080B0F 86%)",
|
||||
status: "active",
|
||||
order: 26,
|
||||
authentikApplicationSlug: "module-foundry",
|
||||
authentikGroupName: "nodedc:module-foundry:access",
|
||||
authHandoffPath: "/auth/nodedc/handoff",
|
||||
isAvailableForAllNewClients: false,
|
||||
createdAt: "2026-07-14T00:00:00.000Z",
|
||||
updatedAt: "2026-07-14T00:00:00.000Z",
|
||||
};
|
||||
const moduleFoundryDefaultGrants = [
|
||||
{
|
||||
id: "grant_module_foundry_dctouch_admins",
|
||||
serviceId: "service_module_foundry",
|
||||
targetType: "group",
|
||||
targetId: "group_dctouch_admins",
|
||||
appRole: "member",
|
||||
status: "active",
|
||||
createdAt: "2026-07-14T00:00:00.000Z",
|
||||
updatedAt: "2026-07-14T00:00:00.000Z",
|
||||
},
|
||||
];
|
||||
const defaultSettings = {
|
||||
brand: {
|
||||
logoLinkUrl: "/",
|
||||
@@ -1967,9 +2001,16 @@ export function createControlPlaneStore({ projectRoot }) {
|
||||
const data = readData();
|
||||
const actor = resolveActor(data, identity);
|
||||
const service = findById(data.services, serviceId, "service");
|
||||
const candidate = syncServiceLaunchLink({
|
||||
...service,
|
||||
...sanitizeServicePatch(payload, service),
|
||||
});
|
||||
|
||||
Object.assign(service, sanitizeServicePatch(payload, service));
|
||||
Object.assign(service, syncServiceLaunchLink(service));
|
||||
candidate.slug = normalizeServiceSlug(candidate.slug);
|
||||
candidate.authHandoffPath = normalizeServiceHandoffPath(candidate.authHandoffPath);
|
||||
assertServiceIdentityAvailable(data, candidate, service.id);
|
||||
|
||||
Object.assign(service, candidate);
|
||||
service.updatedAt = isoNow();
|
||||
|
||||
addAuditEvent(data, actor, {
|
||||
@@ -1985,6 +2026,51 @@ export function createControlPlaneStore({ projectRoot }) {
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureService(serviceSlug, payload, identity) {
|
||||
return enqueueMutation(async () => {
|
||||
const data = readData();
|
||||
const actor = resolveActor(data, identity);
|
||||
const now = isoNow();
|
||||
const normalizedSlug = normalizeServiceSlug(serviceSlug);
|
||||
const payloadSlug = payload?.slug == null ? normalizedSlug : normalizeServiceSlug(payload.slug);
|
||||
|
||||
if (payloadSlug !== normalizedSlug) {
|
||||
throw new Error("service slug path and payload mismatch");
|
||||
}
|
||||
|
||||
const existingService = data.services.find((service) => service.slug === normalizedSlug) ?? null;
|
||||
const service = existingService
|
||||
? syncServiceLaunchLink({
|
||||
...existingService,
|
||||
...sanitizeServicePatch({ ...payload, slug: normalizedSlug }, existingService),
|
||||
})
|
||||
: createServiceRecord(data, { ...payload, slug: normalizedSlug }, now);
|
||||
|
||||
service.slug = normalizedSlug;
|
||||
service.authHandoffPath = normalizeServiceHandoffPath(service.authHandoffPath);
|
||||
service.updatedAt = now;
|
||||
assertServiceIdentityAvailable(data, service, existingService?.id ?? null);
|
||||
|
||||
if (existingService) {
|
||||
Object.assign(existingService, service);
|
||||
} else {
|
||||
data.services.push(service);
|
||||
}
|
||||
|
||||
addAuditEvent(data, actor, {
|
||||
action: existingService ? "Обновлена регистрация сервиса" : "Зарегистрирован сервис",
|
||||
objectType: "service",
|
||||
objectName: service.title,
|
||||
result: "success",
|
||||
details: `Slug: ${service.slug}; Authentik group: ${service.authentikGroupName ?? "none"}`,
|
||||
});
|
||||
markPendingSync(data, service, "service");
|
||||
|
||||
await writeData(data);
|
||||
return { service, data, created: !existingService };
|
||||
});
|
||||
}
|
||||
|
||||
async function reorderServices(payload, identity) {
|
||||
const data = readData();
|
||||
const actor = resolveActor(data, identity);
|
||||
@@ -2010,48 +2096,25 @@ export function createControlPlaneStore({ projectRoot }) {
|
||||
}
|
||||
|
||||
async function createService(payload, identity) {
|
||||
const data = readData();
|
||||
const actor = resolveActor(data, identity);
|
||||
const now = isoNow();
|
||||
const nextIndex = data.services.length + 1;
|
||||
const nextOrder = Math.max(0, ...data.services.map((service) => Number(service.order) || 0)) + 10;
|
||||
const title = optionalString(payload?.title, "New Service");
|
||||
const service = syncServiceLaunchLink({
|
||||
id: uniqueId(data.services, "service", title),
|
||||
slug: optionalString(payload?.slug, `new-service-${nextIndex}`),
|
||||
title,
|
||||
subtitle: nullableString(payload?.subtitle) ?? "Новый сервис",
|
||||
description: optionalString(payload?.description, "Описание сервиса для витрины."),
|
||||
fullDescription: nullableString(payload?.fullDescription) ?? "Заполните описание, медиа и ссылку запуска в редакторе контента.",
|
||||
url: optionalString(payload?.url, "https://service.handhdc.ru/sso/launch"),
|
||||
launchUrl: nullableString(payload?.launchUrl) ?? optionalString(payload?.url, "https://service.handhdc.ru/sso/launch"),
|
||||
accentColor: nullableString(payload?.accentColor) ?? "#F7F8F4",
|
||||
fallbackGradient:
|
||||
nullableString(payload?.fallbackGradient) ??
|
||||
"linear-gradient(135deg, rgba(247, 248, 244, 0.72), rgba(36, 37, 42, 0.9) 52%, #090B0F 88%)",
|
||||
coverMediaSource: nullableString(payload?.coverMediaSource) ?? "url",
|
||||
coverMediaKind: nullableString(payload?.coverMediaKind) ?? "image",
|
||||
ambientMediaSource: nullableString(payload?.ambientMediaSource) ?? "url",
|
||||
ambientMediaKind: nullableString(payload?.ambientMediaKind) ?? "gif",
|
||||
status: pickEnum(payload?.status, serviceStatuses, "hidden"),
|
||||
order: nextOrder,
|
||||
authentikApplicationSlug: nullableString(payload?.authentikApplicationSlug) ?? `new-service-${nextIndex}`,
|
||||
authentikGroupName: nullableString(payload?.authentikGroupName) ?? `service-new-${nextIndex}`,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
return enqueueMutation(async () => {
|
||||
const data = readData();
|
||||
const actor = resolveActor(data, identity);
|
||||
const now = isoNow();
|
||||
const service = createServiceRecord(data, payload, now);
|
||||
|
||||
data.services.push(service);
|
||||
addAuditEvent(data, actor, {
|
||||
action: "Создан сервис",
|
||||
objectType: "service",
|
||||
objectName: service.title,
|
||||
result: "success",
|
||||
});
|
||||
markPendingSync(data, service, "service");
|
||||
assertServiceIdentityAvailable(data, service);
|
||||
data.services.push(service);
|
||||
addAuditEvent(data, actor, {
|
||||
action: "Создан сервис",
|
||||
objectType: "service",
|
||||
objectName: service.title,
|
||||
result: "success",
|
||||
});
|
||||
markPendingSync(data, service, "service");
|
||||
|
||||
await writeData(data);
|
||||
return { service, data };
|
||||
await writeData(data);
|
||||
return { service, data };
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteService(serviceId, identity) {
|
||||
@@ -2273,6 +2336,7 @@ export function createControlPlaneStore({ projectRoot }) {
|
||||
getLoginAccountStatus,
|
||||
getSnapshot,
|
||||
ensureTaskerInvitePlatformInvite,
|
||||
ensureService,
|
||||
prepareInviteRegistration,
|
||||
readData,
|
||||
replaceData,
|
||||
@@ -2333,6 +2397,7 @@ function normalizeData(payload) {
|
||||
data.engineWorkflowAccessRequests = data.engineWorkflowAccessRequests.map(normalizeEngineWorkflowAccessRequest).filter(Boolean);
|
||||
applyProtectedLauncherUserInvariants(data);
|
||||
applyBimViewerServiceInvariants(data);
|
||||
applyModuleFoundryServiceInvariants(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -2396,6 +2461,65 @@ function applyBimViewerServiceInvariants(data) {
|
||||
}
|
||||
}
|
||||
|
||||
function applyModuleFoundryServiceInvariants(data) {
|
||||
let service = data.services.find(
|
||||
(candidate) => candidate.id === moduleFoundryService.id || candidate.slug === moduleFoundryService.slug
|
||||
);
|
||||
|
||||
if (!service) {
|
||||
service = normalizeService({ ...moduleFoundryService });
|
||||
data.services.push(service);
|
||||
} else {
|
||||
service.id = service.id || moduleFoundryService.id;
|
||||
service.slug = service.slug || moduleFoundryService.slug;
|
||||
service.title = service.title || moduleFoundryService.title;
|
||||
service.subtitle = service.subtitle || moduleFoundryService.subtitle;
|
||||
service.description = service.description || moduleFoundryService.description;
|
||||
service.fullDescription = service.fullDescription || moduleFoundryService.fullDescription;
|
||||
service.url = service.url || moduleFoundryService.url;
|
||||
service.launchUrl = service.launchUrl || service.url || moduleFoundryService.launchUrl;
|
||||
service.logoutUrl = service.logoutUrl || moduleFoundryService.logoutUrl;
|
||||
service.accentColor = service.accentColor || moduleFoundryService.accentColor;
|
||||
service.fallbackGradient = service.fallbackGradient || moduleFoundryService.fallbackGradient;
|
||||
service.status = service.status || moduleFoundryService.status;
|
||||
service.order = service.order ?? moduleFoundryService.order;
|
||||
service.authentikApplicationSlug = service.authentikApplicationSlug || moduleFoundryService.authentikApplicationSlug;
|
||||
service.authentikGroupName = service.authentikGroupName || moduleFoundryService.authentikGroupName;
|
||||
service.authHandoffPath = service.authHandoffPath || moduleFoundryService.authHandoffPath;
|
||||
service.isAvailableForAllNewClients = service.isAvailableForAllNewClients ?? false;
|
||||
service.createdAt = service.createdAt || moduleFoundryService.createdAt;
|
||||
service.updatedAt = service.updatedAt || moduleFoundryService.updatedAt;
|
||||
}
|
||||
|
||||
const serviceId = service.id || moduleFoundryService.id;
|
||||
const defaultGrant = { ...moduleFoundryDefaultGrants[0], serviceId };
|
||||
const groupExists = data.groups.some((group) => group.id === defaultGrant.targetId);
|
||||
const grantExists = data.grants.some(
|
||||
(candidate) =>
|
||||
candidate.serviceId === defaultGrant.serviceId &&
|
||||
candidate.targetType === defaultGrant.targetType &&
|
||||
candidate.targetId === defaultGrant.targetId
|
||||
);
|
||||
if (groupExists && !grantExists) {
|
||||
data.grants.push(defaultGrant);
|
||||
}
|
||||
|
||||
ensureStaticSyncStatus(data, {
|
||||
id: "sync_module_foundry_authentik",
|
||||
objectId: serviceId,
|
||||
objectName: moduleFoundryService.title,
|
||||
objectType: "service",
|
||||
});
|
||||
if (groupExists) {
|
||||
ensureStaticSyncStatus(data, {
|
||||
id: `sync_${defaultGrant.id}`,
|
||||
objectId: defaultGrant.id,
|
||||
objectName: `${moduleFoundryService.slug}:${defaultGrant.targetType}:${defaultGrant.targetId}`,
|
||||
objectType: "grant",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function ensureStaticSyncStatus(data, status) {
|
||||
const exists = data.syncStatuses.some(
|
||||
(candidate) => candidate.target === "authentik" && candidate.objectType === status.objectType && candidate.objectId === status.objectId
|
||||
@@ -2491,6 +2615,22 @@ function upsertSystemProtectedUserGrant(data, user, service, appRole, now) {
|
||||
|
||||
function normalizeService(service) {
|
||||
if (typeof service !== "object" || service === null) return service;
|
||||
if (
|
||||
service.id === "service_module_foundry" ||
|
||||
service.slug === "module-foundry" ||
|
||||
service.authentikApplicationSlug === "module-foundry"
|
||||
) {
|
||||
return {
|
||||
...service,
|
||||
url: service.url || moduleFoundryService.url,
|
||||
launchUrl: service.launchUrl || service.url || moduleFoundryService.launchUrl,
|
||||
logoutUrl: service.logoutUrl || moduleFoundryService.logoutUrl,
|
||||
authentikApplicationSlug: service.authentikApplicationSlug || moduleFoundryService.authentikApplicationSlug,
|
||||
authentikGroupName: service.authentikGroupName || moduleFoundryService.authentikGroupName,
|
||||
authHandoffPath: service.authHandoffPath || moduleFoundryService.authHandoffPath,
|
||||
isAvailableForAllNewClients: service.isAvailableForAllNewClients ?? false,
|
||||
};
|
||||
}
|
||||
if (service.id === "service_bim_viewer" || service.slug === "bim-viewer" || service.authentikApplicationSlug === "bim-viewer") {
|
||||
const legacyLocalUrl = (value) => value === "http://localhost:8080" || value === "http://127.0.0.1:8080";
|
||||
return {
|
||||
@@ -3680,6 +3820,7 @@ function sanitizeServicePatch(payload, service) {
|
||||
"fallbackGradient",
|
||||
"authentikApplicationSlug",
|
||||
"authentikGroupName",
|
||||
"authHandoffPath",
|
||||
];
|
||||
|
||||
for (const field of stringFields) {
|
||||
@@ -3700,6 +3841,113 @@ function sanitizeServicePatch(payload, service) {
|
||||
return patch;
|
||||
}
|
||||
|
||||
function createServiceRecord(data, payload, now) {
|
||||
const nextIndex = data.services.length + 1;
|
||||
const nextOrder = Math.max(0, ...data.services.map((service) => Number(service.order) || 0)) + 10;
|
||||
const title = optionalString(payload?.title, "New Service");
|
||||
const defaultUrl = optionalString(payload?.url, "https://service.handhdc.ru/sso/launch");
|
||||
const base = {
|
||||
id: uniqueId(data.services, "service", title),
|
||||
slug: optionalString(payload?.slug, `new-service-${nextIndex}`),
|
||||
title,
|
||||
subtitle: "Новый сервис",
|
||||
description: "Описание сервиса для витрины.",
|
||||
fullDescription: "Заполните описание, медиа и ссылку запуска в редакторе контента.",
|
||||
url: defaultUrl,
|
||||
launchUrl: defaultUrl,
|
||||
logoutUrl: null,
|
||||
loginSyncUrl: null,
|
||||
iconUrl: null,
|
||||
coverImageUrl: null,
|
||||
coverMediaKind: "image",
|
||||
coverMediaSource: "url",
|
||||
coverMediaFileName: null,
|
||||
previewVideoUrl: null,
|
||||
ambientVideoUrl: null,
|
||||
ambientMediaKind: "gif",
|
||||
ambientMediaSource: "url",
|
||||
ambientMediaFileName: null,
|
||||
accentColor: "#F7F8F4",
|
||||
fallbackGradient: "linear-gradient(135deg, rgba(247, 248, 244, 0.72), rgba(36, 37, 42, 0.9) 52%, #090B0F 88%)",
|
||||
status: "hidden",
|
||||
order: nextOrder,
|
||||
authentikApplicationSlug: `new-service-${nextIndex}`,
|
||||
authentikGroupName: `service-new-${nextIndex}`,
|
||||
authHandoffPath: null,
|
||||
isAvailableForAllNewClients: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
const service = syncServiceLaunchLink({
|
||||
...base,
|
||||
...sanitizeServicePatch(payload, base),
|
||||
});
|
||||
|
||||
service.slug = normalizeServiceSlug(service.slug);
|
||||
service.authHandoffPath = normalizeServiceHandoffPath(service.authHandoffPath);
|
||||
return service;
|
||||
}
|
||||
|
||||
function normalizeServiceSlug(value) {
|
||||
const slug = requireString(value, "service slug");
|
||||
|
||||
if (!/^[a-z][a-z0-9-]{1,62}$/.test(slug)) {
|
||||
throw new Error("service slug must be 2-63 lowercase letters, digits or hyphens");
|
||||
}
|
||||
|
||||
return slug;
|
||||
}
|
||||
|
||||
function normalizeServiceHandoffPath(value) {
|
||||
const path = nullableString(value);
|
||||
|
||||
if (path == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!path.startsWith("/") || path.startsWith("//") || path.includes("://") || path.includes("\\")) {
|
||||
throw new Error("authHandoffPath must be a relative absolute-path reference");
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
function assertServiceIdentityAvailable(data, candidate, ignoredServiceId = null) {
|
||||
const duplicateSlug = data.services.find(
|
||||
(service) => service.id !== ignoredServiceId && service.slug === candidate.slug
|
||||
);
|
||||
|
||||
if (duplicateSlug) {
|
||||
throw new Error(`service slug already exists: ${candidate.slug}`);
|
||||
}
|
||||
|
||||
if (candidate.authentikApplicationSlug) {
|
||||
const duplicateApplication = data.services.find(
|
||||
(service) =>
|
||||
service.id !== ignoredServiceId &&
|
||||
service.authentikApplicationSlug === candidate.authentikApplicationSlug
|
||||
);
|
||||
|
||||
if (duplicateApplication) {
|
||||
throw new Error(`Authentik application slug already exists: ${candidate.authentikApplicationSlug}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (!candidate.authentikGroupName) {
|
||||
return;
|
||||
}
|
||||
|
||||
const duplicateGroup = data.services.find(
|
||||
(service) =>
|
||||
service.id !== ignoredServiceId &&
|
||||
service.authentikGroupName === candidate.authentikGroupName
|
||||
);
|
||||
|
||||
if (duplicateGroup) {
|
||||
throw new Error(`Authentik group already exists: ${candidate.authentikGroupName}`);
|
||||
}
|
||||
}
|
||||
|
||||
function syncServiceLaunchLink(service) {
|
||||
const launchLink = String(service.launchUrl || service.url || "").trim();
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { createControlPlaneStore } from "./control-plane-store.mjs";
|
||||
|
||||
const temporaryRoots = [];
|
||||
const actor = { sub: "phase1-contract", name: "Phase 1 contract test" };
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(temporaryRoots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
async function createStore() {
|
||||
const projectRoot = await mkdtemp(join(tmpdir(), "nodedc-launcher-service-registration-"));
|
||||
temporaryRoots.push(projectRoot);
|
||||
return createControlPlaneStore({ projectRoot });
|
||||
}
|
||||
|
||||
function registration(overrides = {}) {
|
||||
return {
|
||||
slug: "device-core",
|
||||
title: "DEVICE CORE",
|
||||
subtitle: "Управление устройствами",
|
||||
description: "Универсальный Device Manager NODE.DC.",
|
||||
url: "https://device.nodedc.ru",
|
||||
launchUrl: "https://device.nodedc.ru",
|
||||
logoutUrl: "https://device.nodedc.ru/auth/logout",
|
||||
loginSyncUrl: "https://device.nodedc.ru/auth/login-sync",
|
||||
status: "active",
|
||||
authentikApplicationSlug: "device-core",
|
||||
authentikGroupName: "nodedc:device-core:access",
|
||||
authHandoffPath: "/auth/nodedc/handoff",
|
||||
isAvailableForAllNewClients: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("generic Hub service registration", () => {
|
||||
it("creates and then updates one service by slug without an implicit grant", async () => {
|
||||
const store = await createStore();
|
||||
const first = await store.ensureService("device-core", registration(), actor);
|
||||
|
||||
expect(first.created).toBe(true);
|
||||
expect(first.service).toMatchObject({
|
||||
slug: "device-core",
|
||||
authentikApplicationSlug: "device-core",
|
||||
authentikGroupName: "nodedc:device-core:access",
|
||||
authHandoffPath: "/auth/nodedc/handoff",
|
||||
isAvailableForAllNewClients: false,
|
||||
});
|
||||
expect(first.data.grants.some((grant) => grant.serviceId === first.service.id)).toBe(false);
|
||||
|
||||
const second = await store.ensureService("device-core", registration({ title: "DEVICE CORE 2" }), actor);
|
||||
const registered = second.data.services.filter((service) => service.slug === "device-core");
|
||||
|
||||
expect(second.created).toBe(false);
|
||||
expect(second.service.id).toBe(first.service.id);
|
||||
expect(second.service.title).toBe("DEVICE CORE 2");
|
||||
expect(registered).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rejects slug mismatch, duplicate identities and unsafe handoff destinations", async () => {
|
||||
const store = await createStore();
|
||||
await store.ensureService("device-core", registration(), actor);
|
||||
|
||||
await expect(store.ensureService("device-core", registration({ slug: "another-service" }), actor)).rejects.toThrow(
|
||||
"service slug path and payload mismatch"
|
||||
);
|
||||
await expect(
|
||||
store.createService(registration({ slug: "device-core-copy", authentikApplicationSlug: "device-core" }), actor)
|
||||
).rejects.toThrow("Authentik application slug already exists");
|
||||
await expect(
|
||||
store.createService(registration({
|
||||
slug: "device-core-group-copy",
|
||||
authentikApplicationSlug: "device-core-group-copy",
|
||||
}), actor)
|
||||
).rejects.toThrow("Authentik group already exists");
|
||||
await expect(
|
||||
store.ensureService("unsafe-handoff", registration({
|
||||
slug: "unsafe-handoff",
|
||||
authentikApplicationSlug: "unsafe-handoff",
|
||||
authHandoffPath: "https://attacker.example/handoff",
|
||||
}), actor)
|
||||
).rejects.toThrow("authHandoffPath must be a relative absolute-path reference");
|
||||
});
|
||||
});
|
||||
+352
-36
@@ -1,6 +1,6 @@
|
||||
import express from "express";
|
||||
import { createServer as createHttpServer } from "node:http";
|
||||
import { randomBytes, randomUUID, createHash, timingSafeEqual } from "node:crypto";
|
||||
import { randomBytes, randomUUID, createHash } from "node:crypto";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, extname, isAbsolute, join, resolve } from "node:path";
|
||||
@@ -8,6 +8,11 @@ import { fileURLToPath } from "node:url";
|
||||
import { createRemoteJWKSet, jwtVerify } from "jose";
|
||||
import { createAuthentikSyncClient, resolveRequiredGroups } from "./authentik-sync.mjs";
|
||||
import { createControlPlaneStore } from "./control-plane-store.mjs";
|
||||
import { resolveDeviceCoreSessionAccess } from "./device-core-session-access.mjs";
|
||||
import {
|
||||
isInternalRequestTokenAuthorized,
|
||||
isInternalRequestTokenConfigured,
|
||||
} from "./internal-request-auth.mjs";
|
||||
import { createNotificationCoreClient } from "./notification-core-client.mjs";
|
||||
|
||||
const serverRoot = dirname(fileURLToPath(import.meta.url));
|
||||
@@ -68,6 +73,7 @@ app.get("/healthz", (_req, res) => {
|
||||
oidcConfigured: config.oidcConfigured,
|
||||
authentikApiConfigured: authentikSyncClient.isConfigured(),
|
||||
internalAccessApiConfigured: Boolean(config.internalAccessToken),
|
||||
deviceCoreInternalAccessConfigured: Boolean(config.deviceCoreInternalAccessToken),
|
||||
notificationCoreConfigured: notificationCoreClient.isConfigured(),
|
||||
});
|
||||
});
|
||||
@@ -454,16 +460,17 @@ app.get("/api/services/:serviceSlug/launch", requireSession, (req, res) => {
|
||||
});
|
||||
|
||||
app.post("/api/internal/handoff/consume", (req, res) => {
|
||||
if (!isInternalRequestAuthorized(req)) {
|
||||
res.status(config.internalAccessToken ? 401 : 503).json({
|
||||
const serviceSlug = sanitizeServiceSlug(req.body?.serviceSlug);
|
||||
if (!isInternalRequestAuthorized(req, { serviceSlug })) {
|
||||
const configured = isInternalRequestConfigured(serviceSlug);
|
||||
res.status(configured ? 401 : 503).json({
|
||||
ok: false,
|
||||
error: config.internalAccessToken ? "internal_handoff_unauthorized" : "internal_handoff_not_configured",
|
||||
error: configured ? "internal_handoff_unauthorized" : "internal_handoff_not_configured",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const token = typeof req.body?.token === "string" ? req.body.token : "";
|
||||
const serviceSlug = sanitizeServiceSlug(req.body?.serviceSlug);
|
||||
const handoff = consumeServiceHandoff(token, serviceSlug);
|
||||
|
||||
if (!handoff) {
|
||||
@@ -488,6 +495,7 @@ app.post("/api/internal/handoff/consume", (req, res) => {
|
||||
ok: true,
|
||||
serviceSlug,
|
||||
launcherSessionId: handoff.launcherSessionId ?? null,
|
||||
access: resolveDeviceCoreSessionAccess(snapshot.data, user, serviceSlug),
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
@@ -501,16 +509,17 @@ app.post("/api/internal/handoff/consume", (req, res) => {
|
||||
});
|
||||
|
||||
app.post("/api/internal/session/validate", (req, res) => {
|
||||
if (!isInternalRequestAuthorized(req)) {
|
||||
res.status(config.internalAccessToken ? 401 : 503).json({
|
||||
const serviceSlug = sanitizeServiceSlug(req.body?.serviceSlug);
|
||||
if (!isInternalRequestAuthorized(req, { serviceSlug })) {
|
||||
const configured = isInternalRequestConfigured(serviceSlug);
|
||||
res.status(configured ? 401 : 503).json({
|
||||
ok: false,
|
||||
active: false,
|
||||
error: config.internalAccessToken ? "internal_session_unauthorized" : "internal_session_not_configured",
|
||||
error: configured ? "internal_session_unauthorized" : "internal_session_not_configured",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const serviceSlug = sanitizeServiceSlug(req.body?.serviceSlug);
|
||||
const launcherSessionId = typeof req.body?.launcherSessionId === "string" ? req.body.launcherSessionId : "";
|
||||
|
||||
if (!launcherSessionId) {
|
||||
@@ -551,6 +560,7 @@ app.post("/api/internal/session/validate", (req, res) => {
|
||||
active: true,
|
||||
serviceSlug,
|
||||
launcherSessionId,
|
||||
access: resolveDeviceCoreSessionAccess(snapshot.data, user, serviceSlug),
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
@@ -674,6 +684,62 @@ app.post("/api/internal/access/check", (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
app.post("/api/ai-workspace/internal/v1/entitlements", (req, res) => {
|
||||
if (!isInternalRequestAuthorized(req)) {
|
||||
res.status(config.internalAccessToken ? 401 : 503).json({
|
||||
ok: false,
|
||||
error: config.internalAccessToken ? "ai_workspace_entitlement_unauthorized" : "internal_access_not_configured",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const snapshot = controlPlaneStore.getSnapshot({ name: "AI Workspace entitlement adapter", source: "ai-workspace" });
|
||||
const ownerLookup = aiWorkspaceEntitlementOwnerLookup(req.body);
|
||||
const user = findInternalAccessUser(snapshot.data, ownerLookup);
|
||||
const requestedAt = new Date().toISOString();
|
||||
|
||||
if (!user) {
|
||||
res.json({
|
||||
ok: true,
|
||||
schemaVersion: "ai-workspace.entitlement-response.v1",
|
||||
source: "launcher-control-plane",
|
||||
requestedAt,
|
||||
appGrants: buildAiWorkspaceDeniedAppGrants("launcher_user_not_found", requestedAt),
|
||||
user: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const groups = resolveRequiredGroups(snapshot.data, user);
|
||||
const apps = getAppsForUser(groups);
|
||||
const adminScope = resolveAdminScope(buildAssistantGatewaySessionUser(user, groups), groups);
|
||||
|
||||
res.json({
|
||||
ok: true,
|
||||
schemaVersion: "ai-workspace.entitlement-response.v1",
|
||||
source: "launcher-control-plane",
|
||||
requestedAt,
|
||||
appGrants: buildAiWorkspaceAppGrants({
|
||||
data: snapshot.data,
|
||||
user,
|
||||
groups,
|
||||
apps,
|
||||
adminScope,
|
||||
payload: req.body,
|
||||
requestedAt,
|
||||
}),
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
avatarUrl: user.avatarUrl ?? null,
|
||||
authentikUserId: user.authentikUserId ?? null,
|
||||
globalStatus: user.globalStatus,
|
||||
groups,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.post("/api/internal/tasker/invite-requests", asyncRoute(async (req, res) => {
|
||||
if (!isInternalRequestAuthorized(req)) {
|
||||
res.status(config.internalAccessToken ? 401 : 503).json({
|
||||
@@ -2143,6 +2209,14 @@ app.post("/api/admin/services", requireLauncherAdmin, requireRootLauncherAdmin,
|
||||
res.status(201).json(result);
|
||||
}));
|
||||
|
||||
app.put("/api/admin/services/registrations/:serviceSlug", requireLauncherAdmin, requireRootLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
await sendAdminIdempotentJson(req, res, async () => {
|
||||
const result = await controlPlaneStore.ensureService(req.params.serviceSlug, req.body, req.nodedcSession.user);
|
||||
publishControlPlaneEvent(result.created ? "admin.service.created" : "admin.service.updated");
|
||||
return result;
|
||||
});
|
||||
}));
|
||||
|
||||
app.patch("/api/admin/services/reorder", requireLauncherAdmin, requireRootLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.reorderServices(req.body, req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.service.reordered");
|
||||
@@ -2187,14 +2261,16 @@ app.post("/api/admin/access/grants", requireLauncherAdmin, asyncRoute(async (req
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await controlPlaneStore.upsertGrant(req.body, req.nodedcSession.user);
|
||||
const syncResult = await syncUsersToAuthentik(
|
||||
result.data,
|
||||
resolveGrantTargetUserIds(result.data, result.grant.targetType, result.grant.targetId),
|
||||
req.nodedcSession.user
|
||||
);
|
||||
publishControlPlaneEvent("admin.access.grant.updated", syncResult.userIds);
|
||||
res.json(scopeAdminMutationResult(req, { ...result, data: syncResult.data }));
|
||||
await sendAdminIdempotentJson(req, res, async () => {
|
||||
const result = await controlPlaneStore.upsertGrant(req.body, req.nodedcSession.user);
|
||||
const syncResult = await syncUsersToAuthentik(
|
||||
result.data,
|
||||
resolveGrantTargetUserIds(result.data, result.grant.targetType, result.grant.targetId),
|
||||
req.nodedcSession.user
|
||||
);
|
||||
publishControlPlaneEvent("admin.access.grant.updated", syncResult.userIds);
|
||||
return scopeAdminMutationResult(req, { ...result, data: syncResult.data });
|
||||
});
|
||||
}));
|
||||
|
||||
app.post("/api/admin/access/exceptions", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
@@ -2465,6 +2541,9 @@ function readConfig() {
|
||||
process.env.NODEDC_INTERNAL_ACCESS_TOKEN ??
|
||||
process.env.NODEDC_PLATFORM_SERVICE_TOKEN ??
|
||||
"",
|
||||
deviceCoreInternalAccessToken: readSecretFile(
|
||||
process.env.NODEDC_DEVICE_CORE_INTERNAL_TOKEN_FILE,
|
||||
),
|
||||
taskLogoutUrl:
|
||||
process.env.TASK_LOGOUT_URL ??
|
||||
`${(process.env.TASK_BASE_URL ?? `http://${process.env.TASK_DOMAIN ?? "task.local.nodedc"}`).replace(/\/$/, "")}/logout`,
|
||||
@@ -2483,6 +2562,13 @@ function readConfig() {
|
||||
};
|
||||
}
|
||||
|
||||
function readSecretFile(value) {
|
||||
const pathname = String(value || "").trim();
|
||||
if (!pathname) return "";
|
||||
const resolvedPath = isAbsolute(pathname) ? pathname : resolve(projectRoot, pathname);
|
||||
return readFileSync(resolvedPath, "utf8").trim();
|
||||
}
|
||||
|
||||
function ensureOidcConfigured() {
|
||||
if (!config.oidcConfigured) {
|
||||
throw new Error("Launcher OIDC is not configured. Set LAUNCHER_OIDC_ISSUER, LAUNCHER_OIDC_CLIENT_ID and LAUNCHER_OIDC_CLIENT_SECRET.");
|
||||
@@ -3052,6 +3138,207 @@ function getSessionAccessState(session) {
|
||||
}
|
||||
}
|
||||
|
||||
function aiWorkspaceEntitlementOwnerLookup(payload) {
|
||||
const source = isPlainRecord(payload) ? payload : {};
|
||||
const owner = isPlainRecord(source.owner) ? source.owner : {};
|
||||
const ownerKey = normalizeOptionalText(owner.ownerKey ?? owner.owner_key ?? source.ownerKey ?? source.owner_key);
|
||||
const ownerKeyParts = parseAiWorkspaceOwnerKey(ownerKey);
|
||||
|
||||
return {
|
||||
userId: normalizeOptionalText(owner.userId ?? owner.user_id ?? source.userId ?? source.user_id) ?? ownerKeyParts.userId,
|
||||
email: normalizeOptionalText(owner.email ?? source.email) ?? ownerKeyParts.email,
|
||||
subject: normalizeOptionalText(owner.subject ?? owner.sub ?? source.subject ?? source.sub) ?? ownerKeyParts.subject,
|
||||
};
|
||||
}
|
||||
|
||||
function parseAiWorkspaceOwnerKey(ownerKey) {
|
||||
const text = normalizeOptionalText(ownerKey) ?? "";
|
||||
if (text.startsWith("email:")) return { email: text.slice("email:".length), userId: null, subject: null };
|
||||
if (text.startsWith("user:")) return { email: null, userId: text.slice("user:".length), subject: null };
|
||||
return { email: null, userId: null, subject: text || null };
|
||||
}
|
||||
|
||||
function buildAiWorkspaceDeniedAppGrants(reason, requestedAt) {
|
||||
return {
|
||||
launcher: aiWorkspaceGrant({
|
||||
appId: "launcher",
|
||||
appTitle: "NODE.DC Launcher",
|
||||
allowed: false,
|
||||
reason,
|
||||
requestedAt,
|
||||
}),
|
||||
engine: aiWorkspaceGrant({
|
||||
appId: "engine",
|
||||
appTitle: "NODE.DC Engine / InJoin",
|
||||
allowed: false,
|
||||
reason,
|
||||
requestedAt,
|
||||
}),
|
||||
ops: aiWorkspaceGrant({
|
||||
appId: "ops",
|
||||
appTitle: "NODE.DC Ops / Tasker",
|
||||
allowed: false,
|
||||
reason,
|
||||
requestedAt,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function buildAiWorkspaceAppGrants({ data, user, groups, apps, adminScope, payload, requestedAt }) {
|
||||
const launcherApp = apps.find((candidate) => candidate.slug === "launcher");
|
||||
const opsApp = apps.find((candidate) => candidate.slug === "task-manager");
|
||||
const engineApp = apps.find((candidate) => isEngineServiceSlug(candidate.slug));
|
||||
const membership = resolveAiWorkspaceBestMembership(data, user);
|
||||
const opsWorkspaceSlug = resolveAiWorkspaceOpsWorkspaceSlug(payload);
|
||||
const opsServiceModules = aiWorkspaceAppAllowed(user, opsApp)
|
||||
? resolveTaskManagerWorkspaceServiceModules(data, user, "task-manager", opsWorkspaceSlug)
|
||||
: {};
|
||||
|
||||
const baseContext = {
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
launcherUserStatus: user.globalStatus ?? "active",
|
||||
groups,
|
||||
membershipRole: membership?.role ?? null,
|
||||
membershipStatus: membership?.status ?? null,
|
||||
coreAssistantRole: membership?.coreAssistantRole ?? null,
|
||||
};
|
||||
const adminContext = {
|
||||
...baseContext,
|
||||
adminScope: adminScope?.isRoot
|
||||
? "root"
|
||||
: adminScope?.clientIds?.size
|
||||
? "client"
|
||||
: "none",
|
||||
adminClientIds: adminScope?.clientIds ? Array.from(adminScope.clientIds).sort() : [],
|
||||
};
|
||||
|
||||
return {
|
||||
launcher: aiWorkspaceGrant({
|
||||
appId: "launcher",
|
||||
appTitle: "NODE.DC Launcher",
|
||||
surface: "launcher",
|
||||
allowed: aiWorkspaceAppAllowed(user, launcherApp),
|
||||
reason: aiWorkspaceAccessReason(user, launcherApp),
|
||||
scopes: aiWorkspaceLauncherScopes(adminScope),
|
||||
context: adminContext,
|
||||
requestedAt,
|
||||
}),
|
||||
engine: aiWorkspaceGrant({
|
||||
appId: "engine",
|
||||
appTitle: "NODE.DC Engine / InJoin",
|
||||
surface: "engine",
|
||||
allowed: aiWorkspaceAppAllowed(user, engineApp),
|
||||
reason: aiWorkspaceAccessReason(user, engineApp),
|
||||
scopes: ["engine:workspace:read", "engine:workflow:read"],
|
||||
context: {
|
||||
...baseContext,
|
||||
serviceSlug: engineApp?.slug ?? null,
|
||||
matchedGroups: engineApp?.matchedGroups ?? [],
|
||||
},
|
||||
requestedAt,
|
||||
}),
|
||||
ops: aiWorkspaceGrant({
|
||||
appId: "ops",
|
||||
appTitle: "NODE.DC Ops / Tasker",
|
||||
surface: "ops",
|
||||
allowed: aiWorkspaceAppAllowed(user, opsApp),
|
||||
reason: aiWorkspaceAccessReason(user, opsApp),
|
||||
scopes: [
|
||||
"ops:project:read",
|
||||
"ops:card:read",
|
||||
"ops:card:create",
|
||||
...(opsServiceModules.codex_agents ? ["ops:codex-agent:use"] : []),
|
||||
],
|
||||
context: {
|
||||
...baseContext,
|
||||
serviceSlug: opsApp?.slug ?? null,
|
||||
opsWorkspaceSlug,
|
||||
matchedGroups: opsApp?.matchedGroups ?? [],
|
||||
serviceModules: opsServiceModules,
|
||||
},
|
||||
requestedAt,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function aiWorkspaceGrant({ appId, appTitle, surface, allowed, reason, scopes = [], context = {}, requestedAt }) {
|
||||
return {
|
||||
appId,
|
||||
appTitle,
|
||||
surface: surface ?? appId,
|
||||
status: allowed ? "granted" : "denied",
|
||||
granted: Boolean(allowed),
|
||||
allowed: Boolean(allowed),
|
||||
enabled: Boolean(allowed),
|
||||
denied: !allowed,
|
||||
reason: allowed ? "launcher_access_confirmed" : reason,
|
||||
deniedReason: allowed ? null : reason,
|
||||
deniedText: allowed ? null : "Доступ к модулю ограничен, обратитесь к администратору системы.",
|
||||
scopes: allowed ? scopes : [],
|
||||
context,
|
||||
updatedAt: requestedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function aiWorkspaceAppAllowed(user, app) {
|
||||
return user?.globalStatus === "active" && Boolean(app?.hasAccess) && (app.status ?? "disabled") === "active";
|
||||
}
|
||||
|
||||
function aiWorkspaceAccessReason(user, app) {
|
||||
if (!user) return "launcher_user_not_found";
|
||||
if (user.globalStatus !== "active") return "launcher_user_blocked";
|
||||
if (!app) return "launcher_service_not_found";
|
||||
if (!app.hasAccess) return "launcher_service_access_denied";
|
||||
if ((app.status ?? "disabled") !== "active") return "launcher_service_inactive";
|
||||
return "launcher_access_confirmed";
|
||||
}
|
||||
|
||||
function aiWorkspaceLauncherScopes(adminScope) {
|
||||
const scopes = ["launcher:access:read", "assistant:use"];
|
||||
if (adminScope?.isRoot || adminScope?.clientIds?.size) {
|
||||
scopes.push(
|
||||
"launcher_admin_scope.any",
|
||||
"launcher_admin_scope.can_manage_user",
|
||||
"launcher_admin_scope.can_manage_membership",
|
||||
"launcher:users:read",
|
||||
"launcher:roles:read"
|
||||
);
|
||||
}
|
||||
if (adminScope?.isRoot) {
|
||||
scopes.push("launcher_admin_scope.root", "launcher:service-catalog:manage");
|
||||
}
|
||||
return [...new Set(scopes)].sort();
|
||||
}
|
||||
|
||||
function resolveAiWorkspaceBestMembership(data, user) {
|
||||
if (!user?.id) return null;
|
||||
return data.memberships
|
||||
.filter((membership) => membership.userId === user.id && membership.status === "active")
|
||||
.slice()
|
||||
.sort((left, right) => assistantMembershipWeight(right) - assistantMembershipWeight(left))[0] ?? null;
|
||||
}
|
||||
|
||||
function resolveAiWorkspaceOpsWorkspaceSlug(payload) {
|
||||
const source = isPlainRecord(payload) ? payload : {};
|
||||
const activeContext = isPlainRecord(source.activeContext) ? source.activeContext : {};
|
||||
const runContext = isPlainRecord(source.runContext) ? source.runContext : {};
|
||||
const activeOps = isPlainRecord(activeContext.ops) ? activeContext.ops : {};
|
||||
const runOps = isPlainRecord(runContext.contexts?.ops)
|
||||
? runContext.contexts.ops
|
||||
: isPlainRecord(runContext.ops)
|
||||
? runContext.ops
|
||||
: {};
|
||||
return normalizeOptionalText(
|
||||
runOps.opsWorkspaceSlug ??
|
||||
runOps.workspaceSlug ??
|
||||
activeOps.opsWorkspaceSlug ??
|
||||
activeOps.workspaceSlug ??
|
||||
source.opsWorkspaceSlug ??
|
||||
source.workspaceSlug
|
||||
);
|
||||
}
|
||||
|
||||
function getAppsForUser(userGroups) {
|
||||
const groupSet = new Set(userGroups);
|
||||
const catalog = getAppCatalog();
|
||||
@@ -3090,6 +3377,7 @@ function getAppCatalog() {
|
||||
url: getServiceUrl(service),
|
||||
openUrl: getServiceUrl(service),
|
||||
launchTargetUrl: getServiceLaunchTargetUrl(service),
|
||||
authHandoffPath: service.authHandoffPath || null,
|
||||
status: service.status ?? "disabled",
|
||||
provider: "authentik",
|
||||
requiredGroups,
|
||||
@@ -3148,7 +3436,12 @@ function specialRequiredGroups(serviceOrSlug) {
|
||||
}
|
||||
|
||||
function getServiceUrl(service) {
|
||||
if (service.slug === "task-manager" || isEngineServiceSlug(service.slug) || isBimViewerServiceSlug(service.slug)) {
|
||||
if (
|
||||
service.slug === "task-manager" ||
|
||||
isEngineServiceSlug(service.slug) ||
|
||||
isBimViewerServiceSlug(service.slug) ||
|
||||
service.authHandoffPath
|
||||
) {
|
||||
return `/api/services/${encodeURIComponent(service.slug)}/launch`;
|
||||
}
|
||||
|
||||
@@ -3156,6 +3449,14 @@ function getServiceUrl(service) {
|
||||
}
|
||||
|
||||
function getServiceLaunchTargetUrl(service) {
|
||||
// Catalog entries replace `url` with the Launcher launch route for services
|
||||
// that need a handoff. Keep their external origin separately so a relative
|
||||
// handoff path is always resolved against the target application, never the
|
||||
// internal `/api/services/:slug/launch` route.
|
||||
if (service?.launchTargetUrl) {
|
||||
return service.launchTargetUrl;
|
||||
}
|
||||
|
||||
if (isEngineServiceSlug(service?.slug)) {
|
||||
return service.launchUrl || service.url || getEnginePublicBaseUrl();
|
||||
}
|
||||
@@ -3243,6 +3544,25 @@ function redirectToServiceLaunchTarget(res, serviceSlug, runtimeContext, app, re
|
||||
return;
|
||||
}
|
||||
|
||||
// Module Foundry and future internal services use the same Launcher-owned
|
||||
// session contract as BIM. The path is service metadata, so the launcher
|
||||
// does not grow a separate authentication mechanism per module.
|
||||
const handoffPath = String(app?.authHandoffPath || "").trim();
|
||||
if (handoffPath) {
|
||||
const handoffToken = createServiceHandoff(serviceSlug, runtimeContext.user, { launcherSessionId: session?.id });
|
||||
const targetUrl = new URL(handoffPath, getServiceLaunchTargetUrl(app));
|
||||
const nextPath = sanitizeReturnTo(returnTo);
|
||||
|
||||
targetUrl.searchParams.set("token", handoffToken);
|
||||
|
||||
if (nextPath && nextPath !== "/") {
|
||||
targetUrl.searchParams.set("next_path", nextPath);
|
||||
}
|
||||
|
||||
res.redirect(targetUrl.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
if (serviceSlug !== "task-manager") {
|
||||
res.redirect(app.openUrl || app.url || "/");
|
||||
return;
|
||||
@@ -4583,28 +4903,24 @@ function readRequestHeader(req, name) {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function isInternalRequestAuthorized(req) {
|
||||
if (!config.internalAccessToken) {
|
||||
return false;
|
||||
}
|
||||
|
||||
function isInternalRequestAuthorized(req, { serviceSlug = "" } = {}) {
|
||||
const authorization = typeof req.headers.authorization === "string" ? req.headers.authorization : "";
|
||||
const bearerToken = authorization.match(/^Bearer\s+(.+)$/i)?.[1] ?? "";
|
||||
const headerToken = typeof req.headers["x-nodedc-internal-token"] === "string" ? req.headers["x-nodedc-internal-token"] : "";
|
||||
const requestToken = bearerToken || headerToken;
|
||||
|
||||
return safeTokenEquals(requestToken, config.internalAccessToken);
|
||||
return isInternalRequestTokenAuthorized({
|
||||
authorization,
|
||||
headerToken,
|
||||
globalToken: config.internalAccessToken,
|
||||
scopedToken: config.deviceCoreInternalAccessToken,
|
||||
serviceSlug,
|
||||
});
|
||||
}
|
||||
|
||||
function safeTokenEquals(actual, expected) {
|
||||
if (!actual || !expected) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const actualBuffer = Buffer.from(String(actual));
|
||||
const expectedBuffer = Buffer.from(String(expected));
|
||||
|
||||
return actualBuffer.length === expectedBuffer.length && timingSafeEqual(actualBuffer, expectedBuffer);
|
||||
function isInternalRequestConfigured(serviceSlug = "") {
|
||||
return isInternalRequestTokenConfigured({
|
||||
globalToken: config.internalAccessToken,
|
||||
scopedToken: config.deviceCoreInternalAccessToken,
|
||||
serviceSlug,
|
||||
});
|
||||
}
|
||||
|
||||
function findInternalAccessUser(data, payload) {
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
const administrativeMembershipRoles = new Set(["client_owner", "client_admin"]);
|
||||
const administrativeAppRoles = new Set(["owner", "admin"]);
|
||||
const appRoleWeights = Object.freeze({ viewer: 10, member: 20, admin: 30, owner: 40 });
|
||||
|
||||
export function resolveDeviceCoreSessionAccess(data, user, serviceSlug = "device-core") {
|
||||
const empty = Object.freeze({ allowed: false, hubRole: "viewer", ownerScopes: Object.freeze([]) });
|
||||
if (!data || !user || user.globalStatus !== "active") return empty;
|
||||
|
||||
const service = data.services?.find((candidate) => candidate.slug === serviceSlug);
|
||||
if (!service || service.status !== "active") return empty;
|
||||
if (hasUserException(data, user.id, service.id, "deny")) return empty;
|
||||
|
||||
const ownerScopes = [];
|
||||
const roles = [];
|
||||
const isRoot = user.id === "user_root";
|
||||
const directGrant = activeGrant(data, service.id, "user", user.id);
|
||||
const explicitlyAllowed = hasUserException(data, user.id, service.id, "allow");
|
||||
|
||||
if (isRoot) {
|
||||
roles.push("owner");
|
||||
} else if (explicitlyAllowed) {
|
||||
roles.push("member");
|
||||
} else if (directGrant) {
|
||||
roles.push(directGrant.appRole);
|
||||
}
|
||||
|
||||
for (const membership of data.memberships ?? []) {
|
||||
if (membership.userId !== user.id || membership.status !== "active") continue;
|
||||
const client = data.clients?.find((candidate) => candidate.id === membership.clientId);
|
||||
if (!client || ["suspended", "expired"].includes(client.status)) continue;
|
||||
|
||||
const clientGroupIds = new Set(
|
||||
(data.groups ?? [])
|
||||
.filter((group) => group.clientId === client.id && group.memberIds?.includes(user.id))
|
||||
.map((group) => group.id),
|
||||
);
|
||||
const groupGrant = (data.grants ?? []).find((grant) =>
|
||||
grant.serviceId === service.id
|
||||
&& grant.targetType === "group"
|
||||
&& clientGroupIds.has(grant.targetId)
|
||||
&& grant.status === "active");
|
||||
const clientGrant = activeGrant(data, service.id, "client", client.id);
|
||||
const scopedGrant = groupGrant || clientGrant;
|
||||
|
||||
if (!explicitlyAllowed && scopedGrant) roles.push(scopedGrant.appRole);
|
||||
if (
|
||||
client.type === "company"
|
||||
&& administrativeMembershipRoles.has(membership.role)
|
||||
&& (isRoot || (!explicitlyAllowed && administrativeAppRoles.has(scopedGrant?.appRole)))
|
||||
) {
|
||||
ownerScopes.push({
|
||||
scopeKind: "company",
|
||||
ownerRef: `client:${client.id}`,
|
||||
displayName: String(client.name || client.legalName || client.id).trim().slice(0, 240),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const hubRole = strongestRole(roles);
|
||||
if (!hubRole) return empty;
|
||||
if (administrativeAppRoles.has(hubRole)) {
|
||||
ownerScopes.push({
|
||||
scopeKind: "personal",
|
||||
ownerRef: `user:${user.id}`,
|
||||
displayName: String(user.name || user.email || user.id).trim().slice(0, 240),
|
||||
});
|
||||
}
|
||||
|
||||
return Object.freeze({
|
||||
allowed: true,
|
||||
hubRole,
|
||||
ownerScopes: Object.freeze(uniqueOwnerScopes(ownerScopes)),
|
||||
});
|
||||
}
|
||||
|
||||
function activeGrant(data, serviceId, targetType, targetId) {
|
||||
return (data.grants ?? []).find((grant) =>
|
||||
grant.serviceId === serviceId
|
||||
&& grant.targetType === targetType
|
||||
&& grant.targetId === targetId
|
||||
&& grant.status === "active") ?? null;
|
||||
}
|
||||
|
||||
function hasUserException(data, userId, serviceId, type) {
|
||||
return (data.exceptions ?? []).some((exception) =>
|
||||
exception.serviceId === serviceId
|
||||
&& exception.userId === userId
|
||||
&& exception.type === type);
|
||||
}
|
||||
|
||||
function strongestRole(roles) {
|
||||
return roles
|
||||
.filter((role) => Object.hasOwn(appRoleWeights, role))
|
||||
.sort((left, right) => appRoleWeights[right] - appRoleWeights[left])[0] ?? null;
|
||||
}
|
||||
|
||||
function uniqueOwnerScopes(scopes) {
|
||||
const byIdentity = new Map();
|
||||
for (const scope of scopes) byIdentity.set(`${scope.scopeKind}\0${scope.ownerRef}`, scope);
|
||||
return [...byIdentity.values()].sort((left, right) =>
|
||||
`${left.scopeKind}:${left.ownerRef}`.localeCompare(`${right.scopeKind}:${right.ownerRef}`));
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveDeviceCoreSessionAccess } from "./device-core-session-access.mjs";
|
||||
|
||||
const service = {
|
||||
id: "service_device_core",
|
||||
slug: "device-core",
|
||||
status: "active",
|
||||
};
|
||||
const user = {
|
||||
id: "user_device_admin",
|
||||
email: "admin@example.test",
|
||||
name: "Device Admin",
|
||||
globalStatus: "active",
|
||||
};
|
||||
const company = {
|
||||
id: "client_dctouch",
|
||||
type: "company",
|
||||
name: "DC Touch",
|
||||
status: "active",
|
||||
};
|
||||
const membership = {
|
||||
id: "membership_device_admin",
|
||||
clientId: company.id,
|
||||
userId: user.id,
|
||||
role: "client_admin",
|
||||
status: "active",
|
||||
};
|
||||
|
||||
function data(overrides = {}) {
|
||||
return {
|
||||
services: [service],
|
||||
users: [user],
|
||||
clients: [company],
|
||||
memberships: [membership],
|
||||
groups: [],
|
||||
grants: [{
|
||||
id: "grant_device_core_dctouch",
|
||||
serviceId: service.id,
|
||||
targetType: "client",
|
||||
targetId: company.id,
|
||||
appRole: "admin",
|
||||
status: "active",
|
||||
}],
|
||||
exceptions: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("Device Core trusted session access", () => {
|
||||
it("projects an administrative company scope only from an active scoped grant", () => {
|
||||
expect(resolveDeviceCoreSessionAccess(data(), user)).toEqual({
|
||||
allowed: true,
|
||||
hubRole: "admin",
|
||||
ownerScopes: [
|
||||
{
|
||||
scopeKind: "company",
|
||||
ownerRef: "client:client_dctouch",
|
||||
displayName: "DC Touch",
|
||||
},
|
||||
{
|
||||
scopeKind: "personal",
|
||||
ownerRef: "user:user_device_admin",
|
||||
displayName: "Device Admin",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("does not turn company membership alone into a Device Core owner claim", () => {
|
||||
const access = resolveDeviceCoreSessionAccess(data({ grants: [] }), user);
|
||||
expect(access).toEqual({ allowed: false, hubRole: "viewer", ownerScopes: [] });
|
||||
});
|
||||
|
||||
it("keeps member and viewer grants out of administrative owner scopes", () => {
|
||||
for (const appRole of ["member", "viewer"]) {
|
||||
const access = resolveDeviceCoreSessionAccess(data({
|
||||
grants: [{
|
||||
id: `grant_${appRole}`,
|
||||
serviceId: service.id,
|
||||
targetType: "client",
|
||||
targetId: company.id,
|
||||
appRole,
|
||||
status: "active",
|
||||
}],
|
||||
}), user);
|
||||
expect(access.allowed).toBe(true);
|
||||
expect(access.hubRole).toBe(appRole);
|
||||
expect(access.ownerScopes).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
it("fails closed on a deny exception even when grants exist", () => {
|
||||
expect(resolveDeviceCoreSessionAccess(data({
|
||||
exceptions: [{
|
||||
id: "deny_device_core",
|
||||
serviceId: service.id,
|
||||
userId: user.id,
|
||||
type: "deny",
|
||||
}],
|
||||
}), user)).toEqual({ allowed: false, hubRole: "viewer", ownerScopes: [] });
|
||||
});
|
||||
|
||||
it("keeps an individual allow exception at member privilege", () => {
|
||||
expect(resolveDeviceCoreSessionAccess(data({
|
||||
exceptions: [{
|
||||
id: "allow_device_core",
|
||||
serviceId: service.id,
|
||||
userId: user.id,
|
||||
type: "allow",
|
||||
}],
|
||||
}), user)).toEqual({ allowed: true, hubRole: "member", ownerScopes: [] });
|
||||
});
|
||||
|
||||
it("does not leak a grant from one company into another company scope", () => {
|
||||
const secondCompany = { ...company, id: "client_other", name: "Other Company" };
|
||||
const secondMembership = { ...membership, id: "membership_other", clientId: secondCompany.id };
|
||||
const access = resolveDeviceCoreSessionAccess(data({
|
||||
clients: [company, secondCompany],
|
||||
memberships: [membership, secondMembership],
|
||||
}), user);
|
||||
expect(access.ownerScopes.some((scope) => scope.ownerRef === "client:client_other")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
|
||||
export function isInternalRequestTokenAuthorized({
|
||||
authorization = "",
|
||||
headerToken = "",
|
||||
globalToken = "",
|
||||
scopedToken = "",
|
||||
serviceSlug = "",
|
||||
scopedServiceSlug = "device-core",
|
||||
} = {}) {
|
||||
const bearerToken = String(authorization).match(/^Bearer\s+(.+)$/i)?.[1] ?? "";
|
||||
const requestToken = bearerToken || String(headerToken || "");
|
||||
if (safeTokenEquals(requestToken, globalToken)) return true;
|
||||
return serviceSlug === scopedServiceSlug
|
||||
&& safeTokenEquals(requestToken, scopedToken);
|
||||
}
|
||||
|
||||
export function isInternalRequestTokenConfigured({
|
||||
globalToken = "",
|
||||
scopedToken = "",
|
||||
serviceSlug = "",
|
||||
scopedServiceSlug = "device-core",
|
||||
} = {}) {
|
||||
return Boolean(globalToken || (serviceSlug === scopedServiceSlug && scopedToken));
|
||||
}
|
||||
|
||||
function safeTokenEquals(actual, expected) {
|
||||
if (!actual || !expected) return false;
|
||||
const actualBuffer = Buffer.from(String(actual));
|
||||
const expectedBuffer = Buffer.from(String(expected));
|
||||
return actualBuffer.length === expectedBuffer.length
|
||||
&& timingSafeEqual(actualBuffer, expectedBuffer);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
isInternalRequestTokenAuthorized,
|
||||
isInternalRequestTokenConfigured,
|
||||
} from "./internal-request-auth.mjs";
|
||||
|
||||
describe("scoped internal request authorization", () => {
|
||||
it("accepts the Device Core key only for Device Core handoff calls", () => {
|
||||
const base = {
|
||||
authorization: "Bearer device-core-file-token",
|
||||
globalToken: "broad-platform-token",
|
||||
scopedToken: "device-core-file-token",
|
||||
};
|
||||
expect(isInternalRequestTokenAuthorized({ ...base, serviceSlug: "device-core" })).toBe(true);
|
||||
expect(isInternalRequestTokenAuthorized({ ...base, serviceSlug: "module-foundry" })).toBe(false);
|
||||
expect(isInternalRequestTokenAuthorized(base)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the existing global token valid for existing internal callers", () => {
|
||||
expect(isInternalRequestTokenAuthorized({
|
||||
authorization: "Bearer broad-platform-token",
|
||||
globalToken: "broad-platform-token",
|
||||
scopedToken: "device-core-file-token",
|
||||
serviceSlug: "module-foundry",
|
||||
})).toBe(true);
|
||||
});
|
||||
|
||||
it("reports scoped configuration only for the bound service", () => {
|
||||
expect(isInternalRequestTokenConfigured({
|
||||
scopedToken: "device-core-file-token",
|
||||
serviceSlug: "device-core",
|
||||
})).toBe(true);
|
||||
expect(isInternalRequestTokenConfigured({
|
||||
scopedToken: "device-core-file-token",
|
||||
serviceSlug: "operational-core",
|
||||
})).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -39,6 +39,7 @@ import {
|
||||
updateAdminService,
|
||||
updateAdminSettings,
|
||||
updateAdminUserProfile,
|
||||
upsertAdminGrant,
|
||||
type ControlPlaneMutationResult,
|
||||
type TaskManagerWorkspaceMemberRole,
|
||||
type TaskManagerWorkspaceSummary,
|
||||
@@ -68,8 +69,10 @@ import { subscribeToNodeDCLogoutEvents } from "../shared/session/sessionSync";
|
||||
import { loadPersistedLauncherData } from "../shared/api/storageApi";
|
||||
import type {
|
||||
AccessAssignmentValue,
|
||||
ClientGrantAssignmentValue,
|
||||
CreateUserCommand,
|
||||
EnsureTaskManagerProjectMemberCommand,
|
||||
SetClientServiceGrantCommand,
|
||||
SetServiceModuleEntitlementCommand,
|
||||
SetUserServiceAccessCommand,
|
||||
} from "../widgets/admin-overlay/AdminOverlay";
|
||||
@@ -110,6 +113,7 @@ export function LauncherApp() {
|
||||
const [runtimeReady, setRuntimeReady] = useState(false);
|
||||
const [profileSettingsOpen, setProfileSettingsOpen] = useState(false);
|
||||
const [pendingAccessAssignments, setPendingAccessAssignments] = useState<Record<string, AccessAssignmentValue>>({});
|
||||
const [pendingClientGrantAssignments, setPendingClientGrantAssignments] = useState<Record<string, ClientGrantAssignmentValue>>({});
|
||||
const [pendingServiceModuleEntitlements, setPendingServiceModuleEntitlements] = useState<Record<string, boolean>>({});
|
||||
const [pendingTaskManagerMemberships, setPendingTaskManagerMemberships] = useState<Record<string, boolean>>({});
|
||||
const [pendingTaskManagerProjectMemberships, setPendingTaskManagerProjectMemberships] = useState<Record<string, boolean>>({});
|
||||
@@ -580,6 +584,39 @@ export function LauncherApp() {
|
||||
});
|
||||
}
|
||||
|
||||
function handleSetClientServiceGrant({ clientId, serviceId, value }: SetClientServiceGrantCommand) {
|
||||
const assignmentKey = `${clientId}:${serviceId}`;
|
||||
|
||||
if (pendingClientGrantAssignments[assignmentKey] !== undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingGrant = data.grants.find((grant) =>
|
||||
grant.targetType === "client"
|
||||
&& grant.targetId === clientId
|
||||
&& grant.serviceId === serviceId);
|
||||
const appRole = value === "unset" ? (existingGrant?.appRole ?? "member") : value;
|
||||
const status = value === "unset" ? "disabled" : "active";
|
||||
|
||||
setPendingClientGrantAssignments((current) => ({ ...current, [assignmentKey]: value }));
|
||||
upsertAdminGrant(
|
||||
{ serviceId, targetType: "client", targetId: clientId, appRole, status },
|
||||
`launcher-client-grant:${clientId}:${serviceId}:${crypto.randomUUID()}`
|
||||
)
|
||||
.then((result) => {
|
||||
setData(syncLauncherServiceLinks(result.data));
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
console.warn(error instanceof Error ? error.message : "Не удалось обновить доступ контура");
|
||||
})
|
||||
.finally(() => {
|
||||
setPendingClientGrantAssignments((current) => {
|
||||
const { [assignmentKey]: _completed, ...rest } = current;
|
||||
return rest;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function handleSetServiceModuleEntitlement(command: SetServiceModuleEntitlementCommand) {
|
||||
const entitlementKey = `${command.userId}:${command.serviceId}:${command.moduleId}`;
|
||||
|
||||
@@ -992,6 +1029,7 @@ export function LauncherApp() {
|
||||
setAdminOpen(false);
|
||||
}}
|
||||
onSetUserServiceAccess={handleSetUserServiceAccess}
|
||||
onSetClientServiceGrant={handleSetClientServiceGrant}
|
||||
onCreateInvite={handleCreateInvite}
|
||||
onUpdateInvite={handleUpdateInvite}
|
||||
onDeleteInvite={handleDeleteInvite}
|
||||
@@ -1012,6 +1050,7 @@ export function LauncherApp() {
|
||||
onUpdateMembership={handleUpdateMembership}
|
||||
onDeleteMembership={handleDeleteMembership}
|
||||
pendingAccessAssignments={pendingAccessAssignments}
|
||||
pendingClientGrantAssignments={pendingClientGrantAssignments}
|
||||
pendingServiceModuleEntitlements={pendingServiceModuleEntitlements}
|
||||
onCreateGroup={handleCreateGroup}
|
||||
onUpdateGroup={handleUpdateGroup}
|
||||
|
||||
@@ -122,6 +122,71 @@ describe("computeEffectiveAccess", () => {
|
||||
expect(result.source).toBe("user");
|
||||
});
|
||||
|
||||
it("supports a personal client without making the service globally available", () => {
|
||||
const personalClient: Client = {
|
||||
...client,
|
||||
id: "client_personal_a",
|
||||
type: "person",
|
||||
name: "Личный контур пользователя",
|
||||
};
|
||||
const personalMembership: ClientMembership = {
|
||||
...membership,
|
||||
id: "membership_personal_a",
|
||||
clientId: personalClient.id,
|
||||
};
|
||||
const result = computeEffectiveAccess({
|
||||
...baseInput,
|
||||
client: personalClient,
|
||||
membership: personalMembership,
|
||||
userGroups: [],
|
||||
grants: [grant("client", personalClient.id)],
|
||||
});
|
||||
|
||||
expect(result.allowed).toBe(true);
|
||||
expect(result.source).toBe("client");
|
||||
});
|
||||
|
||||
it("isolates an open-pool user grant from other users in the same pool", () => {
|
||||
const publicPoolClient: Client = {
|
||||
...client,
|
||||
id: "client_public_pool",
|
||||
name: "Открытый контур",
|
||||
};
|
||||
const publicPoolMembership: ClientMembership = {
|
||||
...membership,
|
||||
id: "membership_public_pool_a",
|
||||
clientId: publicPoolClient.id,
|
||||
};
|
||||
const granted = computeEffectiveAccess({
|
||||
...baseInput,
|
||||
client: publicPoolClient,
|
||||
membership: publicPoolMembership,
|
||||
userGroups: [],
|
||||
grants: [grant("user", user.id)],
|
||||
});
|
||||
const otherUser: LauncherUser = {
|
||||
...user,
|
||||
id: "user_b",
|
||||
email: "other@example.ru",
|
||||
};
|
||||
const isolated = computeEffectiveAccess({
|
||||
...baseInput,
|
||||
client: publicPoolClient,
|
||||
user: otherUser,
|
||||
membership: {
|
||||
...publicPoolMembership,
|
||||
id: "membership_public_pool_b",
|
||||
userId: otherUser.id,
|
||||
},
|
||||
userGroups: [],
|
||||
grants: [grant("user", user.id)],
|
||||
});
|
||||
|
||||
expect(granted.allowed).toBe(true);
|
||||
expect(granted.source).toBe("user");
|
||||
expect(isolated.allowed).toBe(false);
|
||||
});
|
||||
|
||||
it("deny exception overrides user grant", () => {
|
||||
const result = computeEffectiveAccess({
|
||||
...baseInput,
|
||||
@@ -133,6 +198,26 @@ describe("computeEffectiveAccess", () => {
|
||||
expect(result.source).toBe("exception");
|
||||
});
|
||||
|
||||
it.each(["hidden", "disabled"] as const)("blocks a %s service even when a grant exists", (status) => {
|
||||
const result = computeEffectiveAccess({
|
||||
...baseInput,
|
||||
service: { ...service, status },
|
||||
grants: [grant("client", client.id)],
|
||||
});
|
||||
|
||||
expect(result.allowed).toBe(false);
|
||||
expect(result.visible).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores an inactive entitlement", () => {
|
||||
const result = computeEffectiveAccess({
|
||||
...baseInput,
|
||||
grants: [{ ...grant("client", client.id), status: "disabled" }],
|
||||
});
|
||||
|
||||
expect(result.allowed).toBe(false);
|
||||
});
|
||||
|
||||
it("maintenance service is visible but openEnabled is false", () => {
|
||||
const result = computeEffectiveAccess({
|
||||
...baseInput,
|
||||
|
||||
@@ -31,6 +31,11 @@ export interface Service {
|
||||
order: number;
|
||||
authentikApplicationSlug?: string | null;
|
||||
authentikGroupName?: string | null;
|
||||
/**
|
||||
* Relative handoff endpoint on the target app. Services using the shared
|
||||
* Launcher/Authentik session path never expose a standalone browser token.
|
||||
*/
|
||||
authHandoffPath?: string | null;
|
||||
isAvailableForAllNewClients?: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
|
||||
@@ -49,6 +49,16 @@ describe("assistant-ready Launcher admin routes", () => {
|
||||
expect(builderBlock).toContain("hasAlternativeAssistantAdminPath");
|
||||
});
|
||||
|
||||
it("exposes AI Workspace entitlements only through internal auth", () => {
|
||||
const block = sourceBlock('app.post("/api/ai-workspace/internal/v1/entitlements"', 'app.post("/api/internal/tasker/invite-requests"');
|
||||
|
||||
expect(block).toContain("isInternalRequestAuthorized(req)");
|
||||
expect(block).toContain("aiWorkspaceEntitlementOwnerLookup(req.body)");
|
||||
expect(block).toContain("buildAiWorkspaceAppGrants");
|
||||
expect(block).toContain('schemaVersion: "ai-workspace.entitlement-response.v1"');
|
||||
expect(block).toContain("appGrants");
|
||||
});
|
||||
|
||||
it("keeps user profile mutation guarded, idempotent, audited, and scoped", () => {
|
||||
const block = sourceBlock('app.patch("/api/admin/users/:userId/profile"', 'app.delete("/api/admin/users/:userId"');
|
||||
|
||||
@@ -71,6 +81,28 @@ describe("assistant-ready Launcher admin routes", () => {
|
||||
expect(block).toContain("scopeAdminMutationResult");
|
||||
});
|
||||
|
||||
it("keeps generic service registration root-guarded and idempotent", () => {
|
||||
const block = sourceBlock(
|
||||
'app.put("/api/admin/services/registrations/:serviceSlug"',
|
||||
'app.patch("/api/admin/services/reorder"'
|
||||
);
|
||||
|
||||
expect(block).toContain("requireLauncherAdmin");
|
||||
expect(block).toContain("requireRootLauncherAdmin");
|
||||
expect(block).toContain("sendAdminIdempotentJson");
|
||||
expect(block).toContain("controlPlaneStore.ensureService");
|
||||
});
|
||||
|
||||
it("keeps service grants idempotent and outside the assistant gateway allowlist", () => {
|
||||
const block = sourceBlock('app.post("/api/admin/access/grants"', 'app.post("/api/admin/access/exceptions"');
|
||||
const allowlistBlock = sourceBlock("const assistantGatewayAdminRouteAllowlist = [", "];",);
|
||||
|
||||
expect(block).toContain("sendAdminIdempotentJson");
|
||||
expect(block).toContain("controlPlaneStore.upsertGrant");
|
||||
expect(allowlistBlock).not.toContain("/api/admin/services/registrations");
|
||||
expect(allowlistBlock).not.toContain("/api/admin/access/grants");
|
||||
});
|
||||
|
||||
it("keeps hard delete routes outside assistant-ready routes and root-guarded where available", () => {
|
||||
const userDeleteBlock = sourceBlock('app.delete("/api/admin/users/:userId"', 'app.post("/api/admin/users/:userId/provision-authentik"');
|
||||
|
||||
|
||||
@@ -334,6 +334,21 @@ export async function createAdminService(payload: Partial<Service> = {}): Promis
|
||||
});
|
||||
}
|
||||
|
||||
export async function registerAdminService(
|
||||
serviceSlug: string,
|
||||
payload: Partial<Service>,
|
||||
idempotencyKey: string
|
||||
): Promise<ControlPlaneMutationResult & { created: boolean; service: Service }> {
|
||||
return requestJson<ControlPlaneMutationResult & { created: boolean; service: Service }>(
|
||||
`/api/admin/services/registrations/${encodeURIComponent(serviceSlug)}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: { "Idempotency-Key": idempotencyKey },
|
||||
body: JSON.stringify(payload),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateAdminService(serviceId: string, patch: Partial<Service>): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>(`/api/admin/services/${encodeURIComponent(serviceId)}`, {
|
||||
method: "PATCH",
|
||||
@@ -478,9 +493,10 @@ export async function setAdminServiceModuleEntitlement(payload: {
|
||||
});
|
||||
}
|
||||
|
||||
export async function upsertAdminGrant(payload: Partial<ServiceGrant>): Promise<ControlPlaneMutationResult> {
|
||||
export async function upsertAdminGrant(payload: Partial<ServiceGrant>, idempotencyKey?: string): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>("/api/admin/access/grants", {
|
||||
method: "POST",
|
||||
headers: idempotencyKey ? { "Idempotency-Key": idempotencyKey } : undefined,
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3324,6 +3324,36 @@ code {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.service-integration-heading {
|
||||
margin-top: 0.2rem;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
||||
padding-top: 0.9rem;
|
||||
}
|
||||
|
||||
.service-integration-heading strong {
|
||||
color: var(--text-primary);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.service-content-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.65rem;
|
||||
min-height: 2.7rem;
|
||||
border-radius: 1rem;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
padding: 0.7rem 0.85rem;
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.78rem;
|
||||
font-weight: 750;
|
||||
}
|
||||
|
||||
.service-content-toggle input {
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.service-content-field span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -3640,6 +3670,42 @@ code {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.client-service-grants {
|
||||
grid-column: 1 / -1;
|
||||
min-width: 0;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.client-service-grants__grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
|
||||
gap: 0.55rem;
|
||||
}
|
||||
|
||||
.client-service-grant {
|
||||
display: grid;
|
||||
width: 100%;
|
||||
min-height: 3.5rem;
|
||||
align-content: center;
|
||||
gap: 0.18rem;
|
||||
border: 0;
|
||||
border-radius: 1rem;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: var(--text-primary);
|
||||
padding: 0.65rem 0.8rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.client-service-grant:hover,
|
||||
.client-service-grant[aria-expanded="true"] {
|
||||
background: rgba(255, 255, 255, 0.11);
|
||||
}
|
||||
|
||||
.client-service-grant span {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
.access-tabs-card {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const overlaySource = readFileSync(resolve(process.cwd(), "src/widgets/admin-overlay/AdminOverlay.tsx"), "utf8");
|
||||
const appSource = readFileSync(resolve(process.cwd(), "src/app/LauncherApp.tsx"), "utf8");
|
||||
|
||||
describe("generic service control-plane administration", () => {
|
||||
it("edits every Launcher handoff identity through the generic service editor", () => {
|
||||
for (const marker of [
|
||||
"Authentik application slug",
|
||||
"Authentik group",
|
||||
"Handoff path",
|
||||
"Login sync URL",
|
||||
"Logout URL",
|
||||
"isAvailableForAllNewClients",
|
||||
]) {
|
||||
expect(overlaySource).toContain(marker);
|
||||
}
|
||||
|
||||
expect(overlaySource).not.toContain("DEVICE CORE</");
|
||||
expect(overlaySource).not.toContain("device-core</");
|
||||
});
|
||||
|
||||
it("manages a company-wide grant separately from personal access cells", () => {
|
||||
expect(overlaySource).toContain("Доступ контура · {matrix.client.name}");
|
||||
expect(overlaySource).toContain("onSetClientServiceGrant");
|
||||
expect(appSource).toContain("upsertAdminGrant(");
|
||||
expect(appSource).toContain('targetType: "client"');
|
||||
expect(appSource).toContain('value === "unset" ? "disabled" : "active"');
|
||||
expect(appSource).toContain("crypto.randomUUID()");
|
||||
});
|
||||
});
|
||||
@@ -117,6 +117,14 @@ export interface SetUserServiceAccessCommand {
|
||||
value: AccessAssignmentValue;
|
||||
}
|
||||
|
||||
export type ClientGrantAssignmentValue = Exclude<AccessAssignmentValue, "deny">;
|
||||
|
||||
export interface SetClientServiceGrantCommand {
|
||||
clientId: string;
|
||||
serviceId: string;
|
||||
value: ClientGrantAssignmentValue;
|
||||
}
|
||||
|
||||
export interface SetServiceModuleEntitlementCommand {
|
||||
clientId: string;
|
||||
userId: string;
|
||||
@@ -208,6 +216,7 @@ export function AdminOverlay({
|
||||
activeClientId,
|
||||
onClose,
|
||||
onSetUserServiceAccess,
|
||||
onSetClientServiceGrant,
|
||||
onCreateInvite,
|
||||
onUpdateInvite,
|
||||
onDeleteInvite,
|
||||
@@ -228,6 +237,7 @@ export function AdminOverlay({
|
||||
onUpdateMembership,
|
||||
onDeleteMembership,
|
||||
pendingAccessAssignments,
|
||||
pendingClientGrantAssignments,
|
||||
pendingServiceModuleEntitlements,
|
||||
onCreateGroup,
|
||||
onUpdateGroup,
|
||||
@@ -253,6 +263,7 @@ export function AdminOverlay({
|
||||
activeClientId: string;
|
||||
onClose: () => void;
|
||||
onSetUserServiceAccess: (command: SetUserServiceAccessCommand) => void;
|
||||
onSetClientServiceGrant: (command: SetClientServiceGrantCommand) => void;
|
||||
onCreateInvite: (invite: Pick<Invite, "clientId" | "email" | "role">) => void;
|
||||
onUpdateInvite: (inviteId: string, patch: Partial<Invite>) => void;
|
||||
onDeleteInvite: (inviteId: string) => void;
|
||||
@@ -285,6 +296,7 @@ export function AdminOverlay({
|
||||
onUpdateMembership: (membershipId: string, patch: Partial<ClientMembership>) => void;
|
||||
onDeleteMembership: (membershipId: string) => void;
|
||||
pendingAccessAssignments: Record<string, AccessAssignmentValue>;
|
||||
pendingClientGrantAssignments: Record<string, ClientGrantAssignmentValue>;
|
||||
pendingServiceModuleEntitlements: Record<string, boolean>;
|
||||
onCreateGroup: (clientId: string) => void;
|
||||
onUpdateGroup: (groupId: string, patch: Partial<ClientGroup>) => void;
|
||||
@@ -601,7 +613,9 @@ export function AdminOverlay({
|
||||
selectedCell={selectedAccessCell}
|
||||
onSelectCell={(cell) => setSelectedCell({ userId: cell.userId, serviceId: cell.serviceId })}
|
||||
onSetUserServiceAccess={onSetUserServiceAccess}
|
||||
onSetClientServiceGrant={onSetClientServiceGrant}
|
||||
pendingAccessAssignments={pendingAccessAssignments}
|
||||
pendingClientGrantAssignments={pendingClientGrantAssignments}
|
||||
pendingServiceModuleEntitlements={pendingServiceModuleEntitlements}
|
||||
onUpdateUser={onUpdateUser}
|
||||
onUpdateMembership={onUpdateMembership}
|
||||
@@ -1509,6 +1523,13 @@ const accessAssignmentOptions: Array<NodeDcSelectOption<AccessAssignmentValue>>
|
||||
{ value: "deny", label: "Заблокирован", description: "Запрет доступа", tone: "red" },
|
||||
];
|
||||
|
||||
const clientGrantAssignmentOptions: Array<NodeDcSelectOption<ClientGrantAssignmentValue>> = [
|
||||
{ value: "unset", label: "—", description: "Грант контура выключен" },
|
||||
{ value: "viewer", label: "Гость", description: "Просмотр для контура", tone: "green" },
|
||||
{ value: "member", label: "Участник", description: "Рабочий доступ для контура", tone: "green" },
|
||||
{ value: "admin", label: "Админ", description: "Администрирование в контуре", tone: "green" },
|
||||
];
|
||||
|
||||
const operationalCoreAccessAssignmentOptions: Array<NodeDcSelectOption<AccessAssignmentValue>> = [
|
||||
{ value: "unset", label: "—", description: "Не назначен" },
|
||||
{ value: "viewer", label: "Гость", description: "Просмотр", tone: "green" },
|
||||
@@ -2253,6 +2274,12 @@ function ServiceContentModal({
|
||||
fullDescription: currentDraft.fullDescription,
|
||||
url: currentDraft.url,
|
||||
launchUrl: currentDraft.launchUrl,
|
||||
logoutUrl: currentDraft.logoutUrl,
|
||||
loginSyncUrl: currentDraft.loginSyncUrl,
|
||||
authentikApplicationSlug: currentDraft.authentikApplicationSlug,
|
||||
authentikGroupName: currentDraft.authentikGroupName,
|
||||
authHandoffPath: currentDraft.authHandoffPath,
|
||||
isAvailableForAllNewClients: currentDraft.isAvailableForAllNewClients,
|
||||
coverImageUrl: currentDraft.coverImageUrl,
|
||||
coverMediaKind: currentDraft.coverMediaKind,
|
||||
coverMediaSource: currentDraft.coverMediaSource,
|
||||
@@ -2315,6 +2342,63 @@ function ServiceContentModal({
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div className="service-content-field service-content-field--wide service-integration-heading">
|
||||
<strong>Интеграция и SSO</strong>
|
||||
<span>Общие параметры Launcher handoff и синхронизации доступа для любого сервиса.</span>
|
||||
</div>
|
||||
|
||||
<label className="service-content-field">
|
||||
<span>Authentik application slug</span>
|
||||
<input
|
||||
value={draft.authentikApplicationSlug ?? ""}
|
||||
onChange={(event) => update("authentikApplicationSlug", event.target.value || null)}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="service-content-field">
|
||||
<span>Authentik group</span>
|
||||
<input
|
||||
value={draft.authentikGroupName ?? ""}
|
||||
onChange={(event) => update("authentikGroupName", event.target.value || null)}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="service-content-field">
|
||||
<span>Handoff path</span>
|
||||
<input
|
||||
value={draft.authHandoffPath ?? ""}
|
||||
placeholder="/auth/nodedc/handoff"
|
||||
onChange={(event) => update("authHandoffPath", event.target.value || null)}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="service-content-field">
|
||||
<span>Login sync URL</span>
|
||||
<input
|
||||
value={draft.loginSyncUrl ?? ""}
|
||||
placeholder="https://service.example/auth/login-sync"
|
||||
onChange={(event) => update("loginSyncUrl", event.target.value || null)}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="service-content-field service-content-field--wide">
|
||||
<span>Logout URL</span>
|
||||
<input
|
||||
value={draft.logoutUrl ?? ""}
|
||||
placeholder="https://service.example/auth/logout"
|
||||
onChange={(event) => update("logoutUrl", event.target.value || null)}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="service-content-toggle service-content-field--wide">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(draft.isAvailableForAllNewClients)}
|
||||
onChange={(event) => update("isAvailableForAllNewClients", event.target.checked)}
|
||||
/>
|
||||
<span>Автоматически выдавать новым контурам</span>
|
||||
</label>
|
||||
|
||||
<MediaSourceField
|
||||
label="Карточка"
|
||||
icon={<ImageIcon size={14} />}
|
||||
@@ -3112,7 +3196,9 @@ function AccessSection({
|
||||
selectedCell,
|
||||
onSelectCell,
|
||||
onSetUserServiceAccess,
|
||||
onSetClientServiceGrant,
|
||||
pendingAccessAssignments,
|
||||
pendingClientGrantAssignments,
|
||||
pendingServiceModuleEntitlements,
|
||||
onUpdateUser,
|
||||
onUpdateMembership,
|
||||
@@ -3129,7 +3215,9 @@ function AccessSection({
|
||||
selectedCell: AccessMatrixCell | null;
|
||||
onSelectCell: (cell: AccessMatrixCell) => void;
|
||||
onSetUserServiceAccess: (command: SetUserServiceAccessCommand) => void;
|
||||
onSetClientServiceGrant: (command: SetClientServiceGrantCommand) => void;
|
||||
pendingAccessAssignments: Record<string, AccessAssignmentValue>;
|
||||
pendingClientGrantAssignments: Record<string, ClientGrantAssignmentValue>;
|
||||
pendingServiceModuleEntitlements: Record<string, boolean>;
|
||||
onUpdateUser: (userId: string, patch: Partial<LauncherUser>) => void;
|
||||
onUpdateMembership: (membershipId: string, patch: Partial<ClientMembership>) => void;
|
||||
@@ -3168,6 +3256,55 @@ function AccessSection({
|
||||
|
||||
return (
|
||||
<div className={cn("access-layout", isPublicPoolContext && "access-layout--single")}>
|
||||
{!isPublicPoolContext ? (
|
||||
<GlassSurface className="client-service-grants">
|
||||
<div className="table-toolbar">
|
||||
<div>
|
||||
<h3>Доступ контура · {matrix.client.name}</h3>
|
||||
<span className="muted-text">Базовая роль наследуется участниками компании и может быть уточнена персонально.</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="client-service-grants__grid">
|
||||
{matrix.services.map((service) => {
|
||||
const pendingKey = clientGrantAssignmentKey(matrix.client.id, service.id);
|
||||
const pendingValue = pendingClientGrantAssignments[pendingKey];
|
||||
const value = pendingValue ?? clientGrantAssignmentValue(data, matrix.client.id, service.id);
|
||||
const options = isEngineServiceForAccessControl(service) || isOperationalCoreService(service)
|
||||
? clientGrantAssignmentOptions.filter((option) => option.value !== "admin")
|
||||
: clientGrantAssignmentOptions;
|
||||
|
||||
return (
|
||||
<NodeDcSelect
|
||||
key={service.id}
|
||||
value={value}
|
||||
options={options}
|
||||
label={`Доступ контура ${matrix.client.name} / ${service.title}`}
|
||||
minMenuWidth={220}
|
||||
disabled={pendingValue !== undefined}
|
||||
onChange={(nextValue) => onSetClientServiceGrant({
|
||||
clientId: matrix.client.id,
|
||||
serviceId: service.id,
|
||||
value: nextValue,
|
||||
})}
|
||||
trigger={({ open, toggle, setTriggerRef }) => (
|
||||
<button
|
||||
ref={setTriggerRef}
|
||||
className="client-service-grant"
|
||||
type="button"
|
||||
aria-expanded={open}
|
||||
aria-busy={pendingValue !== undefined}
|
||||
onClick={toggle}
|
||||
>
|
||||
<strong>{service.title}</strong>
|
||||
<span>{pendingValue !== undefined ? "Сохраняем..." : clientGrantAssignmentLabel(value)}</span>
|
||||
</button>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</GlassSurface>
|
||||
) : null}
|
||||
<GlassSurface className="access-matrix">
|
||||
<div className="table-toolbar table-toolbar--access-matrix">
|
||||
<h3>Матрица доступа · {matrix.client.name}</h3>
|
||||
@@ -5348,6 +5485,27 @@ function accessAssignmentLabel(value: AccessAssignmentValue): string {
|
||||
return accessAssignmentOptions.find((option) => option.value === value)?.label ?? value;
|
||||
}
|
||||
|
||||
function clientGrantAssignmentKey(clientId: string, serviceId: string): string {
|
||||
return `${clientId}:${serviceId}`;
|
||||
}
|
||||
|
||||
function clientGrantAssignmentValue(data: LauncherData, clientId: string, serviceId: string): ClientGrantAssignmentValue {
|
||||
const grant = data.grants.find((candidate) =>
|
||||
candidate.targetType === "client"
|
||||
&& candidate.targetId === clientId
|
||||
&& candidate.serviceId === serviceId);
|
||||
|
||||
if (!grant || grant.status !== "active") return "unset";
|
||||
if (grant.appRole === "owner") return "admin";
|
||||
return grant.appRole === "viewer" || grant.appRole === "member" || grant.appRole === "admin"
|
||||
? grant.appRole
|
||||
: "unset";
|
||||
}
|
||||
|
||||
function clientGrantAssignmentLabel(value: ClientGrantAssignmentValue): string {
|
||||
return clientGrantAssignmentOptions.find((option) => option.value === value)?.label ?? value;
|
||||
}
|
||||
|
||||
function accessAssignmentRoleLabel(role?: ServiceAppRole | null): string {
|
||||
if (!role) return "—";
|
||||
return accessAssignmentLabel(role === "owner" ? "admin" : role);
|
||||
|
||||
Reference in New Issue
Block a user