8000 Add UiScriptProvider SPI for custom element admin console extensions by edewit · Pull Request #52778 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions js/apps/admin-ui/src/PageNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import { useRealm } from "./context/realm-context/RealmContext";
import { useServerInfo } from "./context/server-info/ServerInfoProvider";
import type { Environment } from "./environment-types";
import { toPage } from "./page/routes";
import { SCRIPT_PROVIDER } from "./ui-script/constants";
import { toUiScript } from "./ui-script/routes";
import { normalizeNavRoutePath } from "./page-nav-utils";
import { routes } from "./routes";
import { resolveDisplayName } from "./util";
Expand Down Expand Up @@ -72,6 +74,7 @@ export const PageNav = () => {
const isFeatureEnabled = useIsFeatureEnabled();
const pages =
componentTypes?.["org.keycloak.services.ui.extend.UiPageProvider"];
const scripts = componentTypes?.[SCRIPT_PROVIDER];
const navigate = useNavigate();
const { realm, realmRepresentation } = useRealm();

Expand Down Expand Up @@ -162,6 +165,15 @@ export const PageNav = () => {
id="/page-section"
/>
))}
{isFeatureEnabled(Feature.DeclarativeUI) &&
scripts?.map((p) => (
<LeftNav
key={p.id}
title={p.id}
path={toUiScript({ providerId: p.id }).pathname!}
id="/ui-script"
/>
))}
</NavGroup>
)}
</Nav>
Expand Down
2 changes: 2 additions & 0 deletions js/apps/admin-ui/src/environment-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ export type Environment = BaseEnvironment & {
* @see {@link https://www.keycloak.org/server/hostname#_administration_console}
*/
adminBaseUrl: string;
/** The URL to the authentication server. */
authServerUrl: string;
/** The URL to the base of the Admin Console. */
consoleBaseUrl: string;
/** The name of the master realm. */
Expand Down
2 changes: 2 additions & 0 deletions js/apps/admin-ui/src/routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import groupsRoutes from "./groups/routes";
import identityProviders from "./identity-providers/routes";
import organizationRoutes from "./organizations/routes";
import pageRoutes from "./page/routes";
import uiScriptRoutes from "./ui-script/routes";
import permissionsConfigurationRoute from "./permissions-configuration/routes";
import realmRoleRoutes from "./realm-roles/routes";
import realmSettingRoutes from "./realm-settings/routes";
Expand Down Expand Up @@ -57,5 +58,6 @@ export const routes: AppRouteObject[] = [
...groupsRoutes,
...dashboardRoutes,
...pageRoutes,
...uiScriptRoutes,
NotFoundRoute,
];
43 changes: 43 additions & 0 deletions js/apps/admin-ui/src/ui-script/ScriptPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Alert, PageSection } from "@patternfly/react-core";
import { KeycloakSpinner, useEnvironment } from "@keycloak/keycloak-ui-shared";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import { ViewHeader } from "../components/view-header/ViewHeader";
import { useRealm } from "../context/realm-context/RealmContext";
import { useServerInfo } from "../context/server-info/ServerInfoProvider";
import type { Environment } from "../environment-types";
import { SCRIPT_PROVIDER } from "./constants";
import { UiScriptHost } from "./UiScriptHost";
import { useScriptLoader } from "./useScriptLoader";
import type { UiScriptParams } from "./routes";

export default function ScriptPage() {
const { t } = useTranslation();
const { componentTypes } = useServerInfo();
const { realm } = useRealm();
const { environment } = useEnvironment<Environment>();
const { providerId } = useParams<UiScriptParams>();
const scripts = componentTypes?.[SCRIPT_PROVIDER];
const script = scripts?.find((p) => p.id === providerId);

if (!script) {
throw new Error(t("notFound"));
}

const tagName = script.metadata.tagName as string | undefined;
const scriptUrl = `${environment.adminBaseUrl}/admin/realms/${encodeURIComponent(realm)}/ui-scripts/${encodeURIComponent(providerId!)}/script.js`;
const { state, error } = useScriptLoader(scriptUrl, tagName);

return (
<>
<ViewHeader titleKey={script.id} subKey={script.helpText} />
<PageSection variant="light">
{state === "loading" && <KeycloakSpinner />}
{state === "error" && (
<Alert variant="danger" title={error?.message || t("error")} />
)}
{state === "ready" && tagName && <UiScriptHost tagName={tagName} />}
</PageSection>
</>
);
}
60 changes: 60 additions & 0 deletions js/apps/admin-ui/src/ui-script/UiScriptHost.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { useCallback, useEffect, useRef } from "react";
import { useAdminClient } from "../admin-client";
import { useRealm } from "../context/realm-context/RealmContext";
import { useEnvironment } from "@keycloak/keycloak-ui-shared";
import type { Environment } from "../environment-types";
import type { UiScriptContext, UiScriptElement } from "./types";

type UiScriptHostProps = {
tagName: string;
};

export const UiScriptHost = ({ tagName }: UiScriptHostProps) => {
const containerRef = useRef<HTMLDivElement>(null);
const { keycloak } = useAdminClient();
const { environment } = useEnvironment<Environment>();
const { realm, realmRepresentation } = useRealm();

const getAccessToken = useCallback(async () => {
try {
await keycloak.updateToken(5);
return keycloak.token;
} catch {
return undefined;
}
}, [keycloak]);

useEffect(() => {
const container = containerRef.current;
if (!container) {
return;
}

const context: UiScriptContext = {
realm,
realmRepresentation,
adminBaseUrl: environment.adminBaseUrl,
serverBaseUrl: environment.serverBaseUrl,
authServerUrl: environment.authServerUrl,
10000 getAccessToken,
};

const element = document.createElement(tagName) as UiScriptElement;
element.context = context;
container.appendChild(element);

return () => {
container.removeChild(element);
};
}, [
tagName,
realm,
realmRepresentation,
environment.adminBaseUrl,
environment.serverBaseUrl,
environment.authServerUrl,
getAccessToken,
]);

return <div ref={containerRef} />;
};
2 changes: 2 additions & 0 deletions js/apps/admin-ui/src/ui-script/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const SCRIPT_PROVIDER =
"org.keycloak.services.ui.extend.UiScriptProvider";
27 changes: 27 additions & 0 deletions js/apps/admin-ui/src/ui-script/routes.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Path, generatePath } from "react-router-dom";
import type { AppRouteObject } from "../routes";
import { lazy } from "react";

