Files
filebrowser/backend/pkg/settings/config.go
T

1356 lines
46 KiB
Go

package settings
import (
"bytes"
"fmt"
"io"
"log"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
"github.com/go-playground/validator/v10"
"github.com/goccy/go-yaml"
"github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
"github.com/gtsteffaniak/filebrowser/backend/internal/version"
"github.com/gtsteffaniak/go-logger/logger"
)
const (
defaultMinSearchLength = 3
defaultFrontendDescription = "FileBrowser Quantum is a file manager for the web which can be used to manage files on your server"
)
var Config Settings
const (
generatorPath = "/relative/or/absolute/path"
)
func Initialize(configFile string) {
initializeConfig(configFile, false)
}
// InitializeCLI loads config for CLI subcommands without server-only setup (ffmpeg, frontend, etc.).
func InitializeCLI(configFile string) {
initializeConfig(configFile, true)
}
func initializeConfig(configFile string, cliMode bool) {
Env.IsCLIMode = cliMode
err := loadConfigWithDefaults(configFile, false)
if err != nil {
logger.Error("unable to load config, waiting 5 seconds before exiting...")
time.Sleep(5 * time.Second) // allow sleep time before exiting to give docker/kubernetes time before restarting
logger.Fatal(err.Error())
}
setupLogging()
// setup logging first to ensure we log any errors
setupEnv()
err = ValidateConfig(Config)
if err != nil {
errmsg := "The provided config file failed validation. "
errmsg += "If you are seeing this on a config that worked before, "
errmsg += "then check the latest releases for breaking changes. "
errmsg += "visit https://github.com/gtsteffaniak/filebrowser/wiki/Full-Config-Example for more information."
logger.Error(errmsg)
time.Sleep(5 * time.Second) // allow sleep time before exiting to give docker/kubernetes time before restarting
logger.Fatal(err.Error())
}
setupFs()
setupServer()
setupHttp()
setupAuth(false)
setupSources(false)
InitializeUserResolvers() // Initialize user package resolvers after sources are set up
setupUrls()
if cliMode {
return
}
warnHttpProxyConfig()
setupFrontend(false)
setupMedia()
}
func setupServer() {
// Check environment variable first (overrides config file)
if os.Getenv("FILEBROWSER_SQL_WAL") == "true" {
Config.Server.IndexSqlConfig.WalMode = true
}
}
func setupEnv() {
Env.IsPlaywright = os.Getenv("FILEBROWSER_PLAYWRIGHT_TEST") == "true"
if Env.IsPlaywright {
logger.Warning("Running in playwright test mode. This is not recommended for production.")
}
Env.IsDevMode = os.Getenv("FILEBROWSER_DEVMODE") == "true"
if Env.IsDevMode {
logger.Warning("Running in dev mode. This is not recommended for production.")
}
}
func setupHttp() {
if err := ValidateHttpConfig(Config.Http); err != nil {
logger.Fatal(err.Error())
}
if Config.Http.ListenAddress == "" {
Config.Http.ListenAddress = "0.0.0.0"
}
}
func warnHttpProxyConfig() {
if Env.IsDevMode || Env.IsPlaywright {
return
}
if Config.Http.BaseURL != "/" && !Config.Http.TrustProxyHeaders {
logger.Warning(`http.baseURL is not "/" but http.trustProxyHeaders is false. Behind a reverse proxy on a subpath, set trustProxyHeaders: true so cookies, OIDC redirects, and URLs resolve correctly, and list the proxy addresses in http.trustedProxies so the client IP resolves too. See https://filebrowserquantum.com/en/docs/configuration/http/#trustproxyheaders`)
}
if len(Config.Http.TrustedProxies) > 0 && !Config.Http.TrustProxyHeaders {
logger.Warning("http.trustedProxies is set but http.trustProxyHeaders is false; trusted proxy entries are ignored until trustProxyHeaders is enabled")
}
// Check the parsed list: blank entries are accepted by validation but yield no prefixes.
if Config.Http.TrustProxyHeaders && len(TrustedProxyPrefixes()) == 0 && Config.Http.Socket == "" {
logger.Warning("http.trustProxyHeaders is true but http.trustedProxies is empty; X-Forwarded-For and X-Real-IP are ignored, so client IPs (rate limits, activity logs) resolve to the proxy address. Add your reverse proxy addresses to http.trustedProxies.")
}
if Config.Http.TrustProxyHeaders && Config.Http.Socket != "" && !strings.HasPrefix(Config.Http.Socket, "@") &&
len(Config.Http.UnixSocketTrustedUIDs) == 0 && len(Config.Http.UnixSocketTrustedGIDs) == 0 {
logger.Warning("http.trustProxyHeaders is true and http.socket is a filesystem Unix socket, but http.unixSocketTrustedUIDs and http.unixSocketTrustedGIDs are empty; X-Forwarded-For and X-Real-IP are ignored until you list the reverse proxy's UID or GID (Linux peer credentials).")
}
if !Env.IsDevMode {
if u := Config.Http.ExternalUrl; u != "" && strings.HasPrefix(strings.ToLower(u), "http://") {
logger.Warning("http.externalUrl uses http when the url should be https for a production environment")
}
if u := Config.Integrations.OnlyOffice.Url; u != "" && strings.HasPrefix(strings.ToLower(u), "http://") {
logger.Warning("integrations.office.url uses http when it should be https for a production environment.")
}
}
}
func warnOidcProxyHeaders() {
if !Config.Auth.Methods.OidcAuth.Enabled {
return
}
if Config.Http.TrustProxyHeaders {
return
}
logger.Warning("OIDC is enabled but http.trustProxyHeaders is false. Behind a reverse proxy, FileBrowser builds the OIDC redirect_uri from the incoming request; set trustProxyHeaders: true and configure your proxy to send X-Forwarded-Proto and X-Forwarded-Host. http.externalUrl does not apply to OIDC redirects.")
}
func setupFs() {
// Convert permission values (like 644, 755) to octal interpretation
filePermOctal, err := strconv.ParseUint(Config.Server.Filesystem.CreateFilePermission, 8, 32)
if err != nil {
Config.Server.Filesystem.CreateFilePermission = "644"
filePermOctal, _ = strconv.ParseUint("644", 8, 32)
}
dirPermOctal, err := strconv.ParseUint(Config.Server.Filesystem.CreateDirectoryPermission, 8, 32)
if err != nil {
Config.Server.Filesystem.CreateDirectoryPermission = "755"
dirPermOctal, _ = strconv.ParseUint("755", 8, 32)
}
fileutils.SetFsPermissions(uint32(filePermOctal), uint32(dirPermOctal))
// Perform mandatory cache directory speed test
testCacheDirSpeed()
if err := PrepareDownloadSpoolDir(); err != nil {
logger.Fatalf("cacheDir failed to prepare download spool: %v", err)
}
logger.Infof("cache directory setup successfully: %v", Config.Server.CacheDir)
}
// testCacheDirSpeed performs a mandatory speed test on the cache directory by writing,
// reading, and deleting a 10MB test file. Reports write and read performance in MB/s.
func testCacheDirSpeed() {
msgPrfx := "cacheDir"
failSuffix := "Please review documentation to ensure a valid cache directory is configured https://filebrowserquantum.com/en/docs/configuration/server/#cachedir"
const testFileSize = 10 * 1024 * 1024 // 10MB
// Ensure cache directory exists
err := os.MkdirAll(Config.Server.CacheDir, fileutils.PermDir)
if err != nil {
logger.Fatalf("%s failed to create cache directory: %v\n%s", msgPrfx, err, failSuffix)
}
file, err := os.CreateTemp(Config.Server.CacheDir, "speed_test_*.tmp")
if err != nil {
logger.Fatalf("%s failed to create test file: %v\n%s", msgPrfx, err, failSuffix)
}
testFileName := file.Name()
// Create test data (10MB of zeros)
testData := make([]byte, testFileSize)
// Test write performance
writeStart := time.Now()
written, err := file.Write(testData)
if err != nil {
file.Close()
os.Remove(testFileName)
logger.Fatalf("%s failed to write test file: %v\n%s", msgPrfx, err, failSuffix)
}
err = file.Sync() // Ensure data is written to disk
if err != nil {
file.Close()
os.Remove(testFileName)
logger.Fatalf("%s failed to sync test file to disk: %v\n%s", msgPrfx, err, failSuffix)
}
err = file.Close()
if err != nil {
os.Remove(testFileName)
logger.Fatalf("%s failed to close test file: %v\n%s", msgPrfx, err, failSuffix)
}
writeDuration := time.Since(writeStart)
writeSpeedMBs := float64(written) / (1024 * 1024) / writeDuration.Seconds()
// Test read performance
readStart := time.Now()
file, err = os.Open(testFileName)
if err != nil {
os.Remove(testFileName)
logger.Fatalf("%s failed to open test file for reading: %v\n%s", msgPrfx, err, failSuffix)
}
readData := make([]byte, testFileSize)
readBytes, err := io.ReadFull(file, readData)
if err != nil {
file.Close()
os.Remove(testFileName)
logger.Fatalf("%s failed to read test file: %v\n%s", msgPrfx, err, failSuffix)
}
err = file.Close()
if err != nil {
os.Remove(testFileName)
logger.Fatalf("%s failed to close test file after reading: %v\n%s", msgPrfx, err, failSuffix)
}
readDuration := time.Since(readStart)
readSpeedMBs := float64(readBytes) / (1024 * 1024) / readDuration.Seconds()
// Verify data integrity
if readBytes != written {
os.Remove(testFileName)
logger.Fatalf("%s data integrity check failed: wrote %d bytes but read %d bytes\n%s", msgPrfx, written, readBytes, failSuffix)
}
// Clean up test file
err = os.Remove(testFileName)
if err != nil {
logger.Fatalf("%s failed to remove test file: %v\n%s", msgPrfx, err, failSuffix)
}
// Log performance results
writeDurationMs := writeDuration.Seconds() * 1000
readDurationMs := readDuration.Seconds() * 1000
const highLatencyThresholdMs = 1000.0 // 1 second for 10MB file indicates high latency
if writeSpeedMBs < 50 {
slowSuffix := " Ensure you configure a faster cache directory via the `server.cacheDir` configuration option."
logger.Warningf("%s slow write speed detected: %.2f MB/s (%.2f ms)\n%s\n%s", msgPrfx, writeSpeedMBs, writeDurationMs, failSuffix, slowSuffix)
} else if writeDurationMs > highLatencyThresholdMs {
slowSuffix := " Ensure you configure a faster cache directory via the `server.cacheDir` configuration option."
logger.Warningf("%s high write latency detected: %.2f ms for 10MB file (speed: %.2f MB/s). This may indicate network storage or I/O issues.\n%s\n%s", msgPrfx, writeDurationMs, writeSpeedMBs, failSuffix, slowSuffix)
} else {
logger.Debugf("%s write speed: %.2f MB/s (%.2f ms)", msgPrfx, writeSpeedMBs, writeDurationMs)
}
if readSpeedMBs < 50 {
slowSuffix := " Ensure you configure a faster cache directory via the `server.cacheDir` configuration option."
logger.Warningf("%s slow read speed detected: %.2f MB/s (%.2f ms)\n%s\n%s", msgPrfx, readSpeedMBs, readDurationMs, failSuffix, slowSuffix)
} else if readDurationMs > highLatencyThresholdMs {
slowSuffix := " Ensure you configure a faster cache directory via the `server.cacheDir` configuration option."
logger.Warningf("%s high read latency detected: %.2f ms for 10MB file (speed: %.2f MB/s). This may indicate network storage or I/O issues.\n%s\n%s", msgPrfx, readDurationMs, readSpeedMBs, failSuffix, slowSuffix)
} else {
logger.Debugf("%s read speed : %.2f MB/s (%.2f ms)", msgPrfx, readSpeedMBs, readDurationMs)
}
// check cache directory disk free space
freeSpace, err := fileutils.GetFreeSpace(Config.Server.CacheDir)
if err != nil {
logger.Fatalf("%s failed to get free space for cache directory: %v\n%s", msgPrfx, err, failSuffix)
}
freeSpaceGB := float64(freeSpace) / (1024 * 1024 * 1024)
logger.Debugf("%s cache directory has %.2f GB of free space", msgPrfx, freeSpaceGB)
const minRecommendedGB = 20.0
if freeSpaceGB < minRecommendedGB {
logger.Warningf("%s only has %.2f GB of free space, this is less than the %.0f GB minimum recommended free space.\n%s", msgPrfx, freeSpaceGB, minRecommendedGB, failSuffix)
}
}
func setupFrontend(generate bool) {
// Load login icon configuration at startup
loadLoginIcon()
if Config.Server.MinSearchLength == 0 {
Config.Server.MinSearchLength = defaultMinSearchLength
}
if !Config.Frontend.DisableDefaultLinks {
Config.Frontend.ExternalLinks = append(Config.Frontend.ExternalLinks, ExternalLink{
Text: fmt.Sprintf("(%v)", version.Version),
Title: version.CommitSHA,
Url: "https://github.com/gtsteffaniak/filebrowser/releases/",
})
Config.Frontend.ExternalLinks = append(Config.Frontend.ExternalLinks, ExternalLink{
Text: "Help",
Url: "help prompt",
})
}
if Config.Frontend.Description == "" {
Config.Frontend.Description = defaultFrontendDescription
}
Config.Frontend.Styling.LightBackground = FallbackColor(Config.Frontend.Styling.LightBackground, "#f5f5f5")
Config.Frontend.Styling.DarkBackground = FallbackColor(Config.Frontend.Styling.DarkBackground, "#141D24")
var err error
if Config.Frontend.Styling.CustomCSS != "" {
Config.Frontend.Styling.CustomCSSRaw, err = readCustomCSS(Config.Frontend.Styling.CustomCSS)
if err != nil {
logger.Warning(err.Error())
}
}
Config.Frontend.Styling.CustomThemeOptions = map[string]CustomTheme{}
if Config.Frontend.Styling.CustomThemes == nil {
Config.Frontend.Styling.CustomThemes = map[string]CustomTheme{}
}
for name, theme := range Config.Frontend.Styling.CustomThemes {
addCustomTheme(name, theme.Description, theme.CSS)
}
noThemes := len(Config.Frontend.Styling.CustomThemes) == 0
if noThemes {
addCustomTheme("default", "The default theme", "")
// check if file exists
if _, err := os.Stat("reduce-rounded-corners.css"); err == nil {
addCustomTheme("alternative", "Reduce rounded corners", "reduce-rounded-corners.css")
if generate {
Config.Frontend.Styling.CustomThemes["alternative"] = CustomTheme{
Description: "Reduce rounded corners",
CSS: "reduce-rounded-corners.css",
}
}
}
}
_, ok := Config.Frontend.Styling.CustomThemes["default"]
if !ok {
addCustomTheme("default", "The default theme", "")
}
// Load custom favicon if configured
loadCustomFavicon()
}
// setupMedia normalizes the media integration settings. ffmpeg initialization is
// deferred to InitFFmpeg so the hardware codec probe runs once, after persisted
// media settings have been applied.
func setupMedia() {
applyMediaConvertDefaults()
setupMediaTranscode()
}
// applyMediaConvertDefaults re-seeds the conversion format maps and reapplies the
// user's explicit config overrides (the maps are wiped during YAML unmarshal).
func applyMediaConvertDefaults() {
// Save user's explicit config before applying defaults
userImageConfig := make(map[ImagePreviewType]*bool)
for k, v := range Config.Integrations.Media.Convert.ImagePreview {
userImageConfig[k] = v
}
// Re-initialize with defaults (gets wiped out during YAML unmarshal)
Config.Integrations.Media.Convert.ImagePreview = make(map[ImagePreviewType]*bool)
Config.Integrations.Media.Convert.ImagePreview[HEICImagePreview] = boolPtr(false) // HEIC defaults to disabled
Config.Integrations.Media.Convert.ImagePreview[JXLImagePreview] = boolPtr(true) // JXL uses pure Go decode
Config.Integrations.Media.Convert.ImagePreview[JPEGImagePreview] = boolPtr(true) // JPEG fallback defaults to enabled
// Apply user overrides (only for keys explicitly set in YAML). The pointers are
// cloned so the live config never shares *bool values with the settings it was
// built from.
for k, v := range userImageConfig {
Config.Integrations.Media.Convert.ImagePreview[k] = cloneBoolPtr(v)
}
// VideoPreview: Merge user config with defaults
// Save user's explicit config from YAML
userVideoConfig := make(map[VideoPreviewType]*bool)
for k, v := range Config.Integrations.Media.Convert.VideoPreview {
userVideoConfig[k] = v
}
// Re-initialize with defaults (all enabled)
Config.Integrations.Media.Convert.VideoPreview = make(map[VideoPreviewType]*bool)
for _, t := range AllVideoPreviewTypes {
Config.Integrations.Media.Convert.VideoPreview[t] = boolPtr(true)
}
// Apply user overrides (only for keys explicitly set in YAML)
for k, v := range userVideoConfig {
Config.Integrations.Media.Convert.VideoPreview[k] = cloneBoolPtr(v)
}
}
func setupMediaTranscode() {
t := &Config.Integrations.Media.Transcode
if t.MaxConcurrent <= 0 {
t.MaxConcurrent = 2
}
if t.MaxConcurrentPerUser <= 0 {
t.MaxConcurrentPerUser = 1
}
if t.CacheMaxSizeMB < 0 {
t.CacheMaxSizeMB = 0
}
if t.CacheMaxSizeMB == 0 && !t.Enabled {
t.CacheMaxSizeMB = 10240
}
if t.CacheRetentionH <= 0 {
t.CacheRetentionH = 24
}
clampTranscodeReadRate(t)
normalizeTranscodeProfile(&t.Profiles.Quality)
normalizeTranscodeProfile(&t.Profiles.Balanced)
normalizeTranscodeProfile(&t.Profiles.DataSaver)
}
const (
// defaultTranscodeReadRate applies when readRate is unset or non-positive.
defaultTranscodeReadRate = 2.0
// minTranscodeReadRate keeps producers at/above realtime so playback isn't
// starved by a producer slower than the player.
minTranscodeReadRate = 1.0
)
// clampTranscodeReadRate enforces throttled producers: unset or sub-realtime
// read rates are raised, so a producer is never left unthrottled. Burst and
// catch-up pacing are left to ffmpeg's defaults.
func clampTranscodeReadRate(t *FullAdminTranscode) {
if t.ReadRate <= 0 {
t.ReadRate = defaultTranscodeReadRate
} else if t.ReadRate < minTranscodeReadRate {
t.ReadRate = minTranscodeReadRate
}
}
// normalizeTranscodeProfile clamps negative profile values (0 means "original").
func normalizeTranscodeProfile(p *TranscodeProfile) {
if p.MaxResolution < 0 {
p.MaxResolution = 0
}
if p.AvgBitrateKbps < 0 {
p.AvgBitrateKbps = 0
}
}
// DefaultTranscodeProfiles returns the built-in transcode presets.
func DefaultTranscodeProfiles() TranscodeProfiles {
return TranscodeProfiles{
// Quality preserves the source: it stream-copies whatever is already
// HLS-compatible (h264 video / AAC audio) and transcodes only what isn't.
Quality: TranscodeProfile{Enabled: true, MaxResolution: 0, AvgBitrateKbps: 0},
// Balanced always transcodes to a bounded 720p rung. 4000 kbps sits in
// the standard 720p ladder (~3000-6000 kbps); the cap is a ceiling, so a
// source already below it keeps its own bitrate.
Balanced: TranscodeProfile{Enabled: true, MaxResolution: 720, AvgBitrateKbps: 4000},
// Data saver always transcodes to a bounded 480p rung. 1500 kbps gives
// solid 480p quality while still cutting typical source bitrates well
// below balanced.
DataSaver: TranscodeProfile{Enabled: true, MaxResolution: 480, AvgBitrateKbps: 1500},
}
}
func setupSources(generate bool) {
if len(Config.Server.Sources) == 0 {
logger.Fatal("There are no `server.sources` configured. If you have `server.root` configured, please update the config and add at least one `server.sources` with a `path` configured.")
} else {
for k, source := range Config.Server.Sources {
if source.Config.Disabled {
continue
}
realPath, err := AbsPath(source.Path)
if err != nil {
logger.Fatalf("error getting real path for source %v: %v", source.Path, err)
}
exists := utils.CheckPathExists(realPath)
if !exists {
logger.Warningf("source path %v is currently not available", realPath)
}
name := filepath.Base(realPath)
if name == "\\" {
name = strings.Split(realPath, ":")[0]
}
source.Path = realPath // use absolute path
if source.Name == "" {
_, ok := Config.Server.SourceMap[source.Path]
if ok {
source.Name = name + fmt.Sprintf("-%v", k)
} else {
source.Name = name
}
}
if generate {
source.Path = generatorPath // use placeholder path
source.Name = "Source Name"
}
modifyExcludeInclude(source)
setConditionals(source)
if source.Config.DefaultUserScope == "" {
source.Config.DefaultUserScope = "/"
}
Config.Server.SourceMap[source.Path] = source
Config.Server.NameToSource[source.Name] = source
}
}
// clean up the in memory source list to be accurate and unique
sourceList := []*Source{}
defaultScopes := []users.BackendScope{}
allSourceNames := []string{}
if len(Config.Server.Sources) == 1 {
Config.Server.Sources[0].Config.DefaultEnabled = true
}
for _, sourcePathOnly := range Config.Server.Sources {
absPath := sourcePathOnly.Path
if generate {
// When generating, skip path validation and use the already-set path
absPath = sourcePathOnly.Path
}
source, ok := Config.Server.SourceMap[absPath]
if ok && !slices.Contains(allSourceNames, source.Name) {
sourceList = append(sourceList, source)
if source.Config.DefaultEnabled {
defaultScopes = append(defaultScopes, users.BackendScope{
Path: source.Path,
Scope: source.Config.DefaultUserScope,
})
}
allSourceNames = append(allSourceNames, source.Name)
} else {
logger.Warningf("skipping source: %v", sourcePathOnly.Path)
}
}
Config.UserDefaults.DefaultScopes = defaultScopes
Config.Server.Sources = sourceList
finalizeConfigSourceDefaultPermissions()
}
func finalizeConfigSourceDefaultPermissions() {
Env.ConfigSourceDefaultPermissions = nil
for _, source := range Config.Server.Sources {
if source == nil || len(source.Config.DefaultPermissionsFromConfig) == 0 {
continue
}
Env.ConfigSourceDefaultPermissions = source.Config.DefaultPermissionsFromConfig
perms := NormalizeSourceFilePermissions(source.Config.DefaultPermissions)
for flag, val := range source.Config.DefaultPermissionsFromConfig {
setSourcePermissionFlag(&perms, flag, val)
}
source.Config.DefaultPermissions = users.MarkSourceFilePermissionsConfigured(perms)
return
}
}
func setupUrls() {
baseurl := strings.Trim(Config.Http.BaseURL, "/")
if baseurl == "" {
Config.Http.BaseURL = "/"
} else {
Config.Http.BaseURL = "/" + baseurl + "/"
}
if Config.Http.BaseURL != "/" {
if Config.Http.ExternalUrl != "" {
Config.Http.ExternalUrl = strings.TrimSuffix(Config.Http.ExternalUrl, "/") + "/"
Config.Http.ExternalUrl = strings.TrimSuffix(Config.Http.ExternalUrl, Config.Http.BaseURL)
}
if Config.Http.InternalUrl != "" {
Config.Http.InternalUrl = strings.TrimSuffix(Config.Http.InternalUrl, "/") + "/"
Config.Http.InternalUrl = strings.TrimSuffix(Config.Http.InternalUrl, Config.Http.BaseURL)
}
}
Config.Integrations.OnlyOffice.Url = strings.Trim(Config.Integrations.OnlyOffice.Url, "/")
Config.Integrations.OnlyOffice.InternalUrl = strings.Trim(Config.Integrations.OnlyOffice.InternalUrl, "/")
Config.Integrations.OnlyOffice.Product = strings.ToLower(strings.TrimSpace(Config.Integrations.OnlyOffice.Product))
if Config.Integrations.OnlyOffice.TokenExpirationHours <= 0 {
Config.Integrations.OnlyOffice.TokenExpirationHours = 10
}
}
func setupAuth(generate bool) {
if generate {
Config.Auth.Methods.PasswordAuth.AdminUsername = "admin"
Config.Auth.Methods.PasswordAuth.AdminPassword = "admin"
}
if Config.Auth.Methods.PasswordAuth.Enabled {
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "password")
ValidateRecaptcha()
}
if Config.Auth.Methods.ProxyAuth.Enabled {
applyAuthCommonDefaults(&Config.Auth.Methods.ProxyAuth.AuthCommon)
err := ValidateProxyAuth()
if err != nil && !generate {
logger.Fatalf("Error validating proxy auth: %v", err)
}
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "proxy")
}
if Config.Auth.Methods.NoAuth {
logger.Warning("Configured with no authentication, this is not recommended.")
Config.Auth.AuthMethods = []string{"disabled"}
}
if Config.Auth.Methods.OidcAuth.Enabled || generate {
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "oidc")
err := validateOidcAuth()
if err != nil && !generate {
logger.Fatalf("Error validating OIDC auth: %v", err)
}
logger.Info("OIDC Auth configured successfully")
if !generate {
warnOidcProxyHeaders()
}
}
if Config.Auth.Methods.LdapAuth.Enabled || generate {
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "ldap")
err := ValidateLdapAuth()
if err != nil && !generate {
logger.Fatalf("Error validating LDAP auth: %v", err)
}
logger.Info("LDAP Auth configured successfully")
}
if Config.Auth.Methods.JwtAuth.Enabled || generate {
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "jwt")
err := ValidateJwtAuth()
if err != nil && !generate {
logger.Fatalf("Error validating JWT auth: %v", err)
}
logger.Info("JWT Auth configured successfully")
}
if Config.Auth.Methods.PasskeyAuth.Enabled || generate {
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "passkey")
logger.Info("Passkey Auth configured successfully")
}
// use password auth as default if no auth methods are set
if len(Config.Auth.AuthMethods) == 0 {
Config.Auth.Methods.PasswordAuth.Enabled = true
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "password")
ValidateRecaptcha()
}
Config.UserDefaults.Account.LoginMethod = Config.Auth.AuthMethods[0]
}
func setupLogging() {
if len(Config.Server.Logging) == 0 {
Config.Server.Logging = []LogConfig{
{
Output: "stdout",
},
}
}
// Tests quiet the logger in testutil.Main; skip stacking handlers here.
if isGoTest() && os.Getenv("FILEBROWSER_TEST_LOG") == "" {
return
}
for i := range Config.Server.Logging {
cfg := &Config.Server.Logging[i]
// Enable debug logging automatically in dev mode
pattern := cfg.ApiFilter
if pattern == "" {
pattern = "^/health|^/favicon.ico|^/static|^/public/static|^/__vite"
}
levels := cfg.Levels
if os.Getenv("FILEBROWSER_DEVMODE") == "true" {
levels = "info|warning|error|debug"
}
jsonCfg := logger.JsonConfig{
Levels: levels,
ApiLevels: cfg.ApiLevels,
Output: cfg.Output,
Utc: cfg.Utc,
NoColors: cfg.NoColors,
Json: cfg.Json,
Structured: false,
ApiPathExclude: pattern,
}
err := logger.EnableCompatibilityMode(jsonCfg)
if err != nil {
log.Println("[ERROR] Failed to set up logger:", err)
}
}
}
func loadConfigWithDefaults(configFile string, generate bool) error {
Config = SetDefaults(generate)
// Check if config file exists
if _, err := os.Stat(configFile); err != nil {
if configFile != "" {
logger.Errorf("could not open config file '%v', using default settings.", configFile)
}
Config.Server.Sources = []*Source{
{
Path: ".",
},
}
loadEnvConfig()
return ResolveDatabasePaths()
}
// Try multi-file config first (combine all YAML files in the directory)
combinedYAML, err := combineYAMLFiles(configFile)
if err != nil {
return fmt.Errorf("failed to combine YAML files: %v", err)
}
// First pass: Unmarshal into a generic map to resolve all anchors and aliases
// This allows YAML anchors defined in auxiliary files to be properly merged
var rawConfig map[string]interface{}
err = yaml.Unmarshal(combinedYAML, &rawConfig)
if err != nil {
return fmt.Errorf("error parsing YAML data: %v", err)
}
// Expand $VAR / ${VAR} in decoded string scalars only (after parse) so
// secrets may contain quotes, backslashes, or newlines safely.
expandConfigEnv(rawConfig)
// Filter to only keep valid top-level Settings struct fields
// This removes anchor definitions that are just templates (e.g., "test_server: &test_server")
validFields := map[string]bool{
"server": true,
"auth": true,
"integrations": true,
"frontend": true,
"userDefaults": true,
"http": true,
}
filteredConfig := make(map[string]interface{})
for key, value := range rawConfig {
if validFields[key] {
filteredConfig[key] = value
}
}
if udRaw, ok := filteredConfig["userDefaults"]; ok {
Env.ConfigUserDefaultsSpecified = true
if udMap, ok := udRaw.(map[string]interface{}); ok {
Env.ConfigUserDefaultsSpecifiedPaths = CollectMapLeafPaths(udMap, "")
}
}
// Runtime media settings live in the database; record which ones the config
// file pins so they can win over stored values and lock in the admin UI.
if integrations, ok := filteredConfig["integrations"].(map[string]interface{}); ok {
if mediaMap, ok := integrations["media"].(map[string]interface{}); ok {
paths := CollectMapLeafPaths(mediaMap, "")
// skipHwCheck is config-only, not a runtime media setting — don't
// let it trigger the "locked from config" admin UI state.
Env.ConfigMediaSpecifiedPaths = slices.DeleteFunc(paths, func(p string) bool {
return p == "skipHwCheck"
})
}
}
// check if database is set in the config
if server, ok := filteredConfig["server"].(map[string]interface{}); ok {
val, ok := server["database"].(string)
if ok && val != "" {
return fmt.Errorf("old database path is set in the config, please migrate your database to SQLite")
}
}
// Marshal the filtered config back to YAML
filteredYAML, err := yaml.Marshal(filteredConfig)
if err != nil {
return fmt.Errorf("error re-marshaling filtered YAML: %v", err)
}
// Second pass: Decode with strict validation (disallow unknown fields within valid sections)
// UseJSONUnmarshaler lets typed fields with custom UnmarshalJSON (e.g. users.DarkMode)
// handle YAML scalars like booleans instead of the generic decoder casting them to strings.
decoder := yaml.NewDecoder(bytes.NewReader(filteredYAML), yaml.DisallowUnknownField(), yaml.UseJSONUnmarshaler())
err = decoder.Decode(&Config)
if err != nil {
return fmt.Errorf("error unmarshaling YAML data: %v", err)
}
MigrateLegacyPasswordAdminFromAuth()
if err := applyLoadedUserDefaultsFromConfig(generate); err != nil {
return err
}
attachSourceDefaultPermissionsFromConfig(filteredConfig)
loadEnvConfig()
return ResolveDatabasePaths()
}
// applyLoadedUserDefaultsFromConfig merges config-specified userDefaults paths onto
// SetDefaults so partial YAML (e.g. only account.permissions.share) does not zero
// unspecified sections such as preview thumbnails or fileViewer.autoplayMedia.
func applyLoadedUserDefaultsFromConfig(generate bool) error {
if !Env.ConfigUserDefaultsSpecified {
return nil
}
base := SetDefaults(generate).UserDefaults
merged, err := ApplyConfigSpecifiedPathsToUserDefaults(base, Config.UserDefaults)
if err != nil {
return fmt.Errorf("merge user defaults with config: %w", err)
}
Config.UserDefaults = merged
return nil
}
func attachSourceDefaultPermissionsFromConfig(raw map[string]interface{}) {
server, ok := raw["server"].(map[string]interface{})
if !ok {
return
}
sources, ok := server["sources"].([]interface{})
if !ok {
return
}
for i, srcRaw := range sources {
if i >= len(Config.Server.Sources) || Config.Server.Sources[i] == nil {
continue
}
src, ok := srcRaw.(map[string]interface{})
if !ok {
continue
}
config, ok := src["config"].(map[string]interface{})
if !ok {
continue
}
dp, ok := config["defaultPermissions"].(map[string]interface{})
if !ok || len(dp) == 0 {
continue
}
fromConfig := make(map[string]bool, len(dp))
for key, val := range dp {
if b, ok := val.(bool); ok {
fromConfig[key] = b
}
}
Config.Server.Sources[i].Config.DefaultPermissionsFromConfig = fromConfig
}
}
func ValidateConfig(config Settings) error {
validate := validator.New()
// Register custom validator for file permissions
err := validate.RegisterValidation("file_permission", validateFilePermission)
if err != nil {
return fmt.Errorf("could not register file_permission validator: %v", err)
}
err = validate.Struct(Config)
if err != nil {
return fmt.Errorf("could not validate config: %v", err)
}
return nil
}
// validateFilePermission validates that a string is a valid Unix octal file permission (3-4 digits, 0-7)
func validateFilePermission(fl validator.FieldLevel) bool {
value := fl.Field().String()
// Must be 3 or 4 characters long
if len(value) < 3 || len(value) > 4 {
return false
}
// All characters must be octal digits (0-7)
for _, char := range value {
if char < '0' || char > '7' {
return false
}
}
return true
}
func loadEnvConfig() {
adminPassword, ok := os.LookupEnv("FILEBROWSER_ADMIN_PASSWORD")
if ok {
logger.Info("Using admin password from FILEBROWSER_ADMIN_PASSWORD environment variable")
Config.Auth.Methods.PasswordAuth.AdminPassword = adminPassword
}
officeSecret, ok := os.LookupEnv("FILEBROWSER_ONLYOFFICE_SECRET")
if ok {
logger.Info("Using OnlyOffice secret from FILEBROWSER_ONLYOFFICE_SECRET environment variable")
Config.Integrations.OnlyOffice.Secret = officeSecret
}
ffmpegPath, ok := os.LookupEnv("FILEBROWSER_FFMPEG_PATH")
if ok {
Config.Integrations.Media.FfmpegPath = ffmpegPath
}
oidcClientId := os.Getenv("FILEBROWSER_OIDC_CLIENT_ID")
if oidcClientId != "" {
Config.Auth.Methods.OidcAuth.ClientID = oidcClientId
logger.Info("Using OIDC Client ID from FILEBROWSER_OIDC_CLIENT_ID environment variable")
}
oidcClientSecret := os.Getenv("FILEBROWSER_OIDC_CLIENT_SECRET")
if oidcClientSecret != "" {
Config.Auth.Methods.OidcAuth.ClientSecret = oidcClientSecret
logger.Info("Using OIDC Client Secret from FILEBROWSER_OIDC_CLIENT_SECRET environment variable")
}
jwtTokenSecret := os.Getenv("FILEBROWSER_JWT_TOKEN_SECRET")
if jwtTokenSecret != "" {
Config.Auth.Key = jwtTokenSecret
logger.Info("Using JWT Token Secret from FILEBROWSER_JWT_TOKEN_SECRET environment variable")
}
totpSecret := os.Getenv("FILEBROWSER_TOTP_SECRET")
if totpSecret != "" {
Config.Auth.TotpSecret = totpSecret
logger.Info("Using TOTP Secret from FILEBROWSER_TOTP_SECRET environment variable")
}
recaptchaSecret := os.Getenv("FILEBROWSER_RECAPTCHA_SECRET")
if recaptchaSecret != "" {
Config.Auth.Methods.PasswordAuth.Recaptcha.Secret = recaptchaSecret
logger.Info("Using ReCaptcha Secret from FILEBROWSER_RECAPTCHA_SECRET environment variable")
}
ldapUserPassword := os.Getenv("FILEBROWSER_LDAP_USER_PASSWORD")
if ldapUserPassword != "" {
Config.Auth.Methods.LdapAuth.UserPassword = ldapUserPassword
logger.Info("Using LDAP bind password from FILEBROWSER_LDAP_USER_PASSWORD environment variable")
}
}
func SetDefaults(generate bool) Settings {
// New SQLite database path
databaseV2 := os.Getenv("FILEBROWSER_DATABASE_PATH")
if databaseV2 == "" {
databaseV2 = "filebrowser.sqlite"
}
s := Settings{
Http: Http{
Port: 80,
BaseURL: "",
},
Server: Server{
SearchResultsLimit: 1000,
MinSearchLength: defaultMinSearchLength,
NumImageProcessors: 4,
DatabaseV2: Database{
Path: databaseV2,
Activity: ActivityConfig{
RetentionDays: 30,
FlushIntervalSeconds: 10,
MaxBufferSize: 10000,
},
Quotas: QuotasConfig{
FlushIntervalSeconds: 10,
FlushMaxBuffers: 500,
},
},
SourceMap: map[string]*Source{},
NameToSource: map[string]*Source{},
CacheDir: "tmp",
MaxArchiveSizeGB: 20,
IndexSqlConfig: IndexSqlConfig{
WalMode: false,
BatchSize: 1000,
CacheSizeMB: 32,
DisableReuse: false,
FTS5: false,
StartupIntegrityCheck: IndexStartupIntegrityQuickCheck,
},
Filesystem: Filesystem{
CreateFilePermission: "644",
CreateDirectoryPermission: "755",
},
},
Auth: Auth{
TokenExpirationHours: 2,
Methods: LoginMethods{
PasswordAuth: PasswordAuthConfig{
Enabled: true,
MinLength: 5,
Signup: false,
},
},
},
Frontend: Frontend{
Name: "FileBrowser Quantum",
Description: defaultFrontendDescription,
},
UserDefaults: UserDefaults{
// New organized structure
Sidebar: UserDefaultsSidebar{
DisableQuickToggles: false,
HideFileActions: false,
DisableHideOnPreview: false,
Sticky: true,
HideFiles: false,
ShowTools: boolPtr(true),
},
Listing: UserDefaultsListing{
DeleteWithoutConfirming: false,
PromptRightCloseButton: false,
DateFormat: false,
ShowHidden: false,
QuickDownload: false,
ShowSelectMultiple: false,
SingleClick: false,
HideFileExt: "",
ShowCopyPath: false,
ShowTypeColumn: false,
ShowCreationDateColumn: false,
DeleteAfterArchive: true,
ViewMode: "normal",
GallerySize: 3,
NewFileTemplate: []string{""},
},
Preview: UserDefaultsPreview{
Image: boolPtr(true),
Video: boolPtr(true),
Audio: boolPtr(true),
MotionVideoPreview: boolPtr(true),
Office: boolPtr(true),
PopUp: boolPtr(true),
DisablePreviewExt: "",
HighQuality: boolPtr(true),
Folder: boolPtr(true),
Models: boolPtr(true),
},
FileViewer: UserDefaultsFileViewer{
AutoplayMedia: boolPtr(true),
DisableViewingExt: "",
DisableOnlyOfficeExt: ".md .txt .pdf .html .xml",
PreferEditorForMarkdown: false,
DebugOffice: false,
},
Search: UserDefaultsSearch{
DisableOptions: false,
},
UI: UserDefaultsUI{
DarkMode: users.DarkModeDark,
ThemeColor: "var(--blue)",
CustomTheme: "",
Locale: "en",
},
FileLoading: users.FileLoading{
MaxConcurrent: 10,
UploadChunkSize: 10, // 10MB
DownloadChunkSize: 0, // 0MB, default to no chunking
},
Account: UserDefaultsAccount{
Permissions: UserDefaultsAccountPermissions{
Api: false,
Admin: false,
Share: false,
Realtime: false,
},
LockPassword: false,
RequirePasswordChange: false,
DisableSettings: false,
LoginMethod: "",
DisableUpdateNotifications: false,
ShowAdvancedProfile: false,
MaxConcurrentTranscodes: 1,
},
},
}
// Initialize ImagePreview map with defaults
s.Integrations.Media.Convert.ImagePreview = make(map[ImagePreviewType]*bool)
s.Integrations.Media.Convert.ImagePreview[HEICImagePreview] = boolPtr(false) // HEIC defaults to disabled
s.Integrations.Media.Convert.ImagePreview[JXLImagePreview] = boolPtr(true) // JXL uses pure Go decode
s.Integrations.Media.Convert.ImagePreview[JPEGImagePreview] = boolPtr(true) // JPEG fallback defaults to enabled
// Initialize VideoPreview map with defaults (all enabled)
s.Integrations.Media.Convert.VideoPreview = make(map[VideoPreviewType]*bool)
for _, t := range AllVideoPreviewTypes {
s.Integrations.Media.Convert.VideoPreview[t] = boolPtr(true)
}
s.Integrations.Media.Transcode = FullAdminTranscode{
UserTranscode: UserTranscode{
Enabled: false,
MaxConcurrentPerUser: 1,
},
MaxConcurrent: 2,
CacheMaxSizeMB: 10240,
CacheRetentionH: 24,
ReadRate: defaultTranscodeReadRate,
Profiles: DefaultTranscodeProfiles(),
}
// Hardware acceleration is opt-out: "auto" lets go-ffmpeg follow its device
// hierarchy (integrated GPU, discrete GPU, then software).
s.Integrations.Media.HardwareAcceleration = true
s.Integrations.Media.AccelDevice = "auto"
return s
}
// validateCustomImage validates a custom image file path and returns the absolute path or error
func validateCustomImage(configPath, imageName string, allowedFormats []string) (absolutePath string, err error) {
// Get absolute path
absolutePath, err = AbsPath(configPath)
if err != nil {
return "", fmt.Errorf("could not resolve path: %w", err)
}
// Check if file exists
_, err = os.Stat(absolutePath)
if err != nil {
return "", fmt.Errorf("could not access file: %w", err)
}
// Validate file format
ext := strings.ToLower(filepath.Ext(absolutePath))
validFormat := false
for _, format := range allowedFormats {
if ext == format {
validFormat = true
break
}
}
if !validFormat {
return "", fmt.Errorf("unsupported format '%s', supported formats: %v", ext, allowedFormats)
}
return absolutePath, nil
}
func loadCustomFavicon() {
const imageName = "favicon"
allowedFormats := []string{".ico", ".png", ".svg", ".jpg", ".jpeg", ".gif", ".webp"}
// Set default embedded favicon path
Env.FaviconEmbeddedPath = "img/icons/favicon.svg"
// Check if a custom favicon path is configured
if Config.Frontend.Favicon == "" {
Env.FaviconPath = Env.FaviconEmbeddedPath
Env.FaviconIsCustom = false
return
}
// Validate custom favicon
validatedPath, err := validateCustomImage(Config.Frontend.Favicon, imageName, allowedFormats)
if err != nil {
logger.Warningf("Custom favicon validation failed: %v, using default", err)
Config.Frontend.Favicon = ""
Env.FaviconPath = Env.FaviconEmbeddedPath
Env.FaviconIsCustom = false
return
}
// Update to validated path and mark as custom
Config.Frontend.Favicon = validatedPath
Env.FaviconPath = validatedPath
Env.FaviconIsCustom = true
logger.Infof("Using custom favicon: %s", Env.FaviconPath)
// PWA and platform PNGs are generated at server startup from this path (SVG uses a raster
// sidecar next to the .svg when present; see icons.GeneratePWAIcons).
}
// PWAIconsCacheDir is where startup icon generation writes PNGs (under the server cache dir).
func PWAIconsCacheDir() string {
return filepath.Join(Config.Server.CacheDir, "icons")
}
// Where transient archives for multi-request (Range) downloads are stored to support chunked downloads.
func DownloadCacheDir() string {
return filepath.Join(Config.Server.CacheDir, "downloads")
}
// TranscodeCacheDir is where HLS transcode output is cached on disk.
func TranscodeCacheDir() string {
return filepath.Join(Config.Server.CacheDir, "transcoding")
}
// TranscodeKeyframeCacheDir is where probed per-file keyframe indexes are
// persisted. It is separate from TranscodeCacheDir so the segment-cache
// retention/eviction sweep (which owns the transcode tree) never treats a
// keyframe index as a generation.
func TranscodeKeyframeCacheDir() string {
return filepath.Join(Config.Server.CacheDir, "transcode-keyframes")
}
// PrepareDownloadSpoolDir creates the download spool directory and removes any leftover dl-archive-*
func PrepareDownloadSpoolDir() error {
if err := os.MkdirAll(DownloadCacheDir(), fileutils.PermDir); err != nil {
return err
}
return fileutils.ClearDirectoryContents(DownloadCacheDir())
}
func loadLoginIcon() {
const imageName = "login icon"
allowedFormats := []string{".svg", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico"}
// Set default embedded icon path - just use favicon.svg (light/dark handled by CSS)
Env.LoginIconEmbeddedPath = "img/icons/favicon.svg"
// Check if a custom login icon path is configured
if Config.Frontend.LoginIcon == "" {
Env.LoginIconPath = Env.LoginIconEmbeddedPath
Env.LoginIconIsCustom = false
return
}
// Validate custom login icon
validatedPath, err := validateCustomImage(Config.Frontend.LoginIcon, imageName, allowedFormats)
if err != nil {
logger.Warningf("Custom login icon validation failed: %v, using default", err)
Env.LoginIconPath = Env.LoginIconEmbeddedPath
Env.LoginIconIsCustom = false
return
}
// Update to validated path and mark as custom
Env.LoginIconPath = validatedPath
Env.LoginIconIsCustom = true
logger.Infof("Using custom login icon: %s", Env.LoginIconPath)
}
// setConditionals builds optimized map structures from source rules for O(1) lookups.
func setConditionals(config *Source) {
rules := config.Config.Rules
// Initialize the maps structure (only exact match maps for Names)
resolved := ResolvedRulesConfig{
FileNames: make(map[string]ConditionalRule),
FolderNames: make(map[string]ConditionalRule),
FilePaths: make(map[string]ConditionalRule),
FolderPaths: make(map[string]ConditionalRule),
FileEndsWith: make([]ConditionalRule, 0),
FolderEndsWith: make([]ConditionalRule, 0),
FileStartsWith: make([]ConditionalRule, 0),
FolderStartsWith: make([]ConditionalRule, 0),
NeverWatchPaths: make(map[string]struct{}),
IncludeRootItems: make(map[string]struct{}),
IgnoreAllHidden: false,
IgnoreAllZeroSizeFolders: false,
IgnoreAllSymlinks: false,
IndexingDisabled: false,
NoRules: len(rules) == 0,
}
// Process all rules and infer global flags from root-level rules
for _, rule := range rules {
// Check if this is a root-level rule (folderPath == "/")
// Root-level rules with ignoreHidden/ignoreZeroSizeFolders/viewable set global flags
isRootLevelRule := rule.FolderPath == "/"
// Infer global flags from root-level rules
if isRootLevelRule {
if rule.IgnoreHidden {
resolved.IgnoreAllHidden = true
}
if rule.IgnoreSymlinks {
resolved.IgnoreAllSymlinks = true
}
if rule.IgnoreZeroSizeFolders {
resolved.IgnoreAllZeroSizeFolders = true
}
if rule.Viewable {
resolved.IndexingDisabled = true
}
}
// Build optimized lookup structures
if rule.FileEndsWith != "" {
resolved.FileEndsWith = append(resolved.FileEndsWith, rule)
}
if rule.FolderEndsWith != "" {
resolved.FolderEndsWith = append(resolved.FolderEndsWith, rule)
}
if rule.FileStartsWith != "" {
resolved.FileStartsWith = append(resolved.FileStartsWith, rule)
}
if rule.FolderStartsWith != "" {
resolved.FolderStartsWith = append(resolved.FolderStartsWith, rule)
}
if rule.FilePath != "" {
resolved.FilePaths[rule.FilePath] = rule
}
if rule.FolderPath != "" {
resolved.FolderPaths[rule.FolderPath] = rule
}
if rule.NeverWatchPath != "" {
resolved.NeverWatchPaths[rule.NeverWatchPath] = struct{}{}
}
if rule.IncludeRootItem != "" {
resolved.IncludeRootItems[rule.IncludeRootItem] = struct{}{}
}
if rule.FileName != "" {
resolved.FileNames[rule.FileName] = rule
}
if rule.FolderName != "" {
resolved.FolderNames[rule.FolderName] = rule
}
}
config.Config.ResolvedRules = resolved
}
func modifyExcludeInclude(config *Source) {
// Helper to normalize a full path value (FilePaths, FolderPaths)
// These always start with "/" and match against full index paths
normalizeFullPath := func(value string, checkExists bool) string {
if value == "" {
return ""
}
normalized := "/" + strings.Trim(value, "/")
// check if file/folder exists
if checkExists {
realPath, err := filepath.Abs(config.Path + normalized)
if err != nil {
logger.Warningf("could not get absolute path for %v: %v", normalized, err)
return normalized
}
if _, err := os.Stat(realPath); os.IsNotExist(err) {
logger.Warningf("configured exclude/include path %v does not exist", realPath)
}
}
return normalized
}
normalizeName := func(value string) string {
return strings.Trim(value, "/")
}
// Normalize []ConditionalRule slices for full paths
allRules := config.Config.Rules
for i, rule := range allRules {
// normalize full paths
allRules[i].FilePath = normalizeFullPath(rule.FilePath, true)
// FolderPath gets trailing slash for proper prefix matching
if rule.FolderPath != "" {
normalized := normalizeFullPath(rule.FolderPath, true)
if normalized != "/" && !strings.HasSuffix(normalized, "/") {
normalized = normalized + "/"
}
allRules[i].FolderPath = normalized
}
allRules[i].NeverWatchPath = normalizeFullPath(rule.NeverWatchPath, true)
if rule.IncludeRootItem != "" {
normalized := normalizeFullPath(rule.IncludeRootItem, true)
if normalized != "/" && !strings.HasSuffix(normalized, "/") {
normalized = normalized + "/"
}
allRules[i].IncludeRootItem = normalized
}
// normalize names
allRules[i].FileName = normalizeName(rule.FileName)
allRules[i].FolderName = normalizeName(rule.FolderName)
}
config.Config.Rules = allRules
}