keycloak_theme/src/bin/start-keycloak/start-keycloak.ts

469 lines
15 KiB
TypeScript
Raw Normal View History

2024-05-20 15:34:07 +02:00
import { readBuildOptions } from "../shared/buildOptions";
import type { CliCommandOptions as CliCommandOptions_common } from "../main";
import { promptKeycloakVersion } from "../shared/promptKeycloakVersion";
import { readMetaInfKeycloakThemes } from "../shared/metaInfKeycloakThemes";
import { accountV1ThemeName, containerName } from "../shared/constants";
2024-05-20 15:34:07 +02:00
import { SemVer } from "../tools/SemVer";
import type { KeycloakVersionRange } from "../shared/KeycloakVersionRange";
import { getJarFileBasename } from "../shared/getJarFileBasename";
2024-05-17 05:13:41 +02:00
import { assert, type Equals } from "tsafe/assert";
import * as fs from "fs";
import { join as pathJoin, relative as pathRelative, sep as pathSep } from "path";
2024-05-17 05:13:41 +02:00
import * as child_process from "child_process";
2024-05-18 10:02:14 +02:00
import chalk from "chalk";
2024-05-20 02:27:40 +02:00
import chokidar from "chokidar";
import { waitForDebounceFactory } from "powerhooks/tools/waitForDebounce";
2024-05-20 15:34:07 +02:00
import { getThisCodebaseRootDirPath } from "../tools/getThisCodebaseRootDirPath";
import { getAbsoluteAndInOsFormatPath } from "../tools/getAbsoluteAndInOsFormatPath";
import cliSelect from "cli-select";
2024-05-20 19:30:04 +02:00
import * as runExclusive from "run-exclusive";
import { extractArchive } from "../tools/extractArchive";
import { appBuild } from "./appBuild";
import { keycloakifyBuild } from "./keycloakifyBuild";
2024-05-18 11:40:09 +02:00
export type CliCommandOptions = CliCommandOptions_common & {
port: number;
keycloakVersion: string | undefined;
2024-05-20 15:34:07 +02:00
realmJsonFilePath: string | undefined;
2024-05-18 11:40:09 +02:00
};
export async function command(params: { cliCommandOptions: CliCommandOptions }) {
2024-05-18 11:40:09 +02:00
exit_if_docker_not_installed: {
2024-05-18 11:09:04 +02:00
let commandOutput: Buffer | undefined = undefined;
try {
2024-05-20 15:48:51 +02:00
commandOutput = child_process.execSync("docker --version", {
stdio: ["ignore", "pipe", "ignore"]
});
2024-05-18 11:09:04 +02:00
} catch {}
2024-05-18 11:40:09 +02:00
if (commandOutput?.toString("utf8").includes("Docker")) {
break exit_if_docker_not_installed;
2024-05-18 11:09:04 +02:00
}
console.log(
[
`${chalk.red("Docker required.")}`,
2024-05-20 15:48:51 +02:00
`Install it with Docker Desktop: ${chalk.bold.underline(
"https://www.docker.com/products/docker-desktop/"
)}`,
2024-05-18 11:09:04 +02:00
`(or any other way)`
].join(" ")
);
process.exit(1);
}
2024-05-18 11:40:09 +02:00
exit_if_docker_not_running: {
2024-05-18 11:09:04 +02:00
let isDockerRunning: boolean;
try {
2024-05-20 15:48:51 +02:00
child_process.execSync("docker info", { stdio: "ignore" });
2024-05-18 11:09:04 +02:00
isDockerRunning = true;
} catch {
isDockerRunning = false;
}
if (isDockerRunning) {
2024-05-18 11:40:09 +02:00
break exit_if_docker_not_running;
2024-05-18 11:09:04 +02:00
}
2024-05-20 15:48:51 +02:00
console.log(
[
`${chalk.red("Docker daemon is not running.")}`,
`Please start Docker Desktop and try again.`
].join(" ")
);
2024-05-18 11:40:09 +02:00
process.exit(1);
2024-05-18 11:09:04 +02:00
}
const { cliCommandOptions } = params;
const buildOptions = readBuildOptions({ cliCommandOptions });
{
const { isAppBuildSuccess } = await appBuild({
doSkipIfReactAppBuildDirExists: true,
buildOptions
});
if (!isAppBuildSuccess) {
console.log(
chalk.red(
`App build failed, exiting. Try running 'yarn build-keycloak-theme' and see what's wrong.`
)
);
process.exit(1);
2024-05-18 11:40:09 +02:00
}
const { isKeycloakifyBuildSuccess } = await keycloakifyBuild({
doSkipBuildJars: false,
buildOptions
});
if (!isKeycloakifyBuildSuccess) {
console.log(
chalk.red(
`Keycloakify build failed, exiting. Try running 'yarn build-keycloak-theme' and see what's wrong.`
)
);
process.exit(1);
}
2024-05-18 11:40:09 +02:00
}
2024-05-17 05:13:41 +02:00
const metaInfKeycloakThemes = readMetaInfKeycloakThemes({
2024-05-20 15:48:51 +02:00
keycloakifyBuildDirPath: buildOptions.keycloakifyBuildDirPath
2024-05-17 05:13:41 +02:00
});
2024-05-20 15:48:51 +02:00
const doesImplementAccountTheme = metaInfKeycloakThemes.themes.some(
({ name }) => name === accountV1ThemeName
);
const { keycloakVersion, keycloakMajorNumber: keycloakMajorVersionNumber } =
await (async function getKeycloakMajor(): Promise<{
keycloakVersion: string;
keycloakMajorNumber: number;
}> {
if (cliCommandOptions.keycloakVersion !== undefined) {
return {
keycloakVersion: cliCommandOptions.keycloakVersion,
keycloakMajorNumber: SemVer.parse(cliCommandOptions.keycloakVersion)
.major
};
}
2024-05-18 11:40:09 +02:00
2024-05-20 15:48:51 +02:00
console.log(
chalk.cyan("On which version of Keycloak do you want to test your theme?")
);
2024-05-18 11:40:09 +02:00
2024-05-20 15:48:51 +02:00
const { keycloakVersion } = await promptKeycloakVersion({
startingFromMajor: 17,
cacheDirPath: buildOptions.cacheDirPath
});
2024-05-17 05:13:41 +02:00
2024-05-20 15:48:51 +02:00
console.log(`${keycloakVersion}`);
2024-05-20 02:27:40 +02:00
2024-05-20 15:48:51 +02:00
const keycloakMajorNumber = SemVer.parse(keycloakVersion).major;
2024-05-17 05:13:41 +02:00
2024-05-20 15:48:51 +02:00
if (doesImplementAccountTheme && keycloakMajorNumber === 22) {
console.log(
[
"Unfortunately, Keycloakify themes that implements an account theme do not work on Keycloak 22",
"Please select any other Keycloak version"
].join(" ")
);
return getKeycloakMajor();
}
2024-05-17 05:13:41 +02:00
2024-05-20 15:48:51 +02:00
return { keycloakVersion, keycloakMajorNumber };
})();
2024-05-17 05:13:41 +02:00
const keycloakVersionRange: KeycloakVersionRange = (() => {
if (doesImplementAccountTheme) {
const keycloakVersionRange = (() => {
2024-05-20 15:34:07 +02:00
if (keycloakMajorVersionNumber <= 21) {
2024-05-17 05:13:41 +02:00
return "21-and-below" as const;
}
2024-05-20 15:34:07 +02:00
assert(keycloakMajorVersionNumber !== 22);
2024-05-17 05:13:41 +02:00
2024-05-20 15:34:07 +02:00
if (keycloakMajorVersionNumber === 23) {
2024-05-17 05:13:41 +02:00
return "23" as const;
}
return "24-and-above" as const;
})();
2024-05-20 15:48:51 +02:00
assert<
Equals<typeof keycloakVersionRange, KeycloakVersionRange.WithAccountTheme>
>();
2024-05-17 05:13:41 +02:00
return keycloakVersionRange;
} else {
const keycloakVersionRange = (() => {
2024-05-20 15:34:07 +02:00
if (keycloakMajorVersionNumber <= 21) {
2024-05-17 05:13:41 +02:00
return "21-and-below" as const;
}
return "22-and-above" as const;
})();
2024-05-20 15:48:51 +02:00
assert<
Equals<
typeof keycloakVersionRange,
KeycloakVersionRange.WithoutAccountTheme
>
>();
2024-05-17 05:13:41 +02:00
return keycloakVersionRange;
}
})();
const { jarFileBasename } = getJarFileBasename({ keycloakVersionRange });
2024-05-20 02:42:57 +02:00
console.log(`Using Keycloak ${chalk.bold(jarFileBasename)}`);
2024-05-20 15:34:07 +02:00
const realmJsonFilePath = await (async () => {
if (cliCommandOptions.realmJsonFilePath !== undefined) {
2024-05-20 15:48:51 +02:00
console.log(
chalk.green(
`Using realm json file: ${cliCommandOptions.realmJsonFilePath}`
)
);
2024-05-20 15:34:07 +02:00
return getAbsoluteAndInOsFormatPath({
2024-05-20 15:48:51 +02:00
pathIsh: cliCommandOptions.realmJsonFilePath,
cwd: process.cwd()
2024-05-20 15:34:07 +02:00
});
}
2024-05-20 15:48:51 +02:00
const dirPath = pathJoin(
getThisCodebaseRootDirPath(),
"src",
"bin",
"start-keycloak"
);
2024-05-20 15:34:07 +02:00
2024-05-20 15:48:51 +02:00
const filePath = pathJoin(
dirPath,
`myrealm-realm-${keycloakMajorVersionNumber}.json`
);
2024-05-20 15:34:07 +02:00
if (fs.existsSync(filePath)) {
return filePath;
}
2024-05-20 15:48:51 +02:00
console.log(
`${chalk.yellow(
`Keycloakify do not have a realm configuration for Keycloak ${keycloakMajorVersionNumber} yet.`
)}`
);
2024-05-20 15:34:07 +02:00
console.log(chalk.cyan("Select what configuration to use:"));
const { value } = await cliSelect<string>({
2024-05-20 15:48:51 +02:00
values: [
...fs
.readdirSync(dirPath)
.filter(fileBasename => fileBasename.endsWith(".json")),
"none"
]
2024-05-20 15:34:07 +02:00
}).catch(() => {
process.exit(-1);
});
if (value === "none") {
return undefined;
}
return pathJoin(dirPath, value);
})();
const jarFilePath = pathJoin(buildOptions.keycloakifyBuildDirPath, jarFileBasename);
const { doUseBuiltInAccountV1Theme } = await (async () => {
let doUseBuiltInAccountV1Theme = false;
await extractArchive({
archiveFilePath: jarFilePath,
onArchiveFile: async ({ relativeFilePathInArchive, readFile, earlyExit }) => {
for (const themeName of buildOptions.themeNames) {
if (
relativeFilePathInArchive ===
pathJoin("theme", themeName, "account", "theme.properties")
) {
if (
(await readFile())
.toString("utf8")
2024-05-26 19:31:09 +02:00
.includes("parent=keycloak")
) {
doUseBuiltInAccountV1Theme = true;
}
earlyExit();
}
}
}
});
return { doUseBuiltInAccountV1Theme };
})();
const accountThemePropertyPatch = !doUseBuiltInAccountV1Theme
? undefined
: () => {
for (const themeName of buildOptions.themeNames) {
const filePath = pathJoin(
buildOptions.keycloakifyBuildDirPath,
"src",
"main",
"resources",
"theme",
themeName,
"account",
"theme.properties"
);
const sourceCode = fs.readFileSync(filePath);
const modifiedSourceCode = Buffer.from(
sourceCode
.toString("utf8")
.replace(`parent=${accountV1ThemeName}`, "parent=keycloak"),
"utf8"
);
assert(Buffer.compare(modifiedSourceCode, sourceCode) !== 0);
fs.writeFileSync(filePath, modifiedSourceCode);
}
};
accountThemePropertyPatch?.();
2024-05-26 19:40:13 +02:00
try {
child_process.execSync(`docker rm --force ${containerName}`, {
stdio: "ignore"
});
} catch {}
2024-05-20 15:34:07 +02:00
const spawnArgs = [
2024-05-17 05:13:41 +02:00
"docker",
[
"run",
2024-05-18 11:40:09 +02:00
...["-p", `${cliCommandOptions.port}:8080`],
2024-05-17 05:13:41 +02:00
...["--name", containerName],
...["-e", "KEYCLOAK_ADMIN=admin"],
...["-e", "KEYCLOAK_ADMIN_PASSWORD=admin"],
2024-05-20 15:48:51 +02:00
...(realmJsonFilePath === undefined
? []
: [
"-v",
`${realmJsonFilePath}:/opt/keycloak/data/import/myrealm-realm.json`
]),
...["-v", `${jarFilePath}:/opt/keycloak/providers/keycloak-theme.jar`],
2024-05-20 15:48:51 +02:00
...(keycloakMajorVersionNumber <= 20
? ["-e", "JAVA_OPTS=-Dkeycloak.profile=preview"]
: []),
...[
...buildOptions.themeNames,
2024-05-26 19:31:09 +02:00
...(doUseBuiltInAccountV1Theme ? [] : [accountV1ThemeName])
]
.map(themeName => ({
localDirPath: pathJoin(
buildOptions.keycloakifyBuildDirPath,
"src",
"main",
"resources",
"theme",
themeName
),
containerDirPath: `/opt/keycloak/themes/${themeName}`
}))
.map(({ localDirPath, containerDirPath }) => [
2024-05-20 15:48:51 +02:00
"-v",
`${localDirPath}:${containerDirPath}:rw`
2024-05-20 15:48:51 +02:00
])
.flat(),
2024-05-18 07:53:06 +02:00
`quay.io/keycloak/keycloak:${keycloakVersion}`,
2024-05-17 05:13:41 +02:00
"start-dev",
2024-05-20 15:48:51 +02:00
...(21 <= keycloakMajorVersionNumber && keycloakMajorVersionNumber < 24
? ["--features=declarative-user-profile"]
: []),
2024-05-20 15:34:07 +02:00
...(realmJsonFilePath === undefined ? [] : ["--import-realm"])
2024-05-17 05:13:41 +02:00
],
{
2024-05-20 15:48:51 +02:00
cwd: buildOptions.keycloakifyBuildDirPath
2024-05-17 05:13:41 +02:00
}
2024-05-20 02:27:40 +02:00
] as const;
2024-05-20 15:34:07 +02:00
const child = child_process.spawn(...spawnArgs);
2024-05-17 05:13:41 +02:00
2024-05-18 07:53:06 +02:00
child.stdout.on("data", data => process.stdout.write(data));
child.stderr.on("data", data => process.stderr.write(data));
2024-05-17 05:13:41 +02:00
2024-05-20 02:27:40 +02:00
child.on("exit", process.exit);
const srcDirPath = pathJoin(buildOptions.reactAppRootDirPath, "src");
2024-05-20 02:27:40 +02:00
2024-05-18 10:02:14 +02:00
{
const handler = async (data: Buffer) => {
if (!data.toString("utf8").includes("Listening on: http://0.0.0.0:8080")) {
return;
}
child.stdout.off("data", handler);
await new Promise(resolve => setTimeout(resolve, 1_000));
console.log(
[
"",
`${chalk.green("Your theme is accessible at:")}`,
2024-05-20 15:48:51 +02:00
`${chalk.green("➜")} ${chalk.cyan.bold(
"https://my-theme.keycloakify.dev/"
)}`,
"",
"You can login with the following credentials:",
`- username: ${chalk.cyan.bold("testuser")}`,
`- password: ${chalk.cyan.bold("password123")}`,
2024-05-20 02:27:40 +02:00
"",
2024-05-20 15:48:51 +02:00
`Keycloak Admin console: ${chalk.cyan.bold(
`http://localhost:${cliCommandOptions.port}`
)}`,
`- user: ${chalk.cyan.bold("admin")}`,
2024-05-20 02:27:40 +02:00
`- password: ${chalk.cyan.bold("admin")}`,
"",
2024-05-20 15:48:51 +02:00
`Watching for changes in ${chalk.bold(
`.${pathSep}${pathRelative(process.cwd(), srcDirPath)}`
)}`
2024-05-18 10:02:14 +02:00
].join("\n")
);
};
child.stdout.on("data", handler);
}
2024-05-20 02:27:40 +02:00
{
const runFullBuild = runExclusive.build(async () => {
2024-05-20 19:30:04 +02:00
console.log(chalk.cyan("Detected changes in the theme. Rebuilding ..."));
2024-05-20 15:34:07 +02:00
const { isAppBuildSuccess } = await appBuild({
doSkipIfReactAppBuildDirExists: false,
buildOptions
});
2024-05-20 02:27:40 +02:00
if (!isAppBuildSuccess) {
return;
2024-05-20 19:30:04 +02:00
}
2024-05-20 02:27:40 +02:00
const { isKeycloakifyBuildSuccess } = await keycloakifyBuild({
doSkipBuildJars: true,
buildOptions
});
2024-05-20 02:42:57 +02:00
if (!isKeycloakifyBuildSuccess) {
return;
}
2024-05-20 19:30:04 +02:00
accountThemePropertyPatch?.();
2024-05-20 19:30:04 +02:00
console.log(chalk.green("Theme rebuilt and updated in Keycloak."));
2024-05-20 19:30:04 +02:00
});
const { waitForDebounce } = waitForDebounceFactory({ delay: 400 });
2024-05-20 19:30:04 +02:00
chokidar
.watch([srcDirPath, pathJoin(getThisCodebaseRootDirPath(), "src")], {
2024-05-20 19:30:04 +02:00
ignoreInitial: true
})
.on("all", async () => {
2024-05-20 19:30:04 +02:00
await waitForDebounce();
runFullBuild();
2024-05-20 15:48:51 +02:00
});
2024-05-20 02:27:40 +02:00
}
}