export type UiScriptParams = { realm: string; providerId: string };

const ScriptPage = lazy(() => import("./ScriptPage"));

const UiScriptRoute: AppRouteObject = {
path: "/:realm?/ui-script/:providerId",
element: <ScriptPage />,
handle: {
access: "view-realm",
breadcrumb: (t) => t("page"),
},
};

const routes: AppRouteObject[] = [UiScriptRoute];

export const toUiScript = (params: {
realm?: string;
providerId: string;
}): Partial<Path> => ({
pathname: generatePath(UiScriptRoute.path, params),
});

export default routes;
14 changes: 14 additions & 0 deletions js/apps/admin-ui/src/ui-script/types.ts
10BC8
Original file line numberDiff line number Diff line change
@@ -0,0 +1,14 @@
import type RealmRepresentation from "@keycloak/keycloak-admin-client/lib/defs/realmRepresentation";

export type UiScriptContext = {
realm: string;
realmRepresentation: RealmRepresentation;
adminBaseUrl: string;
serverBaseUrl: string;
authServerUrl: string;
getAccessToken: () => Promise<string | undefined>;
};

export type UiScriptElement = HTMLElement & {
context?: UiScriptContext;
};
87 changes: 87 additions & 0 deletions js/apps/admin-ui/src/ui-script/useScriptLoader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { useEffect, useState } from "react";
import { useAdminClient } from "../admin-client";

type ScriptLoaderState = "loading" | "ready" | "error";

