Compare commits

...

56 Commits

Author SHA1 Message Date
Owen 3ed72dd96b Add missing colums to migrations 2026-03-30 18:16:22 -07:00
Owen b8d7d5c910 Add name to provisioning 2026-03-30 17:18:38 -07:00
Owen 673b8b7af5 Add userInviteRoles migration 2026-03-30 17:03:12 -07:00
Owen a651e50759 Fix merge from main 2026-03-30 16:59:05 -07:00
Owen 6484e8e302 Make work for demo 2026-03-30 16:57:36 -07:00
Owen b01d266629 Migration 1.17 first pass 2026-03-30 16:55:37 -07:00
Owen 4465b05404 Merge branch 'provisioning-room' into dev 2026-03-30 16:19:11 -07:00
Owen d1182c3a59 Merge branch 'main' into dev 2026-03-30 15:53:46 -07:00
Owen cb6c47678b Add regions to blueprints 2026-03-30 14:43:49 -07:00
Owen Schwartz 8106620a19 Merge pull request #2149 from infiniteWays/feature/region-rules
Region-based Resource Rules
2026-03-30 14:37:17 -07:00
Owen be3e066843 Merge branch 'dev' into feature/region-rules 2026-03-30 14:36:50 -07:00
Owen Schwartz e345c6ee6e Merge pull request #2627 from shreyaspapi/fix/1547-persist-user-locale
fix: persist user locale preference to database (#1547)
2026-03-30 14:29:15 -07:00
Owen 073b89b355 make path the default 2026-03-30 14:18:10 -07:00
Owen Schwartz 5cad07f8ad Merge pull request #2623 from rodneyosodo/fix/errcheck
refactor(install): improve resource cleanup and remove unused funcs
2026-03-30 14:12:41 -07:00
Owen Schwartz f9d872558e Merge pull request #2624 from fosrl/dependabot/go_modules/install/github.com/charmbracelet/huh-1.0.0
Bump github.com/charmbracelet/huh from 0.8.0 to 1.0.0 in /install
2026-03-30 14:08:26 -07:00
Owen Schwartz c5015d02ae Merge pull request #2646 from LaurenceJJones/feature/installer-default-dir
feat(installer): add default install directory with existing install …
2026-03-30 14:08:00 -07:00
Owen Schwartz 48013228c1 Merge pull request #2653 from shleeable/patch-1
feat(installer): Update docker-compose.yml with HTTPS/3 + QUIC support via traefik
2026-03-30 14:07:34 -07:00
Owen dbafffe73d Update crowdsec and add comment 2026-03-30 14:06:56 -07:00
Owen Schwartz 61cbcb2a06 Merge pull request #2741 from fosrl/dependabot/npm_and_yarn/multi-0b8106bf31
Bump fast-xml-parser and @aws-sdk/xml-builder
2026-03-30 13:58:19 -07:00
Owen Schwartz 89c1ad5d98 Merge pull request #2738 from fosrl/dependabot/github_actions/sigstore/cosign-installer-4.1.1
Bump sigstore/cosign-installer from 4.1.0 to 4.1.1
2026-03-30 13:55:27 -07:00
Owen Schwartz b343ca6290 Merge pull request #2687 from fosrl/dependabot/npm_and_yarn/next-15.5.14
Bump next from 15.5.12 to 15.5.14
2026-03-30 13:55:19 -07:00
dependabot[bot] b913466671 Bump next from 15.5.12 to 15.5.14
Bumps [next](https://github.com/vercel/next.js) from 15.5.12 to 15.5.14.
- [Release notes](https://github.com/vercel/next.js/releases)
- [Changelog](https://github.com/vercel/next.js/blob/canary/release.js)
- [Commits](https://github.com/vercel/next.js/compare/v15.5.12...v15.5.14)

---
updated-dependencies:
- dependency-name: next
  dependency-version: 15.5.14
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-30 20:37:38 +00:00
Owen Schwartz 9054f4f9c3 Merge pull request #2683 from fosrl/dependabot/npm_and_yarn/flatted-3.4.2
Bump flatted from 3.3.3 to 3.4.2
2026-03-30 13:37:18 -07:00
Owen Schwartz 3915024d9a Merge pull request #2714 from fosrl/dependabot/npm_and_yarn/dev-patch-updates-3753551584
Bump the dev-patch-updates group across 1 directory with 3 updates
2026-03-30 13:36:49 -07:00
dependabot[bot] 7d1085b43f Bump fast-xml-parser and @aws-sdk/xml-builder
Bumps [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) and [@aws-sdk/xml-builder](https://github.com/aws/aws-sdk-js-v3/tree/HEAD/packages-internal/xml-builder). These dependencies needed to be updated together.

Updates `fast-xml-parser` from 5.5.6 to 5.5.8
- [Release notes](https://github.com/NaturalIntelligence/fast-xml-parser/releases)
- [Changelog](https://github.com/NaturalIntelligence/fast-xml-parser/blob/master/CHANGELOG.md)
- [Commits](https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.5.6...v5.5.8)

Updates `@aws-sdk/xml-builder` from 3.972.12 to 3.972.16
- [Release notes](https://github.com/aws/aws-sdk-js-v3/releases)
- [Changelog](https://github.com/aws/aws-sdk-js-v3/blob/main/packages-internal/xml-builder/CHANGELOG.md)
- [Commits](https://github.com/aws/aws-sdk-js-v3/commits/HEAD/packages-internal/xml-builder)

---
updated-dependencies:
- dependency-name: fast-xml-parser
  dependency-version: 5.5.8
  dependency-type: indirect
- dependency-name: "@aws-sdk/xml-builder"
  dependency-version: 3.972.16
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-30 20:36:35 +00:00
Owen Schwartz 7c2477cccc Merge pull request #2717 from fosrl/dependabot/npm_and_yarn/multi-bf05dc1ecf
Bump picomatch
2026-03-30 13:36:21 -07:00
Owen Schwartz 5aecb5fb90 Merge pull request #2727 from fosrl/dependabot/npm_and_yarn/yaml-2.8.3
Bump yaml from 2.8.2 to 2.8.3
2026-03-30 13:36:06 -07:00
Owen Schwartz f86d040ee4 Merge pull request #2728 from fosrl/dependabot/npm_and_yarn/nodemailer-8.0.4
Bump nodemailer from 8.0.1 to 8.0.4
2026-03-30 13:35:48 -07:00
Owen Schwartz ed32717b3f Merge pull request #2730 from fosrl/dependabot/npm_and_yarn/multi-95b84c9cdf
Bump brace-expansion
2026-03-30 13:35:31 -07:00
Owen Schwartz aab8462134 Merge pull request #2733 from fosrl/dependabot/npm_and_yarn/path-to-regexp-8.4.0
Bump path-to-regexp from 8.3.0 to 8.4.0
2026-03-30 13:34:56 -07:00
Owen 04943fb4a6 Fix access log 2026-03-30 11:58:48 -07:00
Owen 1e9544af07 Customize table a little more 2026-03-29 20:29:31 -07:00
dependabot[bot] c20dfdabfb Bump the dev-patch-updates group across 1 directory with 3 updates
Bumps the dev-patch-updates group with 3 updates in the / directory: [@tailwindcss/postcss](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/@tailwindcss-postcss), [esbuild](https://github.com/evanw/esbuild) and [tailwindcss](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/tailwindcss).


Updates `@tailwindcss/postcss` from 4.2.1 to 4.2.2
- [Release notes](https://github.com/tailwindlabs/tailwindcss/releases)
- [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.2.2/packages/@tailwindcss-postcss)

Updates `esbuild` from 0.27.3 to 0.27.4
- [Release notes](https://github.com/evanw/esbuild/releases)
- [Changelog](https://github.com/evanw/esbuild/blob/main/CHANGELOG.md)
- [Commits](https://github.com/evanw/esbuild/compare/v0.27.3...v0.27.4)

Updates `tailwindcss` from 4.2.1 to 4.2.2
- [Release notes](https://github.com/tailwindlabs/tailwindcss/releases)
- [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.2.2/packages/tailwindcss)

---
updated-dependencies:
- dependency-name: "@tailwindcss/postcss"
  dependency-version: 4.2.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: esbuild
  dependency-version: 0.27.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: tailwindcss
  dependency-version: 4.2.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-30 01:35:59 +00:00
dependabot[bot] 11a6f1f47f Bump sigstore/cosign-installer from 4.1.0 to 4.1.1
Bumps [sigstore/cosign-installer](https://github.com/sigstore/cosign-installer) from 4.1.0 to 4.1.1.
- [Release notes](https://github.com/sigstore/cosign-installer/releases)
- [Commits](https://github.com/sigstore/cosign-installer/compare/ba7bc0a3fef59531c69a25acd34668d6d3fe6f22...cad07c2e89fa2edd6e2d7bab4c1aa38e53f76003)

---
updated-dependencies:
- dependency-name: sigstore/cosign-installer
  dependency-version: 4.1.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-30 01:34:28 +00:00
Owen fcf92d4e2c Add basic provisioning room v1 and update keys 2026-03-29 16:28:51 -07:00
Owen 77cef554be Provisioning room basics done 2026-03-29 14:20:58 -07:00
Owen Schwartz bdc45887f9 Add chainId to dedup messages (#2737)
* ChainId send through on sensitive messages
2026-03-29 12:08:29 -07:00
dependabot[bot] 8e160902af Bump path-to-regexp from 8.3.0 to 8.4.0
Bumps [path-to-regexp](https://github.com/pillarjs/path-to-regexp) from 8.3.0 to 8.4.0.
- [Release notes](https://github.com/pillarjs/path-to-regexp/releases)
- [Changelog](https://github.com/pillarjs/path-to-regexp/blob/master/History.md)
- [Commits](https://github.com/pillarjs/path-to-regexp/compare/v8.3.0...v8.4.0)

---
updated-dependencies:
- dependency-name: path-to-regexp
  dependency-version: 8.4.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-28 18:37:06 +00:00
dependabot[bot] 06f840a680 Bump brace-expansion
Bumps  and [brace-expansion](https://github.com/juliangruber/brace-expansion). These dependencies needed to be updated together.

Updates `brace-expansion` from 5.0.4 to 5.0.5
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/v5.0.4...v5.0.5)

Updates `brace-expansion` from 1.1.12 to 1.1.13
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/v5.0.4...v5.0.5)

---
updated-dependencies:
- dependency-name: brace-expansion
  dependency-version: 5.0.5
  dependency-type: indirect
- dependency-name: brace-expansion
  dependency-version: 1.1.13
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-27 14:43:09 +00:00
dependabot[bot] 5ddcfeb506 Bump nodemailer from 8.0.1 to 8.0.4
Bumps [nodemailer](https://github.com/nodemailer/nodemailer) from 8.0.1 to 8.0.4.
- [Release notes](https://github.com/nodemailer/nodemailer/releases)
- [Changelog](https://github.com/nodemailer/nodemailer/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodemailer/nodemailer/compare/v8.0.1...v8.0.4)

---
updated-dependencies:
- dependency-name: nodemailer
  dependency-version: 8.0.4
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-27 06:56:52 +00:00
dependabot[bot] 914e95e47f Bump yaml from 2.8.2 to 2.8.3
Bumps [yaml](https://github.com/eemeli/yaml) from 2.8.2 to 2.8.3.
- [Release notes](https://github.com/eemeli/yaml/releases)
- [Commits](https://github.com/eemeli/yaml/compare/v2.8.2...v2.8.3)

---
updated-dependencies:
- dependency-name: yaml
  dependency-version: 2.8.3
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-27 02:36:44 +00:00
dependabot[bot] 5b9efc3c5f Bump picomatch
Bumps  and [picomatch](https://github.com/micromatch/picomatch). These dependencies needed to be updated together.

Updates `picomatch` from 2.3.1 to 2.3.2
- [Release notes](https://github.com/micromatch/picomatch/releases)
- [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/picomatch/compare/2.3.1...2.3.2)

Updates `picomatch` from 4.0.3 to 4.0.4
- [Release notes](https://github.com/micromatch/picomatch/releases)
- [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/picomatch/compare/2.3.1...2.3.2)

---
updated-dependencies:
- dependency-name: picomatch
  dependency-version: 2.3.2
  dependency-type: indirect
- dependency-name: picomatch
  dependency-version: 4.0.4
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-26 08:51:09 +00:00
Owen Schwartz 6d7a19b0a0 Merge pull request #2716 from fosrl/patch-1
Add typecasts
2026-03-25 22:12:59 -07:00
Owen 6b3a6fa380 Add typecasts 2026-03-25 22:11:56 -07:00
Owen Schwartz e2a65b4b74 Merge pull request #2715 from fosrl/batch-band
Batch set bandwidth
2026-03-25 21:54:44 -07:00
Owen 1f01108b62 Batch set bandwidth 2026-03-25 21:53:20 -07:00
dependabot[bot] 871f14ef3a Bump flatted from 3.3.3 to 3.4.2
Bumps [flatted](https://github.com/WebReflection/flatted) from 3.3.3 to 3.4.2.
- [Commits](https://github.com/WebReflection/flatted/compare/v3.3.3...v3.4.2)

---
updated-dependencies:
- dependency-name: flatted
  dependency-version: 3.4.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-21 11:17:41 +00:00
dependabot[bot] 1d5dfd6db2 Bump github.com/charmbracelet/huh from 0.8.0 to 1.0.0 in /install
Bumps [github.com/charmbracelet/huh](https://github.com/charmbracelet/huh) from 0.8.0 to 1.0.0.
- [Release notes](https://github.com/charmbracelet/huh/releases)
- [Commits](https://github.com/charmbracelet/huh/compare/v0.8.0...v1.0.0)

---
updated-dependencies:
- dependency-name: github.com/charmbracelet/huh
  dependency-version: 1.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-18 22:27:43 +00:00
Shlee ad3fe2fa76 Update traefik_config.yml 2026-03-15 19:39:36 +10:30
Shlee 863eb8efe9 Update docker-compose.yml 2026-03-15 19:37:15 +10:30
Laurence 47a99e35ee feat(installer): add default install directory with existing install detection
- Default to /opt/pangolin for new installations
  - Check current directory and /opt/pangolin for existing installs
  - Prompt to use existing install if found at default location
  - Offer to change directory ownership when running via sudo
  - Create installation directory if it doesn't exist
2026-03-13 11:38:00 +00:00
Shreyas Papinwar 5455d1c118 fix: add locale to myDevice user query to fix type error 2026-03-10 12:33:05 +05:30
Shreyas Papinwar ae39084a75 fix: persist user locale preference to database (#1547) 2026-03-10 12:21:06 +05:30
Rodney Osodo 27d20eb1bc refactor(install): improve resource cleanup and remove unused funcs
Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>
2026-03-09 11:17:36 +03:00
Dennis 3d4df906cf Added missing translations 2025-12-22 18:43:43 +01:00
Dennis e051142334 Add region-based resource rule 2025-12-22 17:44:56 +01:00
61 changed files with 2628 additions and 594 deletions
+1 -1
View File
@@ -415,7 +415,7 @@ jobs:
- name: Install cosign
# cosign is used to sign and verify container images (key and keyless)
uses: sigstore/cosign-installer@ba7bc0a3fef59531c69a25acd34668d6d3fe6f22 # v4.1.0
uses: sigstore/cosign-installer@cad07c2e89fa2edd6e2d7bab4c1aa38e53f76003 # v4.1.1
- name: Dual-sign and verify (GHCR & Docker Hub)
# Sign each image by digest using keyless (OIDC) and key-based signing,
+1 -1
View File
@@ -23,7 +23,7 @@ jobs:
skopeo --version
- name: Install cosign
uses: sigstore/cosign-installer@ba7bc0a3fef59531c69a25acd34668d6d3fe6f22 # v4.1.0
uses: sigstore/cosign-installer@cad07c2e89fa2edd6e2d7bab4c1aa38e53f76003 # v4.1.1
- name: Input check
run: |
+7 -7
View File
@@ -99,11 +99,6 @@ func ReadAppConfig(configPath string) (*AppConfigValues, error) {
return values, nil
}
// findPattern finds the start of a pattern in a string
func findPattern(s, pattern string) int {
return bytes.Index([]byte(s), []byte(pattern))
}
func copyDockerService(sourceFile, destFile, serviceName string) error {
// Read source file
sourceData, err := os.ReadFile(sourceFile)
@@ -187,7 +182,7 @@ func backupConfig() error {
return nil
}
func MarshalYAMLWithIndent(data any, indent int) ([]byte, error) {
func MarshalYAMLWithIndent(data any, indent int) (resp []byte, err error) {
buffer := new(bytes.Buffer)
encoder := yaml.NewEncoder(buffer)
encoder.SetIndent(indent)
@@ -196,7 +191,12 @@ func MarshalYAMLWithIndent(data any, indent int) ([]byte, error) {
return nil, err
}
defer encoder.Close()
defer func() {
if cerr := encoder.Close(); cerr != nil && err == nil {
err = cerr
}
}()
return buffer.Bytes(), nil
}
+9 -3
View File
@@ -81,11 +81,17 @@ entryPoints:
transport:
respondingTimeouts:
readTimeout: "30m"
http3:
advertisedPort: 443
http:
tls:
certResolver: "letsencrypt"
middlewares:
- crowdsec@file
encodedCharacters:
allowEncodedSlash: true
allowEncodedQuestionMark: true
serversTransport:
insecureSkipVerify: true
insecureSkipVerify: true
ping:
entryPoint: "web"
+1
View File
@@ -38,6 +38,7 @@ services:
- 51820:51820/udp
- 21820:21820/udp
- 443:443
- 443:443/udp # For http3 QUIC if desired
- 80:80
{{end}}
traefik:
@@ -40,6 +40,8 @@ entryPoints:
transport:
respondingTimeouts:
readTimeout: "30m"
http3:
advertisedPort: 443
http:
tls:
certResolver: "letsencrypt"
+1 -1
View File
@@ -3,7 +3,7 @@ module installer
go 1.25.0
require (
github.com/charmbracelet/huh v0.8.0
github.com/charmbracelet/huh v1.0.0
github.com/charmbracelet/lipgloss v1.1.0
golang.org/x/term v0.41.0
gopkg.in/yaml.v3 v3.0.1
+2 -2
View File
@@ -14,8 +14,8 @@ github.com/charmbracelet/bubbletea v1.3.6 h1:VkHIxPJQeDt0aFJIsVxw8BQdh/F/L2KKZGs
github.com/charmbracelet/bubbletea v1.3.6/go.mod h1:oQD9VCRQFF8KplacJLo28/jofOI2ToOfGYeFgBBxHOc=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=
github.com/charmbracelet/huh v0.8.0 h1:Xz/Pm2h64cXQZn/Jvele4J3r7DDiqFCNIVteYukxDvY=
github.com/charmbracelet/huh v0.8.0/go.mod h1:5YVc+SlZ1IhQALxRPpkGwwEKftN/+OlJlnJYlDRFqN4=
github.com/charmbracelet/huh v1.0.0 h1:wOnedH8G4qzJbmhftTqrpppyqHakl/zbbNdXIWJyIxw=
github.com/charmbracelet/huh v1.0.0/go.mod h1:5YVc+SlZ1IhQALxRPpkGwwEKftN/+OlJlnJYlDRFqN4=
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
github.com/charmbracelet/x/ansi v0.9.3 h1:BXt5DHS/MKF+LjuK4huWrC6NCvHtexww7dMayh6GXd0=
-27
View File
@@ -85,33 +85,6 @@ func readString(prompt string, defaultValue string) string {
return value
}
func readStringNoDefault(prompt string) string {
var value string
for {
input := huh.NewInput().
Title(prompt).
Value(&value).
Validate(func(s string) error {
if s == "" {
return fmt.Errorf("this field is required")
}
return nil
})
err := runField(input)
handleAbort(err)
if value != "" {
// Print the answer so it remains visible in terminal history
if !isAccessibleMode() {
fmt.Printf("%s: %s\n", prompt, value)
}
return value
}
}
}
func readPassword(prompt string) string {
var value string
+138 -34
View File
@@ -8,12 +8,12 @@ import (
"io"
"io/fs"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"text/template"
"time"
@@ -90,6 +90,13 @@ func main() {
var config Config
var alreadyInstalled = false
// Determine installation directory
installDir := findOrSelectInstallDirectory()
if err := os.Chdir(installDir); err != nil {
fmt.Printf("Error changing to installation directory: %v\n", err)
os.Exit(1)
}
// check if there is already a config file
if _, err := os.Stat("config/config.yml"); err != nil {
config = collectUserInput()
@@ -287,6 +294,117 @@ func main() {
fmt.Printf("\nTo complete the initial setup, please visit:\nhttps://%s/auth/initial-setup\n", config.DashboardDomain)
}
func hasExistingInstall(dir string) bool {
configPath := filepath.Join(dir, "config", "config.yml")
_, err := os.Stat(configPath)
return err == nil
}
func findOrSelectInstallDirectory() string {
const defaultInstallDir = "/opt/pangolin"
// Get current working directory
cwd, err := os.Getwd()
if err != nil {
fmt.Printf("Error getting current directory: %v\n", err)
os.Exit(1)
}
// 1. Check current directory for existing install
if hasExistingInstall(cwd) {
fmt.Printf("Found existing Pangolin installation in current directory: %s\n", cwd)
return cwd
}
// 2. Check default location (/opt/pangolin) for existing install
if cwd != defaultInstallDir && hasExistingInstall(defaultInstallDir) {
fmt.Printf("\nFound existing Pangolin installation at: %s\n", defaultInstallDir)
if readBool(fmt.Sprintf("Would you like to use the existing installation at %s?", defaultInstallDir), true) {
return defaultInstallDir
}
}
// 3. No existing install found, prompt for installation directory
fmt.Println("\n=== Installation Directory ===")
fmt.Println("No existing Pangolin installation detected.")
installDir := readString("Enter the installation directory", defaultInstallDir)
// Expand ~ to home directory if present
if strings.HasPrefix(installDir, "~") {
home, err := os.UserHomeDir()
if err != nil {
fmt.Printf("Error getting home directory: %v\n", err)
os.Exit(1)
}
installDir = filepath.Join(home, installDir[1:])
}
// Convert to absolute path
absPath, err := filepath.Abs(installDir)
if err != nil {
fmt.Printf("Error resolving path: %v\n", err)
os.Exit(1)
}
installDir = absPath
// Check if directory exists
if _, err := os.Stat(installDir); os.IsNotExist(err) {
// Directory doesn't exist, create it
if readBool(fmt.Sprintf("Directory %s does not exist. Create it?", installDir), true) {
if err := os.MkdirAll(installDir, 0755); err != nil {
fmt.Printf("Error creating directory: %v\n", err)
os.Exit(1)
}
fmt.Printf("Created directory: %s\n", installDir)
// Offer to change ownership if running via sudo
changeDirectoryOwnership(installDir)
} else {
fmt.Println("Installation cancelled.")
os.Exit(0)
}
}
fmt.Printf("Installation directory: %s\n", installDir)
return installDir
}
func changeDirectoryOwnership(dir string) {
// Check if we're running via sudo by looking for SUDO_USER
sudoUser := os.Getenv("SUDO_USER")
if sudoUser == "" || os.Geteuid() != 0 {
return
}
sudoUID := os.Getenv("SUDO_UID")
sudoGID := os.Getenv("SUDO_GID")
if sudoUID == "" || sudoGID == "" {
return
}
fmt.Printf("\nRunning as root via sudo (original user: %s)\n", sudoUser)
if readBool(fmt.Sprintf("Would you like to change ownership of %s to user '%s'? This makes it easier to manage config files without sudo.", dir, sudoUser), true) {
uid, err := strconv.Atoi(sudoUID)
if err != nil {
fmt.Printf("Warning: Could not parse SUDO_UID: %v\n", err)
return
}
gid, err := strconv.Atoi(sudoGID)
if err != nil {
fmt.Printf("Warning: Could not parse SUDO_GID: %v\n", err)
return
}
if err := os.Chown(dir, uid, gid); err != nil {
fmt.Printf("Warning: Could not change ownership: %v\n", err)
} else {
fmt.Printf("Changed ownership of %s to %s\n", dir, sudoUser)
}
}
}
func podmanOrDocker() SupportedContainer {
inputContainer := readString("Would you like to run Pangolin as Docker or Podman containers?", "docker")
@@ -430,9 +548,9 @@ func createConfigFiles(config Config) error {
}
// Walk through all embedded files
err := fs.WalkDir(configFiles, "config", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
err := fs.WalkDir(configFiles, "config", func(path string, d fs.DirEntry, walkErr error) (err error) {
if walkErr != nil {
return walkErr
}
// Skip the root fs directory itself
@@ -483,7 +601,11 @@ func createConfigFiles(config Config) error {
if err != nil {
return fmt.Errorf("failed to create %s: %v", path, err)
}
defer outFile.Close()
defer func() {
if cerr := outFile.Close(); cerr != nil && err == nil {
err = cerr
}
}()
// Execute template
if err := tmpl.Execute(outFile, config); err != nil {
@@ -499,18 +621,26 @@ func createConfigFiles(config Config) error {
return nil
}
func copyFile(src, dst string) error {
func copyFile(src, dst string) (err error) {
source, err := os.Open(src)
if err != nil {
return err
}
defer source.Close()
defer func() {
if cerr := source.Close(); cerr != nil && err == nil {
err = cerr
}
}()
destination, err := os.Create(dst)
if err != nil {
return err
}
defer destination.Close()
defer func() {
if cerr := destination.Close(); cerr != nil && err == nil {
err = cerr
}
}()
_, err = io.Copy(destination, source)
return err
@@ -622,32 +752,6 @@ func generateRandomSecretKey() string {
return base64.StdEncoding.EncodeToString(secret)
}
func getPublicIP() string {
client := &http.Client{
Timeout: 10 * time.Second,
}
resp, err := client.Get("https://ifconfig.io/ip")
if err != nil {
return ""
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return ""
}
ip := strings.TrimSpace(string(body))
// Validate that it's a valid IP address
if net.ParseIP(ip) != nil {
return ip
}
return ""
}
// Run external commands with stdio/stderr attached.
func run(name string, args ...string) error {
cmd := exec.Command(name, args...)
+34
View File
@@ -1890,6 +1890,40 @@
"exitNode": "Exit-Node",
"country": "Land",
"rulesMatchCountry": "Derzeit basierend auf der Quell-IP",
"region": "Region",
"selectRegion": "Region wählen...",
"searchRegions": "Regionen suchen...",
"noRegionFound": "Keine Region gefunden.",
"rulesMatchRegion": "Wählen Sie eine Regionalgruppe von Ländern",
"rulesErrorInvalidRegion": "Ungültige Region",
"rulesErrorInvalidRegionDescription": "Bitte wählen Sie eine gültige Region aus.",
"regionAfrica": "Afrika",
"regionNorthernAfrica": "Nordafrika",
"regionEasternAfrica": "Ostafrika",
"regionMiddleAfrica": "Zentralafrika",
"regionSouthernAfrica": "Südliches Afrika",
"regionWesternAfrica": "Westafrika",
"regionAmericas": "Amerika",
"regionCaribbean": "Karibik",
"regionCentralAmerica": "Mittelamerika",
"regionSouthAmerica": "Südamerika",
"regionNorthernAmerica": "Nordamerika",
"regionAsia": "Asien",
"regionCentralAsia": "Zentralasien",
"regionEasternAsia": "Ostasien",
"regionSouthEasternAsia": "Südostasien",
"regionSouthernAsia": "Südasien",
"regionWesternAsia": "Westasien",
"regionEurope": "Europa",
"regionEasternEurope": "Osteuropa",
"regionNorthernEurope": "Nordeuropa",
"regionSouthernEurope": "Südeuropa",
"regionWesternEurope": "Westeuropa",
"regionOceania": "Ozeanien",
"regionAustraliaAndNewZealand": "Australien und Neuseeland",
"regionMelanesia": "Melanesien",
"regionMicronesia": "Mikronesien",
"regionPolynesia": "Polynesien",
"managedSelfHosted": {
"title": "Verwaltetes Selbsthosted",
"description": "Zuverlässiger und wartungsarmer Pangolin Server mit zusätzlichen Glocken und Pfeifen",
+47
View File
@@ -331,6 +331,11 @@
"provisioningKeysTitle": "Provisioning Key",
"provisioningKeysManage": "Manage Provisioning Keys",
"provisioningKeysDescription": "Provisioning keys are used to authenticate automated site provisioning for your organization.",
"provisioningManage": "Provisioning",
"provisioningDescription": "Manage provisioning keys and review pending sites awaiting approval.",
"pendingSites": "Pending Sites",
"siteApproveSuccess": "Site approved successfully",
"siteApproveError": "Error approving site",
"provisioningKeys": "Provisioning Keys",
"searchProvisioningKeys": "Search provisioning keys...",
"provisioningKeysAdd": "Generate Provisioning Key",
@@ -360,9 +365,17 @@
"provisioningKeysNeverUsed": "Never",
"provisioningKeysEdit": "Edit Provisioning Key",
"provisioningKeysEditDescription": "Update the max batch size and expiration time for this key.",
"provisioningKeysApproveNewSites": "Approve new sites",
"provisioningKeysApproveNewSitesDescription": "Automatically approve sites that register with this key.",
"provisioningKeysUpdateError": "Error updating provisioning key",
"provisioningKeysUpdated": "Provisioning key updated",
"provisioningKeysUpdatedDescription": "Your changes have been saved.",
"provisioningKeysBannerTitle": "Site Provisioning Keys",
"provisioningKeysBannerDescription": "Generate a provisioning key and use it with the Newt connector to automatically create sites on first startup — no need to set up separate credentials for each site.",
"provisioningKeysBannerButtonText": "Learn More",
"pendingSitesBannerTitle": "Pending Sites",
"pendingSitesBannerDescription": "Sites that connect using a provisioning key appear here for review. Approve each site before it becomes active and gains access to your resources.",
"pendingSitesBannerButtonText": "Learn More",
"apiKeysSettings": "{apiKeyName} Settings",
"userTitle": "Manage All Users",
"userDescription": "View and manage all users in the system",
@@ -1935,6 +1948,40 @@
"exitNode": "Exit Node",
"country": "Country",
"rulesMatchCountry": "Currently based on source IP",
"region": "Region",
"selectRegion": "Select region",
"searchRegions": "Search regions...",
"noRegionFound": "No region found.",
"rulesMatchRegion": "Select a regional grouping of countries",
"rulesErrorInvalidRegion": "Invalid region",
"rulesErrorInvalidRegionDescription": "Please select a valid region.",
"regionAfrica": "Africa",
"regionNorthernAfrica": "Northern Africa",
"regionEasternAfrica": "Eastern Africa",
"regionMiddleAfrica": "Middle Africa",
"regionSouthernAfrica": "Southern Africa",
"regionWesternAfrica": "Western Africa",
"regionAmericas": "Americas",
"regionCaribbean": "Caribbean",
"regionCentralAmerica": "Central America",
"regionSouthAmerica": "South America",
"regionNorthernAmerica": "Northern America",
"regionAsia": "Asia",
"regionCentralAsia": "Central Asia",
"regionEasternAsia": "Eastern Asia",
"regionSouthEasternAsia": "South-Eastern Asia",
"regionSouthernAsia": "Southern Asia",
"regionWesternAsia": "Western Asia",
"regionEurope": "Europe",
"regionEasternEurope": "Eastern Europe",
"regionNorthernEurope": "Northern Europe",
"regionSouthernEurope": "Southern Europe",
"regionWesternEurope": "Western Europe",
"regionOceania": "Oceania",
"regionAustraliaAndNewZealand": "Australia and New Zealand",
"regionMelanesia": "Melanesia",
"regionMicronesia": "Micronesia",
"regionPolynesia": "Polynesia",
"managedSelfHosted": {
"title": "Managed Self-Hosted",
"description": "More reliable and low-maintenance self-hosted Pangolin server with extra bells and whistles",
+34
View File
@@ -1890,6 +1890,40 @@
"exitNode": "Узел выхода",
"country": "Страна",
"rulesMatchCountry": "В настоящее время основано на исходном IP",
"region": "Регион",
"selectRegion": "Выберите регион",
"searchRegions": "Поиск регионов...",
"noRegionFound": "Регион не найден.",
"rulesMatchRegion": "Выберите региональную группу стран",
"rulesErrorInvalidRegion": "Некорректный регион",
"rulesErrorInvalidRegionDescription": "Пожалуйста, выберите корректный регион.",
"regionAfrica": "Африка",
"regionNorthernAfrica": "Северная Африка",
"regionEasternAfrica": "Восточная Африка",
"regionMiddleAfrica": "Центральная Африка",
"regionSouthernAfrica": "Южная Африка",
"regionWesternAfrica": "Западная Африка",
"regionAmericas": "Америка",
"regionCaribbean": "Карибы",
"regionCentralAmerica": "Центральная Америка",
"regionSouthAmerica": "Южная Америка",
"regionNorthernAmerica": "Северная Америка",
"regionAsia": "Азия",
"regionCentralAsia": "Центральная Азия",
"regionEasternAsia": "Восточная Азия",
"regionSouthEasternAsia": "Юго-Восточная Азия",
"regionSouthernAsia": "Южная Азия",
"regionWesternAsia": "Западная Азия",
"regionEurope": "Европа",
"regionEasternEurope": "Восточная Европа",
"regionNorthernEurope": "Северная Европа",
"regionSouthernEurope": "Южная Европа",
"regionWesternEurope": "Западная Европа",
"regionOceania": "Океания",
"regionAustraliaAndNewZealand": "Австралия и Новая Зеландия",
"regionMelanesia": "Меланезия",
"regionMicronesia": "Микронезия",
"regionPolynesia": "Полинезия",
"managedSelfHosted": {
"title": "Управляемый с самовывоза",
"description": "Более надежный и низко обслуживаемый сервер Pangolin с дополнительными колокольнями и свистками",
+326 -315
View File
File diff suppressed because it is too large Load Diff
+7 -7
View File
@@ -92,12 +92,12 @@
"lucide-react": "0.577.0",
"maxmind": "5.0.5",
"moment": "2.30.1",
"next": "15.5.12",
"next": "15.5.14",
"next-intl": "4.8.3",
"next-themes": "0.4.6",
"nextjs-toploader": "3.9.17",
"node-cache": "5.1.2",
"nodemailer": "8.0.1",
"nodemailer": "8.0.4",
"oslo": "1.2.1",
"pg": "8.20.0",
"posthog-node": "5.28.0",
@@ -125,7 +125,7 @@
"winston": "3.19.0",
"winston-daily-rotate-file": "5.0.0",
"ws": "8.19.0",
"yaml": "2.8.2",
"yaml": "2.8.3",
"yargs": "18.0.0",
"zod": "4.3.6",
"zod-validation-error": "5.0.0"
@@ -134,7 +134,7 @@
"@dotenvx/dotenvx": "1.54.1",
"@esbuild-plugins/tsconfig-paths": "0.1.2",
"@react-email/preview-server": "5.2.10",
"@tailwindcss/postcss": "4.2.1",
"@tailwindcss/postcss": "4.2.2",
"@tanstack/react-query-devtools": "5.91.3",
"@types/better-sqlite3": "7.6.13",
"@types/cookie-parser": "1.4.10",
@@ -160,21 +160,21 @@
"@types/yargs": "17.0.35",
"babel-plugin-react-compiler": "1.0.0",
"drizzle-kit": "0.31.10",
"esbuild": "0.27.3",
"esbuild": "0.27.4",
"esbuild-node-externals": "1.20.1",
"eslint": "10.0.3",
"eslint-config-next": "16.1.7",
"postcss": "8.5.8",
"prettier": "3.8.1",
"react-email": "5.2.10",
"tailwindcss": "4.2.1",
"tailwindcss": "4.2.2",
"tsc-alias": "1.8.16",
"tsx": "4.21.0",
"typescript": "5.9.3",
"typescript-eslint": "8.56.1"
},
"overrides": {
"esbuild": "0.27.3",
"esbuild": "0.27.4",
"dompurify": "3.3.2"
}
}
+2 -1
View File
@@ -392,7 +392,8 @@ export const siteProvisioningKeys = pgTable("siteProvisioningKeys", {
lastUsed: varchar("lastUsed", { length: 255 }),
maxBatchSize: integer("maxBatchSize"), // null = no limit
numUsed: integer("numUsed").notNull().default(0),
validUntil: varchar("validUntil", { length: 255 })
validUntil: varchar("validUntil", { length: 255 }),
approveNewSites: boolean("approveNewSites").notNull().default(true)
});
export const siteProvisioningKeyOrg = pgTable(
+4 -2
View File
@@ -100,7 +100,8 @@ export const sites = pgTable("sites", {
publicKey: varchar("publicKey"),
lastHolePunch: bigint("lastHolePunch", { mode: "number" }),
listenPort: integer("listenPort"),
dockerSocketEnabled: boolean("dockerSocketEnabled").notNull().default(true)
dockerSocketEnabled: boolean("dockerSocketEnabled").notNull().default(true),
status: varchar("status").$type<"pending" | "approved">()
});
export const resources = pgTable("resources", {
@@ -292,7 +293,8 @@ export const users = pgTable("user", {
termsVersion: varchar("termsVersion"),
marketingEmailConsent: boolean("marketingEmailConsent").default(false),
serverAdmin: boolean("serverAdmin").notNull().default(false),
lastPasswordChange: bigint("lastPasswordChange", { mode: "number" })
lastPasswordChange: bigint("lastPasswordChange", { mode: "number" }),
locale: varchar("locale")
});
export const newts = pgTable("newt", {
+196
View File
@@ -0,0 +1,196 @@
// Regions of the World
// as of 2025-10-25
//
// Adapted according to the United Nations Geoscheme
// see https://www.unicode.org/cldr/charts/48/supplemental/territory_containment_un_m_49.html
// see https://unstats.un.org/unsd/methodology/m49
export const REGIONS = [
{
name: "regionAfrica",
id: "002",
includes: [
{
name: "regionNorthernAfrica",
id: "015",
countries: ["DZ", "EG", "LY", "MA", "SD", "TN", "EH"]
},
{
name: "regionEasternAfrica",
id: "014",
countries: ["IO", "BI", "KM", "DJ", "ER", "ET", "TF", "KE", "MG", "MW", "MU", "YT", "MZ", "RE", "RW", "SC", "SO", "SS", "UG", "ZM", "ZW"]
},
{
name: "regionMiddleAfrica",
id: "017",
countries: ["AO", "CM", "CF", "TD", "CG", "CD", "GQ", "GA", "ST"]
},
{
name: "regionSouthernAfrica",
id: "018",
countries: ["BW", "SZ", "LS", "NA", "ZA"]
},
{
name: "regionWesternAfrica",
id: "011",
countries: ["BJ", "BF", "CV", "CI", "GM", "GH", "GN", "GW", "LR", "ML", "MR", "NE", "NG", "SH", "SN", "SL", "TG"]
}
]
},
{
name: "regionAmericas",
id: "019",
includes: [
{
name: "regionCaribbean",
id: "029",
countries: ["AI", "AG", "AW", "BS", "BB", "BQ", "VG", "KY", "CU", "CW", "DM", "DO", "GD", "GP", "HT", "JM", "MQ", "MS", "PR", "BL", "KN", "LC", "MF", "VC", "SX", "TT", "TC", "VI"]
},
{
name: "regionCentralAmerica",
id: "013",
countries: ["BZ", "CR", "SV", "GT", "HN", "MX", "NI", "PA"]
},
{
name: "regionSouthAmerica",
id: "005",
countries: ["AR", "BO", "BV", "BR", "CL", "CO", "EC", "FK", "GF", "GY", "PY", "PE", "GS", "SR", "UY", "VE"]
},
{
name: "regionNorthernAmerica",
id: "021",
countries: ["BM", "CA", "GL", "PM", "US"]
}
]
},
{
name: "regionAsia",
id: "142",
includes: [
{
name: "regionCentralAsia",
id: "143",
countries: ["KZ", "KG", "TJ", "TM", "UZ"]
},
{
name: "regionEasternAsia",
id: "030",
countries: ["CN", "HK", "MO", "KP", "JP", "MN", "KR"]
},
{
name: "regionSouthEasternAsia",
id: "035",
countries: ["BN", "KH", "ID", "LA", "MY", "MM", "PH", "SG", "TH", "TL", "VN"]
},
{
name: "regionSouthernAsia",
id: "034",
countries: ["AF", "BD", "BT", "IN", "IR", "MV", "NP", "PK", "LK"]
},
{
name: "regionWesternAsia",
id: "145",
countries: ["AM", "AZ", "BH", "CY", "GE", "IQ", "IL", "JO", "KW", "LB", "OM", "QA", "SA", "PS", "SY", "TR", "AE", "YE"]
}
]
},
{
name: "regionEurope",
id: "150",
includes: [
{
name: "regionEasternEurope",
id: "151",
countries: ["BY", "BG", "CZ", "HU", "PL", "MD", "RO", "RU", "SK", "UA"]
},
{
name: "regionNorthernEurope",
id: "154",
countries: ["AX", "DK", "EE", "FO", "FI", "GG", "IS", "IE", "IM", "JE", "LV", "LT", "NO", "SJ", "SE", "GB"]
},
{
name: "regionSouthernEurope",
id: "039",
countries: ["AL", "AD", "BA", "HR", "GI", "GR", "VA", "IT", "MT", "ME", "MK", "PT", "SM", "RS", "SI", "ES"]
},
{
name: "regionWesternEurope",
id: "155",
countries: ["AT", "BE", "FR", "DE", "LI", "LU", "MC", "NL", "CH"]
}
]
},
{
name: "regionOceania",
id: "009",
includes: [
{
name: "regionAustraliaAndNewZealand",
id: "053",
countries: ["AU", "CX", "CC", "HM", "NZ", "NF"]
},
{
name: "regionMelanesia",
id: "054",
countries: ["FJ", "NC", "PG", "SB", "VU"]
},
{
name: "regionMicronesia",
id: "057",
countries: ["GU", "KI", "MH", "FM", "NR", "MP", "PW", "UM"]
},
{
name: "regionPolynesia",
id: "061",
countries: ["AS", "CK", "PF", "NU", "PN", "WS", "TK", "TO", "TV", "WF"]
}
]
}
];
type Subregion = {
name: string;
id: string;
countries: string[];
};
type Region = {
name: string;
id: string;
includes: Subregion[];
};
export function getRegionNameById(regionId: string): string | undefined {
// Check top-level regions
const region = REGIONS.find((r) => r.id === regionId);
if (region) {
return region.name;
}
// Check subregions
for (const region of REGIONS) {
for (const subregion of region.includes) {
if (subregion.id === regionId) {
return subregion.name;
}
}
}
return undefined;
}
export function isValidRegionId(regionId: string): boolean {
// Check top-level regions
if (REGIONS.find((r) => r.id === regionId)) {
return true;
}
// Check subregions
for (const region of REGIONS) {
if (region.includes.find((s) => s.id === regionId)) {
return true;
}
}
return false;
}
+4 -1
View File
@@ -376,7 +376,10 @@ export const siteProvisioningKeys = sqliteTable("siteProvisioningKeys", {
lastUsed: text("lastUsed"),
maxBatchSize: integer("maxBatchSize"), // null = no limit
numUsed: integer("numUsed").notNull().default(0),
validUntil: text("validUntil")
validUntil: text("validUntil"),
approveNewSites: integer("approveNewSites", { mode: "boolean" })
.notNull()
.default(true)
});
export const siteProvisioningKeyOrg = sqliteTable(
+4 -2
View File
@@ -110,7 +110,8 @@ export const sites = sqliteTable("sites", {
listenPort: integer("listenPort"),
dockerSocketEnabled: integer("dockerSocketEnabled", { mode: "boolean" })
.notNull()
.default(true)
.default(true),
status: text("status").$type<"pending" | "approved">()
});
export const resources = sqliteTable("resources", {
@@ -332,7 +333,8 @@ export const users = sqliteTable("user", {
serverAdmin: integer("serverAdmin", { mode: "boolean" })
.notNull()
.default(false),
lastPasswordChange: integer("lastPasswordChange")
lastPasswordChange: integer("lastPasswordChange"),
locale: text("locale")
});
export const securityKeys = sqliteTable("webauthnCredentials", {
+5
View File
@@ -31,6 +31,7 @@ import { pickPort } from "@server/routers/target/helpers";
import { resourcePassword } from "@server/db";
import { hashPassword } from "@server/auth/password";
import { isValidCIDR, isValidIP, isValidUrlGlobPattern } from "../validators";
import { isValidRegionId } from "@server/db/regions";
import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed";
import { tierMatrix } from "../billing/tierMatrix";
@@ -863,6 +864,10 @@ function validateRule(rule: any) {
if (!isValidUrlGlobPattern(rule.value)) {
throw new Error(`Invalid URL glob pattern: ${rule.value}`);
}
} else if (rule.match === "region") {
if (!isValidRegionId(rule.value)) {
throw new Error(`Invalid region ID provided: ${rule.value}`);
}
}
}
+15 -1
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { portRangeStringSchema } from "@server/lib/ip";
import { MaintenanceSchema } from "#dynamic/lib/blueprints/MaintenanceSchema";
import { isValidRegionId } from "@server/db/regions";
export const SiteSchema = z.object({
name: z.string().min(1).max(100),
@@ -77,7 +78,7 @@ export const AuthSchema = z.object({
export const RuleSchema = z
.object({
action: z.enum(["allow", "deny", "pass"]),
match: z.enum(["cidr", "path", "ip", "country", "asn"]),
match: z.enum(["cidr", "path", "ip", "country", "asn", "region"]),
value: z.string(),
priority: z.int().optional()
})
@@ -137,6 +138,19 @@ export const RuleSchema = z
message:
"Value must be 'AS<number>' format or 'ALL' when match is 'asn'"
}
)
.refine(
(rule) => {
if (rule.match === "region") {
return isValidRegionId(rule.value);
}
return true;
},
{
path: ["value"],
message:
"Value must be a valid UN M.49 region or subregion ID when match is 'region'"
}
);
export const HeaderSchema = z.object({
+1 -1
View File
@@ -2,7 +2,7 @@ import path from "path";
import { fileURLToPath } from "url";
// This is a placeholder value replaced by the build process
export const APP_VERSION = "1.16.0";
export const APP_VERSION = "1.17.0";
export const __FILENAME = fileURLToPath(import.meta.url);
export const __DIRNAME = path.dirname(__FILENAME);
@@ -4,6 +4,7 @@ import { and, eq } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
export async function verifySiteProvisioningKeyAccess(
req: Request,
@@ -116,8 +117,11 @@ export async function verifySiteProvisioningKeyAccess(
}
}
const userOrgRoleId = req.userOrg.roleId;
req.userOrgRoleId = userOrgRoleId;
req.userOrgRoleIds = await getUserOrgRoleIds(
req.userOrg.userId,
row.siteProvisioningKeyOrg.orgId
);
req.userOrgId = row.siteProvisioningKeyOrg.orgId;
return next();
} catch (error) {
+1 -1
View File
@@ -14,7 +14,7 @@
import { rateLimitService } from "#private/lib/rateLimit";
import { cleanup as wsCleanup } from "#private/routers/ws";
import { flushBandwidthToDb } from "@server/routers/newt/handleReceiveBandwidthMessage";
import { flushConnectionLogToDb } from "#dynamic/routers/newt";
import { flushConnectionLogToDb } from "#private/routers/newt";
import { flushSiteBandwidthToDb } from "@server/routers/gerbil/receiveBandwidth";
import { stopPingAccumulator } from "@server/routers/newt/pingAccumulator";
@@ -11,11 +11,11 @@
* This file is not licensed under the AGPLv3.
*/
import { accessAuditLog, logsDb, resources, db, primaryDb } from "@server/db";
import { accessAuditLog, logsDb, resources, siteResources, db, primaryDb } from "@server/db";
import { registry } from "@server/openApi";
import { NextFunction } from "express";
import { Request, Response } from "express";
import { eq, gt, lt, and, count, desc, inArray } from "drizzle-orm";
import { eq, gt, lt, and, count, desc, inArray, isNull } from "drizzle-orm";
import { OpenAPITags } from "@server/openApi";
import { z } from "zod";
import createHttpError from "http-errors";
@@ -122,6 +122,7 @@ export function queryAccess(data: Q) {
actorType: accessAuditLog.actorType,
actorId: accessAuditLog.actorId,
resourceId: accessAuditLog.resourceId,
siteResourceId: accessAuditLog.siteResourceId,
ip: accessAuditLog.ip,
location: accessAuditLog.location,
userAgent: accessAuditLog.userAgent,
@@ -136,37 +137,73 @@ export function queryAccess(data: Q) {
}
async function enrichWithResourceDetails(logs: Awaited<ReturnType<typeof queryAccess>>) {
// If logs database is the same as main database, we can do a join
// Otherwise, we need to fetch resource details separately
const resourceIds = logs
.map(log => log.resourceId)
.filter((id): id is number => id !== null && id !== undefined);
if (resourceIds.length === 0) {
const siteResourceIds = logs
.filter(log => log.resourceId == null && log.siteResourceId != null)
.map(log => log.siteResourceId)
.filter((id): id is number => id !== null && id !== undefined);
if (resourceIds.length === 0 && siteResourceIds.length === 0) {
return logs.map(log => ({ ...log, resourceName: null, resourceNiceId: null }));
}
// Fetch resource details from main database
const resourceDetails = await primaryDb
.select({
resourceId: resources.resourceId,
name: resources.name,
niceId: resources.niceId
})
.from(resources)
.where(inArray(resources.resourceId, resourceIds));
const resourceMap = new Map<number, { name: string | null; niceId: string | null }>();
// Create a map for quick lookup
const resourceMap = new Map(
resourceDetails.map(r => [r.resourceId, { name: r.name, niceId: r.niceId }])
);
if (resourceIds.length > 0) {
const resourceDetails = await primaryDb
.select({
resourceId: resources.resourceId,
name: resources.name,
niceId: resources.niceId
})
.from(resources)
.where(inArray(resources.resourceId, resourceIds));
for (const r of resourceDetails) {
resourceMap.set(r.resourceId, { name: r.name, niceId: r.niceId });
}
}
const siteResourceMap = new Map<number, { name: string | null; niceId: string | null }>();
if (siteResourceIds.length > 0) {
const siteResourceDetails = await primaryDb
.select({
siteResourceId: siteResources.siteResourceId,
name: siteResources.name,
niceId: siteResources.niceId
})
.from(siteResources)
.where(inArray(siteResources.siteResourceId, siteResourceIds));
for (const r of siteResourceDetails) {
siteResourceMap.set(r.siteResourceId, { name: r.name, niceId: r.niceId });
}
}
// Enrich logs with resource details
return logs.map(log => ({
...log,
resourceName: log.resourceId ? resourceMap.get(log.resourceId)?.name ?? null : null,
resourceNiceId: log.resourceId ? resourceMap.get(log.resourceId)?.niceId ?? null : null
}));
return logs.map(log => {
if (log.resourceId != null) {
const details = resourceMap.get(log.resourceId);
return {
...log,
resourceName: details?.name ?? null,
resourceNiceId: details?.niceId ?? null
};
} else if (log.siteResourceId != null) {
const details = siteResourceMap.get(log.siteResourceId);
return {
...log,
resourceId: log.siteResourceId,
resourceName: details?.name ?? null,
resourceNiceId: details?.niceId ?? null
};
}
return { ...log, resourceName: null, resourceNiceId: null };
});
}
export function countAccessQuery(data: Q) {
@@ -212,11 +249,23 @@ async function queryUniqueFilterAttributes(
.from(accessAuditLog)
.where(baseConditions);
// Get unique siteResources (only for logs where resourceId is null)
const uniqueSiteResources = await logsDb
.selectDistinct({
id: accessAuditLog.siteResourceId
})
.from(accessAuditLog)
.where(and(baseConditions, isNull(accessAuditLog.resourceId)));
// Fetch resource names from main database for the unique resource IDs
const resourceIds = uniqueResources
.map(row => row.id)
.filter((id): id is number => id !== null);
const siteResourceIds = uniqueSiteResources
.map(row => row.id)
.filter((id): id is number => id !== null);
let resourcesWithNames: Array<{ id: number; name: string | null }> = [];
if (resourceIds.length > 0) {
@@ -228,10 +277,31 @@ async function queryUniqueFilterAttributes(
.from(resources)
.where(inArray(resources.resourceId, resourceIds));
resourcesWithNames = resourceDetails.map(r => ({
id: r.resourceId,
name: r.name
}));
resourcesWithNames = [
...resourcesWithNames,
...resourceDetails.map(r => ({
id: r.resourceId,
name: r.name
}))
];
}
if (siteResourceIds.length > 0) {
const siteResourceDetails = await primaryDb
.select({
siteResourceId: siteResources.siteResourceId,
name: siteResources.name
})
.from(siteResources)
.where(inArray(siteResources.siteResourceId, siteResourceIds));
resourcesWithNames = [
...resourcesWithNames,
...siteResourceDetails.map(r => ({
id: r.siteResourceId,
name: r.name
}))
];
}
return {
@@ -38,7 +38,8 @@ const bodySchema = z
z.null(),
z.coerce.number().int().positive().max(1_000_000)
]),
validUntil: z.string().max(255).optional()
validUntil: z.string().max(255).optional(),
approveNewSites: z.boolean().optional().default(true)
})
.superRefine((data, ctx) => {
const v = data.validUntil;
@@ -82,7 +83,7 @@ export async function createSiteProvisioningKey(
}
const { orgId } = parsedParams.data;
const { name, maxBatchSize } = parsedBody.data;
const { name, maxBatchSize, approveNewSites } = parsedBody.data;
const vuRaw = parsedBody.data.validUntil;
const validUntil =
vuRaw == null || vuRaw.trim() === ""
@@ -106,7 +107,8 @@ export async function createSiteProvisioningKey(
lastUsed: null,
maxBatchSize,
numUsed: 0,
validUntil
validUntil,
approveNewSites
});
await trx.insert(siteProvisioningKeyOrg).values({
@@ -127,7 +129,8 @@ export async function createSiteProvisioningKey(
lastUsed: null,
maxBatchSize,
numUsed: 0,
validUntil
validUntil,
approveNewSites
},
success: true,
error: false,
@@ -57,7 +57,8 @@ function querySiteProvisioningKeys(orgId: string) {
lastUsed: siteProvisioningKeys.lastUsed,
maxBatchSize: siteProvisioningKeys.maxBatchSize,
numUsed: siteProvisioningKeys.numUsed,
validUntil: siteProvisioningKeys.validUntil
validUntil: siteProvisioningKeys.validUntil,
approveNewSites: siteProvisioningKeys.approveNewSites
})
.from(siteProvisioningKeyOrg)
.innerJoin(
@@ -39,16 +39,18 @@ const bodySchema = z
z.coerce.number().int().positive().max(1_000_000)
])
.optional(),
validUntil: z.string().max(255).optional()
validUntil: z.string().max(255).optional(),
approveNewSites: z.boolean().optional()
})
.superRefine((data, ctx) => {
if (
data.maxBatchSize === undefined &&
data.validUntil === undefined
data.validUntil === undefined &&
data.approveNewSites === undefined
) {
ctx.addIssue({
code: "custom",
message: "Provide maxBatchSize and/or validUntil",
message: "Provide maxBatchSize and/or validUntil and/or approveNewSites",
path: ["maxBatchSize"]
});
}
@@ -129,6 +131,7 @@ export async function updateSiteProvisioningKey(
const setValues: {
maxBatchSize?: number | null;
validUntil?: string | null;
approveNewSites?: boolean;
} = {};
if (body.maxBatchSize !== undefined) {
setValues.maxBatchSize = body.maxBatchSize;
@@ -139,6 +142,9 @@ export async function updateSiteProvisioningKey(
? null
: new Date(Date.parse(body.validUntil)).toISOString();
}
if (body.approveNewSites !== undefined) {
setValues.approveNewSites = body.approveNewSites;
}
await db
.update(siteProvisioningKeys)
@@ -160,7 +166,8 @@ export async function updateSiteProvisioningKey(
lastUsed: siteProvisioningKeys.lastUsed,
maxBatchSize: siteProvisioningKeys.maxBatchSize,
numUsed: siteProvisioningKeys.numUsed,
validUntil: siteProvisioningKeys.validUntil
validUntil: siteProvisioningKeys.validUntil,
approveNewSites: siteProvisioningKeys.approveNewSites
})
.from(siteProvisioningKeys)
.where(
+1 -1
View File
@@ -18,7 +18,7 @@ import {
} from "#private/routers/remoteExitNode";
import { MessageHandler } from "@server/routers/ws";
import { build } from "@server/build";
import { handleConnectionLogMessage } from "#dynamic/routers/newt";
import { handleConnectionLogMessage } from "#private/routers/newt";
export const messageHandlers: Record<string, MessageHandler> = {
"remoteExitNode/register": handleRemoteExitNodeRegisterMessage,
+94 -2
View File
@@ -1,4 +1,37 @@
import { assertEquals } from "@test/assert";
import { REGIONS } from "@server/db/regions";
function isIpInRegion(
ipCountryCode: string | undefined,
checkRegionCode: string
): boolean {
if (!ipCountryCode) {
return false;
}
const upperCode = ipCountryCode.toUpperCase();
for (const region of REGIONS) {
// Check if it's a top-level region (continent)
if (region.id === checkRegionCode) {
for (const subregion of region.includes) {
if (subregion.countries.includes(upperCode)) {
return true;
}
}
return false;
}
// Check subregions
for (const subregion of region.includes) {
if (subregion.id === checkRegionCode) {
return subregion.countries.includes(upperCode);
}
}
}
return false;
}
function isPathAllowed(pattern: string, path: string): boolean {
// Normalize and split paths into segments
@@ -272,12 +305,71 @@ function runTests() {
"Root path should not match non-root path"
);
console.log("All tests passed!");
console.log("All path matching tests passed!");
}
function runRegionTests() {
console.log("\nRunning isIpInRegion tests...");
// Test undefined country code
assertEquals(
isIpInRegion(undefined, "150"),
false,
"Undefined country code should return false"
);
// Test subregion matching (Western Europe)
assertEquals(
isIpInRegion("DE", "155"),
true,
"Country should match its subregion"
);
assertEquals(
isIpInRegion("GB", "155"),
false,
"Country should NOT match wrong subregion"
);
// Test continent matching (Europe)
assertEquals(
isIpInRegion("DE", "150"),
true,
"Country should match its continent"
);
assertEquals(
isIpInRegion("GB", "150"),
true,
"Different European country should match Europe"
);
assertEquals(
isIpInRegion("US", "150"),
false,
"Non-European country should NOT match Europe"
);
// Test case insensitivity
assertEquals(
isIpInRegion("de", "155"),
true,
"Lowercase country code should work"
);
// Test invalid region code
assertEquals(
isIpInRegion("DE", "999"),
false,
"Invalid region code should return false"
);
console.log("All region tests passed!");
}
// Run all tests
try {
runTests();
runRegionTests();
console.log("\n✅ All tests passed!");
} catch (error) {
console.error("Test failed:", error);
console.error("Test failed:", error);
process.exit(1);
}
+46
View File
@@ -36,6 +36,7 @@ import {
enforceResourceSessionLength
} from "#dynamic/lib/checkOrgAccessPolicy";
import { logRequestAudit } from "./logRequestAudit";
import { REGIONS } from "@server/db/regions";
import { localCache } from "#dynamic/lib/cache";
import { APP_VERSION } from "@server/lib/consts";
import { isSubscribed } from "#dynamic/lib/isSubscribed";
@@ -1022,6 +1023,12 @@ async function checkRules(
(await isIpInAsn(ipAsn, rule.value))
) {
return rule.action as any;
} else if (
clientIp &&
rule.match == "REGION" &&
(await isIpInRegion(ipCC, rule.value))
) {
return rule.action as any;
}
}
@@ -1207,6 +1214,45 @@ async function isIpInAsn(
return match;
}
export async function isIpInRegion(
ipCountryCode: string | undefined,
checkRegionCode: string
): Promise<boolean> {
if (!ipCountryCode) {
return false;
}
const upperCode = ipCountryCode.toUpperCase();
for (const region of REGIONS) {
// Check if it's a top-level region (continent)
if (region.id === checkRegionCode) {
for (const subregion of region.includes) {
if (subregion.countries.includes(upperCode)) {
logger.debug(`Country ${upperCode} is in region ${region.id} (${region.name})`);
return true;
}
}
logger.debug(`Country ${upperCode} is not in region ${region.id} (${region.name})`);
return false;
}
// Check subregions
for (const subregion of region.includes) {
if (subregion.id === checkRegionCode) {
if (subregion.countries.includes(upperCode)) {
logger.debug(`Country ${upperCode} is in region ${subregion.id} (${subregion.name})`);
return true;
}
logger.debug(`Country ${upperCode} is not in region ${subregion.id} (${subregion.name})`);
return false;
}
}
}
return false;
}
async function getAsnFromIp(ip: string): Promise<number | undefined> {
const asnCacheKey = `asn:${ip}`;
+5
View File
@@ -796,6 +796,11 @@ unauthenticated.get(
// );
unauthenticated.get("/user", verifySessionMiddleware, user.getUser);
unauthenticated.post(
"/user/locale",
verifySessionMiddleware,
user.updateUserLocale
);
unauthenticated.get("/my-device", verifySessionMiddleware, user.myDevice);
authenticated.get("/users", verifyUserIsServerAdmin, user.adminListUsers);
+1 -18
View File
@@ -9,14 +9,6 @@ import { buildClientConfigurationForNewtClient } from "./buildConfiguration";
import { convertTargetsIfNessicary } from "../client/targets";
import { canCompress } from "@server/lib/clientVersionChecks";
const inputSchema = z.object({
publicKey: z.string(),
port: z.int().positive(),
chainId: z.string()
});
type Input = z.infer<typeof inputSchema>;
export const handleGetConfigMessage: MessageHandler = async (context) => {
const { message, client, sendToClient } = context;
const newt = client as Newt;
@@ -35,16 +27,7 @@ export const handleGetConfigMessage: MessageHandler = async (context) => {
return;
}
const parsed = inputSchema.safeParse(message.data);
if (!parsed.success) {
logger.error(
"handleGetConfigMessage: Invalid input: " +
fromError(parsed.error).toString()
);
return;
}
const { publicKey, port, chainId } = message.data as Input;
const { publicKey, port, chainId } = message.data;
const siteId = newt.siteId;
// Get the current site data
@@ -33,7 +33,7 @@ export const handleNewtPingRequestMessage: MessageHandler = async (context) => {
return;
}
const { noCloud } = message.data;
const { noCloud, chainId } = message.data;
const exitNodesList = await listExitNodes(
site.orgId,
@@ -98,7 +98,8 @@ export const handleNewtPingRequestMessage: MessageHandler = async (context) => {
message: {
type: "newt/ping/exitNodes",
data: {
exitNodes: filteredExitNodes
exitNodes: filteredExitNodes,
chainId: chainId
}
},
broadcast: false, // Send to all clients
+8 -5
View File
@@ -30,7 +30,8 @@ import { INSPECT_MAX_BYTES } from "buffer";
import { v } from "@faker-js/faker/dist/airline-Dz1uGqgJ";
const bodySchema = z.object({
provisioningKey: z.string().nonempty()
provisioningKey: z.string().nonempty(),
name: z.string().optional()
});
export type RegisterNewtBody = z.infer<typeof bodySchema>;
@@ -56,7 +57,7 @@ export async function registerNewt(
);
}
const { provisioningKey } = parsedBody.data;
const { provisioningKey, name } = parsedBody.data;
// Keys are in the format "siteProvisioningKeyId.secret"
const dotIndex = provisioningKey.indexOf(".");
@@ -82,7 +83,8 @@ export async function registerNewt(
orgId: siteProvisioningKeyOrg.orgId,
maxBatchSize: siteProvisioningKeys.maxBatchSize,
numUsed: siteProvisioningKeys.numUsed,
validUntil: siteProvisioningKeys.validUntil
validUntil: siteProvisioningKeys.validUntil,
approveNewSites: siteProvisioningKeys.approveNewSites,
})
.from(siteProvisioningKeys)
.innerJoin(
@@ -193,10 +195,11 @@ export async function registerNewt(
.insert(sites)
.values({
orgId,
name: niceId,
name: name || niceId,
niceId,
type: "newt",
dockerSocketEnabled: true
dockerSocketEnabled: true,
status: keyRecord.approveNewSites ? "approved" : "pending",
})
.returning();
+11 -1
View File
@@ -14,10 +14,11 @@ import {
isValidUrlGlobPattern
} from "@server/lib/validators";
import { OpenAPITags, registry } from "@server/openApi";
import { isValidRegionId } from "@server/db/regions";
const createResourceRuleSchema = z.strictObject({
action: z.enum(["ACCEPT", "DROP", "PASS"]),
match: z.enum(["CIDR", "IP", "PATH", "COUNTRY", "ASN"]),
match: z.enum(["CIDR", "IP", "PATH", "COUNTRY", "ASN", "REGION"]),
value: z.string().min(1),
priority: z.int(),
enabled: z.boolean().optional()
@@ -126,6 +127,15 @@ export async function createResourceRule(
)
);
}
} else if (match === "REGION") {
if (!isValidRegionId(value)) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Invalid region ID provided"
)
);
}
}
// Create the new resource rule
+11 -1
View File
@@ -14,6 +14,7 @@ import {
isValidUrlGlobPattern
} from "@server/lib/validators";
import { OpenAPITags, registry } from "@server/openApi";
import { isValidRegionId } from "@server/db/regions";
// Define Zod schema for request parameters validation
const updateResourceRuleParamsSchema = z.strictObject({
@@ -25,7 +26,7 @@ const updateResourceRuleParamsSchema = z.strictObject({
const updateResourceRuleSchema = z
.strictObject({
action: z.enum(["ACCEPT", "DROP", "PASS"]).optional(),
match: z.enum(["CIDR", "IP", "PATH", "COUNTRY", "ASN"]).optional(),
match: z.enum(["CIDR", "IP", "PATH", "COUNTRY", "ASN", "REGION"]).optional(),
value: z.string().min(1).optional(),
priority: z.int(),
enabled: z.boolean().optional()
@@ -166,6 +167,15 @@ export async function updateResourceRule(
)
);
}
} else if (match === "REGION") {
if (!isValidRegionId(value)) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Invalid region ID provided"
)
);
}
}
}
+6 -3
View File
@@ -298,7 +298,8 @@ export async function createSite(
niceId,
address: updatedAddress || null,
type,
dockerSocketEnabled: true
dockerSocketEnabled: true,
status: "approved"
})
.returning();
} else if (type == "wireguard") {
@@ -355,7 +356,8 @@ export async function createSite(
niceId,
subnet,
type,
pubKey: pubKey || null
pubKey: pubKey || null,
status: "approved"
})
.returning();
} else if (type == "local") {
@@ -370,7 +372,8 @@ export async function createSite(
type,
dockerSocketEnabled: false,
online: true,
subnet: "0.0.0.0/32"
subnet: "0.0.0.0/32",
status: "approved"
})
.returning();
} else {
+15 -2
View File
@@ -135,6 +135,15 @@ const listSitesSchema = z.object({
.openapi({
type: "boolean",
description: "Filter by online status"
}),
status: z
.enum(["pending", "approved"])
.optional()
.catch(undefined)
.openapi({
type: "string",
enum: ["pending", "approved"],
description: "Filter by site status"
})
});
@@ -156,7 +165,8 @@ function querySitesBase() {
exitNodeId: sites.exitNodeId,
exitNodeName: exitNodes.name,
exitNodeEndpoint: exitNodes.endpoint,
remoteExitNodeId: remoteExitNodes.remoteExitNodeId
remoteExitNodeId: remoteExitNodes.remoteExitNodeId,
status: sites.status
})
.from(sites)
.leftJoin(orgs, eq(sites.orgId, orgs.orgId))
@@ -245,7 +255,7 @@ export async function listSites(
.where(eq(sites.orgId, orgId));
}
const { pageSize, page, query, sort_by, order, online } =
const { pageSize, page, query, sort_by, order, online, status } =
parsedQuery.data;
const accessibleSiteIds = accessibleSites.map((site) => site.siteId);
@@ -273,6 +283,9 @@ export async function listSites(
if (typeof online !== "undefined") {
conditions.push(eq(sites.online, online));
}
if (typeof status !== "undefined") {
conditions.push(eq(sites.status, status));
}
const baseQuery = querySitesBase().where(and(...conditions));
+2 -1
View File
@@ -19,7 +19,8 @@ const updateSiteBodySchema = z
.strictObject({
name: z.string().min(1).max(255).optional(),
niceId: z.string().min(1).max(255).optional(),
dockerSocketEnabled: z.boolean().optional()
dockerSocketEnabled: z.boolean().optional(),
status: z.enum(["pending", "approved"]).optional(),
// remoteSubnets: z.string().optional()
// subdomain: z
// .string()
+3
View File
@@ -8,6 +8,7 @@ export type SiteProvisioningKeyListItem = {
maxBatchSize: number | null;
numUsed: number;
validUntil: string | null;
approveNewSites: boolean;
};
export type ListSiteProvisioningKeysResponse = {
@@ -26,6 +27,7 @@ export type CreateSiteProvisioningKeyResponse = {
maxBatchSize: number | null;
numUsed: number;
validUntil: string | null;
approveNewSites: boolean;
};
export type UpdateSiteProvisioningKeyResponse = {
@@ -38,4 +40,5 @@ export type UpdateSiteProvisioningKeyResponse = {
maxBatchSize: number | null;
numUsed: number;
validUntil: string | null;
approveNewSites: boolean;
};
+2 -1
View File
@@ -20,7 +20,8 @@ async function queryUser(userId: string) {
emailVerified: users.emailVerified,
serverAdmin: users.serverAdmin,
idpName: idp.name,
idpId: users.idpId
idpId: users.idpId,
locale: users.locale
})
.from(users)
.leftJoin(idp, eq(users.idpId, idp.idpId))
+1
View File
@@ -17,4 +17,5 @@ export * from "./createOrgUser";
export * from "./adminUpdateUser2FA";
export * from "./adminGetUser";
export * from "./updateOrgUser";
export * from "./updateUserLocale";
export * from "./myDevice";
+2 -1
View File
@@ -63,7 +63,8 @@ export async function myDevice(
emailVerified: users.emailVerified,
serverAdmin: users.serverAdmin,
idpName: idp.name,
idpId: users.idpId
idpId: users.idpId,
locale: users.locale
})
.from(users)
.leftJoin(idp, eq(users.idpId, idp.idpId))
+57
View File
@@ -0,0 +1,57 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { users } from "@server/db";
import { eq } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
const bodySchema = z.strictObject({
locale: z.string().min(2).max(10)
});
export async function updateUserLocale(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const userId = req.user?.userId;
if (!userId) {
return next(
createHttpError(HttpCode.UNAUTHORIZED, "User not found")
);
}
const parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { locale } = parsedBody.data;
await db.update(users).set({ locale }).where(eq(users.userId, userId));
return response(res, {
data: null,
success: true,
error: false,
message: "User locale updated successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}
+171 -5
View File
@@ -20,9 +20,82 @@ export default async function migration() {
`Found ${existingUserOrgRoles.length} existing userOrgs role assignment(s) to migrate`
);
// Query existing roleId data from userInvites before the transaction destroys it
const existingInviteRolesQuery = await db.execute(
sql`SELECT "inviteId", "roleId" FROM "userInvites" WHERE "roleId" IS NOT NULL`
);
const existingUserInviteRoles = existingInviteRolesQuery.rows as {
inviteId: string;
roleId: number;
}[];
console.log(
`Found ${existingUserInviteRoles.length} existing userInvites role assignment(s) to migrate`
);
try {
await db.execute(sql`BEGIN`);
await db.execute(sql`
CREATE TABLE "bannedEmails" (
"email" varchar(255) PRIMARY KEY NOT NULL
);
`);
await db.execute(sql`
CREATE TABLE "bannedIps" (
"ip" varchar(255) PRIMARY KEY NOT NULL
);
`);
await db.execute(sql`
CREATE TABLE "connectionAuditLog" (
"id" serial PRIMARY KEY NOT NULL,
"sessionId" text NOT NULL,
"siteResourceId" integer,
"orgId" text,
"siteId" integer,
"clientId" integer,
"userId" text,
"sourceAddr" text NOT NULL,
"destAddr" text NOT NULL,
"protocol" text NOT NULL,
"startedAt" integer NOT NULL,
"endedAt" integer,
"bytesTx" integer,
"bytesRx" integer
);
`);
await db.execute(sql`
CREATE TABLE "siteProvisioningKeyOrg" (
"siteProvisioningKeyId" varchar(255) NOT NULL,
"orgId" varchar(255) NOT NULL,
CONSTRAINT "siteProvisioningKeyOrg_siteProvisioningKeyId_orgId_pk" PRIMARY KEY("siteProvisioningKeyId","orgId")
);
`);
await db.execute(sql`
CREATE TABLE "siteProvisioningKeys" (
"siteProvisioningKeyId" varchar(255) PRIMARY KEY NOT NULL,
"name" varchar(255) NOT NULL,
"siteProvisioningKeyHash" text NOT NULL,
"lastChars" varchar(4) NOT NULL,
"dateCreated" varchar(255) NOT NULL,
"lastUsed" varchar(255),
"maxBatchSize" integer,
"numUsed" integer DEFAULT 0 NOT NULL,
"validUntil" varchar(255)
);
`);
await db.execute(sql`
CREATE TABLE "userInviteRoles" (
"inviteId" varchar NOT NULL,
"roleId" integer NOT NULL,
CONSTRAINT "userInviteRoles_inviteId_roleId_pk" PRIMARY KEY("inviteId","roleId")
);
`);
await db.execute(sql`
CREATE TABLE "userOrgRoles" (
"userId" varchar NOT NULL,
@@ -31,12 +104,82 @@ export default async function migration() {
CONSTRAINT "userOrgRoles_userId_orgId_roleId_unique" UNIQUE("userId","orgId","roleId")
);
`);
await db.execute(sql`ALTER TABLE "userOrgs" DROP CONSTRAINT "userOrgs_roleId_roles_roleId_fk";`);
await db.execute(sql`ALTER TABLE "userOrgRoles" ADD CONSTRAINT "userOrgRoles_userId_user_id_fk" FOREIGN KEY ("userId") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;`);
await db.execute(sql`ALTER TABLE "userOrgRoles" ADD CONSTRAINT "userOrgRoles_orgId_orgs_orgId_fk" FOREIGN KEY ("orgId") REFERENCES "public"."orgs"("orgId") ON DELETE cascade ON UPDATE no action;`);
await db.execute(sql`ALTER TABLE "userOrgRoles" ADD CONSTRAINT "userOrgRoles_roleId_roles_roleId_fk" FOREIGN KEY ("roleId") REFERENCES "public"."roles"("roleId") ON DELETE cascade ON UPDATE no action;`);
await db.execute(
sql`ALTER TABLE "userOrgs" DROP CONSTRAINT "userOrgs_roleId_roles_roleId_fk";`
);
await db.execute(
sql`ALTER TABLE "userOrgRoles" ADD CONSTRAINT "userOrgRoles_userId_user_id_fk" FOREIGN KEY ("userId") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;`
);
await db.execute(
sql`ALTER TABLE "userOrgRoles" ADD CONSTRAINT "userOrgRoles_orgId_orgs_orgId_fk" FOREIGN KEY ("orgId") REFERENCES "public"."orgs"("orgId") ON DELETE cascade ON UPDATE no action;`
);
await db.execute(
sql`ALTER TABLE "userOrgRoles" ADD CONSTRAINT "userOrgRoles_roleId_roles_roleId_fk" FOREIGN KEY ("roleId") REFERENCES "public"."roles"("roleId") ON DELETE cascade ON UPDATE no action;`
);
await db.execute(sql`ALTER TABLE "userOrgs" DROP COLUMN "roleId";`);
await db.execute(
sql`ALTER TABLE "userInvites" DROP CONSTRAINT "userInvites_roleId_roles_roleId_fk";`
);
await db.execute(
sql`ALTER TABLE "accessAuditLog" ADD COLUMN "siteResourceId" integer;`
);
await db.execute(
sql`ALTER TABLE "clientSitesAssociationsCache" ADD COLUMN "isJitMode" boolean DEFAULT false NOT NULL;`
);
await db.execute(
sql`ALTER TABLE "domains" ADD COLUMN "errorMessage" text;`
);
await db.execute(
sql`ALTER TABLE "orgs" ADD COLUMN "settingsLogRetentionDaysConnection" integer DEFAULT 0 NOT NULL;`
);
await db.execute(
sql`ALTER TABLE "sites" ADD COLUMN "lastPing" integer;`
);
await db.execute(
sql`ALTER TABLE "user" ADD COLUMN "marketingEmailConsent" boolean DEFAULT false;`
);
await db.execute(sql`ALTER TABLE "user" ADD COLUMN "locale" varchar;`);
await db.execute(
sql`ALTER TABLE "connectionAuditLog" ADD CONSTRAINT "connectionAuditLog_siteResourceId_siteResources_siteResourceId_fk" FOREIGN KEY ("siteResourceId") REFERENCES "public"."siteResources"("siteResourceId") ON DELETE cascade ON UPDATE no action;`
);
await db.execute(
sql`ALTER TABLE "connectionAuditLog" ADD CONSTRAINT "connectionAuditLog_orgId_orgs_orgId_fk" FOREIGN KEY ("orgId") REFERENCES "public"."orgs"("orgId") ON DELETE cascade ON UPDATE no action;`
);
await db.execute(
sql`ALTER TABLE "connectionAuditLog" ADD CONSTRAINT "connectionAuditLog_siteId_sites_siteId_fk" FOREIGN KEY ("siteId") REFERENCES "public"."sites"("siteId") ON DELETE cascade ON UPDATE no action;`
);
await db.execute(
sql`ALTER TABLE "connectionAuditLog" ADD CONSTRAINT "connectionAuditLog_clientId_clients_clientId_fk" FOREIGN KEY ("clientId") REFERENCES "public"."clients"("clientId") ON DELETE cascade ON UPDATE no action;`
);
await db.execute(
sql`ALTER TABLE "connectionAuditLog" ADD CONSTRAINT "connectionAuditLog_userId_user_id_fk" FOREIGN KEY ("userId") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;`
);
await db.execute(
sql`ALTER TABLE "siteProvisioningKeyOrg" ADD CONSTRAINT "siteProvisioningKeyOrg_siteProvisioningKeyId_siteProvisioningKeys_siteProvisioningKeyId_fk" FOREIGN KEY ("siteProvisioningKeyId") REFERENCES "public"."siteProvisioningKeys"("siteProvisioningKeyId") ON DELETE cascade ON UPDATE no action;`
);
await db.execute(
sql`ALTER TABLE "siteProvisioningKeyOrg" ADD CONSTRAINT "siteProvisioningKeyOrg_orgId_orgs_orgId_fk" FOREIGN KEY ("orgId") REFERENCES "public"."orgs"("orgId") ON DELETE cascade ON UPDATE no action;`
);
await db.execute(
sql`ALTER TABLE "userInviteRoles" ADD CONSTRAINT "userInviteRoles_inviteId_userInvites_inviteId_fk" FOREIGN KEY ("inviteId") REFERENCES "public"."userInvites"("inviteId") ON DELETE cascade ON UPDATE no action;`
);
await db.execute(
sql`ALTER TABLE "userInviteRoles" ADD CONSTRAINT "userInviteRoles_roleId_roles_roleId_fk" FOREIGN KEY ("roleId") REFERENCES "public"."roles"("roleId") ON DELETE cascade ON UPDATE no action;`
);
await db.execute(
sql`CREATE INDEX "idx_accessAuditLog_startedAt" ON "connectionAuditLog" USING btree ("startedAt");`
);
await db.execute(
sql`CREATE INDEX "idx_accessAuditLog_org_startedAt" ON "connectionAuditLog" USING btree ("orgId","startedAt");`
);
await db.execute(
sql`CREATE INDEX "idx_accessAuditLog_siteResourceId" ON "connectionAuditLog" USING btree ("siteResourceId");`
);
await db.execute(sql`ALTER TABLE "userInvites" DROP COLUMN "roleId";`);
await db.execute(sql`ALTER TABLE "siteProvisioningKeys" ADD COLUMN "approveNewSites" boolean DEFAULT true NOT NULL;`);
await db.execute(sql`ALTER TABLE "sites" ADD COLUMN "status" varchar;`);
await db.execute(sql`COMMIT`);
console.log("Migrated database");
} catch (e) {
@@ -46,6 +189,29 @@ export default async function migration() {
throw e;
}
// Re-insert the preserved invite role assignments into the new userInviteRoles table
if (existingUserInviteRoles.length > 0) {
try {
for (const row of existingUserInviteRoles) {
await db.execute(sql`
INSERT INTO "userInviteRoles" ("inviteId", "roleId")
VALUES (${row.inviteId}, ${row.roleId})
ON CONFLICT DO NOTHING
`);
}
console.log(
`Migrated ${existingUserInviteRoles.length} role assignment(s) into userInviteRoles`
);
} catch (e) {
console.error(
"Error while migrating role assignments into userInviteRoles:",
e
);
throw e;
}
}
// Re-insert the preserved role assignments into the new userOrgRoles table
if (existingUserOrgRoles.length > 0) {
try {
@@ -70,4 +236,4 @@ export default async function migration() {
}
console.log(`${version} migration complete`);
}
}
+150 -1
View File
@@ -24,7 +24,89 @@ export default async function migration() {
`Found ${existingUserOrgRoles.length} existing userOrgs role assignment(s) to migrate`
);
// Query existing roleId data from userInvites before the transaction destroys it
const existingUserInviteRoles = db
.prepare(
`SELECT "inviteId", "roleId" FROM 'userInvites' WHERE "roleId" IS NOT NULL`
)
.all() as { inviteId: string; roleId: number }[];
console.log(
`Found ${existingUserInviteRoles.length} existing userInvites role assignment(s) to migrate`
);
db.transaction(() => {
db.prepare(
`
CREATE TABLE 'bannedEmails' (
'email' text PRIMARY KEY NOT NULL
);
`
).run();
db.prepare(
`
CREATE TABLE 'bannedIps' (
'ip' text PRIMARY KEY NOT NULL
);
`
).run();
db.prepare(
`
CREATE TABLE 'connectionAuditLog' (
'id' integer PRIMARY KEY AUTOINCREMENT NOT NULL,
'sessionId' text NOT NULL,
'siteResourceId' integer,
'orgId' text,
'siteId' integer,
'clientId' integer,
'userId' text,
'sourceAddr' text NOT NULL,
'destAddr' text NOT NULL,
'protocol' text NOT NULL,
'startedAt' integer NOT NULL,
'endedAt' integer,
'bytesTx' integer,
'bytesRx' integer,
FOREIGN KEY ('siteResourceId') REFERENCES 'siteResources'('siteResourceId') ON UPDATE no action ON DELETE cascade,
FOREIGN KEY ('orgId') REFERENCES 'orgs'('orgId') ON UPDATE no action ON DELETE cascade,
FOREIGN KEY ('siteId') REFERENCES 'sites'('siteId') ON UPDATE no action ON DELETE cascade,
FOREIGN KEY ('clientId') REFERENCES 'clients'('clientId') ON UPDATE no action ON DELETE cascade,
FOREIGN KEY ('userId') REFERENCES 'user'('id') ON UPDATE no action ON DELETE cascade
);
`
).run();
db.prepare(`CREATE INDEX 'idx_accessAuditLog_startedAt' ON 'connectionAuditLog' ('startedAt');`).run();
db.prepare(`CREATE INDEX 'idx_accessAuditLog_org_startedAt' ON 'connectionAuditLog' ('orgId','startedAt');`).run();
db.prepare(`CREATE INDEX 'idx_accessAuditLog_siteResourceId' ON 'connectionAuditLog' ('siteResourceId');`).run();
db.prepare(
`
CREATE TABLE 'siteProvisioningKeyOrg' (
'siteProvisioningKeyId' text NOT NULL,
'orgId' text NOT NULL,
PRIMARY KEY('siteProvisioningKeyId', 'orgId'),
FOREIGN KEY ('siteProvisioningKeyId') REFERENCES 'siteProvisioningKeys'('siteProvisioningKeyId') ON UPDATE no action ON DELETE cascade,
FOREIGN KEY ('orgId') REFERENCES 'orgs'('orgId') ON UPDATE no action ON DELETE cascade
);
`
).run();
db.prepare(
`
CREATE TABLE 'siteProvisioningKeys' (
'siteProvisioningKeyId' text PRIMARY KEY NOT NULL,
'name' text NOT NULL,
'siteProvisioningKeyHash' text NOT NULL,
'lastChars' text NOT NULL,
'dateCreated' text NOT NULL,
'lastUsed' text,
'maxBatchSize' integer,
'numUsed' integer DEFAULT 0 NOT NULL,
'validUntil' text
);
`
).run();
db.prepare(
`
CREATE TABLE 'userOrgRoles' (
@@ -63,10 +145,77 @@ export default async function migration() {
db.prepare(
`ALTER TABLE '__new_userOrgs' RENAME TO 'userOrgs';`
).run();
db.prepare(
`
CREATE TABLE 'userInviteRoles' (
'inviteId' text NOT NULL,
'roleId' integer NOT NULL,
PRIMARY KEY('inviteId', 'roleId'),
FOREIGN KEY ('inviteId') REFERENCES 'userInvites'('inviteId') ON UPDATE no action ON DELETE cascade,
FOREIGN KEY ('roleId') REFERENCES 'roles'('roleId') ON UPDATE no action ON DELETE cascade
);
`
).run();
db.prepare(
`
CREATE TABLE '__new_userInvites' (
'inviteId' text PRIMARY KEY NOT NULL,
'orgId' text NOT NULL,
'email' text NOT NULL,
'expiresAt' integer NOT NULL,
'token' text NOT NULL,
FOREIGN KEY ('orgId') REFERENCES 'orgs'('orgId') ON UPDATE no action ON DELETE cascade
);
`
).run();
db.prepare(
`INSERT INTO '__new_userInvites'("inviteId", "orgId", "email", "expiresAt", "token") SELECT "inviteId", "orgId", "email", "expiresAt", "token" FROM 'userInvites';`
).run();
db.prepare(`DROP TABLE 'userInvites';`).run();
db.prepare(
`ALTER TABLE '__new_userInvites' RENAME TO 'userInvites';`
).run();
db.prepare(
`ALTER TABLE 'accessAuditLog' ADD 'siteResourceId' integer;`
).run();
db.prepare(
`ALTER TABLE 'clientSitesAssociationsCache' ADD 'isJitMode' integer DEFAULT false NOT NULL;`
).run();
db.prepare(`ALTER TABLE 'domains' ADD 'errorMessage' text;`).run();
db.prepare(
`ALTER TABLE 'orgs' ADD 'settingsLogRetentionDaysConnection' integer DEFAULT 0 NOT NULL;`
).run();
db.prepare(`ALTER TABLE 'sites' ADD 'lastPing' integer;`).run();
db.prepare(
`ALTER TABLE 'user' ADD 'marketingEmailConsent' integer DEFAULT false;`
).run();
db.prepare(`ALTER TABLE 'user' ADD 'locale' text;`).run();
db.prepare(`ALTER TABLE 'siteProvisioningKeys' ADD COLUMN 'approveNewSites' integer DEFAULT 1 NOT NULL;`).run();
db.prepare(`ALTER TABLE 'sites' ADD COLUMN 'status' text;`).run();
})();
db.pragma("foreign_keys = ON");
// Re-insert the preserved invite role assignments into the new userInviteRoles table
if (existingUserInviteRoles.length > 0) {
const insertUserInviteRole = db.prepare(
`INSERT OR IGNORE INTO 'userInviteRoles' ("inviteId", "roleId") VALUES (?, ?)`
);
const insertAll = db.transaction(() => {
for (const row of existingUserInviteRoles) {
insertUserInviteRole.run(row.inviteId, row.roleId);
}
});
insertAll();
console.log(
`Migrated ${existingUserInviteRoles.length} role assignment(s) into userInviteRoles`
);
}
// Re-insert the preserved role assignments into the new userOrgRoles table
if (existingUserOrgRoles.length > 0) {
const insertUserOrgRole = db.prepare(
@@ -93,4 +242,4 @@ export default async function migration() {
}
console.log(`${version} migration complete`);
}
}
@@ -465,7 +465,11 @@ export default function GeneralPage() {
cell: ({ row }) => {
return (
<Link
href={`/${row.original.orgId}/settings/resources/proxy/${row.original.resourceNiceId}`}
href={
row.original.type === "ssh"
? `/${row.original.orgId}/settings/resources/client?query=${row.original.resourceNiceId}`
: `/${row.original.orgId}/settings/resources/proxy/${row.original.resourceNiceId}`
}
>
<Button
variant="outline"
@@ -0,0 +1,84 @@
import { internal } from "@app/lib/api";
import { authCookieHeader } from "@app/lib/api/cookies";
import { AxiosResponse } from "axios";
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
import SiteProvisioningKeysTable, {
SiteProvisioningKeyRow
} from "../../../../../components/SiteProvisioningKeysTable";
import { ListSiteProvisioningKeysResponse } from "@server/routers/siteProvisioning/types";
import { getTranslations } from "next-intl/server";
import { TierFeature, tierMatrix } from "@server/lib/billing/tierMatrix";
import DismissableBanner from "@app/components/DismissableBanner";
import Link from "next/link";
import { Button } from "@app/components/ui/button";
import { ArrowRight, Plug } from "lucide-react";
type ProvisioningKeysPageProps = {
params: Promise<{ orgId: string }>;
};
export const dynamic = "force-dynamic";
export default async function ProvisioningKeysPage(
props: ProvisioningKeysPageProps
) {
const params = await props.params;
const t = await getTranslations();
let siteProvisioningKeys: ListSiteProvisioningKeysResponse["siteProvisioningKeys"] =
[];
try {
const res = await internal.get<
AxiosResponse<ListSiteProvisioningKeysResponse>
>(
`/org/${params.orgId}/site-provisioning-keys`,
await authCookieHeader()
);
siteProvisioningKeys = res.data.data.siteProvisioningKeys;
} catch (e) {}
const rows: SiteProvisioningKeyRow[] = siteProvisioningKeys.map((k) => ({
name: k.name,
id: k.siteProvisioningKeyId,
key: `${k.siteProvisioningKeyId}••••••••••••••••••••${k.lastChars}`,
createdAt: k.createdAt,
lastUsed: k.lastUsed,
maxBatchSize: k.maxBatchSize,
numUsed: k.numUsed,
validUntil: k.validUntil,
approveNewSites: k.approveNewSites
}));
return (
<>
<DismissableBanner
storageKey="sites-banner-dismissed"
version={1}
title={t("provisioningKeysBannerTitle")}
titleIcon={<Plug className="w-5 h-5 text-primary" />}
description={t("provisioningKeysBannerDescription")}
>
<Link
href="https://docs.pangolin.net/manage/sites/install-site"
target="_blank"
rel="noopener noreferrer"
>
<Button
variant="outline"
size="sm"
className="gap-2 hover:bg-primary/10 hover:border-primary/50 transition-colors"
>
{t("provisioningKeysBannerButtonText")}
<ArrowRight className="w-4 h-4" />
</Button>
</Link>
</DismissableBanner>
<PaidFeaturesAlert
tiers={tierMatrix[TierFeature.SiteProvisioningKeys]}
/>
<SiteProvisioningKeysTable keys={rows} orgId={params.orgId} />
</>
);
}
@@ -0,0 +1,38 @@
import SettingsSectionTitle from "@app/components/SettingsSectionTitle";
import { HorizontalTabs } from "@app/components/HorizontalTabs";
import { getTranslations } from "next-intl/server";
interface ProvisioningLayoutProps {
children: React.ReactNode;
params: Promise<{ orgId: string }>;
}
export default async function ProvisioningLayout({
children,
params
}: ProvisioningLayoutProps) {
const { orgId } = await params;
const t = await getTranslations();
const navItems = [
{
title: t("provisioningKeys"),
href: `/${orgId}/settings/provisioning/keys`
},
{
title: t("pendingSites"),
href: `/${orgId}/settings/provisioning/pending`
}
];
return (
<>
<SettingsSectionTitle
title={t("provisioningManage")}
description={t("provisioningDescription")}
/>
<HorizontalTabs items={navItems}>{children}</HorizontalTabs>
</>
);
}
+3 -53
View File
@@ -1,60 +1,10 @@
import { internal } from "@app/lib/api";
import { authCookieHeader } from "@app/lib/api/cookies";
import { AxiosResponse } from "axios";
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
import SettingsSectionTitle from "@app/components/SettingsSectionTitle";
import SiteProvisioningKeysTable, {
SiteProvisioningKeyRow
} from "../../../../components/SiteProvisioningKeysTable";
import { ListSiteProvisioningKeysResponse } from "@server/routers/siteProvisioning/types";
import { getTranslations } from "next-intl/server";
import { TierFeature, tierMatrix } from "@server/lib/billing/tierMatrix";
import { redirect } from "next/navigation";
type ProvisioningPageProps = {
params: Promise<{ orgId: string }>;
};
export const dynamic = "force-dynamic";
export default async function ProvisioningPage(props: ProvisioningPageProps) {
const params = await props.params;
const t = await getTranslations();
let siteProvisioningKeys: ListSiteProvisioningKeysResponse["siteProvisioningKeys"] =
[];
try {
const res = await internal.get<
AxiosResponse<ListSiteProvisioningKeysResponse>
>(
`/org/${params.orgId}/site-provisioning-keys`,
await authCookieHeader()
);
siteProvisioningKeys = res.data.data.siteProvisioningKeys;
} catch (e) {}
const rows: SiteProvisioningKeyRow[] = siteProvisioningKeys.map((k) => ({
name: k.name,
id: k.siteProvisioningKeyId,
key: `${k.siteProvisioningKeyId}••••••••••••••••••••${k.lastChars}`,
createdAt: k.createdAt,
lastUsed: k.lastUsed,
maxBatchSize: k.maxBatchSize,
numUsed: k.numUsed,
validUntil: k.validUntil
}));
return (
<>
<SettingsSectionTitle
title={t("provisioningKeysManage")}
description={t("provisioningKeysDescription")}
/>
<PaidFeaturesAlert
tiers={tierMatrix[TierFeature.SiteProvisioningKeys]}
/>
<SiteProvisioningKeysTable keys={rows} orgId={params.orgId} />
</>
);
}
redirect(`/${params.orgId}/settings/provisioning/keys`);
}
@@ -0,0 +1,110 @@
import { internal } from "@app/lib/api";
import { authCookieHeader } from "@app/lib/api/cookies";
import { ListSitesResponse } from "@server/routers/site";
import { AxiosResponse } from "axios";
import { SiteRow } from "@app/components/SitesTable";
import PendingSitesTable from "@app/components/PendingSitesTable";
import { getTranslations } from "next-intl/server";
import DismissableBanner from "@app/components/DismissableBanner";
import Link from "next/link";
import { Button } from "@app/components/ui/button";
import { ArrowRight, Plug } from "lucide-react";
type PendingSitesPageProps = {
params: Promise<{ orgId: string }>;
searchParams: Promise<Record<string, string>>;
};
export const dynamic = "force-dynamic";
export default async function PendingSitesPage(props: PendingSitesPageProps) {
const params = await props.params;
const incomingSearchParams = new URLSearchParams(await props.searchParams);
incomingSearchParams.set("status", "pending");
let sites: ListSitesResponse["sites"] = [];
let pagination: ListSitesResponse["pagination"] = {
total: 0,
page: 1,
pageSize: 20
};
try {
const res = await internal.get<AxiosResponse<ListSitesResponse>>(
`/org/${params.orgId}/sites?${incomingSearchParams.toString()}`,
await authCookieHeader()
);
const responseData = res.data.data;
sites = responseData.sites;
pagination = responseData.pagination;
} catch (e) {}
const t = await getTranslations();
function formatSize(mb: number, type: string): string {
if (type === "local") {
return "-";
}
if (mb >= 1024 * 1024) {
return t("terabytes", { count: (mb / (1024 * 1024)).toFixed(2) });
} else if (mb >= 1024) {
return t("gigabytes", { count: (mb / 1024).toFixed(2) });
} else {
return t("megabytes", { count: mb.toFixed(2) });
}
}
const siteRows: SiteRow[] = sites.map((site) => ({
name: site.name,
id: site.siteId,
nice: site.niceId.toString(),
address: site.address?.split("/")[0],
mbIn: formatSize(site.megabytesIn || 0, site.type),
mbOut: formatSize(site.megabytesOut || 0, site.type),
orgId: params.orgId,
type: site.type as any,
online: site.online,
newtVersion: site.newtVersion || undefined,
newtUpdateAvailable: site.newtUpdateAvailable || false,
exitNodeName: site.exitNodeName || undefined,
exitNodeEndpoint: site.exitNodeEndpoint || undefined,
remoteExitNodeId: (site as any).remoteExitNodeId || undefined
}));
return (
<>
<DismissableBanner
storageKey="sites-banner-dismissed"
version={1}
title={t("pendingSitesBannerTitle")}
titleIcon={<Plug className="w-5 h-5 text-primary" />}
description={t("pendingSitesBannerDescription")}
>
<Link
href="https://docs.pangolin.net/manage/sites/install-site"
target="_blank"
rel="noopener noreferrer"
>
<Button
variant="outline"
size="sm"
className="gap-2 hover:bg-primary/10 hover:border-primary/50 transition-colors"
>
{t("pendingSitesBannerButtonText")}
<ArrowRight className="w-4 h-4" />
</Button>
</Link>
</DismissableBanner>
<PendingSitesTable
sites={siteRows}
orgId={params.orgId}
rowCount={pagination.total}
pagination={{
pageIndex: pagination.page - 1,
pageSize: pagination.pageSize
}}
/>
</>
);
}
@@ -6,7 +6,9 @@ import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue
} from "@/components/ui/select";
@@ -76,6 +78,7 @@ import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { COUNTRIES } from "@server/db/countries";
import { MAJOR_ASNS } from "@server/db/asns";
import { REGIONS, getRegionNameById, isValidRegionId } from "@server/db/regions";
import {
Command,
CommandEmpty,
@@ -123,7 +126,10 @@ export default function ResourceRules(props: {
const [countrySelectValue, setCountrySelectValue] = useState("");
const [openAddRuleCountrySelect, setOpenAddRuleCountrySelect] =
useState(false);
const [openAddRuleAsnSelect, setOpenAddRuleAsnSelect] = useState(false);
const [openAddRuleAsnSelect, setOpenAddRuleAsnSelect] =
useState(false);
const [openAddRuleRegionSelect, setOpenAddRuleRegionSelect] =
useState(false);
const router = useRouter();
const t = useTranslations();
const { env } = useEnvContext();
@@ -143,14 +149,15 @@ export default function ResourceRules(props: {
IP: "IP",
CIDR: t("ipAddressRange"),
COUNTRY: t("country"),
ASN: "ASN"
ASN: "ASN",
REGION: t("region")
} as const;
const addRuleForm = useForm({
resolver: zodResolver(addRuleSchema),
defaultValues: {
action: "ACCEPT",
match: "IP",
match: "PATH",
value: ""
}
});
@@ -263,6 +270,20 @@ export default function ResourceRules(props: {
setLoading(false);
return;
}
if (
data.match === "REGION" &&
!isValidRegionId(data.value)
) {
toast({
variant: "destructive",
title: t("rulesErrorInvalidRegion"),
description:
t("rulesErrorInvalidRegionDescription") ||
"Invalid region."
});
setLoading(false);
return;
}
// find the highest priority and add one
let priority = data.priority;
@@ -316,6 +337,8 @@ export default function ResourceRules(props: {
return t("rulesMatchCountry");
case "ASN":
return "Enter an Autonomous System Number (e.g., AS15169 or 15169)";
case "REGION":
return t("rulesMatchRegion");
}
}
@@ -541,16 +564,12 @@ export default function ResourceRules(props: {
<Select
defaultValue={row.original.match}
onValueChange={(
value: "CIDR" | "IP" | "PATH" | "COUNTRY" | "ASN"
value: "CIDR" | "IP" | "PATH" | "COUNTRY" | "ASN" | "REGION"
) =>
updateRule(row.original.ruleId, {
match: value,
value:
value === "COUNTRY"
? "US"
: value === "ASN"
? "AS15169"
: row.original.value
value === "COUNTRY" ? "US" : value === "ASN" ? "AS15169" : value === "REGION" ? "021" : row.original.value
})
}
>
@@ -566,6 +585,11 @@ export default function ResourceRules(props: {
{RuleMatch.COUNTRY}
</SelectItem>
)}
{isMaxmindAvailable && (
<SelectItem value="REGION">
{RuleMatch.REGION}
</SelectItem>
)}
{isMaxmindAsnAvailable && (
<SelectItem value="ASN">{RuleMatch.ASN}</SelectItem>
)}
@@ -645,14 +669,14 @@ export default function ResourceRules(props: {
>
{row.original.value
? (() => {
const found = MAJOR_ASNS.find(
const found = MAJOR_ASNS.find(
(asn) =>
asn.code ===
row.original.value
);
return found
? `${found.name} (${row.original.value})`
: `Custom (${row.original.value})`;
);
return found
? `${found.name} (${row.original.value})`
: `Custom (${row.original.value})`;
})()
: "Select ASN"}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
@@ -722,6 +746,88 @@ export default function ResourceRules(props: {
</div>
</PopoverContent>
</Popover>
) : row.original.match === "REGION" ? (
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
className="min-w-[200px] justify-between"
>
{(() => {
const regionName = getRegionNameById(row.original.value);
if (!regionName) {
return t("selectRegion");
}
return `${t(regionName)} (${row.original.value})`;
})()}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="min-w-[200px] p-0">
<Command>
<CommandInput
placeholder={t("searchRegions")}
/>
<CommandList>
<CommandEmpty>
{t("noRegionFound")}
</CommandEmpty>
{REGIONS.map((continent) => (
<CommandGroup key={continent.id} heading={t(continent.name)}>
<CommandItem
value={continent.id}
keywords={[
t(continent.name),
continent.id
]}
onSelect={() => {
updateRule(
row.original.ruleId,
{ value: continent.id }
);
}}
>
<Check
className={`mr-2 h-4 w-4 ${
row.original.value === continent.id
? "opacity-100"
: "opacity-0"
}`}
/>
{t(continent.name)} ({continent.id})
</CommandItem>
{continent.includes.map((subregion) => (
<CommandItem
key={subregion.id}
value={subregion.id}
keywords={[
t(subregion.name),
subregion.id
]}
onSelect={() => {
updateRule(
row.original.ruleId,
{ value: subregion.id }
);
}}
>
<Check
className={`mr-2 h-4 w-4 ${
row.original.value === subregion.id
? "opacity-100"
: "opacity-0"
}`}
/>
{t(subregion.name)} ({subregion.id})
</CommandItem>
))}
</CommandGroup>
))}
</CommandList>
</Command>
</PopoverContent>
</Popover>
) : (
<Input
defaultValue={row.original.value}
@@ -932,6 +1038,13 @@ export default function ResourceRules(props: {
}
</SelectItem>
)}
{isMaxmindAvailable && (
<SelectItem value="REGION">
{
RuleMatch.REGION
}
</SelectItem>
)}
{isMaxmindAsnAvailable && (
<SelectItem value="ASN">
{
@@ -1197,6 +1310,112 @@ export default function ResourceRules(props: {
</div>
</PopoverContent>
</Popover>
) : addRuleForm.watch(
"match"
) === "REGION" ? (
<Popover
open={
openAddRuleRegionSelect
}
onOpenChange={
setOpenAddRuleRegionSelect
}
>
<PopoverTrigger
asChild
>
<Button
variant="outline"
role="combobox"
aria-expanded={
openAddRuleRegionSelect
}
className="w-full justify-between"
>
{field.value
? (() => {
const regionName = getRegionNameById(field.value);
const translatedName = regionName ? t(regionName) : field.value;
return `${translatedName} (${field.value})`;
})()
: t(
"selectRegion"
)}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-full p-0">
<Command>
<CommandInput
placeholder={t(
"searchRegions"
)}
/>
<CommandList>
<CommandEmpty>
{t(
"noRegionFound"
)}
</CommandEmpty>
{REGIONS.map((continent) => (
<CommandGroup key={continent.id} heading={t(continent.name)}>
<CommandItem
value={continent.id}
keywords={[
t(continent.name),
continent.id
]}
onSelect={() => {
field.onChange(
continent.id
);
setOpenAddRuleRegionSelect(
false
);
}}
>
<Check
className={`mr-2 h-4 w-4 ${
field.value === continent.id
? "opacity-100"
: "opacity-0"
}`}
/>
{t(continent.name)} ({continent.id})
</CommandItem>
{continent.includes.map((subregion) => (
<CommandItem
key={subregion.id}
value={subregion.id}
keywords={[
t(subregion.name),
subregion.id
]}
onSelect={() => {
field.onChange(
subregion.id
);
setOpenAddRuleRegionSelect(
false
);
}}
>
<Check
className={`mr-2 h-4 w-4 ${
field.value === subregion.id
? "opacity-100"
: "opacity-0"
}`}
/>
{t(subregion.name)} ({subregion.id})
</CommandItem>
))}
</CommandGroup>
))}
</CommandList>
</Command>
</PopoverContent>
</Popover>
) : (
<Input {...field} />
)}
+1
View File
@@ -18,6 +18,7 @@ export default async function SitesPage(props: SitesPageProps) {
const params = await props.params;
const searchParams = new URLSearchParams(await props.searchParams);
searchParams.set("status", "approved");
let sites: ListSitesResponse["sites"] = [];
let pagination: ListSitesResponse["pagination"] = {
@@ -79,7 +79,8 @@ export default function CreateSiteProvisioningKeyCredenza({
.max(1_000_000, {
message: t("provisioningKeysMaxBatchSizeInvalid")
}),
validUntil: z.string().optional()
validUntil: z.string().optional(),
approveNewSites: z.boolean()
})
.superRefine((data, ctx) => {
const v = data.validUntil;
@@ -103,7 +104,8 @@ export default function CreateSiteProvisioningKeyCredenza({
name: "",
unlimitedBatchSize: false,
maxBatchSize: 100,
validUntil: ""
validUntil: "",
approveNewSites: true
}
});
@@ -114,7 +116,8 @@ export default function CreateSiteProvisioningKeyCredenza({
name: "",
unlimitedBatchSize: false,
maxBatchSize: 100,
validUntil: ""
validUntil: "",
approveNewSites: true
});
}
}, [open, form]);
@@ -123,18 +126,21 @@ export default function CreateSiteProvisioningKeyCredenza({
setLoading(true);
try {
const res = await api
.put<
AxiosResponse<CreateSiteProvisioningKeyResponse>
>(`/org/${orgId}/site-provisioning-key`, {
name: data.name,
maxBatchSize: data.unlimitedBatchSize
? null
: data.maxBatchSize,
validUntil:
data.validUntil == null || data.validUntil.trim() === ""
? undefined
: data.validUntil
})
.put<AxiosResponse<CreateSiteProvisioningKeyResponse>>(
`/org/${orgId}/site-provisioning-key`,
{
name: data.name,
maxBatchSize: data.unlimitedBatchSize
? null
: data.maxBatchSize,
validUntil:
data.validUntil == null ||
data.validUntil.trim() === ""
? undefined
: data.validUntil,
approveNewSites: data.approveNewSites
}
)
.catch((e) => {
toast({
variant: "destructive",
@@ -152,9 +158,7 @@ export default function CreateSiteProvisioningKeyCredenza({
}
}
const credential =
created &&
created.siteProvisioningKey;
const credential = created && created.siteProvisioningKey;
const unlimitedBatchSize = form.watch("unlimitedBatchSize");
@@ -213,15 +217,12 @@ export default function CreateSiteProvisioningKeyCredenza({
min={1}
max={1_000_000}
autoComplete="off"
disabled={
unlimitedBatchSize
}
disabled={unlimitedBatchSize}
name={field.name}
ref={field.ref}
onBlur={field.onBlur}
onChange={(e) => {
const v =
e.target.value;
const v = e.target.value;
field.onChange(
v === ""
? 100
@@ -269,9 +270,7 @@ export default function CreateSiteProvisioningKeyCredenza({
const dateTimeValue: DateTimeValue =
(() => {
if (!field.value) return {};
const d = new Date(
field.value
);
const d = new Date(field.value);
if (isNaN(d.getTime()))
return {};
const hours = d
@@ -313,11 +312,7 @@ export default function CreateSiteProvisioningKeyCredenza({
value.date
);
if (value.time) {
const [
h,
m,
s
] =
const [h, m, s] =
value.time.split(
":"
);
@@ -352,6 +347,40 @@ export default function CreateSiteProvisioningKeyCredenza({
);
}}
/>
<FormField
control={form.control}
name="approveNewSites"
render={({ field }) => (
<FormItem className="flex flex-row items-start gap-3 space-y-0">
<FormControl>
<Checkbox
id="provisioning-approve-new-sites"
checked={field.value}
onCheckedChange={(c) =>
field.onChange(
c === true
)
}
/>
</FormControl>
<div className="flex flex-col gap-1">
<FormLabel
htmlFor="provisioning-approve-new-sites"
className="cursor-pointer font-normal !mt-0"
>
{t(
"provisioningKeysApproveNewSites"
)}
</FormLabel>
<FormDescription>
{t(
"provisioningKeysApproveNewSitesDescription"
)}
</FormDescription>
</div>
</FormItem>
)}
/>
</form>
</Form>
)}
@@ -395,4 +424,4 @@ export default function CreateSiteProvisioningKeyCredenza({
</CredenzaContent>
</Credenza>
);
}
}
@@ -45,6 +45,7 @@ export type EditableSiteProvisioningKey = {
name: string;
maxBatchSize: number | null;
validUntil: string | null;
approveNewSites: boolean;
};
type EditSiteProvisioningKeyCredenzaProps = {
@@ -76,7 +77,8 @@ export default function EditSiteProvisioningKeyCredenza({
.max(1_000_000, {
message: t("provisioningKeysMaxBatchSizeInvalid")
}),
validUntil: z.string().optional()
validUntil: z.string().optional(),
approveNewSites: z.boolean()
})
.superRefine((data, ctx) => {
const v = data.validUntil;
@@ -100,7 +102,8 @@ export default function EditSiteProvisioningKeyCredenza({
name: "",
unlimitedBatchSize: false,
maxBatchSize: 100,
validUntil: ""
validUntil: "",
approveNewSites: true
}
});
@@ -112,7 +115,8 @@ export default function EditSiteProvisioningKeyCredenza({
name: provisioningKey.name,
unlimitedBatchSize: provisioningKey.maxBatchSize == null,
maxBatchSize: provisioningKey.maxBatchSize ?? 100,
validUntil: provisioningKey.validUntil ?? ""
validUntil: provisioningKey.validUntil ?? "",
approveNewSites: provisioningKey.approveNewSites
});
}, [open, provisioningKey, form]);
@@ -135,7 +139,8 @@ export default function EditSiteProvisioningKeyCredenza({
data.validUntil == null ||
data.validUntil.trim() === ""
? ""
: data.validUntil
: data.validUntil,
approveNewSites: data.approveNewSites
}
)
.catch((e) => {
@@ -255,6 +260,38 @@ export default function EditSiteProvisioningKeyCredenza({
</FormItem>
)}
/>
<FormField
control={form.control}
name="approveNewSites"
render={({ field }) => (
<FormItem className="flex flex-row items-start gap-3 space-y-0">
<FormControl>
<Checkbox
id="provisioning-edit-approve-new-sites"
checked={field.value}
onCheckedChange={(c) =>
field.onChange(c === true)
}
/>
</FormControl>
<div className="flex flex-col gap-1">
<FormLabel
htmlFor="provisioning-edit-approve-new-sites"
className="cursor-pointer font-normal !mt-0"
>
{t(
"provisioningKeysApproveNewSites"
)}
</FormLabel>
<FormDescription>
{t(
"provisioningKeysApproveNewSitesDescription"
)}
</FormDescription>
</div>
</FormItem>
)}
/>
<FormField
control={form.control}
name="validUntil"
+7
View File
@@ -12,6 +12,8 @@ import clsx from "clsx";
import { useTransition } from "react";
import { Locale } from "@/i18n/config";
import { setUserLocale } from "@/services/locale";
import { createApiClient } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
type Props = {
defaultValue: string;
@@ -25,12 +27,17 @@ export default function LocaleSwitcherSelect({
label
}: Props) {
const [isPending, startTransition] = useTransition();
const api = createApiClient(useEnvContext());
function onChange(value: string) {
const locale = value as Locale;
startTransition(() => {
setUserLocale(locale);
});
// Persist locale to the database (fire-and-forget)
api.post("/user/locale", { locale }).catch(() => {
// Silently ignore errors — cookie is already set as fallback
});
}
const selected = items.find((item) => item.value === defaultValue);
+465
View File
@@ -0,0 +1,465 @@
"use client";
import { Badge } from "@app/components/ui/badge";
import { Button } from "@app/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger
} from "@app/components/ui/dropdown-menu";
import { InfoPopup } from "@app/components/ui/info-popup";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { useNavigationContext } from "@app/hooks/useNavigationContext";
import { getNextSortOrder, getSortDirection } from "@app/lib/sortColumn";
import { toast } from "@app/hooks/useToast";
import { createApiClient, formatAxiosError } from "@app/lib/api";
import { build } from "@server/build";
import { type PaginationState } from "@tanstack/react-table";
import {
ArrowDown01Icon,
ArrowUp10Icon,
ArrowUpRight,
Check,
ChevronsUpDownIcon,
MoreHorizontal
} from "lucide-react";
import { useTranslations } from "next-intl";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { useDebouncedCallback } from "use-debounce";
import z from "zod";
import { ColumnFilterButton } from "./ColumnFilterButton";
import {
ControlledDataTable,
type ExtendedColumnDef
} from "./ui/controlled-data-table";
import { SiteRow } from "./SitesTable";
type PendingSitesTableProps = {
sites: SiteRow[];
pagination: PaginationState;
orgId: string;
rowCount: number;
};
export default function PendingSitesTable({
sites,
orgId,
pagination,
rowCount
}: PendingSitesTableProps) {
const router = useRouter();
const pathname = usePathname();
const {
navigate: filter,
isNavigating: isFiltering,
searchParams
} = useNavigationContext();
const [isRefreshing, startTransition] = useTransition();
const [approvingIds, setApprovingIds] = useState<Set<number>>(new Set());
const api = createApiClient(useEnvContext());
const t = useTranslations();
const booleanSearchFilterSchema = z
.enum(["true", "false"])
.optional()
.catch(undefined);
function handleFilterChange(
column: string,
value: string | undefined | null
) {
const sp = new URLSearchParams(searchParams);
sp.delete(column);
sp.delete("page");
if (value) {
sp.set(column, value);
}
startTransition(() => router.push(`${pathname}?${sp.toString()}`));
}
function refreshData() {
startTransition(async () => {
try {
router.refresh();
} catch (error) {
toast({
title: t("error"),
description: t("refreshError"),
variant: "destructive"
});
}
});
}
async function approveSite(siteId: number) {
setApprovingIds((prev) => new Set(prev).add(siteId));
try {
await api.post(`/site/${siteId}`, { status: "approved" });
toast({
title: t("success"),
description: t("siteApproveSuccess"),
variant: "default"
});
router.refresh();
} catch (e) {
toast({
variant: "destructive",
title: t("siteApproveError"),
description: formatAxiosError(e, t("siteApproveError"))
});
} finally {
setApprovingIds((prev) => {
const next = new Set(prev);
next.delete(siteId);
return next;
});
}
}
const columns: ExtendedColumnDef<SiteRow>[] = [
{
accessorKey: "name",
enableHiding: false,
header: () => {
const nameOrder = getSortDirection("name", searchParams);
const Icon =
nameOrder === "asc"
? ArrowDown01Icon
: nameOrder === "desc"
? ArrowUp10Icon
: ChevronsUpDownIcon;
return (
<Button
variant="ghost"
className="p-3"
onClick={() => toggleSort("name")}
>
{t("name")}
<Icon className="ml-2 h-4 w-4" />
</Button>
);
}
},
{
id: "niceId",
accessorKey: "nice",
friendlyName: t("identifier"),
enableHiding: true,
header: () => {
return <span className="p-3">{t("identifier")}</span>;
},
cell: ({ row }) => {
return <span>{row.original.nice || "-"}</span>;
}
},
{
accessorKey: "online",
friendlyName: t("online"),
header: () => {
return (
<ColumnFilterButton
options={[
{ value: "true", label: t("online") },
{ value: "false", label: t("offline") }
]}
selectedValue={booleanSearchFilterSchema.parse(
searchParams.get("online")
)}
onValueChange={(value) =>
handleFilterChange("online", value)
}
searchPlaceholder={t("searchPlaceholder")}
emptyMessage={t("emptySearchOptions")}
label={t("online")}
className="p-3"
/>
);
},
cell: ({ row }) => {
const originalRow = row.original;
if (
originalRow.type == "newt" ||
originalRow.type == "wireguard"
) {
if (originalRow.online) {
return (
<span className="text-green-500 flex items-center space-x-2">
<div className="w-2 h-2 bg-green-500 rounded-full"></div>
<span>{t("online")}</span>
</span>
);
} else {
return (
<span className="text-neutral-500 flex items-center space-x-2">
<div className="w-2 h-2 bg-gray-500 rounded-full"></div>
<span>{t("offline")}</span>
</span>
);
}
} else {
return <span>-</span>;
}
}
},
// {
// accessorKey: "mbIn",
// friendlyName: t("dataIn"),
// header: () => {
// const dataInOrder = getSortDirection(
// "megabytesIn",
// searchParams
// );
// const Icon =
// dataInOrder === "asc"
// ? ArrowDown01Icon
// : dataInOrder === "desc"
// ? ArrowUp10Icon
// : ChevronsUpDownIcon;
// return (
// <Button
// variant="ghost"
// onClick={() => toggleSort("megabytesIn")}
// >
// {t("dataIn")}
// <Icon className="ml-2 h-4 w-4" />
// </Button>
// );
// }
// },
// {
// accessorKey: "mbOut",
// friendlyName: t("dataOut"),
// header: () => {
// const dataOutOrder = getSortDirection(
// "megabytesOut",
// searchParams
// );
// const Icon =
// dataOutOrder === "asc"
// ? ArrowDown01Icon
// : dataOutOrder === "desc"
// ? ArrowUp10Icon
// : ChevronsUpDownIcon;
// return (
// <Button
// variant="ghost"
// onClick={() => toggleSort("megabytesOut")}
// >
// {t("dataOut")}
// <Icon className="ml-2 h-4 w-4" />
// </Button>
// );
// }
// },
{
accessorKey: "type",
friendlyName: t("type"),
header: () => {
return <span className="p-3">{t("type")}</span>;
},
cell: ({ row }) => {
const originalRow = row.original;
if (originalRow.type === "newt") {
return (
<div className="flex items-center space-x-1">
<Badge variant="secondary">
<div className="flex items-center space-x-1">
<span>Newt</span>
{originalRow.newtVersion && (
<span>v{originalRow.newtVersion}</span>
)}
</div>
</Badge>
{originalRow.newtUpdateAvailable && (
<InfoPopup
info={t("newtUpdateAvailableInfo")}
/>
)}
</div>
);
}
if (originalRow.type === "wireguard") {
return (
<div className="flex items-center space-x-2">
<Badge variant="secondary">WireGuard</Badge>
</div>
);
}
if (originalRow.type === "local") {
return (
<div className="flex items-center space-x-2">
<Badge variant="secondary">Local</Badge>
</div>
);
}
}
},
{
accessorKey: "exitNode",
friendlyName: t("exitNode"),
header: () => {
return <span className="p-3">{t("exitNode")}</span>;
},
cell: ({ row }) => {
const originalRow = row.original;
if (!originalRow.exitNodeName) {
return "-";
}
const isCloudNode =
build == "saas" &&
originalRow.exitNodeName &&
[
"mercury",
"venus",
"earth",
"mars",
"jupiter",
"saturn",
"uranus",
"neptune"
].includes(originalRow.exitNodeName.toLowerCase());
if (isCloudNode) {
const capitalizedName =
originalRow.exitNodeName.charAt(0).toUpperCase() +
originalRow.exitNodeName.slice(1).toLowerCase();
return (
<Badge variant="secondary">
Pangolin {capitalizedName}
</Badge>
);
}
if (originalRow.remoteExitNodeId) {
return (
<Link
href={`/${originalRow.orgId}/settings/remote-exit-nodes/${originalRow.remoteExitNodeId}`}
>
<Button variant="outline">
{originalRow.exitNodeName}
<ArrowUpRight className="ml-2 h-4 w-4" />
</Button>
</Link>
);
}
return <span>{originalRow.exitNodeName}</span>;
}
},
{
accessorKey: "address",
header: () => {
return <span className="p-3">{t("address")}</span>;
},
cell: ({ row }: { row: any }) => {
const originalRow = row.original;
return originalRow.address ? (
<div className="flex items-center space-x-2">
<span>{originalRow.address}</span>
</div>
) : (
"-"
);
}
},
{
id: "actions",
enableHiding: false,
header: () => <span className="p-3"></span>,
cell: ({ row }) => {
const siteRow = row.original;
const isApproving = approvingIds.has(siteRow.id);
return (
<div className="flex items-center gap-2 justify-end">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<Link
className="block w-full"
href={`/${siteRow.orgId}/settings/sites/${siteRow.nice}`}
>
<DropdownMenuItem>
{t("viewSettings")}
</DropdownMenuItem>
</Link>
</DropdownMenuContent>
</DropdownMenu>
<Button
variant="outline"
disabled={isApproving}
onClick={() => approveSite(siteRow.id)}
>
<Check className="mr-2 w-4 h-4" />
{t("approve")}
</Button>
</div>
);
}
}
];
function toggleSort(column: string) {
const newSearch = getNextSortOrder(column, searchParams);
filter({
searchParams: newSearch
});
}
const handlePaginationChange = (newPage: PaginationState) => {
searchParams.set("page", (newPage.pageIndex + 1).toString());
searchParams.set("pageSize", newPage.pageSize.toString());
filter({
searchParams
});
};
const handleSearchChange = useDebouncedCallback((query: string) => {
searchParams.set("query", query);
searchParams.delete("page");
filter({
searchParams
});
}, 300);
return (
<ControlledDataTable
columns={columns}
rows={sites}
tableId="pending-sites-table"
searchPlaceholder={t("searchSitesProgress")}
pagination={pagination}
onPaginationChange={handlePaginationChange}
searchQuery={searchParams.get("query")?.toString()}
onSearch={handleSearchChange}
onRefresh={refreshData}
isRefreshing={isRefreshing || isFiltering}
rowCount={rowCount}
columnVisibility={{
niceId: false,
nice: false,
exitNode: false,
address: false
}}
enableColumnVisibility
stickyLeftColumn="name"
stickyRightColumn="actions"
/>
);
}
@@ -36,6 +36,7 @@ export type SiteProvisioningKeyRow = {
maxBatchSize: number | null;
numUsed: number;
validUntil: string | null;
approveNewSites: boolean;
};
type SiteProvisioningKeysTableProps = {
+25 -1
View File
@@ -2,10 +2,13 @@
import { cookies, headers } from "next/headers";
import { Locale, defaultLocale, locales } from "@/i18n/config";
import { internal } from "@app/lib/api";
import { authCookieHeader } from "@app/lib/api/cookies";
// In this example the locale is read from a cookie. You could alternatively
// also read it from a database, backend service, or any other source.
const COOKIE_NAME = "NEXT_LOCALE";
const COOKIE_MAX_AGE = 365 * 24 * 60 * 60; // 1 year in seconds
export async function getUserLocale(): Promise<Locale> {
const cookieLocale = (await cookies()).get(COOKIE_NAME)?.value;
@@ -14,6 +17,23 @@ export async function getUserLocale(): Promise<Locale> {
return cookieLocale as Locale;
}
// No cookie found — try to restore from user's saved locale in DB
try {
const res = await internal.get("/user", await authCookieHeader());
const userLocale = res.data?.data?.locale;
if (userLocale && locales.includes(userLocale as Locale)) {
// Set the cookie so subsequent requests don't need the API call
(await cookies()).set(COOKIE_NAME, userLocale, {
maxAge: COOKIE_MAX_AGE,
path: "/",
sameSite: "lax"
});
return userLocale as Locale;
}
} catch {
// User not logged in or API unavailable — fall through
}
const headerList = await headers();
const acceptLang = headerList.get("accept-language");
@@ -33,5 +53,9 @@ export async function getUserLocale(): Promise<Locale> {
}
export async function setUserLocale(locale: Locale) {
(await cookies()).set(COOKIE_NAME, locale);
(await cookies()).set(COOKIE_NAME, locale, {
maxAge: COOKIE_MAX_AGE,
path: "/",
sameSite: "lax"
});
}