Compare commits

...
Author SHA1 Message Date
Thomas Camlong 3dc382145c refactor(cli): rewrite CLI for reliability and better UX
Replace brocli framework with Node's built-in util.parseArgs and a
declarative command registry. The CLI no longer hangs after completing
because:
- DB connections are lazily created and explicitly closed
- Winston/Redis logging is excluded from the bundle entirely
- process.exit() is always called with proper exit codes

Additional improvements:
- Bundle size reduced from 5.3MB to 1.2MB (native drivers externalized)
- Proper column-aligned table output for list commands
- --json flag on list commands for scripting/automation
- Per-command --help with usage examples
- Execution timing shown on success
- Consistent exit codes (0=success, 1=error, 2=usage)
- Docker wrapper sets DISABLE_REDIS_LOGS and uses exec
2026-05-21 16:05:27 +02:00
20 changed files with 2137 additions and 1358 deletions

No files matched your search

+1 -1
View File
@@ -30,7 +30,7 @@ VOLUME /appdata
# Enable homarr cli # Enable homarr cli
COPY --from=builder /app/packages/cli/cli.cjs /app/apps/cli/cli.cjs COPY --from=builder /app/packages/cli/cli.cjs /app/apps/cli/cli.cjs
RUN echo $'#!/bin/bash\ncd /app/apps/cli && node ./cli.cjs "$@"' > /usr/bin/homarr RUN echo $'#!/bin/bash\nexport DISABLE_REDIS_LOGS=true\ncd /app/apps/cli && exec node ./cli.cjs "$@"' > /usr/bin/homarr
RUN chmod +x /usr/bin/homarr RUN chmod +x /usr/bin/homarr
# Don't run production as root # Don't run production as root
+7 -3
View File
@@ -15,7 +15,7 @@
} }
}, },
"scripts": { "scripts": {
"build": "esbuild src/index.ts --bundle --platform=node --outfile=cli.cjs --external:bcrypt --external:cpu-features --loader:.html=text --loader:.node=text", "build": "esbuild src/index.ts --bundle --platform=node --outfile=cli.cjs --external:bcrypt --external:cpu-features --external:better-sqlite3 --external:mysql2 --external:pg --loader:.html=text --loader:.node=text",
"clean": "rm -rf .turbo node_modules", "clean": "rm -rf .turbo node_modules",
"format": "prettier --check . --ignore-path ../../.gitignore", "format": "prettier --check . --ignore-path ../../.gitignore",
"lint": "eslint", "lint": "eslint",
@@ -25,12 +25,16 @@
}, },
"prettier": "@homarr/prettier-config", "prettier": "@homarr/prettier-config",
"dependencies": { "dependencies": {
"@drizzle-team/brocli": "catalog:",
"@homarr/auth": "workspace:^0.1.0", "@homarr/auth": "workspace:^0.1.0",
"@homarr/common": "workspace:^0.1.0", "@homarr/common": "workspace:^0.1.0",
"@homarr/core": "workspace:^0.1.0",
"@homarr/db": "workspace:^0.1.0", "@homarr/db": "workspace:^0.1.0",
"@homarr/validation": "workspace:^0.1.0", "@homarr/validation": "workspace:^0.1.0",
"dotenv": "catalog:" "better-sqlite3": "catalog:",
"dotenv": "catalog:",
"drizzle-orm": "catalog:",
"mysql2": "catalog:",
"pg": "catalog:"
}, },
"devDependencies": { "devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0", "@homarr/eslint-config": "workspace:^0.2.0",
+127
View File
@@ -0,0 +1,127 @@
import Database from "better-sqlite3";
import { drizzle as drizzleSqlite } from "drizzle-orm/better-sqlite3";
import { drizzle as drizzleMysql } from "drizzle-orm/mysql2";
import { drizzle as drizzlePostgres } from "drizzle-orm/node-postgres";
import mysql from "mysql2";
import type { Pool as MysqlPool } from "mysql2";
import { Pool as PostgresPool } from "pg";
import { DB_CASING } from "@homarr/core/infrastructure/db/constants";
import { dbEnv } from "@homarr/core/infrastructure/db/env";
import { schema } from "@homarr/db/schema";
const CONNECT_TIMEOUT_MS = 10_000;
const dbConfig = {
schema,
casing: DB_CASING,
};
export type CliDatabase = ReturnType<typeof drizzleSqlite<typeof schema>>;
type CliConnection =
| { driver: "better-sqlite3"; raw: Database.Database; db: CliDatabase }
| { driver: "mysql2"; raw: MysqlPool; db: CliDatabase }
| { driver: "node-postgres"; raw: PostgresPool; db: CliDatabase };
let connection: CliConnection | null = null;
const createMysqlPool = () => {
const poolOptions = {
maxIdle: 0,
idleTimeout: 60000,
enableKeepAlive: true,
connectTimeout: CONNECT_TIMEOUT_MS,
};
if (!dbEnv.HOST) {
return mysql.createPool({ ...poolOptions, uri: dbEnv.URL });
}
return mysql.createPool({
...poolOptions,
host: dbEnv.HOST,
port: dbEnv.PORT,
database: dbEnv.NAME,
user: dbEnv.USER,
password: dbEnv.PASSWORD,
});
};
const createPostgresPool = () => {
const poolOptions = {
max: 1,
idleTimeoutMillis: 60000,
connectionTimeoutMillis: CONNECT_TIMEOUT_MS,
allowExitOnIdle: true,
};
if (!dbEnv.HOST) {
return new PostgresPool({
...poolOptions,
connectionString: dbEnv.URL,
});
}
return new PostgresPool({
...poolOptions,
host: dbEnv.HOST,
port: dbEnv.PORT,
database: dbEnv.NAME,
user: dbEnv.USER,
password: dbEnv.PASSWORD,
});
};
const connectionFactories = {
"better-sqlite3": (): CliConnection => {
const raw = new Database(dbEnv.URL);
const db = drizzleSqlite(raw, dbConfig);
return { driver: "better-sqlite3", raw, db };
},
mysql2: (): CliConnection => {
const raw = createMysqlPool();
const db = drizzleMysql(raw, { ...dbConfig, mode: "default" }) as unknown as CliDatabase;
return { driver: "mysql2", raw, db };
},
"node-postgres": (): CliConnection => {
const raw = createPostgresPool();
const db = drizzlePostgres({ ...dbConfig, client: raw }) as unknown as CliDatabase;
return { driver: "node-postgres", raw, db };
},
};
const closeHandlers: Record<CliConnection["driver"], (entry: CliConnection) => Promise<void>> = {
"better-sqlite3": async (entry) => {
(entry as Extract<CliConnection, { driver: "better-sqlite3" }>).raw.close();
},
mysql2: (entry) => {
const pool = (entry as Extract<CliConnection, { driver: "mysql2" }>).raw;
return new Promise<void>((resolve, reject) => {
pool.end((err) => (err ? reject(err) : resolve()));
});
},
"node-postgres": async (entry) => {
await (entry as Extract<CliConnection, { driver: "node-postgres" }>).raw.end();
},
};
export const getCliDb = (): CliDatabase => {
if (connection) {
return connection.db;
}
const driver = dbEnv.DRIVER ?? "better-sqlite3";
connection = connectionFactories[driver]();
return connection.db;
};
export const closeCliDbAsync = async (): Promise<void> => {
if (!connection) {
return;
}
const current = connection;
connection = null;
await closeHandlers[current.driver](current);
};
+14 -15
View File
@@ -1,25 +1,24 @@
import { command } from "@drizzle-team/brocli"; import { eq } from "drizzle-orm";
import { db, eq } from "@homarr/db"; import { getCliDb } from "../cli-db";
import { requireCredentialsProvider } from "../errors";
import { users } from "@homarr/db/schema"; import { users } from "@homarr/db/schema";
export const fixUsernames = command({ export async function fixUsernamesHandler(): Promise<number> {
name: "fix-usernames", requireCredentialsProvider();
desc: "Changes all credentials usernames to lowercase",
// eslint-disable-next-line no-restricted-syntax
handler: async () => {
if (!process.env.AUTH_PROVIDERS?.toLowerCase().includes("credentials")) {
console.error("Credentials provider is not enabled");
return;
}
const db = getCliDb();
const credentialUsers = await db.query.users.findMany({ const credentialUsers = await db.query.users.findMany({
where: eq(users.provider, "credentials"), where: eq(users.provider, "credentials"),
}); });
for (const user of credentialUsers) { for (const user of credentialUsers) {
if (!user.name) continue; if (!user.name) {
if (user.name === user.name.toLowerCase()) continue; continue;
}
if (user.name === user.name.toLowerCase()) {
continue;
}
await db await db
.update(users) .update(users)
@@ -32,5 +31,5 @@ export const fixUsernames = command({
} }
console.log("All usernames have been fixed"); console.log("All usernames have been fixed");
}, return 0;
}); }
@@ -1,39 +1,50 @@
import { command, string } from "@drizzle-team/brocli"; import { parseArgs } from "node:util";
import { db, eq } from "@homarr/db"; import { eq } from "drizzle-orm";
import type { CliDatabase } from "../cli-db";
import { getCliDb } from "../cli-db";
import { CliError } from "../errors";
import { integrations } from "@homarr/db/schema"; import { integrations } from "@homarr/db/schema";
export const integrationsDelete = command({ const integrationLookup: Record<
name: "delete", "id" | "name",
desc: "Delete an integration by id or name", (db: CliDatabase, value: string) => Promise<{ id: string; name: string } | undefined>
> = {
id: (db, value) =>
db.query.integrations.findFirst({
where: eq(integrations.id, value),
}),
name: (db, value) =>
db.query.integrations.findFirst({
where: eq(integrations.name, value),
}),
};
export async function integrationsDeleteHandler(args: string[]): Promise<number> {
const { values } = parseArgs({
args,
options: { options: {
id: string("id").alias("i").desc("ID of the integration"), id: { type: "string", short: "i" },
name: string("name").alias("n").desc("Name of the integration"), name: { type: "string", short: "n" },
}, },
// eslint-disable-next-line no-restricted-syntax });
handler: async (options) => {
if (!options.id && !options.name) { const lookupKey = values.id ? "id" : values.name ? "name" : null;
console.error("Either --id or --name must be provided"); const lookupValue = values.id ?? values.name;
return;
if (!lookupKey || !lookupValue) {
throw new CliError("Either --id or --name must be provided", 2);
} }
let entry; const db = getCliDb();
if (options.id) { const entry = await integrationLookup[lookupKey](db, lookupValue);
entry = await db.query.integrations.findFirst({
where: eq(integrations.id, options.id),
});
} else if (options.name) {
entry = await db.query.integrations.findFirst({
where: eq(integrations.name, options.name),
});
}
if (!entry) { if (!entry) {
console.error("Integration not found"); throw new CliError("Integration not found");
return;
} }
await db.delete(integrations).where(eq(integrations.id, entry.id)); await db.delete(integrations).where(eq(integrations.id, entry.id));
console.log(`Integration ${entry.name} (${entry.id}) deleted`); console.log(`Integration ${entry.name} (${entry.id}) deleted`);
}, return 0;
}); }
+27 -13
View File
@@ -1,21 +1,35 @@
import { command } from "@drizzle-team/brocli"; import { parseArgs } from "node:util";
import { db } from "@homarr/db"; import { getCliDb } from "../cli-db";
import { printTable } from "../utils";
export const integrationsList = command({ export async function integrationsListHandler(args: string[] = []): Promise<number> {
name: "list", const { values } = parseArgs({
desc: "List all integrations (id and name)", args,
// eslint-disable-next-line no-restricted-syntax options: {
handler: async () => { json: { type: "boolean", default: false },
},
strict: false,
});
const db = getCliDb();
const all = await db.query.integrations.findMany(); const all = await db.query.integrations.findMany();
if (values.json) {
const output = all.map((i) => ({ id: i.id, name: i.name, kind: i.kind, url: i.url }));
console.log(JSON.stringify(output, null, 2));
return 0;
}
if (all.length === 0) { if (all.length === 0) {
console.log("No integrations found"); console.log("No integrations found");
return; return 0;
} }
console.log("ID\t\t\t\tName"); printTable(
for (const i of all) { ["ID", "Name", "Kind", "URL"],
console.log(`${i.id}\t${i.name}`); all.map((i) => [i.id, i.name, i.kind, i.url]),
);
console.log(`\n${all.length} integration(s) total`);
return 0;
} }
},
});
-10
View File
@@ -1,10 +0,0 @@
import { command } from "@drizzle-team/brocli";
import { integrationsDelete } from "./integrations-delete";
import { integrationsList } from "./integrations-list";
export const integrationsRoot = command({
name: "integrations",
desc: "Group of commands to manage integrations",
subcommands: [integrationsList, integrationsDelete],
});
+33 -29
View File
@@ -1,34 +1,37 @@
import { command, string } from "@drizzle-team/brocli"; import { parseArgs } from "node:util";
import { hashPasswordAsync } from "@homarr/auth"; import { hashPasswordAsync } from "@homarr/auth/security";
import { createId } from "@homarr/common"; import { createId } from "@homarr/common";
import { generateSecureRandomToken } from "@homarr/common/server"; import { generateSecureRandomToken } from "../utils";
import { and, count, db, eq } from "@homarr/db"; import { and, count, eq, max } from "drizzle-orm";
import { getMaxGroupPositionAsync } from "@homarr/db/queries";
import { getCliDb } from "../cli-db";
import { CliError, requireCredentialsProvider } from "../errors";
import { groupMembers, groupPermissions, groups, users } from "@homarr/db/schema"; import { groupMembers, groupPermissions, groups, users } from "@homarr/db/schema";
import { usernameSchema } from "@homarr/validation/user"; import { usernameSchema } from "@homarr/validation/user";
export const recreateAdmin = command({ export async function recreateAdminHandler(args: string[]): Promise<number> {
name: "recreate-admin", requireCredentialsProvider();
desc: "Recreate credentials admin user if none exists anymore",
const { values } = parseArgs({
args,
options: { options: {
username: string("username").required().alias("u").desc("Name of the admin"), username: { type: "string", short: "u" },
}, },
// eslint-disable-next-line no-restricted-syntax });
handler: async (options) => {
if (!process.env.AUTH_PROVIDERS?.toLowerCase().includes("credentials")) { if (!values.username) {
console.error("Credentials provider is not enabled"); throw new CliError("Missing required option: --username / -u", 2);
return;
} }
const result = await usernameSchema.safeParseAsync(options.username); const result = await usernameSchema.safeParseAsync(values.username);
if (!result.success) { if (!result.success) {
console.error("Invalid username:"); const messages = result.error.issues.map((issue) => `- ${issue.message}`).join("\n");
console.error(result.error.issues.map((error) => `- ${error.message}`).join("\n")); throw new CliError(`Invalid username:\n${messages}`, 2);
return;
} }
const db = getCliDb();
const totalCount = await db const totalCount = await db
.select({ .select({
count: count(), count: count(),
@@ -37,11 +40,10 @@ export const recreateAdmin = command({
.leftJoin(groupMembers, eq(groupMembers.groupId, groupPermissions.groupId)) .leftJoin(groupMembers, eq(groupMembers.groupId, groupPermissions.groupId))
.leftJoin(users, eq(users.id, groupMembers.userId)) .leftJoin(users, eq(users.id, groupMembers.userId))
.where(and(eq(groupPermissions.permission, "admin"), eq(users.provider, "credentials"))) .where(and(eq(groupPermissions.permission, "admin"), eq(users.provider, "credentials")))
.then((rows) => rows.at(0)?.count ?? 0); .then((rows: { count: number }[]) => rows.at(0)?.count ?? 0);
if (totalCount > 0) { if (totalCount > 0) {
console.error("Credentials admin user exists"); throw new CliError("Credentials admin user exists");
return;
} }
const existingUser = await db.query.users.findFirst({ const existingUser = await db.query.users.findFirst({
@@ -49,13 +51,15 @@ export const recreateAdmin = command({
}); });
if (existingUser) { if (existingUser) {
console.error("User with this name already exists"); throw new CliError("User with this name already exists");
return;
} }
const temporaryGroupId = createId(); const temporaryGroupId = createId();
const maxPosition = await db
.select({ value: max(groups.position) })
.from(groups)
.then((result: { value: number | null }[]) => result[0]?.value ?? 1);
const maxPosition = await getMaxGroupPositionAsync(db);
await db.insert(groups).values({ await db.insert(groups).values({
id: temporaryGroupId, id: temporaryGroupId,
name: temporaryGroupId, name: temporaryGroupId,
@@ -69,8 +73,8 @@ export const recreateAdmin = command({
const password = generateSecureRandomToken(24); const password = generateSecureRandomToken(24);
const hashedPassword = await hashPasswordAsync(password); const hashedPassword = await hashPasswordAsync(password);
const userId = createId(); const userId = createId();
await db.insert(users).values({ await db.insert(users).values({
id: userId, id: userId,
name: result.data, name: result.data,
@@ -89,6 +93,6 @@ export const recreateAdmin = command({
console.log(`\tUsername: ${result.data}`); console.log(`\tUsername: ${result.data}`);
console.log(`\tPassword: ${password}`); console.log(`\tPassword: ${password}`);
console.log(`\tGroup: ${temporaryGroupId}`); console.log(`\tGroup: ${temporaryGroupId}`);
console.log(""); // Empty line for better readability console.log("");
}, return 0;
}); }
+24 -22
View File
@@ -1,33 +1,36 @@
import { command, string } from "@drizzle-team/brocli"; import { parseArgs } from "node:util";
import { hashPasswordAsync } from "@homarr/auth"; import { hashPasswordAsync } from "@homarr/auth/security";
import { generateSecureRandomToken } from "@homarr/common/server"; import { generateSecureRandomToken } from "../utils";
import { and, db, eq } from "@homarr/db"; import { and, eq } from "drizzle-orm";
import { getCliDb } from "../cli-db";
import { CliError, requireCredentialsProvider } from "../errors";
import { sessions, users } from "@homarr/db/schema"; import { sessions, users } from "@homarr/db/schema";
export const resetPassword = command({ export async function resetPasswordHandler(args: string[]): Promise<number> {
name: "reset-password", requireCredentialsProvider();
desc: "Reset password for a user",
const { values } = parseArgs({
args,
options: { options: {
username: string("username").required().alias("u").desc("Name of the user"), username: { type: "string", short: "u" },
}, },
// eslint-disable-next-line no-restricted-syntax });
handler: async (options) => {
if (!process.env.AUTH_PROVIDERS?.toLowerCase().includes("credentials")) { if (!values.username) {
console.error("Credentials provider is not enabled"); throw new CliError("Missing required option: --username / -u", 2);
return;
} }
const db = getCliDb();
const user = await db.query.users.findFirst({ const user = await db.query.users.findFirst({
where: and(eq(users.name, options.username), eq(users.provider, "credentials")), where: and(eq(users.name, values.username), eq(users.provider, "credentials")),
}); });
if (!user?.password) { if (!user?.password) {
console.error(`User ${options.username} not found`); throw new CliError(`User ${values.username} not found`);
return;
} }
// Generates a new password with 48 characters
const newPassword = generateSecureRandomToken(24); const newPassword = generateSecureRandomToken(24);
await db await db
@@ -38,9 +41,8 @@ export const resetPassword = command({
.where(eq(users.id, user.id)); .where(eq(users.id, user.id));
await db.delete(sessions).where(eq(sessions.userId, user.id)); await db.delete(sessions).where(eq(sessions.userId, user.id));
console.log(`All sessions for user ${options.username} have been deleted`); console.log(`All sessions for user ${values.username} have been deleted`);
console.log("You can now login with the new password"); console.log("You can now login with the new password");
console.log(`New password for user ${options.username}: ${newPassword}`); console.log(`New password for user ${values.username}: ${newPassword}`);
}, return 0;
}); }
+34 -26
View File
@@ -1,39 +1,47 @@
import { command, string } from "@drizzle-team/brocli"; import { parseArgs } from "node:util";
import { db, eq } from "@homarr/db"; import { eq } from "drizzle-orm";
import type { CliDatabase } from "../cli-db";
import { getCliDb } from "../cli-db";
import { CliError } from "../errors";
import { users } from "@homarr/db/schema"; import { users } from "@homarr/db/schema";
export const usersDelete = command({ const userLookup: Record<"id" | "username", (db: CliDatabase, value: string) => Promise<{ id: string; name: string | null } | undefined>> = {
name: "delete", id: (db, value) =>
desc: "Delete a user by id or username", db.query.users.findFirst({
where: eq(users.id, value),
}),
username: (db, value) =>
db.query.users.findFirst({
where: eq(users.name, value),
}),
};
export async function usersDeleteHandler(args: string[]): Promise<number> {
const { values } = parseArgs({
args,
options: { options: {
id: string("id").alias("i").desc("ID of the user"), id: { type: "string", short: "i" },
username: string("username").alias("u").desc("Name of the user"), username: { type: "string", short: "u" },
}, },
// eslint-disable-next-line no-restricted-syntax });
handler: async (options) => {
if (!options.id && !options.username) { const lookupKey = values.id ? "id" : values.username ? "username" : null;
console.error("Either --id or --username must be provided"); const lookupValue = values.id ?? values.username;
return;
if (!lookupKey || !lookupValue) {
throw new CliError("Either --id or --username must be provided", 2);
} }
let user; const db = getCliDb();
if (options.id) { const user = await userLookup[lookupKey](db, lookupValue);
user = await db.query.users.findFirst({
where: eq(users.id, options.id),
});
} else if (options.username) {
user = await db.query.users.findFirst({
where: eq(users.name, options.username),
});
}
if (!user) { if (!user) {
console.error("User not found"); throw new CliError("User not found");
return;
} }
await db.delete(users).where(eq(users.id, user.id)); await db.delete(users).where(eq(users.id, user.id));
console.log(`User ${user.name ?? user.id} (${user.id}) deleted`); console.log(`User ${user.name ?? user.id} (${user.id}) deleted`);
}, return 0;
}); }
+26 -13
View File
@@ -1,22 +1,35 @@
import { command } from "@drizzle-team/brocli"; import { parseArgs } from "node:util";
import { db } from "@homarr/db"; import { getCliDb } from "../cli-db";
import { printTable } from "../utils";
export const usersList = command({ export async function usersListHandler(args: string[] = []): Promise<number> {
name: "list", const { values } = parseArgs({
desc: "List all users (id, username, email)", args,
// eslint-disable-next-line no-restricted-syntax options: {
handler: async () => { json: { type: "boolean", default: false },
},
strict: false,
});
const db = getCliDb();
const allUsers = await db.query.users.findMany(); const allUsers = await db.query.users.findMany();
if (values.json) {
const output = allUsers.map((u) => ({ id: u.id, name: u.name, email: u.email, provider: u.provider }));
console.log(JSON.stringify(output, null, 2));
return 0;
}
if (allUsers.length === 0) { if (allUsers.length === 0) {
console.log("No users found"); console.log("No users found");
return; return 0;
} }
console.log("ID\t\t\t\tUsername\tEmail"); printTable(
for (const user of allUsers) { ["ID", "Username", "Email", "Provider"],
console.log(`${user.id}\t${user.name ?? ""}\t${user.email ?? ""}`); allUsers.map((u) => [u.id, u.name ?? "", u.email ?? "", u.provider]),
);
console.log(`\n${allUsers.length} user(s) total`);
return 0;
} }
},
});
@@ -1,50 +1,66 @@
import { command, string } from "@drizzle-team/brocli"; import { parseArgs } from "node:util";
import { hashPasswordAsync } from "@homarr/auth"; import { hashPasswordAsync } from "@homarr/auth/security";
import { db, eq } from "@homarr/db"; import { eq } from "drizzle-orm";
import type { CliDatabase } from "../cli-db";
import { getCliDb } from "../cli-db";
import { CliError, requireCredentialsProvider } from "../errors";
import { sessions, users } from "@homarr/db/schema"; import { sessions, users } from "@homarr/db/schema";
export const usersUpdatePassword = command({ const userLookup: Record<
name: "update-password", "id" | "username",
desc: "Update the password for a user (credentials provider only)", (db: CliDatabase, value: string) => Promise<{ id: string; name: string | null; password: string | null } | undefined>
> = {
id: (db, value) =>
db.query.users.findFirst({
where: eq(users.id, value),
}),
username: (db, value) =>
db.query.users.findFirst({
where: eq(users.name, value),
}),
};
export async function usersUpdatePasswordHandler(args: string[]): Promise<number> {
requireCredentialsProvider();
const { values } = parseArgs({
args,
options: { options: {
id: string("id").alias("i").desc("ID of the user"), id: { type: "string", short: "i" },
username: string("username").alias("u").desc("Name of the user"), username: { type: "string", short: "u" },
password: string("password").alias("p").required().desc("New password"), password: { type: "string", short: "p" },
}, },
// eslint-disable-next-line no-restricted-syntax
handler: async (options) => {
if (!process.env.AUTH_PROVIDERS?.toLowerCase().includes("credentials")) {
console.error("Credentials provider is not enabled");
return;
}
if (!options.id && !options.username) {
console.error("Either --id or --username must be provided");
return;
}
const user = await db.query.users.findFirst({
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
where: options.id ? eq(users.id, options.id) : eq(users.name, options.username!),
}); });
const lookupKey = values.id ? "id" : values.username ? "username" : null;
const lookupValue = values.id ?? values.username;
if (!lookupKey || !lookupValue) {
throw new CliError("Either --id or --username must be provided", 2);
}
if (!values.password) {
throw new CliError("Missing required option: --password / -p", 2);
}
const db = getCliDb();
const user = await userLookup[lookupKey](db, lookupValue);
if (!user?.password) { if (!user?.password) {
console.error("User not found or has no credentials record"); throw new CliError("User not found or has no credentials record");
return;
} }
await db await db
.update(users) .update(users)
.set({ .set({
password: await hashPasswordAsync(options.password), password: await hashPasswordAsync(values.password),
}) })
.where(eq(users.id, user.id)); .where(eq(users.id, user.id));
// invalidate existing sessions
await db.delete(sessions).where(eq(sessions.userId, user.id)); await db.delete(sessions).where(eq(sessions.userId, user.id));
console.log(`All sessions for user ${user.name ?? user.id} have been deleted`); console.log(`All sessions for user ${user.name ?? user.id} have been deleted`);
console.log("Password updated successfully"); console.log("Password updated successfully");
}, return 0;
}); }
-11
View File
@@ -1,11 +0,0 @@
import { command } from "@drizzle-team/brocli";
import { usersDelete } from "./users-delete";
import { usersList } from "./users-list";
import { usersUpdatePassword } from "./users-update-password";
export const usersRoot = command({
name: "users",
desc: "Group of commands to manage users",
subcommands: [usersList, usersDelete, usersUpdatePassword],
});
+16
View File
@@ -0,0 +1,16 @@
export class CliError extends Error {
constructor(
message: string,
readonly exitCode: 1 | 2 = 1,
) {
super(message);
this.name = "CliError";
}
}
export const requireCredentialsProvider = () => {
const enabled = process.env.AUTH_PROVIDERS?.toLowerCase().includes("credentials") ?? false;
if (!enabled) {
throw new CliError("Credentials provider is not enabled");
}
};
+37 -10
View File
@@ -1,14 +1,41 @@
import { run } from "@drizzle-team/brocli"; import { closeCliDbAsync } from "./cli-db";
import { CliError } from "./errors";
import { runCliAsync } from "./router";
import { fixUsernames } from "./commands/fix-usernames"; const mainAsync = async (): Promise<number> => {
import { integrationsRoot } from "./commands/integrations"; const argv = process.argv.slice(2);
import { recreateAdmin } from "./commands/recreate-admin"; const start = performance.now();
import { resetPassword } from "./commands/reset-password";
import { usersRoot } from "./commands/users";
const commands = [usersRoot, integrationsRoot, resetPassword, fixUsernames, recreateAdmin]; try {
const code = await runCliAsync(argv);
if (code === 0) {
const elapsed = Math.round(performance.now() - start);
console.error(`\nDone in ${elapsed}ms`);
}
return code;
} catch (error) {
if (error instanceof CliError) {
console.error(error.message);
return error.exitCode;
}
void run(commands, { if (error instanceof TypeError && error.message.startsWith("Unknown option")) {
name: "homarr-cli", console.error(error.message);
version: "1.0.0", return 2;
}
console.error(error instanceof Error ? error.message : error);
return 1;
}
};
mainAsync()
.then(async (code) => {
await closeCliDbAsync();
process.exit(code);
})
.catch(async (error) => {
console.error(error instanceof Error ? error.message : error);
await closeCliDbAsync();
process.exit(1);
}); });
+167
View File
@@ -0,0 +1,167 @@
import { fixUsernamesHandler } from "./commands/fix-usernames";
import { integrationsDeleteHandler } from "./commands/integrations-delete";
import { integrationsListHandler } from "./commands/integrations-list";
import { recreateAdminHandler } from "./commands/recreate-admin";
import { resetPasswordHandler } from "./commands/reset-password";
import { usersDeleteHandler } from "./commands/users-delete";
import { usersListHandler } from "./commands/users-list";
import { usersUpdatePasswordHandler } from "./commands/users-update-password";
import { CliError } from "./errors";
const VERSION = "1.0.0";
type CommandHandler = (args: string[]) => Promise<number>;
interface CommandDef {
handler: CommandHandler;
desc: string;
usage: string;
}
type CommandGroup = Record<string, CommandDef>;
const topLevelCommands: Record<string, CommandDef> = {
"reset-password": {
handler: resetPasswordHandler,
desc: "Reset password for a credentials user",
usage: "homarr reset-password -u <username>",
},
"fix-usernames": {
handler: (args) => fixUsernamesHandler(),
desc: "Lowercase all credentials usernames",
usage: "homarr fix-usernames",
},
"recreate-admin": {
handler: recreateAdminHandler,
desc: "Create credentials admin if none exists",
usage: "homarr recreate-admin -u <username>",
},
};
const commandGroups: Record<string, CommandGroup> = {
users: {
list: {
handler: (args) => usersListHandler(args),
desc: "List all users",
usage: "homarr users list [--json]",
},
delete: {
handler: usersDeleteHandler,
desc: "Delete a user by id or username",
usage: "homarr users delete --id <id> | --username <name>",
},
"update-password": {
handler: usersUpdatePasswordHandler,
desc: "Set password for a credentials user",
usage: "homarr users update-password (--id <id> | --username <name>) --password <pw>",
},
},
integrations: {
list: {
handler: (args) => integrationsListHandler(args),
desc: "List all integrations",
usage: "homarr integrations list [--json]",
},
delete: {
handler: integrationsDeleteHandler,
desc: "Delete an integration by id or name",
usage: "homarr integrations delete --id <id> | --name <name>",
},
},
};
const HELP_TEXT = `homarr-cli ${VERSION}
Usage:
homarr <command> [options]
Commands:
reset-password Reset password for a credentials user
recreate-admin Create credentials admin if none exists
fix-usernames Lowercase all credentials usernames
users list List all users
users delete Delete a user by id or username
users update-password Set password for a credentials user
integrations list List all integrations
integrations delete Delete an integration by id or name
Global Options:
-h, --help Show help (use after a command for command-specific help)
-v, --version Show CLI version
`;
const printHelp = () => {
console.log(HELP_TEXT);
};
const printCommandHelp = (def: CommandDef) => {
console.log(`${def.desc}\n`);
console.log(`Usage:\n ${def.usage}\n`);
};
const resolveHandler = (argv: string[]): { handler: CommandHandler; args: string[] } => {
const [command, subcommand, ...rest] = argv;
if (!command) {
throw new CliError("Missing command", 2);
}
const group = commandGroups[command];
if (group) {
if (!subcommand || subcommand === "--help" || subcommand === "-h") {
const subcommands = Object.entries(group)
.map(([name, def]) => ` ${name.padEnd(18)} ${def.desc}`)
.join("\n");
console.log(`Usage:\n homarr ${command} <subcommand> [options]\n\nSubcommands:\n${subcommands}\n`);
return { handler: async () => subcommand ? 0 : 2, args: [] };
}
const def = group[subcommand];
if (!def) {
throw new CliError(`Unknown subcommand "${subcommand}" for "${command}"`, 2);
}
if (hasFlag(rest, "--help", "-h")) {
printCommandHelp(def);
return { handler: async () => 0, args: [] };
}
return { handler: def.handler, args: rest };
}
const def = topLevelCommands[command];
if (!def) {
throw new CliError(`Unknown command "${command}"`, 2);
}
const args = argv.slice(1);
if (hasFlag(args, "--help", "-h")) {
printCommandHelp(def);
return { handler: async () => 0, args: [] };
}
return { handler: def.handler, args };
};
const hasFlag = (argv: string[], flag: string, short: string) =>
argv.some((arg) => arg === flag || arg === short);
export const runCliAsync = async (argv: string[]): Promise<number> => {
if (hasFlag(argv, "--help", "-h") && argv.length === 1) {
printHelp();
return 0;
}
if (hasFlag(argv, "--version", "-v")) {
console.log(VERSION);
return 0;
}
if (argv.length === 0) {
printHelp();
return 2;
}
const { handler, args } = resolveHandler(argv);
return handler(args);
};
+18
View File
@@ -0,0 +1,18 @@
import { randomBytes } from "node:crypto";
export const generateSecureRandomToken = (size: number) => randomBytes(size).toString("hex");
export const printTable = (headers: string[], rows: string[][]) => {
const widths = headers.map((h, i) =>
Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length)),
);
const formatRow = (cells: string[]) =>
cells.map((cell, i) => cell.padEnd(widths[i]!)).join(" ");
console.log(formatRow(headers));
console.log(widths.map((w) => "─".repeat(w)).join(" "));
for (const row of rows) {
console.log(formatRow(row));
}
};
+1
View File
@@ -14,6 +14,7 @@
"./infrastructure/db": "./src/infrastructure/db/index.ts", "./infrastructure/db": "./src/infrastructure/db/index.ts",
"./infrastructure/db/env": "./src/infrastructure/db/env.ts", "./infrastructure/db/env": "./src/infrastructure/db/env.ts",
"./infrastructure/db/constants": "./src/infrastructure/db/constants.ts", "./infrastructure/db/constants": "./src/infrastructure/db/constants.ts",
"./infrastructure/db/mapping": "./src/infrastructure/db/mapping.ts",
"./infrastructure/certificates": "./src/infrastructure/certificates/index.ts", "./infrastructure/certificates": "./src/infrastructure/certificates/index.ts",
"./infrastructure/certificates/hostnames/db/sqlite": "./src/infrastructure/certificates/hostnames/db/sqlite.ts", "./infrastructure/certificates/hostnames/db/sqlite": "./src/infrastructure/certificates/hostnames/db/sqlite.ts",
"./infrastructure/certificates/hostnames/db/mysql": "./src/infrastructure/certificates/hostnames/db/mysql.ts", "./infrastructure/certificates/hostnames/db/mysql": "./src/infrastructure/certificates/hostnames/db/mysql.ts",
+1 -1
View File
@@ -1,6 +1,6 @@
import type { InferSelectModel } from "drizzle-orm"; import type { InferSelectModel } from "drizzle-orm";
import { createSchema } from "@homarr/core/infrastructure/db"; import { createDbMapping as createSchema } from "@homarr/core/infrastructure/db/mapping";
import * as mysqlSchema from "./mysql"; import * as mysqlSchema from "./mysql";
import * as pgSchema from "./postgresql"; import * as pgSchema from "./postgresql";
+1520 -1147
View File
File diff suppressed because it is too large. Load diff