15 changed files with 1131 additions and 78 deletions
@@ -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");
});
});
+179 -42
View File
@@ -2001,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, {
@@ -2019,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);
@@ -2044,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) {
@@ -2307,6 +2336,7 @@ export function createControlPlaneStore({ projectRoot }) {
getLoginAccountStatus,
getSnapshot,
ensureTaskerInvitePlatformInvite,
ensureService,
prepareInviteRegistration,
readData,
replaceData,
@@ -3811,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");
});
});
+61 -35
View File
@@ -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,
@@ -2199,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");
@@ -2243,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) => {
@@ -2521,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`,
@@ -2539,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.");
@@ -4873,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) {
+102
View File
@@ -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}`));
}
+124
View File
@@ -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);
});
});
+33
View File
@@ -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);
}
+39
View File
@@ -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
View File
@@ -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,
@@ -81,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"');
+17 -1
View File
@@ -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),
});
}
+66
View File
@@ -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()");
});
});
+158
View File
@@ -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);