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 ? ( + 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) => ( +
+ + + + + +
+ )} +
+ + ) : 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 ? ( + handleToggleChange(e, field.name)} + disabled={!hasCertificate} + /> + + + + + )} + +
+
+ + {({ field }: any) => ( + + )} + +
+
+
+
+ + {({ field }: any) => ( + + )} + +
+
+ + {({ field }: any) => ( + + )} + +
+
+ + ); + + 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 ( - - - - - - - {localeOptions.map((item) => { - return ( - } - onClick={() => changeTo(item[0])} - key={`locale-${item[0]}`}> - {intl.formatMessage({ id: `locale-${item[1]}` })} - - ); - })} - - - +
+ +
+ {localeOptions.map((item: any) => ( + { + e.preventDefault(); + changeTo(item[0]); + }} + > + + + ))} +
+
); } 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" })} - - - - - - - - - - - - } - onClick={profileDisclosure.onOpen}> - {intl.formatMessage({ id: "profile.title" })} - - } - onClick={passwordDisclosure.onOpen}> - {intl.formatMessage({ id: "change-password" })} - - - }> - {intl.formatMessage({ id: "profile.logout" })} - - - - - - - - - - - ); -} - -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 ( - - - {subItems && ( - - {subItems.map((item, subIndex) => ( - - {item.label} - - ))} - - )} - - ); - } 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 ( +
+
+ +
+ +
+ Logo +
+ Nginx Proxy Manager +
+
+
+
+
+ +
+
+ +
+
+
+
+ + +
+
{currentUser?.name}
+
+ +
+
+
+
+
+ {/* biome-ignore lint/a11y/noStaticElementInteractions lint/a11y/useKeyWithClickEvents: This div is not interactive. */} +
e.stopPropagation()} + > +
+
{currentUser?.name}
+
+ +
+
+
+ + +
+
+
+
+ { + e.preventDefault(); + showUserModal("me"); + }} + > + + + + { + e.preventDefault(); + showChangePasswordModal("me"); + }} + > + + + + { + e.preventDefault(); + showTwoFactorModal("me"); + }} + > + + + + +
+
+
+
+
+ ); +} 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} - - - -