-
Notifications
You must be signed in to change notification settings - Fork 50
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
Add web UI for querying history from the browser #180
Merged
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
2aecffd
Add initail version of a web UI for querying history from the browser
ddworken 6903f63
Rename webui command
ddworken 301d11f
Add basic test for the web UI
ddworken 132c7bf
Add README for the web UI
ddworken c7862b1
Add basic auth for the web server
ddworken dba1e9a
Add status code when panic-ing
ddworken File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,3 +5,7 @@ postgres-data/ | |
server | ||
!backend/server | ||
.DS_Store | ||
node_modules/ | ||
package.json | ||
package-lock.json | ||
.prettierrc |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
package cmd | ||
|
||
import ( | ||
"os" | ||
|
||
"github.com/ddworken/hishtory/client/hctx" | ||
"github.com/ddworken/hishtory/client/lib" | ||
"github.com/ddworken/hishtory/client/webui" | ||
"github.com/spf13/cobra" | ||
) | ||
|
||
var webUiCmd = &cobra.Command{ | ||
Use: "start-web-ui", | ||
Short: "Serve a basic web UI for interacting with your shell history", | ||
Run: func(cmd *cobra.Command, args []string) { | ||
lib.CheckFatalError(webui.StartWebUiServer(hctx.MakeContext())) | ||
os.Exit(1) | ||
}, | ||
} | ||
|
||
func init() { | ||
rootCmd.AddCommand(webUiCmd) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
<div class="p-3 mb-2 bg-secondary text-white"> | ||
<div class="jumbotron jumbotron-fluid"> | ||
<div class="container"> | ||
<h1 class="display-4">hiSHtory</h1> | ||
<p class="lead">Your shell history in context, synced, and queryable</p> | ||
</div> | ||
</div> | ||
</div> | ||
|
||
<nav class="navbar navbar-light bg-light"> | ||
<form class="form-inline my-2 my-lg-0 w-100" style="display:flex"> | ||
<input | ||
type="search" | ||
name="q" | ||
id="search-input" | ||
autocomplete="off" | ||
placeholder="Search Query" | ||
value="{{ .SearchQuery }}" | ||
class="form-control mr-sm-2" | ||
hx-get="/htmx/results-table" | ||
hx-params="*" | ||
hx-trigger="input changed delay:500ms, search" | ||
hx-target="#search-results" | ||
/> | ||
<button | ||
id="search-button" | ||
class="btn btn-outline-success my-2 my-sm-0 btn-light" | ||
type="submit" | ||
> | ||
Search | ||
</button> | ||
</form> | ||
</nav> | ||
|
||
<hr /> | ||
|
||
{{ block "resultsTable.html" . }} | ||
<div id="search-results" class="table-responsive"> | ||
<table class="table"> | ||
<thead> | ||
<tr class="table-info"> | ||
{{ range .ColumnNames }} | ||
<th scope="col">{{ . }}</th> | ||
{{ end }} | ||
</tr> | ||
</thead> | ||
<tbody> | ||
{{ range .SearchResults }} | ||
<tr class="table-light"> | ||
{{ range . }} | ||
<td>{{ . }}</td> | ||
{{ end }} | ||
</tr> | ||
{{ end }} | ||
</tbody> | ||
</table> | ||
</div> | ||
{{ end }} | ||
|
||
|
||
<link | ||
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" | ||
rel="stylesheet" | ||
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" | ||
crossorigin="anonymous" | ||
/> | ||
<script | ||
src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" | ||
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" | ||
crossorigin="anonymous" | ||
></script> | ||
<script | ||
src="https://cdn.jsdelivr.net/npm/htmx.org@1.9.10/dist/htmx.min.js" | ||
integrity="sha256-s73PXHQYl6U2SLEgf/8EaaDWGQFCm6H26I+Y69hOZp4=" | ||
crossorigin="anonymous" | ||
></script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,147 @@ | ||
package webui | ||
|
||
import ( | ||
"context" | ||
"crypto/subtle" | ||
"embed" | ||
"fmt" | ||
"net" | ||
"net/http" | ||
"net/url" | ||
"os" | ||
|
||
"html/template" | ||
|
||
"github.com/ddworken/hishtory/client/data" | ||
"github.com/ddworken/hishtory/client/hctx" | ||
"github.com/ddworken/hishtory/client/lib" | ||
"github.com/google/uuid" | ||
) | ||
|
||
//go:embed templates | ||
var templateFiles embed.FS | ||
|
||
type webUiData struct { | ||
SearchQuery string | ||
SearchResults [][]string | ||
ColumnNames []string | ||
} | ||
|
||
func getTableRowsForDisplay(ctx context.Context, searchQuery string) ([][]string, error) { | ||
results, err := lib.Search(ctx, hctx.GetDb(ctx), searchQuery, 100) | ||
if err != nil { | ||
panic(err) | ||
} | ||
return buildTableRows(ctx, results) | ||
} | ||
|
||
func htmx_resultsTable(w http.ResponseWriter, r *http.Request) { | ||
searchQuery := r.URL.Query().Get("q") | ||
tableRows, err := getTableRowsForDisplay(r.Context(), searchQuery) | ||
if err != nil { | ||
panic(err) | ||
} | ||
w.Header().Add("Content-Type", "text/html") | ||
w.Header().Add("HX-Replace-Url", getNewUrl(r, searchQuery)) | ||
err = getTemplates().ExecuteTemplate(w, "resultsTable.html", webUiData{ | ||
SearchQuery: searchQuery, | ||
SearchResults: tableRows, | ||
ColumnNames: hctx.GetConf(r.Context()).DisplayedColumns, | ||
}) | ||
if err != nil { | ||
panic(err) | ||
} | ||
} | ||
|
||
func getNewUrl(r *http.Request, searchQuery string) string { | ||
urlStr := r.Header.Get("Hx-Current-Url") | ||
if urlStr == "" { | ||
// In this function we purposefully want to silence any errors since updating the URL is non-critical, so | ||
// we always return an empty string rather than handling the error. | ||
return "" | ||
} | ||
url, err := url.Parse(urlStr) | ||
if err != nil { | ||
return "" | ||
} | ||
q := url.Query() | ||
q.Set("q", searchQuery) | ||
url.RawQuery = q.Encode() | ||
return url.String() | ||
} | ||
|
||
func webuiHandler(w http.ResponseWriter, r *http.Request) { | ||
searchQuery := r.URL.Query().Get("q") | ||
tableRows, err := getTableRowsForDisplay(r.Context(), searchQuery) | ||
if err != nil { | ||
panic(err) | ||
} | ||
w.Header().Add("Content-Type", "text/html") | ||
err = getTemplates().ExecuteTemplate(w, "webui.html", webUiData{ | ||
SearchQuery: searchQuery, | ||
SearchResults: tableRows, | ||
ColumnNames: hctx.GetConf(r.Context()).DisplayedColumns, | ||
}) | ||
if err != nil { | ||
panic(err) | ||
} | ||
} | ||
|
||
func getTemplates() *template.Template { | ||
return template.Must(template.ParseFS(templateFiles, "templates/*")) | ||
|
||
} | ||
|
||
func buildTableRows(ctx context.Context, entries []*data.HistoryEntry) ([][]string, error) { | ||
columnNames := hctx.GetConf(ctx).DisplayedColumns | ||
ret := make([][]string, 0) | ||
for _, entry := range entries { | ||
row, err := lib.BuildTableRow(ctx, columnNames, *entry, func(s string) string { return s }) | ||
if err != nil { | ||
return nil, err | ||
} | ||
ret = append(ret, row) | ||
} | ||
return ret, nil | ||
} | ||
|
||
func withBasicAuth(expectedUsername, expectedPassword string) func(h http.Handler) http.Handler { | ||
return func(h http.Handler) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
username, password, hasCreds := r.BasicAuth() | ||
if !hasCreds || !secureStringEquals(username, expectedUsername) || !secureStringEquals(password, expectedPassword) { | ||
w.Header().Add("WWW-Authenticate", "Basic realm=\"User Visible Realm\"") | ||
w.WriteHeader(401) | ||
return | ||
} | ||
h.ServeHTTP(w, r) | ||
}) | ||
} | ||
} | ||
|
||
func secureStringEquals(s1, s2 string) bool { | ||
return subtle.ConstantTimeCompare([]byte(s1), []byte(s2)) == 1 | ||
} | ||
|
||
func StartWebUiServer(ctx context.Context) error { | ||
username := "hishtory" | ||
// Note that uuid.NewRandom() uses crypto/rand and returns a UUID with 122 bits of security | ||
password := uuid.Must(uuid.NewRandom()).String() | ||
if os.Getenv("HISHTORY_TEST") != "" { | ||
// For testing, we also support having the password be the secret key. This is still mostly secure, but | ||
// it has the risk of the secret key being exposed over HTTP. It also means that the password doesn't | ||
// rotate with each server instance. This is why we don't prefer this normally, but as a test-only method | ||
// this is still plenty secure. | ||
password = hctx.GetConf(ctx).UserSecret | ||
} | ||
http.Handle("/", withBasicAuth(username, password)(http.HandlerFunc(webuiHandler))) | ||
http.Handle("/htmx/results-table", withBasicAuth(username, password)(http.HandlerFunc(htmx_resultsTable))) | ||
|
||
server := http.Server{ | ||
BaseContext: func(l net.Listener) context.Context { return ctx }, | ||
Addr: ":8000", | ||
} | ||
fmt.Printf("Starting web server on %s...\n", server.Addr) | ||
fmt.Printf("Username: %s\nPassword: %s\n", username, password) | ||
return server.ListenAndServe() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check failure
Code scanning / CodeQL
Clear-text logging of sensitive information High