Compare commits

..
Author SHA1 Message Date
Releases Homarr b34102a973 chore(release): 1.61.1-beta.1 [skip ci] 2026-05-08 21:55:01 +00:00
homarr-releases[bot] 378d1e1f1f chore(release): release v1.61.1-beta 2026-05-08 21:53:57 +00:00
Meier Lukas 6feb37dfd4 Merge branch 'main' into next 2026-05-08 23:46:21 +02:00
Releases Homarr c83fdb2a6e chore(release): 1.60.1-beta.2 [skip ci] 2026-05-07 16:39:41 +00:00
homarr-releases[bot] 81fdd90e7a chore(release): release v1.60.1-beta 2026-05-07 16:38:37 +00:00
Thomas 5ee84f8cf4 perf: (next branch) reduce idle memory on startup (#5637) 2026-05-06 21:39:26 +00:00
Releases Homarr 80d18bb10d chore(release): 1.60.1-beta.1 [skip ci] 2026-05-01 20:44:34 +00:00
homarr-releases[bot] 2bb0f61da7 chore(release): release v1.60.1-beta 2026-05-01 20:43:32 +00:00
Meier Lukas 24386656fd Merge branch 'next' of https://github.com/homarr-labs/homarr into next 2026-05-01 22:42:07 +02:00
Meier Lukas 453360fe61 ci: disable package-manager cache 2026-05-01 22:42:02 +02:00
Releases Homarr beac1ed780 chore(release): 1.60.1-beta.1 [skip ci] 2026-05-01 20:41:02 +00:00
homarr-releases[bot] aa1b3810f1 chore(release): release v1.60.1-beta 2026-05-01 20:40:05 +00:00
Meier Lukas ce3c1b6cc1 chore: retrigger release v1.60.1-beta.1 2026-05-01 22:38:50 +02:00
Releases Homarr 3f6b830f9b chore(release): 1.60.1-beta.1 [skip ci] 2026-05-01 20:36:08 +00:00
homarr-releases[bot] f0cb79799a chore(release): release v1.60.1-beta 2026-05-01 20:35:08 +00:00
Meier Lukas 7561462594 Merge branch 'main' into next 2026-05-01 22:30:33 +02:00
Meier LukasandCopilot bfa8566284 ci: add beta release workflow (#5601)
Co-authored-by: Copilot <copilot@github.com>
2026-05-01 22:18:45 +02:00
Meier LukasandCopilot a1aa5505a3 perf(memory): combine 3 node processes into one (#5600)
Co-authored-by: Copilot <copilot@github.com>
2026-05-01 16:35:11 +02:00
Meier LukasandCopilot e77b9bb3d2 ci: support releases on next branch (#5599)
Co-authored-by: Copilot <copilot@github.com>
2026-04-30 18:28:32 +02:00
44 changed files with 5421 additions and 6446 deletions

No files matched your search

-4
View File
@@ -12,10 +12,6 @@ AUTH_SECRET="supersecret"
# or starting the project without any (which will show a randomly generated one).
SECRET_ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000
# Cron job API key is generated every time the container starts as it is required for communication between nextjs-api and tasks-api
# export CRON_JOB_API_KEY=$(openssl rand -base64 32)
# CRON_JOB_API_KEY="your-generated-api-key"
LOG_LEVEL='info'
# This is how you can use the sqlite driver:
+10 -8
View File
@@ -5,6 +5,7 @@ on:
branches:
- main
- beta
- next
- dev
workflow_dispatch:
inputs:
@@ -34,7 +35,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 5
env:
SKIP_RELEASE: ${{ github.event_name == 'workflow_dispatch' || github.ref_name == 'dev' }}
SKIP_RELEASE: ${{ github.event_name == 'workflow_dispatch' || github.ref_name == 'dev' || github.ref_name == 'next' }}
outputs:
version: ${{ steps.read-semver.outputs.version || steps.version-fallback.outputs.version }}
git_ref: ${{ steps.read-git-ref.outputs.ref || github.ref }}
@@ -54,7 +55,7 @@ jobs:
with:
private-key: ${{ secrets.RENOVATE_MERGE_PRIVATE_KEY }}
client-id: ${{ secrets.RENOVATE_MERGE_APP_ID }}
permission-contents: write # required to commit package.json & changelog changes, merge them to dev and publish the release
permission-contents: write # required to commit package.json & changelog changes, merge them to dev / next and publish the release
- uses: actions/checkout@v6
if: env.SKIP_RELEASE == 'false'
@@ -66,7 +67,7 @@ jobs:
if: env.SKIP_RELEASE == 'false'
with:
node-version: 24.15.0
cache: "pnpm"
package-manager-cache: false
- run: npm i -g pnpm
if: env.SKIP_RELEASE == 'false'
- name: Install dependencies
@@ -95,20 +96,21 @@ jobs:
id: read-git-ref
run: |
echo "ref=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
- name: Update dev branch
- name: Update dev / next branch
if: env.SKIP_RELEASE == 'false'
continue-on-error: true # Prevent pipeline from failing when merge fails
env:
GITHUB_TOKEN: ${{ steps.obtainToken.outputs.token }}
UPSTREAM_BRANCH: ${{ github.ref_name == 'main' && 'dev' || 'next' }}
run: |
git config user.name "Releases Homarr"
git config user.email "175486441+homarr-releases[bot]@users.noreply.github.com"
git remote set-url origin https://x-access-token:${{ steps.obtainToken.outputs.token }}@github.com/${{ github.repository }}.git
git fetch origin dev
git checkout dev
git pull origin dev
git fetch origin ${{ env.UPSTREAM_BRANCH }}
git checkout ${{ env.UPSTREAM_BRANCH }}
git pull origin ${{ env.UPSTREAM_BRANCH }}
git rebase ${{ github.ref_name }}
git push origin dev
git push origin ${{ env.UPSTREAM_BRANCH }}
build-amd64:
name: Build docker image for amd64
needs: release
+3854 -3841
View File
File diff suppressed because it is too large. Load diff
+1 -3
View File
@@ -30,7 +30,7 @@ VOLUME /appdata
# Enable homarr cli
COPY --from=builder /app/packages/cli/cli.cjs /app/apps/cli/cli.cjs
RUN echo $'#!/bin/bash\nexport DISABLE_REDIS_LOGS=true\ncd /app/apps/cli && exec node ./cli.cjs "$@"' > /usr/bin/homarr
RUN echo $'#!/bin/bash\ncd /app/apps/cli && node ./cli.cjs "$@"' > /usr/bin/homarr
RUN chmod +x /usr/bin/homarr
# Don't run production as root
@@ -43,8 +43,6 @@ RUN mkdir -p /var/cache/nginx && \
COPY --from=builder /app/apps/nextjs/next.config.ts .
COPY --from=builder /app/apps/nextjs/package.json .
COPY --from=builder /app/apps/tasks/tasks.cjs ./apps/tasks/tasks.cjs
COPY --from=builder /app/apps/websocket/wssServer.cjs ./apps/websocket/wssServer.cjs
COPY --from=builder /app/node_modules/better-sqlite3/build/Release/better_sqlite3.node /app/build/better_sqlite3.node
COPY --from=builder /app/packages/db/migrations ./db/migrations
+2
View File
@@ -32,6 +32,8 @@ const nextConfig: NextConfig = {
experimental: {
optimizePackageImports: ["@mantine/core", "@mantine/hooks", "@tabler/icons-react"],
turbopackFileSystemCacheForDev: true,
preloadEntriesOnStart: false,
webpackMemoryOptimizations: true,
},
transpilePackages: ["@homarr/ui", "@homarr/notifications", "@homarr/modals", "@homarr/spotlight", "@homarr/widgets"],
images: {
+2
View File
@@ -44,9 +44,11 @@
"@homarr/server-settings": "workspace:^0.1.0",
"@homarr/settings": "workspace:^0.1.0",
"@homarr/spotlight": "workspace:^0.1.0",
"@homarr/tasks": "workspace:^0.1.0",
"@homarr/translation": "workspace:^0.1.0",
"@homarr/ui": "workspace:^0.1.0",
"@homarr/validation": "workspace:^0.1.0",
"@homarr/websocket": "workspace:^0.1.0",
"@homarr/widgets": "workspace:^0.1.0",
"@mantine/colors-generator": "catalog:",
"@mantine/core": "catalog:",
+6
View File
@@ -0,0 +1,6 @@
export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
await import("@homarr/tasks");
await import("@homarr/websocket");
}
}
+1 -3
View File
@@ -5,12 +5,11 @@
"license": "Apache-2.0",
"type": "module",
"exports": {
".": "./src/index.ts"
".": "./src/main.ts"
},
"main": "./src/main.ts",
"types": "./src/main.ts",
"scripts": {
"build": "esbuild src/main.ts --bundle --platform=node --loader:.scss=text --external:*.node --external:@opentelemetry/api --external:deasync --external:bcrypt --outfile=tasks.cjs",
"clean": "rm -rf .turbo node_modules",
"dev": "pnpm with-env tsx ./src/main.ts",
"format": "prettier --check . --ignore-path ../../.gitignore",
@@ -24,7 +23,6 @@
"@homarr/auth": "workspace:^0.1.0",
"@homarr/common": "workspace:^0.1.0",
"@homarr/core": "workspace:^",
"@homarr/cron-job-api": "workspace:^0.1.0",
"@homarr/cron-jobs": "workspace:^0.1.0",
"@homarr/cron-jobs-core": "workspace:^0.1.0",
"@homarr/db": "workspace:^0.1.0",
-40
View File
@@ -1,52 +1,12 @@
// This import has to be the first import in the file so that the agent is overridden before any other modules are imported.
import "./overrides";
import type { FastifyTRPCPluginOptions } from "@trpc/server/adapters/fastify";
import { fastifyTRPCPlugin } from "@trpc/server/adapters/fastify";
import fastify from "fastify";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import type { JobRouter } from "@homarr/cron-job-api";
import { jobRouter } from "@homarr/cron-job-api";
import { CRON_JOB_API_KEY_HEADER, CRON_JOB_API_PATH, CRON_JOB_API_PORT } from "@homarr/cron-job-api/constants";
import { jobGroup } from "@homarr/cron-jobs";
import { db } from "@homarr/db";
import { JobManager } from "./job-manager";
import { onStartAsync } from "./on-start";
const logger = createLogger({ module: "tasksMain" });
const server = fastify({
maxParamLength: 5000,
});
server.register(fastifyTRPCPlugin, {
prefix: CRON_JOB_API_PATH,
trpcOptions: {
router: jobRouter,
createContext: ({ req }) => ({
manager: new JobManager(db, jobGroup),
apiKey: req.headers[CRON_JOB_API_KEY_HEADER] as string | undefined,
}),
onError({ path, error }) {
logger.error(new ErrorWithMetadata("Error in tasks tRPC handler", { path }, { cause: error }));
},
} satisfies FastifyTRPCPluginOptions<JobRouter>["trpcOptions"],
});
void (async () => {
await onStartAsync();
await jobGroup.initializeAsync();
await jobGroup.startAllAsync();
try {
await server.listen({ port: CRON_JOB_API_PORT });
logger.info("Tasks web server started successfully", { port: CRON_JOB_API_PORT });
} catch (err) {
logger.error(
new ErrorWithMetadata("Failed to start tasks web server", { port: CRON_JOB_API_PORT }, { cause: err }),
);
process.exit(1);
}
})();
+3 -1
View File
@@ -4,10 +4,12 @@
"private": true,
"license": "Apache-2.0",
"type": "module",
"exports": {
".": "./src/main.ts"
},
"main": "./src/main.ts",
"types": "./src/main.ts",
"scripts": {
"build": "esbuild src/main.ts --bundle --platform=node --outfile=wssServer.cjs --external:bcrypt --external:@opentelemetry/api --external:deasync --external:cpu-features --loader:.html=text --loader:.scss=text --loader:.node=text",
"clean": "rm -rf .turbo node_modules",
"dev": "pnpm with-env tsx ./src/main.ts",
"format": "prettier --check . --ignore-path ../../.gitignore",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "homarr",
"version": "1.61.1",
"version": "1.61.1-beta.1",
"private": true,
"scripts": {
"build": "cross-env CI=true turbo build",
@@ -15,7 +15,7 @@
"db:migration:sqlite:run": "pnpm -F db migration:sqlite:run",
"db:push": "pnpm -F db push:sqlite",
"db:studio": "pnpm -F db studio",
"dev": "turbo dev --parallel",
"dev": "pnpm -F nextjs dev",
"docker:dev": "docker compose -f ./development/development.docker-compose.yml up",
"format": "turbo format --continue -- --cache --cache-location node_modules/.cache/.prettiercache",
"format:fix": "turbo format --continue -- --write --cache --cache-location node_modules/.cache/.prettiercache",
-1
View File
@@ -25,7 +25,6 @@
"@homarr/auth": "workspace:^0.1.0",
"@homarr/common": "workspace:^0.1.0",
"@homarr/core": "workspace:^0.1.0",
"@homarr/cron-job-api": "workspace:^0.1.0",
"@homarr/cron-job-status": "workspace:^0.1.0",
"@homarr/cron-jobs": "workspace:^0.1.0",
"@homarr/db": "workspace:^0.1.0",
+19 -16
View File
@@ -2,33 +2,36 @@ import { observable } from "@trpc/server/observable";
import z from "zod/v4";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { jobGroupKeys, jobNameSchema } from "@homarr/cron-job-api";
import { cronJobApi } from "@homarr/cron-job-api/client";
import type { TaskStatus } from "@homarr/cron-job-status";
import { createCronJobStatusChannel } from "@homarr/cron-job-status";
import { jobGroup } from "@homarr/cron-jobs";
import { JobManager } from "@homarr/cron-jobs/job-manager";
import { createTRPCRouter, permissionRequiredProcedure } from "../trpc";
const jobGroupKeys = jobGroup.getKeys();
const jobNameSchema = z.enum(jobGroup.getKeys());
const logger = createLogger({ module: "cronJobsRouter" });
export const cronJobsRouter = createTRPCRouter({
triggerJob: permissionRequiredProcedure
.requiresPermission("admin")
.input(jobNameSchema)
.mutation(async ({ input }) => {
await cronJobApi.trigger.mutate(input);
.mutation(async ({ input, ctx }) => {
await new JobManager(ctx.db, jobGroup).triggerAsync(input);
}),
startJob: permissionRequiredProcedure
.requiresPermission("admin")
.input(jobNameSchema)
.mutation(async ({ input }) => {
await cronJobApi.start.mutate(input);
.mutation(async ({ input, ctx }) => {
await new JobManager(ctx.db, jobGroup).startAsync(input);
}),
stopJob: permissionRequiredProcedure
.requiresPermission("admin")
.input(jobNameSchema)
.mutation(async ({ input }) => {
await cronJobApi.stop.mutate(input);
.mutation(({ input, ctx }) => {
new JobManager(ctx.db, jobGroup).stop(input);
}),
updateJobInterval: permissionRequiredProcedure
.requiresPermission("admin")
@@ -38,23 +41,23 @@ export const cronJobsRouter = createTRPCRouter({
cron: z.string(),
}),
)
.mutation(async ({ input }) => {
await cronJobApi.updateInterval.mutate(input);
.mutation(async ({ input, ctx }) => {
await new JobManager(ctx.db, jobGroup).updateIntervalAsync(input.name, input.cron);
}),
disableJob: permissionRequiredProcedure
.requiresPermission("admin")
.input(jobNameSchema)
.mutation(async ({ input }) => {
await cronJobApi.disable.mutate(input);
.mutation(async ({ input, ctx }) => {
await new JobManager(ctx.db, jobGroup).disableAsync(input);
}),
enableJob: permissionRequiredProcedure
.requiresPermission("admin")
.input(jobNameSchema)
.mutation(async ({ input }) => {
await cronJobApi.enable.mutate(input);
.mutation(async ({ input, ctx }) => {
await new JobManager(ctx.db, jobGroup).enableAsync(input);
}),
getJobs: permissionRequiredProcedure.requiresPermission("admin").query(async () => {
return await cronJobApi.getAll.query();
getJobs: permissionRequiredProcedure.requiresPermission("admin").query(async ({ ctx }) => {
return await new JobManager(ctx.db, jobGroup).getAllAsync();
}),
subscribeToStatusUpdates: permissionRequiredProcedure.requiresPermission("admin").subscription(() => {
return observable<TaskStatus>((emit) => {
+3 -7
View File
@@ -15,7 +15,7 @@
}
},
"scripts": {
"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",
"build": "esbuild src/index.ts --bundle --platform=node --outfile=cli.cjs --external:bcrypt --external:cpu-features --loader:.html=text --loader:.node=text",
"clean": "rm -rf .turbo node_modules",
"format": "prettier --check . --ignore-path ../../.gitignore",
"lint": "eslint",
@@ -25,16 +25,12 @@
},
"prettier": "@homarr/prettier-config",
"dependencies": {
"@drizzle-team/brocli": "catalog:",
"@homarr/auth": "workspace:^0.1.0",
"@homarr/common": "workspace:^0.1.0",
"@homarr/core": "workspace:^0.1.0",
"@homarr/db": "workspace:^0.1.0",
"@homarr/validation": "workspace:^0.1.0",
"better-sqlite3": "catalog:",
"dotenv": "catalog:",
"drizzle-orm": "catalog:",
"mysql2": "catalog:",
"pg": "catalog:"
"dotenv": "catalog:"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
-127
View File
@@ -1,127 +0,0 @@
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);
};
+29 -28
View File
@@ -1,35 +1,36 @@
import { eq } from "drizzle-orm";
import { command } from "@drizzle-team/brocli";
import { getCliDb } from "../cli-db";
import { requireCredentialsProvider } from "../errors";
import { db, eq } from "@homarr/db";
import { users } from "@homarr/db/schema";
export async function fixUsernamesHandler(): Promise<number> {
requireCredentialsProvider();
const db = getCliDb();
const credentialUsers = await db.query.users.findMany({
where: eq(users.provider, "credentials"),
});
for (const user of credentialUsers) {
if (!user.name) {
continue;
}
if (user.name === user.name.toLowerCase()) {
continue;
export const fixUsernames = command({
name: "fix-usernames",
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;
}
await db
.update(users)
.set({
name: user.name.toLowerCase(),
})
.where(eq(users.id, user.id));
const credentialUsers = await db.query.users.findMany({
where: eq(users.provider, "credentials"),
});
console.log(`Changed username from ${user.name} to ${user.name.toLowerCase()}`);
}
for (const user of credentialUsers) {
if (!user.name) continue;
if (user.name === user.name.toLowerCase()) continue;
console.log("All usernames have been fixed");
return 0;
}
await db
.update(users)
.set({
name: user.name.toLowerCase(),
})
.where(eq(users.id, user.id));
console.log(`Changed username from ${user.name} to ${user.name.toLowerCase()}`);
}
console.log("All usernames have been fixed");
},
});
@@ -1,50 +1,39 @@
import { parseArgs } from "node:util";
import { command, string } from "@drizzle-team/brocli";
import { eq } from "drizzle-orm";
import type { CliDatabase } from "../cli-db";
import { getCliDb } from "../cli-db";
import { CliError } from "../errors";
import { db, eq } from "@homarr/db";
import { integrations } from "@homarr/db/schema";
const integrationLookup: Record<
"id" | "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 const integrationsDelete = command({
name: "delete",
desc: "Delete an integration by id or name",
options: {
id: string("id").alias("i").desc("ID of the integration"),
name: string("name").alias("n").desc("Name of the integration"),
},
// eslint-disable-next-line no-restricted-syntax
handler: async (options) => {
if (!options.id && !options.name) {
console.error("Either --id or --name must be provided");
return;
}
export async function integrationsDeleteHandler(args: string[]): Promise<number> {
const { values } = parseArgs({
args,
options: {
id: { type: "string", short: "i" },
name: { type: "string", short: "n" },
},
});
let entry;
if (options.id) {
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),
});
}
const lookupKey = values.id ? "id" : values.name ? "name" : null;
const lookupValue = values.id ?? values.name;
if (!entry) {
console.error("Integration not found");
return;
}
if (!lookupKey || !lookupValue) {
throw new CliError("Either --id or --name must be provided", 2);
}
const db = getCliDb();
const entry = await integrationLookup[lookupKey](db, lookupValue);
if (!entry) {
throw new CliError("Integration not found");
}
await db.delete(integrations).where(eq(integrations.id, entry.id));
console.log(`Integration ${entry.name} (${entry.id}) deleted`);
return 0;
}
await db.delete(integrations).where(eq(integrations.id, entry.id));
console.log(`Integration ${entry.name} (${entry.id}) deleted`);
},
});
+18 -32
View File
@@ -1,35 +1,21 @@
import { parseArgs } from "node:util";
import { command } from "@drizzle-team/brocli";
import { getCliDb } from "../cli-db";
import { printTable } from "../utils";
import { db } from "@homarr/db";
export async function integrationsListHandler(args: string[] = []): Promise<number> {
const { values } = parseArgs({
args,
options: {
json: { type: "boolean", default: false },
},
strict: false,
});
export const integrationsList = command({
name: "list",
desc: "List all integrations (id and name)",
// eslint-disable-next-line no-restricted-syntax
handler: async () => {
const all = await db.query.integrations.findMany();
if (all.length === 0) {
console.log("No integrations found");
return;
}
const db = getCliDb();
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) {
console.log("No integrations found");
return 0;
}
printTable(
["ID", "Name", "Kind", "URL"],
all.map((i) => [i.id, i.name, i.kind, i.url]),
);
console.log(`\n${all.length} integration(s) total`);
return 0;
}
console.log("ID\t\t\t\tName");
for (const i of all) {
console.log(`${i.id}\t${i.name}`);
}
},
});
+10
View File
@@ -0,0 +1,10 @@
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],
});
+76 -80
View File
@@ -1,98 +1,94 @@
import { parseArgs } from "node:util";
import { command, string } from "@drizzle-team/brocli";
import { hashPasswordAsync } from "@homarr/auth/security";
import { hashPasswordAsync } from "@homarr/auth";
import { createId } from "@homarr/common";
import { generateSecureRandomToken } from "../utils";
import { and, count, eq, max } from "drizzle-orm";
import { getCliDb } from "../cli-db";
import { CliError, requireCredentialsProvider } from "../errors";
import { generateSecureRandomToken } from "@homarr/common/server";
import { and, count, db, eq } from "@homarr/db";
import { getMaxGroupPositionAsync } from "@homarr/db/queries";
import { groupMembers, groupPermissions, groups, users } from "@homarr/db/schema";
import { usernameSchema } from "@homarr/validation/user";
export async function recreateAdminHandler(args: string[]): Promise<number> {
requireCredentialsProvider();
export const recreateAdmin = command({
name: "recreate-admin",
desc: "Recreate credentials admin user if none exists anymore",
options: {
username: string("username").required().alias("u").desc("Name of the admin"),
},
// 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;
}
const { values } = parseArgs({
args,
options: {
username: { type: "string", short: "u" },
},
});
const result = await usernameSchema.safeParseAsync(options.username);
if (!values.username) {
throw new CliError("Missing required option: --username / -u", 2);
}
if (!result.success) {
console.error("Invalid username:");
console.error(result.error.issues.map((error) => `- ${error.message}`).join("\n"));
return;
}
const result = await usernameSchema.safeParseAsync(values.username);
if (!result.success) {
const messages = result.error.issues.map((issue) => `- ${issue.message}`).join("\n");
throw new CliError(`Invalid username:\n${messages}`, 2);
}
const totalCount = await db
.select({
count: count(),
})
.from(groupPermissions)
.leftJoin(groupMembers, eq(groupMembers.groupId, groupPermissions.groupId))
.leftJoin(users, eq(users.id, groupMembers.userId))
.where(and(eq(groupPermissions.permission, "admin"), eq(users.provider, "credentials")))
.then((rows) => rows.at(0)?.count ?? 0);
const db = getCliDb();
if (totalCount > 0) {
console.error("Credentials admin user exists");
return;
}
const totalCount = await db
.select({
count: count(),
})
.from(groupPermissions)
.leftJoin(groupMembers, eq(groupMembers.groupId, groupPermissions.groupId))
.leftJoin(users, eq(users.id, groupMembers.userId))
.where(and(eq(groupPermissions.permission, "admin"), eq(users.provider, "credentials")))
.then((rows: { count: number }[]) => rows.at(0)?.count ?? 0);
const existingUser = await db.query.users.findFirst({
where: eq(users.name, result.data),
});
if (totalCount > 0) {
throw new CliError("Credentials admin user exists");
}
if (existingUser) {
console.error("User with this name already exists");
return;
}
const existingUser = await db.query.users.findFirst({
where: eq(users.name, result.data),
});
const temporaryGroupId = createId();
if (existingUser) {
throw new CliError("User with this name already exists");
}
const maxPosition = await getMaxGroupPositionAsync(db);
await db.insert(groups).values({
id: temporaryGroupId,
name: temporaryGroupId,
position: maxPosition + 1,
});
const temporaryGroupId = createId();
const maxPosition = await db
.select({ value: max(groups.position) })
.from(groups)
.then((result: { value: number | null }[]) => result[0]?.value ?? 1);
await db.insert(groupPermissions).values({
groupId: temporaryGroupId,
permission: "admin",
});
await db.insert(groups).values({
id: temporaryGroupId,
name: temporaryGroupId,
position: maxPosition + 1,
});
const password = generateSecureRandomToken(24);
const hashedPassword = await hashPasswordAsync(password);
await db.insert(groupPermissions).values({
groupId: temporaryGroupId,
permission: "admin",
});
const userId = createId();
await db.insert(users).values({
id: userId,
name: result.data,
provider: "credentials",
password: hashedPassword,
});
const password = generateSecureRandomToken(24);
const hashedPassword = await hashPasswordAsync(password);
const userId = createId();
await db.insert(groupMembers).values({
groupId: temporaryGroupId,
userId,
});
await db.insert(users).values({
id: userId,
name: result.data,
provider: "credentials",
password: hashedPassword,
});
await db.insert(groupMembers).values({
groupId: temporaryGroupId,
userId,
});
console.log(
"We created a new admin user for you. Please keep in mind, that the admin group of it has a temporary name. You should change it to something more meaningful.",
);
console.log(`\tUsername: ${result.data}`);
console.log(`\tPassword: ${password}`);
console.log(`\tGroup: ${temporaryGroupId}`);
console.log("");
return 0;
}
console.log(
"We created a new admin user for you. Please keep in mind, that the admin group of it has a temporary name. You should change it to something more meaningful.",
);
console.log(`\tUsername: ${result.data}`);
console.log(`\tPassword: ${password}`);
console.log(`\tGroup: ${temporaryGroupId}`);
console.log(""); // Empty line for better readability
},
});
+37 -39
View File
@@ -1,48 +1,46 @@
import { parseArgs } from "node:util";
import { command, string } from "@drizzle-team/brocli";
import { hashPasswordAsync } from "@homarr/auth/security";
import { generateSecureRandomToken } from "../utils";
import { and, eq } from "drizzle-orm";
import { getCliDb } from "../cli-db";
import { CliError, requireCredentialsProvider } from "../errors";
import { hashPasswordAsync } from "@homarr/auth";
import { generateSecureRandomToken } from "@homarr/common/server";
import { and, db, eq } from "@homarr/db";
import { sessions, users } from "@homarr/db/schema";
export async function resetPasswordHandler(args: string[]): Promise<number> {
requireCredentialsProvider();
export const resetPassword = command({
name: "reset-password",
desc: "Reset password for a user",
options: {
username: string("username").required().alias("u").desc("Name of the user"),
},
// 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;
}
const { values } = parseArgs({
args,
options: {
username: { type: "string", short: "u" },
},
});
const user = await db.query.users.findFirst({
where: and(eq(users.name, options.username), eq(users.provider, "credentials")),
});
if (!values.username) {
throw new CliError("Missing required option: --username / -u", 2);
}
if (!user?.password) {
console.error(`User ${options.username} not found`);
return;
}
const db = getCliDb();
const user = await db.query.users.findFirst({
where: and(eq(users.name, values.username), eq(users.provider, "credentials")),
});
// Generates a new password with 48 characters
const newPassword = generateSecureRandomToken(24);
if (!user?.password) {
throw new CliError(`User ${values.username} not found`);
}
await db
.update(users)
.set({
password: await hashPasswordAsync(newPassword),
})
.where(eq(users.id, user.id));
const newPassword = generateSecureRandomToken(24);
await db.delete(sessions).where(eq(sessions.userId, user.id));
console.log(`All sessions for user ${options.username} have been deleted`);
await db
.update(users)
.set({
password: await hashPasswordAsync(newPassword),
})
.where(eq(users.id, user.id));
await db.delete(sessions).where(eq(sessions.userId, user.id));
console.log(`All sessions for user ${values.username} have been deleted`);
console.log("You can now login with the new password");
console.log(`New password for user ${values.username}: ${newPassword}`);
return 0;
}
console.log("You can now login with the new password");
console.log(`New password for user ${options.username}: ${newPassword}`);
},
});
+33 -41
View File
@@ -1,47 +1,39 @@
import { parseArgs } from "node:util";
import { command, string } from "@drizzle-team/brocli";
import { eq } from "drizzle-orm";
import type { CliDatabase } from "../cli-db";
import { getCliDb } from "../cli-db";
import { CliError } from "../errors";
import { db, eq } from "@homarr/db";
import { users } from "@homarr/db/schema";
const userLookup: Record<"id" | "username", (db: CliDatabase, value: string) => Promise<{ id: string; name: 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 const usersDelete = command({
name: "delete",
desc: "Delete a user by id or username",
options: {
id: string("id").alias("i").desc("ID of the user"),
username: string("username").alias("u").desc("Name of the user"),
},
// eslint-disable-next-line no-restricted-syntax
handler: async (options) => {
if (!options.id && !options.username) {
console.error("Either --id or --username must be provided");
return;
}
export async function usersDeleteHandler(args: string[]): Promise<number> {
const { values } = parseArgs({
args,
options: {
id: { type: "string", short: "i" },
username: { type: "string", short: "u" },
},
});
let user;
if (options.id) {
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),
});
}
const lookupKey = values.id ? "id" : values.username ? "username" : null;
const lookupValue = values.id ?? values.username;
if (!user) {
console.error("User not found");
return;
}
if (!lookupKey || !lookupValue) {
throw new CliError("Either --id or --username must be provided", 2);
}
const db = getCliDb();
const user = await userLookup[lookupKey](db, lookupValue);
if (!user) {
throw new CliError("User not found");
}
await db.delete(users).where(eq(users.id, user.id));
console.log(`User ${user.name ?? user.id} (${user.id}) deleted`);
return 0;
}
await db.delete(users).where(eq(users.id, user.id));
console.log(`User ${user.name ?? user.id} (${user.id}) deleted`);
},
});
+18 -31
View File
@@ -1,35 +1,22 @@
import { parseArgs } from "node:util";
import { command } from "@drizzle-team/brocli";
import { getCliDb } from "../cli-db";
import { printTable } from "../utils";
import { db } from "@homarr/db";
export async function usersListHandler(args: string[] = []): Promise<number> {
const { values } = parseArgs({
args,
options: {
json: { type: "boolean", default: false },
},
strict: false,
});
export const usersList = command({
name: "list",
desc: "List all users (id, username, email)",
// eslint-disable-next-line no-restricted-syntax
handler: async () => {
const allUsers = await db.query.users.findMany();
const db = getCliDb();
const allUsers = await db.query.users.findMany();
if (allUsers.length === 0) {
console.log("No users found");
return;
}
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) {
console.log("No users found");
return 0;
}
printTable(
["ID", "Username", "Email", "Provider"],
allUsers.map((u) => [u.id, u.name ?? "", u.email ?? "", u.provider]),
);
console.log(`\n${allUsers.length} user(s) total`);
return 0;
}
console.log("ID\t\t\t\tUsername\tEmail");
for (const user of allUsers) {
console.log(`${user.id}\t${user.name ?? ""}\t${user.email ?? ""}`);
}
},
});
@@ -1,66 +1,50 @@
import { parseArgs } from "node:util";
import { command, string } from "@drizzle-team/brocli";
import { hashPasswordAsync } from "@homarr/auth/security";
import { eq } from "drizzle-orm";
import type { CliDatabase } from "../cli-db";
import { getCliDb } from "../cli-db";
import { CliError, requireCredentialsProvider } from "../errors";
import { hashPasswordAsync } from "@homarr/auth";
import { db, eq } from "@homarr/db";
import { sessions, users } from "@homarr/db/schema";
const userLookup: Record<
"id" | "username",
(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 const usersUpdatePassword = command({
name: "update-password",
desc: "Update the password for a user (credentials provider only)",
options: {
id: string("id").alias("i").desc("ID of the user"),
username: string("username").alias("u").desc("Name of the user"),
password: string("password").alias("p").required().desc("New password"),
},
// 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;
}
export async function usersUpdatePasswordHandler(args: string[]): Promise<number> {
requireCredentialsProvider();
if (!options.id && !options.username) {
console.error("Either --id or --username must be provided");
return;
}
const { values } = parseArgs({
args,
options: {
id: { type: "string", short: "i" },
username: { type: "string", short: "u" },
password: { type: "string", short: "p" },
},
});
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 (!user?.password) {
console.error("User not found or has no credentials record");
return;
}
if (!lookupKey || !lookupValue) {
throw new CliError("Either --id or --username must be provided", 2);
}
await db
.update(users)
.set({
password: await hashPasswordAsync(options.password),
})
.where(eq(users.id, user.id));
if (!values.password) {
throw new CliError("Missing required option: --password / -p", 2);
}
// invalidate existing sessions
await db.delete(sessions).where(eq(sessions.userId, user.id));
console.log(`All sessions for user ${user.name ?? user.id} have been deleted`);
const db = getCliDb();
const user = await userLookup[lookupKey](db, lookupValue);
if (!user?.password) {
throw new CliError("User not found or has no credentials record");
}
await db
.update(users)
.set({
password: await hashPasswordAsync(values.password),
})
.where(eq(users.id, 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("Password updated successfully");
return 0;
}
console.log("Password updated successfully");
},
});
+11
View File
@@ -0,0 +1,11 @@
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
@@ -1,16 +0,0 @@
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");
}
};
+11 -38
View File
@@ -1,41 +1,14 @@
import { closeCliDbAsync } from "./cli-db";
import { CliError } from "./errors";
import { runCliAsync } from "./router";
import { run } from "@drizzle-team/brocli";
const mainAsync = async (): Promise<number> => {
const argv = process.argv.slice(2);
const start = performance.now();
import { fixUsernames } from "./commands/fix-usernames";
import { integrationsRoot } from "./commands/integrations";
import { recreateAdmin } from "./commands/recreate-admin";
import { resetPassword } from "./commands/reset-password";
import { usersRoot } from "./commands/users";
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;
}
const commands = [usersRoot, integrationsRoot, resetPassword, fixUsernames, recreateAdmin];
if (error instanceof TypeError && error.message.startsWith("Unknown option")) {
console.error(error.message);
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);
});
void run(commands, {
name: "homarr-cli",
version: "1.0.0",
});
-167
View File
@@ -1,167 +0,0 @@
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
@@ -1,18 +0,0 @@
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,7 +14,6 @@
"./infrastructure/db": "./src/infrastructure/db/index.ts",
"./infrastructure/db/env": "./src/infrastructure/db/env.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/hostnames/db/sqlite": "./src/infrastructure/certificates/hostnames/db/sqlite.ts",
"./infrastructure/certificates/hostnames/db/mysql": "./src/infrastructure/certificates/hostnames/db/mysql.ts",
-9
View File
@@ -1,9 +0,0 @@
import baseConfig from "@homarr/eslint-config/base";
/** @type {import('typescript-eslint').Config} */
export default [
{
ignores: [],
},
...baseConfig,
];
-46
View File
@@ -1,46 +0,0 @@
{
"name": "@homarr/cron-job-api",
"version": "0.1.0",
"private": true,
"license": "Apache-2.0",
"type": "module",
"exports": {
".": "./src/index.ts",
"./env": "./src/env.ts",
"./constants": "./src/constants.ts",
"./client": "./src/client.ts"
},
"typesVersions": {
"*": {
"*": [
"src/*"
]
}
},
"scripts": {
"clean": "rm -rf .turbo node_modules",
"format": "prettier --check . --ignore-path ../../.gitignore",
"lint": "eslint",
"typecheck": "tsc --noEmit"
},
"prettier": "@homarr/prettier-config",
"dependencies": {
"@homarr/common": "workspace:^0.1.0",
"@homarr/core": "workspace:^0.1.0",
"@homarr/cron-jobs": "workspace:^0.1.0",
"@tanstack/react-query": "catalog:",
"@trpc/client": "catalog:",
"@trpc/server": "catalog:",
"@trpc/tanstack-react-query": "catalog:",
"react": "catalog:",
"zod": "catalog:"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"@types/react": "catalog:",
"eslint": "catalog:",
"typescript": "catalog:"
}
}
-20
View File
@@ -1,20 +0,0 @@
import { createTRPCClient, httpLink } from "@trpc/client";
import type { JobRouter } from ".";
import { CRON_JOB_API_KEY_HEADER, CRON_JOB_API_PATH, CRON_JOB_API_PORT } from "./constants";
import { env } from "./env";
export const cronJobApi = createTRPCClient<JobRouter>({
links: [
httpLink({
url: `${getBaseUrl()}${CRON_JOB_API_PATH}`,
headers: {
[CRON_JOB_API_KEY_HEADER]: env.CRON_JOB_API_KEY,
},
}),
],
});
function getBaseUrl() {
return `http://localhost:${CRON_JOB_API_PORT}`;
}
-3
View File
@@ -1,3 +0,0 @@
export const CRON_JOB_API_PORT = 3002;
export const CRON_JOB_API_PATH = "/trpc";
export const CRON_JOB_API_KEY_HEADER = "cron-job-api-key";
-11
View File
@@ -1,11 +0,0 @@
import { z } from "zod/v4";
import { env as commonEnv } from "@homarr/common/env";
import { createEnv } from "@homarr/core/infrastructure/env";
export const env = createEnv({
server: {
CRON_JOB_API_KEY: commonEnv.NODE_ENV === "development" ? z.string().default("test") : z.string(),
},
experimental__runtimeEnv: process.env,
});
-85
View File
@@ -1,85 +0,0 @@
import { initTRPC, TRPCError } from "@trpc/server";
import { z } from "zod/v4";
import type { JobGroupKeys } from "@homarr/cron-jobs";
import { jobGroup } from "@homarr/cron-jobs";
import { env } from "./env";
export const jobGroupKeys = jobGroup.getKeys();
export const jobNameSchema = z.enum(jobGroup.getKeys());
export interface IJobManager {
startAsync(name: JobGroupKeys): Promise<void>;
triggerAsync(name: JobGroupKeys): Promise<void>;
stop(name: JobGroupKeys): void;
updateIntervalAsync(name: JobGroupKeys, cron: string): Promise<void>;
disableAsync(name: JobGroupKeys): Promise<void>;
enableAsync(name: JobGroupKeys): Promise<void>;
getAllAsync(): Promise<
{
name: JobGroupKeys;
cron: string;
preventManualExecution: boolean;
preventCustomInterval: boolean;
isEnabled: boolean;
}[]
>;
}
const t = initTRPC
.context<{
manager: IJobManager;
apiKey?: string;
}>()
.create();
const createTrpcRouter = t.router;
const apiKeyProcedure = t.procedure.use(({ ctx, next }) => {
if (ctx.apiKey !== env.CRON_JOB_API_KEY) {
throw new TRPCError({
code: "FORBIDDEN",
message: "Missing or invalid API key",
});
}
return next({
ctx: {
...ctx,
apiKey: undefined, // Clear the API key after checking
},
});
});
export const jobRouter = createTrpcRouter({
start: apiKeyProcedure.input(jobNameSchema).mutation(async ({ input, ctx }) => {
await ctx.manager.startAsync(input);
}),
trigger: apiKeyProcedure.input(jobNameSchema).mutation(async ({ input, ctx }) => {
await ctx.manager.triggerAsync(input);
}),
stop: apiKeyProcedure.input(jobNameSchema).mutation(({ input, ctx }) => {
ctx.manager.stop(input);
}),
updateInterval: apiKeyProcedure
.input(
z.object({
name: jobNameSchema,
cron: z.string(),
}),
)
.mutation(async ({ input, ctx }) => {
await ctx.manager.updateIntervalAsync(input.name, input.cron);
}),
disable: apiKeyProcedure.input(jobNameSchema).mutation(async ({ input, ctx }) => {
await ctx.manager.disableAsync(input);
}),
enable: apiKeyProcedure.input(jobNameSchema).mutation(async ({ input, ctx }) => {
await ctx.manager.enableAsync(input);
}),
getAll: apiKeyProcedure.query(({ ctx }) => {
return ctx.manager.getAllAsync();
}),
});
export type JobRouter = typeof jobRouter;
-8
View File
@@ -1,8 +0,0 @@
{
"extends": "@homarr/tsconfig/base.json",
"compilerOptions": {
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
},
"include": ["*.ts", "src"],
"exclude": ["node_modules"]
}
+4 -2
View File
@@ -5,7 +5,8 @@
"license": "Apache-2.0",
"type": "module",
"exports": {
".": "./index.ts"
".": "./index.ts",
"./job-manager": "./src/job-manager.ts"
},
"typesVersions": {
"*": {
@@ -38,7 +39,8 @@
"@homarr/server-settings": "workspace:^0.1.0",
"@homarr/translation": "workspace:^0.1.0",
"@homarr/validation": "workspace:^0.1.0",
"semver-parser": "catalog:"
"semver-parser": "catalog:",
"zod": "catalog:"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
+40 -29
View File
@@ -28,34 +28,45 @@ import { updateCheckerJob } from "./jobs/update-checker";
import { weatherJob } from "./jobs/weather";
import { createCronJobGroup } from "./lib";
export const jobGroup = createCronJobGroup({
analytics: analyticsJob,
iconsUpdater: iconsUpdaterJob,
ping: pingJob,
smartHomeEntityState: smartHomeEntityStateJob,
mediaServer: mediaServerJob,
mediaOrganizer: mediaOrganizerJob,
downloads: downloadsJob,
dnsHole: dnsHoleJob,
mediaRequestStats: mediaRequestStatsJob,
mediaRequestList: mediaRequestListJob,
rssFeeds: rssFeedsJob,
indexerManager: indexerManagerJob,
healthMonitoring: healthMonitoringJob,
updateChecker: updateCheckerJob,
mediaTranscoding: mediaTranscodingJob,
minecraftServerStatus: minecraftServerStatusJob,
dockerContainers: dockerContainersJob,
networkController: networkControllerJob,
firewallCpu: firewallCpuJob,
firewallMemory: firewallMemoryJob,
firewallVersion: firewallVersionJob,
firewallInterfaces: firewallInterfacesJob,
refreshNotifications: refreshNotificationsJob,
weather: weatherJob,
timetable: timetableJob,
tracearr: tracearrJob,
umamiActiveVisitors: umamiActiveVisitorsJob,
});
const getJobGroup = () => {
return createCronJobGroup({
analytics: analyticsJob,
iconsUpdater: iconsUpdaterJob,
ping: pingJob,
smartHomeEntityState: smartHomeEntityStateJob,
mediaServer: mediaServerJob,
mediaOrganizer: mediaOrganizerJob,
downloads: downloadsJob,
dnsHole: dnsHoleJob,
mediaRequestStats: mediaRequestStatsJob,
mediaRequestList: mediaRequestListJob,
rssFeeds: rssFeedsJob,
indexerManager: indexerManagerJob,
healthMonitoring: healthMonitoringJob,
updateChecker: updateCheckerJob,
mediaTranscoding: mediaTranscodingJob,
minecraftServerStatus: minecraftServerStatusJob,
dockerContainers: dockerContainersJob,
networkController: networkControllerJob,
firewallCpu: firewallCpuJob,
firewallMemory: firewallMemoryJob,
firewallVersion: firewallVersionJob,
firewallInterfaces: firewallInterfacesJob,
refreshNotifications: refreshNotificationsJob,
weather: weatherJob,
timetable: timetableJob,
tracearr: tracearrJob,
umamiActiveVisitors: umamiActiveVisitorsJob,
});
};
// Add global type augmentation for homarr
declare global {
var cronJobs: ReturnType<typeof getJobGroup> | undefined;
}
global.cronJobs ??= getJobGroup();
export const jobGroup = global.cronJobs;
export type JobGroupKeys = ReturnType<(typeof jobGroup)["getKeys"]>[number];
@@ -1,7 +1,6 @@
import { Cron } from "croner";
import { createLogger } from "@homarr/core/infrastructure/logs";
import type { IJobManager } from "@homarr/cron-job-api";
import type { jobGroup as cronJobGroup, JobGroupKeys } from "@homarr/cron-jobs";
import type { Database, InferInsertModel } from "@homarr/db";
import { eq } from "@homarr/db";
@@ -9,7 +8,7 @@ import { cronJobConfigurations } from "@homarr/db/schema";
const logger = createLogger({ module: "jobManager" });
export class JobManager implements IJobManager {
export class JobManager {
constructor(
private db: Database,
private jobGroup: typeof cronJobGroup,
+1 -1
View File
@@ -1,6 +1,6 @@
import type { InferSelectModel } from "drizzle-orm";
import { createDbMapping as createSchema } from "@homarr/core/infrastructure/db/mapping";
import { createSchema } from "@homarr/core/infrastructure/db";
import * as mysqlSchema from "./mysql";
import * as pgSchema from "./postgresql";
+2 -2
View File
@@ -65,8 +65,8 @@ const columnsRatios: Record<keyof ExtendedDownloadClientItem, number> = {
id: 1,
index: 1,
integration: 1,
name: 16,
progress: 6,
name: 8,
progress: 4,
ratio: 2,
received: 3,
sent: 3,
+1152 -1572
View File
File diff suppressed because it is too large. Load diff
+1 -11
View File
@@ -16,8 +16,6 @@ fi
# Auth secret is generated every time the container starts as it is required, but not used because we don't need JWTs or Mail hashing
export AUTH_SECRET=$(openssl rand -base64 32)
# Cron job API key is generated every time the container starts as it is required for communication between nextjs-api and tasks-api
export CRON_JOB_API_KEY=$(openssl rand -base64 32)
# Start nginx proxy
# 1. Replace the HOSTNAME in the nginx template file
@@ -38,21 +36,13 @@ else
REDIS_PID=$!
fi
node apps/tasks/tasks.cjs &
TASKS_PID=$!
node apps/websocket/wssServer.cjs &
WSS_PID=$!
node apps/nextjs/server.js &
NEXTJS_PID=$!
# Function to handle SIGTERM and shut down services
terminate() {
echo "Received SIGTERM. Shutting down..."
kill -TERM $NGINX_PID $TASKS_PID $WSS_PID $NEXTJS_PID 2>/dev/null
kill -TERM $NGINX_PID $NEXTJS_PID 2>/dev/null
wait
# kill redis-server last because of logging of other services and only if $REDIS_PID is set
if [ -n "$REDIS_PID" ]; then