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