app/config.go

v1.5.2
skunky-art/app/config.go history · blame · raw

255 lines · 8094 bytes · executable

  1package app
  2
  3import (
  4	"encoding/json"
  5	"errors"
  6	"os"
  7	"regexp"
  8	"skunkyart/static"
  9	"strconv"
 10	"time"
 11
 12	"github.com/krazywarez/devianter"
 13)
 14
 15// Release carries the build's version and description, set at link time and
 16// shown by --help and the API.
 17var Release struct {
 18	Version     string
 19	Description string
 20}
 21
 22type cacheConfig struct {
 23	Enabled        bool   `json:"enabled"`
 24	MemCache       bool   `json:"memcache"`
 25	Path           string `json:"path"`
 26	MaxSize        int64  `json:"max-size"`
 27	Lifetime       string `json:"lifetime"`
 28	UpdateInterval int64  `json:"update-interval"`
 29}
 30
 31type apiCacheConfig struct {
 32	Enabled bool   `json:"enabled"`
 33	MaxSize int64  `json:"max-size"`
 34	TTL     string `json:"ttl"`
 35	Stale   string `json:"stale"`
 36}
 37
 38type rateLimitConfig struct {
 39	PerMinute int `json:"per-minute"`
 40	Burst     int `json:"burst"`
 41}
 42
 43type config struct {
 44	cfg           string
 45	Listen        string          `json:"listen"`
 46	URI           string          `json:"uri"`
 47	Cache         cacheConfig     `json:"cache"`
 48	APICache      apiCacheConfig  `json:"api-cache"`
 49	RateLimit     rateLimitConfig `json:"rate-limit"`
 50	Proxy         bool            `json:"proxy"`
 51	Nsfw          bool            `json:"nsfw"`
 52	HideAI        bool            `json:"hide-ai"`
 53	Theme         string          `json:"theme"`
 54	Language      string          `json:"language"`
 55	UserAgent     string          `json:"user-agent"`
 56	DownloadProxy string          `json:"download-proxy"`
 57	StaticPath    string          `json:"static-path"`
 58}
 59
 60// CFG is the running instance's configuration, holding the defaults below until
 61// ExecuteConfig overwrites them from the config file.
 62var CFG = config{
 63	cfg:      "config.json",
 64	Listen:   "127.0.0.1:3003",
 65	Theme:    "auto",
 66	Language: "auto",
 67	URI:      "/",
 68	Cache: cacheConfig{
 69		Enabled:        true,
 70		Path:           "cache",
 71		Lifetime:       "1w",
 72		MaxSize:        200,
 73		UpdateInterval: 1,
 74	},
 75	APICache: apiCacheConfig{
 76		Enabled: true,
 77		MaxSize: 64,
 78		TTL:     "5i",
 79		Stale:   "1h",
 80	},
 81	RateLimit: rateLimitConfig{
 82		PerMinute: 60,
 83		Burst:     20,
 84	},
 85	StaticPath: "static",
 86	UserAgent:  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
 87	Proxy:      true,
 88	Nsfw:       false,
 89}
 90
 91var lifetimeParsed int64
 92
 93// apiCacheTTL and apiCacheStale are api-cache.ttl and api-cache.stale parsed,
 94// set by ExecuteConfig.
 95var apiCacheTTL, apiCacheStale time.Duration
 96
 97// parseLifetime reads a duration in the config's unit syntax: a number
 98// followed by i (minutes), h (hours), d (days), w (weeks), m (30-day
 99// months) or y (360-day years).
