feat(hub): add idempotent service registration

This commit is contained in:
DCCONSTRUCTIONS
2026-08-10 16:53:47 +03:00
parent 24d01fc813
commit 64624293a8
7 changed files with 494 additions and 51 deletions
+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();