import { type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction, redirect, useLoaderData, useNavigation, } from "react-router"; import { CatalogError, foundationErrors } from "@hivegrid/foundation"; import { buildKwpSetupVM, type KwpSetupFeedback, type KwpSetupVM } from "@hivegrid/view-models"; import { KwpSetupPage } from "~/components/screens/integrations/KwpSetupPage"; import ServerError from "~/components/ui/errors/ServerError"; import { getTranslations } from "~/locale/i18next.server"; import { KwpConnectError, beginKwpOAuthConnection, cancelKwpOAuthConnectionAttempt, finalizeKwpOAuthConnection, loadKwpMandantSelection, } from "~/modules/kwp/services/KwpConnectionService.server"; import { requireKwpIntegrationModule } from "~/modules/kwp/routes/kwpAccess.server"; import { useRootData } from "~/utils/data/useRootData"; import { getMyTenants } from "~/utils/db/tenants.db.server"; import { loadIntegrationsContext, notFoundResponse, requireIntegrationsPermission, } from "~/utils/integrations/integrationsAccess.server"; import { integrationsAppPath, KWP_SETUP_PATH, kwpMandantSelectionPath, kwpSetupPath, } from "~/utils/integrations/integrationsRoutePaths"; import { ProviderOAuthCallbackAccessError, runAuthenticatedProviderOAuthCallback, } from "~/utils/integrations/providerOAuthCallbackAccess.server"; import { createScopedLogger } from "~/utils/logger.server"; import { getUserInfo, validateCSRFToken } from "~/utils/session.server"; const MAX_CONTEXT_CODE_LENGTH = 128; const MAX_CONTEXT_ID_LENGTH = 256; const MAX_TENANT_SLUG_LENGTH = 128; const logger = createScopedLogger("kwp.oauth.setup"); type KwpSetupFailureCode = | "intent_invalid" | "tenant_context_invalid" | "tenant_access_denied" | "session_mismatch" | "membership_inactive"; function logKwpSetupFailure(failureCode: KwpSetupFailureCode): void { logger.warn( { op: "kwp.oauth.setup.failed", failureCode }, "KWP OAuth setup failed before provider authorization", ); } type TenantOption = { readonly id: string; readonly name: string; readonly slug: string }; type LoaderData = { readonly title: string; readonly vm: KwpSetupVM }; function isNotFoundCatalogError(error: unknown): error is CatalogError { return error instanceof CatalogError && error.code === foundationErrors.notFound.code; } function setupFeedback(url: URL): KwpSetupFeedback { const values = url.searchParams.getAll("kwp"); if (values.length !== 1) return null; switch (values[0]) { case "error": return "oauth-error"; case "configuration-error": return "configuration-error"; case "selection-error": return "selection-error"; case "selection-expired": return "selection-expired"; default: return null; } } async function loadKwpConnectContext(request: Request, tenantSlug: string) { const ctx = await loadIntegrationsContext({ request, params: { tenant: tenantSlug }, requireModule: true }); await requireKwpIntegrationModule(ctx); requireIntegrationsPermission(ctx, "integrations.connect"); return ctx; } async function requireKwpConnectContext(request: Request, tenantSlug: string) { try { return await loadKwpConnectContext(request, tenantSlug); } catch (error) { if (isNotFoundCatalogError(error)) throw notFoundResponse(); throw error; } } async function filterKwpConnectTenants(request: Request, tenants: readonly TenantOption[]): Promise { const visibleTenants = await Promise.all( tenants.map(async (tenant) => { try { await loadKwpConnectContext(request, tenant.slug); return tenant; } catch (error) { if (isNotFoundCatalogError(error)) return null; throw error; } }), ); return visibleTenants.filter((tenant): tenant is TenantOption => tenant !== null); } export const loader = async ({ request }: LoaderFunctionArgs) => { const { t } = await getTranslations(request); const url = new URL(request.url); const tenantSlug = url.searchParams.get("tenant")?.trim() ?? ""; const connectionIds = url.searchParams.getAll("connection"); const connectionId = connectionIds.length === 1 ? connectionIds[0]?.trim() ?? "" : ""; const feedback = setupFeedback(url); const title = `${t("integrations.kwp.oauth.title")} | ${process.env.APP_NAME}`; if (!tenantSlug) { const session = await getUserInfo(request); const tenantOptions = session.userId ? (await getMyTenants(session.userId)).map((tenant) => ({ id: tenant.id, name: tenant.name, slug: tenant.slug })) : []; const tenants = session.userId ? await filterKwpConnectTenants(request, tenantOptions) : []; return Response.json({ title, vm: buildKwpSetupVM({ mode: "entry", authenticated: Boolean(session.userId), loginHref: `/login?redirectTo=${encodeURIComponent(KWP_SETUP_PATH)}`, tenants: tenants.map((tenant) => ({ ...tenant, setupHref: kwpSetupPath(tenant.slug) })), feedback, }), } satisfies LoaderData); } if (tenantSlug.length > MAX_TENANT_SLUG_LENGTH) throw notFoundResponse(); const ctx = await requireKwpConnectContext(request, tenantSlug); const settingsHref = integrationsAppPath(tenantSlug, "kwp"); if (connectionIds.length > 0) { if (!connectionId || connectionId.length > MAX_CONTEXT_ID_LENGTH || connectionIds.length !== 1) throw notFoundResponse(); try { const selection = await runAuthenticatedProviderOAuthCallback({ request, tenantId: ctx.tenantId, userId: ctx.userId, callback: () => loadKwpMandantSelection({ tenantId: ctx.tenantId, userId: ctx.userId, connectionId, }), }); return Response.json({ title, vm: buildKwpSetupVM({ mode: "mandant", tenantSlug, settingsHref, connectionId, connectionVersion: selection.version, customerCode: selection.customerCode, discoveryMode: selection.mode, mandants: selection.options, feedback, }), } satisfies LoaderData); } catch (error) { if (error instanceof ProviderOAuthCallbackAccessError) throw notFoundResponse(); if (error instanceof KwpConnectError && (error.code === "selection_expired" || error.code === "invalid_state")) { return redirect(`${kwpSetupPath(tenantSlug)}&kwp=selection-expired`, 303); } throw error; } } return Response.json({ title, vm: buildKwpSetupVM({ mode: "oauth", tenantSlug, settingsHref, feedback, }), } satisfies LoaderData); }; export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }]; export const action = async ({ request }: ActionFunctionArgs) => { const form = await request.formData(); await validateCSRFToken(request, { formData: form }); const intent = form.get("intent")?.toString(); if (intent !== "connect" && intent !== "confirm-mandant" && intent !== "cancel-mandant") { logKwpSetupFailure("intent_invalid"); throw notFoundResponse(); } const tenantSlug = (new URL(request.url).searchParams.get("tenant") ?? form.get("tenant")?.toString() ?? "").trim(); if (!tenantSlug || tenantSlug.length > MAX_TENANT_SLUG_LENGTH) { logKwpSetupFailure("tenant_context_invalid"); throw notFoundResponse(); } let ctx: Awaited>; try { ctx = await requireKwpConnectContext(request, tenantSlug); } catch (error) { if (error instanceof Response && error.status === 404) logKwpSetupFailure("tenant_access_denied"); throw error; } try { if (intent === "connect") { const customerCode = form.get("customerCode")?.toString().trim() ?? ""; if (!customerCode || customerCode.length > MAX_CONTEXT_CODE_LENGTH) { return redirect(`${kwpSetupPath(tenantSlug)}&kwp=configuration-error`, 303); } const started = await runAuthenticatedProviderOAuthCallback({ request, tenantId: ctx.tenantId, userId: ctx.userId, callback: () => beginKwpOAuthConnection({ tenantId: ctx.tenantId, tenantSlug, userId: ctx.userId, customerCode, }), }); return redirect(started.authorizationUrl, { headers: { "Set-Cookie": started.setCookie } }); } const connectionId = form.get("connectionId")?.toString().trim() ?? ""; const connectionVersion = form.get("connectionVersion")?.toString().trim() ?? ""; if (!connectionId || connectionId.length > MAX_CONTEXT_ID_LENGTH || !connectionVersion || connectionVersion.length > MAX_CONTEXT_ID_LENGTH) { throw notFoundResponse(); } if (intent === "cancel-mandant") { await runAuthenticatedProviderOAuthCallback({ request, tenantId: ctx.tenantId, userId: ctx.userId, callback: () => cancelKwpOAuthConnectionAttempt({ tenantId: ctx.tenantId, userId: ctx.userId, connectionId, version: connectionVersion, }), }); return redirect(integrationsAppPath(tenantSlug, "kwp"), 303); } const selectionKind = form.get("selectionKind")?.toString(); const mandantCode = form.get("mandantCode")?.toString().trim() ?? ""; if (selectionKind !== "none" && selectionKind !== "selected") throw notFoundResponse(); if (selectionKind === "selected" && (!mandantCode || mandantCode.length > MAX_CONTEXT_CODE_LENGTH)) { return redirect(`${kwpMandantSelectionPath(tenantSlug, connectionId)}&kwp=selection-error`, 303); } await runAuthenticatedProviderOAuthCallback({ request, tenantId: ctx.tenantId, userId: ctx.userId, callback: () => finalizeKwpOAuthConnection({ tenantId: ctx.tenantId, userId: ctx.userId, connectionId, version: connectionVersion, mandantBinding: selectionKind === "none" ? { kind: "none" } : { kind: "selected", code: mandantCode }, }), }); return redirect(`${integrationsAppPath(tenantSlug, "kwp")}?kwp=connected`, 303); } catch (error) { if (error instanceof Response) throw error; if (error instanceof ProviderOAuthCallbackAccessError) { logKwpSetupFailure(error.failureCode); throw notFoundResponse(); } if (error instanceof KwpConnectError) { if (intent === "connect") { const outcome = error.code === "not_configured" ? "configuration-error" : "error"; return redirect(`${kwpSetupPath(tenantSlug)}&kwp=${outcome}`, 303); } const connectionId = form.get("connectionId")?.toString().trim() ?? ""; if (error.code === "selection_expired" || error.code === "invalid_state") { return redirect(`${kwpSetupPath(tenantSlug)}&kwp=selection-expired`, 303); } if (connectionId) { return redirect(`${kwpMandantSelectionPath(tenantSlug, connectionId)}&kwp=selection-error`, 303); } } throw error; } }; export default function KwpSetupRoute() { const { vm } = useLoaderData(); const { csrf } = useRootData(); const navigation = useNavigation(); return ; } export function ErrorBoundary() { return ; }