100func parseLifetime(s string) (time.Duration, error) {
101	if s == "" {
102		return 0, errors.New("empty lifetime")
103	}
104	numstr := regexp.MustCompile("[0-9]+").FindAllString(s, -1)
105	if len(numstr) == 0 {
106		return 0, errors.New("lifetime has no number: " + s)
107	}
108	num, _ := strconv.Atoi(numstr[len(numstr)-1])
109
110	day := 24 * time.Hour
111	var unit time.Duration
112	switch s[len(s)-1:] {
113	case "i":
114		unit = time.Minute
115	case "h":
116		unit = time.Hour
117	case "d":
118		unit = day
119	case "w":
120		unit = 7 * day
121	case "m":
122		unit = 30 * day
123	case "y":
124		unit = 360 * day
125	default:
126		return 0, errors.New("invalid unit specified: " + s[len(s)-1:])
127	}
128	return unit * time.Duration(num), nil
129}
130
131// checkCacheWritable creates the cache directory if it is missing and confirms
132// this process can actually write into it, returning the error that a real cache
133// write would hit.
134//
135// An unwritable cache directory is otherwise a silent cliff: every media request
136// still succeeds by re-downloading from the CDN, so the only symptom is one
137// "permission denied" line per request and a cache that never fills.
138func checkCacheWritable(path string) error {
139	if err := os.MkdirAll(path, 0700); err != nil {
140		return err
141	}
142	probe := path + "/.skunkyart-write-probe"
143	if err := os.WriteFile(probe, nil, 0600); err != nil {
144		return err
145	}
146	return os.Remove(probe)
147}
148
149// cfgExplicit records that -c named the config file, so a missing one is an
150// error rather than a fall-back to the defaults.
151var cfgExplicit bool
152
153// ExecuteConfig loads the config file into CFG, validates it, and starts the
154// cache rotation loop if caching is on. A missing default config.json means
155// the built-in defaults; a missing file named with -c exits. It also exits on
156// a config that cannot be parsed, that asks for caching without proxying, or
157// that points caching at a directory this process cannot write.
158func ExecuteConfig() {
159	f, err := os.ReadFile(CFG.cfg)
160	switch {
161	case err == nil:
162		tryWithExitStatus(json.Unmarshal(f, &CFG), 1)
163	case os.IsNotExist(err) && !cfgExplicit:
164		// The default file is optional: the built-in defaults are a working
165		// instance. A path given with -c is not, since a typo there would
166		// otherwise start something the operator did not configure.
167		println("no", CFG.cfg, "found; running with the built-in defaults")
168	default:
169		tryWithExitStatus(err, 1)
170	}
171
172	if CFG.Cache.Enabled && !CFG.Proxy {
173		exit("Incompatible settings detected: cannot use caching media content without proxy", 1)
174	}
175
176	if CFG.Cache.Enabled {
177		if err := checkCacheWritable(CFG.Cache.Path); err != nil {
178			exit("Cache directory is not writable by this process (uid "+
179				strconv.Itoa(os.Getuid())+"): "+err.Error()+
180				"\nGrant that uid write access to the directory, or set cache.enabled to false."+
181				"\nThe official container image runs as uid 10000, so a bind-mounted cache needs:"+
182				"\n  chown -R 10000:10000 <cache dir on the host>", 1)
183		}
184
185		if CFG.Cache.Lifetime != "" {
186			d, err := parseLifetime(CFG.Cache.Lifetime)
187			if err != nil {
188				exit("config: cache.lifetime: "+err.Error(), 1)
189			}
190			lifetimeParsed = d.Milliseconds()
191		}
192		// max-size is documented in megabytes. This was 1024^2, which in Go is
193		// XOR (1026), not exponentiation — so the cap was ~1000x too small.
194		CFG.Cache.MaxSize *= 1024 * 1024
195		go InitCacheSystem()
196		if CFG.Cache.MemCache {
197			go InitMemCacheJanitor()
198		}
199	}
200
201	About = instanceAbout{
202		Proxy:  CFG.Proxy,
203		Nsfw:   CFG.Nsfw,
204		HideAI: CFG.HideAI,
205		Theme:  CFG.Theme,
206	}
207
208	// A theme the stylesheet cannot honour would silently fall back to auto,
209	// so say so instead.
210	switch CFG.Theme {
211	case "auto", "dark", "light":
212	default:
213		exit("config: theme must be one of auto, dark, light; got "+CFG.Theme, 1)
214	}
215
216	if CFG.APICache.Enabled {
217		d, err := parseLifetime(CFG.APICache.TTL)
218		if err != nil {
219			exit("config: api-cache.ttl: "+err.Error(), 1)
220		}
221		apiCacheTTL = d
222		if CFG.APICache.Stale != "" {
223			d, err := parseLifetime(CFG.APICache.Stale)
224			if err != nil {
225				exit("config: api-cache.stale: "+err.Error(), 1)
226			}
227			apiCacheStale = d
228		}
229	}
230
231	// per-minute 0 turns the limit off; a burst below one token would
232	// refuse every request, so it is floored to one.
233	if CFG.RateLimit.PerMinute > 0 {
234		daLimiter = newRateLimiter(CFG.RateLimit.PerMinute, max(CFG.RateLimit.Burst, 1))
235	}
236
237	static.StaticPath = CFG.StaticPath
238	devianter.UserAgent = CFG.UserAgent
239}
240
241// forcedThemeCSS returns a block that pins the palette when the instance has
242// chosen a theme, or "" for "auto". Light repeats what the prefers-color-scheme
243// block already holds; dark repeats :root. Both are emitted after the
244// stylesheet so they win on order rather than on !important.
245func forcedThemeCSS() string {
246	switch CFG.Theme {
247	case "light":
248		return `
249:root{--bg:#f4f1ee;--fg:#1f2421;--fg-strong:#0d100e;--link:#1c6b78;--link-hover:#5a6b00;--edge:#8fbcae;--edge-strong:#258268;--accent:#4d27d6;--surface:#d9e8e1;--surface-sunken:#e8f0ec;--surface-alt:#e2e4f2;--surface-deep:#dbe7ef;--status-bad:#a11;--status-good:#157a3a;--status-mild:#2e8b57;--status-note:#8a007f}`
250	case "dark":
251		return `
252:root{--bg:black;--fg:rgb(234,216,216);--fg-strong:whitesmoke;--link:cadetblue;--link-hover:#d0ff00;--edge:#164e3e;--edge-strong:#258268;--accent:#4d27d6;--surface:#134134;--surface-sunken:#091f19;--surface-alt:#060820;--surface-deep:#011522;--status-bad:red;--status-good:green;--status-mild:seagreen;--status-note:rgb(160,0,147)}`
253	}
254	return ""
255}