mirror of
https://github.com/luckjiawei/podux.git
synced 2026-11-30 05:06:47 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
de7546a946 |
No files matched your search
@@ -1,91 +0,0 @@
|
||||
# Podux Agent Development Guide
|
||||
|
||||
## Project Scope and Technology Stack
|
||||
|
||||
Podux is a web management platform for centrally managing frpc server configurations, proxies, connection status, network latency, and runtime logs. The current codebase uses Go 1.25.5, PocketBase 0.35.0, and embedded frp 0.68.0. The application frontend is under `site/` and uses React 19, TypeScript 5.9, Vite 7, Radix Themes 3, and Tailwind CSS 4. `docs/` is a VitePress 1 documentation site; its Vue dependency does not mean that the application frontend uses Vue.
|
||||
|
||||
Treat `go.mod`, `site/package.json`, and `docs/package.json` as the sources of truth for versions and dependencies. Do not infer versions from documentation examples.
|
||||
|
||||
## Directory Map
|
||||
|
||||
| Path | Responsibility |
|
||||
| --- | --- |
|
||||
| `main.go` | PocketBase startup and dependency wiring, hooks/custom routes, monitoring scheduler, and static asset serving entry point |
|
||||
| `internal/domain/` | Server/proxy domain models and repository interfaces |
|
||||
| `internal/application/` | Use-case services for dashboard, frpc, importer, monitoring, proxy, server, system, version, and related features |
|
||||
| `internal/infrastructure/persistence/` | Repository implementations based on PocketBase/dbx |
|
||||
| `internal/interfaces/http/` | Custom HTTP handlers and authentication middleware |
|
||||
| `migrations/` | The sole version-controlled source of truth for PocketBase collection schemas |
|
||||
| `pkg/` | Build information, responses, shared types, and utilities |
|
||||
| `site/` | React application frontend; calls both the PocketBase collection API and custom `/api/*` endpoints |
|
||||
| `docs/` | Independent VitePress documentation site |
|
||||
| `development/` | Development design documents for agents and maintainers; not part of the web documentation site |
|
||||
| `pb_public/` | Copy destination for `site/dist`; embedded into the Go binary by `main.go` via `go:embed`; not committed |
|
||||
| `pb_data/` | PocketBase SQLite data, uploads, and `frpc/<server-id>` runtime logs/certificates; not committed |
|
||||
| `build/`, `deploy/` | Multi-platform build scripts and Docker deployment files |
|
||||
|
||||
See the [development design documentation](development/README.md) for the full design index.
|
||||
|
||||
## Local Development and Verification
|
||||
|
||||
Prerequisites: Go 1.25.5 as required by `go.mod`, Node.js 20 (CI baseline), and pnpm 10 (CI baseline).
|
||||
|
||||
```bash
|
||||
# Backend (ensure pb_public/index.html exists first; see the full frontend build below)
|
||||
go run . serve
|
||||
|
||||
# Application frontend; Vite proxies /api to 127.0.0.1:8090
|
||||
pnpm --dir site install --frozen-lockfile
|
||||
pnpm --dir site run dev
|
||||
|
||||
# Documentation site
|
||||
pnpm --dir docs install --frozen-lockfile
|
||||
pnpm --dir docs run docs:dev
|
||||
```
|
||||
|
||||
Run before submitting:
|
||||
|
||||
```bash
|
||||
pnpm --dir site install --frozen-lockfile
|
||||
pnpm --dir site run lint
|
||||
pnpm --dir site run build
|
||||
pnpm --dir docs install --frozen-lockfile
|
||||
pnpm --dir docs run docs:build
|
||||
|
||||
# go:embed must be satisfied before Go tooling loads the main package
|
||||
rm -rf pb_public
|
||||
mkdir -p pb_public
|
||||
cp -R site/dist/. pb_public/
|
||||
go vet ./...
|
||||
go test ./...
|
||||
go build ./...
|
||||
```
|
||||
|
||||
`build/build.sh` builds the frontend, copies `site/dist` to `pb_public`, runs `go mod tidy`, and builds platform packages. It rewrites generated directories and may modify module files, so it is not the preferred verification command for documentation-only or narrowly scoped changes.
|
||||
|
||||
## Change Conventions
|
||||
|
||||
- Backend: preserve the `interfaces -> application -> domain` dependency direction. Infrastructure implements domain repositories, and `main.go` performs central wiring. Handlers own transport-level validation and responses; business orchestration belongs in application services.
|
||||
- Frontend: keep React + TypeScript and follow the existing split between `index.tsx` (state/orchestration) and `*.view.tsx` (presentation). Prefer components from `site/src/components/` and Radix Themes. Reuse `site/src/lib/api.ts` or `pocketbase.ts` for API requests.
|
||||
- Migrations: schema changes must add a reviewable, reversible `migrations/*.go` migration. Migrations are the source of truth; never replace one by modifying a live SQLite database or production schema through the admin UI.
|
||||
- API: place custom routes in `internal/interfaces/http/` and use `requireAuth` by default. Review PocketBase collection rules as well. When paths, request/response contracts, authentication, or collection fields change, update the relevant design documents.
|
||||
- Styling: follow the [UI specification](development/ui-spec.md). Prefer Radix tokens, component props, and Tailwind utilities; do not introduce another unsupported set of brand tokens.
|
||||
- Internationalization: update both `site/src/locales/zh.json` and `en.json` for user-visible text, and access it through `react-i18next`'s `t()`. Avoid new hard-coded strings.
|
||||
- Documentation: implementation changes must update the [architecture](development/architecture.md), [database design](development/database-design.md), or [UI specification](development/ui-spec.md) when applicable. Documentation claims must link to repository paths or be marked "To be confirmed."
|
||||
|
||||
## Security Boundaries
|
||||
|
||||
- Do not commit secrets, tokens, certificates, user data, `pb_data/`, `pb_public/`, `site/dist/`, `docs/.vitepress/dist/`, or build packages.
|
||||
- `fh_servers.auth`, TLS private keys, user passwords, and token keys are sensitive. Never log their original values. Avoid logging, copying, or exposing tokens used in SSE query parameters.
|
||||
- Do not substitute manual database operations for migrations. Relations currently have no cascading deletes; assess orphaned-data risks before deleting parent records.
|
||||
- Do not perform unrelated repository-wide formatting or overwrite existing worktree changes.
|
||||
- Changes to endpoints, authentication rules, or data structures must update tests, callers, and the design documents in this directory.
|
||||
|
||||
## Pre-Submission Checklist
|
||||
|
||||
- [ ] `git diff` contains only the intended scope, with no runtime data, build artifacts, or unrelated formatting.
|
||||
- [ ] Go vet/test/build, frontend lint/build, and documentation build were run and their results reported accurately.
|
||||
- [ ] New or changed APIs, collections, relations, and rules are reflected in the database/architecture documentation.
|
||||
- [ ] The UI reuses shared components; both themes, the 760px mobile layout, Chinese/English text, and basic keyboard operation were checked.
|
||||
- [ ] Relative Markdown links work, and Mermaid names match the code and render correctly.
|
||||
- [ ] No sensitive values appear in code, logs, screenshots, or commit history.
|
||||
@@ -61,13 +61,6 @@
|
||||
- 2026-03-12: Released v0.1.1
|
||||
- 2026-03-12: Released v0.1.2
|
||||
- 2026-03-16: Released v0.1.3
|
||||
- 2026-03-25: Released v0.1.4
|
||||
- 2026-03-26: Released v0.1.5
|
||||
- 2026-03-31: Released v0.1.6
|
||||
|
||||
## License
|
||||
|
||||
[Apache 2.0](LICENSE)
|
||||
|
||||
## Star History
|
||||
|
||||
|
||||
@@ -61,13 +61,6 @@
|
||||
- 2026-03-12: 发布 v0.1.1
|
||||
- 2026-03-14: 发布 v0.1.2
|
||||
- 2026-03-16: 发布 v0.1.3
|
||||
- 2026-03-25: 发布 v0.1.4
|
||||
- 2026-03-26: 发布 v0.1.5
|
||||
- 2026-03-31: 发布 v0.1.6
|
||||
|
||||
## License
|
||||
|
||||
[Apache 2.0](LICENSE)
|
||||
|
||||
## Star 历史
|
||||
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
# Podux Development Design Documentation
|
||||
|
||||
This directory documents the verifiable design of the current `main` baseline and serves as the entry point for future development and agent changes:
|
||||
|
||||
- [System architecture](architecture.md): in-process components, layering, request/startup flows, build and deployment, and CI boundaries.
|
||||
- [Database design](database-design.md): all application collections, relations, rules, indexes, lifecycles, and implementation discrepancies.
|
||||
- [UI specification](ui-spec.md): themes, actual tokens, layouts, and component reuse rules for the React application frontend.
|
||||
|
||||
## Sources of Truth and Scope
|
||||
|
||||
These documents are based on repository code and configuration, not speculation about a target architecture. For the database, `migrations/*.go` is the primary source of truth and is cross-checked against domain models, repositories, application services, HTTP handlers, and callers under `site/src/`. For the UI, the sources are `site/src/index.css`, theme contexts, layouts, shared components, and pages. Build and deployment facts come from `go.mod`, package manifests, `main.go`, CI, `build/build.sh`, and Docker files.
|
||||
|
||||
"Verified current state" describes the present implementation. "Current discrepancy / To be confirmed" and "Technical debt" identify gaps that the code cannot resolve or constraints that are not yet unified; they do not authorize schema or behavior changes.
|
||||
|
||||
## Update Triggers
|
||||
|
||||
- Update the architecture document when component boundaries, startup flow, custom routes, background tasks, persistence, or deployment change.
|
||||
- Update the database document when migrations, collection rules/indexes/relations, field mappings, or retention/deletion policies change.
|
||||
- Update the UI document when theme configuration, design tokens, layout breakpoints, shared components, interaction states, internationalization, or accessibility constraints change.
|
||||
- Update the repository-root `AGENT.md` when any of the changes above also affect agent working conventions.
|
||||
@@ -1,97 +0,0 @@
|
||||
# System Architecture
|
||||
|
||||
## Verified Current State
|
||||
|
||||
Podux is a single Go/PocketBase service that hosts the API, SQLite persistence, background monitoring, frpc client services, and the React static site. The code calls running instances `processes`, but `internal/application/frpc/service.go` actually creates in-process `frp/client.Service` instances and runs them in goroutines; it does not launch separate `frpc` OS processes.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
B[Browser / React Web<br/>site/src] -->|PocketBase collection API| PB[PocketBase / Go<br/>main.go]
|
||||
B -->|custom /api routes| H[HTTP handlers<br/>internal/interfaces/http]
|
||||
H --> A[Application services<br/>internal/application]
|
||||
PB --> H
|
||||
A --> D[Domain contracts/models<br/>internal/domain]
|
||||
A --> R[Repository implementations<br/>internal/infrastructure/persistence]
|
||||
R --> DB[(SQLite / PocketBase collections<br/>pb_data)]
|
||||
PB --> DB
|
||||
A --> F[frp client.Service instances<br/>in-process goroutines]
|
||||
F --> FRPS[Remote frps servers]
|
||||
A --> M[MonitorService + MetricsScheduler]
|
||||
M --> DB
|
||||
PB --> E[Embedded React assets<br/>pb_public]
|
||||
```
|
||||
|
||||
### Layers and Entry Points
|
||||
|
||||
- `main.go` creates the PocketBase app, registers migration commands, constructs repositories/services/handlers, binds the `fh_proxies` update hook, and initializes state, starts background tasks, registers routes, and configures the static-file fallback in `OnServe`.
|
||||
- `internal/domain` currently defines lightweight models, status values, and repository interfaces only for servers and proxies.
|
||||
- `internal/application` handles statistics, imports, frpc configuration/lifecycle, networking and metrics, system settings, and version queries.
|
||||
- `internal/infrastructure/persistence` implements server and proxy repositories with dbx/PocketBase.
|
||||
- `internal/interfaces/http` exposes `/api/dashboard/*`, `/api/frpc/*`, `/api/import/*`, `/api/servers*`, `/api/system/*`, and `/api/frp/version`. Except for initialization-status and initialization endpoints, registered custom routes use `requireAuth`.
|
||||
- React also uses the PocketBase SDK directly for `fh_users`, `fh_servers`, and `fh_proxies`; collection API rules control that access boundary.
|
||||
|
||||
### Typical Request Flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as React Servers page
|
||||
participant H as FrpcHandler
|
||||
participant S as frpc.Service
|
||||
participant R as server/proxy repositories
|
||||
participant DB as PocketBase/SQLite
|
||||
participant C as frp client.Service
|
||||
UI->>H: POST /api/frpc/launch {id}
|
||||
H->>H: requireAuth + 15-char id validation
|
||||
H->>S: LaunchFrpc(id)
|
||||
S->>DB: load fh_servers
|
||||
S->>R: FindEnabledByServerID(id)
|
||||
R->>DB: query fh_proxies
|
||||
S->>C: NewService + Run(ctx)
|
||||
S->>R: bootStatus = running
|
||||
H-->>UI: 200 / error
|
||||
loop every 5 seconds
|
||||
S->>C: StatusExporter
|
||||
S->>R: proxy bootStatus online/offline
|
||||
end
|
||||
```
|
||||
|
||||
Standard server/proxy CRUD primarily uses the PocketBase SDK. Server lists, dashboard data, imports, settings, and runtime controls use custom APIs. After a successful `fh_proxies` update, a hook calls `ReloadFrpc` if the owning server is running.
|
||||
|
||||
### Startup Flow and Background Tasks
|
||||
|
||||
1. Go `init` loads `migrations`; `main` registers the migrate command and wires dependencies.
|
||||
2. PocketBase `serve` triggers `OnServe`, which sets every server to `stopped` and every proxy to `offline`.
|
||||
3. After a 10-second delay, servers with `autoConnection=true` start automatically.
|
||||
4. `MonitorService` immediately runs TCP latency and missing-geolocation checks, then repeats them at intervals from `fh_settings.general`; server-side defaults are 5 seconds and 24 hours.
|
||||
5. PocketBase cron aggregates raw metrics into hourly metrics at minute 5 of every hour. At 01:05 each day it aggregates daily metrics and deletes raw data older than 7 days and hourly data older than 30 days.
|
||||
6. After handlers are registered, `pb_public` is served through `embed.FS` with an SPA fallback; `/_/` remains the PocketBase Admin UI.
|
||||
|
||||
### Frontend Build and Embedding
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
SRC[site/src React + TypeScript] -->|pnpm run build| DIST[site/dist]
|
||||
DIST -->|build/build.sh copy| PUBLIC[pb_public]
|
||||
PUBLIC -->|go:embed all:pb_public| BIN[Podux Go binary]
|
||||
BIN -->|apis.Static fallback| WEB[Browser]
|
||||
```
|
||||
|
||||
The Vite development server listens on `0.0.0.0` and proxies `/api` to `127.0.0.1:8090`. Production builds do not automatically copy files to `pb_public`; CI performs that step through artifact downloads, while `build/build.sh` copies them explicitly. Go compilation still requires the directory to exist when `pb_public/index.html` is missing, and runtime logs a warning.
|
||||
|
||||
## Configuration, Persistence, and Deployment Boundaries
|
||||
|
||||
- PocketBase uses `pb_data/` as its default data root; the Docker volume mounts `/app/pb_data`. The database, uploads, and `pb_data/frpc/<id>/logs|certs` are runtime data.
|
||||
- Server connection/authentication/transport/logging/metadata settings are stored in collection JSON fields. TLS certificate contents are written to a server-specific certificates directory at startup, with private-key permissions set to `0600`. Never commit this content.
|
||||
- The fixed system-settings record ID is `wcstsqmz8hur331`; the initialization transaction creates both the first `fh_users` record and the settings record.
|
||||
- Geolocation and version queries access external services and depend on network availability. frpc instance status exists only in memory; database statuses are reset together on restart.
|
||||
- The Dockerfile builds React and then compiles a static Go binary; deployment files define ports and volumes. This document makes no claims about production reverse proxies, backups, or high availability that are not verified in repository configuration.
|
||||
|
||||
## CI and Quality Boundaries
|
||||
|
||||
`.github/workflows/ci.yml` runs on pushes to main/dev and pull requests to main. It performs a frozen frontend install, permissive type checking (`continue-on-error`), and a production build; it then downloads the frontend artifact and runs `go vet` and a Linux amd64 build. CI currently does not run `go test`, frontend lint, or the documentation build, but this project's pre-submission baseline requires those checks locally. Pushes to dev also build and publish a multi-architecture container.
|
||||
|
||||
## To Be Confirmed
|
||||
|
||||
- `github_handler.go` and its service exist, but their wiring and registration are commented out in `main.go`; they must not be treated as a published API.
|
||||
- No graceful-shutdown hook for `MonitorService` was found; it currently relies on process termination.
|
||||
- No formal repository-level backup/restore, horizontal-scaling, or multi-instance mutual-exclusion design was found.
|
||||
@@ -1,121 +0,0 @@
|
||||
# Database Design
|
||||
|
||||
## Sources of Truth and Migration Constraints
|
||||
|
||||
PocketBase uses SQLite and registers Go migrations through the blank import of `migrations` in `main.go`; `migratecmd` enables `Automigrate: true`. The only current migration is `migrations/1774402980_collections_snapshot.go`, which imports a collection snapshot with `ImportCollectionsByMarshaledJSON(..., false)`; its rollback function is currently empty. The migration, not any running `pb_data/data.db`, is therefore the primary schema source of truth.
|
||||
|
||||
Every structure/rule/index change must add a reviewable migration with an appropriate rollback. Never modify production SQLite directly or make changes only through the PocketBase Admin UI. "Default" below records only snapshot autogeneration behavior; fields without an explicit statement have no verified schema default.
|
||||
|
||||
The snapshot also contains PocketBase system collections such as `_mfas`, `_otps`, `_externalAuths`, `_authOrigins`, and `_superusers`, which are not individually modeled here. There are nine application collections: `fh_users`, `fh_servers`, `fh_proxies`, `fh_version`, `fh_settings`, `fh_metrics_targets`, `fh_metrics_raw`, `fh_metrics_hourly`, and `fh_metrics_daily`.
|
||||
|
||||
Every base collection has a required system text primary key named `id`, automatically generated as 15 lowercase alphanumeric characters. Collections with `created`/`updated` use autodate fields. In the descriptions below, `—` means an empty rule, so only a superuser may perform that operation through the PocketBase Record API; this does not restrict internal server-side database/service access.
|
||||
|
||||
## Relationship Diagram
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
fh_servers ||--o{ fh_proxies : "serverId (no cascade)"
|
||||
fh_servers ||--o{ fh_metrics_targets : "serverId (optional, no cascade)"
|
||||
fh_proxies ||--o{ fh_metrics_targets : "proxyId (optional, no cascade)"
|
||||
fh_metrics_targets ||--o{ fh_metrics_raw : "targetId (no cascade)"
|
||||
fh_metrics_targets ||--o{ fh_metrics_hourly : "targetId (no cascade)"
|
||||
fh_metrics_targets ||--o{ fh_metrics_daily : "targetId (no cascade)"
|
||||
```
|
||||
|
||||
All relation fields use `maxSelect: 1`. The schema neither guarantees that each metrics target is bound exclusively to a server or a proxy nor defines a unique `(serverId, proxyId)` index.
|
||||
|
||||
## Collection Design
|
||||
|
||||
### `fh_users` (auth)
|
||||
|
||||
Purpose: Podux login users. System fields: `password` (required, hidden, minimum 8 characters), `tokenKey` (required, hidden, 30–60 characters, automatically generated with 50 characters), `email` (required), `emailVisibility`, `verified`, `created`, and `updated`. Application fields: optional `nickname` text with max length 255; optional `avatar` file with at most one JPEG/PNG/SVG/GIF/WebP file; optional `passwordChangedAt` date.
|
||||
|
||||
Unique indexes: `tokenKey` and non-empty `email`. Password authentication is enabled with email as the identity; OAuth2, MFA, and OTP are disabled. The create rule is `@collection.fh_settings.initialized = false`; list/view/update/delete are restricted to `id = @request.auth.id`; the auth rule is empty, allowing authentication.
|
||||
|
||||
Mapping: `system.Service.InitializeSystem` creates the user; Login uses PocketBase `authWithPassword`; Settings/Profile reads and updates the user and avatar; ChangePasswordDialog updates the password.
|
||||
|
||||
### `fh_servers`
|
||||
|
||||
Purpose: remote frps connections and shared frpc configuration.
|
||||
|
||||
| Field | Type | Required/default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `serverName` | text | Required | Display name |
|
||||
| `serverAddr` | text | Required | frps address |
|
||||
| `serverPort` | text | Required | Read/edited as an integer by the service/frontend |
|
||||
| `description` | text | Optional | Description |
|
||||
| `auth` | json | Optional | frp authentication; may contain tokens/secrets |
|
||||
| `transport` | json | Optional | frp transport/TLS; may contain certificate private keys |
|
||||
| `metadatas` | json | Optional | frp metadata |
|
||||
| `log` | json | Optional | frp logging configuration |
|
||||
| `serverVersion` | text | Required, auto `built-in` | Current frp source marker |
|
||||
| `bootStatus` | text | Required, auto `stopped` | Runtime status; code uses running/stopped |
|
||||
| `autoConnection` | bool | Optional | Connect automatically after startup |
|
||||
| `geoLocation` | json | Optional | Populated by MonitorService |
|
||||
| `user` | text | Optional | frp user |
|
||||
| `created`,`updated` | autodate | Automatic | Creation/update timestamps |
|
||||
|
||||
Index: non-unique `bootStatus`. All list/view/create/update/delete rules require authentication. Mapping: there is no complete Go domain model; `ServerRecord` covers only ID/name. The server repository, frpc service, monitor service, and custom `/api/servers` handler read it; React Servers, ServerDetail, and ServerForm use it.
|
||||
|
||||
### `fh_proxies`
|
||||
|
||||
Purpose: frpc proxy configuration under a server.
|
||||
|
||||
| Field | Type | Required/default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `name` | text | Required | Proxy name; the record ID is appended to the runtime name |
|
||||
| `proxyType` | select | Required | One of tcp, udp, http, or https |
|
||||
| `serverId` | relation -> `fh_servers` | Required, N:1 | No cascading delete |
|
||||
| `localIP`,`localPort`,`remotePort`,`subdomain` | text | Optional | Endpoint configuration; Go maps ports with NullableInt |
|
||||
| `customDomains` | json | Optional | Domain array |
|
||||
| `transport`,`plugin` | json | Optional | Extended proxy configuration |
|
||||
| `status` | select | Required | enabled/disabled |
|
||||
| `bootStatus` | select | Required | online/offline |
|
||||
| `created`,`updated` | autodate | Automatic | Creation/update timestamps |
|
||||
|
||||
Indexes: non-unique `serverId`, `proxyType`, and `status`. All CRUD/list/view rules require authentication. Mapping: `domain/proxy.Proxy`, the proxy repository/service, frpc configuration generation, and dashboard; used by React Proxies, ProxyForm, and ServerDetail. A successful update hook reloads a running server.
|
||||
|
||||
### `fh_settings`
|
||||
|
||||
Purpose: system initialization state and general settings. Fields are optional `initialized` bool, optional `general` JSON, and autodate `created`/`updated`; there are no application indexes. All list/view/create/update/delete rules require authentication, but the unauthenticated custom initialization API writes the fixed ID `wcstsqmz8hur331` inside a server-side transaction. Used `general` keys include `defaultLanguage`, `latencyCheckInterval`, and `locationCheckInterval`.
|
||||
|
||||
Mapping: `application/system.Service`, the system handler, React GeneralSettings, and the initialization flow.
|
||||
|
||||
### `fh_version`
|
||||
|
||||
Purpose: version name/path records. Optional text fields `version_name` and `version_path`, plus `created`/`updated`. It has no application indexes, and all Record API rules are `null`. The current version service returns the frp version from compile-time dependencies, while the system version uses buildinfo/an external release API. No application read/write path for this collection was found; its actual purpose remains to be confirmed.
|
||||
|
||||
### `fh_metrics_targets`
|
||||
|
||||
Purpose: bind a metric series to a server or proxy. `serverId` is an optional relation to `fh_servers`; `proxyId` is an optional relation to `fh_proxies`; neither cascades on deletion. There are no `created`/`updated` fields or indexes, and all Record API rules are `null`. `MetricsService` currently creates only targets with a populated `serverId` and empty `proxyId`, and caches server-to-target mappings in memory.
|
||||
|
||||
### `fh_metrics_raw`
|
||||
|
||||
Purpose: raw metric points. Required non-cascading `targetId` relation to `fh_metrics_targets`; optional `metricKey` select (currently only `frps_delay`); required `t` date; optional `val` number. The composite non-unique index is ordered `(targetId, t, metricKey)`. There are no autodate fields, and all Record API rules are `null`. MonitorService writes non-negative latency for reachable servers; the 01:05 daily job deletes data older than 7 days.
|
||||
|
||||
### `fh_metrics_hourly`
|
||||
|
||||
Purpose: hourly aggregates. Optional relation `targetId`, optional select `metricKey`, optional date `t`, and optional numbers `valAvg`/`valMax`/`valMin`. It has a composite non-unique `(metricKey, targetId, t)` index, no autodate fields, and `null` for all Record API rules. At minute 5 of every hour, the previous complete hour is aggregated and then updated or inserted after lookup by target/key/time. Data older than 30 days is deleted daily.
|
||||
|
||||
### `fh_metrics_daily`
|
||||
|
||||
Purpose: daily aggregates. Fields match hourly, and all three value fields are optional numbers. It has a composite non-unique `(targetId, metricKey, t)` index, no autodate fields, and `null` for all Record API rules. At 01:05 daily, the previous day's hourly values are aggregated and upserted; the code currently writes only `valAvg`. No retention policy for daily data was found.
|
||||
|
||||
## Lifecycle, Deletion, and Sensitivity
|
||||
|
||||
- Server/proxy runtime statuses are reset at startup. Status is a transient runtime projection; configuration itself is persistent.
|
||||
- Aggregation follows raw -> hourly -> daily. Raw data is retained for 7 days and hourly data for 30 days; no verified limit exists for daily data.
|
||||
- Every relation uses `cascadeDelete: false`. The schema does not automatically delete proxies/metrics targets with a server, and deleting proxies/targets may also leave related records. Although the UI shows a confirmation dialog, no server-side transactional cleanup was found; treat this as an orphaning risk.
|
||||
- PocketBase protects `fh_users.password/tokenKey`; `fh_servers.auth/transport` may contain tokens, OIDC secrets, and TLS private keys. Logs mask common JSON key names, but original values must still never be exported, committed, or echoed.
|
||||
- Migration workflow: identify callers -> add forward/down migrations -> update models/repositories/services/UI -> update this document -> verify upgrade and rollback against a temporary database -> run the full checks. Never rewrite the snapshot to falsify existing deployment history.
|
||||
|
||||
## Current Discrepancies / To Be Confirmed
|
||||
|
||||
- `domain/proxy.Proxy` declares and serializes `description`, but the `fh_proxies` migration has no such field; form payloads also include description. Do not assume here that the field exists.
|
||||
- The `/api/servers` handler reads and returns `sendRate` and `recvRate`, but the migration defines neither field.
|
||||
- ProfileSettings submits both `name` and `nickname`, while the migration defines only `nickname`.
|
||||
- The migration defines `serverPort/localPort/remotePort` as text; some Go/frontend paths treat them as numbers. Preserve conversion compatibility and confirm the long-term type strategy.
|
||||
- `fh_metrics_targets` has no uniqueness constraint. An in-process application lock only prevents concurrent duplicates within one process; multi-instance and pre-existing duplicate risks remain to be confirmed.
|
||||
- Metric aggregation performs application-level "lookup then write" operations. Composite indexes are non-unique, so the database does not guarantee idempotent uniqueness.
|
||||
- No caller for `fh_version` was found; its purpose remains to be confirmed.
|
||||
- The snapshot migration has an empty down function and cannot automatically restore the pre-import schema; rollback strategy remains technical debt.
|
||||
@@ -1,67 +0,0 @@
|
||||
# UI Specification
|
||||
|
||||
## Technology Stack, Entry Point, and Theme
|
||||
|
||||
The application UI under `site/` uses React 19, TypeScript, and Vite 7 together with Radix Themes, Tailwind CSS 4, Iconify, Framer Motion, Recharts, Sonner, and react-i18next; it does not use Vue. Vue is used only by the VitePress site under `docs/`.
|
||||
|
||||
`site/src/main.tsx` loads Radix CSS, `index.css`, and i18n in that order, then wraps the application in `ThemeProvider`, `LanguageProvider`, and Radix `<Theme>`. Theme settings are `accentColor="indigo"`, `grayColor="slate"`, and `radius="large"`. Appearance is light/dark, initially taken from the system `prefers-color-scheme` and then stored in `localStorage.theme`. `index.css` is the entry point for Tailwind and global status-dot styles. `App.css` is an unused Vite template remnant not imported by `App.tsx`; do not treat it as the current UI baseline.
|
||||
|
||||
## Design Tokens in Use
|
||||
|
||||
The project has no custom token file. It primarily consumes Radix CSS variables and component size/gap scales directly.
|
||||
|
||||
| Category | Verified values/usage |
|
||||
| --- | --- |
|
||||
| Brand/accent | Radix indigo mappings `--accent-2/3/4/6/9/10/11` and `--accent-a3`; do not hard-code a new "Podux blue" |
|
||||
| Neutrals/surfaces | Slate mappings `--gray-1..12`, alpha gray, `--color-background`, and `--color-panel-solid`; main page background is `--gray-2` |
|
||||
| Status colors | Radix green/red/amber/orange/blue/purple scales; online dot `--green-9`, offline dot `--red-9`, unknown dot `--gray-9` |
|
||||
| Typography | No project font family; inherits Radix/browser. Body text commonly uses `<Text size="1|2|3|4">`, page titles use `<Heading size="6">`, and section titles commonly use size 3/4 |
|
||||
| Spacing | Prefer Radix `gap/mb/px/py` scales and Tailwind (for example px-4, sm:px-6, lg:px-8); local values commonly include 8/12/16/20/24/32px |
|
||||
| Radius | Radix global `large`; variables `--radius-2/3`; local 8/12/16/24px and full circles |
|
||||
| Borders | Usually `1px solid var(--gray-5|6)`; highlighted areas use `--accent-6` |
|
||||
| Shadows | A few local `0 4px 12px rgba(0,0,0,.05/.2)` and `0 4px 16px rgba(0,0,0,.1)` values; prefer Card/Dialog defaults |
|
||||
| Stacking | Sticky top bar uses `z-50`; full-screen Loading uses `z-index: 9999`; otherwise prefer component overlay defaults |
|
||||
|
||||
Hard-coded values such as `#22c55e`, `#E5484D`, `#30A46C`, and `#6b7280` remain scattered through charts/status implementations. Prefer existing Radix tokens. Cleanup requires a separate task that verifies SVG chart compatibility; do not replace these values in bulk during ordinary feature work.
|
||||
|
||||
## Layout and Component Patterns
|
||||
|
||||
- Application shell: reuse `layouts/MainLayout.tsx`. Desktop uses a sticky top bar with logo, Dashboard/Servers/Proxies navigation, and controls on the right. Below `760px`, mobile uses bottom navigation. Content uses `max-w-7xl`, supports a minimum viewport width of 320px, and reserves space for the mobile bottom bar.
|
||||
- Page titles: reuse `components/PageHeader.tsx`, keeping title, description, and right-side actions at a consistent hierarchy. Reuse `SectionHeading` for section titles.
|
||||
- Forms: prefer Radix `TextField/Select/Switch/Button`; reuse `FormItem` for labels and required markers. Keep page state and submission logic in hooks/index files and layout in views.
|
||||
- Cards and statistics: use Radix `Card` for general content. Reuse `StatCard` and `AnimateNumber` for dashboard value cards rather than duplicating animation/color decisions.
|
||||
- Lists: Servers/Proxies establish the desktop-table + mobile-card, search, pagination, Badge, and DropdownMenu pattern. Prefer it for new resources of the same kind.
|
||||
- Dialogs: use Radix `AlertDialog` for delete confirmation and Radix `Dialog` for editing, passwords, and similar tasks. Mark dangerous actions red, separate cancel and confirm, and prevent duplicate submissions during async work.
|
||||
- Charts: reuse `LatencyChart/ProbeHistory` for latency trends and Dashboard `TopologyChart` for topology. Containers must be responsive, with sufficient contrast in both themes.
|
||||
- Notifications: prefer `sonner` toast for operation success/failure (global top-center with richColors). Do not add alerts; the existing `alert` in ProfileSettings is technical debt.
|
||||
- Empty/loading/error: reuse `EmptyState` for empty lists and `Loading` for route/page loading. Errors should explain the problem and offer a recovery action. There is no unified ErrorState/ErrorBoundary yet; before adding one, assess whether it should become a shared component.
|
||||
|
||||
## Reference Pages
|
||||
|
||||
- Dashboard: `site/src/pages/Dashboard/DashboardPage.view.tsx` combines `PageHeader`, `StatCard`, Radix Grid/Card, and `TopologyChart`; data orchestration is in `useDashboard.ts`.
|
||||
- Servers/Proxies: `site/src/pages/Servers/ServersPage.view.tsx` and `site/src/pages/Proxies/ProxiesPage.view.tsx` are the primary references for responsive lists, status badges, action menus, and AlertDialog. Their forms are under the corresponding `*FormPage` directories.
|
||||
- Settings: `site/src/pages/Settings/SettingsPage.view.tsx` and `SettingsPage.css` use a 240px sidebar, active accent state, and content area. `GeneralSettings.tsx` demonstrates `FormItem`, loading, and save toast; `ProfileSettings.tsx` demonstrates profile cards and security sections.
|
||||
|
||||
## Responsiveness, Themes, Internationalization, and Accessibility
|
||||
|
||||
- Responsiveness: the actual application-shell breakpoint is `max-width: 760px` (the 640px comment is stale). Test at least 320px mobile and desktop widths. On mobile, table content must use cards or controlled scrolling and must not require hover for actions.
|
||||
- Themes: new colors should use `var(--accent-*)`, `var(--gray-*)`, and semantic colors. Avoid fixed white backgrounds/black text. Check charts, overlays, borders, and focus states in light and dark themes.
|
||||
- Internationalization: route all user-facing text through `t()` and update both `locales/zh.json` and `en.json`. LanguageContext/localStorage owns language selection; do not use hard-coded Chinese or English as fallback UI.
|
||||
- Accessibility: use semantic Radix components. Icon-only buttons need accessible names/tooltips; images need alt text; form labels must associate with controls; keyboard focus must remain visible. `index.css` currently forces the Recharts surface outline off and must be limited to non-interactive charts; reassess it if keyboard chart interaction is added.
|
||||
- Motion: the standard page transition is `PageTransition` at 0.3s cubic-bezier; titles use 0.5s easeOut; status dots loop every 1.6–2.5s. Lightweight hover/tap effects are acceptable but must not block interaction. Only the unused Vite-template `App.css` currently observes `prefers-reduced-motion`; actual Framer/status-dot animations do not support it consistently and remain technical debt.
|
||||
|
||||
## Reuse and Addition Rules
|
||||
|
||||
1. Check Radix Themes first, then `site/src/components/`, then neighboring page view/hook patterns.
|
||||
2. Extract a shared component only when a semantically stable pattern spans at least two pages; keep page-specific compositions in the page directory.
|
||||
3. New shared components must use tokens, support `className` and necessary props, cover loading/disabled/error states, and be verified in both themes and mobile layouts.
|
||||
4. Local styles are acceptable for third-party charts, complex layouts, or states difficult to express with Radix props/Tailwind. Scope names to the page/component and avoid global selectors and `!important`. Existing `!important` usage in Settings CSS is a compatibility condition, not a pattern for new styles.
|
||||
5. Do not restore or extend unused `App.css` template styles. Put necessary global rules in `index.css` and document their impact.
|
||||
|
||||
## Technical Debt
|
||||
|
||||
- There is no centralized project-owned set of spacing, shadow, z-index, or motion tokens; the UI relies on Radix scales mixed with local pixel values.
|
||||
- Settings has only a desktop 240px sidebar, with no dedicated mobile adaptation rules found; verify on a real device.
|
||||
- Error state, ErrorBoundary, and form-error presentation do not yet follow a unified shared pattern.
|
||||
- ProfileSettings uses native `alert`, Loading defaults to English `Loading...`, and internationalization remains inconsistent.
|
||||
- Actual interaction animations do not yet systematically honor `prefers-reduced-motion`.
|
||||
@@ -55,15 +55,6 @@ export default defineConfig({
|
||||
items: [
|
||||
{ text: '常见问题', link: '/troubleshoot/faq' },
|
||||
]
|
||||
},
|
||||
{
|
||||
text: '开发设计',
|
||||
items: [
|
||||
{ text: '文档索引', link: '/development/' },
|
||||
{ text: '系统架构', link: '/development/architecture' },
|
||||
{ text: '数据库设计', link: '/development/database-design' },
|
||||
{ text: 'UI 规范', link: '/development/ui-spec' },
|
||||
]
|
||||
}
|
||||
],
|
||||
footer: {
|
||||
|
||||
@@ -3,7 +3,7 @@ module podux
|
||||
go 1.25.5
|
||||
|
||||
require (
|
||||
github.com/fatedier/frp v0.68.0
|
||||
github.com/fatedier/frp v0.67.0
|
||||
github.com/pelletier/go-toml/v2 v2.2.0
|
||||
github.com/pocketbase/dbx v1.11.0
|
||||
github.com/pocketbase/pocketbase v0.35.0
|
||||
@@ -26,6 +26,7 @@ require (
|
||||
github.com/go-ozzo/ozzo-validation/v4 v4.3.0 // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0 // indirect
|
||||
github.com/golang/snappy v0.0.4 // indirect
|
||||
github.com/google/gopacket v1.1.19 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/mux v1.8.1 // indirect
|
||||
github.com/hashicorp/yamux v0.1.1 // indirect
|
||||
|
||||
@@ -27,8 +27,6 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
github.com/fatedier/frp v0.67.0 h1:w6xHLkruAJcq+fZP9VOiY6w/FBy/wB1aPqA4frs98K8=
|
||||
github.com/fatedier/frp v0.67.0/go.mod h1:0Q3mAI0c9WtAsgMQpTQhinWTKa2Qp121YWsqaFu41Zg=
|
||||
github.com/fatedier/frp v0.68.0 h1:woKC31EpgCLQDirRAOAUgHP3IRxLu2mBHS6zGpcw7tw=
|
||||
github.com/fatedier/frp v0.68.0/go.mod h1:qFdez6Z+RDqoqF1xJhh48+IW91SVQ+pNWnrmcl43Wjs=
|
||||
github.com/fatedier/golib v0.5.1 h1:hcKAnaw5mdI/1KWRGejxR+i1Hn/NvbY5UsMKDr7o13M=
|
||||
github.com/fatedier/golib v0.5.1/go.mod h1:W6kIYkIFxHsTzbgqg5piCxIiDo4LzwgTY6R5W8l9NFQ=
|
||||
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
||||
@@ -69,6 +67,8 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw
|
||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8=
|
||||
github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo=
|
||||
github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d h1:KJIErDwbSHjnp/SGzE5ed8Aol7JsKiI5X7yWKAtzhM0=
|
||||
github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
@@ -165,6 +165,7 @@ go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
|
||||
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
@@ -181,6 +182,8 @@ golang.org/x/image v0.34.0/go.mod h1:2RNFBZRB+vnwwFil8GkMdRvrJOFd1AzdZI6vOY+eJVU
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
|
||||
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
|
||||
@@ -251,11 +254,13 @@ golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3
|
||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
|
||||
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg=
|
||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=
|
||||
|
||||
@@ -21,7 +21,6 @@ import (
|
||||
"podux/pkg/utils"
|
||||
|
||||
"github.com/fatedier/frp/client"
|
||||
frpcsource "github.com/fatedier/frp/pkg/config/source"
|
||||
v1 "github.com/fatedier/frp/pkg/config/v1"
|
||||
"github.com/fatedier/frp/pkg/util/log"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
@@ -170,8 +169,6 @@ func (fs *Service) genProxyCfgs(serverId *string) ([]v1.ProxyConfigurer, error)
|
||||
if proxyMap.ProxyType == "http" || proxyMap.ProxyType == "https" {
|
||||
delete(proxyData, "remotePort")
|
||||
}
|
||||
proxyData["type"] = proxyMap.ProxyType
|
||||
delete(proxyData, "proxyType")
|
||||
proxyData["name"] = proxyMap.Name + "-" + proxyMap.Id
|
||||
|
||||
// Remove empty plugin map so frp doesn't try to parse a typeless plugin
|
||||
@@ -238,6 +235,10 @@ func (fs *Service) LaunchFrpc(serverId *string) error {
|
||||
|
||||
fs.app.Logger().Debug("Config", "serverAddr", cfg.ServerAddr, "serverPort", cfg.ServerPort, "proxyCount", len(proxyCfgs))
|
||||
|
||||
for _, c := range proxyCfgs {
|
||||
c.Complete(cfg.User)
|
||||
}
|
||||
|
||||
// Print frp configurations in logs with sensitive data masked
|
||||
commonCfgBytes, _ := json.Marshal(cfg)
|
||||
proxyCfgsBytes, _ := json.Marshal(proxyCfgs)
|
||||
@@ -250,13 +251,9 @@ func (fs *Service) LaunchFrpc(serverId *string) error {
|
||||
cfg.Complete()
|
||||
log.InitLogger(cfg.Log.To, cfg.Log.Level, int(cfg.Log.MaxDays), cfg.Log.DisablePrintColor)
|
||||
|
||||
configSrc := frpcsource.NewConfigSource()
|
||||
if err := configSrc.ReplaceAll(proxyCfgs, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
svr, err := client.NewService(client.ServiceOptions{
|
||||
Common: cfg,
|
||||
ConfigSourceAggregator: frpcsource.NewAggregator(configSrc),
|
||||
Common: cfg,
|
||||
ProxyCfgs: proxyCfgs,
|
||||
})
|
||||
if err != nil {
|
||||
fs.app.Logger().Error("NewService", "err", err)
|
||||
@@ -287,13 +284,13 @@ func (fs *Service) LaunchFrpc(serverId *string) error {
|
||||
done <- err
|
||||
}()
|
||||
|
||||
go fs.monitorServiceStatus(serverId, svr, ctx, done)
|
||||
go fs.monitorServiceStatus(serverId, svr, ctx, done, cfg.User)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// monitorServiceStatus monitors service status and updates the database.
|
||||
func (fs *Service) monitorServiceStatus(id *string, svr *client.Service, ctx context.Context, done <-chan error) {
|
||||
func (fs *Service) monitorServiceStatus(id *string, svr *client.Service, ctx context.Context, done <-chan error, user string) {
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
select {
|
||||
@@ -310,7 +307,7 @@ func (fs *Service) monitorServiceStatus(id *string, svr *client.Service, ctx con
|
||||
fs.app.Logger().Info("Service is running", "id", *id)
|
||||
}
|
||||
|
||||
go fs.monitorProxyStatus(id, svr, ctx)
|
||||
go fs.monitorProxyStatus(id, svr, ctx, user)
|
||||
|
||||
ticker := time.NewTicker(5 * time.Second)
|
||||
defer ticker.Stop()
|
||||
@@ -345,7 +342,7 @@ func (fs *Service) destroying(id *string) {
|
||||
}
|
||||
|
||||
// monitorProxyStatus monitors proxy status from frp and updates the database.
|
||||
func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx context.Context) {
|
||||
func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx context.Context, user string) {
|
||||
fs.app.Logger().Info("Starting proxy status monitoring", "serverId", *serverId)
|
||||
|
||||
statusExporter := svr.StatusExporter()
|
||||
@@ -367,13 +364,11 @@ func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx
|
||||
|
||||
for _, proxy := range proxies {
|
||||
baseName := proxy.Name + "-" + proxy.Id
|
||||
status, exists := statusExporter.GetProxyStatus(baseName)
|
||||
fs.app.Logger().Info("proxy status check", "baseName", baseName, "exists", exists, "phase", func() string {
|
||||
if status != nil {
|
||||
return status.Phase
|
||||
}
|
||||
return "nil"
|
||||
}())
|
||||
prefix := ""
|
||||
if user != "" {
|
||||
prefix = user + "."
|
||||
}
|
||||
status, exists := statusExporter.GetProxyStatus(prefix + baseName)
|
||||
|
||||
if exists {
|
||||
var bootStatus proxydomain.ProxyBootStatus
|
||||
@@ -498,6 +493,15 @@ func (fs *Service) ReloadFrpc(serverId *string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
server, err := fs.app.FindRecordById("fh_servers", *serverId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
user := server.GetString("user")
|
||||
for _, c := range proxyCfgs {
|
||||
c.Complete(user)
|
||||
}
|
||||
|
||||
proxyCfgsBytes, _ := json.Marshal(proxyCfgs)
|
||||
safeProxies := sensitiveRegex.ReplaceAll(proxyCfgsBytes, []byte(`"${1}":"***"`))
|
||||
fs.app.Logger().Info("FRP Reload Configurations", "proxies", string(safeProxies))
|
||||
|
||||
@@ -0,0 +1,570 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/google/gopacket"
|
||||
"github.com/google/gopacket/afpacket"
|
||||
"github.com/google/gopacket/layers"
|
||||
)
|
||||
|
||||
// Device represents a discovered LAN host.
|
||||
type Device struct {
|
||||
IP string `json:"ip"`
|
||||
MAC string `json:"mac"`
|
||||
Hostname string `json:"hostname"`
|
||||
Interface string `json:"interface"`
|
||||
}
|
||||
|
||||
// LocalNetwork describes one scannable subnet on this host.
|
||||
type LocalNetwork struct {
|
||||
Interface string `json:"interface"`
|
||||
CIDR string `json:"cidr"`
|
||||
Hosts int `json:"hosts"`
|
||||
}
|
||||
|
||||
// PortResult is the result of scanning a single TCP port.
|
||||
type PortResult struct {
|
||||
Port int `json:"port"`
|
||||
Open bool `json:"open"`
|
||||
Service string `json:"service"`
|
||||
Done bool `json:"done,omitempty"` // signals end-of-stream
|
||||
}
|
||||
|
||||
// wellKnownPorts maps port numbers to service names.
|
||||
var wellKnownPorts = map[int]string{
|
||||
21: "FTP",
|
||||
22: "SSH",
|
||||
23: "Telnet",
|
||||
25: "SMTP",
|
||||
53: "DNS",
|
||||
80: "HTTP",
|
||||
110: "POP3",
|
||||
143: "IMAP",
|
||||
443: "HTTPS",
|
||||
445: "SMB",
|
||||
1433: "MSSQL",
|
||||
1521: "Oracle",
|
||||
3306: "MySQL",
|
||||
3389: "RDP",
|
||||
5432: "PostgreSQL",
|
||||
5900: "VNC",
|
||||
6379: "Redis",
|
||||
8080: "HTTP-Alt",
|
||||
8443: "HTTPS-Alt",
|
||||
8888: "HTTP-Dev",
|
||||
9200: "Elasticsearch",
|
||||
11211: "Memcached",
|
||||
27017: "MongoDB",
|
||||
}
|
||||
|
||||
// CommonPorts is the default port list for port scanning.
|
||||
var CommonPorts = func() []int {
|
||||
ports := make([]int, 0, len(wellKnownPorts))
|
||||
for p := range wellKnownPorts {
|
||||
ports = append(ports, p)
|
||||
}
|
||||
return ports
|
||||
}()
|
||||
|
||||
// hostProbePorts are the ports tried when checking whether a host is alive
|
||||
// without ARP (TCP fallback mode).
|
||||
var hostProbePorts = []int{22, 80, 443, 445, 3389, 8080, 8443}
|
||||
|
||||
// maxPrefixLen is the smallest prefix we will scan (/20 = 4094 hosts max).
|
||||
// Subnets larger than this (e.g. Docker /16) are skipped automatically.
|
||||
const maxPrefixLen = 20
|
||||
|
||||
// Service provides LAN discovery and port-scan capabilities.
|
||||
type Service struct{}
|
||||
|
||||
func NewService() *Service { return &Service{} }
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public API
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// GetLocalNetworks returns the subnets that will be scanned.
|
||||
func (s *Service) GetLocalNetworks() []LocalNetwork {
|
||||
var out []LocalNetwork
|
||||
for _, iface := range upInterfaces() {
|
||||
addrs, _ := iface.Addrs()
|
||||
for _, addr := range addrs {
|
||||
ipNet, ok := addr.(*net.IPNet)
|
||||
if !ok || ipNet.IP.To4() == nil || ipNet.IP.IsLoopback() {
|
||||
continue
|
||||
}
|
||||
ones, _ := ipNet.Mask.Size()
|
||||
if ones < maxPrefixLen {
|
||||
continue
|
||||
}
|
||||
hosts := (1 << (32 - ones)) - 2
|
||||
out = append(out, LocalNetwork{
|
||||
Interface: iface.Name,
|
||||
CIDR: ipNet.String(),
|
||||
Hosts: hosts,
|
||||
})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// DiscoverDevices scans local subnets for active hosts.
|
||||
// It first attempts a gopacket/afpacket ARP sweep (requires CAP_NET_RAW).
|
||||
// If that is unavailable it falls back to TCP-connect probing + reading the
|
||||
// kernel ARP cache from /proc/net/arp.
|
||||
func (s *Service) DiscoverDevices(ctx context.Context) ([]Device, error) {
|
||||
ifaces := upInterfaces()
|
||||
if len(ifaces) == 0 {
|
||||
return []Device{}, nil
|
||||
}
|
||||
|
||||
// Try ARP sweep on first suitable interface; if permission denied use TCP.
|
||||
devices, err := s.arpDiscover(ctx, ifaces)
|
||||
if err != nil {
|
||||
if isPermissionDenied(err) {
|
||||
return s.tcpDiscover(ctx, ifaces)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return devices, nil
|
||||
}
|
||||
|
||||
// ScanPorts does a concurrent TCP-connect scan on ip for ports.
|
||||
// Results are written to ch; the caller must close ch after this returns.
|
||||
func (s *Service) ScanPorts(ctx context.Context, ip string, ports []int, ch chan<- PortResult) {
|
||||
const concurrency = 200
|
||||
sem := make(chan struct{}, concurrency)
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for _, port := range ports {
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
sem <- struct{}{}
|
||||
wg.Add(1)
|
||||
go func(p int) {
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
|
||||
addr := net.JoinHostPort(ip, strconv.Itoa(p))
|
||||
conn, err := net.DialTimeout("tcp", addr, 500*time.Millisecond)
|
||||
open := err == nil
|
||||
if conn != nil {
|
||||
conn.Close()
|
||||
}
|
||||
|
||||
result := PortResult{Port: p, Open: open}
|
||||
if open {
|
||||
result.Service = wellKnownPorts[p]
|
||||
}
|
||||
select {
|
||||
case ch <- result:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}(port)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ARP-based discovery (gopacket + afpacket, needs CAP_NET_RAW)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func (s *Service) arpDiscover(ctx context.Context, ifaces []net.Interface) ([]Device, error) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
wg sync.WaitGroup
|
||||
devices = make([]Device, 0)
|
||||
seen = map[string]bool{}
|
||||
lastErr error
|
||||
)
|
||||
|
||||
for _, iface := range ifaces {
|
||||
if len(iface.HardwareAddr) == 0 {
|
||||
continue
|
||||
}
|
||||
addrs, _ := iface.Addrs()
|
||||
for _, addr := range addrs {
|
||||
ipNet, ok := addr.(*net.IPNet)
|
||||
if !ok || ipNet.IP.To4() == nil || ipNet.IP.IsLoopback() {
|
||||
continue
|
||||
}
|
||||
ones, _ := ipNet.Mask.Size()
|
||||
if ones < maxPrefixLen {
|
||||
continue // skip huge subnets like Docker /16
|
||||
}
|
||||
|
||||
wg.Add(1)
|
||||
go func(iface net.Interface, ip net.IP, network *net.IPNet) {
|
||||
defer wg.Done()
|
||||
found, err := arpSweep(ctx, iface, ip, network)
|
||||
if err != nil {
|
||||
mu.Lock()
|
||||
lastErr = err
|
||||
mu.Unlock()
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
for _, d := range found {
|
||||
if !seen[d.IP] {
|
||||
seen[d.IP] = true
|
||||
devices = append(devices, d)
|
||||
}
|
||||
}
|
||||
mu.Unlock()
|
||||
}(iface, ipNet.IP, ipNet)
|
||||
}
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
if len(devices) == 0 && lastErr != nil {
|
||||
return nil, lastErr
|
||||
}
|
||||
return devices, nil
|
||||
}
|
||||
|
||||
func arpSweep(ctx context.Context, iface net.Interface, src net.IP, network *net.IPNet) ([]Device, error) {
|
||||
handle, err := afpacket.NewTPacket(
|
||||
afpacket.OptInterface(iface.Name),
|
||||
afpacket.OptBlockTimeout(5*time.Millisecond),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sweepCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
results := make(chan Device, 512)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
captureARP(sweepCtx, handle, results)
|
||||
close(results)
|
||||
}()
|
||||
|
||||
sendARP(sweepCtx, handle, iface, src, network)
|
||||
|
||||
<-sweepCtx.Done()
|
||||
handle.Close()
|
||||
wg.Wait()
|
||||
|
||||
selfIP := src.String()
|
||||
var devices []Device
|
||||
seen := map[string]bool{selfIP: true}
|
||||
for d := range results {
|
||||
if seen[d.IP] {
|
||||
continue
|
||||
}
|
||||
seen[d.IP] = true
|
||||
d.Interface = iface.Name
|
||||
if names, err := net.LookupAddr(d.IP); err == nil && len(names) > 0 {
|
||||
d.Hostname = strings.TrimSuffix(names[0], ".")
|
||||
}
|
||||
devices = append(devices, d)
|
||||
}
|
||||
return devices, nil
|
||||
}
|
||||
|
||||
func captureARP(ctx context.Context, handle *afpacket.TPacket, out chan<- Device) {
|
||||
pktSrc := gopacket.NewPacketSource(handle, layers.LinkTypeEthernet)
|
||||
pktSrc.NoCopy = true
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
pkt, err := pktSrc.NextPacket()
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
arpLayer := pkt.Layer(layers.LayerTypeARP)
|
||||
if arpLayer == nil {
|
||||
continue
|
||||
}
|
||||
arp := arpLayer.(*layers.ARP)
|
||||
if arp.Operation != layers.ARPReply {
|
||||
continue
|
||||
}
|
||||
ip := net.IP(arp.SourceProtAddress).String()
|
||||
mac := net.HardwareAddr(arp.SourceHwAddress).String()
|
||||
select {
|
||||
case out <- Device{IP: ip, MAC: mac}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sendARP(ctx context.Context, handle *afpacket.TPacket, iface net.Interface, src net.IP, network *net.IPNet) {
|
||||
eth := layers.Ethernet{
|
||||
SrcMAC: iface.HardwareAddr,
|
||||
DstMAC: net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
|
||||
EthernetType: layers.EthernetTypeARP,
|
||||
}
|
||||
arp := layers.ARP{
|
||||
AddrType: layers.LinkTypeEthernet,
|
||||
Protocol: layers.EthernetTypeIPv4,
|
||||
HwAddressSize: 6,
|
||||
ProtAddressSize: 4,
|
||||
Operation: layers.ARPRequest,
|
||||
SourceHwAddress: []byte(iface.HardwareAddr),
|
||||
SourceProtAddress: []byte(src.To4()),
|
||||
DstHwAddress: []byte{0, 0, 0, 0, 0, 0},
|
||||
}
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
opts := gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true}
|
||||
|
||||
for ip := cloneIP(network.IP.Mask(network.Mask)); network.Contains(ip); incrementIP(ip) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
target := make(net.IP, 4)
|
||||
copy(target, ip.To4())
|
||||
arp.DstProtAddress = target
|
||||
if err := gopacket.SerializeLayers(buf, opts, ð, &arp); err != nil {
|
||||
continue
|
||||
}
|
||||
_ = handle.WritePacketData(buf.Bytes())
|
||||
time.Sleep(500 * time.Microsecond)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TCP-based host discovery fallback (no special privileges required)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// tcpDiscover probes each host in every local subnet using TCP connect.
|
||||
// A host is "alive" if any probe port responds (open or connection refused).
|
||||
// After the sweep it enriches results with MAC addresses from /proc/net/arp.
|
||||
func (s *Service) tcpDiscover(ctx context.Context, ifaces []net.Interface) ([]Device, error) {
|
||||
type result struct {
|
||||
ip string
|
||||
iface string
|
||||
}
|
||||
|
||||
resultCh := make(chan result, 512)
|
||||
var sweepWg sync.WaitGroup
|
||||
|
||||
const hostConcurrency = 100
|
||||
|
||||
for _, iface := range ifaces {
|
||||
addrs, _ := iface.Addrs()
|
||||
for _, addr := range addrs {
|
||||
ipNet, ok := addr.(*net.IPNet)
|
||||
if !ok || ipNet.IP.To4() == nil || ipNet.IP.IsLoopback() {
|
||||
continue
|
||||
}
|
||||
ones, _ := ipNet.Mask.Size()
|
||||
if ones < maxPrefixLen {
|
||||
continue
|
||||
}
|
||||
|
||||
// Enumerate all host addresses in this subnet.
|
||||
var ips []string
|
||||
selfIP := ipNet.IP.String()
|
||||
for ip := cloneIP(ipNet.IP.Mask(ipNet.Mask)); ipNet.Contains(ip); incrementIP(ip) {
|
||||
candidate := ip.String()
|
||||
if candidate == selfIP {
|
||||
continue
|
||||
}
|
||||
ips = append(ips, candidate)
|
||||
}
|
||||
|
||||
sweepWg.Add(1)
|
||||
go func(ifaceName string, ips []string) {
|
||||
defer sweepWg.Done()
|
||||
sem := make(chan struct{}, hostConcurrency)
|
||||
var wg sync.WaitGroup
|
||||
for _, ip := range ips {
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
sem <- struct{}{}
|
||||
wg.Add(1)
|
||||
go func(ip string) {
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
if isHostAlive(ctx, ip) {
|
||||
select {
|
||||
case resultCh <- result{ip: ip, iface: ifaceName}:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}
|
||||
}(ip)
|
||||
}
|
||||
wg.Wait()
|
||||
}(iface.Name, ips)
|
||||
}
|
||||
}
|
||||
|
||||
// Close resultCh once all sweeps complete.
|
||||
go func() {
|
||||
sweepWg.Wait()
|
||||
close(resultCh)
|
||||
}()
|
||||
|
||||
// Collect results.
|
||||
arpCache := readARPCache()
|
||||
devices := make([]Device, 0)
|
||||
seen := map[string]bool{}
|
||||
|
||||
for r := range resultCh {
|
||||
if seen[r.ip] {
|
||||
continue
|
||||
}
|
||||
seen[r.ip] = true
|
||||
d := Device{IP: r.ip, Interface: r.iface}
|
||||
if mac, ok := arpCache[r.ip]; ok {
|
||||
d.MAC = mac
|
||||
}
|
||||
if names, err := net.LookupAddr(r.ip); err == nil && len(names) > 0 {
|
||||
d.Hostname = strings.TrimSuffix(names[0], ".")
|
||||
}
|
||||
devices = append(devices, d)
|
||||
}
|
||||
return devices, nil
|
||||
}
|
||||
|
||||
// isHostAlive returns true if the host has any TCP port open or actively
|
||||
// refusing connections (which proves the host is up).
|
||||
func isHostAlive(ctx context.Context, ip string) bool {
|
||||
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
found := make(chan struct{}, 1)
|
||||
var wg sync.WaitGroup
|
||||
for _, port := range hostProbePorts {
|
||||
wg.Add(1)
|
||||
go func(p int) {
|
||||
defer wg.Done()
|
||||
addr := net.JoinHostPort(ip, strconv.Itoa(p))
|
||||
d := net.Dialer{}
|
||||
conn, err := d.DialContext(ctx, "tcp", addr)
|
||||
if conn != nil {
|
||||
conn.Close()
|
||||
}
|
||||
if err == nil || isConnRefused(err) {
|
||||
select {
|
||||
case found <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
}(port)
|
||||
}
|
||||
wg.Wait()
|
||||
select {
|
||||
case <-found:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// isConnRefused checks whether err is ECONNREFUSED (host alive, port closed).
|
||||
func isConnRefused(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var opErr *net.OpError
|
||||
if !errors.As(err, &opErr) {
|
||||
return false
|
||||
}
|
||||
var syscallErr *os.SyscallError
|
||||
if !errors.As(opErr.Err, &syscallErr) {
|
||||
return false
|
||||
}
|
||||
errno, ok := syscallErr.Err.(syscall.Errno)
|
||||
return ok && errno == syscall.ECONNREFUSED
|
||||
}
|
||||
|
||||
// readARPCache parses /proc/net/arp and returns an ip→mac map.
|
||||
func readARPCache() map[string]string {
|
||||
f, err := os.Open("/proc/net/arp")
|
||||
if err != nil {
|
||||
return map[string]string{}
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
cache := map[string]string{}
|
||||
scanner := bufio.NewScanner(f)
|
||||
scanner.Scan() // skip header line
|
||||
for scanner.Scan() {
|
||||
fields := strings.Fields(scanner.Text())
|
||||
if len(fields) < 4 {
|
||||
continue
|
||||
}
|
||||
ip := fields[0]
|
||||
mac := fields[3]
|
||||
if mac == "00:00:00:00:00:00" {
|
||||
continue
|
||||
}
|
||||
cache[ip] = mac
|
||||
}
|
||||
return cache
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func upInterfaces() []net.Interface {
|
||||
ifaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var out []net.Interface
|
||||
for _, iface := range ifaces {
|
||||
if iface.Flags&net.FlagLoopback != 0 {
|
||||
continue
|
||||
}
|
||||
if iface.Flags&net.FlagUp == 0 {
|
||||
continue
|
||||
}
|
||||
out = append(out, iface)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func isPermissionDenied(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
s := strings.ToLower(err.Error())
|
||||
return strings.Contains(s, "permission denied") ||
|
||||
strings.Contains(s, "operation not permitted")
|
||||
}
|
||||
|
||||
func cloneIP(ip net.IP) net.IP {
|
||||
clone := make(net.IP, len(ip))
|
||||
copy(clone, ip)
|
||||
return clone
|
||||
}
|
||||
|
||||
func incrementIP(ip net.IP) {
|
||||
for i := len(ip) - 1; i >= 0; i-- {
|
||||
ip[i]++
|
||||
if ip[i] != 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -177,7 +177,7 @@ func (s *Service) GetLatestVersion() (*LatestVersionResponse, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("User-Agent", "podux-server/"+buildinfo.AppVersion)
|
||||
req.Header.Set("User-Agent", "podux-server")
|
||||
req.Header.Set("Accept", "application/vnd.github+json")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package httphandler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"podux/internal/application/scanner"
|
||||
"podux/pkg/response"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
)
|
||||
|
||||
type ScannerHandler struct {
|
||||
app core.App
|
||||
service *scanner.Service
|
||||
}
|
||||
|
||||
func NewScannerHandler(app core.App, service *scanner.Service) *ScannerHandler {
|
||||
return &ScannerHandler{app: app, service: service}
|
||||
}
|
||||
|
||||
func (h *ScannerHandler) RegisterHandlers(e *core.ServeEvent) {
|
||||
// GET /api/scanner/interfaces
|
||||
// Returns local networks that will be scanned.
|
||||
e.Router.GET("/api/scanner/interfaces", requireAuth(func(e *core.RequestEvent) error {
|
||||
return e.JSON(200, h.service.GetLocalNetworks())
|
||||
}, h.app))
|
||||
|
||||
// GET /api/scanner/discover
|
||||
// ARP-sweep local network, returns discovered hosts.
|
||||
e.Router.GET("/api/scanner/discover", requireAuth(func(e *core.RequestEvent) error {
|
||||
ctx := e.Request.Context()
|
||||
devices, err := h.service.DiscoverDevices(ctx)
|
||||
if err != nil {
|
||||
h.app.Logger().Error("LAN discovery failed", "error", err)
|
||||
return e.JSON(500, response.Error(err))
|
||||
}
|
||||
return e.JSON(200, devices)
|
||||
}, h.app))
|
||||
|
||||
// GET /api/scanner/ports/stream?ip=<ip>[&ports=<p1,p2,...>]
|
||||
// Streams port-scan results as Server-Sent Events.
|
||||
e.Router.GET("/api/scanner/ports/stream", requireAuth(func(e *core.RequestEvent) error {
|
||||
q := e.Request.URL.Query()
|
||||
ip := q.Get("ip")
|
||||
if ip == "" {
|
||||
return e.JSON(400, response.Error(fmt.Errorf("ip is required")))
|
||||
}
|
||||
if net.ParseIP(ip) == nil {
|
||||
return e.JSON(400, response.Error(fmt.Errorf("invalid ip address")))
|
||||
}
|
||||
|
||||
var ports []int
|
||||
switch {
|
||||
case q.Get("full") == "true":
|
||||
ports = allPorts()
|
||||
case q.Get("ports") != "":
|
||||
ports = parsePortList(q.Get("ports"))
|
||||
default:
|
||||
ports = scanner.CommonPorts
|
||||
}
|
||||
|
||||
w := e.Response
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Connection", "keep-alive")
|
||||
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
return e.JSON(500, response.Error(fmt.Errorf("streaming not supported")))
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(e.Request.Context())
|
||||
defer cancel()
|
||||
|
||||
results := make(chan scanner.PortResult, 128)
|
||||
|
||||
go func() {
|
||||
defer close(results)
|
||||
h.service.ScanPorts(ctx, ip, ports, results)
|
||||
}()
|
||||
|
||||
for res := range results {
|
||||
data, err := json.Marshal(res)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(w, "data: %s\n\n", data)
|
||||
flusher.Flush()
|
||||
}
|
||||
|
||||
// Signal completion
|
||||
done, _ := json.Marshal(scanner.PortResult{Done: true})
|
||||
fmt.Fprintf(w, "data: %s\n\n", done)
|
||||
flusher.Flush()
|
||||
|
||||
return nil
|
||||
}, h.app))
|
||||
}
|
||||
|
||||
// allPorts returns every valid TCP port (1-65535).
|
||||
func allPorts() []int {
|
||||
ports := make([]int, 65535)
|
||||
for i := range ports {
|
||||
ports[i] = i + 1
|
||||
}
|
||||
return ports
|
||||
}
|
||||
|
||||
// parsePortList parses a comma-separated list of port numbers.
|
||||
func parsePortList(s string) []int {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
var ports []int
|
||||
for _, part := range strings.Split(s, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
if n, err := strconv.Atoi(part); err == nil && n > 0 && n <= 65535 {
|
||||
ports = append(ports, n)
|
||||
}
|
||||
}
|
||||
return ports
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"podux/internal/application/importer"
|
||||
"podux/internal/application/monitoring"
|
||||
"podux/internal/application/proxy"
|
||||
"podux/internal/application/scanner"
|
||||
"podux/internal/application/server"
|
||||
"podux/internal/application/system"
|
||||
"podux/internal/application/version"
|
||||
@@ -51,11 +52,13 @@ func main() {
|
||||
networkMonitorService := monitoring.NewMonitorService(app, geoService, metricsService)
|
||||
importService := importer.NewService(app)
|
||||
versionService := version.NewService(app)
|
||||
scannerService := scanner.NewService()
|
||||
//githubService := github.NewService(app)
|
||||
|
||||
// HTTP Handlers
|
||||
//githubHandler := httphandler.NewGithubHandler(app, githubService)
|
||||
frpcHandler := httphandler.NewFrpcHandler(app, frpcService)
|
||||
scannerHandler := httphandler.NewScannerHandler(app, scannerService)
|
||||
versionHandler := httphandler.NewVersionHandler(app, versionService)
|
||||
dashboardHandler := httphandler.NewDashboardHandler(dashboardService)
|
||||
systemHandler := httphandler.NewSystemHandler(app, settingsService)
|
||||
@@ -100,6 +103,7 @@ func main() {
|
||||
systemHandler.RegisterHandlers(e)
|
||||
importHandler.RegisterHandlers(e)
|
||||
serverHandler.RegisterHandlers(e)
|
||||
scannerHandler.RegisterHandlers(e)
|
||||
|
||||
// Serve static files from embedded FS
|
||||
content, err := fs.Sub(pbPublicDir, "pb_public")
|
||||
|
||||
+9
-13
@@ -1657,33 +1657,29 @@ func init() {
|
||||
},
|
||||
{
|
||||
"hidden": false,
|
||||
"id": "number3814843458",
|
||||
"max": null,
|
||||
"min": null,
|
||||
"id": "date2095552691",
|
||||
"max": "",
|
||||
"min": "",
|
||||
"name": "valMax",
|
||||
"onlyInt": false,
|
||||
"presentable": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "number"
|
||||
"type": "date"
|
||||
},
|
||||
{
|
||||
"hidden": false,
|
||||
"id": "number3748453147",
|
||||
"max": null,
|
||||
"min": null,
|
||||
"id": "date1089120234",
|
||||
"max": "",
|
||||
"min": "",
|
||||
"name": "valMin",
|
||||
"onlyInt": false,
|
||||
"presentable": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "number"
|
||||
"type": "date"
|
||||
}
|
||||
],
|
||||
"id": "pbc_3875966484",
|
||||
"indexes": [
|
||||
"CREATE INDEX ` + "`" + `idx_cytGPviJew` + "`" + ` ON ` + "`" + `fh_metrics_daily` + "`" + ` (\n ` + "`" + `targetId` + "`" + `,\n ` + "`" + `metricKey` + "`" + `,\n ` + "`" + `t` + "`" + `\n)"
|
||||
],
|
||||
"indexes": [],
|
||||
"listRule": null,
|
||||
"name": "fh_metrics_daily",
|
||||
"system": false,
|
||||
@@ -2,4 +2,4 @@ package buildinfo
|
||||
|
||||
// AppVersion is the single source of truth for the application version.
|
||||
// Update this value to release a new version.
|
||||
const AppVersion = "0.1.6"
|
||||
const AppVersion = "0.1.4"
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "podux-web",
|
||||
"private": true,
|
||||
"version": "0.1.6",
|
||||
"version": "0.1.4",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -32,6 +32,9 @@ const ServerFormPage = lazy(() =>
|
||||
const ServerLogPage = lazy(() =>
|
||||
import("./pages/ServerLog/ServerLogPage").then((m) => ({ default: m.ServerLogPage }))
|
||||
);
|
||||
const ScannerPage = lazy(() =>
|
||||
import("./pages/Scanner").then((m) => ({ default: m.ScannerPage }))
|
||||
);
|
||||
|
||||
function AuthenticatedLayout() {
|
||||
console.log("AuthenticatedLayout rendered");
|
||||
@@ -77,6 +80,7 @@ function App() {
|
||||
<Route path="/servers/:id/logs" element={<ServerLogPage />} />
|
||||
<Route path="/settings" element={<SettingsPage />} />
|
||||
<Route path="/import" element={<ImportPage />} />
|
||||
<Route path="/scanner" element={<ScannerPage />} />
|
||||
{/* <Route path="/versions" element={<VersionPage />} /> */}
|
||||
</Route>
|
||||
|
||||
|
||||
@@ -62,6 +62,11 @@ const navItems = [
|
||||
path: "/proxies",
|
||||
icon: <Icon icon="lucide:network" width="18" height="18" />,
|
||||
},
|
||||
{
|
||||
labelKey: "nav.scanner",
|
||||
path: "/scanner",
|
||||
icon: <Icon icon="lucide:radar" width="18" height="18" />,
|
||||
},
|
||||
];
|
||||
|
||||
const mobileBottomNavItems = navItems;
|
||||
|
||||
@@ -40,7 +40,8 @@
|
||||
"logout": "Logout",
|
||||
"pbAdmin": "Admin Panel",
|
||||
"version": "Version",
|
||||
"import": "Import"
|
||||
"import": "Import",
|
||||
"scanner": "Scanner"
|
||||
},
|
||||
"auth": {
|
||||
"login": "Login",
|
||||
@@ -286,7 +287,7 @@
|
||||
"totalProxies": "Total Proxies",
|
||||
"confirmDeletion": "Confirm Deletion",
|
||||
"deleteConfirmMessage": "Are you sure you want to delete this proxy? This action cannot be undone.",
|
||||
"remotePortOrDomain": "Remote Access",
|
||||
"remotePortOrDomain": "Remote Port / Domain",
|
||||
"selectServer": "Select Server",
|
||||
"selectServerPlaceholder": "Select a server",
|
||||
"noServersAvailable": "No servers available",
|
||||
@@ -487,5 +488,38 @@
|
||||
"setupFailed": "Failed to initialize system. Please try again.",
|
||||
"settingsCreateFailed": "Failed to initialize system settings"
|
||||
}
|
||||
},
|
||||
"scanner": {
|
||||
"title": "LAN Scanner",
|
||||
"description": "Discover devices on your local network and scan their open ports",
|
||||
"step1Title": "Step 1 — Device Discovery",
|
||||
"step1Desc": "Scan your local network for active hosts using ARP. Requires root / CAP_NET_RAW on the server.",
|
||||
"discovering": "Scanning...",
|
||||
"discoverBtn": "Start Discovery",
|
||||
"devicesFound": "{{count}} device(s) found",
|
||||
"hosts": "hosts",
|
||||
"ipAddress": "IP Address",
|
||||
"macAddress": "MAC Address",
|
||||
"hostname": "Hostname",
|
||||
"iface": "Interface",
|
||||
"scanPorts": "Scan Ports",
|
||||
"scanTarget": "Target",
|
||||
"startScan": "Start Port Scan",
|
||||
"stop": "Stop",
|
||||
"mode": "Mode",
|
||||
"modeCommon": "Common",
|
||||
"modeCustom": "Custom",
|
||||
"modeFull": "All ports",
|
||||
"customPorts": "Custom ports",
|
||||
"customPortsPlaceholder": "e.g. 22,80,443,8080",
|
||||
"customPortsHint": "Comma-separated port numbers",
|
||||
"fullScanWarning": "Scanning all 65535 ports will take several minutes. The results will stream in real time.",
|
||||
"scanned": "Scanned",
|
||||
"openPorts": "Open",
|
||||
"complete": "Done",
|
||||
"port": "Port",
|
||||
"status": "Status",
|
||||
"service": "Service",
|
||||
"open": "Open"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,8 @@
|
||||
"logout": "退出登录",
|
||||
"pbAdmin": "后台管理",
|
||||
"version": "版本",
|
||||
"import": "导入"
|
||||
"import": "导入",
|
||||
"scanner": "局域网扫描"
|
||||
},
|
||||
"auth": {
|
||||
"login": "登录",
|
||||
@@ -286,7 +287,7 @@
|
||||
"totalProxies": "代理总数",
|
||||
"confirmDeletion": "确认删除",
|
||||
"deleteConfirmMessage": "您确定要删除此代理吗?此操作无法撤消。",
|
||||
"remotePortOrDomain": "远程访问",
|
||||
"remotePortOrDomain": "远程端口 / 域名",
|
||||
"selectServer": "选择服务器",
|
||||
"selectServerPlaceholder": "选择一个服务器",
|
||||
"noServersAvailable": "没有可用的服务器",
|
||||
@@ -487,5 +488,38 @@
|
||||
"setupFailed": "系统初始化失败。请重试。",
|
||||
"settingsCreateFailed": "初始化系统设置失败"
|
||||
}
|
||||
},
|
||||
"scanner": {
|
||||
"title": "局域网扫描",
|
||||
"description": "发现局域网内的在线设备并扫描其开放端口",
|
||||
"step1Title": "第一步 — 设备发现",
|
||||
"step1Desc": "使用 ARP 扫描本地网络中的活跃主机。服务器需要 root 权限或 CAP_NET_RAW 能力。",
|
||||
"discovering": "扫描中...",
|
||||
"discoverBtn": "开始发现",
|
||||
"devicesFound": "发现 {{count}} 台设备",
|
||||
"hosts": "台主机",
|
||||
"ipAddress": "IP 地址",
|
||||
"macAddress": "MAC 地址",
|
||||
"hostname": "主机名",
|
||||
"iface": "网口",
|
||||
"scanPorts": "扫描端口",
|
||||
"scanTarget": "目标",
|
||||
"startScan": "开始端口扫描",
|
||||
"stop": "停止",
|
||||
"mode": "模式",
|
||||
"modeCommon": "常用端口",
|
||||
"modeCustom": "自定义",
|
||||
"modeFull": "全部端口",
|
||||
"customPorts": "自定义端口",
|
||||
"customPortsPlaceholder": "例如 22,80,443,8080",
|
||||
"customPortsHint": "用逗号分隔端口号",
|
||||
"fullScanWarning": "扫描全部 65535 个端口将耗时数分钟,结果会实时流式显示。",
|
||||
"scanned": "已扫描",
|
||||
"openPorts": "开放",
|
||||
"complete": "完成",
|
||||
"port": "端口",
|
||||
"status": "状态",
|
||||
"service": "服务",
|
||||
"open": "开放"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,11 +21,6 @@ interface ProxiesViewProps {
|
||||
onDeleteProxy: (id: string) => Promise<void>;
|
||||
onToggleStatus: (proxy: Proxy) => Promise<void>;
|
||||
refreshProxies: () => void;
|
||||
page: number;
|
||||
setPage: (page: number) => void;
|
||||
totalPages: number;
|
||||
search: string;
|
||||
setSearch: (value: string) => void;
|
||||
}
|
||||
|
||||
export function ProxiesView({
|
||||
@@ -36,11 +31,6 @@ export function ProxiesView({
|
||||
onDeleteProxy,
|
||||
onToggleStatus,
|
||||
refreshProxies,
|
||||
page,
|
||||
setPage,
|
||||
totalPages,
|
||||
search,
|
||||
setSearch,
|
||||
}: ProxiesViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
@@ -50,23 +40,10 @@ export function ProxiesView({
|
||||
const [togglingId, setTogglingId] = useState<string | null>(null);
|
||||
|
||||
const handleCopy = (text: string, id: string) => {
|
||||
const done = () => {
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
setCopiedId(id);
|
||||
setTimeout(() => setCopiedId(null), 1500);
|
||||
};
|
||||
if (navigator.clipboard) {
|
||||
navigator.clipboard.writeText(text).then(done);
|
||||
} else {
|
||||
const el = document.createElement("textarea");
|
||||
el.value = text;
|
||||
el.style.position = "fixed";
|
||||
el.style.opacity = "0";
|
||||
document.body.appendChild(el);
|
||||
el.select();
|
||||
document.execCommand("copy");
|
||||
document.body.removeChild(el);
|
||||
done();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -144,21 +121,10 @@ export function ProxiesView({
|
||||
size="2"
|
||||
placeholder={t("proxy.searchProxies")}
|
||||
className="min-w-32 flex-1"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
>
|
||||
<TextField.Slot>
|
||||
<Icon icon="lucide:search" width="16" height="16" />
|
||||
</TextField.Slot>
|
||||
{search && (
|
||||
<TextField.Slot
|
||||
pr="2"
|
||||
onClick={() => setSearch("")}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
<Icon icon="lucide:x" width="16" height="16" />
|
||||
</TextField.Slot>
|
||||
)}
|
||||
</TextField.Root>
|
||||
<Button variant="soft" onClick={refreshProxies} disabled={refreshing}>
|
||||
<Icon
|
||||
@@ -189,7 +155,6 @@ export function ProxiesView({
|
||||
onAction={() => navigate("/proxies/new")}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div className="overflow-x-auto">
|
||||
<Table.Root>
|
||||
<Table.Header>
|
||||
@@ -207,7 +172,6 @@ export function ProxiesView({
|
||||
</Table.Header>
|
||||
<Table.Body>
|
||||
{proxies.map((proxy) => (
|
||||
|
||||
<Table.Row key={proxy.id}>
|
||||
<Table.Cell>
|
||||
<Text weight="medium">{proxy.name || <Text color="gray">-</Text>}</Text>
|
||||
@@ -314,38 +278,26 @@ export function ProxiesView({
|
||||
</Flex>
|
||||
);
|
||||
}
|
||||
const remotePort = proxy.remotePort ? String(proxy.remotePort) : "";
|
||||
if (!remotePort)
|
||||
const displayText = proxy.remotePort || "-";
|
||||
if (displayText === "-")
|
||||
return <Text size="2" color="gray">-</Text>;
|
||||
const serverAddr =
|
||||
(proxy as { expand?: { serverId?: { serverAddr?: string } } }).expand?.serverId?.serverAddr || "";
|
||||
const items = proxy.proxyType === "tcp" || proxy.proxyType === "udp"
|
||||
? [remotePort, serverAddr ? `${serverAddr}:${remotePort}` : ""].filter(Boolean)
|
||||
: [remotePort];
|
||||
const copyKey = `${proxy.id}-port`;
|
||||
const isCopied = copiedId === copyKey;
|
||||
return (
|
||||
<Flex direction="column" gap="1">
|
||||
{items.map((item, i) => {
|
||||
const copyKey = `${proxy.id}-remote-${i}`;
|
||||
const isCopied = copiedId === copyKey;
|
||||
return (
|
||||
<Flex
|
||||
key={item}
|
||||
align="center"
|
||||
gap="1"
|
||||
style={{ cursor: "pointer" }}
|
||||
onClick={() => handleCopy(item, copyKey)}
|
||||
title={isCopied ? t("common.copied") : t("common.clickToCopy")}
|
||||
>
|
||||
<Text size="2">{item}</Text>
|
||||
<Icon
|
||||
icon={isCopied ? "lucide:check" : "lucide:copy"}
|
||||
width="12"
|
||||
height="12"
|
||||
color={isCopied ? "var(--green-9)" : "var(--gray-8)"}
|
||||
/>
|
||||
</Flex>
|
||||
);
|
||||
})}
|
||||
<Flex
|
||||
align="center"
|
||||
gap="1"
|
||||
style={{ cursor: "pointer" }}
|
||||
onClick={() => handleCopy(displayText, copyKey)}
|
||||
title={isCopied ? t("common.copied") : t("common.clickToCopy")}
|
||||
>
|
||||
<Text size="2">{displayText}</Text>
|
||||
<Icon
|
||||
icon={isCopied ? "lucide:check" : "lucide:copy"}
|
||||
width="12"
|
||||
height="12"
|
||||
color={isCopied ? "var(--green-9)" : "var(--gray-8)"}
|
||||
/>
|
||||
</Flex>
|
||||
);
|
||||
})()}
|
||||
@@ -427,66 +379,6 @@ export function ProxiesView({
|
||||
</Table.Body>
|
||||
</Table.Root>
|
||||
</div>
|
||||
{totalPages > 1 && (
|
||||
<Flex justify="between" align="center" pt="4" px="1">
|
||||
<Text size="2" color="gray">
|
||||
{page} / {totalPages}
|
||||
</Text>
|
||||
<Flex align="center" style={{ border: "1px solid var(--gray-6)", borderRadius: "var(--radius-3)", overflow: "hidden" }}>
|
||||
<button
|
||||
disabled={page === 1}
|
||||
onClick={() => setPage(page - 1)}
|
||||
style={{
|
||||
padding: "6px 10px",
|
||||
background: "none",
|
||||
border: "none",
|
||||
borderRight: "1px solid var(--gray-6)",
|
||||
cursor: page === 1 ? "not-allowed" : "pointer",
|
||||
opacity: page === 1 ? 0.4 : 1,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Icon icon="lucide:chevron-left" width="14" height="14" />
|
||||
</button>
|
||||
{Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
|
||||
<button
|
||||
key={p}
|
||||
onClick={() => setPage(p)}
|
||||
style={{
|
||||
padding: "6px 12px",
|
||||
background: p === page ? "var(--accent-9)" : "none",
|
||||
color: p === page ? "white" : "inherit",
|
||||
border: "none",
|
||||
borderRight: p === totalPages ? "none" : "1px solid var(--gray-6)",
|
||||
cursor: "pointer",
|
||||
fontSize: "var(--font-size-2)",
|
||||
fontWeight: p === page ? 600 : 400,
|
||||
}}
|
||||
>
|
||||
{p}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
disabled={page === totalPages}
|
||||
onClick={() => setPage(page + 1)}
|
||||
style={{
|
||||
padding: "6px 10px",
|
||||
background: "none",
|
||||
border: "none",
|
||||
borderLeft: "1px solid var(--gray-6)",
|
||||
cursor: page === totalPages ? "not-allowed" : "pointer",
|
||||
opacity: page === totalPages ? 0.4 : 1,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Icon icon="lucide:chevron-right" width="14" height="14" />
|
||||
</button>
|
||||
</Flex>
|
||||
</Flex>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useProxies } from "./useProxies";
|
||||
import { ProxiesView } from "./ProxiesPage.view";
|
||||
|
||||
export function ProxiesPage() {
|
||||
const { proxies, loading, refreshing, stats, deleteProxy, toggleStatus, refreshProxies, page, setPage, totalPages, search, setSearch } = useProxies();
|
||||
const { proxies, loading, refreshing, stats, deleteProxy, toggleStatus, refreshProxies } = useProxies();
|
||||
|
||||
return (
|
||||
<ProxiesView
|
||||
@@ -13,11 +13,6 @@ export function ProxiesPage() {
|
||||
onDeleteProxy={deleteProxy}
|
||||
onToggleStatus={toggleStatus}
|
||||
refreshProxies={refreshProxies}
|
||||
page={page}
|
||||
setPage={setPage}
|
||||
totalPages={totalPages}
|
||||
search={search}
|
||||
setSearch={setSearch}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -29,21 +29,8 @@ export function useProxies() {
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [totalItems, setTotalItems] = useState(0);
|
||||
const [onlineCount, setOnlineCount] = useState(0);
|
||||
const [search, setSearch] = useState("");
|
||||
const [debouncedSearch, setDebouncedSearch] = useState("");
|
||||
const PER_PAGE = 10;
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setDebouncedSearch(search), 300);
|
||||
return () => clearTimeout(timer);
|
||||
}, [search]);
|
||||
|
||||
useEffect(() => {
|
||||
setPage(1);
|
||||
}, [debouncedSearch]);
|
||||
|
||||
const fetchProxies = useCallback(
|
||||
async (isRefresh = false) => {
|
||||
try {
|
||||
@@ -53,24 +40,12 @@ export function useProxies() {
|
||||
setRefreshing(true);
|
||||
}
|
||||
|
||||
const searchFilter = debouncedSearch
|
||||
? `name ~ "${debouncedSearch}" || localIP ~ "${debouncedSearch}" || remotePort ~ "${debouncedSearch}"`
|
||||
: "";
|
||||
|
||||
const [result, onlineResult] = await Promise.all([
|
||||
pb.collection("fh_proxies").getList<Proxy>(page, PER_PAGE, {
|
||||
sort: "-created",
|
||||
expand: "serverId",
|
||||
filter: searchFilter,
|
||||
}),
|
||||
pb.collection("fh_proxies").getList(1, 1, {
|
||||
filter: 'bootStatus = "online"',
|
||||
}),
|
||||
]);
|
||||
const result = await pb.collection("fh_proxies").getList<Proxy>(page, PER_PAGE, {
|
||||
sort: "-created",
|
||||
expand: "serverId",
|
||||
});
|
||||
setProxies(result.items);
|
||||
setTotalPages(result.totalPages);
|
||||
setTotalItems(result.totalItems);
|
||||
setOnlineCount(onlineResult.totalItems);
|
||||
initializedRef.current = true;
|
||||
} catch (err) {
|
||||
if ((err as Record<string, unknown>)?.isAbort) return;
|
||||
@@ -80,7 +55,7 @@ export function useProxies() {
|
||||
setRefreshing(false);
|
||||
}
|
||||
},
|
||||
[page, debouncedSearch]
|
||||
[page]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -129,9 +104,9 @@ export function useProxies() {
|
||||
};
|
||||
|
||||
const stats = {
|
||||
total: totalItems,
|
||||
online: onlineCount,
|
||||
offline: totalItems - onlineCount,
|
||||
total: proxies.length,
|
||||
online: proxies.filter((p) => p.bootStatus === "online").length,
|
||||
offline: proxies.filter((p) => p.bootStatus === "offline").length,
|
||||
};
|
||||
|
||||
const isEmpty = !loading && proxies.length === 0;
|
||||
@@ -147,8 +122,6 @@ export function useProxies() {
|
||||
setPage,
|
||||
totalPages,
|
||||
stats,
|
||||
search,
|
||||
setSearch,
|
||||
refreshProxies: () => fetchProxies(true),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
import {
|
||||
Badge,
|
||||
Box,
|
||||
Button,
|
||||
Card,
|
||||
Callout,
|
||||
Flex,
|
||||
Spinner,
|
||||
Table,
|
||||
Text,
|
||||
TextField,
|
||||
SegmentedControl,
|
||||
Progress,
|
||||
} from "@radix-ui/themes";
|
||||
import { useState, useEffect } from "react";
|
||||
import { Icon } from "@iconify/react";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PageHeader } from "../../components/PageHeader";
|
||||
import type { Device, LocalNetwork, PortResult, ScanMode, ScanStep } from "./useScanner";
|
||||
|
||||
interface ScannerViewProps {
|
||||
step: ScanStep;
|
||||
discovering: boolean;
|
||||
devices: Device[];
|
||||
localNetworks: LocalNetwork[];
|
||||
selectedDevice: Device | null;
|
||||
scanning: boolean;
|
||||
portResults: PortResult[];
|
||||
scanDone: boolean;
|
||||
error: string | null;
|
||||
scanMode: ScanMode;
|
||||
setScanMode: (m: ScanMode) => void;
|
||||
customPorts: string;
|
||||
setCustomPorts: (v: string) => void;
|
||||
totalPorts: number;
|
||||
discoverDevices: () => void;
|
||||
selectDevice: (device: Device) => void;
|
||||
startPortScan: () => void;
|
||||
stopScan: () => void;
|
||||
backToDiscover: () => void;
|
||||
}
|
||||
|
||||
export function ScannerView({
|
||||
step,
|
||||
discovering,
|
||||
devices,
|
||||
localNetworks,
|
||||
selectedDevice,
|
||||
scanning,
|
||||
portResults,
|
||||
scanDone,
|
||||
error,
|
||||
scanMode,
|
||||
setScanMode,
|
||||
customPorts,
|
||||
setCustomPorts,
|
||||
totalPorts,
|
||||
discoverDevices,
|
||||
selectDevice,
|
||||
startPortScan,
|
||||
stopScan,
|
||||
backToDiscover,
|
||||
}: ScannerViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setMounted(true), 100);
|
||||
return () => clearTimeout(timer);
|
||||
}, []);
|
||||
|
||||
const openPorts = portResults.filter((r) => r.open);
|
||||
const scannedCount = portResults.length;
|
||||
const progressPct = totalPorts > 0 ? Math.round((scannedCount / totalPorts) * 100) : 0;
|
||||
|
||||
return (
|
||||
<Flex direction="column" gap="5" className="flex flex-1 flex-col">
|
||||
<PageHeader
|
||||
title={t("scanner.title")}
|
||||
description={t("scanner.description")}
|
||||
visible={mounted}
|
||||
/>
|
||||
|
||||
<AnimatePresence>
|
||||
{error && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -8 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -8 }}
|
||||
>
|
||||
<Callout.Root color="red">
|
||||
<Callout.Icon>
|
||||
<Icon icon="lucide:alert-circle" width="16" height="16" />
|
||||
</Callout.Icon>
|
||||
<Callout.Text>{error}</Callout.Text>
|
||||
</Callout.Root>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
{/* ── Step 1: Device Discovery ── */}
|
||||
{step === "discover" && (
|
||||
<motion.div
|
||||
key="discover"
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -16 }}
|
||||
>
|
||||
<Flex direction="column" gap="4">
|
||||
<Card>
|
||||
<Flex direction="column" gap="3" p="2">
|
||||
<Flex align="center" gap="2">
|
||||
<Icon icon="lucide:wifi" width="20" height="20" style={{ color: "var(--accent-9)" }} />
|
||||
<Text size="3" weight="bold">{t("scanner.step1Title")}</Text>
|
||||
</Flex>
|
||||
<Text size="2" color="gray">{t("scanner.step1Desc")}</Text>
|
||||
|
||||
{localNetworks.length > 0 && (
|
||||
<Flex gap="2" wrap="wrap">
|
||||
{localNetworks.map((n) => (
|
||||
<Badge key={n.cidr} variant="outline" color="blue">
|
||||
<Icon icon="lucide:ethernet-port" width="12" height="12" />
|
||||
{n.interface} · {n.cidr} · {n.hosts} {t("scanner.hosts")}
|
||||
</Badge>
|
||||
))}
|
||||
</Flex>
|
||||
)}
|
||||
|
||||
<Button onClick={discoverDevices} disabled={discovering} style={{ alignSelf: "flex-start" }}>
|
||||
{discovering ? (
|
||||
<Flex align="center" gap="2">
|
||||
<Spinner size="1" />
|
||||
{t("scanner.discovering")}
|
||||
</Flex>
|
||||
) : (
|
||||
<Flex align="center" gap="2">
|
||||
<Icon icon="lucide:search" width="16" height="16" />
|
||||
{t("scanner.discoverBtn")}
|
||||
</Flex>
|
||||
)}
|
||||
</Button>
|
||||
</Flex>
|
||||
</Card>
|
||||
|
||||
<AnimatePresence>
|
||||
{devices.length > 0 && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, height: 0 }}
|
||||
animate={{ opacity: 1, height: "auto" }}
|
||||
exit={{ opacity: 0, height: 0 }}
|
||||
>
|
||||
<Card>
|
||||
<Flex direction="column" gap="3" p="2">
|
||||
<Flex align="center" justify="between">
|
||||
<Flex align="center" gap="2">
|
||||
<Icon icon="lucide:monitor-check" width="18" height="18" style={{ color: "var(--green-9)" }} />
|
||||
<Text size="3" weight="bold">
|
||||
{t("scanner.devicesFound", { count: devices.length })}
|
||||
</Text>
|
||||
</Flex>
|
||||
<Badge color="green" variant="soft">
|
||||
{devices.length} {t("scanner.hosts")}
|
||||
</Badge>
|
||||
</Flex>
|
||||
|
||||
<Table.Root variant="surface">
|
||||
<Table.Header>
|
||||
<Table.Row>
|
||||
<Table.ColumnHeaderCell>{t("scanner.ipAddress")}</Table.ColumnHeaderCell>
|
||||
<Table.ColumnHeaderCell>{t("scanner.macAddress")}</Table.ColumnHeaderCell>
|
||||
<Table.ColumnHeaderCell>{t("scanner.hostname")}</Table.ColumnHeaderCell>
|
||||
<Table.ColumnHeaderCell>{t("scanner.iface")}</Table.ColumnHeaderCell>
|
||||
<Table.ColumnHeaderCell>{t("common.actions")}</Table.ColumnHeaderCell>
|
||||
</Table.Row>
|
||||
</Table.Header>
|
||||
<Table.Body>
|
||||
{devices.map((device) => (
|
||||
<motion.tr
|
||||
key={device.ip}
|
||||
initial={{ opacity: 0, x: -8 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
>
|
||||
<Table.Cell>
|
||||
<Flex align="center" gap="2">
|
||||
<Icon icon="lucide:network" width="14" height="14" style={{ color: "var(--accent-9)" }} />
|
||||
<Text size="2" weight="medium" style={{ fontFamily: "monospace" }}>
|
||||
{device.ip}
|
||||
</Text>
|
||||
</Flex>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<Text size="2" color="gray" style={{ fontFamily: "monospace" }}>
|
||||
{device.mac || "—"}
|
||||
</Text>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<Text size="2" color="gray">{device.hostname || "—"}</Text>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<Badge variant="outline" size="1">{device.interface || "—"}</Badge>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<Button size="1" variant="soft" onClick={() => selectDevice(device)}>
|
||||
<Icon icon="lucide:scan-line" width="14" height="14" />
|
||||
{t("scanner.scanPorts")}
|
||||
</Button>
|
||||
</Table.Cell>
|
||||
</motion.tr>
|
||||
))}
|
||||
</Table.Body>
|
||||
</Table.Root>
|
||||
</Flex>
|
||||
</Card>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</Flex>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* ── Step 2: Port Scanner ── */}
|
||||
{step === "scan" && selectedDevice && (
|
||||
<motion.div
|
||||
key="scan"
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -16 }}
|
||||
>
|
||||
<Flex direction="column" gap="4">
|
||||
{/* Target + controls */}
|
||||
<Card>
|
||||
<Flex direction="column" gap="4" p="2">
|
||||
{/* Row 1: back / target / start-stop */}
|
||||
<Flex align="center" justify="between" wrap="wrap" gap="3">
|
||||
<Flex align="center" gap="3">
|
||||
<Button variant="ghost" size="2" onClick={backToDiscover}>
|
||||
<Icon icon="lucide:arrow-left" width="16" height="16" />
|
||||
{t("common.back")}
|
||||
</Button>
|
||||
<Flex align="center" gap="2">
|
||||
<Icon icon="lucide:target" width="20" height="20" style={{ color: "var(--accent-9)" }} />
|
||||
<Text size="3" weight="bold">
|
||||
{t("scanner.scanTarget")}: {selectedDevice.ip}
|
||||
</Text>
|
||||
{selectedDevice.hostname && (
|
||||
<Badge variant="soft" color="blue">{selectedDevice.hostname}</Badge>
|
||||
)}
|
||||
</Flex>
|
||||
</Flex>
|
||||
|
||||
<Flex align="center" gap="2">
|
||||
{scanning ? (
|
||||
<Button color="red" variant="soft" onClick={stopScan}>
|
||||
<Icon icon="lucide:square" width="14" height="14" />
|
||||
{t("scanner.stop")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button onClick={startPortScan}>
|
||||
<Icon icon="lucide:play" width="14" height="14" />
|
||||
{t("scanner.startScan")}
|
||||
</Button>
|
||||
)}
|
||||
</Flex>
|
||||
</Flex>
|
||||
|
||||
{/* Row 2: mode selector */}
|
||||
<Flex align="center" gap="3" wrap="wrap">
|
||||
<Text size="2" color="gray" style={{ whiteSpace: "nowrap" }}>
|
||||
{t("scanner.mode")}:
|
||||
</Text>
|
||||
<SegmentedControl.Root
|
||||
value={scanMode}
|
||||
onValueChange={(v) => setScanMode(v as ScanMode)}
|
||||
disabled={scanning}
|
||||
size="2"
|
||||
>
|
||||
<SegmentedControl.Item value="common">
|
||||
<Flex align="center" gap="1">
|
||||
<Icon icon="lucide:star" width="13" height="13" />
|
||||
{t("scanner.modeCommon")}
|
||||
</Flex>
|
||||
</SegmentedControl.Item>
|
||||
<SegmentedControl.Item value="custom">
|
||||
<Flex align="center" gap="1">
|
||||
<Icon icon="lucide:list" width="13" height="13" />
|
||||
{t("scanner.modeCustom")}
|
||||
</Flex>
|
||||
</SegmentedControl.Item>
|
||||
<SegmentedControl.Item value="full">
|
||||
<Flex align="center" gap="1">
|
||||
<Icon icon="lucide:infinity" width="13" height="13" />
|
||||
{t("scanner.modeFull")}
|
||||
</Flex>
|
||||
</SegmentedControl.Item>
|
||||
</SegmentedControl.Root>
|
||||
</Flex>
|
||||
|
||||
{/* Row 3: custom ports input (only when mode=custom) */}
|
||||
{scanMode === "custom" && (
|
||||
<Flex align="center" gap="2" wrap="wrap">
|
||||
<Box style={{ flex: 1, minWidth: 200, maxWidth: 420 }}>
|
||||
<TextField.Root
|
||||
placeholder={t("scanner.customPortsPlaceholder")}
|
||||
value={customPorts}
|
||||
onChange={(e) => setCustomPorts(e.target.value)}
|
||||
disabled={scanning}
|
||||
/>
|
||||
</Box>
|
||||
<Text size="1" color="gray">{t("scanner.customPortsHint")}</Text>
|
||||
</Flex>
|
||||
)}
|
||||
|
||||
{/* Row 4: full-scan warning */}
|
||||
{scanMode === "full" && (
|
||||
<Callout.Root color="amber" size="1">
|
||||
<Callout.Icon>
|
||||
<Icon icon="lucide:triangle-alert" width="14" height="14" />
|
||||
</Callout.Icon>
|
||||
<Callout.Text>{t("scanner.fullScanWarning")}</Callout.Text>
|
||||
</Callout.Root>
|
||||
)}
|
||||
</Flex>
|
||||
</Card>
|
||||
|
||||
{/* Progress */}
|
||||
{(scanning || scannedCount > 0) && (
|
||||
<Flex direction="column" gap="2">
|
||||
<Flex align="center" justify="between" wrap="wrap" gap="2">
|
||||
<Flex align="center" gap="3">
|
||||
{scanning && <Spinner size="1" />}
|
||||
<Text size="2" color="gray">
|
||||
{t("scanner.scanned")}: {scannedCount}
|
||||
{totalPorts > 0 && ` / ${totalPorts}`}
|
||||
</Text>
|
||||
<Badge color="green" variant="soft">
|
||||
<Icon icon="lucide:unlock" width="12" height="12" />
|
||||
{t("scanner.openPorts")}: {openPorts.length}
|
||||
</Badge>
|
||||
{scanDone && (
|
||||
<Badge color="blue" variant="soft">
|
||||
<Icon icon="lucide:check" width="12" height="12" />
|
||||
{t("scanner.complete")}
|
||||
</Badge>
|
||||
)}
|
||||
</Flex>
|
||||
{totalPorts > 0 && (
|
||||
<Text size="1" color="gray">{progressPct}%</Text>
|
||||
)}
|
||||
</Flex>
|
||||
|
||||
{totalPorts > 0 && (
|
||||
<Progress value={progressPct} size="1" />
|
||||
)}
|
||||
</Flex>
|
||||
)}
|
||||
|
||||
{/* Results */}
|
||||
<AnimatePresence>
|
||||
{openPorts.length > 0 && (
|
||||
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
|
||||
<Card>
|
||||
<Table.Root variant="surface">
|
||||
<Table.Header>
|
||||
<Table.Row>
|
||||
<Table.ColumnHeaderCell>{t("scanner.port")}</Table.ColumnHeaderCell>
|
||||
<Table.ColumnHeaderCell>{t("scanner.status")}</Table.ColumnHeaderCell>
|
||||
<Table.ColumnHeaderCell>{t("scanner.service")}</Table.ColumnHeaderCell>
|
||||
</Table.Row>
|
||||
</Table.Header>
|
||||
<Table.Body>
|
||||
{[...openPorts]
|
||||
.sort((a, b) => a.port - b.port)
|
||||
.map((r) => (
|
||||
<motion.tr
|
||||
key={r.port}
|
||||
initial={{ opacity: 0, x: -8 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
>
|
||||
<Table.Cell>
|
||||
<Text size="2" weight="medium" style={{ fontFamily: "monospace" }}>
|
||||
{r.port}
|
||||
</Text>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<Badge color="green" variant="soft">
|
||||
<Icon icon="lucide:unlock" width="12" height="12" />
|
||||
{t("scanner.open")}
|
||||
</Badge>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<Text size="2" color="gray">{r.service || "—"}</Text>
|
||||
</Table.Cell>
|
||||
</motion.tr>
|
||||
))}
|
||||
</Table.Body>
|
||||
</Table.Root>
|
||||
</Card>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</Flex>
|
||||
</motion.div>
|
||||
)}
|
||||
</Flex>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { useScanner } from "./useScanner";
|
||||
import { ScannerView } from "./ScannerPage.view";
|
||||
|
||||
export function ScannerPage() {
|
||||
const state = useScanner();
|
||||
return <ScannerView {...state} />;
|
||||
}
|
||||
|
||||
export default ScannerPage;
|
||||
@@ -0,0 +1,161 @@
|
||||
import { useState, useRef, useCallback } from "react";
|
||||
import { apiGet } from "../../lib/api";
|
||||
import pb from "../../lib/pocketbase";
|
||||
|
||||
export interface Device {
|
||||
ip: string;
|
||||
mac: string;
|
||||
hostname: string;
|
||||
interface: string;
|
||||
}
|
||||
|
||||
export interface LocalNetwork {
|
||||
interface: string;
|
||||
cidr: string;
|
||||
hosts: number;
|
||||
}
|
||||
|
||||
export interface PortResult {
|
||||
port: number;
|
||||
open: boolean;
|
||||
service: string;
|
||||
done?: boolean;
|
||||
}
|
||||
|
||||
export type ScanStep = "discover" | "scan";
|
||||
export type ScanMode = "common" | "custom" | "full";
|
||||
|
||||
const COMMON_PORT_COUNT = 23; // mirrors wellKnownPorts in service.go
|
||||
const FULL_PORT_COUNT = 65535;
|
||||
|
||||
export function useScanner() {
|
||||
const [step, setStep] = useState<ScanStep>("discover");
|
||||
const [discovering, setDiscovering] = useState(false);
|
||||
const [devices, setDevices] = useState<Device[]>([]);
|
||||
const [localNetworks, setLocalNetworks] = useState<LocalNetwork[]>([]);
|
||||
const [selectedDevice, setSelectedDevice] = useState<Device | null>(null);
|
||||
const [scanning, setScanning] = useState(false);
|
||||
const [portResults, setPortResults] = useState<PortResult[]>([]);
|
||||
const [scanDone, setScanDone] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [scanMode, setScanMode] = useState<ScanMode>("common");
|
||||
const [customPorts, setCustomPorts] = useState("");
|
||||
const [totalPorts, setTotalPorts] = useState(0);
|
||||
const esRef = useRef<EventSource | null>(null);
|
||||
|
||||
const discoverDevices = useCallback(async () => {
|
||||
setDiscovering(true);
|
||||
setDevices([]);
|
||||
setError(null);
|
||||
try {
|
||||
const [netRes, discoverRes] = await Promise.all([
|
||||
apiGet("/api/scanner/interfaces"),
|
||||
apiGet("/api/scanner/discover"),
|
||||
]);
|
||||
if (netRes.ok) {
|
||||
const nets: LocalNetwork[] = await netRes.json();
|
||||
setLocalNetworks(nets ?? []);
|
||||
}
|
||||
if (!discoverRes.ok) {
|
||||
const body = await discoverRes.json().catch(() => ({}));
|
||||
throw new Error(body.error || `HTTP ${discoverRes.status}`);
|
||||
}
|
||||
const data: Device[] = await discoverRes.json();
|
||||
setDevices(data ?? []);
|
||||
} catch (e: unknown) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setDiscovering(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const selectDevice = useCallback((device: Device) => {
|
||||
setSelectedDevice(device);
|
||||
setPortResults([]);
|
||||
setScanDone(false);
|
||||
setStep("scan");
|
||||
}, []);
|
||||
|
||||
const startPortScan = useCallback(() => {
|
||||
if (!selectedDevice) return;
|
||||
esRef.current?.close();
|
||||
|
||||
setPortResults([]);
|
||||
setScanDone(false);
|
||||
setScanning(true);
|
||||
setError(null);
|
||||
|
||||
const token = pb.authStore.token;
|
||||
const params = new URLSearchParams({ ip: selectedDevice.ip, token });
|
||||
|
||||
let total = COMMON_PORT_COUNT;
|
||||
if (scanMode === "full") {
|
||||
params.set("full", "true");
|
||||
total = FULL_PORT_COUNT;
|
||||
} else if (scanMode === "custom" && customPorts.trim()) {
|
||||
params.set("ports", customPorts.trim());
|
||||
total = customPorts.split(",").filter((p) => p.trim()).length;
|
||||
}
|
||||
setTotalPorts(total);
|
||||
|
||||
const es = new EventSource(`/api/scanner/ports/stream?${params.toString()}`);
|
||||
esRef.current = es;
|
||||
|
||||
es.onmessage = (ev) => {
|
||||
try {
|
||||
const result: PortResult = JSON.parse(ev.data);
|
||||
if (result.done) {
|
||||
setScanDone(true);
|
||||
setScanning(false);
|
||||
es.close();
|
||||
return;
|
||||
}
|
||||
setPortResults((prev) => [...prev, result]);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
es.onerror = () => {
|
||||
setScanning(false);
|
||||
setScanDone(true);
|
||||
es.close();
|
||||
};
|
||||
}, [selectedDevice, scanMode, customPorts]);
|
||||
|
||||
const stopScan = useCallback(() => {
|
||||
esRef.current?.close();
|
||||
setScanning(false);
|
||||
setScanDone(true);
|
||||
}, []);
|
||||
|
||||
const backToDiscover = useCallback(() => {
|
||||
stopScan();
|
||||
setStep("discover");
|
||||
setSelectedDevice(null);
|
||||
setPortResults([]);
|
||||
setScanDone(false);
|
||||
}, [stopScan]);
|
||||
|
||||
return {
|
||||
step,
|
||||
discovering,
|
||||
devices,
|
||||
localNetworks,
|
||||
selectedDevice,
|
||||
scanning,
|
||||
portResults,
|
||||
scanDone,
|
||||
error,
|
||||
scanMode,
|
||||
setScanMode,
|
||||
customPorts,
|
||||
setCustomPorts,
|
||||
totalPorts,
|
||||
discoverDevices,
|
||||
selectDevice,
|
||||
startPortScan,
|
||||
stopScan,
|
||||
backToDiscover,
|
||||
};
|
||||
}
|
||||
@@ -474,26 +474,17 @@ export function ServerDetailPage() {
|
||||
</Flex>
|
||||
);
|
||||
}
|
||||
const remotePort = proxy.remotePort || "";
|
||||
if (!remotePort) return <Text size="2" color="gray">-</Text>;
|
||||
const items = proxy.proxyType === "tcp" || proxy.proxyType === "udp"
|
||||
? [remotePort, server?.serverAddr ? `${server.serverAddr}:${remotePort}` : ""].filter(Boolean)
|
||||
: [remotePort];
|
||||
const displayText = proxy.remotePort || "-";
|
||||
if (displayText === "-") return <Text size="2" color="gray">-</Text>;
|
||||
const copyKey = `${proxy.id}-port`;
|
||||
const isCopied = copiedId === copyKey;
|
||||
return (
|
||||
<Flex direction="column" gap="1">
|
||||
{items.map((item, i) => {
|
||||
const copyKey = `${proxy.id}-remote-${i}`;
|
||||
const isCopied = copiedId === copyKey;
|
||||
return (
|
||||
<Flex key={item} align="center" gap="1" style={{ cursor: "pointer" }}
|
||||
onClick={() => handleCopy(item, copyKey)}
|
||||
title={isCopied ? t("common.copied") : t("common.clickToCopy")}>
|
||||
<Text size="2">{item}</Text>
|
||||
<Icon icon={isCopied ? "lucide:check" : "lucide:copy"} width="12" height="12"
|
||||
color={isCopied ? "var(--green-9)" : "var(--gray-8)"} />
|
||||
</Flex>
|
||||
);
|
||||
})}
|
||||
<Flex align="center" gap="1" style={{ cursor: "pointer" }}
|
||||
onClick={() => handleCopy(displayText, copyKey)}
|
||||
title={isCopied ? t("common.copied") : t("common.clickToCopy")}>
|
||||
<Text size="2">{displayText}</Text>
|
||||
<Icon icon={isCopied ? "lucide:check" : "lucide:copy"} width="12" height="12"
|
||||
color={isCopied ? "var(--green-9)" : "var(--gray-8)"} />
|
||||
</Flex>
|
||||
);
|
||||
})()}
|
||||
|
||||
@@ -33,9 +33,6 @@ interface ServersViewProps {
|
||||
search: string;
|
||||
setSearch: (value: string) => void;
|
||||
refreshServers: () => void;
|
||||
page: number;
|
||||
setPage: (page: number) => void;
|
||||
totalPages: number;
|
||||
}
|
||||
|
||||
export function ServersView({
|
||||
@@ -48,9 +45,6 @@ export function ServersView({
|
||||
search,
|
||||
setSearch,
|
||||
refreshServers,
|
||||
page,
|
||||
setPage,
|
||||
totalPages,
|
||||
}: ServersViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
@@ -417,65 +411,6 @@ export function ServersView({
|
||||
</Table.Body>
|
||||
</Table.Root>
|
||||
</div>
|
||||
{totalPages > 1 && (
|
||||
<Flex justify="between" align="center" pt="4" px="1">
|
||||
<Text size="2" color="gray">
|
||||
{page} / {totalPages}
|
||||
</Text>
|
||||
<Flex align="center" style={{ border: "1px solid var(--gray-6)", borderRadius: "var(--radius-3)", overflow: "hidden" }}>
|
||||
<button
|
||||
disabled={page === 1}
|
||||
onClick={() => setPage(page - 1)}
|
||||
style={{
|
||||
padding: "6px 10px",
|
||||
background: "none",
|
||||
border: "none",
|
||||
borderRight: "1px solid var(--gray-6)",
|
||||
cursor: page === 1 ? "not-allowed" : "pointer",
|
||||
opacity: page === 1 ? 0.4 : 1,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Icon icon="lucide:chevron-left" width="14" height="14" />
|
||||
</button>
|
||||
{Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
|
||||
<button
|
||||
key={p}
|
||||
onClick={() => setPage(p)}
|
||||
style={{
|
||||
padding: "6px 12px",
|
||||
background: p === page ? "var(--accent-9)" : "none",
|
||||
color: p === page ? "white" : "inherit",
|
||||
border: "none",
|
||||
borderRight: p === totalPages ? "none" : "1px solid var(--gray-6)",
|
||||
cursor: "pointer",
|
||||
fontSize: "var(--font-size-2)",
|
||||
fontWeight: p === page ? 600 : 400,
|
||||
}}
|
||||
>
|
||||
{p}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
disabled={page === totalPages}
|
||||
onClick={() => setPage(page + 1)}
|
||||
style={{
|
||||
padding: "6px 10px",
|
||||
background: "none",
|
||||
border: "none",
|
||||
borderLeft: "1px solid var(--gray-6)",
|
||||
cursor: page === totalPages ? "not-allowed" : "pointer",
|
||||
opacity: page === totalPages ? 0.4 : 1,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Icon icon="lucide:chevron-right" width="14" height="14" />
|
||||
</button>
|
||||
</Flex>
|
||||
</Flex>
|
||||
)}
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
Reference in new issue
Block a user