Skip to content

Commit

Permalink
Merge branch rewrite-config
Browse files Browse the repository at this point in the history
  • Loading branch information
vednoc committed Oct 13, 2024
2 parents da5c220 + 9b1b3ee commit b1d4537
Show file tree
Hide file tree
Showing 64 changed files with 421 additions and 270 deletions.
4 changes: 1 addition & 3 deletions cmd/userstyles-fonts/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ import (
"path/filepath"
"strings"
"time"

"userstyles.world/modules/config"
)

var (
Expand Down Expand Up @@ -58,7 +56,7 @@ func getAsset() (Asset, error) {
}

asset := release.Assets[0]
asset.Path = path.Join(config.DataDir, asset.Name)
asset.Path = path.Join("data", asset.Name)

return asset, nil
}
Expand Down
11 changes: 3 additions & 8 deletions cmd/userstyles-ts/main.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package main

import (
"log"
"os"

"github.com/evanw/esbuild/pkg/api"

"userstyles.world/modules/config"
"userstyles.world/modules/log"
)

var (
Expand All @@ -31,15 +29,12 @@ func main() {

// TODO: Remove this code?
if shouldWatch {
// Ensure we're seeing the error messages in stdout.
config.Production = false
log.Initialize()
watch = &api.WatchMode{
OnRebuild: func(result api.BuildResult) {
if len(result.Errors) > 0 {
log.Info.Printf("Watch build failed: %d errors\n", len(result.Errors))
log.Printf("Watch build failed: %d errors\n", len(result.Errors))
} else {
log.Info.Printf("Watch build succeeded: %d warnings\n", len(result.Warnings))
log.Printf("Watch build succeeded: %d warnings\n", len(result.Warnings))
}
},
}
Expand Down
38 changes: 32 additions & 6 deletions cmd/userstyles-world/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

import (
"flag"
"fmt"
"net/http"
"os"
"os/signal"
Expand Down Expand Up @@ -34,18 +36,38 @@ import (
)

func main() {
version := flag.Bool("version", false, "print build info")
custom := flag.String("config", "data/config.json", "path to custom config.json")
flag.Parse()

if *version {
fmt.Println("Go version:", config.GoVersion)
fmt.Println("Git commit:", config.GitCommit)
fmt.Println("Git signature:", config.GitSignature)
os.Exit(0)
}

err := config.Load(*custom)
if err != nil {
fmt.Printf("Failed to load config: %s\n", err)
os.Exit(1)
}

log.Initialize()
cache.Initialize()
cache.Init()
images.CheckVips()
util.InitCrypto()
jwtware.Init()
email.Init()
validator.Init()
database.Initialize()
cron.Initialize()
web.Init()

app := fiber.New(fiber.Config{
Views: templates.New(http.FS(web.ViewsDir)),
ViewsLayout: "layouts/main",
ProxyHeader: config.ProxyRealIP,
ProxyHeader: config.App.ProxyHeader,
JSONEncoder: util.JSONEncoder,
IdleTimeout: 5 * time.Second,

Expand All @@ -55,18 +77,22 @@ func main() {

email.SetRenderer(app)

if !config.Production {
if !config.App.Production {
app.Use(logger.New())
}

api.FastRoutes(app)

app.Use(func(c *fiber.Ctx) error {
c.Locals("App", &config.App)
return c.Next()
})
app.Use(core.HSTSMiddleware)
app.Use(core.CSPMiddleware)
app.Use(core.FlagsMiddleware)
app.Use(jwtware.New("user", jwtware.NormalJWTSigning))

if config.PerformanceMonitor {
if config.App.Profiling {
perf := app.Group("/debug")
perf.Use(jwtware.Admin)
perf.Use(pprof.New())
Expand All @@ -91,15 +117,15 @@ func main() {
}))

// TODO: Investigate how to "truly" inline sourcemaps in Sass.
if !config.Production {
if !config.App.Production {
app.Static("/scss", "web/scss")
}

// Fallback route.
app.Use(core.NotFound)

go func() {
if err := app.Listen(config.Port); err != nil {
if err := app.Listen(config.App.Addr); err != nil {
log.Warn.Fatal(err)
}
}()
Expand Down
4 changes: 2 additions & 2 deletions handlers/api/callback.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func CallbackGet(c *fiber.Ctx) error {
if redirectCode != "codeberg" && redirectCode != "gitlab" {
service = "github"
// Decode the string so we get our actual information back.
code, err := util.DecryptText(redirectCode, util.AEADOAuth, config.ScrambleConfig)
code, err := util.DecryptText(redirectCode, util.AEADOAuth, config.Secrets)
if err != nil {
log.Warn.Println("Failed to decode prepared text.")
return c.Next()
Expand Down Expand Up @@ -95,7 +95,7 @@ func CallbackGet(c *fiber.Ctx) error {
Value: t,
Path: "/",
Expires: expiration,
Secure: config.Production,
Secure: config.App.Production,
HTTPOnly: true,
SameSite: fiber.CookieSameSiteLaxMode,
})
Expand Down
2 changes: 1 addition & 1 deletion handlers/api/code.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func GetStyleCode(c *fiber.Ctx) error {

code := cache.Code.Get(i)
if code == nil {
code, err = os.ReadFile(filepath.Join(config.StyleDir, id))
code, err = os.ReadFile(filepath.Join(config.Storage.StyleDir, id))
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"message": "userstyle not found",
Expand Down
2 changes: 1 addition & 1 deletion handlers/core/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func getSystemStatus() {
systemMutex.Lock()
defer systemMutex.Unlock()

uptime := time.Since(config.AppUptime).Round(time.Second)
uptime := time.Since(config.App.Started).Round(time.Second)

system.Uptime = uptime.String()
system.GoRoutines = runtime.NumGoroutine()
Expand Down
8 changes: 4 additions & 4 deletions handlers/core/link.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ import (
func GetLinkedSite(c *fiber.Ctx) error {
switch c.Params("site") {
case "discord":
return c.Redirect(config.AppLinkChatDiscord, fiber.StatusSeeOther)
return c.Redirect(config.App.Discord, fiber.StatusSeeOther)
case "matrix":
return c.Redirect(config.AppLinkChatMatrix, fiber.StatusSeeOther)
return c.Redirect(config.App.Matrix, fiber.StatusSeeOther)
case "opencollective":
return c.Redirect(config.AppLinkOpenCollective, fiber.StatusSeeOther)
return c.Redirect(config.App.OpenCollective, fiber.StatusSeeOther)
case "source":
return c.Redirect(config.AppSourceCode, fiber.StatusSeeOther)
return c.Redirect(config.App.GitRepository, fiber.StatusSeeOther)
default:
u, _ := jwt.User(c)
return c.Render("err", fiber.Map{
Expand Down
4 changes: 1 addition & 3 deletions handlers/core/monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import (
"userstyles.world/modules/config"
)

var addr = []byte(config.ProxyMonitor)

func Monitor(c *fiber.Ctx) error {
u, ok := jwt.User(c)

Expand All @@ -30,7 +28,7 @@ func Monitor(c *fiber.Ctx) error {
}

// Proxy requests.
url := addr
url := []byte(config.App.MonitorURL)
url = append(url, c.Request().URI().Path()[8:]...)
url = append(url, 63)
url = append(url, c.Context().URI().QueryArgs().QueryString()...)
Expand Down
4 changes: 2 additions & 2 deletions handlers/core/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var client = http.Client{
}

// Make sure it doesn't redirect to a loopback thingy.
if config.Production && util.IsLoopback(string(req.Host)) {
if config.App.Production && util.IsLoopback(string(req.Host)) {
return errors.New("*giggles* Mikey Wikey hates you")
}
return nil
Expand All @@ -42,7 +42,7 @@ func Proxy(c *fiber.Ctx) error {
}

// Set resource location and name.
dir := path.Join(config.ProxyDir, path.Clean(t), path.Clean(id))
dir := path.Join(config.Storage.ProxyDir, path.Clean(t), path.Clean(id))
name := path.Join(dir, url.PathEscape(link))

// Check if image exists.
Expand Down
2 changes: 1 addition & 1 deletion handlers/jwt/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ var Protected = func(c *fiber.Ctx) error {

var Admin = func(c *fiber.Ctx) error {
// Bypass checks if monitor is enabled and request is a local IP address.
if config.PerformanceMonitor && util.IsLocal(config.Production, c.IP()) {
if config.App.Profiling && util.IsLocal(config.App.Production, c.IP()) {
return c.Next()
}

Expand Down
6 changes: 5 additions & 1 deletion handlers/jwt/jwtware.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,14 @@ import (
)

var (
JWTSigningKey = []byte(config.JWTSigningKey)
JWTSigningKey []byte
SigningMethod = "HS512"
)

func Init() {
JWTSigningKey = []byte(config.Secrets.SessionTokenKey)
}

func New(local string, keyFunction func(t *jwt.Token) (any, error)) fiber.Handler {
extractors := []func(c *fiber.Ctx) (string, bool){
jwtFromCookie(fiber.HeaderAuthorization),
Expand Down
2 changes: 1 addition & 1 deletion handlers/oauthProvider/access_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func TokenPost(c *fiber.Ctx) error {
return errorMessage(c, 400, "Incorrect client_secret specified")
}

unsealedText, err := util.DecryptText(tCode, util.AEADOAuthp, config.ScrambleConfig)
unsealedText, err := util.DecryptText(tCode, util.AEADOAuthp, config.Secrets)
if err != nil {
log.Warn.Println("Failed to unseal JWT text:", err.Error())
return errorMessage(c, 500, "Error: Please notify the UserStyles.world admins.")
Expand Down
6 changes: 3 additions & 3 deletions handlers/oauthProvider/authorize.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func redirectFunction(c *fiber.Ctx, state, redirectURI string) error {
return errorMessage(c, 500, "Error: Please notify the UserStyles.world admins.")
}

returnCode := "?code=" + util.EncryptText(jwtToken, util.AEADOAuthp, config.ScrambleConfig)
returnCode := "?code=" + util.EncryptText(jwtToken, util.AEADOAuthp, config.Secrets)
if state != "" {
returnCode += "&state=" + state
}
Expand Down Expand Up @@ -98,7 +98,7 @@ func AuthorizeGet(c *fiber.Ctx) error {
arguments := fiber.Map{
"User": u,
"OAuth": oauth,
"SecureToken": util.EncryptText(jwtToken, util.AEADOAuthp, config.ScrambleConfig),
"SecureToken": util.EncryptText(jwtToken, util.AEADOAuthp, config.Secrets),
}
for _, v := range oauth.Scopes {
arguments["Scope_"+v] = true
Expand All @@ -116,7 +116,7 @@ func AuthPost(c *fiber.Ctx) error {
return errorMessage(c, 400, "Incorrect oauthID specified")
}

unsealedText, err := util.DecryptText(secureToken, util.AEADOAuthp, config.ScrambleConfig)
unsealedText, err := util.DecryptText(secureToken, util.AEADOAuthp, config.Secrets)
if err != nil {
log.Warn.Println("Failed to unseal JWT text:", err.Error())
return errorMessage(c, 500, "Error: Please notify the UserStyles.world admins.")
Expand Down
8 changes: 4 additions & 4 deletions handlers/oauthProvider/authorize_style.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func OAuthStyleGet(c *fiber.Ctx) error {
log.Warn.Println("Failed to create a JWT Token:", err.Error())
return errorMessage(c, 500, "Couldn't make JWT Token, Error: Please notify the UserStyles.world admins.")
}
secureToken := util.EncryptText(jwtToken, util.AEADOAuthp, config.ScrambleConfig)
secureToken := util.EncryptText(jwtToken, util.AEADOAuthp, config.Secrets)

styles, err := storage.FindStyleCardsForUsername(u.Username)
if err != nil {
Expand Down Expand Up @@ -83,7 +83,7 @@ func OAuthStylePost(c *fiber.Ctx) error {
return errorMessage(c, 400, "Incorrect oauthID specified")
}

unsealedText, err := util.DecryptText(secureToken, util.AEADOAuthp, config.ScrambleConfig)
unsealedText, err := util.DecryptText(secureToken, util.AEADOAuthp, config.Secrets)
if err != nil {
log.Warn.Println("Failed to unseal JWT text:", err.Error())
return errorMessage(c, 500, "Error: Please notify the UserStyles.world admins.")
Expand Down Expand Up @@ -135,7 +135,7 @@ func OAuthStylePost(c *fiber.Ctx) error {
return errorMessage(c, 500, "Error: Please notify the UserStyles.world admins.")
}

returnCode := "?code=" + util.EncryptText(jwtToken, util.AEADOAuthp, config.ScrambleConfig)
returnCode := "?code=" + util.EncryptText(jwtToken, util.AEADOAuthp, config.Secrets)
returnCode += "&style_id=" + styleID
if state != "" {
returnCode += "&state=" + state
Expand All @@ -153,7 +153,7 @@ func OAuthStyleNewPost(c *fiber.Ctx) error {
return errorMessage(c, 400, "Incorrect oauthID specified")
}

unsealedText, err := util.DecryptText(secureToken, util.AEADOAuthp, config.ScrambleConfig)
unsealedText, err := util.DecryptText(secureToken, util.AEADOAuthp, config.Secrets)
if err != nil {
log.Warn.Println("Failed to unseal JWT text:", err.Error())
return errorMessage(c, 500, "Error: Please notify the UserStyles.world admins.")
Expand Down
2 changes: 1 addition & 1 deletion handlers/review/remove.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ func removeForm(c *fiber.Ctx) error {
args := fiber.Map{
"User": r.User,
"Log": l,
"Link": config.BaseURL + "/modlog#id-" + strconv.Itoa(int(l.ID)),
"Link": config.App.BaseURL + "/modlog#id-" + strconv.Itoa(int(l.ID)),
}

title := "Your review has been removed"
Expand Down
4 changes: 2 additions & 2 deletions handlers/style/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func handleAPIStyle(c *fiber.Ctx, secureToken, oauthID, styleID string, style *m
})
}

unsealedText, err := util.DecryptText(secureToken, util.AEADOAuthp, config.ScrambleConfig)
unsealedText, err := util.DecryptText(secureToken, util.AEADOAuthp, config.Secrets)
if err != nil {
log.Warn.Println("Failed to unseal JWT text:", err.Error())
return c.Status(500).
Expand Down Expand Up @@ -183,7 +183,7 @@ func handleAPIStyle(c *fiber.Ctx, secureToken, oauthID, styleID string, style *m
})
}

returnCode := "?code=" + util.EncryptText(jwtToken, util.AEADOAuthp, config.ScrambleConfig)
returnCode := "?code=" + util.EncryptText(jwtToken, util.AEADOAuthp, config.Secrets)
returnCode += "&style_id=" + styleID
if state != "" {
returnCode += "&state=" + state
Expand Down
2 changes: 1 addition & 1 deletion handlers/style/ban.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ func sendRemovalEmail(user *storage.User, style *models.Style, event *models.Log
"User": user,
"Style": style,
"Log": event,
"Link": config.BaseURL + "/modlog#id-" + strconv.Itoa(int(event.ID)),
"Link": config.App.BaseURL + "/modlog#id-" + strconv.Itoa(int(event.ID)),
}

title := "Your style has been removed"
Expand Down
2 changes: 1 addition & 1 deletion handlers/style/bulkban.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ func sendBulkRemovalEmail(user *storage.User, styles []*models.Style, event *mod
"User": user,
"Styles": styles,
"Log": event,
"Link": config.BaseURL + "/modlog#id-" + strconv.Itoa(int(event.ID)),
"Link": config.App.BaseURL + "/modlog#id-" + strconv.Itoa(int(event.ID)),
}

var title string
Expand Down
2 changes: 1 addition & 1 deletion handlers/style/category.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func GetCategory(c *fiber.Ctx) error {
}
c.Locals("Pagination", p)

cat, err := storage.GetStyleCategories(page, config.AppPageMaxItems)
cat, err := storage.GetStyleCategories(page, config.App.PageMaxItems)
if err != nil {
c.Locals("Title", "Failed to find categories")
return c.Render("err", fiber.Map{})
Expand Down
2 changes: 1 addition & 1 deletion handlers/style/explore.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func GetExplore(c *fiber.Ctx) error {
c.Locals("Pagination", p)

// Query for [sorted] styles.
s, err := storage.FindStyleCardsPaginated(p.Now, config.AppPageMaxItems, p.SortStyles())
s, err := storage.FindStyleCardsPaginated(p.Now, config.App.PageMaxItems, p.SortStyles())
if err != nil {
log.Database.Println("Failed to get styles:", err)
c.Locals("Title", "Styles not found")
Expand Down
Loading

0 comments on commit b1d4537

Please sign in to comment.