Compare commits

..
Author SHA1 Message Date
Thomas Camlong 6befc5ad41 fix(backup): log restore errors via the central logger and harden cleanup
Replace raw console.error calls in the backup import/migrations routes with
createLogger + ErrorWithMetadata so restore failures flow through the standard
log transports (console + Redis). Wrap the temporary DB close in finally so a
close failure cannot 500 a successful restore, and log client-side restore and
analysis failures to the browser console.
2026-08-18 11:14:04 +02:00
Thomas Camlong 2a76bb185b fix(backup): show explicit sign-in prompt after database restore
Restoring a backup replaces the database, invalidating the database-backed
session (Auth.js session strategy: database). The old code silently reloaded
the page, leaving users on an empty board or a login screen with no context.

Replace the opaque reload with an explicit completion state that informs the
user their session was invalidated and auto-redirects to the sign-in page
(bypassing bfcache so the stale board cannot be restored).
2026-08-18 11:11:23 +02:00
Thomas 05ba57c2fa chore: migrate cursor rules to portable agent skills + mantine MCP guidance
* chore: migrate cursor rules to portable agent skills and add mantine MCP guidance

Replace Cursor-only .cursor/rules/*.mdc with Agent Skills open-standard
SKILL.md files in .agents/skills/ (canonical), mirrored to .cursor/skills/
and .claude/skills/ so they work across Claude Code, Cursor, Codex, and
OpenCode. Add mantine MCP server guidance to AGENTS.md and un-ignore
.agents/skills/ in .gitignore.

* refactor: single-source agent skills at .agents/skills

Cursor, Codex, and OpenCode all read .agents/skills/ natively, so the
.cursor/skills/ mirror was redundant. Claude Code reads .claude/skills/,
which is now a symlink back to .agents/skills/ so the content lives once.
Deletes .cursor/skills/ and converts .claude/skills/ to a symlink.

* chore: ship mantine MCP server via project-scoped .mcp.json

Declares the keyless @mantine/mcp-server in .mcp.json (Claude Code
project-scope standard, committable) and documents MCP server setup and
the mantine entry in AGENTS.md.

* chore: address coderabbit security-review and markdown lint findings

Add explicit security-review guidance before exposing MCP tools and label
plain-text code fences to satisfy markdownlint MD040.
2026-08-16 16:27:51 +02:00
Thomas ddbf05524b feat(http): set custom User-Agent on outbound integration requests (#6606)
* feat(http): set custom User-Agent on outbound integration requests

Set a default 'User-Agent: Homarr/<version> (+https://homarr.dev)' header
on all outbound HTTP requests made via fetchWithTrustedCertificatesAsync,
so Homarr's integration traffic is distinguishable in reverse-proxy,
WAF, and security-monitoring logs instead of appearing as generic undici.

Closes #6604

* refactor(version): centralize Homarr version in @homarr/version package

Replace fragile deep-relative 'package.json' imports across the monorepo
with a single source of truth: the new @homarr/version leaf package reads
the version once from the root package.json and exports it as VERSION.

Consumers now import by package name incl. the new User-Agent header in
fetchWithTrustedCertificatesAsync (packages/core):
  - core, api (info router), analytics, request-handler (update checker)
This also removes all manually-maintained relative version imports.

* fix(http): normalize User-Agent injection with Headers

Object-spreading fetchOptions.headers breaks when callers pass a Headers
instance (spread yields no entries) or a tuple array (numeric keys), and is
case-sensitive. Build a Headers instance and set the default User-Agent only
when no case-insensitive User-Agent entry exists, via a shared helper in both
fetch paths.

Adds unit tests covering record, Headers, tuple-array, and casing variants.

* revert(version): undo version refactor and tests, keep single-file change

Keep the User-Agent change as a single edit to
packages/core/src/infrastructure/http/request.ts. Remove the @homarr/version
package, the consumer migrations, and the unit tests.
2026-08-16 16:09:15 +02:00
7 changed files with 81 additions and 12 deletions

No files matched your search

+12 -4
View File
@@ -12,10 +12,14 @@ import { auth } from "@homarr/auth/next";
import { env } from "@homarr/common/env";
import { DB_CASING } from "@homarr/core/infrastructure/db/constants";
import { dbEnv } from "@homarr/core/infrastructure/db/env";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import { db } from "@homarr/db";
import { findMigrationsFolder } from "../shared";
const logger = createLogger({ module: "backupImportRoute" });
const REQUIRED_ZIP_ENTRIES = ["db.sqlite", "metadata.json"] as const;
const ALGORITHM = "aes-256-cbc";
const HEX_KEY_REGEX = /^[0-9a-fA-F]{64}$/;
@@ -174,22 +178,26 @@ export async function POST(req: Request) {
const sidecar = `${dbPath}${suffix}`;
if (fs.existsSync(sidecar)) fs.unlinkSync(sidecar);
} catch (cleanupErr) {
console.error(`Failed to remove ${suffix} file:`, cleanupErr);
logger.warn("Failed to remove SQLite sidecar file after restore", { suffix, dbPath, cause: cleanupErr });
}
}
setTimeout(() => {
console.log("Database restored, restarting server...");
logger.info("Database restored, restarting server...");
process.exit(0);
}, 500);
return NextResponse.json({ success: true, message: "Database restored. Server is restarting..." });
} catch (error) {
console.error("[backup/import] Restore failed:", error);
logger.error(new ErrorWithMetadata("Backup restore failed", { dbPath }, { cause: error }));
const message = error instanceof Error ? error.message : "Unknown error";
return NextResponse.json({ error: `Restore failed: ${message}` }, { status: 500 });
} finally {
tempDb?.close();
try {
tempDb?.close();
} catch (closeErr) {
logger.warn("Failed to close temporary database after restore", { cause: closeErr });
}
if (fs.existsSync(tempPath)) {
try {
fs.unlinkSync(tempPath);
@@ -3,8 +3,13 @@ import path from "path";
import { NextResponse } from "next/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import { findMigrationsFolder } from "../shared";
const logger = createLogger({ module: "backupMigrationsRoute" });
interface JournalEntry {
idx: number;
version: string;
@@ -56,7 +61,7 @@ export async function GET() {
},
);
} catch (error) {
console.error("[backup/migrations] Failed to read migrations:", error);
logger.error(new ErrorWithMetadata("Failed to read migration files", {}, { cause: error }));
const message = error instanceof Error ? error.message : "Unknown error";
return NextResponse.json({ error: `Failed to read migrations: ${message}` }, { status: 500 });
}
@@ -1,10 +1,10 @@
"use client";
import { useCallback, useRef, useState } from "react";
import { Alert, Button, Group, Loader, rem, Stack, Text } from "@mantine/core";
import { useCallback, useEffect, useRef, useState } from "react";
import { Alert, Button, Group, Loader, rem, Stack, Text, ThemeIcon } from "@mantine/core";
import type { FileWithPath } from "@mantine/dropzone";
import { Dropzone, MIME_TYPES } from "@mantine/dropzone";
import { IconAlertTriangle, IconArrowRight, IconFileZip, IconUpload, IconX } from "@tabler/icons-react";
import { IconAlertTriangle, IconArrowRight, IconCheck, IconFileZip, IconUpload, IconX } from "@tabler/icons-react";
import "@mantine/dropzone/styles.css";
@@ -30,8 +30,17 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
const apiDoneRef = useRef(false);
const animDoneRef = useRef(false);
const apiErrorRef = useRef<string | null>(null);
const redirectTimerRef = useRef<number | null>(null);
const { analysis, loading, error: analysisError, migrationProgress, analyzeFile, reset } = useBackupAnalysis();
useEffect(() => {
return () => {
if (redirectTimerRef.current !== null) {
window.clearTimeout(redirectTimerRef.current);
}
};
}, []);
const handleFileDrop = useCallback(
(files: FileWithPath[]) => {
const droppedFile = files[0];
@@ -45,6 +54,10 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
);
const handleClear = useCallback(() => {
if (redirectTimerRef.current !== null) {
window.clearTimeout(redirectTimerRef.current);
redirectTimerRef.current = null;
}
setFile(null);
setStep("upload");
setImportError(null);
@@ -65,9 +78,20 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
if (!animDoneRef.current) return;
onRestoreComplete?.();
window.location.reload();
setStep("complete");
redirectTimerRef.current = window.setTimeout(() => {
window.location.assign("/auth/login");
}, 2000);
}, [onRestoreComplete]);
const handleSignInAgain = useCallback(() => {
if (redirectTimerRef.current !== null) {
window.clearTimeout(redirectTimerRef.current);
redirectTimerRef.current = null;
}
window.location.assign("/auth/login");
}, []);
const handleConfirm = useCallback(async () => {
if (!file) return;
setStep("restoring");
@@ -89,7 +113,8 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
apiErrorRef.current = `Server returned ${response.status}`;
}
}
} catch {
} catch (error) {
console.error("Restore request failed", error);
apiErrorRef.current = t("failed.title");
} finally {
apiDoneRef.current = true;
@@ -212,6 +237,23 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
);
}
if (step === "complete") {
return (
<Stack gap="md" align="center" py="lg">
<ThemeIcon size={64} radius="xl" color="green" variant="light">
<IconCheck size={32} style={{ width: rem(40), height: rem(40) }} stroke={1.5} />
</ThemeIcon>
<Text size="lg" fw={600} ta="center">
{t("complete.title")}
</Text>
<Text size="sm" c="dimmed" ta="center" maw={480}>
{t("complete.message")}
</Text>
<Button onClick={handleSignInAgain}>{t("complete.button")}</Button>
</Stack>
);
}
if (step === "error") {
return (
<Stack gap="md">
+1 -1
View File
@@ -25,6 +25,6 @@ export interface BackupAnalysis {
migrations: MigrationStatus;
}
export type RestoreStep = "upload" | "preview" | "confirm" | "restoring" | "error";
export type RestoreStep = "upload" | "preview" | "confirm" | "restoring" | "complete" | "error";
export const PREVIEW_TABLE_KEYS = ["board", "user", "app", "integration", "item", "media", "search_engine"] as const;
@@ -168,6 +168,7 @@ export const useBackupAnalysis = () => {
dbRef.current = null;
}
} catch (err) {
console.error("Backup analysis failed", err);
setError(err instanceof Error ? err.message : t("analyzeError"));
} finally {
setLoading(false);
@@ -14,6 +14,10 @@ import { UndiciHttpAgent } from "@homarr/core/infrastructure/http";
import type { TrustedCertificateHostname } from "../certificates/hostnames";
import { withTimeoutAsync } from "./timeout";
import packageJson from "../../../../../package.json";
export const getDefaultUserAgent = () => `Homarr/${packageJson.version} (+https://homarr.dev)`;
export const createCustomCheckServerIdentity = (
trustedHostnames: TrustedCertificateHostname[],
): typeof checkServerIdentity => {
@@ -79,6 +83,10 @@ export const fetchWithTrustedCertificatesAsync = async (
async (signal) =>
fetch(url, {
...fetchOptions,
headers: {
"User-Agent": getDefaultUserAgent(),
...fetchOptions.headers,
},
signal,
dispatcher: agent,
}),
@@ -89,6 +97,10 @@ export const fetchWithTrustedCertificatesAsync = async (
const { bodyTimeout: _bodyTimeout, dispatcher: _dispatcher, ...fetchOptions } = options ?? {};
return fetch(url, {
...fetchOptions,
headers: {
"User-Agent": getDefaultUserAgent(),
...fetchOptions.headers,
},
dispatcher: agent,
});
};
+2 -1
View File
@@ -5276,7 +5276,8 @@
},
"complete": {
"title": "Restore Complete",
"message": "Database has been restored successfully. The server is restarting — please refresh the page in a few seconds."
"message": "Database has been restored successfully and the server has restarted. Your previous session was invalidated, so you need to sign in again to see the restored board.",
"button": "Sign in now"
},
"failed": {
"title": "Restore Failed"