Skip to content

feat: enhance asset path handling to include config directory and improve assets directory validation #604

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 14 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/assets
/config
/build
/playground
/.idea
Expand Down
11 changes: 10 additions & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
- [Environment variables](#environment-variables)
- [Other ways of providing tokens/passwords/secrets](#other-ways-of-providing-tokenspasswordssecrets)
- [Including other config files](#including-other-config-files)
- [Config schema](#config-schema)
- [Server](#server)
- [Document](#document)
- [Branding](#branding)
Expand Down Expand Up @@ -182,6 +183,10 @@ docker run --rm -v ./glance.yml:/app/config/glance.yml glanceapp/glance config:p

This assumes that the config you want to print is in your current working directory and is named `glance.yml`.

## Config schema

For property descriptions, validation and autocompletion of the config within your IDE, @not-first has kindly created a [schema](https://github.com/not-first/glance-schema). Massive thanks to them for this, go check it out and give them a star!

## Server
Server configuration is done through a top level `server` property. Example:

Expand Down Expand Up @@ -997,6 +1002,7 @@ Preview:
| search-engine | string | no | duckduckgo |
| new-tab | boolean | no | false |
| autofocus | boolean | no | false |
| target | string | no | _blank |
| placeholder | string | no | Type here to search… |
| bangs | array | no | |

Expand All @@ -1018,6 +1024,9 @@ When set to `true`, swaps the shortcuts for showing results in the same or new t
##### `autofocus`
When set to `true`, automatically focuses the search input on page load.

##### `target`
The target to use when opening the search results in a new tab. Possible values are `_blank`, `_self`, `_parent` and `_top`.

##### `placeholder`
When set, modifies the text displayed in the input field before typing.

Expand Down Expand Up @@ -1623,7 +1632,7 @@ The title used to indicate the site.

`url`

The public facing URL of a monitored service, the user will be redirected here. If `check-url` is not specified, this is used as the status check.
The URL of the monitored service, which must be reachable by Glance, and will be used as the link to go to when clicking on the title. If `check-url` is not specified, this is used as the status check.

`check-url`

Expand Down
1 change: 1 addition & 0 deletions docs/custom-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,7 @@ The following helper functions provided by Glance are available:
- `offsetNow(offset string) time.Time`: Returns the current time with an offset. The offset can be positive or negative and must be in the format "3h" "-1h" or "2h30m10s".
- `duration(str string) time.Duration`: Parses a string such as `1h`, `24h`, `5h30m`, etc into a `time.Duration`.
- `parseTime(layout string, s string) time.Time`: Parses a string into time.Time. The layout must be provided in Go's [date format](https://pkg.go.dev/time#pkg-constants). You can alternatively use these values instead of the literal format: "unix", "RFC3339", "RFC3339Nano", "DateTime", "DateOnly".
- `parseLocalTime(layout string, s string) time.Time`: Same as the above, except in the absence of a timezone, it will use the local timezone instead of UTC.
- `parseRelativeTime(layout string, s string) time.Time`: A shorthand for `{{ .String "date" | parseTime "rfc3339" | toRelativeTime }}`.
- `add(a, b float) float`: Adds two numbers.
- `sub(a, b float) float`: Subtracts two numbers.
Expand Down
2 changes: 1 addition & 1 deletion internal/glance/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ func cliMountpointInfo(requestedPath string) int {

fmt.Println("Path:", usage.Path)
fmt.Println("FS type:", ternary(usage.Fstype == "", "unknown", usage.Fstype))
fmt.Printf("Used percent: %.1f%%", usage.UsedPercent)
fmt.Printf("Used percent: %.1f%%\n", usage.UsedPercent)

return 0
}
28 changes: 26 additions & 2 deletions internal/glance/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -430,8 +430,32 @@ func isConfigStateValid(config *config) error {
}

if config.Server.AssetsPath != "" {
if _, err := os.Stat(config.Server.AssetsPath); os.IsNotExist(err) {
return fmt.Errorf("assets directory does not exist: %s", config.Server.AssetsPath)
if _, err := os.Stat(config.Server.AssetsPath); err == nil {
return nil
}

workingDir, err := os.Getwd()
if err != nil {
return fmt.Errorf("directory does not exist: %v", err)
}

// Try these paths in order:
possiblePaths := []string{
config.Server.AssetsPath, // Original path
filepath.Join(workingDir, "config"), // Local config directory
filepath.Join(workingDir, config.Server.AssetsPath), // Relative to working dir
"/app/config", // Docker path
}

for _, path := range possiblePaths {
if _, err := os.Stat(path); err == nil {
config.Server.AssetsPath = path
return nil
}
}

if !strings.HasPrefix(config.Server.AssetsPath, "/app/") {
return fmt.Errorf("assets directory not found in any of the expected locations. Tried: %v", possiblePaths)
}
}

Expand Down
3 changes: 2 additions & 1 deletion internal/glance/glance.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func (p *page) updateOutdatedWidgets() {
}

func (a *application) transformUserDefinedAssetPath(path string) string {
if strings.HasPrefix(path, "/assets/") {
if strings.HasPrefix(path, "/assets/") || strings.HasPrefix(path, "/config/") {
return a.Config.Server.BaseURL + path
}

Expand Down Expand Up @@ -262,6 +262,7 @@ func (a *application) server() (func() error, func() error) {
absAssetsPath, _ = filepath.Abs(a.Config.Server.AssetsPath)
assetsFS := fileServerWithCache(http.Dir(a.Config.Server.AssetsPath), 2*time.Hour)
mux.Handle("/assets/{path...}", http.StripPrefix("/assets/", assetsFS))
mux.Handle("/config/{path...}", http.StripPrefix("/config/", assetsFS))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a gigantic security hole because not everyone will use environment variables for their passwords/API keys, and you're exposing their configs.

}

server := http.Server{
Expand Down
3 changes: 2 additions & 1 deletion internal/glance/static/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ function setupSearchBoxes() {
for (let i = 0; i < searchWidgets.length; i++) {
const widget = searchWidgets[i];
const defaultSearchUrl = widget.dataset.defaultSearchUrl;
const target = widget.dataset.target || "_blank";
const newTab = widget.dataset.newTab === "true";
const inputElement = widget.getElementsByClassName("search-input")[0];
const bangElement = widget.getElementsByClassName("search-bang")[0];
Expand Down Expand Up @@ -143,7 +144,7 @@ function setupSearchBoxes() {
const url = searchUrlTemplate.replace("!QUERY!", encodeURIComponent(query));

if (newTab && !event.ctrlKey || !newTab && event.ctrlKey) {
window.open(url, '_blank').focus();
window.open(url, target).focus();
} else {
window.location.href = url;
}
Expand Down
2 changes: 1 addition & 1 deletion internal/glance/templates/search.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
{{ define "widget-content-classes" }}widget-content-frameless{{ end }}

{{ define "widget-content" }}
<div class="search widget-content-frame padding-inline-widget flex gap-15 items-center" data-default-search-url="{{ .SearchEngine }}" data-new-tab="{{ .NewTab }}">
<div class="search widget-content-frame padding-inline-widget flex gap-15 items-center" data-default-search-url="{{ .SearchEngine }}" data-new-tab="{{ .NewTab }}" data-target="{{ .Target }}">
<div class="search-bangs">
{{ range .Bangs }}
<input type="hidden" data-shortcut="{{ .Shortcut }}" data-title="{{ .Title }}" data-url="{{ .URL }}">
Expand Down
17 changes: 11 additions & 6 deletions internal/glance/widget-custom-api.go
Original file line number Diff line number Diff line change
Expand Up @@ -454,11 +454,16 @@ var customAPITemplateFuncs = func() template.FuncMap {

return d
},
"parseTime": customAPIFuncParseTime,
"parseTime": func(layout, value string) time.Time {
return customAPIFuncParseTimeInLocation(layout, value, time.UTC)
},
"parseLocalTime": func(layout, value string) time.Time {
return customAPIFuncParseTimeInLocation(layout, value, time.Local)
},
"toRelativeTime": dynamicRelativeTimeAttrs,
"parseRelativeTime": func(layout, value string) template.HTMLAttr {
// Shorthand to do both of the above with a single function call
return dynamicRelativeTimeAttrs(customAPIFuncParseTime(layout, value))
return dynamicRelativeTimeAttrs(customAPIFuncParseTimeInLocation(layout, value, time.UTC))
},
// The reason we flip the parameter order is so that you can chain multiple calls together like this:
// {{ .JSON.String "foo" | trimPrefix "bar" | doSomethingElse }}
Expand Down Expand Up @@ -532,8 +537,8 @@ var customAPITemplateFuncs = func() template.FuncMap {
},
"sortByTime": func(key, layout, order string, results []decoratedGJSONResult) []decoratedGJSONResult {
sort.Slice(results, func(a, b int) bool {
timeA := customAPIFuncParseTime(layout, results[a].String(key))
timeB := customAPIFuncParseTime(layout, results[b].String(key))
timeA := customAPIFuncParseTimeInLocation(layout, results[a].String(key), time.UTC)
timeB := customAPIFuncParseTimeInLocation(layout, results[b].String(key), time.UTC)

if order == "asc" {
return timeA.Before(timeB)
Expand Down Expand Up @@ -570,7 +575,7 @@ var customAPITemplateFuncs = func() template.FuncMap {
return funcs
}()

func customAPIFuncParseTime(layout, value string) time.Time {
func customAPIFuncParseTimeInLocation(layout, value string, loc *time.Location) time.Time {
switch strings.ToLower(layout) {
case "unix":
asInt, err := strconv.ParseInt(value, 10, 64)
Expand All @@ -589,7 +594,7 @@ func customAPIFuncParseTime(layout, value string) time.Time {
layout = time.DateOnly
}

parsed, err := time.Parse(layout, value)
parsed, err := time.ParseInLocation(layout, value, loc)
if err != nil {
return time.Unix(0, 0)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/glance/widget-reddit.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ func fetchSubredditPosts(
var client requestDoer = defaultHTTPClient

if requestUrlTemplate != "" {
requestUrl = strings.ReplaceAll(requestUrlTemplate, "{REQUEST-URL}", requestUrl)
requestUrl = strings.ReplaceAll(requestUrlTemplate, "{REQUEST-URL}", url.QueryEscape(requestUrl))
} else if proxyClient != nil {
client = proxyClient
}
Expand Down
1 change: 1 addition & 0 deletions internal/glance/widget-search.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ type searchWidget struct {
SearchEngine string `yaml:"search-engine"`
Bangs []SearchBang `yaml:"bangs"`
NewTab bool `yaml:"new-tab"`
Target string `yaml:"target"`
Autofocus bool `yaml:"autofocus"`
Placeholder string `yaml:"placeholder"`
}
Expand Down
4 changes: 2 additions & 2 deletions internal/glance/widget-utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,8 @@ func workerPoolDo[I any, O any](job *workerPoolJob[I, O]) ([]O, []error, error)
}

if len(job.data) == 1 {
output, err := job.task(job.data[0])
return append(results, output), append(errs, err), nil
results[0], errs[0] = job.task(job.data[0])
return results, errs, nil
}

tasksQueue := make(chan *workerPoolTask[I, O])
Expand Down