export function useScriptLoader(
scriptUrl?: string,
tagName?: string,
): { state: ScriptLoaderState; error?: Error } {
const { keycloak } = useAdminClient();
const [state, setState] = useState<ScriptLoaderState>("loading");
const [error, setError] = useState<Error>();

useEffect(() => {
if (!scriptUrl || !tagName) {
return;
}

let blobUrl: string | undefined;
let script: HTMLScriptElement | undefined;
let cancelled = false;

const load = async () => {
try {
setState("loading");
setError(undefined);
await keycloak.updateToken(5);
const response = await fetch(scriptUrl, {
headers: {
Authorization: `Bearer ${keycloak.token}`,
},
});

if (!response.ok) {
throw new Error(`Failed to load script: ${response.status}`);
}

const code = await response.text();
if (cancelled) {
return;
}

blobUrl = URL.createObjectURL(
new Blob([code], { type: "text/javascript" }),
);
script = document.createElement("script");
script.src = blobUrl;
script.async = true;

await new Promise<void>((resolve, reject) => {
script!. => resolve();
script!. => reject(new Error("Script failed to load"));
document.head.appendChild(script!);
});

if (!customElements.get(tagName)) {
throw new Error(`Custom element ${tagName} was not registered`);
}

setState("ready");
} catch (loadError) {
if (!cancelled) {
setError(
loadError instanceof Error 10BC8
? loadError
: new Error(String(loadError)),
);
setState("error");
}
}
};

void load();

return () => {
cancelled = true;
if (script?.parentNode) {
script.parentNode.removeChild(script);
}
if (blobUrl) {
URL.revokeObjectURL(blobUrl);
}
};
}, [scriptUrl, tagName, keycloak]);

return { state, error };
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package org.keycloak.services.ui.extend;

import org.keycloak.provider.Provider;

public interface UiScriptProvider extends Provider {

String getHelpText();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package org.keycloak.services.ui.extend;

import java.util.HashMap;
import java.util.Map;

import org.keycloak.component.ComponentFactory;
import org.keycloak.component.ComponentModel;
import org.keycloak.models.KeycloakSession;

public interface UiScriptProviderFactory<T> extends ComponentFactory<T, UiScriptProvider> {
default T create(KeycloakSession session, ComponentModel model) {
return null;
}

String getTagName();

String getScriptPath();

@Override
default Map<String, Object> getTypeMetadata() {
Map<String, Object> metadata = new HashMap<>();
metadata.put("tagName", getTagName());
metadata.put("scriptPath", getScriptPath());
return metadata;
}

@Override
default boolean isInternal() {
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package org.keycloak.services.ui.extend;

import java.util.regex.Pattern;

public final class UiScriptProviderUtils {

private static final Pattern TAG_NAME_PATTERN = Pattern.compile("[a-z][a-z0-9]*(-[a-z0-9]+)+");

private UiScriptProviderUtils() {
}

public static void validateTagName(String tagName) {
if (tagName == null || !TAG_NAME_PATTERN.matcher(tagName).matches()) {
throw new IllegalArgumentException("Invalid custom element tag name: " + tagName);
}
Comment on lines +3 to +15
}

public static void validateScriptPath(String scriptPath) {
if (scriptPath == null || scriptPath.isEmpty() || scriptPath.startsWith("/") || scriptPath.contains("..")) {
throw new IllegalArgumentException("Invalid script path: " + scriptPath);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package org.keycloak.services.ui.extend;

import org.keycloak.common.Profile;
import org.keycloak.provider.Provider;
import org.keycloak.provider.ProviderFactory;
import org.keycloak.provider.Spi;

public class UiScriptSpi implements Spi {
@Override
public boolean isInternal() {
return true;
}

@Override
public String getName() {
return "ui-script";
}

@Override
public Class<? extends Provider> getProviderClass() {
return UiScriptProvider.class;
}

@Override
public Class<? extends ProviderFactory> getProviderFactoryClass() {
return UiScriptProviderFactory.class;
}

@Override
public boolean isEnabled() {
return Profile.isFeatureEnabled(Profile.Feature.DECLARATIVE_UI);
}
}
Loading
Loading
0