diff --git a/backend/internal/api/handler/health.go b/backend/internal/api/handler/health.go
index 1ff94fd34..c940df3d3 100644
--- a/backend/internal/api/handler/health.go
+++ b/backend/internal/api/handler/health.go
@@ -6,15 +6,16 @@ import (
"npm/internal/acme"
h "npm/internal/api/http"
"npm/internal/config"
+ "npm/internal/remoteversion"
)
type healthCheckResponse struct {
- Version string `json:"version"`
- Commit string `json:"commit"`
- AcmeShVersion string `json:"acme.sh"`
- Healthy bool `json:"healthy"`
- IsDBSetup bool `json:"db_setup"`
- IsSetup bool `json:"setup"`
+ Version config.VersionSplit `json:"version"`
+ Commit string `json:"commit"`
+ AcmeShVersion string `json:"acme.sh"`
+ Healthy bool `json:"healthy"`
+ IsDBSetup bool `json:"db_setup"`
+ IsSetup bool `json:"setup"`
}
// Health returns the health of the api
@@ -22,7 +23,7 @@ type healthCheckResponse struct {
func Health() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
health := healthCheckResponse{
- Version: config.Version,
+ Version: config.GetVersionSplit(),
Commit: config.Commit,
Healthy: true,
IsDBSetup: config.IsDBSetup,
@@ -33,3 +34,27 @@ func Health() func(http.ResponseWriter, *http.Request) {
h.ResultResponseJSON(w, r, http.StatusOK, health)
}
}
+
+type versionCheckResponse struct {
+ Current *string `json:"current"`
+ Latest *string `json:"latest"`
+ UpdateAvailable bool `json:"update_available"`
+}
+
+// VersionCheck will check github for new releases and return the latest version
+// Route: GET /version/check
+func VersionCheck() func(http.ResponseWriter, *http.Request) {
+ return func(w http.ResponseWriter, r *http.Request) {
+ // Always respond 200, even when the check fails, to avoid triggering
+ // repeated update checks. Failed checks have null versions.
+ var resp versionCheckResponse
+ if res := remoteversion.Check(); res.Current != "" {
+ resp = versionCheckResponse{
+ Current: &res.Current,
+ Latest: &res.Latest,
+ UpdateAvailable: res.UpdateAvailable,
+ }
+ }
+ h.ResultResponseJSON(w, r, http.StatusOK, resp)
+ }
+}
diff --git a/backend/internal/api/router.go b/backend/internal/api/router.go
index 00959d20b..3c2b62aab 100644
--- a/backend/internal/api/router.go
+++ b/backend/internal/api/router.go
@@ -138,6 +138,10 @@ func applyRoutes(r chi.Router) chi.Router {
Post("/sse", handler.NewSSEToken())
})
+ // Version Check
+ r.With(middleware.EnforceSetup(), middleware.Enforce()).
+ Get("/version/check", handler.VersionCheck())
+
// Users
r.Route("/users", func(r chi.Router) {
// Create - can be done in Setup stage as well
diff --git a/backend/internal/config/vars.go b/backend/internal/config/vars.go
index c989d53e7..c3f816c51 100644
--- a/backend/internal/config/vars.go
+++ b/backend/internal/config/vars.go
@@ -2,6 +2,8 @@ package config
import (
"fmt"
+ "strconv"
+ "strings"
"npm/internal/logger"
)
@@ -46,3 +48,28 @@ type acmesh struct {
func (a *acmesh) GetWellknown() string {
return fmt.Sprintf("%s/.well-known", a.Home)
}
+
+// VersionSplit is a struct that holds the major, minor, and patch versions
+type VersionSplit struct {
+ Major uint `json:"major"`
+ Minor uint `json:"minor"`
+ Patch uint `json:"patch"`
+}
+
+// GetVersionSplit returns the major, minor, and patch versions
+func GetVersionSplit() VersionSplit {
+ bits := strings.Split(Version, ".")
+ if len(bits) != 3 {
+ return VersionSplit{Major: 0, Minor: 0, Patch: 0}
+ }
+ return VersionSplit{Major: parseUintOrZero(bits[0]), Minor: parseUintOrZero(bits[1]), Patch: parseUintOrZero(bits[2])}
+}
+
+// parseUintOrZero parses a string to a uint, returning zero on error
+func parseUintOrZero(s string) uint {
+ u, err := strconv.ParseUint(s, 10, 0)
+ if err != nil {
+ return 0
+ }
+ return uint(u)
+}
diff --git a/backend/internal/remoteversion/remoteversion.go b/backend/internal/remoteversion/remoteversion.go
new file mode 100644
index 000000000..b2d4f31b2
--- /dev/null
+++ b/backend/internal/remoteversion/remoteversion.go
@@ -0,0 +1,173 @@
+// Package remoteversion checks github for the latest release
+package remoteversion
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "npm/internal/config"
+ "npm/internal/logger"
+)
+
+const (
+ defaultURL = "https://api.github.com/repos/NginxProxyManager/nginx-proxy-manager/releases/latest"
+ successCacheTimeout = 15 * time.Minute
+ failureCacheTimeout = 1 * time.Minute
+)
+
+// Result is the outcome of a version check. Current and Latest are empty
+// when the check could not be completed.
+type Result struct {
+ Current string
+ Latest string
+ UpdateAvailable bool
+}
+
+// Checker fetches and caches the latest release version
+type Checker struct {
+ url string
+ client *http.Client
+
+ mu sync.Mutex
+ latest string
+ fetchedAt time.Time
+ lastErr error
+}
+
+// NewChecker creates a Checker that queries the given release url
+func NewChecker(url string) *Checker {
+ return &Checker{
+ url: url,
+ client: &http.Client{Timeout: 10 * time.Second},
+ }
+}
+
+var defaultChecker = NewChecker(defaultURL)
+
+// Check compares the running version against the latest github release
+func Check() Result {
+ return defaultChecker.Check()
+}
+
+// Check compares the running version against the latest release
+func (c *Checker) Check() Result {
+ current, ok := currentVersion()
+ if !ok {
+ return Result{}
+ }
+
+ latest, err := c.getLatest()
+ if err != nil {
+ return Result{}
+ }
+
+ return Result{
+ Current: current,
+ Latest: latest,
+ UpdateAvailable: IsNewer(current, latest),
+ }
+}
+
+// currentVersion returns the running version as vMAJOR.MINOR.PATCH
+func currentVersion() (string, bool) {
+ v := config.GetVersionSplit()
+ if v == (config.VersionSplit{}) {
+ return "", false
+ }
+ return fmt.Sprintf("v%d.%d.%d", v.Major, v.Minor, v.Patch), true
+}
+
+// getLatest returns the cached latest tag, refreshing it when stale. The lock
+// is held during the fetch so concurrent callers share a single request, and
+// failures are cached briefly so an outage doesn't cause a request per call.
+// On failure, a previously fetched tag is served if there is one.
+func (c *Checker) getLatest() (string, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ if !c.fetchedAt.IsZero() {
+ timeout := successCacheTimeout
+ if c.lastErr != nil {
+ timeout = failureCacheTimeout
+ }
+ if time.Since(c.fetchedAt) < timeout {
+ return c.result()
+ }
+ }
+
+ tag, err := c.fetch()
+ c.fetchedAt = time.Now()
+ c.lastErr = err
+ if err != nil {
+ logger.Warn("Remote version check failed: %v", err)
+ } else {
+ c.latest = tag
+ }
+ return c.result()
+}
+
+func (c *Checker) result() (string, error) {
+ if c.latest != "" {
+ return c.latest, nil
+ }
+ return "", c.lastErr
+}
+
+func (c *Checker) fetch() (string, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.url, nil)
+ if err != nil {
+ return "", err
+ }
+ req.Header.Set("User-Agent", "NginxProxyManager v"+config.Version)
+ req.Header.Set("Accept", "application/vnd.github+json")
+
+ resp, err := c.client.Do(req)
+ if err != nil {
+ return "", err
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode != http.StatusOK {
+ return "", fmt.Errorf("unexpected status from github: %d", resp.StatusCode)
+ }
+
+ var release struct {
+ TagName string `json:"tag_name"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
+ return "", err
+ }
+ if release.TagName == "" {
+ return "", errors.New("github response has no tag_name")
+ }
+ return release.TagName, nil
+}
+
+// IsNewer returns true if latest is a higher version than current
+func IsNewer(current, latest string) bool {
+ c := strings.Split(strings.TrimPrefix(current, "v"), ".")
+ l := strings.Split(strings.TrimPrefix(latest, "v"), ".")
+ for i := 0; i < len(c) || i < len(l); i++ {
+ var cv, lv uint64
+ if i < len(c) {
+ cv, _ = strconv.ParseUint(c[i], 10, 64)
+ }
+ if i < len(l) {
+ lv, _ = strconv.ParseUint(l[i], 10, 64)
+ }
+ if lv != cv {
+ return lv > cv
+ }
+ }
+ return false
+}
diff --git a/backend/internal/remoteversion/remoteversion_test.go b/backend/internal/remoteversion/remoteversion_test.go
new file mode 100644
index 000000000..5b5a6f3c8
--- /dev/null
+++ b/backend/internal/remoteversion/remoteversion_test.go
@@ -0,0 +1,77 @@
+package remoteversion
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+
+ "npm/internal/config"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestIsNewer(t *testing.T) {
+ tests := []struct {
+ current, latest string
+ want bool
+ }{
+ {"v2.12.0", "v2.12.1", true},
+ {"v2.12.1", "v2.12.1", false},
+ {"v2.12.1", "v2.12.0", false},
+ {"v2.9.0", "v2.10.0", true},
+ {"v2.12.0", "v3.0.0", true},
+ {"v3.0.0", "v2.99.99", false},
+ {"2.12.0", "v2.12.1", true},
+ {"v2.12", "v2.12.1", true},
+ {"v2.12.0", "v2.12", false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.current+"->"+tt.latest, func(t *testing.T) {
+ assert.Equal(t, tt.want, IsNewer(tt.current, tt.latest))
+ })
+ }
+}
+
+func TestCheck(t *testing.T) {
+ config.Version = "2.12.0"
+
+ var calls atomic.Int32
+ status := http.StatusOK
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ calls.Add(1)
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte(`{"tag_name":"v2.13.0"}`))
+ }))
+ defer srv.Close()
+
+ c := NewChecker(srv.URL)
+
+ r := c.Check()
+ assert.Equal(t, Result{Current: "v2.12.0", Latest: "v2.13.0", UpdateAvailable: true}, r)
+
+ // cached
+ c.Check()
+ assert.EqualValues(t, 1, calls.Load())
+}
+
+func TestCheckFailureIsCached(t *testing.T) {
+ config.Version = "2.12.0"
+
+ var calls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ calls.Add(1)
+ w.WriteHeader(http.StatusForbidden)
+ }))
+ defer srv.Close()
+
+ c := NewChecker(srv.URL)
+ assert.Equal(t, Result{}, c.Check())
+ assert.Equal(t, Result{}, c.Check())
+ assert.EqualValues(t, 1, calls.Load())
+}
+
+func TestCheckNoVersion(t *testing.T) {
+ config.Version = ""
+ assert.Equal(t, Result{}, NewChecker("http://127.0.0.1:1").Check())
+}
diff --git a/docker/dev/Dockerfile b/docker/dev/Dockerfile
index a59c636a1..50c74cd3e 100644
--- a/docker/dev/Dockerfile
+++ b/docker/dev/Dockerfile
@@ -25,7 +25,7 @@ ENV ACMESH_CONFIG_HOME=/data/.acme.sh/config \
RUN echo "fs.file-max = 65535" > /etc/sysctl.conf
# node, fail2ban
-RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
+RUN curl -fsSL https://deb.nodesource.com/setup_24.x | bash - \
&& apt-get update \
&& apt-get install -y --no-install-recommends nodejs vim dnsutils fail2ban logrotate \
&& npm install --location=global yarn \
diff --git a/frontend/.eslintrc.cjs b/frontend/.eslintrc.cjs
deleted file mode 100644
index c9092d625..000000000
--- a/frontend/.eslintrc.cjs
+++ /dev/null
@@ -1,113 +0,0 @@
-module.exports = {
- env: {
- browser: true,
- es2020: true,
- },
- extends: [
- "eslint:recommended",
- "plugin:@typescript-eslint/recommended",
- "plugin:react-hooks/recommended",
- "plugin:import/recommended",
- "plugin:import/typescript",
- "plugin:prettier/recommended",
- "plugin:react/recommended",
- "prettier",
- ],
- parser: "@typescript-eslint/parser",
- parserOptions: {
- ecmaVersion: "latest",
- sourceType: "module",
- },
- plugins: ["react-refresh"],
- settings: {
- "import/resolver": {
- // You will also need to install and configure the TypeScript resolver
- // See also https://github.com/import-js/eslint-import-resolver-typescript#configuration
- typescript: true,
- node: true,
- },
- },
- rules: {
- "import/default": 0,
- "import/no-named-as-default-member": 0,
- "import/no-named-as-default": 0,
- "react-refresh/only-export-components": 0,
- "react/react-in-jsx-scope": 0,
- "prettier/prettier": ["error"],
- "@typescript-eslint/ban-ts-comment": [
- "error",
- {
- "ts-ignore": "allow-with-description",
- },
- ],
- "@typescript-eslint/consistent-type-definitions": ["error", "interface"],
- "@typescript-eslint/explicit-function-return-type": ["off"],
- "@typescript-eslint/explicit-module-boundary-types": ["off"],
- "@typescript-eslint/explicit-member-accessibility": ["off"],
- "@typescript-eslint/no-empty-function": ["off"],
- "@typescript-eslint/no-explicit-any": ["off"],
- "@typescript-eslint/no-non-null-assertion": ["off"],
- "@typescript-eslint/naming-convention": [
- "error",
- {
- selector: "default",
- format: ["camelCase", "PascalCase", "UPPER_CASE"],
- leadingUnderscore: "allow",
- trailingUnderscore: "allow",
- filter: {
- regex: "^(2xl)$",
- match: false,
- },
- },
- ],
- "react-hooks/rules-of-hooks": ["error"],
- "react-hooks/exhaustive-deps": [
- "warn",
- {
- additionalHooks: "useAction|useReduxAction",
- },
- ],
- "react/jsx-curly-brace-presence": [
- "warn",
- {
- props: "never",
- children: "never",
- },
- ],
- "no-restricted-globals": ["off"],
- "import/extensions": 0, // We let webpack handle resolving file extensions
- "import/order": [
- "error",
- {
- alphabetize: {
- order: "asc",
- caseInsensitive: true,
- },
- "newlines-between": "always",
- pathGroups: [
- {
- pattern: "@(react)",
- group: "external",
- position: "before",
- },
- {
- pattern: "@/@(fixtures|jest)/**",
- group: "internal",
- position: "before",
- },
- {
- pattern: "@/**",
- group: "internal",
- },
- ],
- pathGroupsExcludedImportTypes: ["builtin", "internal"],
- groups: [
- "builtin",
- "external",
- "internal",
- ["parent", "sibling", "index"],
- ],
- },
- ],
- },
-};
diff --git a/frontend/.gitignore b/frontend/.gitignore
index aa97ba4ba..50c1dc047 100644
--- a/frontend/.gitignore
+++ b/frontend/.gitignore
@@ -1,4 +1,24 @@
-.eslintcache
-coverage
-junit.xml
-eslint.xml
+src/locale/lang
+
+# Logs
+/logs/
+*.log
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+pnpm-debug.log*
+lerna-debug.log*
+
+node_modules
+dist
+dist-ssr
+*.local
+
+# Editor directories and files
+.idea
+.DS_Store
+*.suo
+*.ntvs*
+*.njsproj
+*.sln
+*.sw?
diff --git a/frontend/.prettierrc b/frontend/.prettierrc
deleted file mode 100644
index 9e6bec4aa..000000000
--- a/frontend/.prettierrc
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "printWidth": 80,
- "tabWidth": 2,
- "useTabs": true,
- "semi": true,
- "singleQuote": false,
- "bracketSpacing": true,
- "bracketSameLine": true,
- "trailingComma": "all",
- "proseWrap": "always"
-}
diff --git a/frontend/README.md b/frontend/README.md
deleted file mode 100644
index c0b8c7ec0..000000000
--- a/frontend/README.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# NPM Frontend
-
-The frontend package is a React based UI, bootstrapped with
-[Create React App](https://github.com/facebook/create-react-app) and written in
-Typescript.
-
-## React Modules
-
-- [Chakra UI](https://chakra-ui.com/)
-- [Formik](https://formik.org/)
-- [React Query](https://react-query.tanstack.com/)
-- [React Table](https://react-table.tanstack.com/)
-- [React Router](https://reactrouter.com/)
-- [Format.js](https://formatjs.io/docs/getting-started/installation/)
-- [Rooks](https://react-hooks.org/)
-
-Some light reading that inspired the concepts used in the UI:
-
-- [Using react-query with react-table](https://nafeu.medium.com/using-react-query-with-react-table-884158535424)
-- [Server side pagination using react-table and react-query](https://dev.to/elangobharathi/server-side-pagination-using-react-table-v7-and-react-query-v3-3lck)
diff --git a/frontend/biome.json b/frontend/biome.json
new file mode 100644
index 000000000..226e0f701
--- /dev/null
+++ b/frontend/biome.json
@@ -0,0 +1,75 @@
+{
+ "$schema": "https://biomejs.dev/schemas/2.5.15/schema.json",
+ "vcs": {
+ "enabled": true,
+ "clientKind": "git",
+ "useIgnoreFile": true
+ },
+ "files": {
+ "ignoreUnknown": false,
+ "includes": ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "!**/dist/**/*"]
+ },
+ "formatter": {
+ "enabled": true,
+ "indentStyle": "tab",
+ "indentWidth": 4,
+ "lineWidth": 120,
+ "formatWithErrors": true
+ },
+ "assist": {
+ "actions": {
+ "source": {
+ "organizeImports": {
+ "level": "on",
+ "options": {
+ "groups": [
+ ":BUN:",
+ ":NODE:",
+ ["npm:*", "npm:*/**"],
+ ":PACKAGE_WITH_PROTOCOL:",
+ ":URL:",
+ ":PACKAGE:",
+ ["/src/*", "/src/**"],
+ ["/**"],
+ ["#*", "#*/**"],
+ ":PATH:"
+ ]
+ }
+ }
+ }
+ }
+ },
+ "linter": {
+ "enabled": true,
+ "rules": {
+ "preset": "recommended",
+ "correctness": {
+ "useUniqueElementIds": "off"
+ },
+ "suspicious": {
+ "noExplicitAny": "off",
+ "noArrayIndexKey": "off"
+ },
+ "performance": {
+ "noDelete": "off"
+ },
+ "nursery": "off",
+ "a11y": {
+ "useSemanticElements": "off",
+ "useValidAnchor": "off"
+ },
+ "style": {
+ "noParameterAssign": "error",
+ "useAsConstAssertion": "error",
+ "useDefaultParameterLast": "error",
+ "useEnumInitializers": "error",
+ "useSelfClosingElements": "error",
+ "useSingleVarDeclarator": "error",
+ "noUnusedTemplateLiteral": "error",
+ "useNumberNamespace": "error",
+ "noInferrableTypes": "error",
+ "noUselessElse": "error"
+ }
+ }
+ }
+}
diff --git a/frontend/check-locales.cjs b/frontend/check-locales.cjs
new file mode 100644
index 000000000..251b19c4b
--- /dev/null
+++ b/frontend/check-locales.cjs
@@ -0,0 +1,170 @@
+#!/usr/bin/env node
+
+// This file does a few things to ensure that the Locales are present and valid:
+// - Ensures that the name of the locale exists in the language list
+// - Ensures that each locale contains the translations used in the application
+// - Ensures that there are no unused translations in the locale files
+// - Also checks the error messages returned by the backend
+
+const allLocales = [
+ ["en", "en-US"],
+ ["de", "de-DE"],
+ ["pt", "pt-PT"],
+ ["es", "es-ES"],
+ ["et", "et-EE"],
+ ["fr", "fr-FR"],
+ ["ga", "ga-IE"],
+ ["it", "it-IT"],
+ ["ja", "ja-JP"],
+ ["nl", "nl-NL"],
+ ["pl", "pl-PL"],
+ ["ru", "ru-RU"],
+ ["sk", "sk-SK"],
+ ["cs", "cs-CZ"],
+ ["vi", "vi-VN"],
+ ["zh", "zh-CN"],
+ ["ko", "ko-KR"],
+ ["bg", "bg-BG"],
+ ["id", "id-ID"],
+ ["tr", "tr-TR"],
+ ["hu", "hu-HU"],
+ ["no", "no-NO"],
+ ["uk", "uk-UA"],
+ ["az", "az-AZ"],
+ ["fa", "fa-IR"],
+];
+
+const ignoreUnused = [/^.*$/];
+
+const { spawnSync } = require("child_process");
+const fs = require("fs");
+
+const tmp = require("tmp");
+
+// Parse backend errors
+const BACKEND_ERRORS_FILE = "../backend/internal/errors/errors.go";
+const BACKEND_ERRORS = [];
+/*
+try {
+ const backendErrorsContent = fs.readFileSync(BACKEND_ERRORS_FILE, "utf8");
+ const backendErrorsContentRes = [
+ ...backendErrorsContent.matchAll(/(?:errors|eris)\.New\("([^"]+)"\)/g),
+ ];
+ backendErrorsContentRes.map((item) => {
+ BACKEND_ERRORS.push("error." + item[1]);
+ return null;
+ });
+} catch (err) {
+ console.log("\x1b[31m%s\x1b[0m", err);
+ process.exit(1);
+}
+*/
+
+// get all translations used in frontend code
+const tmpobj = tmp.fileSync({ postfix: ".json" });
+spawnSync("yarn", ["locale-extract", "--out-file", tmpobj.name]);
+
+const allLocalesInProject = require(tmpobj.name);
+
+// get list og language names and locales
+const langList = require("./src/locale/src/lang-list.json");
+
+// store a list of all validation errors
+const allErrors = [];
+const allWarnings = [];
+const allKeys = [];
+
+const checkLangList = (fullCode) => {
+ const key = "locale-" + fullCode;
+ if (typeof langList[key] === "undefined") {
+ allErrors.push("ERROR: `" + key + "` language does not exist in lang-list.json");
+ }
+};
+
+const compareLocale = (locale) => {
+ const projectLocaleKeys = Object.keys(allLocalesInProject);
+ // Check that locale contains the items used in the codebase
+ projectLocaleKeys.map((key) => {
+ if (typeof locale.data[key] === "undefined") {
+ allErrors.push("ERROR: `" + locale[0] + "` does not contain item: `" + key + "`");
+ }
+ return null;
+ });
+ // Check that locale contains all error.* items
+ BACKEND_ERRORS.forEach((key) => {
+ if (typeof locale.data[key] === "undefined") {
+ allErrors.push("ERROR: `" + locale[0] + "` does not contain item: `" + key + "`");
+ }
+ return null;
+ });
+
+ // Check that locale does not contain items not used in the codebase
+ const localeKeys = Object.keys(locale.data);
+ localeKeys.map((key) => {
+ let ignored = false;
+ ignoreUnused.map((regex) => {
+ if (key.match(regex)) {
+ ignored = true;
+ }
+ return null;
+ });
+
+ if (!ignored && typeof allLocalesInProject[key] === "undefined") {
+ // ensure this key doesn't exist in the backend errors either
+ if (!BACKEND_ERRORS.includes(key)) {
+ allErrors.push("ERROR: `" + locale[0] + "` contains unused item: `" + key + "`");
+ }
+ }
+
+ // Add this key to allKeys
+ if (allKeys.indexOf(key) === -1) {
+ allKeys.push(key);
+ }
+ return null;
+ });
+};
+
+// Checks for any keys missing from this locale, that
+// have been defined in any other locales
+const checkForMissing = (locale) => {
+ allKeys.forEach((key) => {
+ if (typeof locale.data[key] === "undefined") {
+ allWarnings.push("WARN: `" + locale[0] + "` does not contain item: `" + key + "`");
+ }
+ return null;
+ });
+};
+
+// Local all locale data
+allLocales.map((locale, idx) => {
+ checkLangList(locale[1]);
+ allLocales[idx].data = require("./src/locale/src/" + locale[0] + ".json");
+ return null;
+});
+
+// Verify all locale data
+allLocales.map((locale) => {
+ compareLocale(locale);
+ checkForMissing(locale);
+ return null;
+});
+
+if (allErrors.length) {
+ allErrors.map((err) => {
+ console.log("\x1b[31m%s\x1b[0m", err);
+ return null;
+ });
+}
+if (allWarnings.length) {
+ allWarnings.map((err) => {
+ console.log("\x1b[33m%s\x1b[0m", err);
+ return null;
+ });
+}
+
+if (allErrors.length) {
+ process.exit(1);
+}
+
+console.log("\x1b[32m%s\x1b[0m", "Locale check passed");
+process.exit(0);
diff --git a/frontend/check-locales.js b/frontend/check-locales.js
deleted file mode 100755
index 1856b59b3..000000000
--- a/frontend/check-locales.js
+++ /dev/null
@@ -1,174 +0,0 @@
-#!/usr/bin/env node
-
-// This file does a few things to ensure that the Locales are present and valid:
-// - Ensures that the name of the locale exists in the language list
-// - Ensures that each locale contains the translations used in the application
-// - Ensures that there are no unused translations in the locale files
-// - Also checks the error messages returned by the backend
-
-const allLocales = [
- ["en", "en-US"],
- ["de", "de-DE"],
- ["fa", "fa-IR"],
-];
-
-const ignoreUnused = [
- /^acmesh\..*$/,
- /^acmesh-property\..*$/,
- /^capability\..*$/,
- /^status\..*$/,
- /^type\..*$/,
-];
-
-const ignoreMissing = [/^acmesh\..*$/];
-
-const { spawnSync } = require("child_process");
-const fs = require("fs");
-
-const tmp = require("tmp");
-
-// Parse backend errors
-const BACKEND_ERRORS_FILE = "../backend/internal/errors/errors.go";
-const BACKEND_ERRORS = [];
-try {
- const backendErrorsContent = fs.readFileSync(BACKEND_ERRORS_FILE, "utf8");
- const backendErrorsContentRes = [
- ...backendErrorsContent.matchAll(/(?:errors|eris)\.New\("([^"]+)"\)/g),
- ];
- backendErrorsContentRes.map((item) => {
- BACKEND_ERRORS.push("error." + item[1]);
- return null;
- });
-} catch (err) {
- console.log("\x1b[31m%s\x1b[0m", err);
- process.exit(1);
-}
-
-// get all translations used in frontend code
-const tmpobj = tmp.fileSync({ postfix: ".json" });
-spawnSync("yarn", ["locale-extract", "--out-file", tmpobj.name]);
-
-const allLocalesInProject = require(tmpobj.name);
-
-// get list og language names and locales
-const langList = require("./src/locale/src/lang-list.json");
-
-// store a list of all validation errors
-const allErrors = [];
-const allWarnings = [];
-const allKeys = [];
-
-const checkLangList = (fullCode) => {
- const key = "locale-" + fullCode;
- if (typeof langList[key] === "undefined") {
- allErrors.push(
- "ERROR: `" + key + "` language does not exist in lang-list.json",
- );
- }
-};
-
-const compareLocale = (locale) => {
- const projectLocaleKeys = Object.keys(allLocalesInProject);
- // Check that locale contains the items used in the codebase
- projectLocaleKeys.map((key) => {
- if (typeof locale.data[key] === "undefined") {
- allErrors.push(
- "ERROR: `" + locale[0] + "` does not contain item: `" + key + "`",
- );
- }
- return null;
- });
- // Check that locale contains all error.* items
- BACKEND_ERRORS.forEach((key) => {
- if (typeof locale.data[key] === "undefined") {
- allErrors.push(
- "ERROR: `" + locale[0] + "` does not contain item: `" + key + "`",
- );
- }
- return null;
- });
-
- // Check that locale does not contain items not used in the codebase
- const localeKeys = Object.keys(locale.data);
- localeKeys.map((key) => {
- let ignored = false;
- ignoreUnused.map((regex) => {
- if (key.match(regex)) {
- ignored = true;
- }
- return null;
- });
-
- if (!ignored && typeof allLocalesInProject[key] === "undefined") {
- // ensure this key doesn't exist in the backend errors either
- if (!BACKEND_ERRORS.includes(key)) {
- allErrors.push(
- "ERROR: `" + locale[0] + "` contains unused item: `" + key + "`",
- );
- }
- }
-
- // Add this key to allKeys
- if (allKeys.indexOf(key) === -1) {
- allKeys.push(key);
- }
- return null;
- });
-};
-
-// Checks for any keys missing from this locale, that
-// have been defined in any other locales
-const checkForMissing = (locale) => {
- allKeys.forEach((key) => {
- if (typeof locale.data[key] === "undefined") {
- let ignored = false;
- ignoreMissing.map((regex) => {
- if (key.match(regex)) {
- ignored = true;
- }
- return null;
- });
-
- if (!ignored) {
- allWarnings.push(
- "WARN: `" + locale[0] + "` does not contain item: `" + key + "`",
- );
- }
- }
- return null;
- });
-};
-
-// Local all locale data
-allLocales.map((locale, idx) => {
- checkLangList(locale[1]);
- allLocales[idx].data = require("./src/locale/src/" + locale[0] + ".json");
- return null;
-});
-
-// Verify all locale data
-allLocales.map((locale) => {
- compareLocale(locale);
- checkForMissing(locale);
- return null;
-});
-
-if (allErrors.length) {
- allErrors.map((err) => {
- console.log("\x1b[31m%s\x1b[0m", err);
- return null;
- });
-}
-if (allWarnings.length) {
- allWarnings.map((err) => {
- console.log("\x1b[33m%s\x1b[0m", err);
- return null;
- });
-}
-
-if (allErrors.length) {
- process.exit(1);
-}
-
-console.log("\x1b[32m%s\x1b[0m", "Locale check passed");
-process.exit(0);
diff --git a/frontend/globalSetup.js b/frontend/globalSetup.js
deleted file mode 100644
index 7ba927070..000000000
--- a/frontend/globalSetup.js
+++ /dev/null
@@ -1,4 +0,0 @@
-module.exports = async () => {
- process.env.TZ = "Australia/Queensland";
- process.env.IMAGE_INLINE_SIZE_LIMIT = "20000";
-};
diff --git a/frontend/index.html b/frontend/index.html
index d48785f19..08c760964 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -1,20 +1,11 @@
-
+
-
+
Nginx Proxy Manager
-
-
-
-
-
-
-
+
+
-
+
@@ -45,5 +36,10 @@
+
diff --git a/frontend/jest.eslint.js b/frontend/jest.eslint.js
deleted file mode 100644
index 04ee4f2ca..000000000
--- a/frontend/jest.eslint.js
+++ /dev/null
@@ -1,6 +0,0 @@
-module.exports = {
- displayName: "ESLint",
- runner: "jest-runner-eslint",
- testMatch: ["/src/**/*.(js|jsx|ts|tsx)"],
- watchPlugins: ["jest-runner-eslint/watch-fix"],
-};
diff --git a/frontend/package.json b/frontend/package.json
index dd6499103..d864a9a8d 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,78 +1,65 @@
{
- "name": "nginxproxymanager",
+ "name": "nginx-proxy-manager",
"version": "3.0.0",
- "private": true,
+ "type": "module",
+ "author": "Jamie Curnow ",
+ "license": "MIT",
"scripts": {
- "dev": "vite --host",
+ "dev": "vite",
"build": "tsc && vite build",
- "lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
- "lint:ci": "yarn lint --watchAll=false",
- "lint:fix": "eslint --fix --ext .ts --ext .tsx .",
+ "lint": "biome lint",
"preview": "vite preview",
- "prettier": "prettier \"**/*.+(js|json|yml|css|ts|tsx)\"",
- "format": "yarn prettier -- --write",
+ "prettier": "biome format --write ./src",
"locale-extract": "formatjs extract 'src/**/*.tsx'",
"locale-compile": "formatjs compile-folder src/locale/src src/locale/lang",
- "check-locales": "./check-locales.js"
+ "locale-sort": "./src/locale/scripts/locale-sort.sh",
+ "test": "vitest"
},
"dependencies": {
- "@chakra-ui/react": "^2.8.2",
- "@emotion/react": "^11.11.4",
- "@emotion/styled": "^11.11.5",
- "@tanstack/react-query": "^5.35.1",
- "@tanstack/react-query-devtools": "^5.35.1",
- "ajv": "^8.13.0",
- "chakra-react-select": "^4.7.6",
+ "@tabler/core": "^1.6.1",
+ "@tabler/icons-react": "^3.49.0",
+ "@tanstack/react-query": "^5.104.1",
+ "@tanstack/react-table": "^9.2.6",
+ "@uiw/react-textarea-code-editor": "^3.1.2",
"classnames": "^2.5.1",
- "country-flag-icons": "^1.5.11",
- "date-fns": "3.6.0",
- "formik": "^2.4.6",
- "framer-motion": "^11.1.9",
+ "date-fns": "^4.4.0",
+ "ez-modal-react": "^1.0.5",
+ "formik": "^2.4.9",
+ "generate-password-browser": "^1.1.0",
"humps": "^2.0.1",
- "lodash": "4.17.21",
- "moment": "2.30.1",
- "query-string": "9.0.0",
- "react": "^18.3.1",
- "react-async": "10.0.1",
- "react-dom": "18.3.1",
- "react-focus-lock": "^2.12.1",
- "react-icons": "^5.2.1",
- "react-intl": "^6.6.6",
- "react-markdown": "^9.0.1",
- "react-router-dom": "^6.23.0",
- "react-syntax-highlighter": "^15.5.0",
- "react-table": "7.8.0",
- "rooks": "7.14.1",
- "tmp": "^0.2.3"
+ "query-string": "^9.5.1",
+ "react": "^19.3.0",
+ "react-bootstrap": "^2.10.10",
+ "react-dom": "^19.3.0",
+ "react-intl": "^12.1.4",
+ "react-markdown": "^10.1.0",
+ "react-qr-code": "^2.2.0",
+ "react-router-dom": "^7.18.4",
+ "react-select": "^5.10.2",
+ "react-toastify": "^11.1.0",
+ "rooks": "^9.9.0"
},
"devDependencies": {
- "@formatjs/cli": "^6.2.10",
- "@types/country-flag-icons": "^1.2.2",
+ "@biomejs/biome": "^2.5.15",
+ "@formatjs/cli": "^6.16.33",
+ "@tanstack/react-query-devtools": "^5.104.1",
+ "@testing-library/dom": "^10.4.2",
+ "@testing-library/jest-dom": "^7.0.1",
+ "@testing-library/react": "^16.3.3",
"@types/humps": "^2.0.6",
- "@types/lodash": "4.17.1",
- "@types/node": "20.12.10",
- "@types/react": "18.3.1",
- "@types/react-dom": "18.3.0",
- "@types/react-router-dom": "5.3.3",
- "@types/react-syntax-highlighter": "^15.5.13",
+ "@types/node": "^26.6.4",
+ "@types/react": "^19.3.0",
+ "@types/react-dom": "^19.3.0",
"@types/react-table": "^7.7.20",
- "@types/styled-components": "5.1.34",
- "@typescript-eslint/eslint-plugin": "^6.1.0",
- "@typescript-eslint/parser": "^6.1.0",
- "@vitejs/plugin-react": "^4.2.1",
- "eslint": "^8.45.0",
- "eslint-config-prettier": "^8.8.0",
- "eslint-import-resolver-typescript": "^3.5.5",
- "eslint-plugin-import": "^2.27.5",
- "eslint-plugin-jsx-a11y": "^6.7.1",
- "eslint-plugin-prettier": "^5.0.0",
- "eslint-plugin-react": "^7.32.2",
- "eslint-plugin-react-hooks": "^4.6.0",
- "eslint-plugin-react-refresh": "^0.4.3",
- "prettier": "^3.2.5",
- "sass": "^1.77.0",
- "typescript": "^5.4.5",
- "vite": "^5.2.11",
- "vite-plugin-checker": "^0.6.4"
+ "@vitejs/plugin-react": "^6.1.2",
+ "happy-dom": "^20.14.5",
+ "postcss": "^8.5.29",
+ "postcss-simple-vars": "^7.0.1",
+ "sass": "^1.105.1",
+ "tmp": "^0.2.7",
+ "typescript": "7.0.2",
+ "vite": "^8.3.3",
+ "vite-plugin-checker": "^0.14.5",
+ "vitest": "^5.0.3"
}
}
diff --git a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-700.woff b/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-700.woff
deleted file mode 100644
index f2a7dd342..000000000
Binary files a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-700.woff and /dev/null differ
diff --git a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-700.woff2 b/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-700.woff2
deleted file mode 100644
index ce34a9fec..000000000
Binary files a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-700.woff2 and /dev/null differ
diff --git a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-700italic.woff b/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-700italic.woff
deleted file mode 100644
index 38faafb98..000000000
Binary files a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-700italic.woff and /dev/null differ
diff --git a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-700italic.woff2 b/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-700italic.woff2
deleted file mode 100644
index a63c72797..000000000
Binary files a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-700italic.woff2 and /dev/null differ
diff --git a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-italic.woff b/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-italic.woff
deleted file mode 100644
index 4e767cf5c..000000000
Binary files a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-italic.woff and /dev/null differ
diff --git a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-italic.woff2 b/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-italic.woff2
deleted file mode 100644
index d3e979ba6..000000000
Binary files a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-italic.woff2 and /dev/null differ
diff --git a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-regular.woff b/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-regular.woff
deleted file mode 100644
index 5b6e97be7..000000000
Binary files a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-regular.woff and /dev/null differ
diff --git a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-regular.woff2 b/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-regular.woff2
deleted file mode 100644
index 36bdc0e32..000000000
Binary files a/frontend/public/fonts/source-sans-pro/source-sans-pro-v14-latin-regular.woff2 and /dev/null differ
diff --git a/frontend/public/images/unhealthy.svg b/frontend/public/images/unhealthy.svg
new file mode 100644
index 000000000..6c39eeb12
--- /dev/null
+++ b/frontend/public/images/unhealthy.svg
@@ -0,0 +1,63 @@
+
diff --git a/frontend/src/App.css b/frontend/src/App.css
new file mode 100644
index 000000000..ad335caea
--- /dev/null
+++ b/frontend/src/App.css
@@ -0,0 +1,118 @@
+:root {
+ color-scheme: light dark;
+}
+
+.light {
+ color-scheme: light;
+}
+.dark {
+ color-scheme: dark;
+}
+
+.modal-backdrop {
+ --tblr-backdrop-opacity: 0.8 !important;
+}
+
+[data-bs-theme="dark"] .modal-content {
+ --tblr-modal-box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
+}
+
+[data-bs-theme="dark"] .modal-backdrop {
+ --tblr-backdrop-bg: #000 !important;
+ --tblr-backdrop-opacity: 0.65 !important;
+}
+
+.domain-name {
+ font-family: monospace;
+}
+
+.mr-1 {
+ margin-right: 0.25rem;
+}
+.ml-1 {
+ margin-left: 0.25rem;
+}
+
+.react-select-container {
+ .react-select__control {
+ color: var(--tblr-body-color);
+ background-color: var(--tblr-bg-forms);
+ border: var(--tblr-border-width) solid var(--tblr-border-color);
+
+ .react-select__input {
+ color: var(--tblr-body-color) !important;
+ }
+
+ .react-select__single-value {
+ color: var(--tblr-body-color);
+ }
+
+ .react-select__multi-value {
+ border: 1px solid var(--tblr-border-color);
+ background-color: var(--tblr-bg-surface-tertiary);
+ color: var(--tblr-secondary) !important;
+
+ .react-select__multi-value__label {
+ color: var(--tblr-secondary) !important;
+ }
+ }
+ }
+
+ .react-select__menu {
+ background-color: var(--tblr-bg-forms);
+
+ .react-select__option {
+ background: rgba(var(--tblr-primary-rgb), .04);
+ color: inherit !important;
+ &.react-select__option--is-focused {
+ background: rgba(var(--tblr-primary-rgb), .1);
+ }
+
+ &.react-select__option--is-focused.react-select__option--is-selected {
+ background: rgba(var(--tblr-primary-rgb), .2);
+ }
+ }
+ }
+}
+
+.textareaMono {
+ font-family: 'Courier New', Courier, monospace !important;
+ resize: vertical;
+}
+
+label.row {
+ cursor: pointer;
+}
+
+.input-group-select {
+ display: flex;
+ align-items: center;
+ padding: 0;
+ font-size: .875rem;
+ font-weight: 400;
+ line-height: 1.25rem;
+ color: var(--tblr-gray-500);
+ text-align: center;
+ white-space: nowrap;
+ background-color: var(--tblr-bg-surface-secondary);
+ border: var(--tblr-border-width) solid var(--tblr-border-color);
+ border-radius: var(--tblr-border-radius);
+
+ .form-select {
+ border: none;
+ background-color: var(--tblr-bg-surface-secondary);
+ border-radius: var(--tblr-border-radius) 0 0 var(--tblr-border-radius);
+ }
+}
+
+/* Fix for dropdown menus being clipped by table-responsive containers. */
+.table-responsive .dropdown {
+ position: static;
+}
+
+/* Fix for Tabler scrollbar compensation */
+@media (min-width: 992px) {
+ :host, :root {
+ margin-left: 0;
+ }
+}
\ No newline at end of file
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 5eed11969..dfd0c7fe4 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,13 +1,11 @@
-import { ChakraProvider } from "@chakra-ui/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
+import EasyModal from "ez-modal-react";
import { RawIntlProvider } from "react-intl";
-
-import { AuthProvider, LocaleProvider } from "src/context";
-import { intl } from "src/locale";
-
-import Router from "./Router";
-import lightTheme from "./theme/customTheme";
+import { ToastContainer } from "react-toastify";
+import { AuthProvider, LocaleProvider, ThemeProvider } from "src/context";
+import { getLocale, intl, isRTLLocale } from "src/locale";
+import Router from "src/Router.tsx";
// Create a client
const queryClient = new QueryClient();
@@ -16,14 +14,25 @@ function App() {
return (
-
-
+
+
-
+
+
+
+
-
-
-
+
+
+
);
diff --git a/frontend/src/Router.test.tsx b/frontend/src/Router.test.tsx
new file mode 100644
index 000000000..bd6114807
--- /dev/null
+++ b/frontend/src/Router.test.tsx
@@ -0,0 +1,79 @@
+import "@testing-library/jest-dom/vitest";
+import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import type { ReactNode } from "react";
+import Router from "src/Router";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const { authState } = vi.hoisted(() => ({ authState: { authenticated: true } }));
+
+vi.mock("src/context", () => ({ useAuthState: () => authState }));
+vi.mock("src/hooks", () => ({
+ useHealth: () => ({ data: { status: "OK", setup: true }, isLoading: false, isError: false }),
+}));
+vi.mock("src/components", () => ({
+ Page: ({ children }: { children: ReactNode }) => children,
+ SiteContainer: ({ children }: { children: ReactNode }) => children,
+ SiteHeader: () => null,
+ SiteMenu: () => null,
+ SiteFooter: () => null,
+ LoadingPage: () => Loading
,
+ Unhealthy: () => Unhealthy
,
+ ErrorNotFound: () => Not found
,
+}));
+vi.mock("src/pages/Dashboard", () => ({ default: () => Dashboard
}));
+vi.mock("src/pages/Login", () => ({ default: () => Login
}));
+vi.mock("src/pages/Nginx/ProxyHosts", () => ({ default: () => Proxy hosts
}));
+
+describe("Router", () => {
+ beforeEach(() => {
+ authState.authenticated = true;
+ window.history.replaceState(null, "", "/");
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ });
+
+ it.each(["/login", "/login/", "/login?next=/users#form"])(
+ "redirects an authenticated visit to %s to the dashboard",
+ async (path) => {
+ window.history.replaceState(null, "", path);
+ const replaceState = vi.spyOn(window.history, "replaceState");
+ render();
+
+ expect(await screen.findByRole("heading", { name: "Dashboard" })).toBeVisible();
+ expect(window.location.pathname).toBe("/");
+ expect(window.location.search).toBe("");
+ expect(window.location.hash).toBe("");
+ expect(replaceState).toHaveBeenCalledWith(expect.anything(), "", "/");
+ },
+ );
+
+ it("shows the login form when signed out and redirects after sign-in", async () => {
+ authState.authenticated = false;
+ window.history.replaceState(null, "", "/login");
+ const { rerender } = render();
+
+ expect(await screen.findByRole("heading", { name: "Login" })).toBeVisible();
+ expect(window.location.pathname).toBe("/login");
+
+ authState.authenticated = true;
+ rerender();
+
+ expect(await screen.findByRole("heading", { name: "Dashboard" })).toBeVisible();
+ await waitFor(() => expect(window.location.pathname).toBe("/"));
+ });
+
+ it.each([
+ ["/", "Dashboard"],
+ ["/nginx/proxy", "Proxy hosts"],
+ ["/unknown", "Not found"],
+ ])("preserves the existing route for %s", async (path, heading) => {
+ window.history.replaceState(null, "", path);
+ render();
+
+ expect(await screen.findByRole("heading", { name: heading })).toBeVisible();
+ expect(window.location.pathname).toBe(path);
+ });
+});
diff --git a/frontend/src/Router.tsx b/frontend/src/Router.tsx
index 5081a610e..85148cc9c 100644
--- a/frontend/src/Router.tsx
+++ b/frontend/src/Router.tsx
@@ -1,48 +1,39 @@
import { lazy, Suspense } from "react";
-
-import { BrowserRouter, Route, Routes } from "react-router-dom";
-
-import { TokenResponse } from "src/api/npm";
-import { SiteWrapper, SpinnerPage, Unhealthy } from "src/components";
-import { useAuthState, useLocaleState } from "src/context";
+import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
+import {
+ ErrorNotFound,
+ LoadingPage,
+ Page,
+ SiteContainer,
+ SiteFooter,
+ SiteHeader,
+ SiteMenu,
+ Unhealthy,
+} from "src/components";
+import { useAuthState } from "src/context";
import { useHealth } from "src/hooks";
-const AccessLists = lazy(() => import("src/pages/AccessLists"));
-const AuditLog = lazy(() => import("src/pages/AuditLog"));
-const Certificates = lazy(() => import("src/pages/Certificates"));
-const CertificateAuthorities = lazy(
- () => import("src/pages/CertificateAuthorities"),
-);
-const Dashboard = lazy(() => import("src/pages/Dashboard"));
-const DNSProviders = lazy(() => import("src/pages/DNSProviders"));
-const Hosts = lazy(() => import("src/pages/Hosts"));
-const NginxTemplates = lazy(() => import("src/pages/NginxTemplates"));
+const SetupUser = lazy(() => import("src/pages/Setup/SetupUser"));
+const SetupDatabase = lazy(() => import("src/pages/Setup/SetupDatabase"));
const Login = lazy(() => import("src/pages/Login"));
-const GeneralSettings = lazy(() => import("src/pages/Settings"));
-const Setup = lazy(() => import("src/pages/Setup"));
-const SetupDatabase = lazy(() => import("src/pages/SetupDatabase"));
-const Upstreams = lazy(() => import("src/pages/Upstreams"));
+const Dashboard = lazy(() => import("src/pages/Dashboard"));
+const Settings = lazy(() => import("src/pages/Settings"));
+const Certificates = lazy(() => import("src/pages/Certificates"));
+const Access = lazy(() => import("src/pages/Access"));
+const AuditLog = lazy(() => import("src/pages/AuditLog"));
+const Logs = lazy(() => import("src/pages/Logs"));
const Users = lazy(() => import("src/pages/Users"));
+const ProxyHosts = lazy(() => import("src/pages/Nginx/ProxyHosts"));
+const RedirectionHosts = lazy(() => import("src/pages/Nginx/RedirectionHosts"));
+const DeadHosts = lazy(() => import("src/pages/Nginx/DeadHosts"));
+const Streams = lazy(() => import("src/pages/Nginx/Streams"));
function Router() {
const health = useHealth();
- const { authenticated, handleTokenUpdate } = useAuthState();
- const { locale } = useLocaleState();
- const Spinner = ;
-
- // Load token from URL Query Params
- const searchParams = new URLSearchParams(document.location.search);
- const t = searchParams.get("token_response");
- if (t) {
- const tokenResponse: TokenResponse = JSON.parse(t);
- handleTokenUpdate(tokenResponse);
- window.location.href = "/";
- return;
- }
- // End Load token from URL Query Params
+ const { authenticated } = useAuthState();
if (health.isLoading) {
- return Spinner;
+ return ;
}
if (health.isError || !health.data?.healthy) {
@@ -51,23 +42,19 @@ function Router() {
if (health.data?.healthy && !health.data?.dbSetup) {
return (
-
+ }>
);
}
- if (health.data?.healthy && !health.data?.setup) {
- return (
-
-
-
- );
+ if (!health.data?.setup) {
+ return ;
}
if (!authenticated) {
return (
-
+ }>
);
@@ -75,29 +62,32 @@ function Router() {
return (
-
-
-
- } />
- } />
- } />
- }
- />
- } />
- } />
- } />
- } />
- }
- />
- } />
- } />
-
-
-
+
+
+
+
+
+
+ }>
+
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+
+
+
+
+
);
}
diff --git a/frontend/src/api/backend/base.ts b/frontend/src/api/backend/base.ts
new file mode 100644
index 000000000..ed6f12e64
--- /dev/null
+++ b/frontend/src/api/backend/base.ts
@@ -0,0 +1,163 @@
+import { QueryClient } from "@tanstack/react-query";
+import { camelizeKeys, decamelize, decamelizeKeys } from "humps";
+import queryString, { type StringifiableRecord } from "query-string";
+import AuthStore from "src/modules/AuthStore";
+
+const queryClient = new QueryClient();
+const contentTypeHeader = "Content-Type";
+
+interface BuildUrlArgs {
+ url: string;
+ params?: StringifiableRecord;
+}
+
+function decamelizeParams(params?: StringifiableRecord): StringifiableRecord | undefined {
+ if (!params) {
+ return undefined;
+ }
+ const result: StringifiableRecord = {};
+ for (const [key, value] of Object.entries(params)) {
+ result[decamelize(key)] = value;
+ }
+
+ return result;
+}
+
+function buildUrl({ url, params }: BuildUrlArgs) {
+ const endpoint = url.replace(/^\/|\/$/g, "");
+ const baseUrl = `/api/${endpoint}`;
+ const apiUrl = queryString.stringifyUrl({
+ url: baseUrl,
+ query: decamelizeParams(params),
+ });
+ return apiUrl;
+}
+
+function buildAuthHeader(): Record | undefined {
+ if (AuthStore.token) {
+ return { Authorization: `Bearer ${AuthStore.token.token}` };
+ }
+ return {};
+}
+
+function buildBody(data?: Record): string | undefined {
+ if (data) {
+ return JSON.stringify(decamelizeKeys(data));
+ }
+}
+
+async function processResponse(response: Response, skipCamelize = false) {
+ const payload = await response.json();
+ if (!response.ok) {
+ if (response.status === 401) {
+ // Force logout user and reload the page if Unauthorized
+ AuthStore.clear();
+ queryClient.clear();
+ window.location.reload();
+ }
+ throw new Error(
+ typeof payload.error.messageI18n !== "undefined" ? payload.error.messageI18n : payload.error.message,
+ );
+ }
+ return (skipCamelize ? payload : camelizeKeys(payload)) as any;
+}
+
+interface GetArgs {
+ url: string;
+ params?: queryString.StringifiableRecord;
+ skipCamelize?: boolean;
+}
+
+async function baseGet({ url, params }: GetArgs) {
+ const apiUrl = buildUrl({ url, params });
+ const method = "GET";
+ const headers = buildAuthHeader();
+ const response = await fetch(apiUrl, { method, headers });
+ return response;
+}
+
+export async function get(args: GetArgs) {
+ return processResponse(await baseGet(args), args.skipCamelize);
+}
+
+export async function download({ url, params }: GetArgs, filename = "download.file") {
+ const headers = buildAuthHeader();
+ const res = await fetch(buildUrl({ url, params }), { headers });
+ const bl = await res.blob();
+ const u = window.URL.createObjectURL(bl);
+ const a = document.createElement("a");
+ a.href = u;
+ a.download = filename;
+ a.click();
+ window.URL.revokeObjectURL(url);
+}
+
+interface PostArgs {
+ url: string;
+ params?: queryString.StringifiableRecord;
+ data?: any;
+ noAuth?: boolean;
+ skipCamelize?: boolean;
+}
+
+export async function post({ url, params, data, noAuth, skipCamelize }: PostArgs) {
+ const apiUrl = buildUrl({ url, params });
+ const method = "POST";
+
+ let headers: Record = {};
+ if (!noAuth) {
+ headers = {
+ ...buildAuthHeader(),
+ };
+ }
+
+ let body: string | FormData | undefined;
+ // Check if the data is an instance of FormData
+ // If data is FormData, let the browser set the Content-Type header
+ if (data instanceof FormData) {
+ body = data;
+ } else {
+ // If data is JSON, set the Content-Type header to 'application/json'
+ headers = {
+ ...headers,
+ [contentTypeHeader]: "application/json",
+ };
+ body = buildBody(data);
+ }
+
+ const response = await fetch(apiUrl, { method, headers, body });
+ return processResponse(response, skipCamelize);
+}
+
+interface PutArgs {
+ url: string;
+ params?: queryString.StringifiableRecord;
+ data?: Record;
+ skipCamelize?: boolean;
+}
+export async function put({ url, params, data, skipCamelize }: PutArgs) {
+ const apiUrl = buildUrl({ url, params });
+ const method = "PUT";
+ const headers = {
+ ...buildAuthHeader(),
+ [contentTypeHeader]: "application/json",
+ };
+ const body = buildBody(data);
+ const response = await fetch(apiUrl, { method, headers, body });
+ return processResponse(response, skipCamelize);
+}
+
+interface DeleteArgs {
+ url: string;
+ params?: queryString.StringifiableRecord;
+ skipCamelize?: boolean;
+}
+export async function del({ url, params, skipCamelize }: DeleteArgs) {
+ const apiUrl = buildUrl({ url, params });
+ const method = "DELETE";
+ const headers = {
+ ...buildAuthHeader(),
+ };
+ const response = await fetch(apiUrl, { method, headers });
+ return processResponse(response, skipCamelize);
+}
diff --git a/frontend/src/api/backend/checkVersion.ts b/frontend/src/api/backend/checkVersion.ts
new file mode 100644
index 000000000..5095526ef
--- /dev/null
+++ b/frontend/src/api/backend/checkVersion.ts
@@ -0,0 +1,8 @@
+import * as api from "./base";
+import type { VersionCheckResponse } from "./responseTypes";
+
+export async function checkVersion(): Promise {
+ return await api.get({
+ url: "/version/check",
+ });
+}
diff --git a/frontend/src/api/backend/createAccessList.ts b/frontend/src/api/backend/createAccessList.ts
new file mode 100644
index 000000000..4a17f6755
--- /dev/null
+++ b/frontend/src/api/backend/createAccessList.ts
@@ -0,0 +1,9 @@
+import * as api from "./base";
+import type { AccessList } from "./models";
+
+export async function createAccessList(item: AccessList): Promise {
+ return await api.post({
+ url: "/nginx/access-lists",
+ data: item,
+ });
+}
diff --git a/frontend/src/api/backend/createCertificate.ts b/frontend/src/api/backend/createCertificate.ts
new file mode 100644
index 000000000..ea81c44e4
--- /dev/null
+++ b/frontend/src/api/backend/createCertificate.ts
@@ -0,0 +1,9 @@
+import * as api from "./base";
+import type { Certificate } from "./models";
+
+export async function createCertificate(item: Certificate): Promise {
+ return await api.post({
+ url: "/nginx/certificates",
+ data: item,
+ });
+}
diff --git a/frontend/src/api/backend/createDeadHost.ts b/frontend/src/api/backend/createDeadHost.ts
new file mode 100644
index 000000000..f2a9f4503
--- /dev/null
+++ b/frontend/src/api/backend/createDeadHost.ts
@@ -0,0 +1,9 @@
+import * as api from "./base";
+import type { DeadHost } from "./models";
+
+export async function createDeadHost(item: DeadHost): Promise {
+ return await api.post({
+ url: "/nginx/dead-hosts",
+ data: item,
+ });
+}
diff --git a/frontend/src/api/backend/createProxyHost.ts b/frontend/src/api/backend/createProxyHost.ts
new file mode 100644
index 000000000..fcde7cd60
--- /dev/null
+++ b/frontend/src/api/backend/createProxyHost.ts
@@ -0,0 +1,9 @@
+import * as api from "./base";
+import type { ProxyHost } from "./models";
+
+export async function createProxyHost(item: ProxyHost): Promise {
+ return await api.post({
+ url: "/nginx/proxy-hosts",
+ data: item,
+ });
+}
diff --git a/frontend/src/api/backend/createRedirectionHost.ts b/frontend/src/api/backend/createRedirectionHost.ts
new file mode 100644
index 000000000..a797f819d
--- /dev/null
+++ b/frontend/src/api/backend/createRedirectionHost.ts
@@ -0,0 +1,9 @@
+import * as api from "./base";
+import type { RedirectionHost } from "./models";
+
+export async function createRedirectionHost(item: RedirectionHost): Promise {
+ return await api.post({
+ url: "/nginx/redirection-hosts",
+ data: item,
+ });
+}
diff --git a/frontend/src/api/backend/createStream.ts b/frontend/src/api/backend/createStream.ts
new file mode 100644
index 000000000..adad2a1eb
--- /dev/null
+++ b/frontend/src/api/backend/createStream.ts
@@ -0,0 +1,9 @@
+import * as api from "./base";
+import type { Stream } from "./models";
+
+export async function createStream(item: Stream): Promise {
+ return await api.post({
+ url: "/nginx/streams",
+ data: item,
+ });
+}
diff --git a/frontend/src/api/backend/createUser.ts b/frontend/src/api/backend/createUser.ts
new file mode 100644
index 000000000..081abd067
--- /dev/null
+++ b/frontend/src/api/backend/createUser.ts
@@ -0,0 +1,19 @@
+import * as api from "./base";
+import type { NewAuth, User, UserAuth } from "./models";
+
+export interface NewUser {
+ name: string;
+ email: string;
+ isDisabled?: boolean;
+ auth?: UserAuth | NewAuth;
+ capabilities?: string[];
+}
+
+export async function createUser(item: NewUser, noAuth?: boolean): Promise {
+ const { result } = await api.post({
+ url: "/users",
+ data: item,
+ noAuth,
+ });
+ return result;
+}
diff --git a/frontend/src/api/backend/deleteAccessList.ts b/frontend/src/api/backend/deleteAccessList.ts
new file mode 100644
index 000000000..838c940b8
--- /dev/null
+++ b/frontend/src/api/backend/deleteAccessList.ts
@@ -0,0 +1,7 @@
+import * as api from "./base";
+
+export async function deleteAccessList(id: number): Promise {
+ return await api.del({
+ url: `/nginx/access-lists/${id}`,
+ });
+}
diff --git a/frontend/src/api/backend/deleteCertificate.ts b/frontend/src/api/backend/deleteCertificate.ts
new file mode 100644
index 000000000..2257316c4
--- /dev/null
+++ b/frontend/src/api/backend/deleteCertificate.ts
@@ -0,0 +1,7 @@
+import * as api from "./base";
+
+export async function deleteCertificate(id: number): Promise {
+ return await api.del({
+ url: `/nginx/certificates/${id}`,
+ });
+}
diff --git a/frontend/src/api/backend/deleteDeadHost.ts b/frontend/src/api/backend/deleteDeadHost.ts
new file mode 100644
index 000000000..8e72ca84f
--- /dev/null
+++ b/frontend/src/api/backend/deleteDeadHost.ts
@@ -0,0 +1,7 @@
+import * as api from "./base";
+
+export async function deleteDeadHost(id: number): Promise {
+ return await api.del({
+ url: `/nginx/dead-hosts/${id}`,
+ });
+}
diff --git a/frontend/src/api/backend/deleteProxyHost.ts b/frontend/src/api/backend/deleteProxyHost.ts
new file mode 100644
index 000000000..7b7f2d827
--- /dev/null
+++ b/frontend/src/api/backend/deleteProxyHost.ts
@@ -0,0 +1,7 @@
+import * as api from "./base";
+
+export async function deleteProxyHost(id: number): Promise {
+ return await api.del({
+ url: `/nginx/proxy-hosts/${id}`,
+ });
+}
diff --git a/frontend/src/api/backend/deleteRedirectionHost.ts b/frontend/src/api/backend/deleteRedirectionHost.ts
new file mode 100644
index 000000000..7c594b68f
--- /dev/null
+++ b/frontend/src/api/backend/deleteRedirectionHost.ts
@@ -0,0 +1,7 @@
+import * as api from "./base";
+
+export async function deleteRedirectionHost(id: number): Promise {
+ return await api.del({
+ url: `/nginx/redirection-hosts/${id}`,
+ });
+}
diff --git a/frontend/src/api/backend/deleteStream.ts b/frontend/src/api/backend/deleteStream.ts
new file mode 100644
index 000000000..db9e11f14
--- /dev/null
+++ b/frontend/src/api/backend/deleteStream.ts
@@ -0,0 +1,7 @@
+import * as api from "./base";
+
+export async function deleteStream(id: number): Promise {
+ return await api.del({
+ url: `/nginx/streams/${id}`,
+ });
+}
diff --git a/frontend/src/api/backend/deleteUser.ts b/frontend/src/api/backend/deleteUser.ts
new file mode 100644
index 000000000..2a04a6e99
--- /dev/null
+++ b/frontend/src/api/backend/deleteUser.ts
@@ -0,0 +1,7 @@
+import * as api from "./base";
+
+export async function deleteUser(id: number): Promise {
+ return await api.del({
+ url: `/users/${id}`,
+ });
+}
diff --git a/frontend/src/api/backend/downloadCertificate.ts b/frontend/src/api/backend/downloadCertificate.ts
new file mode 100644
index 000000000..079f33594
--- /dev/null
+++ b/frontend/src/api/backend/downloadCertificate.ts
@@ -0,0 +1,10 @@
+import * as api from "./base";
+
+export async function downloadCertificate(id: number): Promise {
+ await api.download(
+ {
+ url: `/nginx/certificates/${id}/download`,
+ },
+ `certificate-${id}.zip`,
+ );
+}
diff --git a/frontend/src/api/backend/expansions.ts b/frontend/src/api/backend/expansions.ts
new file mode 100644
index 000000000..e098a4900
--- /dev/null
+++ b/frontend/src/api/backend/expansions.ts
@@ -0,0 +1,6 @@
+export type AccessListExpansion = "owner" | "items" | "clients";
+export type AuditLogExpansion = "user";
+export type CertificateExpansion = "owner" | "proxy_hosts" | "redirection_hosts" | "dead_hosts" | "streams";
+export type HostExpansion = "owner" | "certificate";
+export type ProxyHostExpansion = "owner" | "access_list" | "certificate";
+export type UserExpansion = "permissions";
diff --git a/frontend/src/api/backend/getAccessList.ts b/frontend/src/api/backend/getAccessList.ts
new file mode 100644
index 000000000..a1afd3508
--- /dev/null
+++ b/frontend/src/api/backend/getAccessList.ts
@@ -0,0 +1,13 @@
+import * as api from "./base";
+import type { AccessListExpansion } from "./expansions";
+import type { AccessList } from "./models";
+
+export async function getAccessList(id: number, expand?: AccessListExpansion[], params = {}): Promise {
+ return await api.get({
+ url: `/nginx/access-lists/${id}`,
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getAccessLists.ts b/frontend/src/api/backend/getAccessLists.ts
new file mode 100644
index 000000000..515f1e217
--- /dev/null
+++ b/frontend/src/api/backend/getAccessLists.ts
@@ -0,0 +1,13 @@
+import * as api from "./base";
+import type { AccessListExpansion } from "./expansions";
+import type { AccessList } from "./models";
+
+export async function getAccessLists(expand?: AccessListExpansion[], params = {}): Promise {
+ return await api.get({
+ url: "/nginx/access-lists",
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getAuditLog.ts b/frontend/src/api/backend/getAuditLog.ts
new file mode 100644
index 000000000..d2d01f708
--- /dev/null
+++ b/frontend/src/api/backend/getAuditLog.ts
@@ -0,0 +1,13 @@
+import * as api from "./base";
+import type { AuditLogExpansion } from "./expansions";
+import type { AuditLog } from "./models";
+
+export async function getAuditLog(id: number, expand?: AuditLogExpansion[], params = {}): Promise {
+ return await api.get({
+ url: `/audit-log/${id}`,
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getAuditLogs.ts b/frontend/src/api/backend/getAuditLogs.ts
new file mode 100644
index 000000000..bbdb2f160
--- /dev/null
+++ b/frontend/src/api/backend/getAuditLogs.ts
@@ -0,0 +1,13 @@
+import * as api from "./base";
+import type { AuditLogExpansion } from "./expansions";
+import type { AuditLog } from "./models";
+
+export async function getAuditLogs(expand?: AuditLogExpansion[], params = {}): Promise {
+ return await api.get({
+ url: "/audit-log",
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getCertificate.ts b/frontend/src/api/backend/getCertificate.ts
new file mode 100644
index 000000000..13de898db
--- /dev/null
+++ b/frontend/src/api/backend/getCertificate.ts
@@ -0,0 +1,13 @@
+import * as api from "./base";
+import type { CertificateExpansion } from "./expansions";
+import type { Certificate } from "./models";
+
+export async function getCertificate(id: number, expand?: CertificateExpansion[], params = {}): Promise {
+ return await api.get({
+ url: `/nginx/certificates/${id}`,
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getCertificateDNSProviders.ts b/frontend/src/api/backend/getCertificateDNSProviders.ts
new file mode 100644
index 000000000..03e3afa2e
--- /dev/null
+++ b/frontend/src/api/backend/getCertificateDNSProviders.ts
@@ -0,0 +1,9 @@
+import * as api from "./base";
+import type { DNSProvider } from "./models";
+
+export async function getCertificateDNSProviders(params = {}): Promise {
+ return await api.get({
+ url: "/nginx/certificates/dns-providers",
+ params,
+ });
+}
diff --git a/frontend/src/api/backend/getCertificates.ts b/frontend/src/api/backend/getCertificates.ts
new file mode 100644
index 000000000..d6d215b5d
--- /dev/null
+++ b/frontend/src/api/backend/getCertificates.ts
@@ -0,0 +1,13 @@
+import * as api from "./base";
+import type { CertificateExpansion } from "./expansions";
+import type { Certificate } from "./models";
+
+export async function getCertificates(expand?: CertificateExpansion[], params = {}): Promise {
+ return await api.get({
+ url: "/nginx/certificates",
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getDeadHost.ts b/frontend/src/api/backend/getDeadHost.ts
new file mode 100644
index 000000000..d6c062b91
--- /dev/null
+++ b/frontend/src/api/backend/getDeadHost.ts
@@ -0,0 +1,13 @@
+import * as api from "./base";
+import type { HostExpansion } from "./expansions";
+import type { DeadHost } from "./models";
+
+export async function getDeadHost(id: number, expand?: HostExpansion[], params = {}): Promise {
+ return await api.get({
+ url: `/nginx/dead-hosts/${id}`,
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getDeadHosts.ts b/frontend/src/api/backend/getDeadHosts.ts
new file mode 100644
index 000000000..1ca410e46
--- /dev/null
+++ b/frontend/src/api/backend/getDeadHosts.ts
@@ -0,0 +1,13 @@
+import * as api from "./base";
+import type { HostExpansion } from "./expansions";
+import type { DeadHost } from "./models";
+
+export async function getDeadHosts(expand?: HostExpansion[], params = {}): Promise {
+ return await api.get({
+ url: "/nginx/dead-hosts",
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getHostsReport.ts b/frontend/src/api/backend/getHostsReport.ts
new file mode 100644
index 000000000..938d3a747
--- /dev/null
+++ b/frontend/src/api/backend/getHostsReport.ts
@@ -0,0 +1,7 @@
+import * as api from "./base";
+
+export async function getHostsReport(): Promise> {
+ return await api.get({
+ url: "/reports/hosts",
+ });
+}
diff --git a/frontend/src/api/backend/getLogSources.ts b/frontend/src/api/backend/getLogSources.ts
new file mode 100644
index 000000000..4bec70002
--- /dev/null
+++ b/frontend/src/api/backend/getLogSources.ts
@@ -0,0 +1,8 @@
+import * as api from "./base";
+import type { LogSources } from "./models";
+
+export async function getLogSources(): Promise {
+ return await api.get({
+ url: "/logs/sources",
+ });
+}
diff --git a/frontend/src/api/backend/getLogTail.ts b/frontend/src/api/backend/getLogTail.ts
new file mode 100644
index 000000000..899282b32
--- /dev/null
+++ b/frontend/src/api/backend/getLogTail.ts
@@ -0,0 +1,19 @@
+import * as api from "./base";
+import type { LogChannel, LogHostType, LogSourceType, LogTail } from "./models";
+
+export interface GetLogTailParams {
+ type: LogSourceType;
+ hostType?: LogHostType;
+ hostId?: number;
+ channel?: LogChannel;
+ lines?: number;
+ level?: string;
+ search?: string;
+}
+
+export async function getLogTail(params: GetLogTailParams): Promise {
+ return await api.get({
+ url: "/logs/tail",
+ params: { ...params },
+ });
+}
diff --git a/frontend/src/api/backend/getProxyHost.ts b/frontend/src/api/backend/getProxyHost.ts
new file mode 100644
index 000000000..911b89c30
--- /dev/null
+++ b/frontend/src/api/backend/getProxyHost.ts
@@ -0,0 +1,13 @@
+import * as api from "./base";
+import type { ProxyHostExpansion } from "./expansions";
+import type { ProxyHost } from "./models";
+
+export async function getProxyHost(id: number, expand?: ProxyHostExpansion[], params = {}): Promise {
+ return await api.get({
+ url: `/nginx/proxy-hosts/${id}`,
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getProxyHostLogs.ts b/frontend/src/api/backend/getProxyHostLogs.ts
new file mode 100644
index 000000000..91944c9d7
--- /dev/null
+++ b/frontend/src/api/backend/getProxyHostLogs.ts
@@ -0,0 +1,8 @@
+import * as api from "./base";
+
+export async function getProxyHostLogs(id: number, type: "access" | "error" = "access"): Promise<{ logs: string }> {
+ return await api.get({
+ url: `/nginx/proxy-hosts/${id}/logs`,
+ params: { type },
+ });
+}
diff --git a/frontend/src/api/backend/getProxyHosts.ts b/frontend/src/api/backend/getProxyHosts.ts
new file mode 100644
index 000000000..ba9c864a5
--- /dev/null
+++ b/frontend/src/api/backend/getProxyHosts.ts
@@ -0,0 +1,13 @@
+import * as api from "./base";
+import type { ProxyHostExpansion } from "./expansions";
+import type { ProxyHost } from "./models";
+
+export async function getProxyHosts(expand?: ProxyHostExpansion[], params = {}): Promise {
+ return await api.get({
+ url: "/nginx/proxy-hosts",
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getRedirectionHost.ts b/frontend/src/api/backend/getRedirectionHost.ts
new file mode 100644
index 000000000..01df988ac
--- /dev/null
+++ b/frontend/src/api/backend/getRedirectionHost.ts
@@ -0,0 +1,13 @@
+import * as api from "./base";
+import type { HostExpansion } from "./expansions";
+import type { RedirectionHost } from "./models";
+
+export async function getRedirectionHost(id: number, expand?: HostExpansion[], params = {}): Promise {
+ return await api.get({
+ url: `/nginx/redirection-hosts/${id}`,
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getRedirectionHosts.ts b/frontend/src/api/backend/getRedirectionHosts.ts
new file mode 100644
index 000000000..63e292f79
--- /dev/null
+++ b/frontend/src/api/backend/getRedirectionHosts.ts
@@ -0,0 +1,13 @@
+import * as api from "./base";
+import type { HostExpansion } from "./expansions";
+import type { RedirectionHost } from "./models";
+
+export async function getRedirectionHosts(expand?: HostExpansion[], params = {}): Promise {
+ return await api.get({
+ url: "/nginx/redirection-hosts",
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getSetting.ts b/frontend/src/api/backend/getSetting.ts
new file mode 100644
index 000000000..daa54fee1
--- /dev/null
+++ b/frontend/src/api/backend/getSetting.ts
@@ -0,0 +1,12 @@
+import * as api from "./base";
+import type { Setting } from "./models";
+
+export async function getSetting(id: string, expand?: string[], params = {}): Promise {
+ return await api.get({
+ url: `/settings/${id}`,
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getSettings.ts b/frontend/src/api/backend/getSettings.ts
new file mode 100644
index 000000000..b8e992c62
--- /dev/null
+++ b/frontend/src/api/backend/getSettings.ts
@@ -0,0 +1,12 @@
+import * as api from "./base";
+import type { Setting } from "./models";
+
+export async function getSettings(expand?: string[], params = {}): Promise {
+ return await api.get({
+ url: "/settings",
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getStream.ts b/frontend/src/api/backend/getStream.ts
new file mode 100644
index 000000000..82e10a045
--- /dev/null
+++ b/frontend/src/api/backend/getStream.ts
@@ -0,0 +1,13 @@
+import * as api from "./base";
+import type { HostExpansion } from "./expansions";
+import type { Stream } from "./models";
+
+export async function getStream(id: number, expand?: HostExpansion[], params = {}): Promise {
+ return await api.get({
+ url: `/nginx/streams/${id}`,
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getStreams.ts b/frontend/src/api/backend/getStreams.ts
new file mode 100644
index 000000000..b5e9379b5
--- /dev/null
+++ b/frontend/src/api/backend/getStreams.ts
@@ -0,0 +1,13 @@
+import * as api from "./base";
+import type { HostExpansion } from "./expansions";
+import type { Stream } from "./models";
+
+export async function getStreams(expand?: HostExpansion[], params = {}): Promise {
+ return await api.get({
+ url: "/nginx/streams",
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/getToken.ts b/frontend/src/api/backend/getToken.ts
new file mode 100644
index 000000000..62decf8fa
--- /dev/null
+++ b/frontend/src/api/backend/getToken.ts
@@ -0,0 +1,30 @@
+import * as api from "./base";
+import type { TokenResponse, TwoFactorChallengeResponse } from "./responseTypes";
+
+export type LoginResponse = TokenResponse | TwoFactorChallengeResponse;
+
+export function isTwoFactorChallenge(response: LoginResponse): response is TwoFactorChallengeResponse {
+ return "requires2fa" in response && response.requires2fa === true;
+}
+
+interface Payload {
+ type: string;
+ identity: string;
+ secret: string;
+}
+export async function getToken(payload: Payload): Promise {
+ const { result } = await api.post(
+ {
+ url: "/auth",
+ data: payload,
+ },
+ );
+ return result;
+}
+
+export async function verify2FA(challengeToken: string, code: string): Promise {
+ return await api.post({
+ url: "/auth/2fa",
+ data: { challengeToken, code },
+ });
+}
diff --git a/frontend/src/api/backend/getUser.ts b/frontend/src/api/backend/getUser.ts
new file mode 100644
index 000000000..c04e90aa6
--- /dev/null
+++ b/frontend/src/api/backend/getUser.ts
@@ -0,0 +1,15 @@
+import * as api from "./base";
+import type { UserExpansion } from "./expansions";
+import type { User } from "./models";
+
+export async function getUser(id: number | string = "me", expand?: UserExpansion[], params = {}): Promise {
+ const userId = id ? id : "me";
+ const {result} = await api.get({
+ url: `/users/${userId}`,
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+ return result;
+}
diff --git a/frontend/src/api/backend/getUsers.ts b/frontend/src/api/backend/getUsers.ts
new file mode 100644
index 000000000..dab584f42
--- /dev/null
+++ b/frontend/src/api/backend/getUsers.ts
@@ -0,0 +1,13 @@
+import * as api from "./base";
+import type { UserExpansion } from "./expansions";
+import type { User } from "./models";
+
+export async function getUsers(expand?: UserExpansion[], params = {}): Promise {
+ return await api.get({
+ url: "/users",
+ params: {
+ expand: expand?.join(","),
+ ...params,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/health.ts b/frontend/src/api/backend/health.ts
new file mode 100644
index 000000000..75f404585
--- /dev/null
+++ b/frontend/src/api/backend/health.ts
@@ -0,0 +1,23 @@
+import * as api from "./base";
+
+export interface AppVersion {
+ major: number;
+ minor: number;
+ patch: number;
+}
+
+export interface HealthResponse {
+ commit: string;
+ dbSetup: boolean;
+ errorReporting: boolean;
+ healthy: boolean;
+ setup: boolean;
+ version: AppVersion;
+}
+
+export async function getHealth(): Promise {
+ const { result } = await api.get({
+ url: "/",
+ });
+ return result;
+}
diff --git a/frontend/src/api/npm/helpers.ts b/frontend/src/api/backend/helpers.ts
similarity index 51%
rename from frontend/src/api/npm/helpers.ts
rename to frontend/src/api/backend/helpers.ts
index da6b8ca89..8d9773191 100644
--- a/frontend/src/api/npm/helpers.ts
+++ b/frontend/src/api/backend/helpers.ts
@@ -9,7 +9,7 @@ export function tableSortToAPI(sortBy: any): string | undefined {
if (sortBy?.length > 0) {
const strs: string[] = [];
sortBy.map((item: any) => {
- strs.push(decamelize(item.id) + "." + (item.desc ? "desc" : "asc"));
+ strs.push(`${decamelize(item.id)}.${item.desc ? "desc" : "asc"}`);
return undefined;
});
return strs.join(",");
@@ -22,7 +22,7 @@ export function tableSortToAPI(sortBy: any): string | undefined {
* a string that the backend api likes:
* name:contains=jam
*/
-export function tableFiltersToAPI(filters: any): { [key: string]: string } {
+export function tableFiltersToAPI(filters: any[]): { [key: string]: string } {
const items: { [key: string]: string } = {};
if (filters?.length > 0) {
filters.map((item: any) => {
@@ -32,3 +32,23 @@ export function tableFiltersToAPI(filters: any): { [key: string]: string } {
}
return items;
}
+
+/**
+ * Builds a filters object by removing entries with undefined, null, or empty string values.
+ *
+ */
+export function buildFilters(filters?: Record) {
+ if (!filters) {
+ return filters;
+ }
+ const result: Record = {};
+ for (const key in filters) {
+ const value = filters[key];
+ // If the value is undefined, null, or an empty string, skip it
+ if (value === undefined || value === null || value === "") {
+ continue;
+ }
+ result[key] = value.toString();
+ }
+ return result;
+}
diff --git a/frontend/src/api/backend/index.ts b/frontend/src/api/backend/index.ts
new file mode 100644
index 000000000..cf05f436d
--- /dev/null
+++ b/frontend/src/api/backend/index.ts
@@ -0,0 +1,67 @@
+export * from "./checkVersion";
+export * from "./createAccessList";
+export * from "./createCertificate";
+export * from "./createDeadHost";
+export * from "./createProxyHost";
+export * from "./createRedirectionHost";
+export * from "./createStream";
+export * from "./createUser";
+export * from "./deleteAccessList";
+export * from "./deleteCertificate";
+export * from "./deleteDeadHost";
+export * from "./deleteProxyHost";
+export * from "./deleteRedirectionHost";
+export * from "./deleteStream";
+export * from "./deleteUser";
+export * from "./downloadCertificate";
+export * from "./expansions";
+export * from "./getAccessList";
+export * from "./getAccessLists";
+export * from "./getAuditLog";
+export * from "./getAuditLogs";
+export * from "./getCertificate";
+export * from "./getCertificateDNSProviders";
+export * from "./getCertificates";
+export * from "./getDeadHost";
+export * from "./getDeadHosts";
+export * from "./getHostsReport";
+export * from "./getLogSources";
+export * from "./getLogTail";
+export * from "./getProxyHost";
+export * from "./getProxyHostLogs";
+export * from "./getProxyHosts";
+export * from "./getRedirectionHost";
+export * from "./getRedirectionHosts";
+export * from "./getSetting";
+export * from "./getSettings";
+export * from "./getStream";
+export * from "./getStreams";
+export * from "./getToken";
+export * from "./getUser";
+export * from "./getUsers";
+export * from "./health";
+export * from "./helpers";
+export * from "./loginAsUser";
+export * from "./models";
+export * from "./refreshToken";
+export * from "./renewCertificate";
+export * from "./responseTypes";
+export * from "./setPermissions";
+export * from "./setupDatabase";
+export * from "./testHttpCertificate";
+export * from "./toggleDeadHost";
+export * from "./toggleProxyHost";
+export * from "./toggleRedirectionHost";
+export * from "./toggleStream";
+export * from "./toggleUser";
+export * from "./twoFactor";
+export * from "./updateAccessList";
+export * from "./updateAuth";
+export * from "./updateDeadHost";
+export * from "./updateProxyHost";
+export * from "./updateRedirectionHost";
+export * from "./updateSetting";
+export * from "./updateStream";
+export * from "./updateUser";
+export * from "./uploadCertificate";
+export * from "./validateCertificate";
diff --git a/frontend/src/api/backend/loginAsUser.ts b/frontend/src/api/backend/loginAsUser.ts
new file mode 100644
index 000000000..2ade379d8
--- /dev/null
+++ b/frontend/src/api/backend/loginAsUser.ts
@@ -0,0 +1,8 @@
+import * as api from "./base";
+import type { LoginAsTokenResponse } from "./responseTypes";
+
+export async function loginAsUser(id: number): Promise {
+ return await api.post({
+ url: `/users/${id}/login`,
+ });
+}
diff --git a/frontend/src/api/backend/models.ts b/frontend/src/api/backend/models.ts
new file mode 100644
index 000000000..1970b6fbe
--- /dev/null
+++ b/frontend/src/api/backend/models.ts
@@ -0,0 +1,244 @@
+export interface UserPermissions {
+ id?: number;
+ createdOn?: string;
+ modifiedOn?: string;
+ userId?: number;
+ visibility: string;
+ proxyHosts: string;
+ redirectionHosts: string;
+ deadHosts: string;
+ streams: string;
+ accessLists: string;
+ certificates: string;
+}
+
+export interface UserAuth {
+ id: number;
+ userId: number;
+ type: string;
+ createdOn: number;
+ updatedOn: number;
+}
+
+export interface NewAuth {
+ type: string;
+ secret: string;
+}
+
+export interface User {
+ id: number;
+ createdOn: string;
+ modifiedOn: string;
+ isDisabled: boolean;
+ email: string;
+ name: string;
+ gravatarUrl: string;
+ roles?: string[];
+ notifications?: Notification[];
+ capabilities?: string[];
+ auth?: UserAuth | NewAuth;
+}
+
+export interface AuditLog {
+ id: number;
+ createdOn: string;
+ modifiedOn: string;
+ userId: number;
+ objectType: string;
+ objectId: number;
+ action: string;
+ meta: Record;
+ // Expansions:
+ user?: User;
+}
+
+export type LogSourceType = "system" | "letsencrypt" | "host";
+export type LogHostType = "proxy" | "redirection" | "dead" | "stream";
+// Which of the two files nginx writes per host - named "channel", not "stream",
+// to avoid confusion with the "stream" LogHostType (TCP/UDP stream hosts).
+export type LogChannel = "access" | "error";
+
+export interface LogHostOption {
+ id: number;
+ label: string;
+}
+
+export interface LogSources {
+ system: { label: string };
+ letsencrypt: { label: string };
+ hosts: Record;
+}
+
+export interface LogTail {
+ lines: string[];
+ size: number;
+ truncated: boolean;
+ exists: boolean;
+}
+
+export interface AccessList {
+ id?: number;
+ createdOn?: string;
+ modifiedOn?: string;
+ ownerUserId: number;
+ name: string;
+ meta: Record;
+ satisfyAny: boolean;
+ passAuth: boolean;
+ proxyHostCount?: number;
+ // Expansions:
+ owner?: User;
+ items?: AccessListItem[];
+ clients?: AccessListClient[];
+}
+
+export interface AccessListItem {
+ id?: number;
+ createdOn?: string;
+ modifiedOn?: string;
+ accessListId?: number;
+ username: string;
+ password: string;
+ meta?: Record;
+ hint?: string;
+}
+
+export type AccessListClient = {
+ id?: number;
+ createdOn?: string;
+ modifiedOn?: string;
+ accessListId?: number;
+ address: string;
+ directive: "allow" | "deny";
+ meta?: Record;
+};
+
+export interface Certificate {
+ id: number;
+ createdOn: string;
+ modifiedOn: string;
+ ownerUserId: number;
+ provider: string;
+ niceName: string;
+ domainNames: string[];
+ expiresOn: string;
+ meta: Record;
+ owner?: User;
+ proxyHosts?: ProxyHost[];
+ deadHosts?: DeadHost[];
+ redirectionHosts?: RedirectionHost[];
+}
+
+export interface ProxyLocation {
+ path: string;
+ advancedConfig: string;
+ forwardScheme: string;
+ forwardHost: string;
+ forwardPort: number;
+ accessListId?: number;
+ accessList?: AccessList;
+}
+
+export interface ProxyHost {
+ id: number;
+ createdOn: string;
+ modifiedOn: string;
+ ownerUserId: number;
+ domainNames: string[];
+ forwardScheme: string;
+ forwardHost: string;
+ forwardPort: number;
+ accessListId: number;
+ certificateId: number;
+ sslForced: boolean;
+ cachingEnabled: boolean;
+ blockExploits: boolean;
+ advancedConfig: string;
+ meta: Record;
+ allowWebsocketUpgrade: boolean;
+ http2Support: boolean;
+ enabled: boolean;
+ locations?: ProxyLocation[];
+ hstsEnabled: boolean;
+ hstsSubdomains: boolean;
+ trustForwardedProto: boolean;
+ // Expansions:
+ owner?: User;
+ accessList?: AccessList;
+ certificate?: Certificate;
+}
+
+export interface DeadHost {
+ id: number;
+ createdOn: string;
+ modifiedOn: string;
+ ownerUserId: number;
+ domainNames: string[];
+ certificateId: number;
+ sslForced: boolean;
+ advancedConfig: string;
+ meta: Record;
+ http2Support: boolean;
+ enabled: boolean;
+ hstsEnabled: boolean;
+ hstsSubdomains: boolean;
+ // Expansions:
+ owner?: User;
+ certificate?: Certificate;
+}
+
+export interface RedirectionHost {
+ id: number;
+ createdOn: string;
+ modifiedOn: string;
+ ownerUserId: number;
+ domainNames: string[];
+ forwardDomainName: string;
+ preservePath: boolean;
+ certificateId: number;
+ sslForced: boolean;
+ blockExploits: boolean;
+ advancedConfig: string;
+ meta: Record;
+ http2Support: boolean;
+ forwardScheme: string;
+ forwardHttpCode: number;
+ enabled: boolean;
+ hstsEnabled: boolean;
+ hstsSubdomains: boolean;
+ // Expansions:
+ owner?: User;
+ certificate?: Certificate;
+}
+
+export interface Stream {
+ id: number;
+ createdOn: string;
+ modifiedOn: string;
+ ownerUserId: number;
+ incomingPort: number;
+ forwardingHost: string;
+ forwardingPort: number;
+ tcpForwarding: boolean;
+ udpForwarding: boolean;
+ meta: Record;
+ enabled: boolean;
+ certificateId: number;
+ // Expansions:
+ owner?: User;
+ certificate?: Certificate;
+}
+
+export interface Setting {
+ id: string;
+ name?: string;
+ description?: string;
+ value: string;
+ meta?: Record;
+}
+
+export interface DNSProvider {
+ id: string;
+ name: string;
+ credentials: string;
+}
diff --git a/frontend/src/api/backend/refreshToken.ts b/frontend/src/api/backend/refreshToken.ts
new file mode 100644
index 000000000..de1848c25
--- /dev/null
+++ b/frontend/src/api/backend/refreshToken.ts
@@ -0,0 +1,8 @@
+import * as api from "./base";
+import type { TokenResponse } from "./responseTypes";
+
+export async function refreshToken(): Promise {
+ return await api.get({
+ url: "/tokens",
+ });
+}
diff --git a/frontend/src/api/backend/renewCertificate.ts b/frontend/src/api/backend/renewCertificate.ts
new file mode 100644
index 000000000..0f3d082dc
--- /dev/null
+++ b/frontend/src/api/backend/renewCertificate.ts
@@ -0,0 +1,8 @@
+import * as api from "./base";
+import type { Certificate } from "./models";
+
+export async function renewCertificate(id: number): Promise {
+ return await api.post({
+ url: `/nginx/certificates/${id}/renew`,
+ });
+}
diff --git a/frontend/src/api/backend/responseTypes.ts b/frontend/src/api/backend/responseTypes.ts
new file mode 100644
index 000000000..95742b6b2
--- /dev/null
+++ b/frontend/src/api/backend/responseTypes.ts
@@ -0,0 +1,40 @@
+import type { User } from "./models";
+
+export interface TokenResponse {
+ expires: number;
+ token: string;
+}
+
+export interface ValidatedCertificateResponse {
+ certificate: Record;
+ certificateKey: boolean;
+}
+
+export interface LoginAsTokenResponse extends TokenResponse {
+ user: User;
+}
+
+export interface VersionCheckResponse {
+ current: string | null;
+ latest: string | null;
+ updateAvailable: boolean;
+}
+
+export interface TwoFactorChallengeResponse {
+ requires2fa: boolean;
+ challengeToken: string;
+}
+
+export interface TwoFactorStatusResponse {
+ enabled: boolean;
+ backupCodesRemaining: number;
+}
+
+export interface TwoFactorSetupResponse {
+ secret: string;
+ otpauthUrl: string;
+}
+
+export interface TwoFactorEnableResponse {
+ backupCodes: string[];
+}
diff --git a/frontend/src/api/backend/setPermissions.ts b/frontend/src/api/backend/setPermissions.ts
new file mode 100644
index 000000000..47fa6306f
--- /dev/null
+++ b/frontend/src/api/backend/setPermissions.ts
@@ -0,0 +1,10 @@
+import * as api from "./base";
+import type { UserPermissions } from "./models";
+
+export async function setPermissions(userId: number, data: UserPermissions): Promise {
+ // Remove readonly fields
+ return await api.put({
+ url: `/users/${userId}/permissions`,
+ data,
+ });
+}
diff --git a/frontend/src/api/npm/setupDatabase.ts b/frontend/src/api/backend/setupDatabase.ts
similarity index 82%
rename from frontend/src/api/npm/setupDatabase.ts
rename to frontend/src/api/backend/setupDatabase.ts
index eba1e3dde..d476ec1cb 100644
--- a/frontend/src/api/npm/setupDatabase.ts
+++ b/frontend/src/api/backend/setupDatabase.ts
@@ -12,15 +12,13 @@ export interface DatabaseConfig {
}
export async function setupDatabase(
- data: DatabaseConfig,
- abortController?: AbortController,
+ data: DatabaseConfig
): Promise {
const { result } = await api.post(
{
url: "/setup/database",
data,
},
- abortController,
);
return result;
}
diff --git a/frontend/src/api/backend/testHttpCertificate.ts b/frontend/src/api/backend/testHttpCertificate.ts
new file mode 100644
index 000000000..23dfa4b7d
--- /dev/null
+++ b/frontend/src/api/backend/testHttpCertificate.ts
@@ -0,0 +1,10 @@
+import * as api from "./base";
+
+export async function testHttpCertificate(domains: string[]): Promise> {
+ return await api.post({
+ url: "/nginx/certificates/test-http",
+ data: {
+ domains,
+ },
+ });
+}
diff --git a/frontend/src/api/backend/toggleDeadHost.ts b/frontend/src/api/backend/toggleDeadHost.ts
new file mode 100644
index 000000000..71a780ef9
--- /dev/null
+++ b/frontend/src/api/backend/toggleDeadHost.ts
@@ -0,0 +1,7 @@
+import * as api from "./base";
+
+export async function toggleDeadHost(id: number, enabled: boolean): Promise {
+ return await api.post({
+ url: `/nginx/dead-hosts/${id}/${enabled ? "enable" : "disable"}`,
+ });
+}
diff --git a/frontend/src/api/backend/toggleProxyHost.ts b/frontend/src/api/backend/toggleProxyHost.ts
new file mode 100644
index 000000000..376e78818
--- /dev/null
+++ b/frontend/src/api/backend/toggleProxyHost.ts
@@ -0,0 +1,7 @@
+import * as api from "./base";
+
+export async function toggleProxyHost(id: number, enabled: boolean): Promise {
+ return await api.post({
+ url: `/nginx/proxy-hosts/${id}/${enabled ? "enable" : "disable"}`,
+ });
+}
diff --git a/frontend/src/api/backend/toggleRedirectionHost.ts b/frontend/src/api/backend/toggleRedirectionHost.ts
new file mode 100644
index 000000000..0cfa5733d
--- /dev/null
+++ b/frontend/src/api/backend/toggleRedirectionHost.ts
@@ -0,0 +1,7 @@
+import * as api from "./base";
+
+export async function toggleRedirectionHost(id: number, enabled: boolean): Promise {
+ return await api.post({
+ url: `/nginx/redirection-hosts/${id}/${enabled ? "enable" : "disable"}`,
+ });
+}
diff --git a/frontend/src/api/backend/toggleStream.ts b/frontend/src/api/backend/toggleStream.ts
new file mode 100644
index 000000000..2b71f720c
--- /dev/null
+++ b/frontend/src/api/backend/toggleStream.ts
@@ -0,0 +1,7 @@
+import * as api from "./base";
+
+export async function toggleStream(id: number, enabled: boolean): Promise {
+ return await api.post({
+ url: `/nginx/streams/${id}/${enabled ? "enable" : "disable"}`,
+ });
+}
diff --git a/frontend/src/api/backend/toggleUser.ts b/frontend/src/api/backend/toggleUser.ts
new file mode 100644
index 000000000..d2a24c94a
--- /dev/null
+++ b/frontend/src/api/backend/toggleUser.ts
@@ -0,0 +1,10 @@
+import type { User } from "./models";
+import { updateUser } from "./updateUser";
+
+export async function toggleUser(id: number, enabled: boolean): Promise {
+ await updateUser({
+ id,
+ isDisabled: !enabled,
+ } as User);
+ return true;
+}
diff --git a/frontend/src/api/backend/twoFactor.ts b/frontend/src/api/backend/twoFactor.ts
new file mode 100644
index 000000000..855e9cc1e
--- /dev/null
+++ b/frontend/src/api/backend/twoFactor.ts
@@ -0,0 +1,37 @@
+import * as api from "./base";
+import type { TwoFactorEnableResponse, TwoFactorSetupResponse, TwoFactorStatusResponse } from "./responseTypes";
+
+export async function get2FAStatus(userId: number | "me"): Promise {
+ return await api.get({
+ url: `/users/${userId}/2fa`,
+ });
+}
+
+export async function start2FASetup(userId: number | "me"): Promise {
+ return await api.post({
+ url: `/users/${userId}/2fa`,
+ });
+}
+
+export async function enable2FA(userId: number | "me", code: string): Promise {
+ return await api.post({
+ url: `/users/${userId}/2fa/enable`,
+ data: { code },
+ });
+}
+
+export async function disable2FA(userId: number | "me", code: string): Promise {
+ return await api.del({
+ url: `/users/${userId}/2fa`,
+ params: {
+ code,
+ },
+ });
+}
+
+export async function regenerateBackupCodes(userId: number | "me", code: string): Promise {
+ return await api.post({
+ url: `/users/${userId}/2fa/backup-codes`,
+ data: { code },
+ });
+}
diff --git a/frontend/src/api/backend/updateAccessList.ts b/frontend/src/api/backend/updateAccessList.ts
new file mode 100644
index 000000000..7a23566b0
--- /dev/null
+++ b/frontend/src/api/backend/updateAccessList.ts
@@ -0,0 +1,12 @@
+import * as api from "./base";
+import type { AccessList } from "./models";
+
+export async function updateAccessList(item: AccessList): Promise {
+ // Remove readonly fields
+ const { id, createdOn: _, modifiedOn: __, ...data } = item;
+
+ return await api.put({
+ url: `/nginx/access-lists/${id}`,
+ data: data,
+ });
+}
diff --git a/frontend/src/api/backend/updateAuth.ts b/frontend/src/api/backend/updateAuth.ts
new file mode 100644
index 000000000..5b14b076b
--- /dev/null
+++ b/frontend/src/api/backend/updateAuth.ts
@@ -0,0 +1,18 @@
+import * as api from "./base";
+import type { User } from "./models";
+
+export async function updateAuth(userId: number | "me", newPassword: string, current?: string): Promise {
+ const data = {
+ type: "password",
+ current: current,
+ secret: newPassword,
+ };
+ if (userId === "me") {
+ data.current = current;
+ }
+
+ return await api.put({
+ url: `/users/${userId}/auth`,
+ data,
+ });
+}
diff --git a/frontend/src/api/backend/updateDeadHost.ts b/frontend/src/api/backend/updateDeadHost.ts
new file mode 100644
index 000000000..1eb5631b1
--- /dev/null
+++ b/frontend/src/api/backend/updateDeadHost.ts
@@ -0,0 +1,12 @@
+import * as api from "./base";
+import type { DeadHost } from "./models";
+
+export async function updateDeadHost(item: DeadHost): Promise {
+ // Remove readonly fields
+ const { id, createdOn: _, modifiedOn: __, ...data } = item;
+
+ return await api.put({
+ url: `/nginx/dead-hosts/${id}`,
+ data: data,
+ });
+}
diff --git a/frontend/src/api/backend/updateProxyHost.ts b/frontend/src/api/backend/updateProxyHost.ts
new file mode 100644
index 000000000..e7ee3d906
--- /dev/null
+++ b/frontend/src/api/backend/updateProxyHost.ts
@@ -0,0 +1,12 @@
+import * as api from "./base";
+import type { ProxyHost } from "./models";
+
+export async function updateProxyHost(item: ProxyHost): Promise {
+ // Remove readonly fields
+ const { id, createdOn: _, modifiedOn: __, ...data } = item;
+
+ return await api.put({
+ url: `/nginx/proxy-hosts/${id}`,
+ data: data,
+ });
+}
diff --git a/frontend/src/api/backend/updateRedirectionHost.ts b/frontend/src/api/backend/updateRedirectionHost.ts
new file mode 100644
index 000000000..4cc36f1e6
--- /dev/null
+++ b/frontend/src/api/backend/updateRedirectionHost.ts
@@ -0,0 +1,12 @@
+import * as api from "./base";
+import type { RedirectionHost } from "./models";
+
+export async function updateRedirectionHost(item: RedirectionHost): Promise {
+ // Remove readonly fields
+ const { id, createdOn: _, modifiedOn: __, ...data } = item;
+
+ return await api.put({
+ url: `/nginx/redirection-hosts/${id}`,
+ data: data,
+ });
+}
diff --git a/frontend/src/api/backend/updateSetting.ts b/frontend/src/api/backend/updateSetting.ts
new file mode 100644
index 000000000..bcb94059b
--- /dev/null
+++ b/frontend/src/api/backend/updateSetting.ts
@@ -0,0 +1,12 @@
+import * as api from "./base";
+import type { Setting } from "./models";
+
+export async function updateSetting(item: Setting): Promise {
+ // Remove readonly fields
+ const { id, ...data } = item;
+
+ return await api.put({
+ url: `/settings/${id}`,
+ data: data,
+ });
+}
diff --git a/frontend/src/api/backend/updateStream.ts b/frontend/src/api/backend/updateStream.ts
new file mode 100644
index 000000000..508bcece0
--- /dev/null
+++ b/frontend/src/api/backend/updateStream.ts
@@ -0,0 +1,12 @@
+import * as api from "./base";
+import type { Stream } from "./models";
+
+export async function updateStream(item: Stream): Promise {
+ // Remove readonly fields
+ const { id, createdOn: _, modifiedOn: __, ...data } = item;
+
+ return await api.put({
+ url: `/nginx/streams/${id}`,
+ data: data,
+ });
+}
diff --git a/frontend/src/api/backend/updateUser.ts b/frontend/src/api/backend/updateUser.ts
new file mode 100644
index 000000000..d063e127d
--- /dev/null
+++ b/frontend/src/api/backend/updateUser.ts
@@ -0,0 +1,12 @@
+import * as api from "./base";
+import type { User } from "./models";
+
+export async function updateUser(item: User): Promise {
+ // Remove readonly fields
+ const { id, createdOn: _, modifiedOn: __, ...data } = item;
+
+ return await api.put({
+ url: `/users/${id}`,
+ data: data,
+ });
+}
diff --git a/frontend/src/api/backend/uploadCertificate.ts b/frontend/src/api/backend/uploadCertificate.ts
new file mode 100644
index 000000000..b28c4e096
--- /dev/null
+++ b/frontend/src/api/backend/uploadCertificate.ts
@@ -0,0 +1,9 @@
+import * as api from "./base";
+import type { Certificate } from "./models";
+
+export async function uploadCertificate(id: number, data: FormData): Promise {
+ return await api.post({
+ url: `/nginx/certificates/${id}/upload`,
+ data,
+ });
+}
diff --git a/frontend/src/api/backend/validateCertificate.ts b/frontend/src/api/backend/validateCertificate.ts
new file mode 100644
index 000000000..d404e514c
--- /dev/null
+++ b/frontend/src/api/backend/validateCertificate.ts
@@ -0,0 +1,9 @@
+import * as api from "./base";
+import type { ValidatedCertificateResponse } from "./responseTypes";
+
+export async function validateCertificate(data: FormData): Promise {
+ return await api.post({
+ url: "/nginx/certificates/validate",
+ data,
+ });
+}
diff --git a/frontend/src/api/npm/base.ts b/frontend/src/api/npm/base.ts
deleted file mode 100644
index a9bcc86df..000000000
--- a/frontend/src/api/npm/base.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-import { camelizeKeys, decamelizeKeys } from "humps";
-import queryString from "query-string";
-
-import AuthStore from "src/modules/AuthStore";
-
-const contentTypeHeader = "Content-Type";
-
-interface BuildUrlArgs {
- url: string;
- params?: queryString.StringifiableRecord;
-}
-function buildUrl({ url, params }: BuildUrlArgs) {
- const endpoint = url.replace(/^\/|\/$/g, "");
- const apiParams = params ? `?${queryString.stringify(params)}` : "";
- const apiUrl = `/api/${endpoint}${apiParams}`;
- return apiUrl;
-}
-
-function buildAuthHeader(): Record | undefined {
- if (AuthStore.token) {
- return { Authorization: `Bearer ${AuthStore.token.token}` };
- }
- return {};
-}
-
-function buildBody(data?: Record, skipDecamelize = false) {
- if (data) {
- return JSON.stringify(skipDecamelize ? data : decamelizeKeys(data));
- }
-}
-
-async function processResponse(response: Response, skipCamelize = false) {
- const payload = await response.json();
- if (!response.ok) {
- throw new Error(payload.error.message);
- }
- return (skipCamelize ? payload : camelizeKeys(payload)) as any;
-}
-
-interface GetArgs {
- url: string;
- params?: queryString.StringifiableRecord;
- skipCamelize?: boolean;
-}
-
-export async function get(
- { url, params, skipCamelize }: GetArgs,
- abortController?: AbortController,
-) {
- const apiUrl = buildUrl({ url, params });
- const method = "GET";
- const signal = abortController?.signal;
- const headers = buildAuthHeader();
- const response = await fetch(apiUrl, { method, headers, signal });
- return processResponse(response, skipCamelize);
-}
-
-interface PostArgs {
- url: string;
- data?: any;
- skipCamelize?: boolean;
- skipDecamelize?: boolean;
-}
-
-export async function post(
- { url, data, skipCamelize, skipDecamelize }: PostArgs,
- abortController?: AbortController,
-) {
- const apiUrl = buildUrl({ url });
- const method = "POST";
- const headers = {
- ...buildAuthHeader(),
- [contentTypeHeader]: "application/json",
- };
- const signal = abortController?.signal;
- const body = buildBody(data, skipDecamelize);
- const response = await fetch(apiUrl, { method, headers, body, signal });
- return processResponse(response, skipCamelize);
-}
-
-interface PutArgs {
- url: string;
- data?: any;
- skipCamelize?: boolean;
- skipDecamelize?: boolean;
-}
-export async function put(
- { url, data, skipCamelize, skipDecamelize }: PutArgs,
- abortController?: AbortController,
-) {
- const apiUrl = buildUrl({ url });
- const method = "PUT";
- const headers = {
- ...buildAuthHeader(),
- [contentTypeHeader]: "application/json",
- };
- const signal = abortController?.signal;
- const body = buildBody(data, skipDecamelize);
- const response = await fetch(apiUrl, { method, headers, body, signal });
- return processResponse(response, skipCamelize);
-}
-
-interface DeleteArgs {
- url: string;
-}
-export async function del(
- { url }: DeleteArgs,
- abortController?: AbortController,
-) {
- const apiUrl = buildUrl({ url });
- const method = "DELETE";
- const headers = {
- ...buildAuthHeader(),
- [contentTypeHeader]: "application/json",
- };
- const signal = abortController?.signal;
- const response = await fetch(apiUrl, { method, headers, signal });
- return processResponse(response);
-}
diff --git a/frontend/src/api/npm/createCertificate.ts b/frontend/src/api/npm/createCertificate.ts
deleted file mode 100644
index 5f662a634..000000000
--- a/frontend/src/api/npm/createCertificate.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import * as api from "./base";
-import { Certificate } from "./models";
-
-export async function createCertificate(
- data: Certificate,
- abortController?: AbortController,
-): Promise {
- const { result } = await api.post(
- {
- url: "/certificates",
- data,
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/createCertificateAuthority.ts b/frontend/src/api/npm/createCertificateAuthority.ts
deleted file mode 100644
index 1822c7445..000000000
--- a/frontend/src/api/npm/createCertificateAuthority.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import * as api from "./base";
-import { CertificateAuthority } from "./models";
-
-export async function createCertificateAuthority(
- data: CertificateAuthority,
- abortController?: AbortController,
-): Promise {
- const { result } = await api.post(
- {
- url: "/certificate-authorities",
- data,
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/createDNSProvider.ts b/frontend/src/api/npm/createDNSProvider.ts
deleted file mode 100644
index fea8a5b99..000000000
--- a/frontend/src/api/npm/createDNSProvider.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { decamelizeKeys } from "humps";
-
-import * as api from "./base";
-import { DNSProvider } from "./models";
-
-export async function createDNSProvider(
- data: DNSProvider,
- abortController?: AbortController,
-): Promise {
- // Because the meta property of the data should not be decamelized,
- // we're going to decamelize the rest here instead of in base.ts
- const dcData: any = decamelizeKeys(data);
- if (typeof data.meta !== "undefined") {
- dcData.meta = data.meta;
- }
-
- const { result } = await api.post(
- {
- url: "/dns-providers",
- data: dcData,
- skipCamelize: true,
- skipDecamelize: true,
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/createUser.ts b/frontend/src/api/npm/createUser.ts
deleted file mode 100644
index 59f740359..000000000
--- a/frontend/src/api/npm/createUser.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import * as api from "./base";
-import { User } from "./models";
-
-export interface AuthOptions {
- type: string;
- secret: string;
-}
-
-export interface NewUser {
- name: string;
- email: string;
- isDisabled: boolean;
- auth: AuthOptions;
- capabilities: string[];
-}
-
-export async function createUser(
- data: NewUser,
- abortController?: AbortController,
-): Promise {
- const { result } = await api.post(
- {
- url: "/users",
- data,
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/deleteCertificate.ts b/frontend/src/api/npm/deleteCertificate.ts
deleted file mode 100644
index 75afabe97..000000000
--- a/frontend/src/api/npm/deleteCertificate.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import * as api from "./base";
-
-export async function deleteCertificate(
- id: number,
- abortController?: AbortController,
-): Promise {
- const { result } = await api.del(
- {
- url: `/certificates/${id}`,
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/getAccessLists.ts b/frontend/src/api/npm/getAccessLists.ts
deleted file mode 100644
index 7fb846594..000000000
--- a/frontend/src/api/npm/getAccessLists.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import * as api from "./base";
-import { AccessListsResponse } from "./responseTypes";
-
-export async function getAccessLists(
- offset = 0,
- limit = 10,
- sort?: string,
- filters?: { [key: string]: string },
- abortController?: AbortController,
-): Promise {
- const { result } = await api.get(
- {
- url: "access-lists",
- params: { limit, offset, sort, ...filters },
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/getCertificate.ts b/frontend/src/api/npm/getCertificate.ts
deleted file mode 100644
index 32cc84d91..000000000
--- a/frontend/src/api/npm/getCertificate.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import * as api from "./base";
-import { Certificate } from "./models";
-
-export async function getCertificate(
- id: number,
- params = {},
-): Promise {
- const { result } = await api.get({
- url: `/certificates/${id}`,
- params,
- });
- return result;
-}
diff --git a/frontend/src/api/npm/getCertificateAuthorities.ts b/frontend/src/api/npm/getCertificateAuthorities.ts
deleted file mode 100644
index e956bf529..000000000
--- a/frontend/src/api/npm/getCertificateAuthorities.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import * as api from "./base";
-import { CertificateAuthoritiesResponse } from "./responseTypes";
-
-export async function getCertificateAuthorities(
- offset = 0,
- limit = 10,
- sort?: string,
- filters?: { [key: string]: string },
- abortController?: AbortController,
-): Promise {
- const { result } = await api.get(
- {
- url: "certificate-authorities",
- params: { limit, offset, sort, ...filters },
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/getCertificateAuthority.ts b/frontend/src/api/npm/getCertificateAuthority.ts
deleted file mode 100644
index 10674f14a..000000000
--- a/frontend/src/api/npm/getCertificateAuthority.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import * as api from "./base";
-import { CertificateAuthority } from "./models";
-
-export async function getCertificateAuthority(
- id: number,
- params = {},
-): Promise {
- const { result } = await api.get({
- url: `/certificate-authorities/${id}`,
- params,
- });
- return result;
-}
diff --git a/frontend/src/api/npm/getCertificates.ts b/frontend/src/api/npm/getCertificates.ts
deleted file mode 100644
index c8df51f48..000000000
--- a/frontend/src/api/npm/getCertificates.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import * as api from "./base";
-import { CertificatesResponse } from "./responseTypes";
-
-export async function getCertificates(
- offset = 0,
- limit = 10,
- sort?: string,
- filters?: { [key: string]: string },
- abortController?: AbortController,
-): Promise {
- const { result } = await api.get(
- {
- url: "certificates",
- params: { limit, offset, sort, expand: "user", ...filters },
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/getDNSProvider.ts b/frontend/src/api/npm/getDNSProvider.ts
deleted file mode 100644
index 380e5d786..000000000
--- a/frontend/src/api/npm/getDNSProvider.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import * as api from "./base";
-import { DNSProvider } from "./models";
-
-export async function getDNSProvider(
- id: number,
- params = {},
-): Promise {
- const { result } = await api.get({
- url: `/dns-providers/${id}`,
- params,
- });
- return result;
-}
diff --git a/frontend/src/api/npm/getDNSProviders.ts b/frontend/src/api/npm/getDNSProviders.ts
deleted file mode 100644
index 51028a566..000000000
--- a/frontend/src/api/npm/getDNSProviders.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import * as api from "./base";
-import { DNSProvidersResponse } from "./responseTypes";
-
-export async function getDNSProviders(
- offset = 0,
- limit = 10,
- sort?: string,
- filters?: { [key: string]: string },
- abortController?: AbortController,
-): Promise {
- const { result } = await api.get(
- {
- url: "dns-providers",
- params: { limit, offset, sort, ...filters },
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/getDNSProvidersAcmesh.ts b/frontend/src/api/npm/getDNSProvidersAcmesh.ts
deleted file mode 100644
index b46d55f9a..000000000
--- a/frontend/src/api/npm/getDNSProvidersAcmesh.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import * as api from "./base";
-import { DNSProvidersAcmesh } from "./models";
-
-export async function getDNSProvidersAcmesh(
- abortController?: AbortController,
-): Promise {
- const { result } = await api.get(
- {
- url: "dns-providers/acmesh",
- // Important for this endpoint:
- skipCamelize: true,
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/getHealth.ts b/frontend/src/api/npm/getHealth.ts
deleted file mode 100644
index 9c6d77b91..000000000
--- a/frontend/src/api/npm/getHealth.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import * as api from "./base";
-import { HealthResponse } from "./responseTypes";
-
-export async function getHealth(
- abortController?: AbortController,
-): Promise {
- const { result } = await api.get(
- {
- url: "",
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/getHosts.ts b/frontend/src/api/npm/getHosts.ts
deleted file mode 100644
index 4529fb8e3..000000000
--- a/frontend/src/api/npm/getHosts.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import * as api from "./base";
-import { HostsResponse } from "./responseTypes";
-
-export async function getHosts(
- offset = 0,
- limit = 10,
- sort?: string,
- filters?: { [key: string]: string },
- abortController?: AbortController,
-): Promise {
- const { result } = await api.get(
- {
- url: "hosts",
- params: { limit, offset, sort, expand: "user,certificate", ...filters },
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/getNginxTemplates.ts b/frontend/src/api/npm/getNginxTemplates.ts
deleted file mode 100644
index 15d8e2873..000000000
--- a/frontend/src/api/npm/getNginxTemplates.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import * as api from "./base";
-import { NginxTemplatesResponse } from "./responseTypes";
-
-export async function getNginxTemplates(
- offset = 0,
- limit = 10,
- sort?: string,
- filters?: { [key: string]: string },
- abortController?: AbortController,
-): Promise {
- const { result } = await api.get(
- {
- url: "nginx-templates",
- params: { limit, offset, sort, ...filters },
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/getSSEToken.ts b/frontend/src/api/npm/getSSEToken.ts
deleted file mode 100644
index c8a2a602f..000000000
--- a/frontend/src/api/npm/getSSEToken.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import * as api from "./base";
-import { TokenResponse } from "./responseTypes";
-
-export async function getSSEToken(
- abortController?: AbortController,
-): Promise {
- const { result } = await api.post(
- {
- url: "/auth/sse",
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/getSettings.ts b/frontend/src/api/npm/getSettings.ts
deleted file mode 100644
index 6e07806d9..000000000
--- a/frontend/src/api/npm/getSettings.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import * as api from "./base";
-import { SettingsResponse } from "./responseTypes";
-
-export async function getSettings(
- offset = 0,
- limit = 10,
- sort?: string,
- filters?: { [key: string]: string },
- abortController?: AbortController,
-): Promise {
- const { result } = await api.get(
- {
- url: "settings",
- params: { limit, offset, sort, ...filters },
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/getToken.ts b/frontend/src/api/npm/getToken.ts
deleted file mode 100644
index 750016ec6..000000000
--- a/frontend/src/api/npm/getToken.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import * as api from "./base";
-import { TokenResponse } from "./responseTypes";
-
-interface Options {
- payload: {
- type: string;
- identity: string;
- secret: string;
- };
-}
-
-export async function getToken(
- { payload }: Options,
- abortController?: AbortController,
-): Promise {
- const { result } = await api.post(
- {
- url: "/auth",
- data: payload,
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/getUpstreamNginxConfig.ts b/frontend/src/api/npm/getUpstreamNginxConfig.ts
deleted file mode 100644
index f106344d4..000000000
--- a/frontend/src/api/npm/getUpstreamNginxConfig.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import * as api from "./base";
-
-export async function getUpstreamNginxConfig(
- id: number,
- params = {},
-): Promise {
- const { result } = await api.get({
- url: `/upstreams/${id}/nginx-config`,
- params,
- });
- return result;
-}
diff --git a/frontend/src/api/npm/getUpstreams.ts b/frontend/src/api/npm/getUpstreams.ts
deleted file mode 100644
index e64c29e9d..000000000
--- a/frontend/src/api/npm/getUpstreams.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import * as api from "./base";
-import { UpstreamsResponse } from "./responseTypes";
-
-export async function getUpstreams(
- offset = 0,
- limit = 10,
- sort?: string,
- filters?: { [key: string]: string },
- abortController?: AbortController,
-): Promise {
- const { result } = await api.get(
- {
- url: "upstreams",
- params: { limit, offset, sort, expand: "user", ...filters },
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/getUser.ts b/frontend/src/api/npm/getUser.ts
deleted file mode 100644
index a6485f915..000000000
--- a/frontend/src/api/npm/getUser.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import * as api from "./base";
-import { User } from "./models";
-
-export async function getUser(
- id: number | string = "me",
- params = {},
-): Promise {
- const userId = id ? id : "me";
- const { result } = await api.get({
- url: `/users/${userId}`,
- params,
- });
- return result;
-}
diff --git a/frontend/src/api/npm/getUsers.ts b/frontend/src/api/npm/getUsers.ts
deleted file mode 100644
index 89b163d5e..000000000
--- a/frontend/src/api/npm/getUsers.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import * as api from "./base";
-import { UsersResponse } from "./responseTypes";
-
-export async function getUsers(
- offset = 0,
- limit = 10,
- sort?: string,
- filters?: { [key: string]: string },
- abortController?: AbortController,
-): Promise {
- const { result } = await api.get(
- {
- url: "users",
- params: { limit, offset, sort, expand: "capabilities", ...filters },
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/index.ts b/frontend/src/api/npm/index.ts
deleted file mode 100644
index 256384bf8..000000000
--- a/frontend/src/api/npm/index.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-export * from "./createCertificate";
-export * from "./createCertificateAuthority";
-export * from "./createDNSProvider";
-export * from "./createUser";
-export * from "./deleteCertificate";
-export * from "./getAccessLists";
-export * from "./getCertificate";
-export * from "./getCertificateAuthorities";
-export * from "./getCertificateAuthority";
-export * from "./getCertificates";
-export * from "./getDNSProvider";
-export * from "./getDNSProviders";
-export * from "./getDNSProvidersAcmesh";
-export * from "./getHealth";
-export * from "./getHosts";
-export * from "./getNginxTemplates";
-export * from "./getSettings";
-export * from "./getSSEToken";
-export * from "./getToken";
-export * from "./getUpstreamNginxConfig";
-export * from "./getUpstreams";
-export * from "./getUser";
-export * from "./getUsers";
-export * from "./helpers";
-export * from "./models";
-export * from "./refreshToken";
-export * from "./renewCertificate";
-export * from "./responseTypes";
-export * from "./setAuth";
-export * from "./setCertificate";
-export * from "./setCertificateAuthority";
-export * from "./setDNSProvider";
-export * from "./setUser";
-export * from "./setupDatabase";
diff --git a/frontend/src/api/npm/models.ts b/frontend/src/api/npm/models.ts
deleted file mode 100644
index 75e86089c..000000000
--- a/frontend/src/api/npm/models.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-export interface Sort {
- field: string;
- direction: "ASC" | "DESC";
-}
-
-export interface UserAuth {
- id: number;
- userId: number;
- type: string;
- createdOn: number;
- updatedOn: number;
-}
-
-export interface User {
- id: number;
- name: string;
- email: string;
- createdOn: number;
- updatedOn: number;
- gravatarUrl: string;
- isDisabled: boolean;
- notifications: Notification[];
- capabilities?: string[];
- auth?: UserAuth;
-}
-
-export interface Notification {
- title: string;
- seen: boolean;
-}
-
-export interface Setting {
- id: number;
- createdOn: number;
- modifiedOn: number;
- name: string;
- value: any;
-}
-
-export interface AccessList {
- id: number;
- createdOn: number;
- modifiedOn: number;
- userId: number;
- name: string;
- meta: any;
-}
-
-// TODO: copy pasta not right
-export interface Certificate {
- id: number;
- createdOn: number;
- modifiedOn: number;
- expiresOn: number | null;
- type: string;
- userId: number;
- certificateAuthorityId: number;
- dnsProviderId: number;
- name: string;
- domainNames: string[];
- status: string;
- errorMessage: string;
- isEcc: boolean;
-}
-
-export interface CertificateAuthority {
- id: number;
- createdOn: number;
- modifiedOn: number;
- name: string;
- acmeshServer: string;
- caBundle: string;
- maxDomains: number;
- isWildcardSupported: boolean;
- isReadonly: boolean;
-}
-
-export interface DNSProvider {
- id: number;
- createdOn: number;
- modifiedOn: number;
- userId: number;
- name: string;
- acmeshName: string;
- dnsSleep: number;
- meta: any;
-}
-
-export interface DNSProvidersAcmeshProperty {
- title: string;
- type: string;
- additionalProperties: boolean;
- minimum: number;
- maximum: number;
- minLength: number;
- maxLength: number;
- pattern: string;
- isSecret: boolean;
-}
-
-export interface DNSProvidersAcmesh {
- title: string;
- type: string;
- additionalProperties: boolean;
- minProperties: number;
- required: string[];
- properties: any;
-}
-
-export interface Host {
- id: number;
- createdOn: number;
- modifiedOn: number;
- userId: number;
- type: string;
- nginxTemplateId: number;
- listenInterface: number;
- domainNames: string[];
- upstreamId: number;
- certificateId: number;
- accessListId: number;
- sslForced: boolean;
- cachingEnabled: boolean;
- blockExploits: boolean;
- allowWebsocketUpgrade: boolean;
- http2Support: boolean;
- hstsEnabled: boolean;
- hstsSubdomains: boolean;
- paths: string;
- advancedConfig: string;
- isDisabled: boolean;
-}
-
-export interface NginxTemplate {
- id: number;
- createdOn: number;
- modifiedOn: number;
- userId: number;
- type: string;
- template: string;
-}
-
-export interface Upstream {
- // todo
- id: number;
- createdOn: number;
- modifiedOn: number;
- userId: number;
- type: string;
- nginxTemplateId: number;
- listenInterface: number;
- domainNames: string[];
- upstreamId: number;
- certificateId: number;
- accessListId: number;
- sslForced: boolean;
- cachingEnabled: boolean;
- blockExploits: boolean;
- allowWebsocketUpgrade: boolean;
- http2Support: boolean;
- hstsEnabled: boolean;
- hstsSubdomains: boolean;
- paths: string;
- advancedConfig: string;
- isDisabled: boolean;
-}
-
-export interface SSEMessage {
- lang?: string;
- langParams?: string;
- type?: "info" | "warning" | "success" | "error" | "loading";
- affects?: string | string[];
-}
diff --git a/frontend/src/api/npm/refreshToken.ts b/frontend/src/api/npm/refreshToken.ts
deleted file mode 100644
index 7f448f565..000000000
--- a/frontend/src/api/npm/refreshToken.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import * as api from "./base";
-import { TokenResponse } from "./responseTypes";
-
-export async function refreshToken(
- abortController?: AbortController,
-): Promise {
- const { result } = await api.post(
- {
- url: "/auth/refresh",
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/renewCertificate.ts b/frontend/src/api/npm/renewCertificate.ts
deleted file mode 100644
index a7b513c44..000000000
--- a/frontend/src/api/npm/renewCertificate.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import * as api from "./base";
-import { Certificate } from "./models";
-
-export async function renewCertificate(
- id: number,
- abortController?: AbortController,
-): Promise {
- const { result } = await api.post(
- {
- url: `/certificates/${id}/renew`,
- },
- abortController,
- );
- return result;
-}
diff --git a/frontend/src/api/npm/responseTypes.ts b/frontend/src/api/npm/responseTypes.ts
deleted file mode 100644
index 5e88aefa7..000000000
--- a/frontend/src/api/npm/responseTypes.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import {
- AccessList,
- Certificate,
- CertificateAuthority,
- DNSProvider,
- Host,
- NginxTemplate,
- Setting,
- Sort,
- User,
- Upstream,
-} from "./models";
-
-export interface BaseResponse {
- total: number;
- offset: number;
- limit: number;
- sort: Sort[];
-}
-
-export interface HealthResponse {
- commit: string;
- dbSetup: boolean;
- errorReporting: boolean;
- healthy: boolean;
- setup: boolean;
- version: string;
-}
-
-export interface TokenResponse {
- expires: number;
- token: string;
-}
-
-export interface SettingsResponse extends BaseResponse {
- items: Setting[];
-}
-
-export interface AccessListsResponse extends BaseResponse {
- items: AccessList[];
-}
-
-export interface CertificatesResponse extends BaseResponse {
- items: Certificate[];
-}
-
-export interface CertificateAuthoritiesResponse extends BaseResponse {
- items: CertificateAuthority[];
-}
-
-export interface UsersResponse extends BaseResponse {
- items: User[];
-}
-
-export interface DNSProvidersResponse extends BaseResponse {
- items: DNSProvider[];
-}
-
-export interface HostsResponse extends BaseResponse {
- items: Host[];
-}
-
-export interface NginxTemplatesResponse extends BaseResponse {
- items: NginxTemplate[];
-}
-
-export interface UpstreamsResponse extends BaseResponse {
- items: Upstream[];
-}
diff --git a/frontend/src/api/npm/setAuth.ts b/frontend/src/api/npm/setAuth.ts
deleted file mode 100644
index f0a7049e0..000000000
--- a/frontend/src/api/npm/setAuth.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import * as api from "./base";
-import { UserAuth } from "./models";
-
-export async function setAuth(
- id: number | string = "me",
- data: any,
-): Promise {
- const userId = id ? id : "me";
- if (data.id) {
- delete data.id;
- }
-
- const { result } = await api.post({
- url: `/users/${userId}/auth`,
- data,
- });
- return result;
-}
diff --git a/frontend/src/api/npm/setCertificate.ts b/frontend/src/api/npm/setCertificate.ts
deleted file mode 100644
index b5bb998cb..000000000
--- a/frontend/src/api/npm/setCertificate.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import * as api from "./base";
-import { Certificate } from "./models";
-
-export async function setCertificate(
- id: number,
- data: any,
-): Promise {
- if (data.id) {
- delete data.id;
- }
-
- const { result } = await api.put({
- url: `/certificates/${id}`,
- data,
- });
- return result;
-}
diff --git a/frontend/src/api/npm/setCertificateAuthority.ts b/frontend/src/api/npm/setCertificateAuthority.ts
deleted file mode 100644
index 1719e2edd..000000000
--- a/frontend/src/api/npm/setCertificateAuthority.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import * as api from "./base";
-import { CertificateAuthority } from "./models";
-
-export async function setCertificateAuthority(
- id: number,
- data: any,
-): Promise {
- if (data.id) {
- delete data.id;
- }
-
- const { result } = await api.put({
- url: `/certificate-authorities/${id}`,
- data,
- });
- return result;
-}
diff --git a/frontend/src/api/npm/setDNSProvider.ts b/frontend/src/api/npm/setDNSProvider.ts
deleted file mode 100644
index 5ae93a91c..000000000
--- a/frontend/src/api/npm/setDNSProvider.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { decamelizeKeys } from "humps";
-
-import * as api from "./base";
-import { DNSProvider } from "./models";
-
-export async function setDNSProvider(
- id: number,
- data: any,
-): Promise {
- if (data.id) {
- delete data.id;
- }
-
- // Because the meta property of the data should not be decamelized,
- // we're going to decamelize the rest here instead of in base.ts
- const dcData: any = decamelizeKeys(data);
- if (typeof data.meta !== "undefined") {
- dcData.meta = data.meta;
- }
-
- const { result } = await api.put({
- url: `/dns-providers/${id}`,
- data: dcData,
- skipCamelize: true,
- skipDecamelize: true,
- });
- return result;
-}
diff --git a/frontend/src/api/npm/setUser.ts b/frontend/src/api/npm/setUser.ts
deleted file mode 100644
index 743dba7a9..000000000
--- a/frontend/src/api/npm/setUser.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import * as api from "./base";
-import { User } from "./models";
-
-export async function setUser(
- id: number | string = "me",
- data: any,
-): Promise {
- const userId = id ? id : "me";
- if (data.id) {
- delete data.id;
- }
-
- const { result } = await api.put({
- url: `/users/${userId}`,
- data,
- });
- return result;
-}
diff --git a/frontend/src/assets/logo-256.png b/frontend/src/assets/logo-256.png
deleted file mode 100644
index 2bfb661dc..000000000
Binary files a/frontend/src/assets/logo-256.png and /dev/null differ
diff --git a/frontend/src/assets/logo-text-vertical-grey.png b/frontend/src/assets/logo-text-vertical-grey.png
deleted file mode 100644
index 70273171a..000000000
Binary files a/frontend/src/assets/logo-text-vertical-grey.png and /dev/null differ
diff --git a/frontend/src/components/Button.tsx b/frontend/src/components/Button.tsx
new file mode 100644
index 000000000..6d02f9314
--- /dev/null
+++ b/frontend/src/components/Button.tsx
@@ -0,0 +1,64 @@
+import cn from "classnames";
+import type { ReactNode } from "react";
+
+interface Props {
+ children: ReactNode;
+ className?: string;
+ type?: "button" | "submit";
+ actionType?: "primary" | "secondary" | "success" | "warning" | "danger" | "info" | "light" | "dark";
+ variant?: "ghost" | "outline" | "pill" | "square" | "action";
+ size?: "sm" | "md" | "lg" | "xl";
+ fullWidth?: boolean;
+ isLoading?: boolean;
+ disabled?: boolean;
+ color?:
+ | "blue"
+ | "azure"
+ | "indigo"
+ | "purple"
+ | "pink"
+ | "red"
+ | "orange"
+ | "yellow"
+ | "lime"
+ | "green"
+ | "teal"
+ | "cyan";
+ onClick?: () => void;
+}
+function Button({
+ children,
+ className,
+ onClick,
+ type,
+ actionType,
+ variant,
+ size,
+ color,
+ fullWidth,
+ isLoading,
+ disabled,
+}: Props) {
+ const myOnClick = () => {
+ !isLoading && onClick && onClick();
+ };
+
+ const cns = cn(
+ "btn",
+ className,
+ actionType && `btn-${actionType}`,
+ variant && `btn-${variant}`,
+ size && `btn-${size}`,
+ color && `btn-${color}`,
+ fullWidth && "w-100",
+ isLoading && "btn-loading",
+ );
+
+ return (
+
+ );
+}
+
+export { Button };
diff --git a/frontend/src/components/EmptyData.tsx b/frontend/src/components/EmptyData.tsx
new file mode 100644
index 000000000..104c8a361
--- /dev/null
+++ b/frontend/src/components/EmptyData.tsx
@@ -0,0 +1,64 @@
+import type { Table as ReactTable, RowData } from "@tanstack/react-table";
+import cn from "classnames";
+import type { ReactNode } from "react";
+import { Button, HasPermission } from "src/components";
+import type { Features } from "src/components/Table/features";
+import { T } from "src/locale";
+import { type ADMIN, MANAGE, type Permission, type Section } from "src/modules/Permissions";
+
+interface Props {
+ tableInstance: ReactTable;
+ onNew?: () => void;
+ isFiltered?: boolean;
+ object: string;
+ objects: string;
+ color?: string;
+ customAddBtn?: ReactNode;
+ permissionSection?: Section | typeof ADMIN;
+ permission?: Permission;
+}
+function EmptyData({
+ tableInstance,
+ onNew,
+ isFiltered,
+ object,
+ objects,
+ color = "primary",
+ customAddBtn,
+ permissionSection,
+ permission,
+}: Props) {
+ return (
+
+
+
+ {isFiltered ? (
+
+
+
+ ) : (
+ <>
+
+
+
+
+
+
+
+ {customAddBtn ? (
+ customAddBtn
+ ) : (
+
+ )}
+
+ >
+ )}
+
+ |
+
+ );
+}
+
+export { EmptyData };
diff --git a/frontend/src/components/EmptyList.tsx b/frontend/src/components/EmptyList.tsx
deleted file mode 100644
index 2f6a83b58..000000000
--- a/frontend/src/components/EmptyList.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { ReactNode } from "react";
-
-import { Box, Heading, Text } from "@chakra-ui/react";
-
-interface EmptyListProps {
- title: string;
- summary: string;
- createButton?: ReactNode;
-}
-
-function EmptyList({ title, summary, createButton }: EmptyListProps) {
- return (
-
-
- {title}
-
- {summary}
- {createButton}
-
- );
-}
-
-export { EmptyList };
diff --git a/frontend/src/components/ErrorNotFound.tsx b/frontend/src/components/ErrorNotFound.tsx
new file mode 100644
index 000000000..a162d1cd6
--- /dev/null
+++ b/frontend/src/components/ErrorNotFound.tsx
@@ -0,0 +1,25 @@
+import { useNavigate } from "react-router-dom";
+import { Button } from "src/components";
+import { T } from "src/locale";
+
+export function ErrorNotFound() {
+ const navigate = useNavigate();
+
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+}
diff --git a/frontend/src/components/Flag/Flag.tsx b/frontend/src/components/Flag/Flag.tsx
deleted file mode 100644
index 6f264f791..000000000
--- a/frontend/src/components/Flag/Flag.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import { Box } from "@chakra-ui/layout";
-import { hasFlag } from "country-flag-icons";
-// @ts-ignore Creating a typing for a subfolder is not easily possible
-import Flags from "country-flag-icons/react/3x2";
-
-interface FlagProps {
- /**
- * Additional Class
- */
- className?: string;
- /**
- * Two letter country code of flag
- */
- countryCode: string;
-}
-function Flag({ className, countryCode }: FlagProps) {
- countryCode = countryCode.toUpperCase();
-
- if (hasFlag(countryCode)) {
- // @ts-ignore have to do this because of above
- const FlagElement = Flags[countryCode] as any;
- return (
-
- );
- } else {
- console.error(`No flag for country ${countryCode} found!`);
-
- return ;
- }
-}
-
-export { Flag };
diff --git a/frontend/src/components/Flag/index.ts b/frontend/src/components/Flag/index.ts
deleted file mode 100644
index 62845cc19..000000000
--- a/frontend/src/components/Flag/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./Flag";
diff --git a/frontend/src/components/Footer.tsx b/frontend/src/components/Footer.tsx
deleted file mode 100644
index d4c21174c..000000000
--- a/frontend/src/components/Footer.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import {
- Box,
- Container,
- Link,
- Stack,
- Text,
- Tooltip,
- useColorModeValue,
-} from "@chakra-ui/react";
-
-import { intl } from "src/locale";
-
-function Footer() {
- return (
-
-
-
- {intl.formatMessage(
- { id: "footer.copyright" },
- { year: new Date().getFullYear() },
- )}
-
-
-
- {intl.formatMessage({ id: "footer.userguide" })}
-
-
- {intl.formatMessage({ id: "footer.changelog" })}
-
-
- {intl.formatMessage({ id: "footer.github" })}
-
-
-
- v{import.meta.env.VITE_APP_VERSION}
-
-
-
-
-
- );
-}
-
-export { Footer };
diff --git a/frontend/src/components/Form/AccessClientFields.tsx b/frontend/src/components/Form/AccessClientFields.tsx
new file mode 100644
index 000000000..bac445840
--- /dev/null
+++ b/frontend/src/components/Form/AccessClientFields.tsx
@@ -0,0 +1,134 @@
+import { IconX } from "@tabler/icons-react";
+import cn from "classnames";
+import { useFormikContext } from "formik";
+import { useState } from "react";
+import type { AccessListClient } from "src/api/backend";
+import { intl, T } from "src/locale";
+
+interface Props {
+ initialValues: AccessListClient[];
+ name?: string;
+}
+export function AccessClientFields({ initialValues, name = "clients" }: Props) {
+ const [values, setValues] = useState(initialValues || []);
+ const { setFieldValue } = useFormikContext();
+
+ const blankClient: AccessListClient = { directive: "allow", address: "" };
+
+ if (values?.length === 0) {
+ setValues([blankClient]);
+ }
+
+ const handleAdd = () => {
+ setValues([...values, blankClient]);
+ };
+
+ const handleRemove = (idx: number) => {
+ const newValues = values.filter((_: AccessListClient, i: number) => i !== idx);
+ if (newValues.length === 0) {
+ newValues.push(blankClient);
+ }
+ setValues(newValues);
+ setFormField(newValues);
+ };
+
+ const handleChange = (idx: number, field: string, fieldValue: string) => {
+ const newValues = values.map((v: AccessListClient, i: number) =>
+ i === idx ? { ...v, [field]: fieldValue } : v,
+ );
+ setValues(newValues);
+ setFormField(newValues);
+ };
+
+ const setFormField = (newValues: AccessListClient[]) => {
+ const filtered = newValues.filter((v: AccessListClient) => v?.address?.trim() !== "");
+ setFieldValue(name, filtered);
+ };
+
+ return (
+ <>
+
+
+
+ {values.map((client: AccessListClient, idx: number) => (
+
+
+
+
+
+
+ handleChange(idx, "address", e.target.value)}
+ placeholder={intl.formatMessage({ id: "access-list.rule-source.placeholder" })}
+ />
+
+
+
+
+
+
+ ))}
+
+
+
+
+ >
+ );
+}
diff --git a/frontend/src/components/Form/AccessField.tsx b/frontend/src/components/Form/AccessField.tsx
new file mode 100644
index 000000000..ef955a033
--- /dev/null
+++ b/frontend/src/components/Form/AccessField.tsx
@@ -0,0 +1,122 @@
+import { IconArrowBackUp, IconLock, IconLockOpen2 } from "@tabler/icons-react";
+import { Field, useFormikContext } from "formik";
+import type { ReactNode } from "react";
+import Select, { type ActionMeta, components, type OptionProps } from "react-select";
+import type { AccessList } from "src/api/backend";
+import { useLocaleState } from "src/context";
+import { useAccessLists } from "src/hooks";
+import { formatDateTime, intl, T } from "src/locale";
+
+interface AccessOption {
+ readonly value: number;
+ readonly label: string;
+ readonly subLabel: string;
+ readonly icon: ReactNode;
+}
+
+const Option = (props: OptionProps) => {
+ return (
+
+
+
+ {props.data.icon} {props.data.label}
+
+
{props.data.subLabel}
+
+
+ );
+};
+
+interface Props {
+ id?: string;
+ name?: string;
+ label?: string;
+ onFormChange?: (value: number) => void;
+ // When set, the 0 option inherits the host's access list instead of being public
+ inheritHost?: boolean;
+}
+export function AccessField({
+ name = "accessListId",
+ label = "access-list",
+ id = "accessListId",
+ onFormChange,
+ inheritHost = false,
+}: Props) {
+ const { locale } = useLocaleState();
+ const { isLoading, isError, error, data } = useAccessLists(["owner", "items", "clients"]);
+ const { setFieldValue } = useFormikContext();
+
+ const handleChange = (newValue: any, _actionMeta: ActionMeta) => {
+ setFieldValue(name, newValue?.value);
+ if (onFormChange) {
+ onFormChange(newValue?.value ?? 0);
+ }
+ };
+
+ const options: AccessOption[] =
+ data?.map((item: AccessList) => ({
+ value: item.id || 0,
+ label: item.name,
+ subLabel: intl.formatMessage(
+ { id: "access-list.subtitle" },
+ {
+ users: item?.items?.length,
+ rules: item?.clients?.length,
+ date: item?.createdOn ? formatDateTime(item?.createdOn, locale) : "N/A",
+ },
+ ),
+ icon: ,
+ })) || [];
+
+ // Public or inherit option
+ options?.unshift(
+ inheritHost
+ ? {
+ value: 0,
+ label: intl.formatMessage({ id: "access-list.inherit" }),
+ subLabel: intl.formatMessage({ id: "access-list.inherit.subtitle" }),
+ icon: ,
+ }
+ : {
+ value: 0,
+ label: intl.formatMessage({ id: "access-list.public" }),
+ subLabel: intl.formatMessage({ id: "access-list.public.subtitle" }),
+ icon: ,
+ },
+ );
+
+ return (
+
+ {({ field, form }: any) => (
+
+
+ {isLoading ?
: null}
+ {isError ?
{`${error}`}
: null}
+ {!isLoading && !isError ? (
+
+ )}
+
+ );
+}
diff --git a/frontend/src/components/Form/BasicAuthFields.tsx b/frontend/src/components/Form/BasicAuthFields.tsx
new file mode 100644
index 000000000..d8d33d159
--- /dev/null
+++ b/frontend/src/components/Form/BasicAuthFields.tsx
@@ -0,0 +1,102 @@
+import { IconX } from "@tabler/icons-react";
+import { useFormikContext } from "formik";
+import { useState } from "react";
+import type { AccessListItem } from "src/api/backend";
+import { T } from "src/locale";
+
+interface Props {
+ initialValues: AccessListItem[];
+ name?: string;
+}
+export function BasicAuthFields({ initialValues, name = "items" }: Props) {
+ const [values, setValues] = useState(initialValues || []);
+ const { setFieldValue } = useFormikContext();
+
+ const blankItem: AccessListItem = { username: "", password: "" };
+
+ if (values?.length === 0) {
+ setValues([blankItem]);
+ }
+
+ const handleAdd = () => {
+ setValues([...values, blankItem]);
+ };
+
+ const handleRemove = (idx: number) => {
+ const newValues = values.filter((_: AccessListItem, i: number) => i !== idx);
+ if (newValues.length === 0) {
+ newValues.push(blankItem);
+ }
+ setValues(newValues);
+ setFormField(newValues);
+ };
+
+ const handleChange = (idx: number, field: string, fieldValue: string) => {
+ const newValues = values.map((v: AccessListItem, i: number) => (i === idx ? { ...v, [field]: fieldValue } : v));
+ setValues(newValues);
+ setFormField(newValues);
+ };
+
+ const setFormField = (newValues: AccessListItem[]) => {
+ const filtered = newValues.filter((v: AccessListItem) => v?.username?.trim() !== "");
+ setFieldValue(name, filtered);
+ };
+
+ return (
+ <>
+
+ {values.map((item: AccessListItem, idx: number) => (
+
+
+ handleChange(idx, "username", e.target.value)}
+ />
+
+
+ iv.username === item.username).length > 0
+ ? "••••••••"
+ : ""
+ }
+ onChange={(e) => handleChange(idx, "password", e.target.value)}
+ />
+
+
+
+
+
+ ))}
+
+
+
+ >
+ );
+}
diff --git a/frontend/src/components/Form/DNSProviderFields.module.css b/frontend/src/components/Form/DNSProviderFields.module.css
new file mode 100644
index 000000000..fdf04b018
--- /dev/null
+++ b/frontend/src/components/Form/DNSProviderFields.module.css
@@ -0,0 +1,8 @@
+.dnsChallengeWarning {
+ border: 1px solid var(--tblr-orange-lt);
+ padding: 1rem;
+ border-radius: 0.375rem;
+ margin-top: 1rem;
+ background-color: var(--tblr-cyan-lt);
+}
+
diff --git a/frontend/src/components/Form/DNSProviderFields.tsx b/frontend/src/components/Form/DNSProviderFields.tsx
new file mode 100644
index 000000000..182654811
--- /dev/null
+++ b/frontend/src/components/Form/DNSProviderFields.tsx
@@ -0,0 +1,132 @@
+import { IconAlertTriangle } from "@tabler/icons-react";
+import CodeEditor from "@uiw/react-textarea-code-editor";
+import { Field, useFormikContext } from "formik";
+import { useState } from "react";
+import Select, { type ActionMeta } from "react-select";
+import type { DNSProvider } from "src/api/backend";
+import { useDnsProviders } from "src/hooks";
+import { intl, T } from "src/locale";
+import styles from "./DNSProviderFields.module.css";
+
+interface DNSProviderOption {
+ readonly value: string;
+ readonly label: string;
+ readonly credentials: string;
+}
+
+interface Props {
+ showBoundaryBox?: boolean;
+}
+export function DNSProviderFields({ showBoundaryBox = false }: Props) {
+ const { values, setFieldValue } = useFormikContext();
+ const { data: dnsProviders, isLoading } = useDnsProviders();
+ const [dnsProviderId, setDnsProviderId] = useState(null);
+
+ const v: any = values || {};
+
+ const handleChange = (newValue: any, _actionMeta: ActionMeta) => {
+ setFieldValue("meta.dnsProvider", newValue?.value);
+ setFieldValue("meta.dnsProviderCredentials", newValue?.credentials);
+ setDnsProviderId(newValue?.value);
+ };
+
+ const options: DNSProviderOption[] =
+ dnsProviders?.map((p: DNSProvider) => ({
+ value: p.id,
+ label: p.name,
+ credentials: p.credentials,
+ })) || [];
+
+ return (
+
+
+
+
+
+
+
+ {({ field }: any) => (
+
+
+
+
+ )}
+
+
+ {dnsProviderId ? (
+ <>
+
+ {({ field }: any) => (
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ )}
+
+
+ {({ field }: any) => (
+
+
+
+
+
+
+
+ )}
+
+ >
+ ) : null}
+
+ );
+}
diff --git a/frontend/src/components/Form/DomainNamesField.tsx b/frontend/src/components/Form/DomainNamesField.tsx
new file mode 100644
index 000000000..bdba2f2e2
--- /dev/null
+++ b/frontend/src/components/Form/DomainNamesField.tsx
@@ -0,0 +1,85 @@
+import { Field, useFormikContext } from "formik";
+import type { ReactNode } from "react";
+import type { ActionMeta, MultiValue } from "react-select";
+import CreatableSelect from "react-select/creatable";
+import { intl, T } from "src/locale";
+import { validateDomain, validateDomains } from "src/modules/Validations";
+
+type SelectOption = {
+ label: string;
+ value: string;
+ color?: string;
+};
+
+interface Props {
+ id?: string;
+ maxDomains?: number;
+ isWildcardPermitted?: boolean;
+ dnsProviderWildcardSupported?: boolean;
+ name?: string;
+ label?: string;
+ onChange?: (domains: string[]) => void;
+}
+export function DomainNamesField({
+ name = "domainNames",
+ label = "domain-names",
+ id = "domainNames",
+ maxDomains,
+ isWildcardPermitted = false,
+ dnsProviderWildcardSupported = false,
+ onChange,
+}: Props) {
+ const { setFieldValue } = useFormikContext();
+
+ const handleChange = (v: MultiValue, _actionMeta: ActionMeta) => {
+ const doms = v?.map((i: SelectOption) => {
+ return i.value;
+ });
+ setFieldValue(name, doms);
+ onChange?.(doms);
+ };
+
+ const helperTexts: ReactNode[] = [];
+ if (maxDomains) {
+ helperTexts.push();
+ }
+ if (!isWildcardPermitted) {
+ helperTexts.push();
+ } else if (!dnsProviderWildcardSupported) {
+ helperTexts.push();
+ }
+
+ return (
+
+ {({ field, form }: any) => (
+
+
+ ({ label: d, value: d }))}
+ />
+ {form.errors[field.name] && form.touched[field.name] ? (
+ {form.errors[field.name]}
+ ) : helperTexts.length ? (
+ helperTexts.map((i, idx) => (
+
+ {i}
+
+ ))
+ ) : null}
+
+ )}
+
+ );
+}
diff --git a/frontend/src/components/Form/LocationsFields.module.css b/frontend/src/components/Form/LocationsFields.module.css
new file mode 100644
index 000000000..9551e0d4e
--- /dev/null
+++ b/frontend/src/components/Form/LocationsFields.module.css
@@ -0,0 +1,51 @@
+/* card-active points --tblr-card-border-color at --tblr-primary, which both the
+ card outline and the card header's bottom border are drawn from. Tabler's
+ stylesheet is loaded after this one, so the override needs !important. */
+.locationCard {
+ --tblr-card-border-color: light-dark(var(--tblr-gray-200), var(--tblr-gray-700)) !important;
+}
+
+.filter {
+ max-width: 20rem;
+}
+
+/* The header is a plain toggle rather than a button-styled control, so that a
+ list of collapsed locations reads as rows instead of a stack of buttons. */
+.toggle {
+ display: flex;
+ flex: 1 1 auto;
+ align-self: stretch;
+ align-items: center;
+ min-width: 0;
+ padding: 0;
+ color: inherit;
+ text-align: left;
+ background: transparent;
+ border: 0;
+}
+
+.toggle:focus-visible {
+ outline: 2px solid var(--tblr-primary);
+ outline-offset: -2px;
+}
+
+/* Keeps the marker on one line next to the delete button, and lets it drop out
+ of the way before the path does when the row runs out of room. */
+.marker {
+ display: flex;
+ flex: 0 1 auto;
+ align-items: center;
+ overflow: hidden;
+ white-space: nowrap;
+}
+
+.path {
+ font-weight: 500;
+ white-space: nowrap;
+}
+
+.summary {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
diff --git a/frontend/src/components/Form/LocationsFields.tsx b/frontend/src/components/Form/LocationsFields.tsx
new file mode 100644
index 000000000..a0f64c239
--- /dev/null
+++ b/frontend/src/components/Form/LocationsFields.tsx
@@ -0,0 +1,345 @@
+import {
+ IconChevronDown,
+ IconChevronRight,
+ IconPlus,
+ IconSearch,
+ IconSettings,
+ IconTrash,
+ IconX,
+} from "@tabler/icons-react";
+import CodeEditor from "@uiw/react-textarea-code-editor";
+import cn from "classnames";
+import { useFormikContext } from "formik";
+import { useRef, useState } from "react";
+import type { ProxyLocation } from "src/api/backend";
+import { intl, T } from "src/locale";
+import { AccessField } from "./AccessField";
+import styles from "./LocationsFields.module.css";
+
+// Below this many locations the list is short enough to scan by eye, and the
+// filter would only take up space.
+const FILTER_THRESHOLD = 5;
+
+// Locations are identified by a client-side id rather than their array index,
+// so that expanded/advanced state stays with the right row when one is removed.
+interface Row {
+ id: number;
+ value: ProxyLocation;
+}
+
+interface Props {
+ initialValues: ProxyLocation[];
+ name?: string;
+}
+export function LocationsFields({ initialValues, name = "locations" }: Props) {
+ const [rows, setRows] = useState(() => (initialValues || []).map((value, id) => ({ id, value })));
+ const { setFieldValue } = useFormikContext();
+ const [expanded, setExpanded] = useState([]);
+ const [advVisible, setAdvVisible] = useState([]);
+ const [filter, setFilter] = useState("");
+ const nextId = useRef(rows.length);
+ const scrollToId = useRef(null);
+
+ const blankItem: ProxyLocation = {
+ path: "",
+ advancedConfig: "",
+ forwardScheme: "http",
+ forwardHost: "",
+ forwardPort: 80,
+ accessListId: 0,
+ };
+
+ const toggleExpanded = (id: number) => {
+ setExpanded(expanded.includes(id) ? expanded.filter((i) => i !== id) : [...expanded, id]);
+ };
+
+ const toggleAdvVisible = (id: number) => {
+ setAdvVisible(advVisible.includes(id) ? advVisible.filter((i) => i !== id) : [...advVisible, id]);
+ };
+
+ const handleAdd = () => {
+ const id = nextId.current++;
+ setRows([...rows, { id, value: blankItem }]);
+ // A new location starts empty, so open it and make sure an active filter
+ // doesn't hide the row that was just added.
+ setExpanded([...expanded, id]);
+ setFilter("");
+ scrollToId.current = id;
+ };
+
+ const handleRemove = (id: number) => {
+ const newRows = rows.filter((r: Row) => r.id !== id);
+ setRows(newRows);
+ setExpanded(expanded.filter((i) => i !== id));
+ setAdvVisible(advVisible.filter((i) => i !== id));
+ setFormField(newRows);
+ };
+
+ const handleChange = (id: number, field: string, fieldValue: string) => {
+ const newRows = rows.map((r: Row) => (r.id === id ? { ...r, value: { ...r.value, [field]: fieldValue } } : r));
+ setRows(newRows);
+ setFormField(newRows);
+ };
+
+ const handleAccessListChange = (id: number, accessListId: number) => {
+ const newRows = rows.map((r: Row) => (r.id === id ? { ...r, value: { ...r.value, accessListId } } : r));
+ setRows(newRows);
+ setFormField(newRows);
+ };
+
+ const setFormField = (newRows: Row[]) => {
+ const filtered = newRows.map((r: Row) => r.value).filter((v: ProxyLocation) => v?.path?.trim() !== "");
+ setFieldValue(name, filtered);
+ };
+
+ const forwardSummary = (item: ProxyLocation) => {
+ if (!item.forwardHost) {
+ return "";
+ }
+ return `${item.forwardScheme}://${item.forwardHost}${item.forwardPort ? `:${item.forwardPort}` : ""}`;
+ };
+
+ // Matches the path as well as the destination, so a location can be found by
+ // the host or port it forwards to and not just by its path.
+ const matchesFilter = (item: ProxyLocation, query: string) =>
+ [item.path, item.forwardScheme, item.forwardHost, item.forwardPort, forwardSummary(item)]
+ .join(" ")
+ .toLowerCase()
+ .includes(query);
+
+ const query = filter.trim().toLowerCase();
+ const visibleRows = query ? rows.filter((r: Row) => matchesFilter(r.value, query)) : rows;
+
+ if (rows.length === 0) {
+ return (
+
+
+
+ );
+ }
+
+ return (
+ <>
+
+ {rows.length >= FILTER_THRESHOLD && (
+
+
+
+
+ setFilter(e.target.value)}
+ />
+ {filter ? (
+
+ ) : null}
+
+ )}
+
+
+ {visibleRows.length === 0 ? (
+
+
+
+ ) : (
+ visibleRows.map((row: Row) => {
+ const item = row.value;
+ const isOpen = expanded.includes(row.id);
+ const bodyId = `location-body-${row.id}`;
+ return (
+ {
+ if (node && scrollToId.current === row.id) {
+ scrollToId.current = null;
+ node.scrollIntoView({ block: "nearest" });
+ }
+ }}
+ className={cn("card", "card-active", "mb-2", styles.locationCard)}
+ >
+
+
+ {item.advancedConfig ? (
+ // Deliberately the same icon as the advanced-config toggle in the
+ // body below, so the marker reads as "this row has that section
+ // filled in" rather than as a decoration of its own.
+
+
+
+ ) : null}
+
+
+ {isOpen && (
+
+
+
+
+ Location
+ handleChange(row.id, "path", e.target.value)}
+ />
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ handleChange(row.id, "forwardHost", e.target.value)
+ }
+ />
+
+
+
+
+
+
+ handleChange(row.id, "forwardPort", e.target.value)
+ }
+ />
+
+
+
+
handleAccessListChange(row.id, value)}
+ inheritHost
+ />
+ {advVisible.includes(row.id) && (
+
+ handleChange(row.id, "advancedConfig", e.target.value)}
+ style={{
+ fontFamily:
+ "ui-monospace,SFMono-Regular,SF Mono,Consolas,Liberation Mono,Menlo,monospace",
+ borderRadius: "0.3rem",
+ minHeight: "170px",
+ }}
+ />
+
+ )}
+
+ )}
+
+ );
+ })
+ )}
+ >
+ );
+}
diff --git a/frontend/src/components/Form/NginxConfigField.tsx b/frontend/src/components/Form/NginxConfigField.tsx
new file mode 100644
index 000000000..208a38486
--- /dev/null
+++ b/frontend/src/components/Form/NginxConfigField.tsx
@@ -0,0 +1,41 @@
+import CodeEditor from "@uiw/react-textarea-code-editor";
+import { Field } from "formik";
+import { intl, T } from "src/locale";
+
+interface Props {
+ id?: string;
+ name?: string;
+ label?: string;
+}
+export function NginxConfigField({
+ name = "advancedConfig",
+ label = "nginx-config.label",
+ id = "advancedConfig",
+}: Props) {
+ return (
+
+ {({ field }: any) => (
+
+
+
+
+ )}
+
+ );
+}
diff --git a/frontend/src/components/Form/SSLCertificateField.tsx b/frontend/src/components/Form/SSLCertificateField.tsx
new file mode 100644
index 000000000..6ab3ea92c
--- /dev/null
+++ b/frontend/src/components/Form/SSLCertificateField.tsx
@@ -0,0 +1,140 @@
+import { IconShield } from "@tabler/icons-react";
+import { Field, useFormikContext } from "formik";
+import Select, { type ActionMeta, components, type OptionProps } from "react-select";
+import type { Certificate } from "src/api/backend";
+import { useLocaleState } from "src/context";
+import { useCertificates } from "src/hooks";
+import { formatDateTime, intl, T } from "src/locale";
+
+interface CertOption {
+ readonly value: number | "new";
+ readonly label: string;
+ readonly subLabel: string;
+ readonly icon: React.ReactNode;
+}
+
+const Option = (props: OptionProps) => {
+ return (
+
+
+
+ {props.data.icon} {props.data.label}
+
+
{props.data.subLabel}
+
+
+ );
+};
+
+interface Props {
+ id?: string;
+ name?: string;
+ label?: string;
+ required?: boolean;
+ allowNew?: boolean;
+ forHttp?: boolean; // the sslForced, http2Support, hstsEnabled, hstsSubdomains fields
+}
+export function SSLCertificateField({
+ name = "certificateId",
+ label = "ssl-certificate",
+ id = "certificateId",
+ required,
+ allowNew,
+ forHttp = true,
+}: Props) {
+ const { locale } = useLocaleState();
+ const { isLoading, isError, error, data } = useCertificates();
+ const { values, setFieldValue } = useFormikContext();
+ const v: any = values || {};
+
+ const handleChange = (newValue: any, _actionMeta: ActionMeta) => {
+ setFieldValue(name, newValue?.value);
+ const {
+ sslForced,
+ http2Support,
+ hstsEnabled,
+ hstsSubdomains,
+ dnsChallenge,
+ dnsProvider,
+ dnsProviderCredentials,
+ propagationSeconds,
+ } = v;
+ if (forHttp && !newValue?.value) {
+ sslForced && setFieldValue("sslForced", false);
+ http2Support && setFieldValue("http2Support", false);
+ hstsEnabled && setFieldValue("hstsEnabled", false);
+ hstsSubdomains && setFieldValue("hstsSubdomains", false);
+ }
+ if (newValue?.value !== "new") {
+ dnsChallenge && setFieldValue("dnsChallenge", undefined);
+ dnsProvider && setFieldValue("dnsProvider", undefined);
+ dnsProviderCredentials && setFieldValue("dnsProviderCredentials", undefined);
+ propagationSeconds && setFieldValue("propagationSeconds", undefined);
+ }
+ };
+
+ const options: CertOption[] =
+ data?.map((cert: Certificate) => ({
+ value: cert.id,
+ label: cert.niceName,
+ subLabel: `${cert.provider === "letsencrypt" ? intl.formatMessage({ id: "lets-encrypt" }) : cert.provider} — ${intl.formatMessage({ id: "expires.on" }, { date: cert.expiresOn ? formatDateTime(cert.expiresOn, locale) : "N/A" })}`,
+ icon: ,
+ })) || [];
+
+ // Prepend the Add New option
+ if (allowNew) {
+ options?.unshift({
+ value: "new",
+ label: intl.formatMessage({ id: "certificates.request.title" }),
+ subLabel: intl.formatMessage({ id: "certificates.request.subtitle" }),
+ icon: ,
+ });
+ }
+
+ // Prepend the None option
+ if (!required) {
+ options?.unshift({
+ value: 0,
+ label: intl.formatMessage({ id: "certificate.none.title" }),
+ subLabel: forHttp
+ ? intl.formatMessage({ id: "certificate.none.subtitle.for-http" })
+ : intl.formatMessage({ id: "certificate.none.subtitle" }),
+ icon: ,
+ });
+ }
+
+ return (
+
+ {({ field, form }: any) => (
+
+
+ {isLoading ?
: null}
+ {isError ?
{`${error}`}
: null}
+ {!isLoading && !isError ? (
+
+ )}
+
+ );
+}
diff --git a/frontend/src/components/Form/SSLOptionsFields.tsx b/frontend/src/components/Form/SSLOptionsFields.tsx
new file mode 100644
index 000000000..ebfe38a65
--- /dev/null
+++ b/frontend/src/components/Form/SSLOptionsFields.tsx
@@ -0,0 +1,183 @@
+import cn from "classnames";
+import { Field, useFormikContext } from "formik";
+import { DNSProviderFields, DomainNamesField } from "src/components";
+import { T } from "src/locale";
+
+interface Props {
+ forHttp?: boolean; // the sslForced, http2Support, hstsEnabled, hstsSubdomains fields
+ forProxyHost?: boolean; // the advanced fields
+ forceDNSForNew?: boolean;
+ requireDomainNames?: boolean; // used for streams
+ color?: string;
+}
+export function SSLOptionsFields({
+ forHttp = true,
+ forProxyHost = false,
+ forceDNSForNew,
+ requireDomainNames,
+ color = "bg-cyan",
+}: Props) {
+ const { values, setFieldValue } = useFormikContext();
+ const v: any = values || {};
+
+ const newCertificate = v?.certificateId === "new";
+ const hasCertificate = newCertificate || (v?.certificateId && v?.certificateId > 0);
+ const { sslForced, http2Support, hstsEnabled, hstsSubdomains, trustForwardedProto, meta } = v;
+ const { dnsChallenge } = meta || {};
+
+ if (forceDNSForNew && newCertificate && !dnsChallenge) {
+ setFieldValue("meta.dnsChallenge", true);
+ }
+
+ const handleToggleChange = (e: any, fieldName: string) => {
+ setFieldValue(fieldName, e.target.checked);
+ if (fieldName === "meta.dnsChallenge" && !e.target.checked) {
+ setFieldValue("meta.dnsProvider", undefined);
+ setFieldValue("meta.dnsProviderCredentials", undefined);
+ setFieldValue("meta.propagationSeconds", undefined);
+ }
+ };
+
+ const toggleClasses = "form-check-input";
+ const toggleEnabled = cn(toggleClasses, color);
+
+ const getHttpOptions = () => (
+
+ );
+
+ const getHttpAdvancedOptions = () => (
+
+
+
+
+
+
+
+
+ {({ field }: any) => (
+
+ )}
+
+
+
+
+
+ );
+
+ return (
+
+ {forHttp ? getHttpOptions() : null}
+ {newCertificate ? (
+ <>
+
+ {({ field }: any) => (
+
+ )}
+
+ {requireDomainNames ? : null}
+ {dnsChallenge ? : null}
+ >
+ ) : null}
+ {forProxyHost && forHttp ? getHttpAdvancedOptions() : null}
+
+ );
+}
diff --git a/frontend/src/components/Form/index.ts b/frontend/src/components/Form/index.ts
new file mode 100644
index 000000000..f218b2e33
--- /dev/null
+++ b/frontend/src/components/Form/index.ts
@@ -0,0 +1,9 @@
+export * from "./AccessClientFields";
+export * from "./AccessField";
+export * from "./BasicAuthFields";
+export * from "./DNSProviderFields";
+export * from "./DomainNamesField";
+export * from "./LocationsFields";
+export * from "./NginxConfigField";
+export * from "./SSLCertificateField";
+export * from "./SSLOptionsFields";
diff --git a/frontend/src/components/HasPermission.tsx b/frontend/src/components/HasPermission.tsx
new file mode 100644
index 000000000..b049397c4
--- /dev/null
+++ b/frontend/src/components/HasPermission.tsx
@@ -0,0 +1,56 @@
+import type { ReactNode } from "react";
+// import Alert from "react-bootstrap/Alert";
+import { Loading, LoadingPage } from "src/components";
+import { useUser } from "src/hooks";
+// import { T } from "src/locale";
+import type { ADMIN, /*hasPermission,*/ Permission, Section } from "src/modules/Permissions";
+
+interface Props {
+ section?: Section | typeof ADMIN;
+ permission: Permission;
+ hideError?: boolean;
+ children?: ReactNode;
+ pageLoading?: boolean;
+ loadingNoLogo?: boolean;
+}
+function HasPermission({
+ section,
+ // permission,
+ children,
+ hideError = false,
+ pageLoading = false,
+ loadingNoLogo = false,
+}: Props) {
+ const { /*data,*/ isLoading } = useUser("me");
+
+ if (!section) {
+ return <>{children}>;
+ }
+
+ if (isLoading) {
+ if (hideError) {
+ return null;
+ }
+ if (pageLoading) {
+ return ;
+ }
+ return ;
+ }
+
+ return <>{children}>;
+ // TODO:
+ /*
+ const allowed = hasPermission(section, permission, data?.permissions, data?.roles);
+ if (allowed) {
+ return <>{children}>;
+ }
+
+ return !hideError ? (
+
+
+
+ ) : null;
+ */
+}
+
+export { HasPermission };
diff --git a/frontend/src/components/HelpDrawer/HelpDrawer.tsx b/frontend/src/components/HelpDrawer/HelpDrawer.tsx
deleted file mode 100644
index 1c935d2e5..000000000
--- a/frontend/src/components/HelpDrawer/HelpDrawer.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import { useEffect, useState } from "react";
-
-import {
- Button,
- Drawer,
- DrawerContent,
- DrawerOverlay,
- DrawerBody,
- useDisclosure,
-} from "@chakra-ui/react";
-import { FiHelpCircle } from "react-icons/fi";
-import ReactMarkdown from "react-markdown";
-
-import { getLocale } from "src/locale";
-import { getHelpFile } from "src/locale/src/HelpDoc";
-
-interface HelpDrawerProps {
- /**
- * Section to show
- */
- section: string;
-}
-function HelpDrawer({ section }: HelpDrawerProps) {
- const { isOpen, onOpen, onClose } = useDisclosure();
- const [markdownText, setMarkdownText] = useState("");
- const lang = getLocale(true);
-
- useEffect(() => {
- try {
- const docFile = getHelpFile(lang, section) as any;
- fetch(docFile)
- .then((response) => response.text())
- .then(setMarkdownText);
- } catch (ex: any) {
- setMarkdownText(`**ERROR:** ${ex.message}`);
- }
- }, [lang, section]);
-
- return (
- <>
-
-
-
-
-
- {markdownText}
-
-
-
- >
- );
-}
-
-export { HelpDrawer };
diff --git a/frontend/src/components/HelpDrawer/index.ts b/frontend/src/components/HelpDrawer/index.ts
deleted file mode 100644
index 4b6357df4..000000000
--- a/frontend/src/components/HelpDrawer/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./HelpDrawer";
diff --git a/frontend/src/components/Loader/Loader.tsx b/frontend/src/components/Loader/Loader.tsx
deleted file mode 100644
index 2c44bd6ca..000000000
--- a/frontend/src/components/Loader/Loader.tsx
+++ /dev/null
@@ -1,19 +0,0 @@
-import { ReactNode } from "react";
-
-import cn from "classnames";
-
-interface LoaderProps {
- /**
- * Child elements within
- */
- children?: ReactNode;
- /**
- * Additional Class
- */
- className?: string;
-}
-function Loader({ children, className }: LoaderProps) {
- return {children}
;
-}
-
-export { Loader };
diff --git a/frontend/src/components/Loader/index.ts b/frontend/src/components/Loader/index.ts
deleted file mode 100644
index f9f5a2b49..000000000
--- a/frontend/src/components/Loader/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./Loader";
diff --git a/frontend/src/components/Loading.module.css b/frontend/src/components/Loading.module.css
new file mode 100644
index 000000000..7a13ded3f
--- /dev/null
+++ b/frontend/src/components/Loading.module.css
@@ -0,0 +1,3 @@
+.logo {
+ max-height: 100px;
+}
diff --git a/frontend/src/components/Loading.tsx b/frontend/src/components/Loading.tsx
index baf05c4f5..14d96e6da 100644
--- a/frontend/src/components/Loading.tsx
+++ b/frontend/src/components/Loading.tsx
@@ -1,13 +1,23 @@
-import { Box } from "@chakra-ui/react";
+import type { ReactNode } from "react";
+import { T } from "src/locale";
+import styles from "./Loading.module.css";
-import { Loader } from "src/components";
-
-function Loading() {
+interface Props {
+ label?: string | ReactNode;
+ noLogo?: boolean;
+}
+export function Loading({ label, noLogo }: Props) {
return (
-
-
-
+
+ {noLogo ? null : (
+
+

+
+ )}
+
{label || }
+
+
);
}
-
-export { Loading };
diff --git a/frontend/src/components/LoadingPage.tsx b/frontend/src/components/LoadingPage.tsx
new file mode 100644
index 000000000..7d3bec1ea
--- /dev/null
+++ b/frontend/src/components/LoadingPage.tsx
@@ -0,0 +1,15 @@
+import { Loading, Page } from "src/components";
+
+interface Props {
+ label?: string;
+ noLogo?: boolean;
+}
+export function LoadingPage({ label, noLogo }: Props) {
+ return (
+
+
+
+
+
+ );
+}
diff --git a/frontend/src/components/LocalePicker.module.css b/frontend/src/components/LocalePicker.module.css
new file mode 100644
index 000000000..6f39e7fa7
--- /dev/null
+++ b/frontend/src/components/LocalePicker.module.css
@@ -0,0 +1,8 @@
+.btn {
+ color: light-dark(var(--tblr-dark), var(--tblr-light)) !important;
+
+ &:hover {
+ border: var(--tblr-btn-border-width) solid transparent !important;
+ background: color-mix(in srgb, var(--tblr-btn-hover-bg) 10%, transparent) !important;
+ }
+}
diff --git a/frontend/src/components/LocalePicker.tsx b/frontend/src/components/LocalePicker.tsx
index 225840738..9ddaebaae 100644
--- a/frontend/src/components/LocalePicker.tsx
+++ b/frontend/src/components/LocalePicker.tsx
@@ -1,63 +1,51 @@
-import {
- Button,
- Box,
- Menu,
- MenuButton,
- MenuButtonProps,
- MenuList,
- MenuItem,
-} from "@chakra-ui/react";
-
-import { Flag } from "src/components";
+import cn from "classnames";
import { useLocaleState } from "src/context";
-import {
- changeLocale,
- getFlagCodeForLocale,
- intl,
- localeOptions,
-} from "src/locale";
+import { useTheme } from "src/hooks";
+import { changeLocale, localeOptions, T } from "src/locale";
+import styles from "./LocalePicker.module.css";
-interface LocalPickerProps {
- onChange?: any;
- className?: string;
- background?: "normal" | "transparent";
+interface Props {
+ menuAlign?: "start" | "end";
}
-function LocalePicker({ onChange, className, background }: LocalPickerProps) {
+function LocalePicker({ menuAlign = "start" }: Props) {
const { locale, setLocale } = useLocaleState();
-
- const additionalProps: Partial = {};
- if (background === "transparent") {
- additionalProps["backgroundColor"] = "transparent";
- }
+ const { getTheme } = useTheme();
const changeTo = (lang: string) => {
changeLocale(lang);
setLocale(lang);
- onChange && onChange(locale);
location.reload();
};
+ const classes = ["btn", "dropdown-toggle", "btn-sm", styles.btn];
+ const cns = cn(...classes, getTheme() === "dark" ? "btn-ghost-dark" : "btn-ghost-light");
+
return (
-
-
-
+
+
+
+
);
}
diff --git a/frontend/src/components/Monospace.tsx b/frontend/src/components/Monospace.tsx
deleted file mode 100644
index 0f9dffcd6..000000000
--- a/frontend/src/components/Monospace.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import { Text, TextProps } from "@chakra-ui/react";
-
-function Monospace(props: TextProps) {
- return (
-
- {props.children}
-
- );
-}
-
-export { Monospace };
diff --git a/frontend/src/components/NavLink.tsx b/frontend/src/components/NavLink.tsx
new file mode 100644
index 000000000..b6a414af6
--- /dev/null
+++ b/frontend/src/components/NavLink.tsx
@@ -0,0 +1,29 @@
+import { useNavigate } from "react-router-dom";
+
+interface Props {
+ children: React.ReactNode;
+ to?: string;
+ isDropdownItem?: boolean;
+ onClick?: () => void;
+}
+export function NavLink({ children, to, isDropdownItem, onClick }: Props) {
+ const navigate = useNavigate();
+
+ return (
+ {
+ e.preventDefault();
+ if (onClick) {
+ onClick();
+ }
+ if (to) {
+ navigate(to);
+ }
+ }}
+ >
+ {children}
+
+ );
+}
diff --git a/frontend/src/components/Navigation/Navigation.tsx b/frontend/src/components/Navigation/Navigation.tsx
deleted file mode 100644
index 9f8dea26d..000000000
--- a/frontend/src/components/Navigation/Navigation.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import { useDisclosure } from "@chakra-ui/react";
-
-import { NavigationHeader, NavigationMenu } from "src/components";
-
-function Navigation() {
- const {
- isOpen: mobileNavIsOpen,
- onToggle: mobileNavToggle,
- onClose: mobileNavClose,
- } = useDisclosure();
- return (
- <>
-
-
- >
- );
-}
-
-export { Navigation };
diff --git a/frontend/src/components/Navigation/NavigationHeader.tsx b/frontend/src/components/Navigation/NavigationHeader.tsx
deleted file mode 100644
index 498e10a87..000000000
--- a/frontend/src/components/Navigation/NavigationHeader.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-import {
- Avatar,
- Box,
- Button,
- chakra,
- Container,
- Flex,
- HStack,
- Icon,
- IconButton,
- Menu,
- MenuButton,
- MenuDivider,
- MenuItem,
- MenuList,
- Text,
- useColorModeValue,
- useDisclosure,
-} from "@chakra-ui/react";
-import { FiLock, FiLogOut, FiMenu, FiUser, FiX } from "react-icons/fi";
-
-import { LocalePicker, ThemeSwitcher } from "src/components";
-import { useAuthState } from "src/context";
-import { useUser } from "src/hooks";
-import { intl } from "src/locale";
-import { ChangePasswordModal, ProfileModal } from "src/modals";
-
-interface NavigationHeaderProps {
- mobileNavIsOpen: boolean;
- toggleMobileNav: () => void;
-}
-function NavigationHeader({
- mobileNavIsOpen,
- toggleMobileNav,
-}: NavigationHeaderProps) {
- const passwordDisclosure = useDisclosure();
- const profileDisclosure = useDisclosure();
- const { data: user } = useUser("me");
- const { logout } = useAuthState();
-
- return (
-
-
-
- }
- />
-
-
-
- {intl.formatMessage({ id: "brand.name" })}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- );
-}
-
-export { NavigationHeader };
diff --git a/frontend/src/components/Navigation/NavigationMenu.tsx b/frontend/src/components/Navigation/NavigationMenu.tsx
deleted file mode 100644
index ef7ce0275..000000000
--- a/frontend/src/components/Navigation/NavigationMenu.tsx
+++ /dev/null
@@ -1,340 +0,0 @@
-import { FC, useCallback, useMemo, ReactNode } from "react";
-
-import {
- Box,
- Collapse,
- Flex,
- forwardRef,
- HStack,
- Icon,
- Link,
- Menu,
- MenuButton,
- MenuItem,
- MenuList,
- Text,
- Stack,
- useColorModeValue,
- useDisclosure,
- Container,
- useBreakpointValue,
-} from "@chakra-ui/react";
-import {
- FiHome,
- FiSettings,
- FiUser,
- FiBook,
- FiLock,
- FiShield,
- FiMonitor,
- FiChevronDown,
-} from "react-icons/fi";
-import { Link as RouterLink, useLocation } from "react-router-dom";
-
-import { intl } from "src/locale";
-
-interface NavItem {
- /** Displayed label */
- label: string;
- /** Icon shown before the label */
- icon: ReactNode;
- /** Link where to navigate to */
- to?: string;
- subItems?: { label: string; to: string }[];
-}
-
-const navItems: NavItem[] = [
- {
- label: intl.formatMessage({ id: "dashboard.title" }),
- icon: ,
- to: "/",
- },
- {
- label: intl.formatMessage({ id: "hosts.title" }),
- icon: ,
- subItems: [
- {
- label: intl.formatMessage({ id: "hosts.title" }),
- to: "/hosts",
- },
- {
- label: intl.formatMessage({ id: "upstreams.title" }),
- to: "/upstreams",
- },
- ],
- },
- {
- label: intl.formatMessage({ id: "access-lists.title" }),
- icon: ,
- to: "/access-lists",
- },
- {
- label: intl.formatMessage({ id: "ssl.title" }),
- icon: ,
- subItems: [
- {
- label: intl.formatMessage({ id: "certificates.title" }),
- to: "/ssl/certificates",
- },
- {
- label: intl.formatMessage({ id: "certificate-authorities.title" }),
- to: "/ssl/authorities",
- },
- {
- label: intl.formatMessage({ id: "dns-providers.title" }),
- to: "/ssl/dns-providers",
- },
- ],
- },
- {
- label: intl.formatMessage({ id: "audit-log.title" }),
- icon: ,
- to: "/audit-log",
- },
- {
- label: intl.formatMessage({ id: "users.title" }),
- icon: ,
- to: "/users",
- },
- {
- label: intl.formatMessage({ id: "settings.title" }),
- icon: ,
- subItems: [
- {
- label: intl.formatMessage({ id: "general-settings.title" }),
- to: "/settings/general",
- },
- {
- label: intl.formatMessage({ id: "nginx-templates.title" }),
- to: "/settings/nginx-templates",
- },
- ],
- },
-];
-
-interface NavigationMenuProps {
- /** Navigation is currently hidden on mobile */
- mobileNavIsOpen: boolean;
- closeMobileNav: () => void;
-}
-function NavigationMenu({
- mobileNavIsOpen,
- closeMobileNav,
-}: NavigationMenuProps) {
- const isMobile = useBreakpointValue({ base: true, md: false });
- return (
- <>
- {isMobile ? (
-
-
-
- ) : (
-
- )}
- >
- );
-}
-
-/** Single tab element for desktop navigation */
-type NavTabProps = Omit & { active?: boolean };
-const NavTab = forwardRef(
- ({ label, icon, to, active, ...props }, ref) => {
- const linkColor = useColorModeValue("gray.500", "gray.200");
- const linkHoverColor = useColorModeValue("gray.900", "white");
- return (
-
- {icon}
-
- {label}
-
-
- );
- },
-);
-
-const DesktopNavigation: FC = () => {
- const path = useLocation().pathname;
- const activeNavItemIndex = useMemo(
- () =>
- navItems.findIndex((item) => {
- // Find the nav item whose location / sub items location is the beginning of the currently active path
- if (item.to) {
- if (item.to === "/") {
- return path === item.to;
- }
- return path.startsWith(item.to !== "" ? item.to : "/dashboard");
- } else if (item.subItems) {
- return item.subItems.some((subItem) => path.startsWith(subItem.to));
- }
- return false;
- }),
- [path],
- );
-
- return (
-
-
-
- {navItems.map((navItem, index) => {
- const { subItems, ...propsWithoutSubItems } = navItem;
- const additionalProps: Partial = {};
- if (index === activeNavItemIndex) {
- additionalProps["active"] = true;
- }
- if (subItems) {
- return (
-
- );
- } else {
- return (
-
- );
- }
- })}
-
-
-
- );
-};
-
-const MobileNavigation: FC> = ({
- closeMobileNav,
-}) => {
- return (
-
- {navItems.map((navItem, index) => (
-
- ))}
-
- );
-};
-
-const MobileNavItem: FC<
- NavItem & {
- index: number;
- closeMobileNav: NavigationMenuProps["closeMobileNav"];
- }
-> = ({ closeMobileNav, ...props }) => {
- const { isOpen, onToggle } = useDisclosure();
-
- const onClickHandler = useCallback(() => {
- if (props.subItems) {
- // Toggle accordeon
- onToggle();
- } else {
- // Close menu on navigate
- closeMobileNav();
- }
- }, [closeMobileNav, onToggle, props.subItems]);
-
- return (
-
-
-
-
- {props.icon}
-
- {props.label}
-
-
- {props.subItems && (
-
- )}
-
-
-
-
- {props.subItems &&
- props.subItems.map((subItem, subIndex) => (
-
- {subItem.label}
-
- ))}
-
-
-
-
- );
-};
-
-export { NavigationMenu };
diff --git a/frontend/src/components/Navigation/index.ts b/frontend/src/components/Navigation/index.ts
deleted file mode 100644
index 302ad0e69..000000000
--- a/frontend/src/components/Navigation/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export * from "./Navigation";
-export * from "./NavigationHeader";
-export * from "./NavigationMenu";
diff --git a/frontend/src/components/Page.module.css b/frontend/src/components/Page.module.css
new file mode 100644
index 000000000..00086bbac
--- /dev/null
+++ b/frontend/src/components/Page.module.css
@@ -0,0 +1,5 @@
+.page {
+ display: grid;
+ grid-template-rows: auto 1fr auto; /* Header, Main Content, Footer */
+ min-height: 100vh;
+}
diff --git a/frontend/src/components/Page.tsx b/frontend/src/components/Page.tsx
new file mode 100644
index 000000000..a96a6b1f9
--- /dev/null
+++ b/frontend/src/components/Page.tsx
@@ -0,0 +1,10 @@
+import cn from "classnames";
+import styles from "./Page.module.css";
+
+interface Props {
+ children: React.ReactNode;
+ className?: string;
+}
+export function Page({ children, className }: Props) {
+ return {children}
;
+}
diff --git a/frontend/src/components/Permissions/AdminPermissionSelector.tsx b/frontend/src/components/Permissions/AdminPermissionSelector.tsx
deleted file mode 100644
index 4f60e7dff..000000000
--- a/frontend/src/components/Permissions/AdminPermissionSelector.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { MouseEventHandler } from "react";
-
-import { Heading, Stack, Text, useColorModeValue } from "@chakra-ui/react";
-
-import { intl } from "src/locale";
-
-interface AdminPermissionSelectorProps {
- selected?: boolean;
- onClick: MouseEventHandler;
-}
-
-function AdminPermissionSelector({
- selected,
- onClick,
-}: AdminPermissionSelectorProps) {
- return (
-
-
- {intl.formatMessage({ id: "full-access" })}
-
-
- {intl.formatMessage({ id: "full-access.description" })}
-
-
- );
-}
-
-export { AdminPermissionSelector };
diff --git a/frontend/src/components/Permissions/PermissionSelector.tsx b/frontend/src/components/Permissions/PermissionSelector.tsx
deleted file mode 100644
index 25ea95279..000000000
--- a/frontend/src/components/Permissions/PermissionSelector.tsx
+++ /dev/null
@@ -1,286 +0,0 @@
-import { ChangeEvent, MouseEventHandler } from "react";
-
-import {
- Flex,
- Heading,
- Select,
- Stack,
- Text,
- useColorModeValue,
-} from "@chakra-ui/react";
-
-import { intl } from "src/locale";
-
-interface PermissionSelectorProps {
- capabilities: string[];
- selected?: boolean;
- onClick: MouseEventHandler;
- onChange: (i: string[]) => any;
-}
-
-function PermissionSelector({
- capabilities,
- selected,
- onClick,
- onChange,
-}: PermissionSelectorProps) {
- const textColor = useColorModeValue("gray.700", "gray.400");
-
- const onSelectChange = ({ target }: ChangeEvent) => {
- // remove all items starting with target.name
- const i: string[] = [];
- const re = new RegExp(`^${target.name}\\.`, "g");
- capabilities.forEach((capability) => {
- if (!capability.match(re)) {
- i.push(capability);
- }
- });
-
- // add a new item, if value is something, and doesn't already exist
- if (target.value) {
- const c = `${target.name}.${target.value}`;
- if (i.indexOf(c) === -1) {
- i.push(c);
- }
- }
-
- onChange(i);
- };
-
- const getDefaultValue = (c: string): string => {
- if (capabilities.indexOf(`${c}.manage`) !== -1) {
- return "manage";
- }
- if (capabilities.indexOf(`${c}.view`) !== -1) {
- return "view";
- }
- return "";
- };
-
- return (
-
-
- {intl.formatMessage({ id: "restricted-access" })}
-
- {selected ? (
-
-
-
- {intl.formatMessage({ id: "access-lists.title" })}
-
-
-
-
-
-
-
- {intl.formatMessage({ id: "audit-log.title" })}
-
-
-
-
-
-
-
- {intl.formatMessage({ id: "certificates.title" })}
-
-
-
-
-
-
-
- {intl.formatMessage({ id: "certificate-authorities.title" })}
-
-
-
-
-
-
-
- {intl.formatMessage({ id: "dns-providers.title" })}
-
-
-
-
-
-
- {intl.formatMessage({ id: "hosts.title" })}
-
-
-
-
-
-
- {intl.formatMessage({ id: "nginx-templates.title" })}
-
-
-
-
-
-
- {intl.formatMessage({ id: "settings.title" })}
-
-
-
-
-
- {intl.formatMessage({ id: "users.title" })}
-
-
-
-
-
- ) : (
-
- {intl.formatMessage({ id: "restricted-access.description" })}
-
- )}
-
- );
-}
-
-export { PermissionSelector };
diff --git a/frontend/src/components/Permissions/index.ts b/frontend/src/components/Permissions/index.ts
deleted file mode 100644
index e0cf81207..000000000
--- a/frontend/src/components/Permissions/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export * from "./AdminPermissionSelector";
-export * from "./PermissionSelector";
diff --git a/frontend/src/components/PrettyButton.tsx b/frontend/src/components/PrettyButton.tsx
deleted file mode 100644
index b717d0f7f..000000000
--- a/frontend/src/components/PrettyButton.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import { Button, ButtonProps } from "@chakra-ui/react";
-
-function PrettyButton(props: ButtonProps) {
- return (
-
- );
-}
-
-export { PrettyButton };
diff --git a/frontend/src/components/PrettyMenuButton.tsx b/frontend/src/components/PrettyMenuButton.tsx
deleted file mode 100644
index 554a078cf..000000000
--- a/frontend/src/components/PrettyMenuButton.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { Button, MenuButton, MenuButtonProps } from "@chakra-ui/react";
-import { FiChevronDown } from "react-icons/fi";
-
-function PrettyMenuButton(props: MenuButtonProps) {
- return (
- }
- _hover={{
- bgGradient: "linear(to-r, red.400,pink.400)",
- boxShadow: "xl",
- }}
- {...props}>
- {props.children}
-
- );
-}
-
-export { PrettyMenuButton };
diff --git a/frontend/src/components/SiteContainer.tsx b/frontend/src/components/SiteContainer.tsx
new file mode 100644
index 000000000..01a9cb52b
--- /dev/null
+++ b/frontend/src/components/SiteContainer.tsx
@@ -0,0 +1,6 @@
+interface Props {
+ children: React.ReactNode;
+}
+export function SiteContainer({ children }: Props) {
+ return {children}
;
+}
diff --git a/frontend/src/components/SiteFooter.tsx b/frontend/src/components/SiteFooter.tsx
new file mode 100644
index 000000000..ea0e8180b
--- /dev/null
+++ b/frontend/src/components/SiteFooter.tsx
@@ -0,0 +1,78 @@
+import { useCheckVersion, useHealth } from "src/hooks";
+import { T } from "src/locale";
+
+export function SiteFooter() {
+ const health = useHealth();
+ const { data: versionData } = useCheckVersion();
+
+ const getVersion = () => {
+ if (!health.data) {
+ return "";
+ }
+ const v = health.data.version;
+ return `v${v.major}.${v.minor}.${v.patch}`;
+ };
+
+ return (
+
+ );
+}
diff --git a/frontend/src/components/SiteHeader.module.css b/frontend/src/components/SiteHeader.module.css
new file mode 100644
index 000000000..a88f81c9e
--- /dev/null
+++ b/frontend/src/components/SiteHeader.module.css
@@ -0,0 +1,8 @@
+.logo {
+ font-size: 1.1rem;
+ font-weight: 500;
+
+ img {
+ margin-right: 0.8rem;
+ }
+}
diff --git a/frontend/src/components/SiteHeader.tsx b/frontend/src/components/SiteHeader.tsx
new file mode 100644
index 000000000..f37de5771
--- /dev/null
+++ b/frontend/src/components/SiteHeader.tsx
@@ -0,0 +1,144 @@
+import { IconLock, IconLogout, IconShieldLock, IconUser } from "@tabler/icons-react";
+import { LocalePicker, NavLink, ThemeSwitcher } from "src/components";
+import { useAuthState } from "src/context";
+import { useUser } from "src/hooks";
+import { T } from "src/locale";
+import { showChangePasswordModal, showTwoFactorModal, showUserModal } from "src/modals";
+import styles from "./SiteHeader.module.css";
+
+export function SiteHeader() {
+ const { data: currentUser } = useUser("me");
+ const isAdmin = currentUser?.roles?.includes("admin");
+ const { logout } = useAuthState();
+console.log("currentUser", currentUser);
+ return (
+
+
+
+
+
+
+

+
+ Nginx Proxy Manager
+
+
+
+
+
+ );
+}
diff --git a/frontend/src/components/SiteMenu.tsx b/frontend/src/components/SiteMenu.tsx
new file mode 100644
index 000000000..c7274751a
--- /dev/null
+++ b/frontend/src/components/SiteMenu.tsx
@@ -0,0 +1,214 @@
+import {
+ IconBook,
+ IconDeviceDesktop,
+ IconFileText,
+ IconHome,
+ IconLock,
+ IconSettings,
+ IconShield,
+ IconUser,
+} from "@tabler/icons-react";
+import cn from "classnames";
+import React from "react";
+import { HasPermission, NavLink } from "src/components";
+import { T } from "src/locale";
+import {
+ ACCESS_LISTS,
+ ADMIN,
+ CERTIFICATES,
+ DEAD_HOSTS,
+ type MANAGE,
+ PROXY_HOSTS,
+ REDIRECTION_HOSTS,
+ type Section,
+ STREAMS,
+ VIEW,
+} from "src/modules/Permissions";
+
+interface MenuItem {
+ label: string;
+ icon?: React.ElementType;
+ to?: string;
+ items?: MenuItem[];
+ permissionSection?: Section | typeof ADMIN;
+ permission?: typeof VIEW | typeof MANAGE;
+}
+
+const menuItems: MenuItem[] = [
+ {
+ to: "/",
+ icon: IconHome,
+ label: "dashboard",
+ },
+ {
+ icon: IconDeviceDesktop,
+ label: "hosts",
+ items: [
+ {
+ to: "/nginx/proxy",
+ label: "proxy-hosts",
+ permissionSection: PROXY_HOSTS,
+ permission: VIEW,
+ },
+ {
+ to: "/nginx/redirection",
+ label: "redirection-hosts",
+ permissionSection: REDIRECTION_HOSTS,
+ permission: VIEW,
+ },
+ {
+ to: "/nginx/stream",
+ label: "streams",
+ permissionSection: STREAMS,
+ permission: VIEW,
+ },
+ {
+ to: "/nginx/404",
+ label: "dead-hosts",
+ permissionSection: DEAD_HOSTS,
+ permission: VIEW,
+ },
+ ],
+ },
+ {
+ to: "/access",
+ icon: IconLock,
+ label: "access-lists",
+ permissionSection: ACCESS_LISTS,
+ permission: VIEW,
+ },
+ {
+ to: "/certificates",
+ icon: IconShield,
+ label: "certificates",
+ permissionSection: CERTIFICATES,
+ permission: VIEW,
+ },
+ {
+ to: "/users",
+ icon: IconUser,
+ label: "users",
+ permissionSection: ADMIN,
+ },
+ {
+ to: "/audit-log",
+ icon: IconBook,
+ label: "auditlogs",
+ permissionSection: ADMIN,
+ },
+ {
+ to: "/logs",
+ icon: IconFileText,
+ label: "logs",
+ permissionSection: ADMIN,
+ },
+ {
+ to: "/settings",
+ icon: IconSettings,
+ label: "settings",
+ permissionSection: ADMIN,
+ },
+];
+
+const getMenuItem = (item: MenuItem, onClick?: () => void) => {
+ if (item.items && item.items.length > 0) {
+ return getMenuDropown(item, onClick);
+ }
+
+ return (
+
+
+
+
+ {item.icon && React.createElement(item.icon, { height: 24, width: 24 })}
+
+
+
+
+
+
+
+ );
+};
+
+const getMenuDropown = (item: MenuItem, onClick?: () => void) => {
+ const cns = cn("nav-item", "dropdown");
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ {item.items?.map((subitem, idx) => {
+ return (
+
+
+
+
+
+ );
+ })}
+
+
+
+ );
+};
+
+export function SiteMenu() {
+ const closeMenu = () =>
+ setTimeout(() => {
+ const navbarToggler = document.querySelector(".navbar-toggler");
+ const navbarMenu = document.querySelector("#navbar-menu");
+ if (navbarToggler && navbarMenu?.classList.contains("show")) {
+ navbarToggler.click();
+ }
+ }, 300);
+
+ return (
+
+ );
+}
diff --git a/frontend/src/components/SiteWrapper.tsx b/frontend/src/components/SiteWrapper.tsx
deleted file mode 100644
index 4dd975fb1..000000000
--- a/frontend/src/components/SiteWrapper.tsx
+++ /dev/null
@@ -1,85 +0,0 @@
-import { ReactNode, useCallback, useEffect } from "react";
-
-import { Box, Container, useToast } from "@chakra-ui/react";
-import { useQueryClient } from "@tanstack/react-query";
-
-import { getSSEToken, SSEMessage } from "src/api/npm";
-import { Footer, Navigation } from "src/components";
-import { intl } from "src/locale";
-import AuthStore from "src/modules/AuthStore";
-
-interface Props {
- children?: ReactNode;
-}
-function SiteWrapper({ children }: Props) {
- const queryClient = useQueryClient();
- const toast = useToast();
-
- const cb = useCallback(
- async function fetchData() {
- if (AuthStore.token) {
- return;
- }
-
- // Fetch the SSE token and set up the EventSource
- const response = await getSSEToken();
- const eventSource = new EventSource(
- `/api/sse/changes?jwt=${response.token}`,
- );
- eventSource.onmessage = (e: any) => {
- const j: SSEMessage = JSON.parse(e.data);
- if (j) {
- console.log("SSE Message:", j);
- if (j.affects) {
- queryClient.invalidateQueries({ queryKey: [j.affects] });
- }
- if (j.type) {
- toast({
- description: intl.formatMessage({ id: j.lang }),
- status: j.type || "info",
- position: "top",
- duration: 3000,
- isClosable: true,
- });
- }
- }
- };
- eventSource.onerror = (e) => {
- console.error("SSE EventSource failed:", e);
- };
- return () => {
- eventSource.close();
- };
- },
- [queryClient, toast],
- );
-
- // TODO: fix bug where this will fail if the browser is kept open longer
- // than the expiry of the sse token
- useEffect(() => {
- cb();
- });
-
- return (
-
-
-
-
-
-
- {children}
-
-
-
-
-
-
- );
-}
-
-export { SiteWrapper };
diff --git a/frontend/src/components/SpinnerPage.tsx b/frontend/src/components/SpinnerPage.tsx
deleted file mode 100644
index 1b77389e6..000000000
--- a/frontend/src/components/SpinnerPage.tsx
+++ /dev/null
@@ -1,9 +0,0 @@
-import { Flex, Spinner } from "@chakra-ui/react";
-
-export function SpinnerPage() {
- return (
-
-
-
- );
-}
diff --git a/frontend/src/components/Table/EmptyRow.tsx b/frontend/src/components/Table/EmptyRow.tsx
new file mode 100644
index 000000000..ada39e3e1
--- /dev/null
+++ b/frontend/src/components/Table/EmptyRow.tsx
@@ -0,0 +1,17 @@
+import type { Table as ReactTable, RowData } from "@tanstack/react-table";
+import type { Features } from "./features";
+
+interface Props {
+ tableInstance: ReactTable;
+}
+function EmptyRow({ tableInstance }: Props) {
+ return (
+
+ |
+ There are no items
+ |
+
+ );
+}
+
+export { EmptyRow };
diff --git a/frontend/src/components/Table/Formatter/AccessListformatter.tsx b/frontend/src/components/Table/Formatter/AccessListformatter.tsx
new file mode 100644
index 000000000..b5830fd9c
--- /dev/null
+++ b/frontend/src/components/Table/Formatter/AccessListformatter.tsx
@@ -0,0 +1,24 @@
+import type { AccessList } from "src/api/backend";
+import { T } from "src/locale";
+import { showAccessListModal } from "src/modals";
+
+interface Props {
+ access?: AccessList;
+}
+export function AccessListFormatter({ access }: Props) {
+ if (!access) {
+ return ;
+ }
+ return (
+
+ );
+}
diff --git a/frontend/src/components/Table/Formatter/CertificateFormatter.tsx b/frontend/src/components/Table/Formatter/CertificateFormatter.tsx
new file mode 100644
index 000000000..6b791bfbf
--- /dev/null
+++ b/frontend/src/components/Table/Formatter/CertificateFormatter.tsx
@@ -0,0 +1,18 @@
+import type { Certificate } from "src/api/backend";
+import { T } from "src/locale";
+
+interface Props {
+ certificate?: Certificate;
+}
+export function CertificateFormatter({ certificate }: Props) {
+ let translation = "http-only";
+ if (certificate) {
+ translation = certificate.provider;
+ if (translation === "letsencrypt") {
+ translation = "lets-encrypt";
+ } else if (translation === "other") {
+ translation = "certificates.custom";
+ }
+ }
+ return ;
+}
diff --git a/frontend/src/components/Table/Formatter/CertificateInUseFormatter.tsx b/frontend/src/components/Table/Formatter/CertificateInUseFormatter.tsx
new file mode 100644
index 000000000..a49374d65
--- /dev/null
+++ b/frontend/src/components/Table/Formatter/CertificateInUseFormatter.tsx
@@ -0,0 +1,82 @@
+import OverlayTrigger from "react-bootstrap/OverlayTrigger";
+import Popover from "react-bootstrap/Popover";
+import type { DeadHost, ProxyHost, RedirectionHost, Stream } from "src/api/backend";
+import { TrueFalseFormatter } from "src/components";
+import { T } from "src/locale";
+
+const getSection = (title: string, items: ProxyHost[] | RedirectionHost[] | DeadHost[]) => {
+ if (items.length === 0) {
+ return null;
+ }
+ return (
+ <>
+
+
+
+
+
+ {items.map((host) => (
+
+ {host.domainNames.join(", ")}
+
+ ))}
+ >
+ );
+};
+
+const getSectionStream = (items: Stream[]) => {
+ if (items.length === 0) {
+ return null;
+ }
+ return (
+ <>
+
+
+
+
+
+ {items.map((stream) => (
+
+ {stream.forwardingHost}:{stream.forwardingPort}
+
+ ))}
+ >
+ );
+};
+
+interface Props {
+ proxyHosts: ProxyHost[];
+ redirectionHosts: RedirectionHost[];
+ deadHosts: DeadHost[];
+ streams: Stream[];
+}
+export function CertificateInUseFormatter({ proxyHosts, redirectionHosts, deadHosts, streams }: Props) {
+ const totalCount = proxyHosts?.length + redirectionHosts?.length + deadHosts?.length + streams?.length;
+ if (totalCount === 0) {
+ return ;
+ }
+
+ proxyHosts.sort();
+ redirectionHosts.sort();
+ deadHosts.sort();
+ streams.sort();
+
+ const popover = (
+
+
+ {getSection("proxy-hosts", proxyHosts)}
+ {getSection("redirection-hosts", redirectionHosts)}
+ {getSection("dead-hosts", deadHosts)}
+ {getSectionStream(streams)}
+
+
+ );
+
+ return (
+
+
+
+
+
+ );
+}
diff --git a/frontend/src/components/Table/Formatter/DateFormatter.tsx b/frontend/src/components/Table/Formatter/DateFormatter.tsx
new file mode 100644
index 000000000..830b06e2e
--- /dev/null
+++ b/frontend/src/components/Table/Formatter/DateFormatter.tsx
@@ -0,0 +1,21 @@
+import cn from "classnames";
+import { differenceInDays, isPast } from "date-fns";
+import { useLocaleState } from "src/context";
+import { formatDateTime, parseDate } from "src/locale";
+
+interface Props {
+ value: string;
+ highlightPast?: boolean;
+ highlistNearlyExpired?: boolean;
+}
+export function DateFormatter({ value, highlightPast, highlistNearlyExpired }: Props) {
+ const { locale } = useLocaleState();
+ const d = parseDate(value);
+ const dateIsPast = d ? isPast(d) : false;
+ const days = d ? differenceInDays(d, new Date()) : 0;
+ const cl = cn({
+ "text-danger": highlightPast && dateIsPast,
+ "text-warning": highlistNearlyExpired && !dateIsPast && days <= 30 && days >= 0,
+ });
+ return {formatDateTime(value, locale)};
+}
diff --git a/frontend/src/components/Table/Formatter/DomainsFormatter.tsx b/frontend/src/components/Table/Formatter/DomainsFormatter.tsx
new file mode 100644
index 000000000..3ccc4d804
--- /dev/null
+++ b/frontend/src/components/Table/Formatter/DomainsFormatter.tsx
@@ -0,0 +1,74 @@
+import cn from "classnames";
+import type { ReactNode } from "react";
+import { useLocaleState } from "src/context";
+import { formatDateTime, T } from "src/locale";
+
+interface Props {
+ domains: string[];
+ createdOn?: string;
+ niceName?: string;
+ provider?: string;
+ color?: string;
+}
+
+const DomainLink = ({ domain, color }: { domain?: string; color?: string }) => {
+ // when domain contains a wildcard, make the link go nowhere.
+ // Apparently the domain can be null or undefined sometimes.
+ // This try is just a safeguard to prevent the whole formatter from breaking.
+ if (!domain) return null;
+ try {
+ let onClick: ((e: React.MouseEvent) => void) | undefined;
+ if (domain.includes("*")) {
+ onClick = (e: React.MouseEvent) => e.preventDefault();
+ }
+ return (
+
+ {domain}
+
+ );
+ } catch {
+ return null;
+ }
+};
+
+export function DomainsFormatter({ domains, createdOn, niceName, provider, color }: Props) {
+ const { locale } = useLocaleState();
+ const elms: ReactNode[] = [];
+
+ if ((!domains || domains.length === 0) && !niceName) {
+ elms.push(
+
+ Unknown
+ ,
+ );
+ }
+ if (!domains || (niceName && provider !== "letsencrypt")) {
+ elms.push(
+
+ {niceName}
+ ,
+ );
+ }
+
+ if (domains) {
+ domains.map((domain: string) => elms.push());
+ }
+
+ return (
+
+
{...elms}
+ {createdOn ? (
+
+
+
+ ) : null}
+
+ );
+}
diff --git a/frontend/src/components/Table/Formatter/EmailFormatter.tsx b/frontend/src/components/Table/Formatter/EmailFormatter.tsx
new file mode 100644
index 000000000..3371c66a3
--- /dev/null
+++ b/frontend/src/components/Table/Formatter/EmailFormatter.tsx
@@ -0,0 +1,10 @@
+interface Props {
+ email: string;
+}
+export function EmailFormatter({ email }: Props) {
+ return (
+
+ {email}
+
+ );
+}
diff --git a/frontend/src/components/Table/Formatter/EventFormatter.tsx b/frontend/src/components/Table/Formatter/EventFormatter.tsx
new file mode 100644
index 000000000..1220fa096
--- /dev/null
+++ b/frontend/src/components/Table/Formatter/EventFormatter.tsx
@@ -0,0 +1,81 @@
+import { IconArrowsCross, IconBolt, IconBoltOff, IconDisc, IconLock, IconShield, IconUser } from "@tabler/icons-react";
+import cn from "classnames";
+import type { AuditLog } from "src/api/backend";
+import { useLocaleState } from "src/context";
+import { formatDateTime, T } from "src/locale";
+
+const getEventValue = (event: AuditLog) => {
+ switch (event.objectType) {
+ case "access-list":
+ case "user":
+ return event.meta?.name;
+ case "proxy-host":
+ case "redirection-host":
+ case "dead-host":
+ return event.meta?.domainNames?.join(", ") || "N/A";
+ case "stream":
+ return event.meta?.incomingPort || "N/A";
+ case "certificate":
+ return event.meta?.domainNames?.join(", ") || event.meta?.niceName || "N/A";
+ default:
+ return `UNKNOWN EVENT TYPE: ${event.objectType}`;
+ }
+};
+
+const getColorForAction = (action: string) => {
+ switch (action) {
+ case "created":
+ return "text-lime";
+ case "deleted":
+ return "text-red";
+ default:
+ return "text-blue";
+ }
+};
+
+const getIcon = (row: AuditLog) => {
+ const c = cn(getColorForAction(row.action), "me-1");
+ let ico = null;
+ switch (row.objectType) {
+ case "user":
+ ico = ;
+ break;
+ case "proxy-host":
+ ico = ;
+ break;
+ case "redirection-host":
+ ico = ;
+ break;
+ case "dead-host":
+ ico = ;
+ break;
+ case "stream":
+ ico = ;
+ break;
+ case "access-list":
+ ico = ;
+ break;
+ case "certificate":
+ ico = ;
+ break;
+ }
+
+ return ico;
+};
+
+interface Props {
+ row: AuditLog;
+}
+export function EventFormatter({ row }: Props) {
+ const { locale } = useLocaleState();
+ return (
+
+
+ {getIcon(row)}
+
+ — {getEventValue(row)}
+
+
{formatDateTime(row.createdOn, locale)}
+
+ );
+}
diff --git a/frontend/src/components/Table/Formatter/GravatarFormatter.tsx b/frontend/src/components/Table/Formatter/GravatarFormatter.tsx
new file mode 100644
index 000000000..58b820ba4
--- /dev/null
+++ b/frontend/src/components/Table/Formatter/GravatarFormatter.tsx
@@ -0,0 +1,19 @@
+const defaultImg = "/images/default-avatar.jpg";
+
+interface Props {
+ url?: string;
+ name?: string;
+}
+export function GravatarFormatter({ url, name }: Props) {
+ return (
+
+
+
+ );
+}
diff --git a/frontend/src/components/Table/Formatter/RolesFormatter.tsx b/frontend/src/components/Table/Formatter/RolesFormatter.tsx
new file mode 100644
index 000000000..2e025605d
--- /dev/null
+++ b/frontend/src/components/Table/Formatter/RolesFormatter.tsx
@@ -0,0 +1,20 @@
+import { T } from "src/locale";
+
+interface Props {
+ roles: string[];
+}
+export function RolesFormatter({ roles }: Props) {
+ const r = roles || [];
+ if (r.length === 0) {
+ r[0] = "standard-user";
+ }
+ return (
+ <>
+ {r.map((role: string) => (
+
+
+
+ ))}
+ >
+ );
+}
diff --git a/frontend/src/components/Table/Formatter/TrueFalseFormatter.tsx b/frontend/src/components/Table/Formatter/TrueFalseFormatter.tsx
new file mode 100644
index 000000000..633395023
--- /dev/null
+++ b/frontend/src/components/Table/Formatter/TrueFalseFormatter.tsx
@@ -0,0 +1,24 @@
+import cn from "classnames";
+import { T } from "src/locale";
+
+interface Props {
+ value: boolean;
+ trueLabel?: string;
+ trueColor?: string;
+ falseLabel?: string;
+ falseColor?: string;
+}
+export function TrueFalseFormatter({
+ value,
+ trueLabel = "enabled",
+ trueColor = "lime",
+ falseLabel = "disabled",
+ falseColor = "red",
+}: Props) {
+ return (
+
+
+
+
+ );
+}
diff --git a/frontend/src/components/Table/Formatter/ValueWithDateFormatter.tsx b/frontend/src/components/Table/Formatter/ValueWithDateFormatter.tsx
new file mode 100644
index 000000000..d83ccbfa7
--- /dev/null
+++ b/frontend/src/components/Table/Formatter/ValueWithDateFormatter.tsx
@@ -0,0 +1,23 @@
+import { useLocaleState } from "src/context";
+import { formatDateTime, T } from "src/locale";
+
+interface Props {
+ value: string;
+ createdOn?: string;
+ disabled?: boolean;
+}
+export function ValueWithDateFormatter({ value, createdOn, disabled }: Props) {
+ const { locale } = useLocaleState();
+ return (
+
+
+ {createdOn ? (
+
+
+
+ ) : null}
+
+ );
+}
diff --git a/frontend/src/components/Table/Formatter/index.ts b/frontend/src/components/Table/Formatter/index.ts
new file mode 100644
index 000000000..04a47193d
--- /dev/null
+++ b/frontend/src/components/Table/Formatter/index.ts
@@ -0,0 +1,11 @@
+export * from "./AccessListformatter";
+export * from "./CertificateFormatter";
+export * from "./CertificateInUseFormatter";
+export * from "./DateFormatter";
+export * from "./DomainsFormatter";
+export * from "./EmailFormatter";
+export * from "./EventFormatter";
+export * from "./GravatarFormatter";
+export * from "./RolesFormatter";
+export * from "./TrueFalseFormatter";
+export * from "./ValueWithDateFormatter";
diff --git a/frontend/src/components/Table/Formatters.tsx b/frontend/src/components/Table/Formatters.tsx
deleted file mode 100644
index b8e6baaf5..000000000
--- a/frontend/src/components/Table/Formatters.tsx
+++ /dev/null
@@ -1,337 +0,0 @@
-import {
- Avatar,
- Badge,
- Text,
- Tooltip,
- Popover,
- PopoverTrigger,
- PopoverContent,
- PopoverArrow,
- PopoverBody,
-} from "@chakra-ui/react";
-
-import { Monospace, RowAction, RowActionsMenu } from "src/components";
-import { intl } from "src/locale";
-import getNiceDNSProvider from "src/modules/Acmesh";
-
-const errorColor = "red.400";
-
-function ActionsFormatter(rowActions: RowAction[]) {
- const formatCell = (instance: any) => {
- return ;
- };
-
- return formatCell;
-}
-
-function BooleanFormatter() {
- const formatCell = ({ value }: any) => {
- return (
-
- {value ? "true" : "false"}
-
- );
- };
-
- return formatCell;
-}
-
-function CapabilitiesFormatter() {
- const formatCell = ({ row, value }: any) => {
- const style = {} as any;
- if (row?.original?.isDisabled) {
- style.textDecoration = "line-through";
- }
-
- if (row?.original?.isSystem) {
- return (
-
- {intl.formatMessage({ id: "capability.system" })}
-
- );
- }
-
- if (value?.indexOf("full-admin") !== -1) {
- return (
-
- {intl.formatMessage({ id: "capability.full-admin" })}
-
- );
- }
-
- if (value?.length) {
- const strs: string[] = [];
- value.map((c: string) => {
- strs.push(intl.formatMessage({ id: `capability.${c}` }));
- return null;
- });
-
- return (
-
-
- {intl.formatMessage(
- { id: "capability-count" },
- { count: value.length },
- )}
-
-
- );
- }
-
- return null;
- };
-
- return formatCell;
-}
-
-function CertificateStatusFormatter() {
- const formatCell = ({ value, row }: any) => {
- let color = "cyan.500";
- switch (value) {
- case "failed":
- color = errorColor;
- break;
- case "provided":
- color = "green.400";
- break;
- case "requesting":
- color = "yellow.400";
- break;
- }
- // special case for failed to show an error popover
- if (value === "failed" && row?.original?.errorMessage) {
- return (
-
-
-
- {intl.formatMessage({ id: `status.${value}` })}
-
-
-
-
-
-
- {row?.original?.errorMessage}
-
-
-
-
- );
- }
- return (
-
- {intl.formatMessage({ id: `status.${value}` })}
-
- );
- };
-
- return formatCell;
-}
-
-function CertificateTypeFormatter() {
- const formatCell = ({ value }: any) => {
- let color = "cyan.500";
- if (value === "dns") {
- color = "green.400";
- }
- return (
- {intl.formatMessage({ id: `type.${value}` })}
- );
- };
-
- return formatCell;
-}
-
-function DisabledFormatter() {
- const formatCell = ({ value, row }: any) => {
- if (row?.original?.isDisabled) {
- return (
-
-
- {value}
-
-
- );
- }
- return value;
- };
-
- return formatCell;
-}
-
-function DNSProviderFormatter() {
- const formatCell = ({ value }: any) => {
- return getNiceDNSProvider(value);
- };
-
- return formatCell;
-}
-
-function DomainsFormatter() {
- const formatCell = ({ value }: any) => {
- if (value?.length > 0) {
- return (
- <>
- {value.map((dom: string, idx: number) => {
- return (
-
- {dom}
-
- );
- })}
- >
- );
- }
- return No domains!;
- };
-
- return formatCell;
-}
-
-function GravatarFormatter() {
- const formatCell = ({ value }: any) => {
- return ;
- };
-
- return formatCell;
-}
-
-function HostStatusFormatter() {
- const formatCell = ({ row }: any) => {
- if (row.original.isDisabled) {
- return (
-
- {intl.formatMessage({ id: "disabled" })}
-
- );
- }
-
- if (row.original.certificateId) {
- if (row.original.certificate.status === "provided") {
- return (
-
- {row.original.sslForced
- ? intl.formatMessage({ id: "https-only" })
- : intl.formatMessage({ id: "http-https" })}
-
- );
- }
-
- if (row.original.certificate.status === "error") {
- return (
-
-
- {intl.formatMessage({ id: "error" })}
-
-
- );
- }
-
- return (
-
- {intl.formatMessage({
- id: `certificate.${row.original.certificate.status}`,
- })}
-
- );
- }
-
- return (
-
- {intl.formatMessage({ id: "http-only" })}
-
- );
- };
-
- return formatCell;
-}
-
-function MonospaceFormatter() {
- const formatCell = ({ value }: any) => {
- return {value};
- };
-
- return formatCell;
-}
-
-function UpstreamStatusFormatter() {
- const formatCell = ({ value, row }: any) => {
- if (value === "ready") {
- return (
-
- {intl.formatMessage({ id: "status.ready" })}
-
- );
- }
- if (value === "ok") {
- return (
-
- {intl.formatMessage({ id: "status.ok" })}
-
- );
- }
- if (value === "error") {
- return (
-
-
-
- {intl.formatMessage({ id: "error" })}
-
-
-
-
-
-
- {row?.original?.errorMessage}
-
-
-
-
- );
- }
- };
-
- return formatCell;
-}
-
-function HostTypeFormatter() {
- const formatCell = ({ value }: any) => {
- return intl.formatMessage({ id: `host-type.${value}` });
- };
-
- return formatCell;
-}
-
-function IDFormatter() {
- const formatCell = ({ value }: any) => {
- return {value};
- };
-
- return formatCell;
-}
-
-function SecondsFormatter() {
- const formatCell = ({ value }: any) => {
- return intl.formatMessage({ id: "seconds" }, { seconds: value });
- };
-
- return formatCell;
-}
-
-export {
- ActionsFormatter,
- BooleanFormatter,
- CapabilitiesFormatter,
- CertificateStatusFormatter,
- CertificateTypeFormatter,
- DisabledFormatter,
- DNSProviderFormatter,
- DomainsFormatter,
- GravatarFormatter,
- HostStatusFormatter,
- HostTypeFormatter,
- IDFormatter,
- MonospaceFormatter,
- SecondsFormatter,
- UpstreamStatusFormatter,
-};
diff --git a/frontend/src/components/Table/RowActionsMenu.tsx b/frontend/src/components/Table/RowActionsMenu.tsx
deleted file mode 100644
index 6e0936040..000000000
--- a/frontend/src/components/Table/RowActionsMenu.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import { ReactNode } from "react";
-
-import {
- Menu,
- MenuButton,
- MenuList,
- MenuItem,
- IconButton,
-} from "@chakra-ui/react";
-import { FiMoreVertical } from "react-icons/fi";
-
-// A row action is a single menu item for the actions column
-export interface RowAction {
- title: string;
- onClick: (e: any, data: any) => any;
- show?: (data: any) => any;
- disabled?: (data: any) => any;
- icon?: any;
-}
-
-interface RowActionsProps {
- /**
- * Row Data
- */
- data: any;
- /**
- * Actions
- */
- actions: RowAction[];
-}
-function RowActionsMenu({ data, actions }: RowActionsProps) {
- const elms: ReactNode[] = [];
- actions.map((action) => {
- if (!action.show || action.show(data)) {
- const disabled = action.disabled && action.disabled(data);
- elms.push(
- ,
- );
- }
- return null;
- });
-
- if (!elms.length) {
- return null;
- }
-
- return (
-
-
-
- );
-}
-
-export { RowActionsMenu };
diff --git a/frontend/src/components/Table/TableBody.tsx b/frontend/src/components/Table/TableBody.tsx
new file mode 100644
index 000000000..a3114196b
--- /dev/null
+++ b/frontend/src/components/Table/TableBody.tsx
@@ -0,0 +1,37 @@
+import { flexRender, type RowData } from "@tanstack/react-table";
+import type { TableLayoutProps } from "src/components";
+import { EmptyRow } from "./EmptyRow";
+
+function TableBody(props: TableLayoutProps) {
+ const { tableInstance, extraStyles, emptyState } = props;
+ const rows = tableInstance.getRowModel().rows;
+
+ if (rows.length === 0) {
+ return (
+
+ {emptyState ? emptyState : }
+
+ );
+ }
+
+ return (
+
+ {rows.map((row: any) => {
+ return (
+
+ {row.getVisibleCells().map((cell: any) => {
+ const { className } = (cell.column.columnDef.meta as any) ?? {};
+ return (
+ |
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ |
+ );
+ })}
+
+ );
+ })}
+
+ );
+}
+
+export { TableBody };
diff --git a/frontend/src/components/Table/TableHeader.tsx b/frontend/src/components/Table/TableHeader.tsx
new file mode 100644
index 000000000..f656c4656
--- /dev/null
+++ b/frontend/src/components/Table/TableHeader.tsx
@@ -0,0 +1,53 @@
+import { IconArrowsSort, IconChevronDown, IconChevronUp } from "@tabler/icons-react";
+import { flexRender, type RowData } from "@tanstack/react-table";
+import type { TableLayoutProps } from "src/components";
+
+function TableHeader(props: TableLayoutProps) {
+ const { tableInstance } = props;
+ const headerGroups = tableInstance.getHeaderGroups();
+
+ return (
+
+ {headerGroups.map((headerGroup: any) => (
+
+ {headerGroup.headers.map((header: any) => {
+ const { column } = header;
+ const { className } = (column.columnDef.meta as any) ?? {};
+ const canSort = column.getCanSort();
+ const sortDir = column.getIsSorted();
+
+ const headerContent = header.isPlaceholder
+ ? null
+ : typeof column.columnDef.header === "string"
+ ? column.columnDef.header
+ : flexRender(column.columnDef.header, header.getContext());
+
+ const sortIcon = canSort ? (
+ sortDir === "asc" ? (
+
+ ) : sortDir === "desc" ? (
+
+ ) : (
+
+ )
+ ) : null;
+
+ return (
+ |
+ {headerContent}
+ {sortIcon}
+ |
+ );
+ })}
+
+ ))}
+
+ );
+}
+
+export { TableHeader };
diff --git a/frontend/src/components/Table/TableHelpers.ts b/frontend/src/components/Table/TableHelpers.ts
index 0df329c80..a6302e09b 100644
--- a/frontend/src/components/Table/TableHelpers.ts
+++ b/frontend/src/components/Table/TableHelpers.ts
@@ -61,4 +61,4 @@ const tableEventReducer = (state: any, { type, payload }: any) => {
}
};
-export { tableEvents, tableEventReducer };
+export { tableEventReducer, tableEvents };
diff --git a/frontend/src/components/Table/TableLayout.tsx b/frontend/src/components/Table/TableLayout.tsx
index cf8df7bd4..5db64bafc 100644
--- a/frontend/src/components/Table/TableLayout.tsx
+++ b/frontend/src/components/Table/TableLayout.tsx
@@ -1,251 +1,25 @@
-import { ReactNode } from "react";
+import type { Table as ReactTable, RowData } from "@tanstack/react-table";
+import type { Features } from "./features";
+import { TableBody } from "./TableBody";
+import { TableHeader } from "./TableHeader";
-import {
- ButtonGroup,
- Center,
- Flex,
- HStack,
- IconButton,
- Link,
- Select,
- Table,
- Tbody,
- Td,
- Text,
- Th,
- Thead,
- Tr,
- VStack,
-} from "@chakra-ui/react";
-import {
- FiChevronsLeft,
- FiChevronLeft,
- FiChevronsRight,
- FiChevronRight,
- FiChevronDown,
- FiChevronUp,
- FiX,
-} from "react-icons/fi";
-
-import { TablePagination } from "src/components";
-import { intl } from "src/locale";
-
-export interface TableLayoutProps {
- pagination: TablePagination;
- getTableProps: any;
- getTableBodyProps: any;
- headerGroups: any;
- rows: any;
- prepareRow: any;
- gotoPage: any;
- canPreviousPage: any;
- previousPage: any;
- canNextPage: any;
- nextPage: any;
- pageCount: any;
- pageOptions: any;
- visibleColumns: any;
- setAllFilters: any;
- state: any;
+interface TableLayoutProps {
+ tableInstance: ReactTable;
+ emptyState?: React.ReactNode;
+ extraStyles?: {
+ row: (rowData: TFields) => any | undefined;
+ };
}
-function TableLayout({
- pagination,
- getTableProps,
- getTableBodyProps,
- headerGroups,
- rows,
- prepareRow,
- gotoPage,
- canPreviousPage,
- previousPage,
- canNextPage,
- nextPage,
- pageCount,
- pageOptions,
- visibleColumns,
- setAllFilters,
- state,
-}: TableLayoutProps) {
- const currentPage = state.pageIndex + 1;
- const getPageList = () => {
- const list = [];
- for (let x = 0; x < pageOptions.length; x++) {
- list.push(
- ,
- );
- }
- return list;
- };
-
- const renderEmpty = (): ReactNode => {
- return (
-
- |
-
- {state?.filters?.length
- ? intl.formatMessage(
- { id: "tables.no-items-with-filters" },
- { count: state.filters.length },
- )
- : intl.formatMessage({ id: "tables.no-items" })}
-
- |
-
- );
- };
-
+function TableLayout(props: TableLayoutProps) {
+ const hasRows = props.tableInstance.getRowModel().rows.length > 0;
return (
- <>
-
-
- {headerGroups.map((headerGroup: any, idx: any) => (
-
- {headerGroup.headers.map((column: any, idx2: any) => (
- |
-
-
-
- {column.render("Header")}
-
- {column.sortable && column.isSorted ? (
- column.isSortedDesc ? (
-
- ) : (
-
- )
- ) : null}
- {column.Filter ? column.render("Filter") : null}
-
-
- |
- ))}
-
- ))}
-
-
- {rows.length
- ? rows.map((row: any, idx: any) => {
- prepareRow(row);
- return (
-
- {row.cells.map((cell: any, idx2: any) => (
- |
- {cell.render("Cell")}
- |
- ))}
-
- );
- })
- : renderEmpty()}
-
-
-
-
-
- {rows.length
- ? intl.formatMessage(
- { id: "tables.pagination-counts" },
- {
- start: pagination.offset + 1,
- end: Math.min(
- pagination.total,
- pagination.offset + pagination.limit,
- ),
- total: pagination.total,
- },
- )
- : null}
-
- {state?.filters?.length ? (
- setAllFilters([])}>
-
-
-
- {intl.formatMessage(
- { id: "tables.clear-all-filters" },
- { count: state.filters.length },
- )}
-
-
-
- ) : null}
-
-
-
- >
+
);
}
-export { TableLayout };
+export { TableLayout, type TableLayoutProps };
diff --git a/frontend/src/components/Table/TextFilter.tsx b/frontend/src/components/Table/TextFilter.tsx
deleted file mode 100644
index d1eeef7f1..000000000
--- a/frontend/src/components/Table/TextFilter.tsx
+++ /dev/null
@@ -1,143 +0,0 @@
-import {
- Popover,
- PopoverTrigger,
- PopoverContent,
- PopoverArrow,
- IconButton,
- FormControl,
- FormErrorMessage,
- Input,
- Stack,
- ButtonGroup,
- Button,
- useDisclosure,
- Select,
-} from "@chakra-ui/react";
-import { Formik, Form, Field } from "formik";
-import FocusLock from "react-focus-lock";
-import { FiFilter } from "react-icons/fi";
-
-import { PrettyButton } from "src/components";
-import { intl } from "src/locale";
-import { validateString } from "src/modules/Validations";
-
-function TextFilter({ column: { filterValue, setFilter } }: any) {
- const { onOpen, onClose, isOpen } = useDisclosure();
-
- const onSubmit = (values: any, { setSubmitting }: any) => {
- setFilter(values);
- setSubmitting(false);
- onClose();
- };
-
- const clearFilter = () => {
- setFilter(undefined);
- onClose();
- };
-
- const isFiltered = (): boolean => {
- return !(typeof filterValue === "undefined" || filterValue === "");
- };
-
- return (
-
-
- }
- aria-label="Filter"
- />
-
-
-
-
-
- {({ isSubmitting }) => (
-
- )}
-
-
-
-
- );
-}
-
-export { TextFilter };
diff --git a/frontend/src/components/Table/features.ts b/frontend/src/components/Table/features.ts
new file mode 100644
index 000000000..9b79e1d59
--- /dev/null
+++ b/frontend/src/components/Table/features.ts
@@ -0,0 +1,35 @@
+import {
+ columnVisibilityFeature,
+ createSortedRowModel,
+ metaHelper,
+ rowSortingFeature,
+ tableFeatures,
+} from "@tanstack/react-table";
+
+interface ColumnMeta {
+ className?: string;
+}
+
+interface TableMeta {
+ isFetching?: boolean;
+}
+
+/**
+ * Shared TanStack Table v9 feature registration for every table in the app.
+ * Sorting and column visibility are used (or their APIs are called
+ * unconditionally, e.g. `getVisibleFlatColumns`/`getVisibleCells`) by the
+ * shared TableLayout/TableHeader/TableBody/EmptyData components, so every
+ * table instance must register them even when a particular table doesn't
+ * wire up controlled sorting state itself.
+ */
+const features = tableFeatures({
+ rowSortingFeature,
+ sortedRowModel: createSortedRowModel(),
+ columnVisibilityFeature,
+ columnMeta: metaHelper(),
+ tableMeta: metaHelper(),
+});
+
+type Features = typeof features;
+
+export { type ColumnMeta, type Features, features, type TableMeta };
diff --git a/frontend/src/components/Table/index.ts b/frontend/src/components/Table/index.ts
index 16d6d0a60..84b64610a 100644
--- a/frontend/src/components/Table/index.ts
+++ b/frontend/src/components/Table/index.ts
@@ -1,5 +1,5 @@
-export * from "./Formatters";
-export * from "./RowActionsMenu";
+export * from "./Formatter";
+export * from "./features";
+export * from "./TableHeader";
export * from "./TableHelpers";
export * from "./TableLayout";
-export * from "./TextFilter";
diff --git a/frontend/src/components/Table/react-table-config.d.ts b/frontend/src/components/Table/react-table-config.d.ts
deleted file mode 100644
index 59f716890..000000000
--- a/frontend/src/components/Table/react-table-config.d.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-// See: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react-table#configuration-using-declaration-merging
-import {
- UseColumnOrderInstanceProps,
- UseColumnOrderState,
- UseExpandedHooks,
- UseExpandedInstanceProps,
- UseExpandedOptions,
- UseExpandedRowProps,
- UseExpandedState,
- UseFiltersColumnOptions,
- UseFiltersColumnProps,
- UseFiltersInstanceProps,
- UseFiltersOptions,
- UseFiltersState,
- UseGlobalFiltersColumnOptions,
- UseGlobalFiltersInstanceProps,
- UseGlobalFiltersOptions,
- UseGlobalFiltersState,
- UseGroupByCellProps,
- UseGroupByColumnOptions,
- UseGroupByColumnProps,
- UseGroupByHooks,
- UseGroupByInstanceProps,
- UseGroupByOptions,
- UseGroupByRowProps,
- UseGroupByState,
- UsePaginationInstanceProps,
- UsePaginationOptions,
- UsePaginationState,
- UseResizeColumnsColumnOptions,
- UseResizeColumnsColumnProps,
- UseResizeColumnsOptions,
- UseResizeColumnsState,
- UseRowSelectHooks,
- UseRowSelectInstanceProps,
- UseRowSelectOptions,
- UseRowSelectRowProps,
- UseRowSelectState,
- UseRowStateCellProps,
- UseRowStateInstanceProps,
- UseRowStateOptions,
- UseRowStateRowProps,
- UseRowStateState,
- UseSortByColumnOptions,
- UseSortByColumnProps,
- UseSortByHooks,
- UseSortByInstanceProps,
- UseSortByOptions,
- UseSortByState,
-} from "react-table";
-
-declare module "react-table" {
- // take this file as-is, or comment out the sections that don't apply to your plugin configuration
-
- export interface TableOptions>
- extends UseExpandedOptions,
- UseFiltersOptions,
- UseGlobalFiltersOptions,
- UseGroupByOptions,
- UsePaginationOptions,
- UseResizeColumnsOptions,
- UseRowSelectOptions,
- UseRowStateOptions,
- UseSortByOptions,
- // note that having Record here allows you to add anything to the options, this matches the spirit of the
- // underlying js library, but might be cleaner if it's replaced by a more specific type that matches your
- // feature set, this is a safe default.
- Record {}
-
- export interface Hooks<
- D extends Record = Record,
- > extends UseExpandedHooks,
- UseGroupByHooks,
- UseRowSelectHooks,
- UseSortByHooks {}
-
- export interface TableInstance<
- D extends Record = Record,
- > extends UseColumnOrderInstanceProps,
- UseExpandedInstanceProps,
- UseFiltersInstanceProps,
- UseGlobalFiltersInstanceProps,
- UseGroupByInstanceProps,
- UsePaginationInstanceProps,
- UseRowSelectInstanceProps,
- UseRowStateInstanceProps,
- UseSortByInstanceProps {}
-
- export interface TableState<
- D extends Record = Record,
- > extends UseColumnOrderState,
- UseExpandedState,
- UseFiltersState,
- UseGlobalFiltersState,
- UseGroupByState,
- UsePaginationState,
- UseResizeColumnsState,
- UseRowSelectState,
- UseRowStateState,
- UseSortByState {}
-
- export interface ColumnInterface<
- D extends Record = Record,
- > extends UseFiltersColumnOptions,
- UseGlobalFiltersColumnOptions,
- UseGroupByColumnOptions,
- UseResizeColumnsColumnOptions,
- UseSortByColumnOptions {}
-
- export interface ColumnInstance<
- D extends Record = Record,
- > extends UseFiltersColumnProps,
- UseGroupByColumnProps,
- UseResizeColumnsColumnProps,
- UseSortByColumnProps {}
-
- export interface Cell<
- D extends Record = Record,
- // V = any,
- > extends UseGroupByCellProps,
- UseRowStateCellProps {}
-
- export interface Row<
- D extends Record = Record,
- > extends UseExpandedRowProps,
- UseGroupByRowProps,
- UseRowSelectRowProps,
- UseRowStateRowProps {}
-}
diff --git a/frontend/src/components/ThemeSwitcher.module.css b/frontend/src/components/ThemeSwitcher.module.css
new file mode 100644
index 000000000..2233d2f8f
--- /dev/null
+++ b/frontend/src/components/ThemeSwitcher.module.css
@@ -0,0 +1,15 @@
+.darkBtn {
+ color: var(--tblr-light) !important;
+ &:hover {
+ border: var(--tblr-btn-border-width) solid transparent !important;
+ background: color-mix(in srgb, var(--tblr-btn-hover-bg) 10%, transparent) !important;
+ }
+}
+
+.lightBtn {
+ color: var(--tblr-dark) !important;
+ &:hover {
+ border: var(--tblr-btn-border-width) solid transparent !important;
+ background: color-mix(in srgb, var(--tblr-btn-hover-bg) 10%, transparent) !important;
+ }
+}
diff --git a/frontend/src/components/ThemeSwitcher.tsx b/frontend/src/components/ThemeSwitcher.tsx
index af155100c..9cb669787 100644
--- a/frontend/src/components/ThemeSwitcher.tsx
+++ b/frontend/src/components/ThemeSwitcher.tsx
@@ -1,34 +1,40 @@
-import {
- Icon,
- IconButton,
- IconButtonProps,
- useColorMode,
-} from "@chakra-ui/react";
-import { FiSun, FiMoon } from "react-icons/fi";
+import { IconMoon, IconSun } from "@tabler/icons-react";
+import cn from "classnames";
+import { Button } from "src/components";
+import { useTheme } from "src/hooks";
+import styles from "./ThemeSwitcher.module.css";
-import { intl } from "src/locale";
-
-interface ThemeSwitcherProps {
- background?: "normal" | "transparent";
+interface Props {
+ className?: string;
}
-function ThemeSwitcher({ background }: ThemeSwitcherProps) {
- const { colorMode, toggleColorMode } = useColorMode();
- const additionalProps: Partial = {};
- if (background === "transparent") {
- additionalProps["backgroundColor"] = "transparent";
- }
+function ThemeSwitcher({ className }: Props) {
+ const { setTheme } = useTheme();
return (
- }
- />
+
+
+
+
);
}
diff --git a/frontend/src/components/Unhealthy.tsx b/frontend/src/components/Unhealthy.tsx
index ee028d5cf..d4b6e33c9 100644
--- a/frontend/src/components/Unhealthy.tsx
+++ b/frontend/src/components/Unhealthy.tsx
@@ -1,39 +1,17 @@
-import { Box, Flex, Heading, Text, Stack } from "@chakra-ui/react";
-import { FaTimes } from "react-icons/fa";
+import { Page } from "src/components";
-import { LocalePicker, ThemeSwitcher } from "src/components";
-import { intl } from "src/locale";
-
-function Unhealthy() {
+export function Unhealthy() {
return (
- <>
-
-
-
-
-
-
-
-
-
-
-
- {intl.formatMessage({ id: "unhealthy.title" })}
-
-
- {intl.formatMessage({ id: "unhealthy.body" })}
-
-
- >
+
+
+
+
+

+
+
The API is not healthy.
+
We'll keep checking and hope to be back soon!
+
+
+
);
}
-
-export { Unhealthy };
diff --git a/frontend/src/components/index.ts b/frontend/src/components/index.ts
index 3f88be3ed..42f214be7 100644
--- a/frontend/src/components/index.ts
+++ b/frontend/src/components/index.ts
@@ -1,17 +1,17 @@
-export * from "./EmptyList";
-export * from "./Flag";
-export * from "./Footer";
-export * from "./HelpDrawer";
-export * from "./Loader";
+export * from "./Button";
+export * from "./EmptyData";
+export * from "./ErrorNotFound";
+export * from "./Form";
+export * from "./HasPermission";
export * from "./Loading";
+export * from "./LoadingPage";
export * from "./LocalePicker";
-export * from "./Monospace";
-export * from "./Navigation";
-export * from "./Permissions";
-export * from "./PrettyButton";
-export * from "./PrettyMenuButton";
-export * from "./SiteWrapper";
-export * from "./SpinnerPage";
+export * from "./NavLink";
+export * from "./Page";
+export * from "./SiteContainer";
+export * from "./SiteFooter";
+export * from "./SiteHeader";
+export * from "./SiteMenu";
export * from "./Table";
export * from "./ThemeSwitcher";
export * from "./Unhealthy";
diff --git a/frontend/src/context/AuthContext.tsx b/frontend/src/context/AuthContext.tsx
index c3a196e8c..29399c9f3 100644
--- a/frontend/src/context/AuthContext.tsx
+++ b/frontend/src/context/AuthContext.tsx
@@ -1,16 +1,29 @@
-import { createContext, ReactNode, useContext, useState } from "react";
-
import { useQueryClient } from "@tanstack/react-query";
+import { createContext, type ReactNode, useContext, useState } from "react";
import { useIntervalWhen } from "rooks";
-
-import { getToken, refreshToken, TokenResponse } from "src/api/npm";
+import {
+ getToken,
+ isTwoFactorChallenge,
+ loginAsUser,
+ refreshToken,
+ type TokenResponse,
+ verify2FA,
+} from "src/api/backend";
import AuthStore from "src/modules/AuthStore";
+// 2FA challenge state
+export interface TwoFactorChallenge {
+ challengeToken: string;
+}
+
// Context
export interface AuthContextType {
authenticated: boolean;
- handleTokenUpdate: (response: TokenResponse) => void;
+ twoFactorChallenge: TwoFactorChallenge | null;
login: (type: string, username: string, password: string) => Promise;
+ verifyTwoFactor: (code: string) => Promise;
+ cancelTwoFactor: () => void;
+ loginAs: (id: number) => Promise;
logout: () => void;
token?: string;
}
@@ -23,26 +36,52 @@ interface Props {
children?: ReactNode;
tokenRefreshInterval?: number;
}
-function AuthProvider({
- children,
- tokenRefreshInterval = 5 * 60 * 1000,
-}: Props) {
+function AuthProvider({ children, tokenRefreshInterval = 5 * 60 * 1000 }: Props) {
const queryClient = useQueryClient();
- const [authenticated, setAuthenticated] = useState(
- AuthStore.hasActiveToken(),
- );
+ const [authenticated, setAuthenticated] = useState(AuthStore.hasActiveToken());
+ const [twoFactorChallenge, setTwoFactorChallenge] = useState(null);
const handleTokenUpdate = (response: TokenResponse) => {
AuthStore.set(response);
setAuthenticated(true);
+ setTwoFactorChallenge(null);
};
const login = async (type: string, identity: string, secret: string) => {
- const response = await getToken({ payload: { type, identity, secret } });
+ const response = await getToken({ type, identity, secret });
+ if (isTwoFactorChallenge(response)) {
+ setTwoFactorChallenge({ challengeToken: response.challengeToken });
+ return;
+ }
handleTokenUpdate(response);
};
+ const verifyTwoFactor = async (code: string) => {
+ if (!twoFactorChallenge) {
+ throw new Error("No 2FA challenge pending");
+ }
+ const response = await verify2FA(twoFactorChallenge.challengeToken, code);
+ handleTokenUpdate(response);
+ };
+
+ const cancelTwoFactor = () => {
+ setTwoFactorChallenge(null);
+ };
+
+ const loginAs = async (id: number) => {
+ const response = await loginAsUser(id);
+ AuthStore.add(response);
+ queryClient.clear();
+ window.location.reload();
+ };
+
const logout = () => {
+ if (AuthStore.count() >= 2) {
+ AuthStore.drop();
+ queryClient.clear();
+ window.location.reload();
+ return;
+ }
AuthStore.clear();
setAuthenticated(false);
queryClient.clear();
@@ -63,7 +102,15 @@ function AuthProvider({
true,
);
- const value = { authenticated, login, logout, handleTokenUpdate };
+ const value = {
+ authenticated,
+ twoFactorChallenge,
+ login,
+ verifyTwoFactor,
+ cancelTwoFactor,
+ loginAs,
+ logout,
+ };
return {children};
}
@@ -71,7 +118,7 @@ function AuthProvider({
function useAuthState() {
const context = useContext(AuthContext);
if (!context) {
- throw new Error(`useAuthState must be used within a AuthProvider`);
+ throw new Error("useAuthState must be used within a AuthProvider");
}
return context;
}
diff --git a/frontend/src/context/LocaleContext.tsx b/frontend/src/context/LocaleContext.tsx
index 4056e52fd..ca30a5f31 100644
--- a/frontend/src/context/LocaleContext.tsx
+++ b/frontend/src/context/LocaleContext.tsx
@@ -1,5 +1,4 @@
-import { createContext, ReactNode, useContext, useState } from "react";
-
+import { createContext, type ReactNode, useContext, useState } from "react";
import { getLocale } from "src/locale";
// Context
@@ -24,15 +23,13 @@ function LocaleProvider({ children }: Props) {
const value = { locale, setLocale };
- return (
- {children}
- );
+ return {children};
}
function useLocaleState() {
const context = useContext(LocaleContext);
if (!context) {
- throw new Error(`useLocaleState must be used within a LocaleProvider`);
+ throw new Error("useLocaleState must be used within a LocaleProvider");
}
return context;
}
diff --git a/frontend/src/context/ThemeContext.tsx b/frontend/src/context/ThemeContext.tsx
new file mode 100644
index 000000000..e01ad022c
--- /dev/null
+++ b/frontend/src/context/ThemeContext.tsx
@@ -0,0 +1,70 @@
+import type React from "react";
+import { createContext, type ReactNode, useContext, useEffect, useState } from "react";
+
+const StorageKey = "tabler-theme";
+export const Light = "light";
+export const Dark = "dark";
+
+// Define theme types
+export type Theme = "light" | "dark";
+
+interface ThemeContextType {
+ theme: Theme;
+ toggleTheme: () => void;
+ setTheme: (theme: Theme) => void;
+ getTheme: () => Theme;
+}
+
+const ThemeContext = createContext(undefined);
+
+interface ThemeProviderProps {
+ children: ReactNode;
+}
+
+const getBrowserDefault = (): Theme => {
+ if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
+ return Dark;
+ }
+ return Light;
+};
+
+export const ThemeProvider: React.FC = ({ children }) => {
+ const [theme, setThemeState] = useState(() => {
+ // Try to read theme from localStorage or use 'light' as default
+ if (typeof window !== "undefined") {
+ const stored = localStorage.getItem(StorageKey) as Theme | null;
+ return stored || getBrowserDefault();
+ }
+ return getBrowserDefault();
+ });
+
+ useEffect(() => {
+ document.body.dataset.theme = theme;
+ document.body.classList.remove(theme === Light ? Dark : Light);
+ document.body.classList.add(theme);
+ localStorage.setItem(StorageKey, theme);
+ }, [theme]);
+
+ const toggleTheme = () => {
+ setThemeState((prev) => (prev === Light ? Dark : Light));
+ };
+
+ const setTheme = (newTheme: Theme) => {
+ setThemeState(newTheme);
+ };
+
+ const getTheme = () => {
+ return theme;
+ };
+
+ document.documentElement.setAttribute("data-bs-theme", theme);
+ return {children};
+};
+
+export function useTheme(): ThemeContextType {
+ const context = useContext(ThemeContext);
+ if (!context) {
+ throw new Error("useTheme must be used within a ThemeProvider");
+ }
+ return context;
+}
diff --git a/frontend/src/context/index.ts b/frontend/src/context/index.ts
index 224db0581..a24e06574 100644
--- a/frontend/src/context/index.ts
+++ b/frontend/src/context/index.ts
@@ -1,2 +1,3 @@
export * from "./AuthContext";
export * from "./LocaleContext";
+export * from "./ThemeContext";
diff --git a/frontend/src/hooks/index.ts b/frontend/src/hooks/index.ts
index ca1d1842e..761c9578c 100644
--- a/frontend/src/hooks/index.ts
+++ b/frontend/src/hooks/index.ts
@@ -1,16 +1,25 @@
+export * from "./useAccessList";
export * from "./useAccessLists";
+export * from "./useAuditLog";
+export * from "./useAuditLogs";
export * from "./useCertificate";
-export * from "./useCertificateAuthorities";
-export * from "./useCertificateAuthority";
export * from "./useCertificates";
-export * from "./useDNSProvider";
-export * from "./useDNSProviders";
-export * from "./useDNSProvidersAcmesh";
+export * from "./useCheckVersion";
+export * from "./useDeadHost";
+export * from "./useDeadHosts";
+export * from "./useDnsProviders";
export * from "./useHealth";
-export * from "./useHosts";
-export * from "./useNginxTemplates";
-export * from "./useSettings";
-export * from "./useUpstreamNginxConfig";
-export * from "./useUpstreams";
+export * from "./useHostReport";
+export * from "./useLogSources";
+export * from "./useLogTail";
+export * from "./useProxyHost";
+export * from "./useProxyHostLogs";
+export * from "./useProxyHosts";
+export * from "./useRedirectionHost";
+export * from "./useRedirectionHosts";
+export * from "./useSetting";
+export * from "./useStream";
+export * from "./useStreams";
+export * from "./useTheme";
export * from "./useUser";
export * from "./useUsers";
diff --git a/frontend/src/hooks/useAccessList.ts b/frontend/src/hooks/useAccessList.ts
new file mode 100644
index 000000000..1f6638588
--- /dev/null
+++ b/frontend/src/hooks/useAccessList.ts
@@ -0,0 +1,60 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ type AccessList,
+ type AccessListExpansion,
+ createAccessList,
+ getAccessList,
+ updateAccessList,
+} from "src/api/backend";
+
+const fetchAccessList = (id: number | "new", expand: AccessListExpansion[] = ["owner"]) => {
+ if (id === "new") {
+ return Promise.resolve({
+ id: 0,
+ createdOn: "",
+ modifiedOn: "",
+ ownerUserId: 0,
+ name: "",
+ satisfyAny: false,
+ passAuth: false,
+ meta: {},
+ } as AccessList);
+ }
+ return getAccessList(id, expand);
+};
+
+const useAccessList = (id: number | "new", expand?: AccessListExpansion[], options = {}) => {
+ return useQuery({
+ queryKey: ["access-list", id, expand],
+ queryFn: () => fetchAccessList(id, expand),
+ staleTime: 60 * 1000, // 1 minute
+ ...options,
+ });
+};
+
+const useSetAccessList = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (values: AccessList) => (values.id ? updateAccessList(values) : createAccessList(values)),
+ onMutate: (values: AccessList) => {
+ if (!values.id) {
+ return;
+ }
+ const previousObject = queryClient.getQueryData(["access-list", values.id]);
+ queryClient.setQueryData(["access-list", values.id], (old: AccessList) => ({
+ ...old,
+ ...values,
+ }));
+ return () => queryClient.setQueryData(["access-list", values.id], previousObject);
+ },
+ onError: (_, __, rollback: any) => rollback(),
+ onSuccess: async ({ id }: AccessList) => {
+ queryClient.invalidateQueries({ queryKey: ["access-list", id] });
+ queryClient.invalidateQueries({ queryKey: ["access-lists"] });
+ queryClient.invalidateQueries({ queryKey: ["audit-logs"] });
+ queryClient.invalidateQueries({ queryKey: ["proxy-hosts"] });
+ },
+ });
+};
+
+export { useAccessList, useSetAccessList };
diff --git a/frontend/src/hooks/useAccessLists.ts b/frontend/src/hooks/useAccessLists.ts
index 4dff5d029..cb052f68c 100644
--- a/frontend/src/hooks/useAccessLists.ts
+++ b/frontend/src/hooks/useAccessLists.ts
@@ -1,39 +1,17 @@
import { useQuery } from "@tanstack/react-query";
+import { type AccessList, type AccessListExpansion, getAccessLists } from "src/api/backend";
-import {
- getAccessLists,
- AccessListsResponse,
- tableSortToAPI,
- tableFiltersToAPI,
-} from "src/api/npm";
-
-const fetchAccessLists = (
- offset = 0,
- limit = 10,
- sortBy?: any,
- filters?: any,
-) => {
- return getAccessLists(
- offset,
- limit,
- tableSortToAPI(sortBy),
- tableFiltersToAPI(filters),
- );
+const fetchAccessLists = (expand?: AccessListExpansion[]) => {
+ return getAccessLists(expand);
};
-const useAccessLists = (
- offset = 0,
- limit = 10,
- sortBy?: any,
- filters?: any,
- options = {},
-) => {
- return useQuery({
- queryKey: ["access-lists", { offset, limit, sortBy, filters }],
- queryFn: () => fetchAccessLists(offset, limit, sortBy, filters),
- staleTime: 15 * 1000, // 15 seconds
+const useAccessLists = (expand?: AccessListExpansion[], options = {}) => {
+ return useQuery({
+ queryKey: ["access-lists", { expand }],
+ queryFn: () => fetchAccessLists(expand),
+ staleTime: 60 * 1000,
...options,
});
};
-export { useAccessLists };
+export { fetchAccessLists, useAccessLists };
diff --git a/frontend/src/hooks/useAuditLog.ts b/frontend/src/hooks/useAuditLog.ts
new file mode 100644
index 000000000..95e08ebcd
--- /dev/null
+++ b/frontend/src/hooks/useAuditLog.ts
@@ -0,0 +1,17 @@
+import { useQuery } from "@tanstack/react-query";
+import { type AuditLog, getAuditLog } from "src/api/backend";
+
+const fetchAuditLog = (id: number) => {
+ return getAuditLog(id, ["user"]);
+};
+
+const useAuditLog = (id: number, options = {}) => {
+ return useQuery({
+ queryKey: ["audit-log", id],
+ queryFn: () => fetchAuditLog(id),
+ staleTime: 5 * 60 * 1000, // 5 minutes
+ ...options,
+ });
+};
+
+export { useAuditLog };
diff --git a/frontend/src/hooks/useAuditLogs.ts b/frontend/src/hooks/useAuditLogs.ts
new file mode 100644
index 000000000..bbe8b5063
--- /dev/null
+++ b/frontend/src/hooks/useAuditLogs.ts
@@ -0,0 +1,17 @@
+import { useQuery } from "@tanstack/react-query";
+import { type AuditLog, type AuditLogExpansion, getAuditLogs } from "src/api/backend";
+
+const fetchAuditLogs = (expand?: AuditLogExpansion[]) => {
+ return getAuditLogs(expand);
+};
+
+const useAuditLogs = (expand?: AuditLogExpansion[], options = {}) => {
+ return useQuery({
+ queryKey: ["audit-logs", { expand }],
+ queryFn: () => fetchAuditLogs(expand),
+ staleTime: 10 * 1000,
+ ...options,
+ });
+};
+
+export { fetchAuditLogs, useAuditLogs };
diff --git a/frontend/src/hooks/useCertificate.ts b/frontend/src/hooks/useCertificate.ts
index 87691f9f0..fc99c8402 100644
--- a/frontend/src/hooks/useCertificate.ts
+++ b/frontend/src/hooks/useCertificate.ts
@@ -1,14 +1,8 @@
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useQuery } from "@tanstack/react-query";
+import { type Certificate, getCertificate } from "src/api/backend";
-import {
- createCertificate,
- getCertificate,
- setCertificate,
- Certificate,
-} from "src/api/npm";
-
-const fetchCertificate = (id: any) => {
- return getCertificate(id);
+const fetchCertificate = (id: number) => {
+ return getCertificate(id, ["owner"]);
};
const useCertificate = (id: number, options = {}) => {
@@ -20,34 +14,4 @@ const useCertificate = (id: number, options = {}) => {
});
};
-const useSetCertificate = () => {
- const queryClient = useQueryClient();
- return useMutation({
- mutationFn: (values: Certificate) => {
- return values.id
- ? setCertificate(values.id, values)
- : createCertificate(values);
- },
- onMutate: (values: Certificate) => {
- const previousObject = queryClient.getQueryData([
- "certificate",
- values.id,
- ]);
-
- queryClient.setQueryData(["certificate", values.id], (old: any) => ({
- ...old,
- ...values,
- }));
-
- return () =>
- queryClient.setQueryData(["certificate", values.id], previousObject);
- },
- onError: (_, __, rollback: any) => rollback(),
- onSuccess: async ({ id }: Certificate) => {
- queryClient.invalidateQueries({ queryKey: ["certificate", id] });
- queryClient.invalidateQueries({ queryKey: ["certificates"] });
- },
- });
-};
-
-export { useCertificate, useSetCertificate };
+export { useCertificate };
diff --git a/frontend/src/hooks/useCertificateAuthorities.ts b/frontend/src/hooks/useCertificateAuthorities.ts
deleted file mode 100644
index a4bcc9325..000000000
--- a/frontend/src/hooks/useCertificateAuthorities.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-
-import {
- CertificateAuthoritiesResponse,
- getCertificateAuthorities,
- tableSortToAPI,
- tableFiltersToAPI,
-} from "src/api/npm";
-
-const fetchCertificateAuthorities = (
- offset = 0,
- limit = 10,
- sortBy?: any,
- filters?: any,
-) => {
- return getCertificateAuthorities(
- offset,
- limit,
- tableSortToAPI(sortBy),
- tableFiltersToAPI(filters),
- );
-};
-
-const useCertificateAuthorities = (
- offset = 0,
- limit = 10,
- sortBy?: any,
- filters?: any,
- options = {},
-) => {
- return useQuery({
- queryKey: ["certificate-authorities", { offset, limit, sortBy, filters }],
- queryFn: () => fetchCertificateAuthorities(offset, limit, sortBy, filters),
- staleTime: 15 * 1000, // 15 seconds
- ...options,
- });
-};
-
-export { fetchCertificateAuthorities, useCertificateAuthorities };
diff --git a/frontend/src/hooks/useCertificateAuthority.ts b/frontend/src/hooks/useCertificateAuthority.ts
deleted file mode 100644
index 15814e30e..000000000
--- a/frontend/src/hooks/useCertificateAuthority.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-
-import {
- createCertificateAuthority,
- getCertificateAuthority,
- setCertificateAuthority,
- CertificateAuthority,
-} from "src/api/npm";
-
-const fetchCertificateAuthority = (id: any) => {
- return getCertificateAuthority(id);
-};
-
-const useCertificateAuthority = (id: number, options = {}) => {
- return useQuery({
- queryKey: ["certificate-authority", id],
- queryFn: () => fetchCertificateAuthority(id),
- staleTime: 60 * 1000, // 1 minute
- ...options,
- });
-};
-
-const useSetCertificateAuthority = () => {
- const queryClient = useQueryClient();
- return useMutation({
- mutationFn: (values: CertificateAuthority) => {
- return values.id
- ? setCertificateAuthority(values.id, values)
- : createCertificateAuthority(values);
- },
- onMutate: (values: CertificateAuthority) => {
- const previousObject = queryClient.getQueryData([
- "certificate-authority",
- values.id,
- ]);
-
- queryClient.setQueryData(
- ["certificate-authority", values.id],
- (old: any) => ({
- ...old,
- ...values,
- }),
- );
-
- return () =>
- queryClient.setQueryData(
- ["certificate-authority", values.id],
- previousObject,
- );
- },
- onError: (_: any, __: any, rollback: any) => rollback(),
- onSuccess: async ({ id }: CertificateAuthority) => {
- queryClient.invalidateQueries({
- queryKey: ["certificate-authority", id],
- });
- queryClient.invalidateQueries({
- queryKey: ["certificate-authorities"],
- });
- },
- });
-};
-
-export { useCertificateAuthority, useSetCertificateAuthority };
diff --git a/frontend/src/hooks/useCertificates.ts b/frontend/src/hooks/useCertificates.ts
index 26557e520..261c79d81 100644
--- a/frontend/src/hooks/useCertificates.ts
+++ b/frontend/src/hooks/useCertificates.ts
@@ -1,37 +1,15 @@
import { useQuery } from "@tanstack/react-query";
+import { type Certificate, type CertificateExpansion, getCertificates } from "src/api/backend";
-import {
- getCertificates,
- CertificatesResponse,
- tableSortToAPI,
- tableFiltersToAPI,
-} from "src/api/npm";
-
-const fetchCertificates = (
- offset = 0,
- limit = 10,
- sortBy?: any,
- filters?: any,
-) => {
- return getCertificates(
- offset,
- limit,
- tableSortToAPI(sortBy),
- tableFiltersToAPI(filters),
- );
+const fetchCertificates = (expand?: CertificateExpansion[]) => {
+ return getCertificates(expand);
};
-const useCertificates = (
- offset = 0,
- limit = 10,
- sortBy?: any,
- filters?: any,
- options = {},
-) => {
- return useQuery({
- queryKey: ["certificates", { offset, limit, sortBy, filters }],
- queryFn: () => fetchCertificates(offset, limit, sortBy, filters),
- staleTime: 15 * 1000, // 15 seconds
+const useCertificates = (expand?: CertificateExpansion[], options = {}) => {
+ return useQuery({
+ queryKey: ["certificates", { expand }],
+ queryFn: () => fetchCertificates(expand),
+ staleTime: 60 * 1000,
...options,
});
};
diff --git a/frontend/src/hooks/useCheckVersion.ts b/frontend/src/hooks/useCheckVersion.ts
new file mode 100644
index 000000000..83ee9960b
--- /dev/null
+++ b/frontend/src/hooks/useCheckVersion.ts
@@ -0,0 +1,18 @@
+import { useQuery } from "@tanstack/react-query";
+import { checkVersion, type VersionCheckResponse } from "src/api/backend";
+
+const fetchVersion = () => checkVersion();
+
+const useCheckVersion = (options = {}) => {
+ return useQuery({
+ queryKey: ["version-check"],
+ queryFn: fetchVersion,
+ refetchOnWindowFocus: false,
+ retry: 5,
+ refetchInterval: 30 * 1000, // 30 seconds
+ staleTime: 5 * 60 * 1000, // 5 mins
+ ...options,
+ });
+};
+
+export { fetchVersion, useCheckVersion };
diff --git a/frontend/src/hooks/useDNSProvider.ts b/frontend/src/hooks/useDNSProvider.ts
deleted file mode 100644
index 17260ed4f..000000000
--- a/frontend/src/hooks/useDNSProvider.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-
-import {
- createDNSProvider,
- getDNSProvider,
- setDNSProvider,
- DNSProvider,
-} from "src/api/npm";
-
-const fetchDNSProvider = (id: any) => {
- return getDNSProvider(id);
-};
-
-const useDNSProvider = (id: number, options = {}) => {
- return useQuery({
- queryKey: ["dns-provider", id],
- queryFn: () => fetchDNSProvider(id),
- staleTime: 60 * 1000, // 1 minute
- ...options,
- });
-};
-
-const useSetDNSProvider = () => {
- const queryClient = useQueryClient();
- return useMutation({
- mutationFn: (values: DNSProvider) => {
- return values.id
- ? setDNSProvider(values.id, values)
- : createDNSProvider(values);
- },
- onMutate: (values: DNSProvider) => {
- const previousObject = queryClient.getQueryData([
- "dns-provider",
- values.id,
- ]);
-
- queryClient.setQueryData(["dns-provider", values.id], (old: any) => ({
- ...old,
- ...values,
- }));
-
- return () =>
- queryClient.setQueryData(["dns-provider", values.id], previousObject);
- },
- onError: (_, __, rollback: any) => rollback(),
- onSuccess: async ({ id }: DNSProvider) => {
- queryClient.invalidateQueries({ queryKey: ["dns-provider", id] });
- queryClient.invalidateQueries({ queryKey: ["dns-providers"] });
- },
- });
-};
-
-export { useDNSProvider, useSetDNSProvider };
diff --git a/frontend/src/hooks/useDNSProviders.ts b/frontend/src/hooks/useDNSProviders.ts
deleted file mode 100644
index 0a9fbbb89..000000000
--- a/frontend/src/hooks/useDNSProviders.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-
-import {
- getDNSProviders,
- DNSProvidersResponse,
- tableSortToAPI,
- tableFiltersToAPI,
-} from "src/api/npm";
-
-const fetchDNSProviders = (
- offset = 0,
- limit = 10,
- sortBy?: any,
- filters?: any,
-) => {
- return getDNSProviders(
- offset,
- limit,
- tableSortToAPI(sortBy),
- tableFiltersToAPI(filters),
- );
-};
-
-const useDNSProviders = (
- offset = 0,
- limit = 10,
- sortBy?: any,
- filters?: any,
- options = {},
-) => {
- return useQuery({
- queryKey: ["dns-providers", { offset, limit, sortBy, filters }],
- queryFn: () => fetchDNSProviders(offset, limit, sortBy, filters),
- staleTime: 15 * 1000, // 15 seconds
- ...options,
- });
-};
-
-export { useDNSProviders };
diff --git a/frontend/src/hooks/useDNSProvidersAcmesh.ts b/frontend/src/hooks/useDNSProvidersAcmesh.ts
deleted file mode 100644
index 1b92349e3..000000000
--- a/frontend/src/hooks/useDNSProvidersAcmesh.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-
-import { DNSProvidersAcmesh, getDNSProvidersAcmesh } from "src/api/npm";
-
-const useDNSProvidersAcmesh = (options = {}) => {
- return useQuery({
- queryKey: ["dns-providers-acmesh"],
- queryFn: () => getDNSProvidersAcmesh(),
- staleTime: 60 * 60 * 1000, // 1 hour
- ...options,
- });
-};
-
-export { useDNSProvidersAcmesh };
diff --git a/frontend/src/hooks/useDeadHost.ts b/frontend/src/hooks/useDeadHost.ts
new file mode 100644
index 000000000..dd8355e3a
--- /dev/null
+++ b/frontend/src/hooks/useDeadHost.ts
@@ -0,0 +1,60 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { createDeadHost, type DeadHost, getDeadHost, updateDeadHost } from "src/api/backend";
+
+const fetchDeadHost = (id: number | "new") => {
+ if (id === "new") {
+ return Promise.resolve({
+ id: 0,
+ createdOn: "",
+ modifiedOn: "",
+ ownerUserId: 0,
+ domainNames: [],
+ certificateId: 0,
+ sslForced: false,
+ advancedConfig: "",
+ meta: {},
+ http2Support: false,
+ enabled: true,
+ hstsEnabled: false,
+ hstsSubdomains: false,
+ } as DeadHost);
+ }
+ return getDeadHost(id, ["owner"]);
+};
+
+const useDeadHost = (id: number | "new", options = {}) => {
+ return useQuery({
+ queryKey: ["dead-host", id],
+ queryFn: () => fetchDeadHost(id),
+ staleTime: 60 * 1000, // 1 minute
+ ...options,
+ });
+};
+
+const useSetDeadHost = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (values: DeadHost) => (values.id ? updateDeadHost(values) : createDeadHost(values)),
+ onMutate: (values: DeadHost) => {
+ if (!values.id) {
+ return;
+ }
+ const previousObject = queryClient.getQueryData(["dead-host", values.id]);
+ queryClient.setQueryData(["dead-host", values.id], (old: DeadHost) => ({
+ ...old,
+ ...values,
+ }));
+ return () => queryClient.setQueryData(["dead-host", values.id], previousObject);
+ },
+ onError: (_, __, rollback: any) => rollback(),
+ onSuccess: async ({ id }: DeadHost) => {
+ queryClient.invalidateQueries({ queryKey: ["dead-host", id] });
+ queryClient.invalidateQueries({ queryKey: ["dead-hosts"] });
+ queryClient.invalidateQueries({ queryKey: ["audit-logs"] });
+ queryClient.invalidateQueries({ queryKey: ["host-report"] });
+ queryClient.invalidateQueries({ queryKey: ["certificates"] });
+ },
+ });
+};
+
+export { useDeadHost, useSetDeadHost };
diff --git a/frontend/src/hooks/useDeadHosts.ts b/frontend/src/hooks/useDeadHosts.ts
new file mode 100644
index 000000000..744d28c4b
--- /dev/null
+++ b/frontend/src/hooks/useDeadHosts.ts
@@ -0,0 +1,17 @@
+import { useQuery } from "@tanstack/react-query";
+import { type DeadHost, getDeadHosts, type HostExpansion } from "src/api/backend";
+
+const fetchDeadHosts = (expand?: HostExpansion[]) => {
+ return getDeadHosts(expand);
+};
+
+const useDeadHosts = (expand?: HostExpansion[], options = {}) => {
+ return useQuery({
+ queryKey: ["dead-hosts", { expand }],
+ queryFn: () => fetchDeadHosts(expand),
+ staleTime: 60 * 1000,
+ ...options,
+ });
+};
+
+export { fetchDeadHosts, useDeadHosts };
diff --git a/frontend/src/hooks/useDnsProviders.ts b/frontend/src/hooks/useDnsProviders.ts
new file mode 100644
index 000000000..ec6a5736b
--- /dev/null
+++ b/frontend/src/hooks/useDnsProviders.ts
@@ -0,0 +1,17 @@
+import { useQuery } from "@tanstack/react-query";
+import { type DNSProvider, getCertificateDNSProviders } from "src/api/backend";
+
+const fetchDnsProviders = () => {
+ return getCertificateDNSProviders();
+};
+
+const useDnsProviders = (options = {}) => {
+ return useQuery({
+ queryKey: ["dns-providers"],
+ queryFn: () => fetchDnsProviders(),
+ staleTime: 300 * 1000,
+ ...options,
+ });
+};
+
+export { fetchDnsProviders, useDnsProviders };
diff --git a/frontend/src/hooks/useHealth.ts b/frontend/src/hooks/useHealth.ts
index 91a177123..6a261c95b 100644
--- a/frontend/src/hooks/useHealth.ts
+++ b/frontend/src/hooks/useHealth.ts
@@ -1,6 +1,5 @@
import { useQuery } from "@tanstack/react-query";
-
-import { getHealth, HealthResponse } from "src/api/npm";
+import { getHealth, type HealthResponse } from "src/api/backend";
const fetchHealth = () => getHealth();
diff --git a/frontend/src/hooks/useHostReport.ts b/frontend/src/hooks/useHostReport.ts
new file mode 100644
index 000000000..c54096d20
--- /dev/null
+++ b/frontend/src/hooks/useHostReport.ts
@@ -0,0 +1,18 @@
+import { useQuery } from "@tanstack/react-query";
+import { getHostsReport } from "src/api/backend";
+
+const fetchHostReport = () => getHostsReport();
+
+const useHostReport = (options = {}) => {
+ return useQuery, Error>({
+ queryKey: ["host-report"],
+ queryFn: fetchHostReport,
+ refetchOnWindowFocus: false,
+ retry: 5,
+ refetchInterval: 15 * 1000, // 15 seconds
+ staleTime: 14 * 1000, // 14 seconds
+ ...options,
+ });
+};
+
+export { fetchHostReport, useHostReport };
diff --git a/frontend/src/hooks/useHosts.ts b/frontend/src/hooks/useHosts.ts
deleted file mode 100644
index fda9f1606..000000000
--- a/frontend/src/hooks/useHosts.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-
-import {
- getHosts,
- HostsResponse,
- tableSortToAPI,
- tableFiltersToAPI,
-} from "src/api/npm";
-
-const fetchHosts = (offset = 0, limit = 10, sortBy?: any, filters?: any) => {
- return getHosts(
- offset,
- limit,
- tableSortToAPI(sortBy),
- tableFiltersToAPI(filters),
- );
-};
-
-const useHosts = (
- offset = 0,
- limit = 10,
- sortBy?: any,
- filters?: any,
- options = {},
-) => {
- return useQuery({
- queryKey: ["hosts", { offset, limit, sortBy, filters }],
- queryFn: () => fetchHosts(offset, limit, sortBy, filters),
- staleTime: 15 * 1000, // 15 seconds
- ...options,
- });
-};
-
-export { fetchHosts, useHosts };
diff --git a/frontend/src/hooks/useLogSources.ts b/frontend/src/hooks/useLogSources.ts
new file mode 100644
index 000000000..3f77bbd1e
--- /dev/null
+++ b/frontend/src/hooks/useLogSources.ts
@@ -0,0 +1,15 @@
+import { useQuery } from "@tanstack/react-query";
+import { getLogSources, type LogSources } from "src/api/backend";
+
+const fetchLogSources = () => getLogSources();
+
+const useLogSources = (options = {}) => {
+ return useQuery({
+ queryKey: ["log-sources"],
+ queryFn: fetchLogSources,
+ staleTime: 30 * 1000,
+ ...options,
+ });
+};
+
+export { fetchLogSources, useLogSources };
diff --git a/frontend/src/hooks/useLogTail.ts b/frontend/src/hooks/useLogTail.ts
new file mode 100644
index 000000000..d817dd0c1
--- /dev/null
+++ b/frontend/src/hooks/useLogTail.ts
@@ -0,0 +1,25 @@
+import { useQuery } from "@tanstack/react-query";
+import { type GetLogTailParams, getLogTail, type LogTail } from "src/api/backend";
+
+const POLL_INTERVAL_MS = 5000;
+
+interface UseLogTailOptions extends GetLogTailParams {
+ live?: boolean;
+}
+
+// Polls for new log lines while `live` is true. React Query only runs the interval
+// while the tab is focused (refetchIntervalInBackground defaults to false), so an
+// idle/backgrounded browser tab never generates load.
+const useLogTail = ({ live = true, ...params }: UseLogTailOptions) => {
+ const enabled = params.type === "host" ? Boolean(params.hostType && params.hostId && params.channel) : true;
+
+ return useQuery({
+ queryKey: ["log-tail", params],
+ queryFn: () => getLogTail(params),
+ enabled,
+ refetchInterval: live ? POLL_INTERVAL_MS : false,
+ placeholderData: (previousData) => previousData,
+ });
+};
+
+export { useLogTail };
diff --git a/frontend/src/hooks/useNginxTemplates.ts b/frontend/src/hooks/useNginxTemplates.ts
deleted file mode 100644
index 4faf09506..000000000
--- a/frontend/src/hooks/useNginxTemplates.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-
-import {
- getNginxTemplates,
- NginxTemplatesResponse,
- tableSortToAPI,
- tableFiltersToAPI,
-} from "src/api/npm";
-
-const fetchNginxTemplates = (
- offset = 0,
- limit = 10,
- sortBy?: any,
- filters?: any,
-) => {
- return getNginxTemplates(
- offset,
- limit,
- tableSortToAPI(sortBy),
- tableFiltersToAPI(filters),
- );
-};
-
-const useNginxTemplates = (
- offset = 0,
- limit = 10,
- sortBy?: any,
- filters?: any,
- options = {},
-) => {
- return useQuery({
- queryKey: ["nginx-templates", { offset, limit, sortBy, filters }],
- queryFn: () => fetchNginxTemplates(offset, limit, sortBy, filters),
- staleTime: 15 * 1000, // 15 seconds
- ...options,
- });
-};
-
-export { fetchNginxTemplates, useNginxTemplates };
diff --git a/frontend/src/hooks/useProxyHost.ts b/frontend/src/hooks/useProxyHost.ts
new file mode 100644
index 000000000..24e7f4fae
--- /dev/null
+++ b/frontend/src/hooks/useProxyHost.ts
@@ -0,0 +1,68 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { createProxyHost, getProxyHost, type ProxyHost, updateProxyHost } from "src/api/backend";
+
+const fetchProxyHost = (id: number | "new") => {
+ if (id === "new") {
+ return Promise.resolve({
+ id: 0,
+ createdOn: "",
+ modifiedOn: "",
+ ownerUserId: 0,
+ domainNames: [],
+ forwardHost: "",
+ forwardPort: 0,
+ accessListId: 0,
+ certificateId: 0,
+ sslForced: false,
+ cachingEnabled: false,
+ blockExploits: false,
+ advancedConfig: "",
+ meta: {},
+ allowWebsocketUpgrade: false,
+ http2Support: false,
+ forwardScheme: "",
+ enabled: true,
+ hstsEnabled: false,
+ hstsSubdomains: false,
+ trustForwardedProto: false,
+ } as ProxyHost);
+ }
+ return getProxyHost(id, ["owner"]);
+};
+
+const useProxyHost = (id: number | "new", options = {}) => {
+ return useQuery({
+ queryKey: ["proxy-host", id],
+ queryFn: () => fetchProxyHost(id),
+ staleTime: 60 * 1000, // 1 minute
+ ...options,
+ });
+};
+
+const useSetProxyHost = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (values: ProxyHost) => (values.id ? updateProxyHost(values) : createProxyHost(values)),
+ onMutate: (values: ProxyHost) => {
+ if (!values.id) {
+ return;
+ }
+ const previousObject = queryClient.getQueryData(["proxy-host", values.id]);
+ queryClient.setQueryData(["proxy-host", values.id], (old: ProxyHost) => ({
+ ...old,
+ ...values,
+ }));
+ return () => queryClient.setQueryData(["proxy-host", values.id], previousObject);
+ },
+ onError: (_, __, rollback: any) => rollback(),
+ onSuccess: async ({ id }: ProxyHost) => {
+ queryClient.invalidateQueries({ queryKey: ["proxy-host", id] });
+ queryClient.invalidateQueries({ queryKey: ["proxy-hosts"] });
+ queryClient.invalidateQueries({ queryKey: ["audit-logs"] });
+ queryClient.invalidateQueries({ queryKey: ["host-report"] });
+ queryClient.invalidateQueries({ queryKey: ["certificates"] });
+ },
+ });
+};
+
+export { useProxyHost, useSetProxyHost };
diff --git a/frontend/src/hooks/useProxyHostLogs.ts b/frontend/src/hooks/useProxyHostLogs.ts
new file mode 100644
index 000000000..efcda1b68
--- /dev/null
+++ b/frontend/src/hooks/useProxyHostLogs.ts
@@ -0,0 +1,12 @@
+import { useQuery } from "@tanstack/react-query";
+import { getProxyHostLogs } from "src/api/backend";
+
+const useProxyHostLogs = (id: number, type: "access" | "error" = "access") => {
+ return useQuery<{ logs: string }, Error>({
+ queryKey: ["proxy-host-logs", id, type],
+ queryFn: () => getProxyHostLogs(id, type),
+ staleTime: 10_000,
+ });
+};
+
+export { useProxyHostLogs };
diff --git a/frontend/src/hooks/useProxyHosts.ts b/frontend/src/hooks/useProxyHosts.ts
new file mode 100644
index 000000000..86366fef7
--- /dev/null
+++ b/frontend/src/hooks/useProxyHosts.ts
@@ -0,0 +1,17 @@
+import { useQuery } from "@tanstack/react-query";
+import { getProxyHosts, type ProxyHost, type ProxyHostExpansion } from "src/api/backend";
+
+const fetchProxyHosts = (expand?: ProxyHostExpansion[]) => {
+ return getProxyHosts(expand);
+};
+
+const useProxyHosts = (expand?: ProxyHostExpansion[], options = {}) => {
+ return useQuery({
+ queryKey: ["proxy-hosts", { expand }],
+ queryFn: () => fetchProxyHosts(expand),
+ staleTime: 60 * 1000,
+ ...options,
+ });
+};
+
+export { fetchProxyHosts, useProxyHosts };
diff --git a/frontend/src/hooks/useRedirectionHost.ts b/frontend/src/hooks/useRedirectionHost.ts
new file mode 100644
index 000000000..ff2126538
--- /dev/null
+++ b/frontend/src/hooks/useRedirectionHost.ts
@@ -0,0 +1,71 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ createRedirectionHost,
+ getRedirectionHost,
+ type RedirectionHost,
+ updateRedirectionHost,
+} from "src/api/backend";
+
+const fetchRedirectionHost = (id: number | "new") => {
+ if (id === "new") {
+ return Promise.resolve({
+ id: 0,
+ createdOn: "",
+ modifiedOn: "",
+ ownerUserId: 0,
+ domainNames: [],
+ forwardDomainName: "",
+ preservePath: false,
+ certificateId: 0,
+ sslForced: false,
+ advancedConfig: "",
+ meta: {},
+ http2Support: false,
+ forwardScheme: "auto",
+ forwardHttpCode: 301,
+ blockExploits: false,
+ enabled: true,
+ hstsEnabled: false,
+ hstsSubdomains: false,
+ } as RedirectionHost);
+ }
+ return getRedirectionHost(id, ["owner"]);
+};
+
+const useRedirectionHost = (id: number | "new", options = {}) => {
+ return useQuery