94 Commits

Author SHA1 Message Date
fdc6f687f3 Keep verified Gateway active through transient discovery failures
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 16s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-31 10:57:00 +03:00
c6d3fd39fb Add stop confirmation to client power action
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 17s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-15 15:25:10 +03:00
b4adcce26a Switch mac client install to tarball download
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-15 12:13:12 +03:00
7b94f2dee4 Refine server health loading indicator and bump Harbor versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-15 00:22:57 +03:00
7f276b0404 Refine server picker layout and bump Harbor versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 16s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-15 00:09:50 +03:00
c2f9623394 Refine server picker layout and bump Harbor versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-14 23:55:10 +03:00
bc3cc12f69 Bump Harbor versions and tighten server picker layout
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-14 23:06:29 +03:00
8139543e9a Refine server picker ping labels and layout
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-14 22:53:06 +03:00
162ef861d7 Simplify client overview access controls and layout
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-14 22:06:38 +03:00
e5a69dcb73 Bump Harbor clients and clarify disabled local rules
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 18s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-14 21:55:37 +03:00
a37c211c42 Raise Harbor versions and move secondary menus to the right rail
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-14 21:49:48 +03:00
f629309f32 Bump Harbor versions and surface gateway mode in overview
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-13 20:32:59 +03:00
56f5e408e3 Handle rejected subscriptions and add local client compose
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-13 20:23:37 +03:00
8c19f2cba9 Remove initial server health check and bump Harbor versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 12s
2026-07-13 13:36:56 +03:00
90447de0aa Polish server health checking feedback and bump Harbor versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 16s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-12 19:14:00 +03:00
5874df2fce Add initial server health check and update Harbor versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 18:49:45 +03:00
d551d41b71 Keep the server picker simple by default
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 16:30:53 +03:00
9a539409f0 Improve server picker health state handling and bump Harbor versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 15:31:41 +03:00
0480e617cd Bump Harbor versions and adjust subscribed desktop layout
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 16s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 15:22:18 +03:00
77eaed8d90 Align client panel desktop spacing and bump Harbor versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 14:58:55 +03:00
e8c1c9d403 Bump Harbor versions and add desktop subscription spacing
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-12 14:52:43 +03:00
12c1b128f8 Bump Harbor client versions and pin form content alignment
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-12 14:48:07 +03:00
6bd51dc8fb Raise client layout version and add subscription form height cap
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-12 14:41:47 +03:00
fca3c0b705 Refine server picker toggle and bump Harbor versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 14:31:34 +03:00
d9745e9aed Add simple server picker mode with version bump
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 14:13:42 +03:00
57330f1c78 Refactor server picker and limit ping requests
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 13:42:22 +03:00
24fda3e34e Improve client accessibility and bump Harbor versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-12 13:24:05 +03:00
5b3d288405 Bump Harbor versions and refine disabled local rules toggle
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 19s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-12 13:09:56 +03:00
2a71466670 Refine client panel layout and bump Harbor versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 13s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-12 13:01:45 +03:00
2d1d89911e Animate Harbor brand swap arrow and bump client versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-12 12:47:37 +03:00
394fceac15 Bump Harbor client versions and refine mode swap animation
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-12 12:44:45 +03:00
c40f465708 Bump Harbor versions and refine mode swap animation
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 12:42:35 +03:00
ba1e53a824 Bump Harbor versions and refine mode swap arrow animation
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 12:38:50 +03:00
1fe13703eb Bump Harbor client versions and refine arrow reveal animation
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 12:36:56 +03:00
17577ea460 Bump Harbor client versions and tighten gateway mode animation
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 12:33:44 +03:00
2a214fc28b Clarify and strengthen state invariant tests
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 13s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-12 12:22:59 +03:00
5e33360c92 Bump Harbor versions and refine gateway mode transition
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 13s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 12:09:31 +03:00
ef33ad9c84 Bump Harbor client versions and refine brand mode transition
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 21s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 12:04:00 +03:00
267afc5c7e Introduce stable server IDs for subscription state
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 11:59:22 +03:00
005c7a101b Refine subscription import and refresh flow
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 13s
2026-07-12 11:18:33 +03:00
ba15a25c89 Refine local rule delete animation and bump Harbor versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 16s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 11:00:54 +03:00
d4897e5dcf Bump Harbor versions and soften rule editor dimming animation
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 16s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-12 01:48:24 +03:00
7182bc2c1a Bump Harbor versions and add delete dimming animation
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-12 01:45:47 +03:00
8db9d30828 Refine rule editor exit animations and bump Harbor versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 00:28:34 +03:00
c56f51e07b Add delete strike overlay and bump Harbor versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 16s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 00:23:19 +03:00
d6ba05ac7d Refine client delete animation and local rule button styling
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 00:21:21 +03:00
4ed25301db Refine rule delete animation and bump Harbor versions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 00:17:17 +03:00
d49a1f6837 Raise delete strike overlay above row content
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 19s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-12 00:14:54 +03:00
56304514ff Bump Harbor versions and refine delete strike styling
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 22s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-12 00:10:25 +03:00
4519577295 Bump Harbor versions and refine delete strike styling
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-12 00:06:14 +03:00
87cd83f89a Refine client rule delete strike animation
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 16s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-11 23:57:00 +03:00
fbbd6e40b4 Add delete strike animation for local rules
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 28s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-11 23:54:21 +03:00
483fce55f3 Update Harbor Gateway UI for direct routing mode
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 18s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-11 23:47:45 +03:00
62d2044dc1 Bump Harbor versions and raise open rule row stacking
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 13s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-11 23:41:02 +03:00
f135ade43b Track applied route rules separately from pending edits
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 16s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-11 23:07:20 +03:00
65bf88bf41 Add shared critical confirmation popup for destructive actions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 23s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-11 22:50:51 +03:00
387cc273e8 Improve local rules persistence and dirty-state handling
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 20s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-11 22:37:04 +03:00
1304a22f1f Add enabled local routing rules and gateway version reporting
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 13s
2026-07-11 22:14:43 +03:00
a0c66edb02 Add local routing rules to Harbor
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 17s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-11 21:52:03 +03:00
306a9b8ced Bump Harbor versions and add direct .ru routing
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 12s
2026-07-11 21:36:04 +03:00
7a6f9a26ac Add runtime version reporting and display
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 16s
Build and Deploy Gateway / deploy (push) Successful in 12s
2026-07-11 21:24:18 +03:00
c9223aa3a9 Harden server state and config persistence
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 16s
Build and Deploy Gateway / deploy (push) Successful in 6s
2026-07-11 21:07:11 +03:00
e6b21ed8a9 Copy shared sources into client Docker build
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 12s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-11 20:58:43 +03:00
74660d915f Track client operations and show inline progress
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 16s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-11 20:55:20 +03:00
9da4fef1f0 Unify Harbor error handling across server and client
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 15s
Build and Deploy Gateway / deploy (push) Successful in 12s
2026-07-11 20:38:41 +03:00
457dd912d1 Bypass bridge traffic in TProxy and simplify subscription refresh
Some checks failed
Build and Deploy Gateway / build-and-push (push) Failing after 1m12s
Build and Deploy Gateway / deploy (push) Has been skipped
2026-07-11 19:48:04 +03:00
198669694c Handle stale sync state in client UI
Some checks failed
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Failing after 1m21s
2026-07-11 19:31:35 +03:00
a775d8456a Ignore local workpack roadmap workspace
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 11s
Build and Deploy Gateway / deploy (push) Successful in 7s
2026-07-11 19:18:50 +03:00
40f73ee98c Include shared server modules in runtime images
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 18s
Build and Deploy Gateway / deploy (push) Successful in 12s
2026-07-11 19:02:27 +03:00
e81a48a5b1 Persist operation state in server and reuse returned snapshots
Some checks failed
Build and Deploy Gateway / build-and-push (push) Successful in 16s
Build and Deploy Gateway / deploy (push) Failing after 1s
2026-07-11 18:59:14 +03:00
b0b9da51b6 Split gateway control and dataplane into separate services
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 13s
Build and Deploy Gateway / deploy (push) Successful in 12s
2026-07-11 17:52:48 +03:00
4b326c5e99 Refine VPN client design guidance for mode-aware motion
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 11s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 16:51:41 +03:00
0bf7d2ee30 Refresh Harbor docs and subscription controls
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 16:42:03 +03:00
b53cd08dcc Rename client app to Harbor Connect and refresh state animations
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 16:24:28 +03:00
edad26d978 Refresh Harbor Gateway branding assets and accent styling
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 13s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 16:15:54 +03:00
322f5a125b Polish client duration and tooltip interactions
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 13s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 16:12:09 +03:00
85053f9948 Add ambient motion to harbor mode branding
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 13s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 16:06:25 +03:00
9efd446d4e Refine Harbor brand mode hover animation
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 16:02:49 +03:00
bfc85c3056 Add smooth transform transition to harbor mode swap icons
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 13s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 15:59:09 +03:00
89feffd0b7 Refine Harbor mode swap icon animation
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 12s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 15:56:02 +03:00
aa54be9c9b Refine Harbor mode swap and client delete modal animations
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 13s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 15:52:56 +03:00
befd41933d Refine Harbor delete flow and gateway affordances
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 15:46:15 +03:00
b389664824 Refine client accent styling with dynamic harbor colors
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 12s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 15:39:30 +03:00
d5a42d8b7b Add Harbor mode tooltip on hover and focus
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 13s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 15:28:42 +03:00
e6bcdc9c62 Refine harbor brand mode swap positioning and styling
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 13s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 15:24:23 +03:00
a58fb26e4f Accept 16-character subscription secrets for gateway presence
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 12s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 15:18:22 +03:00
0ab912c64c Add gateway auto toggle for client mode
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 13s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 15:17:07 +03:00
51312d51cd Add Harbor Gateway auto-detection for client routing
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 13s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 15:02:33 +03:00
0a1aa8aed3 Add subscription validation and first-run onboarding reveal
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 16s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 14:13:39 +03:00
84efbe7450 Rename product to Harbor and refine connection timer
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 12s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 13:20:32 +03:00
42c15df8c9 Close client instructions panel on outside click
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 9s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 12:36:30 +03:00
fa3b455fab Refine VPN client instructions and subscription refresh flow
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 12:34:14 +03:00
6f565ded2e Rename gateway proxy labels and update window title
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 13s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 11:40:19 +03:00
41922ad30b Add direct gateway forwarding when VPN is off
All checks were successful
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 1s
2026-07-11 11:37:08 +03:00
90 changed files with 10263 additions and 749 deletions

View File

@@ -5,29 +5,37 @@ description: Design, implement, review, or refine the client-facing VPN interfac
# Design VPN Client UI
Preserve the repo's focused one-screen VPN client language: a centered primary action, quiet technical typography, restrained green state color, and motion that feels slow, fluid, and deliberate without moving layout.
Preserve the repo's focused one-screen VPN client language: a centered primary action, quiet technical typography, mode-specific accents, and motion that makes live state and interaction legible without moving layout.
## Workflow
1. Read `PRODUCT.md` and the complete client component and styles before editing.
2. Inspect the supplied screenshot or live UI. Trace the real DOM and state change that causes the visual issue.
2. Inspect supplied evidence and trace the real DOM and state change that causes the visual issue. Follow repository testing policy; do not launch manual or interactive visual testing unless the user explicitly requests it in the current prompt.
3. Read [visual-language.md](references/visual-language.md) for layout, hierarchy, color, and typography work.
4. Read [motion-and-interaction.md](references/motion-and-interaction.md) for animation, hover, refresh, input, copy, or state-transition work.
5. Reuse existing React state, CSS variables, formatters, and API paths. Prefer a narrow CSS/markup change over a new abstraction or dependency.
6. Keep geometry stable across every state. Reserve space before animating content.
7. Implement `prefers-reduced-motion` alongside every new animation.
8. Run `npm test`, `npm run build`, and `git diff --check`. Visually inspect when a runnable client is available.
8. Run `npm test`, `npm run build`, and `git diff --check`. Perform manual visual inspection only when explicitly requested.
## Non-negotiable decisions
- Keep the power action on the screen's central vertical axis. Place subscription content to its right without shifting that axis.
- Keep the power hit target generous while rendering only the icon, never a large enclosing green circle.
- Use green only for active, selected, successful, or refreshed states. Keep inactive power gray, including hover.
- Keep the power hit target generous while rendering only the icon, never a large enclosing accent circle.
- Drive every active accent from the current mode token: Connect is blue-green; Gateway is orange. Keep inactive power gray, including hover, and preserve semantic warning/error colors.
- Never let labels, timers, feedback, icons, progress, or server rows shift neighboring content.
- Animate state, opacity, blur, glow, color, filter, and transform. Do not animate layout properties.
- Let visible cycles finish. Never stop a spinner mid-turn or remount a list before its exit animation completes.
- Make live behavior visibly alive: running processes, changing values, mode changes, and interactive affordances should communicate through restrained motion instead of abrupt static replacement.
- Let every visible cycle finish and return to its resting coordinates before stopping. Never cancel a hover animation, spinner, or list exit at an arbitrary frame.
- Animate dynamic rows through complete enter and exit phases; keep a departing row mounted until its exit finishes, with immediate removal under reduced motion.
- Animate only what changed. Keep unchanged digits, labels, icons, and surrounding geometry stable.
- Keep tooltips outside transformed, rotating, glowing, or filtered controls. Show them quickly above the control as independent translucent cloud surfaces.
- Prefer one clear value over unsupported detail. Hide subscription fields the provider does not supply.
- Keep client UI compact and calm. Do not introduce dashboard cards, decorative chrome, or admin-console density.
- Do not use a modal, popup, or blocking backdrop unless the user explicitly asks for one. Prefer inline disclosure or a non-modal layer that preserves the main screen.
- When the owner explicitly chooses modal treatment for critical confirmations, reuse one accessible full-screen confirmation popup: blur and block the background, reveal from center, then stage text and actions.
- Avoid borders, divider lines, and framed regions by default. Build hierarchy with spacing, typography, subtle surface changes, light, and depth; use a line only when it communicates an essential state.
- In client-side editors, prefer flat text controls and accessible custom pickers over browser-native menus when the native surface breaks the visual language. Do not append another blank row until the current row is complete.
## Acceptance pass
@@ -35,6 +43,10 @@ Before handing off, verify:
- Power on/off is unmistakable without reading the label.
- Switching on/off preserves the exact positions of title, timer, and hint.
- Switching Connect/Gateway crossfades status in a fixed slot, changes the full accent palette, and clearly de-emphasizes data irrelevant to the active route.
- A timer tick animates only changed digits and reads as a soft flow, never a blink.
- Hover motion completes its current cycle and settles before stopping; ambient affordance motion remains subtle and infrequent.
- Tooltips remain upright, unfiltered, above adjacent content, and visually consistent across controls.
- Refresh and copy feedback cannot change element width or alignment.
- Server separators are compact and only slightly wider than their content.
- Repeated polling does not replay decorative list animations.

View File

@@ -4,6 +4,8 @@
Aim for fluid, slightly viscous motion: noticeable, calm, and complete. Avoid bounce, elastic easing, abrupt unmounts, decorative page choreography, or tiny effects too weak to communicate feedback.
Motion is functional feedback. If the system is running, refreshing, counting, switching route, or inviting interaction, show that activity with restrained movement. Do not animate every static decoration; animate the part that proves work, state, or affordance.
Use exponential ease-out curves such as `cubic-bezier(0.16, 1, 0.3, 1)` for arrivals. Typical timing:
- hover and press: 180-300 ms;
@@ -12,10 +14,19 @@ Use exponential ease-out curves such as `cubic-bezier(0.16, 1, 0.3, 1)` for arri
- numeric tween and progress: about 900 ms;
- copy feedback: about 800 ms;
- server cascade: 620-760 ms per row with 90-110 ms stagger.
- tooltip arrival: about 90-140 ms with almost no delay;
- ambient affordance hint: one small cycle roughly every 10 seconds.
## Cycle completion
- On pointer leave, do not snap an infinite hover animation or reverse it from the middle. Mark it for stopping, let the current iteration reach its original coordinates, then remove the animation.
- If the user re-enters before the iteration ends, clear the stop request and continue the same behavior.
- Separate state transforms from repeating motion when both affect one control. Animate a child for the cycle and its wrapper for durable state, or wait for `animationiteration` before clearing the animated class.
- Keep reduced-motion behavior immediate and static; never wait for an iteration event that will not fire.
## Power state
- Transition gray to green slowly when connecting and green to gray when disconnecting.
- Transition gray to the current mode accent slowly when connecting and back to gray when disconnecting.
- Animate icon color, localized light, and SVG shadow together.
- Let the light expand and brighten on enable, then contract and fade on disable.
- Keep the hit target and all surrounding geometry fixed.
@@ -24,12 +35,22 @@ Use exponential ease-out curves such as `cubic-bezier(0.16, 1, 0.3, 1)` for arri
## Changing text and numbers
- Put alternate labels in fixed-size slots.
- Reveal connection title, timer, and hint with opacity plus light blur, never vertical layout movement.
- Do not reanimate the timer every second; animate only its initial appearance.
- Reveal connection title, timer, and hint with overlapping fixed layers, opacity, and light blur, never vertical layout movement.
- Crossfade `VPN включён`, `Gateway подключён`, and disconnected copy in the same reserved slot when route state changes.
- Split changing numeric values into stable digits. On a tick such as `33 → 34`, keep the first `3` mounted and animate only `3 → 4` with a soft color/glow/blur flow; avoid low-opacity blinking or scaling the whole seconds value.
- Persist user-selected timer presentation locally and restore it on the next visit.
- Tween numeric traffic values from old to new with `requestAnimationFrame` or an equivalent stable counter.
- Animate progress width concurrently and add a brief glow that fully fades.
- Never translate changing numbers if the user asked for a fluid morph; use numerical interpolation, opacity, color, blur, and light.
## Mode switch affordance
- Treat the Connect/Gateway brand as one state control with a foreground label, a background label, and two independently colored direction arrows.
- On hover, move both labels continuously: let the foreground drift slightly down while the background rises toward it. Move the right arrow right and the left arrow left, then return; keep amplitudes small.
- When mode changes, swap the arrows' positions smoothly and bring the new label to the foreground without changing the brand's centered geometry.
- When hover ends, finish the current cycle at rest before stopping. Outside hover, replay one smaller cycle about every 10 seconds to hint that the control is clickable.
- Keep explanatory tooltip geometry tied to the mode-label-to-arrows span, not to the entire Harbor wordmark.
## Refresh
- Use a clean, symmetric SVG refresh icon aligned in the same flex row as its label.
@@ -37,7 +58,8 @@ Use exponential ease-out curves such as `cubic-bezier(0.16, 1, 0.3, 1)` for arri
- Update data immediately when it arrives; finishing the icon cycle must not delay the data.
- Manual refresh may replay meaningful data and server transitions.
- Background polling should update quietly and must not repeatedly replay the server cascade.
- On updated traffic, tween the number, advance the bar, and emit a visible but brief green flare.
- On updated traffic, tween the number, advance the bar, and emit a visible but brief mode-accent flare.
- Keep refresh tooltip outside the rotating button so it remains upright and unfiltered.
## Server cascade
@@ -47,14 +69,32 @@ Use exponential ease-out curves such as `cubic-bezier(0.16, 1, 0.3, 1)` for arri
- Disable pointer interaction during exit.
- Do not replay on ping updates or unrelated renders.
## Dynamic editors
- Reveal added rows with opacity, blur, and a small transform while keeping surrounding geometry predictable.
- Keep interactive add latency constant regardless of collection length. Never multiply an added row's delay by its index; use bounded staggering only for a one-time group reveal.
- Give removal its own exit state and keep the row mounted until `animationend`; then animate surviving rows into their new positions instead of letting layout snap. Under reduced motion, remove it immediately.
- Do not let repeated add actions accumulate unfinished rows. Disable add while any current row lacks its required value and explain the disabled state in a reserved hint slot.
- Track the editor's dirty draft against its open/save baseline. Guard Escape, outside click, navigation controls, Cancel, and page unload; use an inline discard confirmation for in-app exits.
- Replace browser-native dropdowns when their platform chrome conflicts with the client surface. Use an accessible custom listbox with trigger, selected state, outside-click and Escape closing, arrow-key navigation, and restored trigger focus.
- Let picker options appear as a short staggered cloud using opacity, blur, and transform. Avoid borders, shadows, raised cards, and layout-property animation.
## Subscription input
- Show the public domain while retaining the full URL internally.
- Disable browser autocomplete suggestions and neutralize autofill backgrounds.
- Hide the blinking caret when the paste-first interaction does not need it, while preserving keyboard input and focus outline.
- When an existing subscription is being edited and the field is idle, use the green underline as a five-second timeout indicator: start bright, fade to quiet, then restore display mode.
- When an existing subscription is being edited and the field is idle, use the mode-accent underline as a five-second timeout indicator: start bright, fade to quiet, then restore display mode.
- Pause the timeout once the user enters content.
- Close and clear unfinished input on outside click or Escape.
- Animate the trash lid independently on hover. Use the shared critical confirmation popup instead of a browser-native confirm dialog.
## Critical confirmation popup
- Reserve the blocking popup for explicit destructive or data-loss confirmation. It must cover the viewport, make the background inert, and use `alertdialog` with `aria-modal`.
- Fade and blur the backdrop first, resolve the popup from the center, then reveal its title, description, and actions in a short sequence.
- Put initial focus on the safe action, trap Tab within the popup, let Escape and backdrop click choose the safe action, and restore the invoking focus on close.
- Reuse the same component and motion vocabulary for every critical confirmation. Reduced motion presents the final state immediately.
## First-run initialization
@@ -68,7 +108,7 @@ Use exponential ease-out curves such as `cubic-bezier(0.16, 1, 0.3, 1)` for arri
- Keep protocol buttons fixed-size and centered.
- Copy the complete protocol URL while showing a shared address separately.
- Overlay green `Copied` feedback in the same fixed box; do not append text or move the label.
- Overlay mode-accent `Copied` feedback in the same fixed box; do not append text or move the label.
- Make feedback appear immediately, hold briefly, and fade fully before restoring the original label. Keep the whole cycle near 800 ms.
## Reduced motion

View File

@@ -11,7 +11,8 @@ Design for a macOS user glancing at a small VPN control surface in a quiet deskt
- Build the left flow vertically: power icon, stable connection copy, proxy address, copy actions.
- Place subscription identity, usage, expiry, and servers in a compact column to the right.
- Collapse to one centered column on narrow screens.
- Avoid cards and enclosing frames. Use spacing, type, thin rules, and state color for hierarchy.
- Avoid enclosing frames, borders, and divider lines. Use spacing, type, subtle surface changes, light, depth, and state color for hierarchy.
- Do not introduce popups or modals without an explicit user request. Prefer inline disclosure or a non-modal side layer when supporting content must coexist with the main control surface.
- Keep server rows vertical and narrow. Underlines should be only slightly wider than the server label and ping.
## Geometry and alignment
@@ -22,6 +23,8 @@ Design for a macOS user glancing at a small VPN control surface in a quiet deskt
- Preserve a generous invisible hit area around icon-only controls.
- Center proxy address and protocol actions with the power column.
- Treat one-pixel optical misalignment as a defect when controls sit beside uppercase labels.
- Center the semantic brand or label independently from optional action icons. Place secondary icons beside it without letting their width move the centered content.
- Layer mutually exclusive status text in one fixed slot and crossfade between layers. Never replace text in normal flow when its length can move the interface.
## Typography
@@ -34,10 +37,20 @@ Design for a macOS user glancing at a small VPN control surface in a quiet deskt
## Color and light
- Preserve green-tinted dark and light neutrals through the existing OKLCH variables.
- Inactive power stays neutral gray even on hover; active power becomes green.
- Use green for active VPN, selected server underline, progress, copy success, refresh success, and focus.
- Prefer localized `drop-shadow`, `text-shadow`, or a soft radial light layer over filled green containers.
- Treat mode color as a system-wide state, not a logo-only decoration: Connect uses its blue-green token and Gateway uses its orange token for power, glow, selected rows, progress, copy/refresh feedback, focus, and mode-relevant labels.
- Inactive power stays neutral gray even on hover. Warning and destructive actions remain semantic red rather than inheriting the mode accent.
- Prefer localized `drop-shadow`, `text-shadow`, or a soft radial light layer over filled accent containers.
- Let glow support state recognition. Do not leave every element glowing continuously.
- Give Connect and Gateway distinct favicons and brand marks using the same mode palette.
- When Gateway carries traffic, fade, desaturate, and disable the local subscription/server block: it remains understandable context but must not look active or actionable.
## Interactive surfaces
- Use one fast translucent cloud treatment for explanatory tooltips. Place the cloud above its target with strong enough contrast to survive busy content beneath it.
- Keep a tooltip as a sibling of the animated icon/button it describes. A tooltip must never rotate, glow, blur, scale, or move with the control.
- Use the shared full-screen critical confirmation popup for destructive actions and unsaved-data exits. Keep the centered surface flat, with hierarchy from blur, spacing, type, and staged motion rather than borders or rounded cards.
- Animate physical icon parts when their function suggests it, such as lifting a trash lid on hover, while keeping hit areas and nearby text fixed.
- Keep advanced client editors flat inside their side layer: rows, notes, selectors, and actions should not become nested cards, bordered fields, or raised buttons. Use spacing, type, focus light, and state color for hierarchy.
## Data presentation

View File

@@ -0,0 +1,26 @@
---
name: manage-harbor-versions
description: Check and bump Harbor component versions for every runtime, UI, API, dependency, packaging, or deployment-config change in this repository. Use before completing implementation work, release preparation, or any change that can alter the shipped Mac client, Gateway client, or Gateway backend.
---
# Manage Harbor Versions
Treat `src/shared/versions.js` as the only component-version source. Do not use the root package version as a release version.
## Required workflow
1. Inspect the complete diff and choose the comparison base, normally `HEAD` for working-tree changes or the target branch for a review.
2. Run `npm run version:harbor -- affected <base>`.
3. Classify the highest compatibility impact:
- `major`: changes an ecosystem contract or requires all cooperating components and clients to update;
- `minor`: changes one component and its tightly linked components while remaining compatible with other clients on the same major;
- `hotfix`: changes only the affected component without requiring linked components or other clients to update.
4. Run one explicit bump command:
- `npm run version:harbor -- bump major`
- `npm run version:harbor -- bump minor <components...>`
- `npm run version:harbor -- bump hotfix <components...>`
5. Run `npm run version:harbor -- check <base>` and the repository tests before completion.
Valid component names are `mac`, `gateway-client`, and `gateway-backend`. A major bump always updates all three components. A minor bump for either Gateway component automatically updates both Gateway client and Gateway backend. A hotfix updates only the named component.
Do not bump documentation- or test-only changes. If the version contract is new and the base has no `src/shared/versions.js`, keep the initial versions and let the checker report that no baseline exists.

View File

@@ -0,0 +1,4 @@
interface:
display_name: "Manage Harbor Versions"
short_description: "Check and bump Harbor component versions."
default_prompt: "Use $manage-harbor-versions to classify changes and update the required Harbor component versions."

View File

@@ -1,5 +1,6 @@
node_modules
.vpn-proxy
.runtime
.git
.gitea
.github

View File

@@ -2,6 +2,7 @@ PORT=3456
APP_MODE=gateway
CLIENT_UI_PORT=3456
CLIENT_PROXY_PORT=8082
HARBOR_GATEWAY_CONTROL_PORT=3456
BASE_IMAGE=debian:bookworm-slim
SINGBOX_VERSION=1.12.13
INSTALL_RUNTIME_DEPS=true
@@ -12,4 +13,7 @@ TPROXY_PORT=7895
TPROXY_MARK=1
TPROXY_TABLE=100
TPROXY_CHAIN=VPN_PROXY_TPROXY
GATEWAY_FORWARD_CHAIN=VPN_PROXY_FORWARD
GATEWAY_NAT_CHAIN=VPN_PROXY_NAT
GATEWAY_CLIENT_CIDRS=10.0.0.0/8 172.16.0.0/12 192.168.0.0/16
LOG_LEVEL=info

View File

@@ -35,6 +35,8 @@ jobs:
REGISTRY_HOST=$(echo "${{ gitea.server_url }}" | sed 's|https\?://||')
IMAGE="${REGISTRY_HOST}/${{ gitea.repository }}/gateway"
CONTROL_IMAGE="${IMAGE}-control"
DATAPLANE_IMAGE="${IMAGE}-dataplane"
echo "Build runner: $(hostname)"
echo "Base image: ${{ env.BASE_IMAGE }}"
@@ -73,11 +75,15 @@ jobs:
--build-arg SINGBOX_VERSION="${{ env.SINGBOX_VERSION }}" \
--build-arg INSTALL_RUNTIME_DEPS=false \
--build-arg INSTALL_SINGBOX=false \
-t "${IMAGE}:latest" \
-t "${IMAGE}:${{ gitea.sha }}" \
-t "${CONTROL_IMAGE}:latest" \
-t "${CONTROL_IMAGE}:${{ gitea.sha }}" \
-t "${DATAPLANE_IMAGE}:latest" \
-t "${DATAPLANE_IMAGE}:${{ gitea.sha }}" \
.
docker push "${IMAGE}:latest"
docker push "${IMAGE}:${{ gitea.sha }}"
docker push "${CONTROL_IMAGE}:latest"
docker push "${CONTROL_IMAGE}:${{ gitea.sha }}"
docker push "${DATAPLANE_IMAGE}:latest"
docker push "${DATAPLANE_IMAGE}:${{ gitea.sha }}"
deploy:
runs-on: lxc-111
@@ -101,7 +107,19 @@ jobs:
REGISTRY_HOST=$(echo "${{ gitea.server_url }}" | sed 's|https\?://||')
IMAGE="${REGISTRY_HOST}/${{ gitea.repository }}/gateway"
CONTROL_IMAGE="${IMAGE}-control:${{ gitea.sha }}"
DATAPLANE_IMAGE="${IMAGE}-dataplane:${{ gitea.sha }}"
UPDATE_DATAPLANE=false
if git diff-tree --no-commit-id --name-only -r -m HEAD | grep -Eq \
'^(Dockerfile|entrypoint\.sh|package(-lock)?\.json|scripts/build-runtime-base\.sh|\.gitea/workflows/gateway-build\.yml|src/server/(config|dataplane|gatewayRouting|singboxRuntime|version)\.js|src/shared/errors\.js)$'; then
UPDATE_DATAPLANE=true
fi
echo "Deploy runner: $(hostname)"
echo "Update dataplane: ${UPDATE_DATAPLANE}"
echo "${{ secrets.REGISTRY_TOKEN }}" | docker login "$REGISTRY_HOST" -u "${{ gitea.actor }}" --password-stdin
DEPLOY_PATH="${{ env.DEPLOY_PATH }}" GATEWAY_IMAGE="${IMAGE}:${{ gitea.sha }}" bash scripts/deploy-gateway.sh
DEPLOY_PATH="${{ env.DEPLOY_PATH }}" \
CONTROL_IMAGE="${CONTROL_IMAGE}" \
DATAPLANE_IMAGE="${DATAPLANE_IMAGE}" \
UPDATE_DATAPLANE="${UPDATE_DATAPLANE}" \
bash scripts/deploy-gateway.sh

4
.gitignore vendored
View File

@@ -3,8 +3,12 @@
*.env.local
data/
.vpn-proxy/
.runtime/
.worktrees/
# Local roadmap and task workspace
/workpack/
# Node/Vite
node_modules/
dist/

7
AGENTS.md Normal file
View File

@@ -0,0 +1,7 @@
# Harbor task workflow
Use the checked-in `workpack/` directory as the only roadmap source. Do not require or read the original archive.
Follow `workpack/AGENTS.md` for every roadmap task, including status updates. Completed tasks must not be selected or implemented again unless the user explicitly asks to reopen one.
For every runtime, UI, API, dependency or deployment-config change, use `.codex/skills/manage-harbor-versions/SKILL.md`. Before completion, classify the affected components, bump the required version level and run `npm run version:harbor -- check <base>`. Documentation- and test-only changes do not require a bump.

View File

@@ -7,13 +7,12 @@ COPY dist /app/dist
RUN if [ "${INSTALL_RUNTIME_DEPS}" = "true" ]; then \
apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates curl iptables ipset iproute2 nodejs dumb-init \
&& apt-get install -y --no-install-recommends ca-certificates curl iptables iproute2 nodejs dumb-init \
&& rm -rf /var/lib/apt/lists/*; \
else \
command -v dumb-init >/dev/null \
&& command -v node >/dev/null \
&& command -v iptables >/dev/null \
&& command -v ipset >/dev/null; \
&& command -v iptables >/dev/null; \
fi
RUN if [ "${INSTALL_SINGBOX}" = "true" ]; then \
@@ -36,6 +35,7 @@ RUN if [ "${INSTALL_SINGBOX}" = "true" ]; then \
WORKDIR /app
COPY package.json /app/package.json
COPY src/server /app/src/server
COPY src/shared /app/src/shared
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh \
@@ -45,8 +45,6 @@ ENV PORT=3456 \
PROXY_PORT=8080 \
PROXY_BIND_IP=0.0.0.0 \
TPROXY_PORT=7895 \
DIRECT_BYPASS_CACHE=false \
RULE_SET_DOWNLOAD_DETOUR=vpn \
DATA_DIR=/var/lib/vpn-proxy \
SING_BOX_CONFIG=/etc/sing-box/config.json \
SING_BOX_CACHE=/var/lib/sing-box/cache.db

View File

@@ -7,6 +7,7 @@ COPY package.json package-lock.json ./
RUN npm ci
COPY index.html vite.config.js ./
COPY src/web ./src/web
COPY src/shared ./src/shared
RUN npm run build
FROM ${RUNTIME_IMAGE}
@@ -33,6 +34,7 @@ WORKDIR /app
COPY --from=web-build /src/dist /app/dist
COPY package.json /app/package.json
COPY src/server /app/src/server
COPY src/shared /app/src/shared
COPY entrypoint.client.sh /entrypoint.client.sh
RUN chmod +x /entrypoint.client.sh \

335
README.md
View File

@@ -1,43 +1,330 @@
# VPN Proxy
# Harbor
Один компактный VPN-клиент в двух режимах:
Harbor помогает пользоваться одной VPN-подпиской дома и на Mac без ручной настройки `sing-box`.
- `gateway` — отдельная Linux-машина принимает трафик устройств как системный Gateway или HTTP/SOCKS5 Proxy;
- `client` — локальный proxy-клиент для macOS.
Проект работает в двух режимах:
В обоих режимах пользователь добавляет подписку, выбирает сервер и включает VPN на одном экране.
| Режим | Где работает | Для чего нужен |
| --- | --- | --- |
| **Harbor Gateway** | На отдельной Linux-машине | Проводит через VPN весь интернет-трафик домашних устройств или работает как общий HTTP/SOCKS5-прокси |
| **Harbor Connect** | На macOS | Даёт приложениям на Mac локальный HTTP/SOCKS5-прокси |
## Gateway
В обоих режимах управление одинаковое: откройте веб-интерфейс, вставьте ссылку VPN-подписки, выберите сервер и нажмите кнопку подключения.
## Что понадобится
- ссылка на подписку от VPN-провайдера;
- Docker с командой `docker compose`;
- для ручной установки Gateway — Git;
- для Gateway — Linux-машина в одной локальной сети с устройствами;
- для Connect — Mac с запущенным Docker Desktop.
Harbor не является VPN-провайдером и не создаёт подписки самостоятельно.
## Что выбрать
Используйте **Harbor Connect**, если VPN нужен только приложениям на одном Mac.
Используйте **Harbor Gateway**, если нужно подключить телевизор, телефон, игровую приставку или сразу несколько устройств. Устройства можно направить через Gateway целиком либо настроить в отдельных приложениях общий прокси.
Оба режима можно использовать вместе. Дома Connect автоматически распознаёт настроенный Harbor Gateway и не запускает второй VPN-маршрут. В другой сети Connect возвращается к локальному VPN.
## Установка Harbor Gateway
### 1. Скачайте проект
```bash
git clone https://git.dokops.ru/dokril/vpn-proxy.git
cd vpn-proxy
```
### 2. Создайте настройки
```bash
cp .env.example .env
```
Стандартные значения подходят для обычной домашней сети. При необходимости откройте `.env` в текстовом редакторе и измените порты.
### 3. Запустите Gateway
```bash
docker compose -f docker-compose.gateway.yml up -d --build
```
Интерфейс: `http://<gateway-ip>:3456`.
Откройте в браузере:
После подключения экран показывает:
- `Gateway` — адрес, который можно назначить устройству как основной шлюз;
- `Proxy` — один адрес на порту `8080`, доступный как `HTTP` и `SOCKS5`.
Весь перехваченный публичный TCP/UDP и весь proxy-трафик идут через выбранный VPN. Приватные и локальные сети не перехватываются, чтобы сохранить доступ к Gateway и LAN.
Proxy по умолчанию разрешён только из приватных сетей. Диапазоны задаются через `PROXY_ALLOWED_CIDRS`.
## macOS client
```bash
./scripts/install-macos-client.sh
```text
http://АДРЕС-GATEWAY:3456
```
По умолчанию интерфейс доступен на `http://127.0.0.1:3456`, локальный HTTP/SOCKS5 proxy — на `127.0.0.1:8082`.
Например, если Linux-машина имеет адрес `192.168.1.20`, интерфейс будет доступен по адресу `http://192.168.1.20:3456`.
## Проверка
### 4. Добавьте подписку
1. Вставьте ссылку VPN-подписки.
2. Нажмите «Сохранить подписку».
3. Выберите сервер.
4. Включите VPN.
После подключения Harbor покажет два варианта использования:
- **Gateway** — укажите IP-адрес Linux-машины как основной шлюз устройства. Через VPN пойдёт весь его интернет-трафик;
- **Gateway Proxy** — укажите адрес Linux-машины и порт `8080` в приложении. Поддерживаются HTTP и SOCKS5 на одном порту.
Приватные и локальные адреса не отправляются в VPN, поэтому устройства сохраняют доступ к домашней сети. Общий прокси по умолчанию принимает подключения только из приватных сетей.
## Установка Harbor Connect на macOS
### 1. Запустите Docker Desktop
Установщик проверит наличие Docker, Docker Compose, `curl` и `tar`. Если Docker Desktop не запущен, установка остановится с понятным сообщением.
### 2. Запустите установщик
```bash
curl -fsSL https://git.dokops.ru/dokril/vpn-proxy/raw/branch/master/install.sh | sh
```
Установщик:
- сохранит рабочую копию в `~/.vpn-proxy-client`;
- предложит порт для локального прокси;
- соберёт и запустит контейнер Harbor Connect;
- добавит пользовательский LaunchAgent для определения текущего Gateway.
По умолчанию используются адреса:
| Назначение | Адрес |
| --- | --- |
| Интерфейс Harbor Connect | `http://127.0.0.1:3456` |
| HTTP-прокси | `127.0.0.1:8082` |
| SOCKS5-прокси | `127.0.0.1:8082` |
### 3. Добавьте подписку
Откройте `http://127.0.0.1:3456`, вставьте ссылку подписки, выберите сервер и включите VPN.
Сам по себе локальный прокси не перенаправляет приложения автоматически. Адрес `127.0.0.1:8082` нужно указать в настройках нужного приложения или в системных настройках macOS.
### Другие порты
Передайте нужные значения при повторном запуске установщика:
```bash
curl -fsSL https://git.dokops.ru/dokril/vpn-proxy/raw/branch/master/install.sh | \
VPN_PROXY_CLIENT_PORT=9080 \
VPN_PROXY_CLIENT_UI_PORT=3457 \
sh
```
Допустимы порты от `1024` до `65535`. Установщик не позволит выбрать занятый порт или один порт одновременно для интерфейса и прокси.
## Локальные правила маршрутизации
После добавления подписки откройте «Локальные правила» справа от основного экрана. При первом обновлении Harbor добавит обычное включённое правило `*.ru`, поэтому российские домены пойдут напрямую. Его, как и любое другое правило, можно выключить или удалить. Доступны точный домен, suffix домена и фрагмент имени; включённые правила обходят VPN, а остальной трафик идёт через выбранный сервер.
Полный URL можно вставить в поле точного домена, но Harbor сохранит только hostname. Путь и параметры HTTPS зашифрованы и недоступны sing-box на уровне маршрутизации. GeoSite, GeoIP и подключаемые списки пока не поддерживаются.
При сохранении Harbor проверяет фактическое состояние sing-box. Работающий процесс автоматически перезагружает новую конфигурацию. Если sing-box остановлен, правила сохраняются с признаком «ждут перезапуска» и начнут работать при следующем запуске или restart; этот статус виден в интерфейсе.
## Системный прокси macOS
Сначала посмотрите точное имя сетевого подключения:
```bash
networksetup -listallnetworkservices
```
Для подключения с именем `Wi-Fi` включите HTTP, HTTPS и SOCKS5-прокси:
```bash
networksetup -setwebproxy Wi-Fi 127.0.0.1 8082
networksetup -setsecurewebproxy Wi-Fi 127.0.0.1 8082
networksetup -setsocksfirewallproxy Wi-Fi 127.0.0.1 8082
```
Чтобы отключить их:
```bash
networksetup -setwebproxystate Wi-Fi off
networksetup -setsecurewebproxystate Wi-Fi off
networksetup -setsocksfirewallproxystate Wi-Fi off
```
Если сетевое подключение называется иначе, замените `Wi-Fi` его точным именем.
## Автоматическое использование домашнего Gateway
Harbor Connect раз в пять секунд узнаёт у macOS адрес текущего основного шлюза. Если по этому адресу работает Harbor Gateway с той же VPN-подпиской, Connect оставляет локальный прокси доступным для приложений, но не создаёт второй VPN-маршрут: трафик уже обрабатывает Gateway.
Для этого:
1. добавьте одну и ту же ссылку подписки в Gateway и Connect;
2. убедитесь, что Mac может открыть интерфейс Gateway на порту `3456`;
3. оставьте автоматический режим включённым в Harbor Connect.
Ссылка должна содержать персональный секрет или token длиной не менее 16 символов — обычные ссылки подписок уже соответствуют этому условию. Ссылка между устройствами не передаётся: она используется локально для проверки, что Connect нашёл именно ваш Gateway. При смене сети или после трёх неудачных проверок Connect возвращается к локальному VPN.
## Повседневные команды
Все команды Gateway выполняются из каталога проекта. Команды Connect — из `~/.vpn-proxy-client`.
### Harbor Gateway
| Действие | Команда |
| --- | --- |
| Запустить или обновить после изменения файлов | `docker compose -f docker-compose.gateway.yml up -d --build` |
| Обновить только интерфейс и управление | `docker compose -f docker-compose.gateway.yml build vpn-proxy-control && docker compose -f docker-compose.gateway.yml up -d --no-deps vpn-proxy-control` |
| Показать состояние | `docker compose -f docker-compose.gateway.yml ps` |
| Смотреть журнал | `docker compose -f docker-compose.gateway.yml logs -f` |
| Перезапустить только интерфейс и управление | `docker compose -f docker-compose.gateway.yml restart vpn-proxy-control` |
| Перезапустить VPN dataplane | `docker compose -f docker-compose.gateway.yml restart vpn-proxy-dataplane` |
| Остановить | `docker compose -f docker-compose.gateway.yml down` |
| Удалить вместе с сохранёнными данными | `docker compose -f docker-compose.gateway.yml down -v` |
### Harbor Connect
```bash
cd ~/.vpn-proxy-client
```
| Действие | Команда |
| --- | --- |
| Обновить и снова запустить | `./scripts/install-macos-client.sh` |
| Показать состояние | `docker compose -f docker-compose.client.yml ps` |
| Смотреть журнал | `docker compose -f docker-compose.client.yml logs -f` |
| Перезапустить | `docker compose -f docker-compose.client.yml restart` |
| Остановить | `docker compose -f docker-compose.client.yml down` |
| Удалить вместе с сохранёнными данными | `docker compose -f docker-compose.client.yml down -v` |
Команда с `-v` удаляет подписку, выбранный сервер и другие сохранённые данные. Для обычной остановки используйте `down` без `-v`.
## Обновление
### Gateway
```bash
git pull --ff-only
docker compose -f docker-compose.gateway.yml up -d --build
```
### Connect
Повторно запустите однострочный установщик. Он обновит рабочую копию, снова спросит порт прокси и пересоберёт Connect:
```bash
curl -fsSL https://git.dokops.ru/dokril/vpn-proxy/raw/branch/master/install.sh | sh
```
Если раньше использовался нестандартный порт, укажите его снова через `VPN_PROXY_CLIENT_PORT`.
### Версии
Текущая версия всегда показана в правом нижнем углу интерфейса. Connect показывает строку `M` (Mac client). Gateway показывает `C` (Gateway client UI), `B` (текущий control-backend) и `D` (фактически развёрнутый dataplane). Поэтому после control-only deploy `B` обновится сразу, а `D` может намеренно остаться на прежней версии до следующего runtime-deploy. Наведите курсор или переведите клавиатурный фокус на цифру, чтобы увидеть смысл `major`, `minor` или `hotfix`; у `D` также указана фактическая версия `sing-box`.
Компонентные версии меняются в `src/shared/versions.js`. У всех компонентов должен совпадать `major`, у Gateway client и backend — `major.minor`; `hotfix` может отличаться. Runtime-значения доступны через `GET /api/version`.
Для изменения версии используйте `npm run version:harbor -- affected HEAD`, затем `npm run version:harbor -- bump <major|minor|hotfix> [компонент]` и `npm run version:harbor -- check HEAD`. Правила выбора уровня закреплены в обязательном repo skill `manage-harbor-versions`.
## Настройки `.env`
Для большинства установок достаточно стандартных значений.
| Переменная | По умолчанию | Назначение |
| --- | --- | --- |
| `PORT` | `3456` | Внутренний порт веб-интерфейса Gateway |
| `CLIENT_UI_PORT` | `3456` | Порт интерфейса Connect на Mac |
| `PROXY_PORT` | `8080` | Порт общего прокси Gateway |
| `CLIENT_PROXY_PORT` | `8082` | Порт локального прокси Connect |
| `HARBOR_GATEWAY_CONTROL_PORT` | `3456` | Порт, на котором Connect проверяет домашний Gateway |
| `PROXY_BIND_IP` | `0.0.0.0` | Адрес, на котором Gateway принимает прокси-подключения |
| `PROXY_ALLOWED_CIDRS` | приватные IPv4-сети | Сети, которым разрешён доступ к Gateway Proxy |
| `GATEWAY_CLIENT_CIDRS` | приватные IPv4-сети | Сети, трафик которых Gateway может маршрутизировать |
| `LOG_LEVEL` | `info` | Уровень подробности журнала |
Остальные значения в `.env.example` относятся к сборке контейнера и внутренней маршрутизации. Меняйте их только при нестандартном развёртывании.
После изменения `.env` пересоздайте контейнер командой `up -d` — обычного `restart` недостаточно.
## Если что-то не работает
### Интерфейс не открывается
Проверьте контейнер и журнал:
```bash
docker compose -f docker-compose.gateway.yml ps
docker compose -f docker-compose.gateway.yml logs --tail=100
```
Для Connect замените имя файла на `docker-compose.client.yml` и выполняйте команду из `~/.vpn-proxy-client`.
### Прокси не отвечает
Убедитесь, что Harbor включён в интерфейсе, а приложение использует правильные адрес и порт. Для Connect это обычно `127.0.0.1:8082`; для Gateway — IP Linux-машины и порт `8080`.
### Connect не распознаёт Gateway
Проверьте три условия:
- Gateway является текущим основным шлюзом Mac;
- на обоих устройствах сохранена одна и та же подписка;
- с Mac открывается `http://АДРЕС-GATEWAY:3456`.
### Проверка конфигурации без запуска
```bash
npm test
npm run build
docker compose -f docker-compose.gateway.yml config
docker compose -f docker-compose.client.yml config
docker compose -f docker-compose.client.local.yml config
```
Эти команды только проверяют и показывают итоговую конфигурацию Docker Compose.
### Локальное тестирование Harbor Connect
Тестовый Connect запускается рядом с установленным клиентом и использует отдельные контейнер, volumes и порты:
```bash
docker compose -f docker-compose.client.local.yml up -d --build
```
Интерфейс доступен на `http://127.0.0.1:3457`, HTTP/SOCKS5-прокси — на `127.0.0.1:8083`. Остановить и удалить только тестовый стек можно командой:
```bash
docker compose -f docker-compose.client.local.yml down -v
```
Порты можно заменить через `LOCAL_CLIENT_UI_PORT` и `LOCAL_CLIENT_PROXY_PORT`.
## Служебные команды
Этот раздел нужен тем, кто собирает, проверяет или развёртывает сам проект. Для обычного использования он не требуется.
### Команды npm
| Команда | Назначение |
| --- | --- |
| `npm ci` | Установить точные версии зависимостей из `package-lock.json` |
| `npm test` | Запустить автоматические проверки |
| `npm run build` | Собрать веб-интерфейс в `dist/` |
| `npm run dev` | Запустить Vite для разработки интерфейса |
| `npm start` | Запустить управляющий Node.js-сервис в подготовленном окружении |
### Сборка и развёртывание
| Команда | Назначение |
| --- | --- |
| `./scripts/build-runtime-base.sh` | Собрать базовый runtime-образ с Node.js, сетевыми утилитами и `sing-box` |
| `./scripts/build-on-107-deploy-111.sh` | Собрать Gateway на хосте `107` и развернуть на хосте `111`; хосты меняются через `BUILD_HOST` и `DEPLOY_HOST` |
| `GATEWAY_IMAGE=<образ> ./scripts/deploy-gateway.sh` | Развернуть уже собранный образ в `/opt/vpn-proxy` |
| `./scripts/harbor-network-monitor.sh` | Один раз записать текущий Gateway macOS; обычно этот скрипт запускает установленный LaunchAgent |
Отправка изменений в ветку `master` также запускает автоматическую сборку и развёртывание Gateway через Gitea Actions. Каждый деплой пересоздаёт `vpn-proxy-control`, поэтому строка `B` соответствует текущему коду API. Процесс `sing-box` и сетевые правила остаются в `vpn-proxy-dataplane`; он пересоздаётся только при изменении его runtime-зависимостей, а его фактическая версия показывается отдельно как `D`.
## Хранение данных
Подписка, выбранный сервер и состояние подключения хранятся в именованных Docker volumes. Поэтому обычные команды `restart`, `down`, обновление проекта и повторная сборка не удаляют настройки.
Не публикуйте файл `.env`, ссылку подписки и содержимое Docker volumes. `.env` уже исключён из Git.

View File

@@ -0,0 +1,24 @@
name: harbor-connect-local
services:
harbor-connect:
extends:
file: docker-compose.client.yml
service: harbor-connect
container_name: harbor-connect-local
environment:
PORT: ${LOCAL_CLIENT_UI_PORT:-3457}
PROXY_PORT: ${LOCAL_CLIENT_PROXY_PORT:-8083}
ports: !override
- "127.0.0.1:${LOCAL_CLIENT_UI_PORT:-3457}:${LOCAL_CLIENT_UI_PORT:-3457}"
- "127.0.0.1:${LOCAL_CLIENT_PROXY_PORT:-8083}:${LOCAL_CLIENT_PROXY_PORT:-8083}"
volumes: !override
- vpn-proxy-client-local-data:/var/lib/vpn-proxy
- sing-box-client-local-cache:/var/lib/sing-box
- ./.runtime:/run/harbor-host:ro
healthcheck:
test: ["CMD", "curl", "--noproxy", "*", "-fsS", "http://127.0.0.1:${LOCAL_CLIENT_UI_PORT:-3457}/api/state"]
volumes:
vpn-proxy-client-local-data:
sing-box-client-local-cache:

View File

@@ -1,11 +1,11 @@
services:
vpn-proxy-client:
harbor-connect:
build:
context: .
dockerfile: Dockerfile.client
args:
SINGBOX_VERSION: ${SINGBOX_VERSION:-1.12.13}
container_name: vpn-proxy-client
container_name: harbor-connect
environment:
APP_MODE: client
PORT: ${PORT:-3456}
@@ -14,6 +14,8 @@ services:
DATA_DIR: /var/lib/vpn-proxy
SING_BOX_CONFIG: /etc/sing-box/config.json
SING_BOX_CACHE: /var/lib/sing-box/cache.db
HARBOR_HOST_NETWORK_STATE: /run/harbor-host/network.json
HARBOR_GATEWAY_CONTROL_PORT: ${HARBOR_GATEWAY_CONTROL_PORT:-3456}
LOG_LEVEL: ${LOG_LEVEL:-info}
HTTP_PROXY: ""
HTTPS_PROXY: ""
@@ -29,6 +31,7 @@ services:
volumes:
- vpn-proxy-client-data:/var/lib/vpn-proxy
- sing-box-client-cache:/var/lib/sing-box
- ./.runtime:/run/harbor-host:ro
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "--noproxy", "*", "-fsS", "http://127.0.0.1:${PORT:-3456}/api/state"]

View File

@@ -1,14 +1,18 @@
x-gateway-image: &gateway-image
image: ${GATEWAY_IMAGE:-vpn-proxy-gateway:local}
build:
context: .
dockerfile: Dockerfile
args:
BASE_IMAGE: ${BASE_IMAGE:-debian:bookworm-slim}
SINGBOX_VERSION: ${SINGBOX_VERSION:-1.12.13}
INSTALL_RUNTIME_DEPS: ${INSTALL_RUNTIME_DEPS:-true}
INSTALL_SINGBOX: ${INSTALL_SINGBOX:-true}
services:
vpn-proxy-gateway:
build:
context: .
dockerfile: Dockerfile
args:
BASE_IMAGE: ${BASE_IMAGE:-debian:bookworm-slim}
SINGBOX_VERSION: ${SINGBOX_VERSION:-1.12.13}
INSTALL_RUNTIME_DEPS: ${INSTALL_RUNTIME_DEPS:-true}
INSTALL_SINGBOX: ${INSTALL_SINGBOX:-true}
container_name: vpn-proxy-gateway
vpn-proxy-dataplane:
<<: *gateway-image
container_name: vpn-proxy-dataplane
network_mode: host
cap_add:
- NET_ADMIN
@@ -17,11 +21,43 @@ services:
- path: .env
required: false
environment:
APP_COMPONENT: dataplane
DATA_DIR: /var/lib/vpn-proxy
SING_BOX_CONFIG: /var/lib/vpn-proxy/sing-box-config.json
SING_BOX_CACHE: /var/lib/sing-box/cache.db
DATAPLANE_SOCKET: /run/vpn-proxy/dataplane.sock
volumes:
- vpn-proxy-data:/var/lib/vpn-proxy
- sing-box-cache:/var/lib/sing-box
- vpn-proxy-runtime:/run/vpn-proxy
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "--unix-socket", "/run/vpn-proxy/dataplane.sock", "-fsS", "http://localhost/status"]
interval: 5s
timeout: 3s
retries: 12
start_period: 5s
vpn-proxy-control:
<<: *gateway-image
container_name: vpn-proxy-gateway
env_file:
- path: .env
required: false
environment:
APP_COMPONENT: control
DATA_DIR: /var/lib/vpn-proxy
SING_BOX_CONFIG: /var/lib/vpn-proxy/sing-box-config.json
SING_BOX_CACHE: /var/lib/sing-box/cache.db
DATAPLANE_SOCKET: /run/vpn-proxy/dataplane.sock
ports:
- "${PORT:-3456}:${PORT:-3456}"
volumes:
- vpn-proxy-data:/var/lib/vpn-proxy
- vpn-proxy-runtime:/run/vpn-proxy
depends_on:
vpn-proxy-dataplane:
condition: service_healthy
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-fsS", "http://127.0.0.1:${PORT:-3456}/api/state"]
@@ -33,3 +69,4 @@ services:
volumes:
vpn-proxy-data:
sing-box-cache:
vpn-proxy-runtime:

View File

@@ -1,22 +0,0 @@
services:
vpn-proxy-gateway:
image: ${GATEWAY_IMAGE}
container_name: vpn-proxy-gateway
network_mode: host
cap_add:
- NET_ADMIN
- NET_RAW
env_file:
- .env
environment:
DATA_DIR: /var/lib/vpn-proxy
SING_BOX_CONFIG: /etc/sing-box/config.json
SING_BOX_CACHE: /var/lib/sing-box/cache.db
volumes:
- vpn-proxy-data:/var/lib/vpn-proxy
- sing-box-cache:/var/lib/sing-box
restart: unless-stopped
volumes:
vpn-proxy-data:
sing-box-cache:

View File

@@ -0,0 +1,21 @@
# Harbor responsive layout
The client page has three stable regions: the Harbor brand, the primary power control and the subscription/details form.
## Desktop
At widths above 920 px the main panel uses a symmetric three-column grid. Equal outer columns keep the power control on the exact horizontal center axis; the details form occupies the right column. The form has a viewport-relative maximum height and its own vertical scroll for unusually long content, so a large server list cannot move the power control away from the visual center.
The no-subscription setup state collapses the panel to one column and centers the form. No `left` offset or translated absolute element participates in either layout.
## Tablet and mobile
At 920 px and below all main regions use one normal-flow grid column. The brand becomes an absolute header inside the page shell, while reserved top padding prevents it from overlapping the primary content. Errors become normal-flow rows instead of floating over nearby controls. Form width is capped by both the available space and a readable maximum.
At 560 px and below spacing and drawer padding become more compact. Controls with a preferred fixed size, such as the duration switch, use `min(..., 100%)` so the primary flow remains available at 320 px.
## Motion and overflow contract
Layout properties are not animated. State feedback may animate opacity and blur, and the existing `prefers-reduced-motion` rules disable those transitions and animations. Drawers are capped at `100vw`; dialogs and inline content retain viewport-relative width limits.
Automated source-contract tests protect the symmetric desktop grid, normal-flow narrow layout, viewport-safe control widths and reduced-motion fallback. Release acceptance still includes a rendered check at 390, 768 and 1440 px; TASK-017 will later make that browser matrix automatic in CI.

View File

@@ -0,0 +1,85 @@
# Harbor application state v1
`GET /api/state` is the canonical Harbor domain snapshot. Successful POST and DELETE endpoints return the same snapshot as `state` while retaining their v0 response fields for compatibility.
```json
{
"apiVersion": 1,
"revision": 42,
"generatedAt": "2026-07-11T15:00:00.000Z",
"mode": "client",
"subscription": {
"status": "ready",
"host": "provider.example/…",
"fetchedAt": "2026-07-11T14:58:00.000Z",
"userInfo": {}
},
"selection": {
"desiredServerId": "srv_4d7c5d1bcd60d665",
"appliedServerId": "srv_4d7c5d1bcd60d665"
},
"connection": {
"desired": "running",
"process": "running",
"startedAt": "2026-07-11T14:59:10.000Z",
"lastError": null
},
"route": {
"mode": "local-vpn",
"gatewayAddress": null,
"lastVerifiedAt": null,
"reason": "auto"
},
"operation": {
"kind": null,
"status": "idle",
"startedAt": null,
"error": null
},
"servers": [
{
"id": "srv_4d7c5d1bcd60d665",
"label": "Amsterdam",
"host": "nl.example.net",
"port": 443,
"protocol": "vless"
}
]
}
```
The backend owns subscription metadata, servers, desired/applied selection, desired/process connection state, route and current operation. React may keep only unsaved form values, pending selection and visual state. Browser transport freshness is not part of this contract.
## Revision rules
`revision` is persisted in the existing `state.json` and increases on externally visible transitions, including operation start/completion/failure, import, refresh, forget, apply, start, stop and Gateway Auto changes. `generatedAt` is response metadata and does not change revision by itself.
A consumer must eventually apply only snapshots whose revision is at least its current revision. The frontend comparison and stale/offline transport envelope are intentionally handled by TASK-002 and TASK-003.
The frontend keeps the accepted snapshot in one reducer and replaces it only when `incoming.revision` is greater. Equal revisions preserve object identity so background polling does not replay decorative transitions. Mutation responses are applied directly; polling requests started before a mutation are logically invalidated and cannot overwrite its result. A locally pending server choice remains local until a newer snapshot acknowledges it or removes that server.
Browser transport state lives beside, not inside, the domain snapshot. It records boot status, last successful sync time and consecutive failures. Three failed polls mark the retained snapshot stale; the next successful GET or mutation clears that marker. An initial failure shows `control-unreachable`, `incompatible-api` or `fatal` without inventing domain state.
Gateway discovery follows the same retain-and-mark-stale rule. Once a concrete default Gateway has been verified, transient presence failures or a briefly stale macOS route snapshot keep `gateway-direct` active and report `route.reason = gateway-stale`; they do not restart sing-box into `local-vpn`. Local routing resumes only after the user disables Gateway mode or macOS reports a different default Gateway identity.
## Desired and applied state
`selection.desiredServerId` records the user's requested server. `selection.appliedServerId` changes only after its sing-box configuration has been applied. Likewise, `connection.desired` records intent while `connection.process` reports the observed runtime. A failed operation can therefore leave desired and applied values different without pretending that the request succeeded.
Server IDs are deterministic from normalized protocol, host and port, while provider order and the human-readable `label` are separate. Duplicate labels remain separate servers; reorder and cosmetic rename keep the same ID. Ping results, React keys, persisted selection and apply commands use the ID. If the selected endpoint disappears, Harbor stops the active process, clears selection and requires an explicit new choice instead of silently switching traffic.
## Subscription import and refresh
The browser validates only the shape and `http`/`https` protocol of a subscription URL. The provider is contacted once, after explicit submit. The backend fetches and parses the complete response before entering the serialized commit.
Import and refresh share one commit path. It prepares the candidate server list and sing-box config first, then updates cache, config, runtime and canonical state. If provider fetch, parsing, config validation or runtime apply fails, the previous subscription cache, selected server, config and running process remain active. Refreshes for the saved URL share one in-flight Promise; a refresh that finishes after another import is rejected with `STATE_CONFLICT` instead of overwriting the newer subscription.
The existing background refresh remains every 15 minutes. Provider requests time out after 15 seconds by default (`SUBSCRIPTION_TIMEOUT_MS` may override it). A failed background refresh logs a redacted warning and keeps the last successful subscription snapshot.
## Compatibility and migration
No path, volume or file is renamed. A legacy `state.json` without stable IDs is migrated to schema v4. A unique `selectedTag` is matched to its normalized endpoint and stored as `selectedServerId`/`appliedServerId`; an ambiguous or missing tag explicitly clears selection. The raw provider config remains unchanged in subscription cache and is normalized only in memory, so an older Harbor build can still use its original tags after rollback. Existing unknown fields remain untouched.
During the v0 compatibility window, the snapshot also exposes `selectedTag`, `singboxRunning`, `servers[].tag`, `gatewayAuto` and the other previous GET fields. Mutation responses retain their previous result fields and add `state`. The canonical `subscription` object never contains the full subscription URL.
Rollback is code-only: deploy the previous build. The v4 state keeps `selectedTag`, `appliedTag` and server aliases for older builds, while subscription cache keeps raw provider tags. The added ID fields are ignored by the previous implementation.

View File

@@ -0,0 +1,17 @@
# Data consistency regression suite
`npm test` is the required fast regression gate. It uses generated fixtures, temporary directories, loopback HTTP servers and a fake sing-box executable; it does not require internet, root or an installed sing-box.
The protected invariants are:
| Invariant | Regression coverage |
|---|---|
| One backend canonical snapshot owns servers and desired/applied selection | `test/data-consistency-regression.test.js`, `test/server/state-contract.test.js` |
| Revisions increase and an older response cannot replace newer state | `test/server/state-contract.test.js`, `test/web/harbor-state.test.js` |
| Provider failure, parser failure and runtime failure do not partially commit subscription state | `test/server/state-contract.test.js` |
| Atomic write failure preserves the last file and corrupt JSON preserves its original bytes | `test/server/state-store.test.js` |
| Legacy state migrates with an explicit result for ambiguous selection | `test/server/state-store.test.js` |
| Stable IDs survive reorder and duplicate labels for 1, 30 and 300 servers | `test/data-consistency-regression.test.js`, `test/server/subscription.test.js` |
| Initial control outage does not invent domain state; repeated failures retain and mark the last snapshot stale | `test/web/harbor-state.test.js` |
Fixtures are generated in test code to keep the suite small and deterministic. Packet-level networking, browser screenshots and accessibility automation are intentionally deferred to their dedicated roadmap tasks.

View File

@@ -0,0 +1,22 @@
# Harbor error contract v1
Public API failures use one envelope:
```json
{
"success": false,
"error": {
"code": "PROVIDER_UNAVAILABLE",
"message": "Провайдер подписки временно недоступен.",
"retryable": true,
"correlationId": "6f1a63de-30f9-4dc5-b8ce-38d38c164fe3",
"details": "HTTP 503"
}
}
```
`code`, Russian user copy, HTTP status and retry policy come from `src/shared/errors.js`. The browser maps copy and retry behavior by `code`; it does not display server-provided `details`. Unknown failures use `UNKNOWN`, never expose the raw exception, and always receive a correlation reference. Server logs use the same reference and redact complete HTTP(S) URLs.
Errors are local operation results, not canonical state replacements. A failed apply keeps the previous snapshot; in particular, server existence is validated before `desiredServerId` is persisted. Frontend errors are shown beside subscription or connection controls. Only retryable codes expose `Повторить`.
This is a coordinated API change: old frontends do not understand the object-valued `error` field, so frontend and control plane must be deployed together. Persisted files and volumes are unchanged. Rollback is code-only and requires no data migration.

View File

@@ -0,0 +1,16 @@
# Frontend operation registry
Harbor tracks active browser mutations by operation key instead of one global `busy` flag:
- `connection`: start, stop and restart;
- `serverApply`: apply the selected server;
- `subscriptionImport`, `subscriptionRefresh`, `subscriptionDelete`;
- `gatewayAuto`: change the active route preference.
Each entry is `{ status: "running", startedAt }`. A repeated operation key receives the same in-flight Promise, so a double click sends one request. A conflicting key resolves to `false` without starting its action. The symmetric conflict matrix lives in `src/web/state/operations.js`.
The registry only disables controls that can mutate the same domain state. Copy actions, instruction navigation and local tabs remain available during subscription refresh. Progress is announced with `role="status"`; the structured error from TASK-004 remains `role="alert"` after failure.
Subscription URL validation is local and accepts only well-formed `http` and `https` URLs. It does not contact the provider; the explicit import operation performs the single provider request and reports provider failures through the structured subscription error.
The registry is local transport/UI state. It does not replace backend `snapshot.operation`, change revisions or persist data. Rollback is frontend-only. A `diagnostics` key is intentionally deferred until TASK-016 adds a diagnostics operation to run.

View File

@@ -0,0 +1,36 @@
# Harbor state recovery
Harbor keeps the existing data paths and volumes. `state.json` now uses `schemaVersion: 4`; subscription cache, generated sing-box config and HWID keep their existing filenames. Schema v2 introduced locally managed domain routing rules. Schema v3 added rule `enabled` state. Schema v4 adds stable server IDs and migrates an unambiguous legacy `selectedTag` to `selectedServerId`.
## Atomic writes
Persistent files are written to a unique temporary file in the same directory, flushed with `fsync`, closed and atomically renamed over the target. A failure before rename leaves the previous target untouched and removes the temporary file.
## Migration
On startup, a legacy `state.json` without `schemaVersion`, or any v1-v3 state, is normalized and migrated to the current schema. Existing custom rules are preserved. Server identity is derived from protocol, host and port; a unique legacy tag keeps selection, while duplicate or missing matches require a new explicit choice. Before replacement Harbor saves the original beside it:
```text
state.json.backup-v0-2026-07-11T12-00-00-000Z
```
The migration preserves compatibility aliases, adds normalized revision, selection and server fields, and does not rename the volume. Subscription cache keeps the raw provider config so older builds can still use its original outbound tags. The backup remains the safest manual recovery source.
## Corrupt JSON
If `state.json` cannot be parsed, Harbor renames the exact damaged bytes to:
```text
state.json.corrupt-2026-07-11T12-00-00-000Z
```
It then creates a valid empty current-schema state and reports `storage-recovery` through `snapshot.operation`. A corrupt subscription cache is preserved with the same suffix and reported in control logs.
Recovery should be performed while Harbor is stopped:
1. Copy the whole data directory before changing anything.
2. Inspect a backup with `jq . <backup-file>`.
3. Restore only a valid JSON backup to the original filename.
4. Start Harbor and verify `GET /api/state` before applying or importing anything.
Generated config rollback also uses the atomic writer. No automatic recovery tries to guess missing subscription credentials or repair semantically invalid sing-box configuration.

View File

@@ -1,10 +1,14 @@
#!/usr/bin/env bash
set -euo pipefail
APP_COMPONENT="${APP_COMPONENT:-combined}"
TPROXY_PORT="${TPROXY_PORT:-7895}"
TPROXY_MARK="${TPROXY_MARK:-1}"
TPROXY_TABLE="${TPROXY_TABLE:-100}"
TPROXY_CHAIN="${TPROXY_CHAIN:-VPN_PROXY_TPROXY}"
GATEWAY_FORWARD_CHAIN="${GATEWAY_FORWARD_CHAIN:-VPN_PROXY_FORWARD}"
GATEWAY_NAT_CHAIN="${GATEWAY_NAT_CHAIN:-VPN_PROXY_NAT}"
GATEWAY_CLIENT_CIDRS="${GATEWAY_CLIENT_CIDRS:-10.0.0.0/8 172.16.0.0/12 192.168.0.0/16}"
PROXY_PORT="${PROXY_PORT:-8080}"
PROXY_BIND_IP="${PROXY_BIND_IP:-0.0.0.0}"
PROXY_INPUT_CHAIN="${PROXY_INPUT_CHAIN:-VPN_PROXY_INPUT}"
@@ -16,6 +20,10 @@ log() {
printf '[gateway-entrypoint] %s\n' "$*"
}
if [[ "$APP_COMPONENT" == "control" ]]; then
exec node /app/src/server/index.js
fi
ipt() {
iptables -w "$@"
}
@@ -35,6 +43,15 @@ cleanup_tproxy() {
ip route flush table "$TPROXY_TABLE" 2>/dev/null || true
}
cleanup_gateway_forwarding() {
ipt -D FORWARD -j "$GATEWAY_FORWARD_CHAIN" 2>/dev/null || true
ipt -t nat -D POSTROUTING -j "$GATEWAY_NAT_CHAIN" 2>/dev/null || true
ipt -F "$GATEWAY_FORWARD_CHAIN" 2>/dev/null || true
ipt -X "$GATEWAY_FORWARD_CHAIN" 2>/dev/null || true
ipt -t nat -F "$GATEWAY_NAT_CHAIN" 2>/dev/null || true
ipt -t nat -X "$GATEWAY_NAT_CHAIN" 2>/dev/null || true
}
enable_ip_forwarding() {
if [[ -w /proc/sys/net/ipv4/ip_forward ]]; then
printf '1' > /proc/sys/net/ipv4/ip_forward || true
@@ -58,6 +75,22 @@ setup_proxy_firewall() {
ipt -I INPUT -p udp --dport "$PROXY_PORT" -j "$PROXY_INPUT_CHAIN"
}
setup_gateway_forwarding() {
log "setup direct gateway forwarding"
cleanup_gateway_forwarding
enable_ip_forwarding
ipt -N "$GATEWAY_FORWARD_CHAIN"
ipt -t nat -N "$GATEWAY_NAT_CHAIN"
for cidr in $GATEWAY_CLIENT_CIDRS; do
ipt -A "$GATEWAY_FORWARD_CHAIN" -s "$cidr" -j ACCEPT
ipt -A "$GATEWAY_FORWARD_CHAIN" -d "$cidr" -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
ipt -t nat -A "$GATEWAY_NAT_CHAIN" -s "$cidr" -m addrtype ! --dst-type LOCAL -j MASQUERADE
done
ipt -I FORWARD 1 -j "$GATEWAY_FORWARD_CHAIN"
ipt -t nat -I POSTROUTING 1 -j "$GATEWAY_NAT_CHAIN"
}
setup_tproxy() {
log "setup tproxy on port ${TPROXY_PORT}"
cleanup_tproxy
@@ -68,6 +101,7 @@ setup_tproxy() {
ipt -t mangle -N "$TPROXY_CHAIN"
ipt -t mangle -A "$TPROXY_CHAIN" -m addrtype --dst-type LOCAL -j RETURN
ipt -t mangle -A "$TPROXY_CHAIN" -m mark --mark "$TPROXY_MARK" -j RETURN
ipt -t mangle -A "$TPROXY_CHAIN" -i 'br-+' -j RETURN
# Private/local destinations stay reachable; every intercepted public packet goes to VPN.
for cidr in $BYPASS_CIDRS; do
@@ -76,13 +110,17 @@ setup_tproxy() {
ipt -t mangle -A "$TPROXY_CHAIN" -p tcp -j TPROXY --on-port "$TPROXY_PORT" --tproxy-mark "$TPROXY_MARK/$TPROXY_MARK"
ipt -t mangle -A "$TPROXY_CHAIN" -p udp -j TPROXY --on-port "$TPROXY_PORT" --tproxy-mark "$TPROXY_MARK/$TPROXY_MARK"
ipt -t mangle -A PREROUTING -j "$TPROXY_CHAIN"
}
setup_gateway_forwarding
setup_tproxy
setup_proxy_firewall
node /app/src/server/index.js &
if [[ "$APP_COMPONENT" == "dataplane" ]]; then
node /app/src/server/dataplane.js &
else
node /app/src/server/index.js &
fi
APP_PID=$!
shutdown() {
@@ -90,6 +128,7 @@ shutdown() {
wait "$APP_PID" 2>/dev/null || true
cleanup_proxy_firewall
cleanup_tproxy
cleanup_gateway_forwarding
}
trap 'shutdown; exit 0' SIGTERM SIGINT
@@ -97,4 +136,5 @@ wait "$APP_PID"
STATUS=$?
cleanup_proxy_firewall
cleanup_tproxy
cleanup_gateway_forwarding
exit "$STATUS"

View File

@@ -3,7 +3,8 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>VPN</title>
<link id="harbor-favicon" rel="icon" href="/harbor-connect.svg?v=2" type="image/svg+xml" sizes="any" />
<title>Harbor</title>
</head>
<body>
<div id="root"></div>

27
install.sh Executable file
View File

@@ -0,0 +1,27 @@
#!/bin/sh
set -eu
need() {
command -v "$1" >/dev/null 2>&1 || {
printf '[harbor-connect] error: %s is required\n' "$1" >&2
exit 1
}
}
need curl
need tar
[ -x /bin/bash ] || { printf '[harbor-connect] error: /bin/bash is required\n' >&2; exit 1; }
branch="${VPN_PROXY_BRANCH:-master}"
archive_url="${VPN_PROXY_ARCHIVE_URL:-https://git.dokops.ru/dokril/vpn-proxy/archive/${branch}.tar.gz}"
tmp="$(mktemp -d "${TMPDIR:-/tmp}/harbor-connect.XXXXXX")"
trap 'rm -rf "$tmp"' 0 1 2 3 15
mkdir -p "$tmp/source"
curl -fsSL "$archive_url" | tar -xzf - -C "$tmp/source" --strip-components=1
[ -f "$tmp/source/scripts/install-macos-client.sh" ] || {
printf '[harbor-connect] error: installer is missing from archive\n' >&2
exit 1
}
VPN_PROXY_SOURCE_DIR="$tmp/source" /bin/bash "$tmp/source/scripts/install-macos-client.sh"

View File

@@ -8,6 +8,7 @@
"dev": "vite --host 0.0.0.0",
"build": "vite build",
"test": "node --test",
"version:harbor": "node scripts/harbor-version.mjs",
"start": "node src/server/index.js"
},
"dependencies": {

View File

@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<rect width="32" height="32" rx="9" fill="#101812"/>
<circle cx="16" cy="16" r="11" fill="#56c9bd" opacity=".09"/>
<g fill="none" stroke="#62d6c9" stroke-width="2.6" stroke-linecap="round">
<path d="M16 6.5v9"/>
<path d="M10.1 10.3a8 8 0 1 0 11.8 0"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 341 B

View File

@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<rect width="32" height="32" rx="9" fill="#18150f"/>
<circle cx="16" cy="7" r="2.5" fill="none" stroke="#efad58" stroke-width="2.3"/>
<g fill="none" stroke="#efad58" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round">
<path d="M16 9.5V25M10.5 14h11"/>
<path d="M16 27c-5 0-8-2.8-9.5-6.5M16 27c5 0 8-2.8 9.5-6.5"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 418 B

View File

@@ -104,9 +104,9 @@ echo "Starting gateway on ${DEPLOY_HOST}"
if [ "${DEPLOY_HOST}" = "local" ]; then
cd "${DEPLOY_PATH}"
chmod +x ./deploy-gateway.sh
DEPLOY_PATH="${DEPLOY_PATH}" GATEWAY_IMAGE="${GATEWAY_IMAGE}" PULL_IMAGE=false ./deploy-gateway.sh
DEPLOY_PATH="${DEPLOY_PATH}" GATEWAY_IMAGE="${GATEWAY_IMAGE}" UPDATE_DATAPLANE=true PULL_IMAGE=false ./deploy-gateway.sh
else
ensure_known_host "${DEPLOY_HOST}"
ssh_cmd "${DEPLOY_HOST}" \
"cd '${DEPLOY_PATH}' && chmod +x ./deploy-gateway.sh && DEPLOY_PATH='${DEPLOY_PATH}' GATEWAY_IMAGE='${GATEWAY_IMAGE}' PULL_IMAGE=false ./deploy-gateway.sh"
"cd '${DEPLOY_PATH}' && chmod +x ./deploy-gateway.sh && DEPLOY_PATH='${DEPLOY_PATH}' GATEWAY_IMAGE='${GATEWAY_IMAGE}' UPDATE_DATAPLANE=true PULL_IMAGE=false ./deploy-gateway.sh"
fi

View File

@@ -2,17 +2,29 @@
set -euo pipefail
DEPLOY_PATH="${DEPLOY_PATH:-/opt/vpn-proxy}"
GATEWAY_IMAGE="${GATEWAY_IMAGE:?GATEWAY_IMAGE is required}"
CONTROL_IMAGE="${CONTROL_IMAGE:-${GATEWAY_IMAGE:-}}"
DATAPLANE_IMAGE="${DATAPLANE_IMAGE:-${GATEWAY_IMAGE:-}}"
CONTROL_IMAGE="${CONTROL_IMAGE:?CONTROL_IMAGE or GATEWAY_IMAGE is required}"
DATAPLANE_IMAGE="${DATAPLANE_IMAGE:?DATAPLANE_IMAGE or GATEWAY_IMAGE is required}"
UPDATE_DATAPLANE="${UPDATE_DATAPLANE:-false}"
PULL_IMAGE="${PULL_IMAGE:-true}"
echo "Preparing deploy directory: ${DEPLOY_PATH}"
mkdir -p "${DEPLOY_PATH}"
EXISTING_DATAPLANE_IMAGE="$(docker inspect --format '{{.Config.Image}}' vpn-proxy-dataplane 2>/dev/null || true)"
FIRST_SPLIT_DEPLOY=false
if [ -z "${EXISTING_DATAPLANE_IMAGE}" ]; then
FIRST_SPLIT_DEPLOY=true
elif [ "${UPDATE_DATAPLANE}" != "true" ]; then
DATAPLANE_IMAGE="${EXISTING_DATAPLANE_IMAGE}"
fi
cat > "${DEPLOY_PATH}/docker-compose.server.yml" <<EOF
services:
vpn-proxy-gateway:
image: ${GATEWAY_IMAGE}
container_name: vpn-proxy-gateway
vpn-proxy-dataplane:
image: ${DATAPLANE_IMAGE}
container_name: vpn-proxy-dataplane
network_mode: host
cap_add:
- NET_ADMIN
@@ -20,11 +32,42 @@ services:
env_file:
- .env
environment:
APP_COMPONENT: dataplane
DATA_DIR: /var/lib/vpn-proxy
SING_BOX_CONFIG: /var/lib/vpn-proxy/sing-box-config.json
SING_BOX_CACHE: /var/lib/sing-box/cache.db
DATAPLANE_SOCKET: /run/vpn-proxy/dataplane.sock
volumes:
- vpn-proxy-data:/var/lib/vpn-proxy
- sing-box-cache:/var/lib/sing-box
- vpn-proxy-runtime:/run/vpn-proxy
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "--unix-socket", "/run/vpn-proxy/dataplane.sock", "-fsS", "http://localhost/status"]
interval: 5s
timeout: 3s
retries: 12
start_period: 5s
vpn-proxy-control:
image: ${CONTROL_IMAGE}
container_name: vpn-proxy-gateway
env_file:
- .env
environment:
APP_COMPONENT: control
DATA_DIR: /var/lib/vpn-proxy
SING_BOX_CONFIG: /var/lib/vpn-proxy/sing-box-config.json
SING_BOX_CACHE: /var/lib/sing-box/cache.db
DATAPLANE_SOCKET: /run/vpn-proxy/dataplane.sock
ports:
- "\${PORT:-3456}:\${PORT:-3456}"
volumes:
- vpn-proxy-data:/var/lib/vpn-proxy
- vpn-proxy-runtime:/run/vpn-proxy
depends_on:
vpn-proxy-dataplane:
condition: service_healthy
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-fsS", "http://127.0.0.1:\${PORT:-3456}/api/state"]
@@ -36,6 +79,7 @@ services:
volumes:
vpn-proxy-data:
sing-box-cache:
vpn-proxy-runtime:
EOF
if [ ! -f "${DEPLOY_PATH}/.env" ]; then
@@ -47,11 +91,9 @@ TPROXY_PORT=7895
TPROXY_MARK=1
TPROXY_TABLE=100
TPROXY_CHAIN=VPN_PROXY_TPROXY
TPROXY_SOURCE_BYPASS_CHAIN=VPN_PROXY_SRC_BYPASS
TPROXY_SOURCE_FORWARD_CHAIN=VPN_PROXY_FWD_BYPASS
TPROXY_SOURCE_NAT_CHAIN=VPN_PROXY_NAT_BYPASS
TPROXY_BYPASS_SOURCE_CIDRS=
ROUTING_RU_DIRECT=true
GATEWAY_FORWARD_CHAIN=VPN_PROXY_FORWARD
GATEWAY_NAT_CHAIN=VPN_PROXY_NAT
GATEWAY_CLIENT_CIDRS=10.0.0.0/8 172.16.0.0/12 192.168.0.0/16
LOG_LEVEL=info
EOF
echo "Created default .env. Edit ${DEPLOY_PATH}/.env if this server needs different ports."
@@ -61,15 +103,29 @@ fi
cd "${DEPLOY_PATH}"
echo "Pulling image: ${GATEWAY_IMAGE}"
echo "Control image: ${CONTROL_IMAGE}"
echo "Dataplane image: ${DATAPLANE_IMAGE}"
if [ "${PULL_IMAGE}" = "true" ]; then
docker compose -f docker-compose.server.yml pull
docker compose -f docker-compose.server.yml pull vpn-proxy-control
if [ "${FIRST_SPLIT_DEPLOY}" = "true" ] || [ "${UPDATE_DATAPLANE}" = "true" ]; then
docker compose -f docker-compose.server.yml pull vpn-proxy-dataplane
fi
else
echo "Skipping image pull; using local image ${GATEWAY_IMAGE}"
echo "Skipping image pull"
fi
echo "Starting gateway..."
docker compose -f docker-compose.server.yml up -d
if [ "${FIRST_SPLIT_DEPLOY}" = "true" ]; then
echo "Migrating the legacy combined gateway to split services..."
docker stop vpn-proxy-gateway 2>/dev/null || true
docker rm vpn-proxy-gateway 2>/dev/null || true
docker compose -f docker-compose.server.yml up -d --wait --wait-timeout 90
elif [ "${UPDATE_DATAPLANE}" = "true" ]; then
echo "Updating control and dataplane..."
docker compose -f docker-compose.server.yml up -d --wait --wait-timeout 90
else
echo "Updating control; keeping dataplane running..."
docker compose -f docker-compose.server.yml up -d --no-deps --wait --wait-timeout 90 vpn-proxy-control
fi
echo "Current container:"
docker ps --filter "name=vpn-proxy-gateway"
echo "Current containers:"
docker ps --filter "name=vpn-proxy-gateway" --filter "name=vpn-proxy-dataplane"

View File

@@ -0,0 +1,46 @@
#!/usr/bin/env bash
set -euo pipefail
export LC_ALL=C
RUNTIME_DIR="${HARBOR_RUNTIME_DIR:-$HOME/.vpn-proxy-client/.runtime}"
STATE_FILE="$RUNTIME_DIR/network.json"
ROUTE_BIN="${HARBOR_ROUTE_BIN:-/sbin/route}"
ARP_BIN="${HARBOR_ARP_BIN:-/usr/sbin/arp}"
NETSTAT_BIN="${HARBOR_NETSTAT_BIN:-/usr/sbin/netstat}"
route_info="$($ROUTE_BIN -n get default 2>/dev/null || true)"
gateway="$(awk '/^[[:space:]]*gateway:/{print $2; exit}' <<<"$route_info")"
network_interface="$(awk '/^[[:space:]]*interface:/{print $2; exit}' <<<"$route_info")"
if [[ -z "$gateway" || -z "$network_interface" ]]; then
read -r gateway network_interface < <(
"$NETSTAT_BIN" -rn -f inet 2>/dev/null \
| awk '$1 == "default" && $2 ~ /^[0-9]+\./ { print $2, $4; exit }'
) || true
fi
if [[ ! "$gateway" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
gateway=""
network_interface=""
fi
if [[ ! "$network_interface" =~ ^[a-zA-Z0-9._-]{1,32}$ ]]; then
network_interface=""
fi
mac=""
if [[ -n "$gateway" ]]; then
mac="$($ARP_BIN -n "$gateway" 2>/dev/null | awk '/ at /{print $4; exit}' || true)"
if [[ ! "$mac" =~ ^[a-fA-F0-9]{2}(:[a-fA-F0-9]{2}){5}$ ]]; then
mac=""
else
mac="$(printf '%s' "$mac" | tr '[:upper:]' '[:lower:]')"
fi
fi
mkdir -p "$RUNTIME_DIR"
tmp="$(mktemp "${STATE_FILE}.XXXXXX")"
trap 'rm -f "$tmp"' EXIT
printf '{"gateway":"%s","interface":"%s","mac":"%s","observedAt":"%s"}\n' \
"$gateway" "$network_interface" "$mac" "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" > "$tmp"
mv "$tmp" "$STATE_FILE"

177
scripts/harbor-version.mjs Normal file
View File

@@ -0,0 +1,177 @@
#!/usr/bin/env node
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { parseVersion, versionCompatibility } from '../src/shared/versions.js';
const COMPONENTS = ['macClient', 'gatewayClient', 'gatewayBackend'];
const VERSION_FILE = 'src/shared/versions.js';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const aliases = {
mac: 'macClient',
'mac-client': 'macClient',
client: 'gatewayClient',
'gateway-client': 'gatewayClient',
backend: 'gatewayBackend',
'gateway-backend': 'gatewayBackend',
};
export function versionsFromSource(source) {
return Object.fromEntries(COMPONENTS.map((component) => {
const match = new RegExp(`${component}:\\s*'(\\d+\\.\\d+\\.\\d+)'`).exec(source);
if (!match) throw new Error(`Не найдена версия ${component}`);
return [component, match[1]];
}));
}
export function affectedComponents(files) {
const affected = new Set();
const add = (...components) => components.forEach((component) => affected.add(component));
for (const file of files) {
if (file === VERSION_FILE) continue;
if (/^(package-lock\.json|src\/shared\/)/.test(file)) add(...COMPONENTS);
else if (/^(src\/web\/|public\/|index\.html$|vite\.config\.js$)/.test(file)) {
add('macClient', 'gatewayClient');
} else if (/^src\/server\//.test(file)) add('macClient', 'gatewayBackend');
else if (/^(install\.sh|Dockerfile\.client|docker-compose\.client(\.local)?\.yml|entrypoint\.client\.sh|scripts\/(install-macos-client|harbor-network-monitor)\.sh)$/.test(file)) {
add('macClient');
} else if (/^(Dockerfile|Dockerfile\.runtime-base|docker-compose\.gateway\.yml|entrypoint\.sh|scripts\/(deploy-gateway|build-runtime-base|build-on-107-deploy-111)\.sh)$/.test(file)) {
add('gatewayBackend');
}
}
return COMPONENTS.filter((component) => affected.has(component));
}
function formatVersion({ major, minor, hotfix }) {
return `${major}.${minor}.${hotfix}`;
}
export function bumpVersions(versions, level, requested = []) {
const current = Object.fromEntries(COMPONENTS.map((component) => {
const parsed = parseVersion(versions[component]);
if (!parsed) throw new Error(`Некорректная версия ${component}: ${versions[component]}`);
return [component, parsed];
}));
if (level === 'major') {
const major = Math.max(...COMPONENTS.map((component) => current[component].major)) + 1;
return Object.fromEntries(COMPONENTS.map((component) => [component, `${major}.0.0`]));
}
const targets = new Set(requested.map((target) => aliases[target] || target));
if (!targets.size) throw new Error(`${level} требует хотя бы один компонент`);
for (const target of targets) {
if (!COMPONENTS.includes(target)) throw new Error(`Неизвестный компонент: ${target}`);
}
if (level === 'minor' && (targets.has('gatewayClient') || targets.has('gatewayBackend'))) {
targets.add('gatewayClient');
targets.add('gatewayBackend');
}
if (!['minor', 'hotfix'].includes(level)) throw new Error(`Неизвестный уровень: ${level}`);
const next = { ...versions };
if (level === 'minor' && targets.has('gatewayClient')) {
const minor = Math.max(current.gatewayClient.minor, current.gatewayBackend.minor) + 1;
next.gatewayClient = `${current.gatewayClient.major}.${minor}.0`;
next.gatewayBackend = `${current.gatewayBackend.major}.${minor}.0`;
targets.delete('gatewayClient');
targets.delete('gatewayBackend');
}
for (const target of targets) {
const value = current[target];
next[target] = level === 'minor'
? `${value.major}.${value.minor + 1}.0`
: formatVersion({ ...value, hotfix: value.hotfix + 1 });
}
return next;
}
function git(args) {
return execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
}
function changedFiles(base) {
const tracked = git(['diff', '--name-only', base, '--']).split('\n');
const untracked = git(['ls-files', '--others', '--exclude-standard']).split('\n');
return [...new Set([...tracked, ...untracked].filter(Boolean))];
}
function baselineVersions(base) {
try {
return versionsFromSource(git(['show', `${base}:${VERSION_FILE}`]));
} catch {
return null;
}
}
function compareVersions(before, after) {
const left = parseVersion(before);
const right = parseVersion(after);
if (!left || !right) return -1;
for (const key of ['major', 'minor', 'hotfix']) {
if (right[key] !== left[key]) return right[key] > left[key] ? 1 : -1;
}
return 0;
}
function validateCompatibility(versions) {
const compatibility = versionCompatibility(versions);
if (!compatibility.major) throw new Error('У всех компонентов должен совпадать major');
if (!compatibility.gateway) throw new Error('Gateway client и backend должны совпадать по major.minor');
}
function writeVersions(versions) {
const file = path.join(root, VERSION_FILE);
let source = fs.readFileSync(file, 'utf8');
for (const component of COMPONENTS) {
source = source.replace(
new RegExp(`(${component}:\\s*')\\d+\\.\\d+\\.\\d+(')`),
`$1${versions[component]}$2`,
);
}
fs.writeFileSync(file, source);
}
function printVersions(versions) {
for (const component of COMPONENTS) console.log(`${component}: ${versions[component]}`);
}
function main([command = 'check', ...args]) {
const source = fs.readFileSync(path.join(root, VERSION_FILE), 'utf8');
const current = versionsFromSource(source);
validateCompatibility(current);
if (command === 'bump') {
const next = bumpVersions(current, args[0], args.slice(1));
validateCompatibility(next);
writeVersions(next);
printVersions(next);
return;
}
const base = args[0] || 'HEAD';
const affected = affectedComponents(changedFiles(base));
if (command === 'affected') {
console.log(affected.length ? affected.join('\n') : 'Нет изменений, требующих bump.');
return;
}
if (command !== 'check') throw new Error(`Неизвестная команда: ${command}`);
const baseline = baselineVersions(base);
if (!baseline) {
console.log('Version contract создаётся впервые; baseline для bump отсутствует.');
return;
}
const missing = affected.filter((component) => compareVersions(baseline[component], current[component]) <= 0);
if (missing.length) throw new Error(`Не повышена версия: ${missing.join(', ')}`);
console.log(affected.length ? `Version check: ${affected.join(', ')}` : 'Version check: bump не требуется.');
}
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
try {
main(process.argv.slice(2));
} catch (error) {
console.error(`[harbor-version] ${error.message}`);
process.exitCode = 1;
}
}

View File

@@ -2,20 +2,23 @@
set -euo pipefail
INSTALL_DIR="${VPN_PROXY_INSTALL_DIR:-$HOME/.vpn-proxy-client}"
REPO_URL="${VPN_PROXY_REPO_URL:-https://git.dokops.ru/dokril/vpn-proxy.git}"
BRANCH="${VPN_PROXY_BRANCH:-master}"
ARCHIVE_URL="${VPN_PROXY_ARCHIVE_URL:-https://git.dokops.ru/dokril/vpn-proxy/archive/${BRANCH}.tar.gz}"
SOURCE_DIR="${VPN_PROXY_SOURCE_DIR:-}"
COMPOSE_FILE="docker-compose.client.yml"
DEFAULT_PROXY_PORT="8082"
REQUESTED_PROXY_PORT="${VPN_PROXY_CLIENT_PORT:-}"
REQUESTED_UI_PORT="${VPN_PROXY_CLIENT_UI_PORT:-${CLIENT_UI_PORT:-}}"
CLIENT_CONTAINER_NAME="vpn-proxy-client"
CLIENT_CONTAINER_NAME="harbor-connect"
LEGACY_CLIENT_CONTAINER_NAME="vpn-proxy-client"
NETWORK_MONITOR_LABEL="com.dokril.harbor-connect.network"
log() {
printf '[vpn-proxy-client] %s\n' "$*"
printf '[harbor-connect] %s\n' "$*"
}
die() {
printf '[vpn-proxy-client] error: %s\n' "$*" >&2
printf '[harbor-connect] error: %s\n' "$*" >&2
exit 1
}
@@ -66,7 +69,7 @@ published_port_conflicts() {
while IFS= read -r line; do
[ -n "$line" ] || continue
case "$line" in
"${CLIENT_CONTAINER_NAME}"$'\t'*) ;;
"${CLIENT_CONTAINER_NAME}"$'\t'*|"${LEGACY_CLIENT_CONTAINER_NAME}"$'\t'*) ;;
*) printf '%s\n' "$line" ;;
esac
done < <(docker ps --filter "publish=${port}" --format '{{.Names}} {{.Ports}}')
@@ -85,7 +88,7 @@ assert_proxy_port_available() {
return 0
fi
printf '[vpn-proxy-client] proxy port %s is already used:\n%s\n' \
printf '[harbor-connect] proxy port %s is already used:\n%s\n' \
"$port" "$conflicts" >&2
die "choose another proxy port with VPN_PROXY_CLIENT_PORT=<port> or stop the conflicting container"
}
@@ -100,7 +103,7 @@ assert_single_port_available() {
return 0
fi
printf '[vpn-proxy-client] %s port %s is already used:\n%s\n' \
printf '[harbor-connect] %s port %s is already used:\n%s\n' \
"$label" "$port" "$conflicts" >&2
die "choose another ${label} port or stop the conflicting container"
}
@@ -167,14 +170,62 @@ wait_for_client_ui() {
sleep 1
done
printf '\n[vpn-proxy-client] client did not become ready at %s\n' "$ui_url" >&2
printf '[vpn-proxy-client] docker compose status:\n' >&2
printf '\n[harbor-connect] client did not become ready at %s\n' "$ui_url" >&2
printf '[harbor-connect] docker compose status:\n' >&2
docker compose -f "$COMPOSE_FILE" ps >&2 || true
printf '\n[vpn-proxy-client] recent service logs:\n' >&2
docker compose -f "$COMPOSE_FILE" logs --tail=120 vpn-proxy-client >&2 || true
printf '\n[harbor-connect] recent service logs:\n' >&2
docker compose -f "$COMPOSE_FILE" logs --tail=120 harbor-connect >&2 || true
die "client UI is not ready; see Docker status and logs above"
}
xml_escape() {
sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g' -e 's/"/\&quot;/g'
}
install_network_monitor() {
local launch_agents_dir="$HOME/Library/LaunchAgents"
local plist_path="$launch_agents_dir/${NETWORK_MONITOR_LABEL}.plist"
local escaped_script_path
local escaped_runtime_dir
local user_domain="gui/$(id -u)"
escaped_script_path="$(printf '%s' "$INSTALL_DIR/scripts/harbor-network-monitor.sh" | xml_escape)"
escaped_runtime_dir="$(printf '%s' "$INSTALL_DIR/.runtime" | xml_escape)"
mkdir -p "$INSTALL_DIR/.runtime" "$launch_agents_dir"
cat > "$plist_path" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>${NETWORK_MONITOR_LABEL}</string>
<key>ProgramArguments</key>
<array>
<string>/bin/bash</string>
<string>${escaped_script_path}</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>HARBOR_RUNTIME_DIR</key>
<string>${escaped_runtime_dir}</string>
</dict>
<key>RunAtLoad</key>
<true/>
<key>StartInterval</key>
<integer>5</integer>
<key>ProcessType</key>
<string>Background</string>
</dict>
</plist>
EOF
/bin/bash "$INSTALL_DIR/scripts/harbor-network-monitor.sh"
launchctl bootout "$user_domain" "$plist_path" >/dev/null 2>&1 || true
launchctl bootstrap "$user_domain" "$plist_path"
log "automatic Gateway detection enabled"
}
set_env_value() {
local key="$1"
local value="$2"
@@ -204,26 +255,49 @@ get_env_value() {
' .env
}
copy_source() {
local source_dir="$1"
[ -f "$source_dir/docker-compose.client.yml" ] || die "invalid Harbor source archive"
log "installing files to $INSTALL_DIR"
mkdir -p "$INSTALL_DIR"
cp -R "$source_dir/." "$INSTALL_DIR/"
}
download_source() {
local tmp_dir
tmp_dir="$(mktemp -d)"
mkdir -p "$tmp_dir/source"
log "downloading $ARCHIVE_URL"
if ! curl -fsSL "$ARCHIVE_URL" | tar -xzf - -C "$tmp_dir/source" --strip-components=1; then
rm -rf "$tmp_dir"
die "failed to download Harbor source"
fi
copy_source "$tmp_dir/source"
rm -rf "$tmp_dir"
}
if [[ "$(uname -s)" != "Darwin" ]]; then
die "this installer is intended for macOS"
fi
need git
need docker
need curl
need tar
docker compose version >/dev/null 2>&1 || die "Docker Compose plugin is required"
docker info >/dev/null 2>&1 || die "Docker Desktop is not running"
if [[ -d "$INSTALL_DIR/.git" ]]; then
if [[ -n "$SOURCE_DIR" ]]; then
copy_source "$SOURCE_DIR"
elif [[ -d "$INSTALL_DIR/.git" ]]; then
need git
log "updating $INSTALL_DIR"
git -C "$INSTALL_DIR" fetch origin "$BRANCH"
git -C "$INSTALL_DIR" checkout "$BRANCH"
git -C "$INSTALL_DIR" pull --ff-only origin "$BRANCH"
else
log "cloning $REPO_URL#$BRANCH to $INSTALL_DIR"
mkdir -p "$(dirname "$INSTALL_DIR")"
git clone --branch "$BRANCH" "$REPO_URL" "$INSTALL_DIR"
download_source
fi
cd "$INSTALL_DIR"
@@ -247,13 +321,15 @@ set_env_value PROXY_PORT "$PROXY_PORT"
log "UI port: http://127.0.0.1:${UI_PORT}"
log "proxy port: 127.0.0.1:${PROXY_PORT}"
install_network_monitor
log "building and starting Docker client"
docker compose -f "$COMPOSE_FILE" up -d --build
docker compose -f "$COMPOSE_FILE" up -d --build --remove-orphans
wait_for_client_ui
cat <<EOF
VPN Proxy Client is running.
Harbor Connect is running.
UI:
http://127.0.0.1:${UI_PORT}

View File

@@ -15,6 +15,8 @@ export const settings = {
port: parsePort(process.env.PORT, 3456),
proxyPort,
tproxyPort: parsePort(process.env.TPROXY_PORT, 7895),
tproxyChain: process.env.TPROXY_CHAIN || "VPN_PROXY_TPROXY",
dataplaneSocket: process.env.DATAPLANE_SOCKET || "/run/vpn-proxy/dataplane.sock",
bindIp: process.env.PROXY_BIND_IP || "0.0.0.0",
dataDir,
distDir: process.env.DIST_DIR || "/app/dist",
@@ -24,6 +26,10 @@ export const settings = {
statePath: path.join(dataDir, "state.json"),
subscriptionCachePath: path.join(dataDir, "subscription-cache.json"),
sharedProxyHost: process.env.SHARED_PROXY_HOST || "",
hostNetworkStatePath:
process.env.HARBOR_HOST_NETWORK_STATE || "/run/harbor-host/network.json",
gatewayPresencePort: parsePort(process.env.HARBOR_GATEWAY_CONTROL_PORT, 3456),
subscriptionTimeoutMs: parsePort(process.env.SUBSCRIPTION_TIMEOUT_MS, 15_000),
hwidPath: path.join(dataDir, "hwid"),
logLevel: process.env.LOG_LEVEL || "info",
appName: "VPN Proxy Gateway",

74
src/server/dataplane.js Normal file
View File

@@ -0,0 +1,74 @@
import fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
import { settings } from './config.js';
import { createSingboxRuntime } from './singboxRuntime.js';
import { buildVersionInfo } from './version.js';
const socketPath = settings.dataplaneSocket;
const runtime = createSingboxRuntime({
configPath: settings.configPath,
gateway: true,
tproxyChain: settings.tproxyChain,
});
const versionInfo = buildVersionInfo('gateway');
let ready = false;
function sendJson(res, statusCode, payload) {
res.writeHead(statusCode, { 'content-type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(payload));
}
const server = http.createServer(async (req, res) => {
try {
if (req.method === 'GET' && req.url === '/status') {
return sendJson(res, ready ? 200 : 503, {
...await runtime.refresh(),
gatewayBackendVersion: versionInfo.components.gatewayBackend,
singBoxVersion: versionInfo.runtime.singBox,
ready,
});
}
if (req.method === 'POST' && req.url === '/apply') {
return sendJson(res, 200, await runtime.apply());
}
if (req.method === 'POST' && req.url === '/restart') {
return sendJson(res, 200, await runtime.restart());
}
if (req.method === 'POST' && req.url === '/stop') {
return sendJson(res, 200, await runtime.stop());
}
return sendJson(res, 404, { error: 'Не найдено' });
} catch (error) {
return sendJson(res, 500, { error: error.message || String(error) });
}
});
fs.mkdirSync(path.dirname(socketPath), { recursive: true });
fs.rmSync(socketPath, { force: true });
server.listen(socketPath, async () => {
fs.chmodSync(socketPath, 0o660);
try {
await runtime.apply();
} catch (error) {
console.warn(`[dataplane] sing-box не запущен: ${error.message}`);
} finally {
ready = true;
console.log(`[dataplane] control socket: ${socketPath}`);
}
});
let shuttingDown = false;
async function shutdown() {
if (shuttingDown) return;
shuttingDown = true;
ready = false;
await runtime.shutdown();
server.close(() => {
fs.rmSync(socketPath, { force: true });
process.exit(0);
});
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);

View File

@@ -0,0 +1,51 @@
import http from 'node:http';
import { HarborError } from '../shared/errors.js';
function request(socketPath, pathname, method = 'GET') {
return new Promise((resolve, reject) => {
const req = http.request({ socketPath, path: pathname, method }, (res) => {
const chunks = [];
res.on('data', (chunk) => chunks.push(chunk));
res.on('end', () => {
let body = {};
try {
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
} catch {
return reject(new Error('Dataplane вернул невалидный JSON'));
}
if ((res.statusCode || 500) >= 400) {
return reject(new Error(body.error || `Dataplane HTTP ${res.statusCode}`));
}
resolve(body);
});
});
req.on('error', reject);
req.setTimeout(6000, () => req.destroy(new Error('Dataplane не ответил за 6 секунд')));
req.end();
});
}
export function createDataplaneClient(socketPath, send = request) {
let current = { running: false, startedAt: null };
const update = async (pathname, method) => {
try {
current = await send(socketPath, pathname, method);
return current;
} catch (cause) {
if (pathname === '/apply' || pathname === '/restart') {
throw new HarborError('PROCESS_START_FAILED', { cause });
}
throw cause;
}
};
return {
get running() { return Boolean(current.running); },
get startedAt() { return current.startedAt || null; },
refresh: () => update('/status', 'GET'),
apply: () => update('/apply', 'POST'),
restart: () => update('/restart', 'POST'),
stop: () => update('/stop', 'POST'),
shutdown: async () => current,
};
}

View File

@@ -0,0 +1,228 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import { HarborError } from '../shared/errors.js';
const NONCE_RE = /^[a-f0-9]{32}$/;
const PROOF_RE = /^[a-f0-9]{64}$/;
const INTERFACE_RE = /^[a-zA-Z0-9._-]{1,32}$/;
const MAC_RE = /^[a-f0-9]{2}(?::[a-f0-9]{2}){5}$/i;
const SECRET_QUERY_KEYS = new Set(['access_token', 'auth', 'key', 'secret', 'token', 'uuid']);
function isIpv4(value) {
const parts = String(value || '').split('.');
return parts.length === 4 && parts.every((part) => (
/^\d{1,3}$/.test(part) && Number(part) >= 0 && Number(part) <= 255
));
}
function subscriptionSecret(subscriptionUrl) {
try {
const url = new URL(String(subscriptionUrl || '').trim());
const pathSegments = url.pathname.split('/').filter(Boolean);
const candidates = [
url.username,
url.password,
...[...url.searchParams.entries()]
.filter(([key]) => SECRET_QUERY_KEYS.has(key.toLowerCase()))
.map(([, value]) => value),
pathSegments.at(-1),
]
.map((value) => String(value || '').trim())
.filter((value) => value.length >= 16);
if (!candidates.length) return '';
url.hash = '';
url.searchParams.sort();
return url.toString();
} catch {
return '';
}
}
function presenceProof(subscriptionUrl, nonce, gatewayId) {
const credentialUrl = subscriptionSecret(subscriptionUrl);
if (!credentialUrl) return '';
const key = crypto.createHash('sha256')
.update(`harbor-gateway-presence-key\n${credentialUrl}`)
.digest();
return crypto.createHmac('sha256', key)
.update(`v1\n${nonce}\n${gatewayId}`)
.digest('hex');
}
export function buildGatewayPresence({ appMode, subscriptionUrl, gatewayId, nonce }) {
if (!NONCE_RE.test(String(nonce || ''))) {
throw new HarborError('REQUEST_INVALID');
}
const subscription = String(subscriptionUrl || '').trim();
const id = String(gatewayId || '').trim();
if (appMode !== 'gateway' || !subscriptionSecret(subscription) || !id) {
return {
success: true,
available: false,
product: 'harbor',
role: appMode,
protocolVersion: 1,
};
}
return {
success: true,
available: true,
product: 'harbor',
role: 'gateway',
protocolVersion: 1,
gatewayId: id,
transparentRouting: true,
proof: presenceProof(subscription, nonce, id),
};
}
export function verifyGatewayPresence(payload, { subscriptionUrl, nonce }) {
if (
payload?.available !== true ||
payload?.product !== 'harbor' ||
payload?.role !== 'gateway' ||
payload?.protocolVersion !== 1 ||
payload?.transparentRouting !== true ||
!payload.gatewayId ||
!NONCE_RE.test(String(nonce || '')) ||
!PROOF_RE.test(String(payload.proof || ''))
) return false;
const actual = Buffer.from(payload.proof, 'hex');
const expectedProof = presenceProof(subscriptionUrl, nonce, String(payload.gatewayId));
if (!expectedProof) return false;
const expected = Buffer.from(expectedProof, 'hex');
return crypto.timingSafeEqual(actual, expected);
}
export async function probeGatewayPresence({
gateway,
subscriptionUrl,
port = 3456,
fetchImpl = fetch,
timeoutMs = 1000,
nonce = crypto.randomBytes(16).toString('hex'),
}) {
if (!isIpv4(gateway)) throw new Error('Некорректный адрес default gateway');
const presenceUrl = `http://${gateway}:${port}/api/gateway-presence?nonce=${nonce}`;
const response = await fetchImpl(
presenceUrl,
{ headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeoutMs) },
);
const payload = await response.json().catch(() => ({}));
if (!response.ok || !verifyGatewayPresence(payload, { subscriptionUrl, nonce })) {
throw new Error('Текущий default gateway не является доверенным Harbor Gateway');
}
return {
gatewayId: payload.gatewayId,
uiOrigin: new URL(presenceUrl).origin,
verifiedAt: new Date().toISOString(),
};
}
export function normalizeHostNetworkState(value, {
now = Date.now(),
maxAgeMs = 15_000,
} = {}) {
const gateway = String(value?.gateway || '').trim();
const networkInterface = String(value?.interface || '').trim();
const mac = String(value?.mac || '').trim().toLowerCase();
const observedAt = Date.parse(value?.observedAt || '');
// ponytail: IPv4-only matches the current Gateway; add IPv6 when its TProxy path supports it.
if (
!isIpv4(gateway) ||
!INTERFACE_RE.test(networkInterface) ||
!MAC_RE.test(mac) ||
!Number.isFinite(observedAt) ||
observedAt > now + 5_000 ||
now - observedAt > maxAgeMs
) return null;
return { gateway, interface: networkInterface, mac, observedAt };
}
export function readHostNetworkState(filePath, options) {
try {
return normalizeHostNetworkState(
JSON.parse(fs.readFileSync(filePath, 'utf8')),
options,
);
} catch {
return null;
}
}
export function sameGatewayRoute(previous, current) {
return Boolean(
previous &&
current &&
previous.gateway === current.gateway &&
previous.interface === current.interface &&
previous.mac === current.mac,
);
}
export function createGatewayAutoState() {
return {
mode: 'local-vpn',
failures: 0,
gateway: null,
gatewayId: '',
uiOrigin: '',
lastVerifiedAt: null,
lastError: '',
};
}
export function applyGatewayPreference(state, enabled) {
return {
...state,
mode: enabled && state.gatewayId ? 'gateway-direct' : 'local-vpn',
};
}
export function nextGatewayAutoState(current, {
network,
verifiedGateway = null,
error = 'Gateway presence check failed',
}) {
if (!network) {
if (!current.gatewayId) return createGatewayAutoState();
return {
...current,
failures: current.failures + 1,
lastError: String(error || 'Gateway presence check failed'),
};
}
const routeChanged = !sameGatewayRoute(current.gateway, network);
const base = routeChanged
? { ...createGatewayAutoState(), gateway: network }
: { ...current, gateway: network };
if (verifiedGateway?.gatewayId) {
return {
...base,
mode: 'gateway-direct',
failures: 0,
gatewayId: verifiedGateway.gatewayId,
uiOrigin: verifiedGateway.uiOrigin || '',
lastVerifiedAt: verifiedGateway.verifiedAt || new Date().toISOString(),
lastError: '',
};
}
const failures = base.failures + 1;
return {
...base,
mode: base.gatewayId ? 'gateway-direct' : 'local-vpn',
failures,
lastError: String(error || 'Gateway presence check failed'),
};
}

View File

@@ -0,0 +1,23 @@
import { spawnSync } from 'node:child_process';
const options = { encoding: 'utf8' };
export function setGatewayInterception(enabled, chain, run = spawnSync) {
const rule = ['-w', '-t', 'mangle', 'PREROUTING', '-j', chain];
const exists = run('iptables', [...rule.slice(0, 3), '-C', ...rule.slice(3)], options).status === 0;
if (!enabled) {
if (exists) run('iptables', [...rule.slice(0, 3), '-D', ...rule.slice(3)], options);
return;
}
if (exists) return;
const result = run(
'iptables',
[...rule.slice(0, 3), '-I', 'PREROUTING', '1', '-j', chain],
options,
);
if (result.status !== 0) {
throw new Error((result.stderr || 'Не удалось включить Gateway VPN').trim());
}
}

View File

@@ -1,37 +1,145 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
import { spawn, spawnSync } from 'node:child_process';
import { isDeepStrictEqual } from 'node:util';
import { createDataplaneClient } from './dataplaneClient.js';
import { settings } from './config.js';
import {
applyGatewayPreference,
buildGatewayPresence,
createGatewayAutoState,
nextGatewayAutoState,
probeGatewayPresence,
readHostNetworkState,
sameGatewayRoute,
} from './gatewayPresence.js';
import { createSingboxRuntime } from './singboxRuntime.js';
import { tcpPing } from './ping.js';
import { checkServerHealth } from './serverHealth.js';
import { buildSharedProxyInfo } from './sharedProxy.js';
import {
buildGatewayConfig,
removeSingboxConfig,
restoreSingboxConfig,
writeSingboxConfig,
} from './singbox.js';
import { fetchSubscription, fetchSubscriptionInfo } from './subscription.js';
import {
fetchSubscription,
getHwid,
normalizeSubscriptionConfig,
selectRefreshedServer,
} from './subscription.js';
import {
createStateSnapshot,
normalizeStoredState,
withStateV0Compatibility,
} from '../shared/contracts/state.js';
import { HarborError, normalizeHarborError } from '../shared/errors.js';
import { normalizeRouteRules } from '../shared/routingRules.js';
import { createJsonStore, createStateStore } from './services/stateStore.js';
import { buildGatewayVersionInfo, buildVersionInfo } from './version.js';
const MAX_BODY_BYTES = 1_000_000;
const SUBSCRIPTION_REFRESH_INTERVAL_MS = 15 * 60 * 1000;
const GATEWAY_DISCOVERY_INTERVAL_MS = 5_000;
const TERMINAL_SUBSCRIPTION_CODES = new Set([
'SUBSCRIPTION_EXPIRED',
'SUBSCRIPTION_DISABLED',
'SUBSCRIPTION_REJECTED',
]);
fs.mkdirSync(settings.dataDir, { recursive: true });
let singboxProcess = null;
let singboxStartedAt = null;
const stateStore = createStateStore(settings.statePath);
const subscriptionCacheStore = createJsonStore({
filePath: settings.subscriptionCachePath,
defaultValue: null,
});
let cacheRecoveryLogged = false;
function readJson(filePath, fallback) {
function readSubscriptionCache() {
const cached = subscriptionCacheStore.read();
if (subscriptionCacheStore.recovery && !cacheRecoveryLogged) {
cacheRecoveryLogged = true;
console.warn(`[storage] corrupt subscription cache recovered; backup: ${subscriptionCacheStore.recovery.backupPath}`);
}
return cached?.config
? { ...cached, ...normalizeSubscriptionConfig(cached.config), _persisted: cached }
: cached;
}
const initialStoredState = stateStore.read();
if (stateStore.migration) {
console.log(`[storage] state migrated to v${stateStore.migration.toVersion}; backup: ${stateStore.migration.backupPath}`);
}
if (stateStore.recovery) {
console.warn(`[storage] corrupt state recovered; backup: ${stateStore.recovery.backupPath}`);
}
const remoteDataplane = settings.appMode === 'gateway' && Boolean(process.env.DATAPLANE_SOCKET);
const versionInfo = buildVersionInfo(settings.appMode);
const singboxRuntime = remoteDataplane
? createDataplaneClient(settings.dataplaneSocket)
: createSingboxRuntime({
configPath: settings.configPath,
gateway: settings.appMode === 'gateway',
tproxyChain: settings.tproxyChain,
});
let subscriptionRefreshPromise = null;
let subscriptionRefreshTimer = null;
let gatewayDiscoveryPromise = null;
let gatewayDiscoveryTimer = null;
let gatewayAutoState = createGatewayAutoState();
let controlOperation = Promise.resolve();
let operationState = stateStore.recovery ? {
kind: 'storage-recovery',
status: 'failed',
startedAt: stateStore.recovery.recoveredAt,
error: `Повреждённый state сохранён: ${path.basename(stateStore.recovery.backupPath)}`,
} : { kind: null, status: 'idle', startedAt: null, error: null };
let revision = normalizeStoredState(initialStoredState).revision;
function updateStoredState(update) {
return stateStore.update((stored) => {
const current = normalizeStoredState(stored);
const next = normalizeStoredState({ schemaVersion: current.schemaVersion, ...update(current) });
revision = Math.max(revision, current.revision) + 1;
next.revision = revision;
return next;
});
}
async function withOperation(kind, operation) {
operationState = {
kind,
status: 'running',
startedAt: new Date().toISOString(),
error: null,
};
updateStoredState((state) => state);
try {
return fs.existsSync(filePath)
? JSON.parse(fs.readFileSync(filePath, 'utf8'))
: fallback;
} catch {
return fallback;
const result = await operation();
operationState = { kind: null, status: 'idle', startedAt: null, error: null };
updateStoredState((state) => state);
return result;
} catch (error) {
const harborError = normalizeHarborError(error);
operationState = {
...operationState,
status: 'failed',
error: harborError.message,
};
updateStoredState((state) => state);
throw error;
}
}
function writeJson(filePath, value) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(value, null, 2), 'utf8');
function serializeControl(operation) {
const result = controlOperation.then(operation, operation);
// The caller observes result; this settled tail only keeps the next operation runnable.
controlOperation = result.then(() => undefined, () => undefined);
return result;
}
function sendJson(res, statusCode, payload) {
@@ -39,6 +147,29 @@ function sendJson(res, statusCode, payload) {
res.end(JSON.stringify(payload));
}
function redactLogDetails(value) {
return String(value || '').replace(/https?:\/\/\S+/gi, '[redacted-url]');
}
function sendError(res, error) {
const harborError = normalizeHarborError(error);
const correlationId = crypto.randomUUID();
const technical = harborError.cause?.message || harborError.details || error;
console.error(
`[control] request failed [${correlationId}] ${harborError.code}: ${redactLogDetails(technical?.message || technical)}`,
);
return sendJson(res, harborError.status, {
success: false,
error: {
code: harborError.code,
message: harborError.message,
retryable: harborError.retryable,
correlationId,
...(harborError.details ? { details: harborError.details } : {}),
},
});
}
function readBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
@@ -49,9 +180,7 @@ function readBody(req) {
size += chunk.length;
if (size > MAX_BODY_BYTES) {
tooLarge = true;
const error = new Error('Тело запроса слишком большое');
error.statusCode = 413;
reject(error);
reject(new HarborError('REQUEST_INVALID'));
return;
}
chunks.push(chunk);
@@ -61,10 +190,8 @@ function readBody(req) {
if (!chunks.length) return resolve({});
try {
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
} catch {
const error = new Error('Невалидный JSON в теле запроса');
error.statusCode = 400;
reject(error);
} catch (cause) {
reject(new HarborError('REQUEST_INVALID', { cause }));
}
});
req.on('error', reject);
@@ -79,183 +206,529 @@ function subscriptionHost(url) {
}
}
function checkSingboxConfig() {
const result = spawnSync('sing-box', ['check', '-c', settings.configPath], {
encoding: 'utf8',
});
if (result.status !== 0) {
throw new Error((result.stderr || result.stdout || 'sing-box check failed').trim());
}
}
function stopSingbox() {
return new Promise((resolve) => {
if (!singboxProcess) {
singboxStartedAt = null;
return resolve();
}
const current = singboxProcess;
singboxProcess = null;
singboxStartedAt = null;
const timeout = setTimeout(() => {
current.kill('SIGKILL');
resolve();
}, 4000);
current.once('exit', () => {
clearTimeout(timeout);
resolve();
});
current.kill('SIGTERM');
function buildActiveConfig(
subscriptionConfig,
selectedServerId,
routeRules = stateStore.read().routeRules,
) {
return buildGatewayConfig(subscriptionConfig, selectedServerId, {
clientDirect: settings.appMode === 'client' && gatewayAutoState.mode === 'gateway-direct',
routeRules,
});
}
async function startSingbox() {
if (!fs.existsSync(settings.configPath)) return false;
checkSingboxConfig();
await stopSingbox();
const stopSingbox = () => singboxRuntime.stop();
const startSingbox = () => singboxRuntime.apply();
const child = spawn('sing-box', ['run', '-c', settings.configPath], {
stdio: ['ignore', 'inherit', 'inherit'],
function resetSavedSubscription({ stopRuntime = true } = {}) {
return serializeControl(async () => {
if (stopRuntime) await stopSingbox();
removeSingboxConfig();
subscriptionCacheStore.remove();
updateStoredState((state) => ({ routeRules: state.routeRules }));
gatewayAutoState = createGatewayAutoState();
});
singboxProcess = child;
singboxStartedAt = new Date().toISOString();
child.once('exit', () => {
if (singboxProcess === child) {
singboxProcess = null;
singboxStartedAt = null;
}
}
async function publicState() {
const runtime = await singboxRuntime.refresh();
const state = normalizeStoredState(stateStore.read());
const gatewayAutoEnabled = state.gatewayAutoEnabled !== false;
const configExists = fs.existsSync(settings.configPath);
const snapshot = createStateSnapshot({
storedState: state,
runtime,
gatewayAuto: gatewayAutoState,
appMode: settings.appMode,
configExists,
subscriptionHost: subscriptionHost(state.subscriptionUrl),
operation: operationState,
});
return withStateV0Compatibility(snapshot, {
storedState: { ...state, gatewayAutoEnabled },
gatewayAuto: gatewayAutoState,
port: settings.port,
proxyPort: settings.proxyPort,
configExists,
});
}
function writeCurrentConfig() {
const state = stateStore.read();
const cached = readSubscriptionCache();
if (!state.selectedServerId || !cached?.config) return false;
writeSingboxConfig(buildActiveConfig(cached.config, state.selectedServerId));
return true;
}
function publicState() {
const state = readJson(settings.statePath, {});
return {
mode: settings.appMode,
port: settings.port,
proxyPort: settings.proxyPort,
configExists: fs.existsSync(settings.configPath),
singboxRunning: Boolean(singboxProcess),
singboxStartedAt,
subscriptionHost: subscriptionHost(state.subscriptionUrl),
hasSubscription: Boolean(state.subscriptionUrl),
selectedTag: state.selectedTag || '',
userInfo: state.userInfo || {},
fetchedAt: state.fetchedAt || null,
servers: (state.servers || []).map((server) => ({
...server,
tag: String(server.tag || '').trim(),
})),
};
}
async function applySelectedServer(selectedTag) {
const cached = readJson(settings.subscriptionCachePath, null);
if (!cached?.config) throw new Error('Сначала загрузите подписку');
async function applyGatewayAutoState(nextState, { reconfigure = true } = {}) {
const previousState = gatewayAutoState;
const stateChanged = !isDeepStrictEqual(previousState, nextState);
const modeChanged = previousState.mode !== nextState.mode;
gatewayAutoState = nextState;
if (!modeChanged) {
if (stateChanged) updateStoredState((state) => state);
return;
}
const previousConfig = fs.existsSync(settings.configPath)
? fs.readFileSync(settings.configPath, 'utf8')
: null;
writeSingboxConfig(buildGatewayConfig(cached.config, selectedTag));
const wasRunning = singboxRuntime.running;
try {
const configured = writeCurrentConfig();
if (reconfigure && configured && wasRunning) await startSingbox();
} catch (error) {
gatewayAutoState = previousState;
if (previousConfig === null) removeSingboxConfig();
else restoreSingboxConfig(previousConfig);
throw error;
}
if (stateChanged) updateStoredState((state) => state);
const route = nextState.gateway?.gateway ? ` (${nextState.gateway.gateway})` : '';
console.log(`[control] client route: ${nextState.mode}${route}`);
}
function refreshGatewayAutoMode({ reconfigure = true } = {}) {
if (settings.appMode !== 'client') return Promise.resolve(gatewayAutoState);
if (gatewayDiscoveryPromise) return gatewayDiscoveryPromise;
gatewayDiscoveryPromise = serializeControl(async () => {
const state = stateStore.read();
const network = state.subscriptionUrl
? readHostNetworkState(settings.hostNetworkStatePath)
: null;
if (!network) {
const discoveryError = 'macOS default gateway недоступен или устарел';
const discoveredState = nextGatewayAutoState(gatewayAutoState, {
network: null,
error: discoveryError,
});
const nextState = applyGatewayPreference(
state.subscriptionUrl
? { ...discoveredState, lastError: discoveryError }
: discoveredState,
state.gatewayAutoEnabled !== false,
);
await applyGatewayAutoState(
nextState,
{ reconfigure },
);
return gatewayAutoState;
}
if (
gatewayAutoState.mode === 'gateway-direct' &&
!sameGatewayRoute(gatewayAutoState.gateway, network)
) {
await applyGatewayAutoState(
nextGatewayAutoState(gatewayAutoState, { network }),
{ reconfigure },
);
}
try {
const verifiedGateway = await probeGatewayPresence({
gateway: network.gateway,
port: settings.gatewayPresencePort,
subscriptionUrl: state.subscriptionUrl,
});
const latestState = stateStore.read();
const latestNetwork = latestState.subscriptionUrl
? readHostNetworkState(settings.hostNetworkStatePath)
: null;
if (
latestState.subscriptionUrl !== state.subscriptionUrl ||
!sameGatewayRoute(network, latestNetwork)
) {
await applyGatewayAutoState(createGatewayAutoState(), { reconfigure });
return gatewayAutoState;
}
await applyGatewayAutoState(
applyGatewayPreference(
nextGatewayAutoState(gatewayAutoState, { network: latestNetwork, verifiedGateway }),
latestState.gatewayAutoEnabled !== false,
),
{ reconfigure },
);
} catch (error) {
const reason = error?.message || 'Gateway presence check failed';
const latestState = stateStore.read();
const latestNetwork = latestState.subscriptionUrl
? readHostNetworkState(settings.hostNetworkStatePath)
: null;
if (
latestState.subscriptionUrl !== state.subscriptionUrl ||
!sameGatewayRoute(network, latestNetwork)
) {
await applyGatewayAutoState(createGatewayAutoState(), { reconfigure });
return gatewayAutoState;
}
if (gatewayAutoState.lastError !== reason) {
console.warn(`[control] Gateway не используется: ${reason}`);
}
await applyGatewayAutoState(
applyGatewayPreference(
nextGatewayAutoState(gatewayAutoState, { network: latestNetwork, error: reason }),
latestState.gatewayAutoEnabled !== false,
),
{ reconfigure },
);
}
return gatewayAutoState;
}).finally(() => {
gatewayDiscoveryPromise = null;
});
return gatewayDiscoveryPromise;
}
async function applySelectedServer(selectedServerId, { persist = true } = {}) {
const cached = readSubscriptionCache();
if (!cached?.config) throw new HarborError('CONFIG_INVALID');
const nextConfig = buildActiveConfig(cached.config, selectedServerId);
if (persist) {
updateStoredState((state) => ({
...state,
selectedServerId,
connectionDesired: 'running',
}));
}
const previousConfig = fs.existsSync(settings.configPath)
? fs.readFileSync(settings.configPath, 'utf8')
: null;
writeSingboxConfig(nextConfig);
try {
await startSingbox();
} catch (error) {
if (previousConfig === null) removeSingboxConfig();
else fs.writeFileSync(settings.configPath, previousConfig, 'utf8');
else restoreSingboxConfig(previousConfig);
throw error;
}
writeJson(settings.statePath, {
...readJson(settings.statePath, {}),
selectedTag,
appliedAt: new Date().toISOString(),
updateStoredState((state) => ({
...state,
...(persist ? {
appliedServerId: selectedServerId,
appliedAt: new Date().toISOString(),
} : {}),
appliedRouteRules: state.routeRules,
}));
}
async function applyRouteRules(routeRules) {
const state = normalizeStoredState(stateStore.read());
const cached = readSubscriptionCache();
if (!state.selectedServerId || !cached?.config) {
updateStoredState((current) => ({
...current,
routeRules,
routeRulesRevision: current.routeRulesRevision + 1,
}));
return;
}
const previousConfig = fs.existsSync(settings.configPath)
? fs.readFileSync(settings.configPath, 'utf8')
: null;
const wasRunning = Boolean((await singboxRuntime.refresh()).running);
try {
writeSingboxConfig(buildActiveConfig(cached.config, state.selectedServerId, routeRules));
if (wasRunning) await startSingbox();
updateStoredState((current) => ({
...current,
routeRules,
...(wasRunning ? { appliedRouteRules: routeRules } : {}),
routeRulesRevision: current.routeRulesRevision + 1,
}));
} catch (error) {
if (previousConfig === null) removeSingboxConfig();
else restoreSingboxConfig(previousConfig);
if (wasRunning) {
try {
await startSingbox();
} catch (rollbackError) {
throw new HarborError('PROCESS_START_FAILED', {
cause: new AggregateError([error, rollbackError], 'Route rules rollback failed'),
});
}
}
throw error;
}
}
async function commitSubscription(subscriptionUrl, parsed, { resetSelection = false } = {}) {
return serializeControl(async () => {
const previousState = normalizeStoredState(stateStore.read());
if (!resetSelection && previousState.subscriptionUrl !== subscriptionUrl) {
throw new HarborError('STATE_CONFLICT');
}
const selectedServerId = resetSelection
? ''
: selectRefreshedServer(
previousState.selectedServerId,
previousState.servers,
parsed.servers,
);
const candidateConfig = selectedServerId
? buildActiveConfig(parsed.config, selectedServerId, previousState.routeRules)
: null;
const previousCache = readSubscriptionCache();
const previousConfig = fs.existsSync(settings.configPath)
? fs.readFileSync(settings.configPath, 'utf8')
: null;
const previousGatewayAutoState = gatewayAutoState;
const wasRunning = Boolean((await singboxRuntime.refresh()).running);
try {
if ((resetSelection || !candidateConfig) && wasRunning) await stopSingbox();
if (candidateConfig) writeSingboxConfig(candidateConfig);
else removeSingboxConfig();
subscriptionCacheStore.write({
url: subscriptionUrl,
config: parsed.sourceConfig || parsed.config,
servers: parsed.servers,
userInfo: parsed.userInfo,
fetchedAt: parsed.fetchedAt,
});
if (!resetSelection && wasRunning && candidateConfig) await startSingbox();
updateStoredState((state) => ({
...(resetSelection ? {
routeRules: state.routeRules,
gatewayAutoEnabled: state.gatewayAutoEnabled !== false,
connectionDesired: 'stopped',
} : state),
subscriptionUrl,
servers: parsed.servers,
userInfo: parsed.userInfo,
fetchedAt: parsed.fetchedAt,
selectedServerId,
appliedServerId: selectedServerId,
...(!selectedServerId ? { connectionDesired: 'stopped' } : {}),
}));
if (resetSelection) gatewayAutoState = createGatewayAutoState();
} catch (error) {
gatewayAutoState = previousGatewayAutoState;
if (previousCache) subscriptionCacheStore.write(previousCache._persisted || previousCache);
else subscriptionCacheStore.remove();
if (previousConfig === null) removeSingboxConfig();
else restoreSingboxConfig(previousConfig);
if (wasRunning) {
try {
await startSingbox();
} catch (rollbackError) {
throw new HarborError('PROCESS_START_FAILED', {
cause: new AggregateError([error, rollbackError], 'Subscription rollback failed'),
});
}
}
throw error;
}
return {
success: true,
servers: parsed.servers,
userInfo: parsed.userInfo,
fetchedAt: parsed.fetchedAt,
selectedServerId,
selectedTag: parsed.servers.find((server) => server.id === selectedServerId)?.label || '',
};
});
}
async function importSubscription(subscriptionUrl) {
const parsed = await fetchSubscription(subscriptionUrl);
return commitSubscription(subscriptionUrl, parsed, { resetSelection: true });
}
function refreshSavedSubscription() {
if (subscriptionRefreshPromise) return subscriptionRefreshPromise;
subscriptionRefreshPromise = (async () => {
try {
const subscriptionUrl = stateStore.read().subscriptionUrl;
if (!subscriptionUrl) throw new HarborError('SUBSCRIPTION_INVALID');
const parsed = await fetchSubscription(subscriptionUrl);
return await commitSubscription(subscriptionUrl, parsed);
} catch (error) {
if (TERMINAL_SUBSCRIPTION_CODES.has(error?.code)) {
await resetSavedSubscription();
}
throw error;
}
})().finally(() => {
subscriptionRefreshPromise = null;
});
return subscriptionRefreshPromise;
}
async function sendState(res, extra = {}) {
return sendJson(res, 200, { success: true, ...extra, state: await publicState() });
}
async function handleApi(req, res) {
if (req.method === 'GET' && req.url === '/api/state') {
return sendJson(res, 200, publicState());
return sendJson(res, 200, await publicState());
}
if (req.method === 'GET' && req.url === '/api/version') {
if (!remoteDataplane) return sendJson(res, 200, versionInfo);
const runtime = await singboxRuntime.refresh();
return sendJson(res, 200, buildGatewayVersionInfo(versionInfo, runtime));
}
if (req.method === 'GET' && req.url === '/api/shared-proxy') {
return sendJson(res, 200, buildSharedProxyInfo({
appMode: settings.appMode,
proxyPort: settings.proxyPort,
running: Boolean(singboxProcess),
running: (await singboxRuntime.refresh()).running,
hostHeader: req.headers.host,
sharedProxyHost: settings.sharedProxyHost,
}));
}
const requestUrl = new URL(req.url, `http://localhost:${settings.port}`);
if (req.method === 'GET' && requestUrl.pathname === '/api/gateway-presence') {
const state = stateStore.read();
return sendJson(res, 200, buildGatewayPresence({
appMode: settings.appMode,
subscriptionUrl: state.subscriptionUrl,
gatewayId: getHwid(),
nonce: requestUrl.searchParams.get('nonce'),
}));
}
if (req.method === 'POST' && req.url === '/api/servers/ping-all') {
const state = readJson(settings.statePath, {});
const results = await Promise.all((state.servers || []).map(async (server) => ({
tag: String(server.tag || '').trim(),
...await tcpPing(server.server, server.server_port),
checkedAt: new Date().toISOString(),
})));
return sendJson(res, 200, { success: true, results });
const state = stateStore.read();
const { serverIds = [] } = await readBody(req);
const requestedIds = new Set(Array.isArray(serverIds) ? serverIds.map(String) : []);
const servers = requestedIds.size
? (state.servers || []).filter((server) => requestedIds.has(server.id))
: state.servers || [];
const results = await checkServerHealth(servers, tcpPing);
return sendState(res, { results });
}
if (req.method === 'POST' && req.url === '/api/subscription/fetch') {
const { url = '' } = await readBody(req);
const normalizedUrl = String(url).trim();
const parsed = await fetchSubscription(normalizedUrl);
writeJson(settings.subscriptionCachePath, { url: normalizedUrl, ...parsed });
writeJson(settings.statePath, {
subscriptionUrl: normalizedUrl,
servers: parsed.servers,
userInfo: parsed.userInfo,
fetchedAt: parsed.fetchedAt,
const parsed = await withOperation('subscription-import', async () => {
return importSubscription(normalizedUrl);
});
await stopSingbox();
removeSingboxConfig();
return sendJson(res, 200, { success: true, ...parsed });
return sendState(res, parsed);
}
if (req.method === 'POST' && req.url === '/api/subscription/refresh-info') {
const state = readJson(settings.statePath, {});
if (!state.subscriptionUrl) {
return sendJson(res, 400, { success: false, error: 'Подписка не настроена' });
if (req.method === 'POST' && req.url === '/api/subscription/validate') {
const { url = '' } = await readBody(req);
const parsed = await fetchSubscription(String(url).trim());
return sendState(res, { servers: parsed.servers.length });
}
if (req.method === 'POST' && req.url === '/api/subscription/refresh') {
const { success, ...result } = await withOperation(
'subscription-refresh',
() => refreshSavedSubscription(),
);
return sendState(res, result);
}
if (req.method === 'POST' && req.url === '/api/gateway-auto') {
if (settings.appMode !== 'client') {
throw new HarborError('REQUEST_INVALID');
}
const info = await fetchSubscriptionInfo(state.subscriptionUrl);
writeJson(settings.statePath, { ...state, ...info });
const cached = readJson(settings.subscriptionCachePath, null);
if (cached) writeJson(settings.subscriptionCachePath, { ...cached, ...info });
return sendJson(res, 200, { success: true, ...info });
const { enabled } = await readBody(req);
if (typeof enabled !== 'boolean') {
throw new HarborError('REQUEST_INVALID');
}
await withOperation('gateway-auto', () => serializeControl(async () => {
await applyGatewayAutoState(applyGatewayPreference(gatewayAutoState, enabled));
updateStoredState((state) => ({
...state,
gatewayAutoEnabled: enabled,
}));
}));
const state = await publicState();
return sendJson(res, 200, { success: true, gatewayAuto: state.gatewayAuto, state });
}
if (req.method === 'PUT' && req.url === '/api/route-rules') {
const { rules, expectedRulesRevision, expectedRevision } = await readBody(req);
let routeRules;
try {
routeRules = normalizeRouteRules(rules, { strict: true });
} catch (cause) {
throw new HarborError('REQUEST_INVALID', { cause });
}
const rulesRevision = expectedRulesRevision ?? expectedRevision;
if (!Number.isSafeInteger(rulesRevision) || rulesRevision < 0) {
throw new HarborError('REQUEST_INVALID');
}
await serializeControl(async () => {
const current = normalizeStoredState(stateStore.read());
const currentRevision = expectedRulesRevision == null
? current.revision
: current.routeRulesRevision;
if (currentRevision !== rulesRevision) throw new HarborError('STATE_CONFLICT');
if (isDeepStrictEqual(current.routeRules, routeRules)) return;
await withOperation('route-rules', () => applyRouteRules(routeRules));
});
return sendState(res);
}
if (req.method === 'DELETE' && req.url === '/api/subscription') {
await stopSingbox();
removeSingboxConfig();
fs.rmSync(settings.subscriptionCachePath, { force: true });
writeJson(settings.statePath, {});
return sendJson(res, 200, { success: true });
await withOperation('subscription-forget', () => resetSavedSubscription());
return sendState(res);
}
if (req.method === 'POST' && req.url === '/api/apply') {
const { selectedTag = '' } = await readBody(req);
const tag = String(selectedTag).trim();
if (!tag) return sendJson(res, 400, { success: false, error: 'Выберите сервер' });
await applySelectedServer(tag);
return sendJson(res, 200, { success: true, selectedTag: tag });
const { serverId = '', selectedTag = '' } = await readBody(req);
const state = normalizeStoredState(stateStore.read());
const id = String(serverId).trim() || (() => {
const matches = state.servers.filter((server) => server.label === String(selectedTag).trim());
return matches.length === 1 ? matches[0].id : '';
})();
if (!id || !state.servers.some((server) => server.id === id)) {
throw new HarborError('SERVER_NOT_FOUND');
}
await withOperation('apply-server', () => serializeControl(() => applySelectedServer(id)));
return sendState(res, {
serverId: id,
selectedTag: state.servers.find((server) => server.id === id)?.label || '',
});
}
if (req.method === 'POST' && req.url === '/api/singbox/stop') {
await stopSingbox();
return sendJson(res, 200, { success: true, singboxRunning: false });
await withOperation('stop', () => serializeControl(async () => {
await stopSingbox();
updateStoredState((state) => ({ ...state, connectionDesired: 'stopped' }));
}));
return sendState(res, { singboxRunning: false });
}
if (req.method === 'POST' && req.url === '/api/singbox/restart') {
if (!fs.existsSync(settings.configPath)) {
return sendJson(res, 400, { success: false, error: 'Сначала выберите сервер' });
}
await startSingbox();
return sendJson(res, 200, { success: true, singboxRunning: true });
await withOperation('start', () => serializeControl(async () => {
if (!fs.existsSync(settings.configPath)) {
throw new HarborError('CONFIG_INVALID');
}
await singboxRuntime.restart();
updateStoredState((state) => ({
...state,
appliedServerId: state.selectedServerId,
connectionDesired: 'running',
appliedRouteRules: state.routeRules,
}));
}));
return sendState(res, { singboxRunning: true });
}
return sendJson(res, 404, { success: false, error: 'Не найдено' });
return sendError(res, new HarborError('ENDPOINT_NOT_FOUND'));
}
const mime = {
@@ -288,29 +761,52 @@ const server = http.createServer(async (req, res) => {
? await handleApi(req, res)
: serveStatic(req, res);
} catch (error) {
console.error('[control] request failed', error);
return sendJson(res, error.statusCode || 500, {
success: false,
error: error.message || String(error),
});
return sendError(res, error);
}
});
async function shutdown() {
await stopSingbox();
clearInterval(subscriptionRefreshTimer);
clearInterval(gatewayDiscoveryTimer);
await serializeControl(() => singboxRuntime.shutdown());
process.exit(0);
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
const state = readJson(settings.statePath, {});
const cached = readJson(settings.subscriptionCachePath, null);
if (!fs.existsSync(settings.configPath) && state.selectedTag && cached?.config) {
writeSingboxConfig(buildGatewayConfig(cached.config, state.selectedTag));
await refreshGatewayAutoMode({ reconfigure: false })
.catch((error) => console.warn(`[control] Gateway не определён: ${error.message}`));
if (settings.appMode === 'client' || !fs.existsSync(settings.configPath)) {
try {
writeCurrentConfig();
} catch (error) {
if (!String(error?.code || '').startsWith('SUBSCRIPTION_')) throw error;
console.warn(`[storage] сохранённая подписка отклонена: ${error.message}; возврат к первичной настройке`);
await resetSavedSubscription({ stopRuntime: false });
}
}
await startSingbox().catch((error) => console.warn(`[control] sing-box не запущен: ${error.message}`));
await startSingbox()
.then(() => {
if (fs.existsSync(settings.configPath)) {
updateStoredState((state) => ({ ...state, appliedRouteRules: state.routeRules }));
}
})
.catch((error) => console.warn(`[control] sing-box не запущен: ${error.message}`));
server.listen(settings.port, '0.0.0.0', () => {
console.log(`[control] ${settings.appMode} UI слушает :${settings.port}`);
});
subscriptionRefreshTimer = setInterval(() => {
if (!stateStore.read().subscriptionUrl) return;
refreshSavedSubscription()
.catch((error) => console.warn(`[control] подписка не обновлена: ${error.message}`));
}, SUBSCRIPTION_REFRESH_INTERVAL_MS);
subscriptionRefreshTimer.unref();
gatewayDiscoveryTimer = setInterval(() => {
refreshGatewayAutoMode()
.catch((error) => console.warn(`[control] Gateway detection failed: ${error.message}`));
}, GATEWAY_DISCOVERY_INTERVAL_MS);
gatewayDiscoveryTimer.unref();

View File

@@ -0,0 +1,27 @@
export const SERVER_HEALTH_MAX_COUNT = 30;
export const SERVER_HEALTH_CONCURRENCY = 4;
export async function checkServerHealth(servers, ping, {
maxCount = SERVER_HEALTH_MAX_COUNT,
concurrency = SERVER_HEALTH_CONCURRENCY,
} = {}) {
const queue = servers.slice(0, maxCount);
const results = new Array(queue.length);
let nextIndex = 0;
async function worker() {
while (nextIndex < queue.length) {
const index = nextIndex++;
const server = queue[index];
results[index] = {
id: server.id,
tag: server.label,
...await ping(server.host, server.port),
checkedAt: new Date().toISOString(),
};
}
}
await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, worker));
return results;
}

View File

@@ -0,0 +1,154 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { normalizeStoredState } from '../../shared/contracts/state.js';
import { INITIAL_ROUTE_RULES } from '../../shared/routingRules.js';
export const STATE_SCHEMA_VERSION = 4;
const clone = (value) => structuredClone(value);
const stamp = (value) => value.toISOString().replace(/[:.]/g, '-');
function syncDirectory(directory) {
let descriptor;
try {
descriptor = fs.openSync(directory, 'r');
fs.fsyncSync(descriptor);
} catch (error) {
if (!['EINVAL', 'ENOTSUP', 'EPERM'].includes(error.code)) throw error;
} finally {
if (descriptor !== undefined) fs.closeSync(descriptor);
}
}
export function atomicWriteFile(filePath, contents, { beforeRename, mode } = {}) {
const directory = path.dirname(filePath);
fs.mkdirSync(directory, { recursive: true });
const temporaryPath = path.join(
directory,
`.${path.basename(filePath)}.${process.pid}.${crypto.randomUUID()}.tmp`,
);
const fileMode = mode ?? (fs.existsSync(filePath) ? fs.statSync(filePath).mode & 0o777 : 0o666);
let descriptor;
try {
descriptor = fs.openSync(temporaryPath, 'wx', fileMode);
fs.writeFileSync(descriptor, contents, 'utf8');
fs.fsyncSync(descriptor);
fs.closeSync(descriptor);
descriptor = undefined;
beforeRename?.(temporaryPath, filePath);
fs.renameSync(temporaryPath, filePath);
syncDirectory(directory);
} finally {
if (descriptor !== undefined) fs.closeSync(descriptor);
fs.rmSync(temporaryPath, { force: true });
}
}
export function atomicWriteJson(filePath, value, options) {
atomicWriteFile(filePath, JSON.stringify(value, null, 2), options);
}
export function migrateStoredState(value) {
const stored = value && typeof value === 'object' && !Array.isArray(value) ? value : {};
const version = Number.isSafeInteger(stored.schemaVersion) ? stored.schemaVersion : 0;
if (version < 0 || version > STATE_SCHEMA_VERSION) {
throw new Error(`Unsupported Harbor state schemaVersion: ${version}`);
}
const routeRules = version < 3
? [...INITIAL_ROUTE_RULES, ...(Array.isArray(stored.routeRules) ? stored.routeRules : [])]
: stored.routeRules;
return {
...normalizeStoredState({ ...stored, routeRules }),
schemaVersion: STATE_SCHEMA_VERSION,
};
}
export function createJsonStore({
filePath,
defaultValue,
migrate = (value) => value,
initializeMissing = false,
backupWhen = () => false,
now = () => new Date(),
} = {}) {
let recovery = null;
let migration = null;
function write(value, options) {
const migrated = migrate(clone(value));
atomicWriteJson(filePath, migrated, options);
return clone(migrated);
}
function read() {
if (!fs.existsSync(filePath)) {
const initial = migrate(clone(defaultValue));
return initializeMissing ? write(initial) : clone(initial);
}
const raw = fs.readFileSync(filePath, 'utf8');
let parsed;
try {
parsed = JSON.parse(raw);
} catch (cause) {
const backupPath = `${filePath}.corrupt-${stamp(now())}`;
fs.renameSync(filePath, backupPath);
try {
const recovered = write(defaultValue);
recovery = { kind: 'corrupt-json', backupPath, recoveredAt: now().toISOString() };
return recovered;
} catch (error) {
fs.renameSync(backupPath, filePath);
throw new AggregateError([cause, error], `Failed to recover corrupt JSON: ${filePath}`);
}
}
const migrated = migrate(clone(parsed));
if (JSON.stringify(migrated) !== JSON.stringify(parsed)) {
if (backupWhen(parsed, migrated)) {
const fromVersion = Number.isSafeInteger(parsed?.schemaVersion) ? parsed.schemaVersion : 0;
const backupPath = `${filePath}.backup-v${fromVersion}-${stamp(now())}`;
atomicWriteFile(backupPath, raw, { mode: fs.statSync(filePath).mode & 0o777 });
migration = {
fromVersion,
toVersion: migrated.schemaVersion,
backupPath,
migratedAt: now().toISOString(),
};
}
atomicWriteJson(filePath, migrated);
}
return clone(migrated);
}
function update(mutator) {
// ponytail: sync mutators serialize in Node's event loop; add a queue only if updates must await I/O.
const next = mutator(read());
if (next && typeof next.then === 'function') {
throw new TypeError('State store mutator must be synchronous');
}
return write(next);
}
return {
read,
write,
update,
remove: () => fs.rmSync(filePath, { force: true }),
get recovery() { return recovery; },
get migration() { return migration; },
};
}
export function createStateStore(filePath, options = {}) {
return createJsonStore({
filePath,
defaultValue: {},
migrate: migrateStoredState,
initializeMissing: true,
backupWhen: (before, after) => before?.schemaVersion !== after.schemaVersion,
...options,
});
}

View File

@@ -1,17 +1,3 @@
function normalizeControlUrl(value) {
const raw = String(value || "").trim();
if (!raw) return "";
const withProtocol = /^https?:\/\//i.test(raw) ? raw : `http://${raw}`;
const url = new URL(withProtocol);
if (!["http:", "https:"].includes(url.protocol)) {
throw new Error("Gateway URL must use http or https");
}
url.hash = "";
url.search = "";
url.pathname = url.pathname.replace(/\/api\/shared-proxy\/?$/, "") || "/";
return url.toString().replace(/\/$/, "");
}
function proxyHostFromHeader(hostHeader) {
const raw = String(hostHeader || "").trim();
if (!raw) return "";
@@ -22,17 +8,6 @@ function proxyHostFromHeader(hostHeader) {
return raw.split(":")[0];
}
function normalizeProxyInfo(proxy) {
if (!proxy || typeof proxy !== "object") return null;
const host = String(proxy.host || "").trim();
const port = Number.parseInt(proxy.port, 10);
const protocol = proxy.protocol === "http" ? "http" : "socks5";
if (!host || !Number.isInteger(port) || port <= 0 || port > 65535) {
return null;
}
return { host, port, protocol };
}
export function buildSharedProxyInfo({
appMode,
proxyPort,
@@ -67,28 +42,3 @@ export function buildSharedProxyInfo({
proxy,
};
}
export async function checkSharedProxyGateway(controlUrl, fetchImpl = fetch) {
const baseUrl = normalizeControlUrl(controlUrl);
const response = await fetchImpl(`${baseUrl}/api/shared-proxy`, {
headers: { accept: "application/json" },
});
const data = await response.json().catch(() => ({}));
if (!response.ok || data.success === false) {
throw new Error(data.error || `Gateway returned ${response.status}`);
}
if (!data.available) {
throw new Error("Gateway shared proxy is not available");
}
const sharedProxy = normalizeProxyInfo(data.proxy);
if (!sharedProxy) {
throw new Error("Gateway returned invalid shared proxy settings");
}
return {
sharedProxyEnabled: true,
sharedProxyControlUrl: baseUrl,
sharedProxy,
};
}

View File

@@ -1,6 +1,8 @@
import fs from 'node:fs';
import path from 'node:path';
import { settings } from './config.js';
import { HarborError } from '../shared/errors.js';
import { normalizeRouteRules } from '../shared/routingRules.js';
import { atomicWriteFile, atomicWriteJson } from './services/stateStore.js';
const PROXY_TYPES = new Set(['vless', 'vmess', 'trojan', 'shadowsocks', 'hysteria2']);
const MIXED_INBOUND = 'mixed-in';
@@ -16,14 +18,21 @@ function findOutbound(subscriptionConfig, selectedTag) {
));
}
export function buildGatewayConfig(subscriptionConfig, selectedTag) {
export function buildGatewayConfig(subscriptionConfig, selectedTag, {
clientDirect = false,
routeRules = [],
} = {}) {
const clientMode = settings.appMode === 'client';
const vpnOutbound = structuredClone(findOutbound(subscriptionConfig, selectedTag));
if (!vpnOutbound) throw new Error(`Outbound не найден: ${selectedTag}`);
if (!vpnOutbound.tag) vpnOutbound.tag = 'vpn-out';
if (vpnOutbound.type === 'vless' && !vpnOutbound.packet_encoding) {
const directClient = clientMode && clientDirect;
const vpnOutbound = directClient
? null
: structuredClone(findOutbound(subscriptionConfig, selectedTag));
if (!directClient && !vpnOutbound) throw new HarborError('SERVER_NOT_FOUND');
if (vpnOutbound && !vpnOutbound.tag) vpnOutbound.tag = 'vpn-out';
if (vpnOutbound?.type === 'vless' && !vpnOutbound.packet_encoding) {
vpnOutbound.packet_encoding = 'xudp';
}
const outboundTag = directClient ? 'direct' : vpnOutbound.tag;
const inbounds = [
...(!clientMode ? [{
@@ -43,11 +52,15 @@ export function buildGatewayConfig(subscriptionConfig, selectedTag) {
set_system_proxy: false,
},
];
const directRules = normalizeRouteRules(routeRules)
.filter((rule) => rule.enabled)
.map((rule) => ({ [rule.type]: [rule.value], outbound: 'direct' }));
const rules = clientMode
? [{ inbound: [MIXED_INBOUND], outbound: vpnOutbound.tag }]
? [...directRules, { inbound: [MIXED_INBOUND], outbound: outboundTag }]
: [
{ inbound: [TPROXY_INBOUND], outbound: vpnOutbound.tag },
{ inbound: [MIXED_INBOUND], outbound: vpnOutbound.tag },
...directRules,
{ inbound: [TPROXY_INBOUND], outbound: outboundTag },
{ inbound: [MIXED_INBOUND], outbound: outboundTag },
];
return {
@@ -58,22 +71,25 @@ export function buildGatewayConfig(subscriptionConfig, selectedTag) {
dns: { independent_cache: true },
inbounds,
outbounds: [
vpnOutbound,
...(vpnOutbound ? [vpnOutbound] : []),
{ type: 'direct', tag: 'direct' },
{ type: 'block', tag: 'block' },
],
route: {
rule_set: [],
rules,
final: vpnOutbound.tag,
final: outboundTag,
...(clientMode ? {} : { auto_detect_interface: true }),
},
};
}
export function writeSingboxConfig(config) {
fs.mkdirSync(path.dirname(settings.configPath), { recursive: true });
fs.writeFileSync(settings.configPath, JSON.stringify(config, null, 2), 'utf8');
atomicWriteJson(settings.configPath, config);
}
export function restoreSingboxConfig(contents) {
atomicWriteFile(settings.configPath, contents);
}
export function removeSingboxConfig() {

View File

@@ -0,0 +1,100 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import { spawn, spawnSync } from 'node:child_process';
import { setGatewayInterception } from './gatewayRouting.js';
import { HarborError } from '../shared/errors.js';
export function createSingboxRuntime({ configPath, gateway = false, tproxyChain = '' }) {
let child = null;
let configHash = '';
let startedAt = null;
const state = () => ({ running: Boolean(child), startedAt });
async function stop() {
if (gateway) setGatewayInterception(false, tproxyChain);
if (!child) {
configHash = '';
startedAt = null;
return state();
}
const current = child;
child = null;
configHash = '';
startedAt = null;
await new Promise((resolve) => {
const timeout = setTimeout(() => {
current.kill('SIGKILL');
resolve();
}, 4000);
current.once('exit', () => {
clearTimeout(timeout);
resolve();
});
current.kill('SIGTERM');
});
return state();
}
async function apply({ force = false } = {}) {
if (!fs.existsSync(configPath)) {
await stop();
return state();
}
const check = spawnSync('sing-box', ['check', '-c', configPath], { encoding: 'utf8' });
if (check.status !== 0) {
throw new HarborError('CONFIG_INVALID', {
cause: new Error((check.stderr || check.stdout || check.error?.message || 'sing-box check failed').trim()),
});
}
const nextHash = crypto.createHash('sha256').update(fs.readFileSync(configPath)).digest('hex');
if (!force && child && nextHash === configHash) return state();
await stop();
let current;
try {
current = spawn('sing-box', ['run', '-c', configPath], {
stdio: ['ignore', 'inherit', 'inherit'],
});
await new Promise((resolve, reject) => {
current.once('spawn', resolve);
current.once('error', reject);
});
} catch (cause) {
throw new HarborError('PROCESS_START_FAILED', { cause });
}
child = current;
configHash = nextHash;
startedAt = new Date().toISOString();
try {
if (gateway) setGatewayInterception(true, tproxyChain);
} catch (error) {
current.kill('SIGTERM');
child = null;
configHash = '';
startedAt = null;
throw new HarborError('PROCESS_START_FAILED', { cause: error });
}
current.once('exit', () => {
if (child !== current) return;
child = null;
configHash = '';
startedAt = null;
if (gateway) setGatewayInterception(false, tproxyChain);
});
return state();
}
return {
get running() { return Boolean(child); },
get startedAt() { return startedAt; },
refresh: async () => state(),
apply,
restart: () => apply({ force: true }),
stop,
shutdown: stop,
};
}

View File

@@ -1,8 +1,32 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import { settings } from './config.js';
import { HarborError } from '../shared/errors.js';
import {
createServerId,
normalizeServer,
serverIdentityKey,
} from '../shared/serverIdentity.js';
import { atomicWriteFile } from './services/stateStore.js';
const PROXY_TYPES = new Set(['vless', 'vmess', 'trojan', 'shadowsocks', 'hysteria2']);
const UNSPECIFIED_HOSTS = new Set(['0.0.0.0', '::', '[::]']);
function usableProxyOutbound(outbound) {
const host = String(outbound?.server || '').trim().toLowerCase();
const port = Number(outbound?.server_port);
return Boolean(host) && !UNSPECIFIED_HOSTS.has(host) && Number.isInteger(port) && port > 0 && port <= 65535;
}
function rejectedSubscriptionCode(outbounds) {
const labels = outbounds.map((outbound) => String(outbound?.tag || '').toLowerCase()).join(' ');
if (labels.includes('expired')) return 'SUBSCRIPTION_EXPIRED';
if (labels.includes('disabled')) return 'SUBSCRIPTION_DISABLED';
if (/traffic|quota|bandwidth|трафик/.test(labels)) return 'SUBSCRIPTION_TRAFFIC_EXHAUSTED';
return outbounds.some((outbound) => UNSPECIFIED_HOSTS.has(String(outbound?.server || '').trim().toLowerCase()))
? 'SUBSCRIPTION_REJECTED'
: 'SUBSCRIPTION_INVALID';
}
export function getHwid() {
fs.mkdirSync(settings.dataDir, { recursive: true });
@@ -10,7 +34,7 @@ export function getHwid() {
return fs.readFileSync(settings.hwidPath, 'utf8').trim();
}
const hwid = crypto.randomBytes(8).toString('hex');
fs.writeFileSync(settings.hwidPath, hwid, 'utf8');
atomicWriteFile(settings.hwidPath, hwid);
return hwid;
}
@@ -40,10 +64,15 @@ export function parseUserInfo(headerValue) {
export function parseVlessUrl(rawUrl) {
if (!rawUrl.startsWith('vless://')) {
throw new Error('VLESS URL must start with vless://');
throw new HarborError('SUBSCRIPTION_INVALID');
}
const parsed = new URL(rawUrl);
let parsed;
try {
parsed = new URL(rawUrl);
} catch (cause) {
throw new HarborError('SUBSCRIPTION_INVALID', { cause });
}
const tag = decodeURIComponent(parsed.hash ? parsed.hash.slice(1) : 'vless-out');
const uuid = decodeURIComponent(parsed.username || '');
const server = parsed.hostname;
@@ -55,11 +84,11 @@ export function parseVlessUrl(rawUrl) {
const flow = parsed.searchParams.get('flow') || '';
if (!uuid || !server || !serverPort) {
throw new Error('VLESS URL misses uuid, host or port');
throw new HarborError('SUBSCRIPTION_INVALID');
}
if (!publicKey || !shortId) {
throw new Error('VLESS REALITY parameters pbk and sid are required');
throw new HarborError('SUBSCRIPTION_INVALID');
}
return {
@@ -98,8 +127,36 @@ function maybeDecodeBase64(content) {
return content;
}
export function normalizeSubscriptionConfig(value) {
const parsedConfig = value && typeof value === 'object' ? value : {};
const outbounds = Array.isArray(parsedConfig.outbounds) ? parsedConfig.outbounds : [];
const servers = [];
const rejectedOutbounds = [];
const seen = new Set();
const normalizedOutbounds = outbounds.flatMap((outbound) => {
if (!outbound || typeof outbound !== 'object') {
rejectedOutbounds.push(outbound);
return [];
}
if (!PROXY_TYPES.has(outbound.type)) return [outbound];
if (!usableProxyOutbound(outbound)) {
rejectedOutbounds.push(outbound);
return [];
}
const id = createServerId(outbound);
// ponytail: endpoint identity deduplicates indistinguishable entries; include provider IDs if real feeds need same-endpoint variants.
if (seen.has(id)) return [];
seen.add(id);
servers.push(normalizeServer({ ...outbound, id }));
return [{ ...outbound, tag: id }];
});
if (!servers.length) throw new HarborError(rejectedSubscriptionCode(rejectedOutbounds));
return { config: { ...parsedConfig, outbounds: normalizedOutbounds }, servers };
}
export function parseSubscriptionBody(body) {
let parsedConfig = null;
let parsedConfig;
try {
parsedConfig = JSON.parse(body);
@@ -111,7 +168,7 @@ export function parseSubscriptionBody(body) {
.filter((line) => line.startsWith('vless://'));
if (!links.length) {
throw new Error('Subscription does not contain JSON config or VLESS links');
throw new HarborError('SUBSCRIPTION_INVALID');
}
parsedConfig = {
@@ -119,61 +176,60 @@ export function parseSubscriptionBody(body) {
};
}
const outbounds = Array.isArray(parsedConfig.outbounds) ? parsedConfig.outbounds : [];
const servers = outbounds
.filter((outbound) => PROXY_TYPES.has(outbound.type))
.map((outbound) => ({
tag: String(outbound.tag || `${outbound.type}-${outbound.server || 'server'}`).trim(),
type: outbound.type,
server: outbound.server || 'unknown',
server_port: outbound.server_port || 443,
}));
if (!servers.length) {
throw new Error('No supported proxy outbounds found in subscription');
}
return { config: parsedConfig, servers };
return { ...normalizeSubscriptionConfig(parsedConfig), sourceConfig: parsedConfig };
}
async function requestSubscription(url) {
async function requestSubscription(url, { fetchImpl = fetch, timeoutMs = settings.subscriptionTimeoutMs } = {}) {
let parsedUrl;
try {
parsedUrl = new URL(url);
} catch {
throw new Error('Invalid subscription URL');
} catch (cause) {
throw new HarborError('SUBSCRIPTION_INVALID', { cause });
}
if (!['http:', 'https:'].includes(parsedUrl.protocol)) {
throw new Error('Subscription URL must use http or https');
throw new HarborError('SUBSCRIPTION_INVALID');
}
const response = await fetch(parsedUrl, {
headers: subscriptionHeaders(),
redirect: 'follow',
});
let response;
try {
response = await fetchImpl(parsedUrl, {
headers: subscriptionHeaders(),
redirect: 'follow',
signal: AbortSignal.timeout(timeoutMs),
});
} catch (cause) {
throw new HarborError('PROVIDER_UNAVAILABLE', { cause });
}
if (!response.ok) {
throw new Error(`Subscription request failed: HTTP ${response.status}`);
throw new HarborError('PROVIDER_UNAVAILABLE', { details: `HTTP ${response.status}` });
}
return response;
}
export async function fetchSubscriptionInfo(url) {
const response = await requestSubscription(url);
await response.body?.cancel();
return {
userInfo: parseUserInfo(response.headers.get('subscription-userinfo')),
fetchedAt: new Date().toISOString(),
};
export function selectRefreshedServer(currentServerId, currentServers, nextServers) {
if (!currentServerId) return '';
if (nextServers.some((server) => server.id === currentServerId)) return currentServerId;
const previous = currentServers.find((server) => server.id === currentServerId);
if (!previous) return '';
const identity = serverIdentityKey(previous);
const matches = nextServers.filter((server) => serverIdentityKey(server) === identity);
return matches.length === 1 ? matches[0].id : '';
}
export async function fetchSubscription(url) {
const response = await requestSubscription(url);
export async function fetchSubscription(url, options) {
const response = await requestSubscription(url, options);
const body = await response.text();
const userInfo = parseUserInfo(response.headers.get('subscription-userinfo'));
if (userInfo.expire > 0 && userInfo.expire * 1000 <= Date.now()) {
throw new HarborError('SUBSCRIPTION_EXPIRED');
}
if (userInfo.total > 0 && (userInfo.upload || 0) + (userInfo.download || 0) >= userInfo.total) {
throw new HarborError('SUBSCRIPTION_TRAFFIC_EXHAUSTED');
}
const parsed = parseSubscriptionBody(body);
return {

30
src/server/version.js Normal file
View File

@@ -0,0 +1,30 @@
import { spawnSync } from 'node:child_process';
import { HARBOR_VERSIONS } from '../shared/versions.js';
export function detectSingBoxVersion(run = spawnSync) {
const result = run('sing-box', ['version'], { encoding: 'utf8', timeout: 1000 });
const match = /sing-box version\s+v?([^\s]+)/i.exec(`${result.stdout || ''}\n${result.stderr || ''}`);
return match?.[1] || null;
}
export function buildVersionInfo(appMode, run = spawnSync) {
const client = appMode === 'client';
return {
apiVersion: 1,
location: client ? 'mac' : 'gateway',
components: client
? { macClient: HARBOR_VERSIONS.macClient }
: { gatewayBackend: HARBOR_VERSIONS.gatewayBackend },
runtime: { singBox: detectSingBoxVersion(run) },
};
}
export function buildGatewayVersionInfo(controlInfo, dataplaneState) {
return {
...controlInfo,
runtime: {
dataplaneVersion: dataplaneState?.gatewayBackendVersion || null,
singBox: dataplaneState?.singBoxVersion || null,
},
};
}

View File

@@ -0,0 +1,218 @@
import { normalizeRouteRules } from '../routingRules.js';
import { normalizeServers, resolveServerId } from '../serverIdentity.js';
const MODES = new Set(['client', 'gateway']);
const CONNECTION_STATES = new Set(['running', 'stopped']);
const OPERATION_STATES = new Set(['idle', 'running', 'failed']);
const text = (value) => String(value || '').trim();
const nullableText = (value) => value == null ? null : String(value);
const dateOrNull = (value) => (
typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null
);
export function normalizeStoredState(value) {
const state = value && typeof value === 'object' && !Array.isArray(value) ? value : {};
const servers = normalizeServers(state.servers);
const selectedServerId = resolveServerId(servers, state.selectedServerId, state.selectedTag);
const appliedServerId = Object.hasOwn(state, 'appliedServerId')
? resolveServerId(servers, state.appliedServerId)
: resolveServerId(servers, '', state.appliedTag || state.selectedTag);
const selectedServer = servers.find((server) => server.id === selectedServerId);
const appliedServer = servers.find((server) => server.id === appliedServerId);
return {
...state,
revision: Number.isSafeInteger(state.revision) && state.revision >= 0 ? state.revision : 0,
selectedServerId,
appliedServerId,
selectedTag: selectedServer?.label || '',
appliedTag: appliedServer?.label || '',
servers,
routeRules: normalizeRouteRules(state.routeRules),
appliedRouteRules: normalizeRouteRules(state.appliedRouteRules),
routeRulesRevision: Number.isSafeInteger(state.routeRulesRevision) && state.routeRulesRevision >= 0
? state.routeRulesRevision
: 0,
};
}
export function createStateSnapshot({
storedState,
runtime,
gatewayAuto,
appMode,
configExists,
subscriptionHost,
operation = { kind: null, status: 'idle', startedAt: null, error: null },
now = new Date(),
}) {
const stored = normalizeStoredState(storedState);
const mode = MODES.has(appMode) ? appMode : 'gateway';
const hasSubscription = Boolean(stored.subscriptionUrl);
const desired = CONNECTION_STATES.has(stored.connectionDesired)
? stored.connectionDesired
: configExists ? 'running' : 'stopped';
const servers = stored.servers;
const routeMode = mode === 'client' ? gatewayAuto?.mode || 'local-vpn' : 'gateway-transparent';
const gatewayAutoEnabled = stored.gatewayAutoEnabled !== false;
const routeReason = mode !== 'client'
? 'gateway-host'
: !gatewayAutoEnabled
? 'disabled'
: routeMode === 'gateway-direct'
? gatewayAuto?.failures ? 'gateway-stale' : 'gateway-found'
: gatewayAuto?.lastError ? 'gateway-lost' : 'local';
const activeLocalRules = runtime?.running ? stored.appliedRouteRules : [];
return assertStateSnapshot({
apiVersion: 1,
revision: stored.revision,
generatedAt: now.toISOString(),
mode,
subscription: {
status: hasSubscription ? 'ready' : 'missing',
host: hasSubscription ? subscriptionHost : '',
fetchedAt: dateOrNull(stored.fetchedAt),
userInfo: stored.userInfo && typeof stored.userInfo === 'object' ? stored.userInfo : {},
},
selection: {
desiredServerId: stored.selectedServerId,
appliedServerId: stored.appliedServerId,
},
connection: {
desired,
process: runtime?.running ? 'running' : 'stopped',
startedAt: dateOrNull(runtime?.startedAt),
lastError: null,
},
route: {
mode: routeMode,
gatewayAddress: mode === 'client' ? gatewayAuto?.gateway?.gateway || null : null,
gatewayUiOrigin: mode === 'client' ? gatewayAuto?.uiOrigin || null : null,
lastVerifiedAt: mode === 'client' ? dateOrNull(gatewayAuto?.lastVerifiedAt) : null,
autoEnabled: mode === 'client' && gatewayAutoEnabled,
fallbackPreference: mode === 'client' ? 'local-vpn' : 'none',
reason: routeReason,
localRules: stored.routeRules,
activeLocalRules,
localRulesRevision: stored.routeRulesRevision,
localRulesPendingRestart: !isSameRules(stored.routeRules, activeLocalRules),
},
operation: {
kind: nullableText(operation.kind),
status: operation.status,
startedAt: nullableText(operation.startedAt),
error: nullableText(operation.error),
},
servers,
});
}
export function withStateV0Compatibility(snapshot, {
storedState,
gatewayAuto,
port,
proxyPort,
configExists,
}) {
const stored = normalizeStoredState(storedState);
return {
...snapshot,
port,
proxyPort,
configExists,
singboxRunning: snapshot.connection.process === 'running',
singboxStartedAt: snapshot.connection.startedAt,
subscriptionHost: snapshot.subscription.host,
hasSubscription: snapshot.subscription.status === 'ready',
selectedTag: stored.selectedTag,
userInfo: snapshot.subscription.userInfo,
fetchedAt: snapshot.subscription.fetchedAt,
gatewayAuto: snapshot.mode === 'client' ? {
mode: gatewayAuto?.mode || 'local-vpn',
enabled: stored.gatewayAutoEnabled !== false,
available: Boolean(gatewayAuto?.gatewayId),
address: gatewayAuto?.gateway?.gateway || '',
uiOrigin: gatewayAuto?.uiOrigin || '',
interface: gatewayAuto?.gateway?.interface || '',
failures: Number(gatewayAuto?.failures) || 0,
lastError: gatewayAuto?.lastError || '',
} : null,
};
}
export function assertStateSnapshot(snapshot) {
const validDate = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value));
const nullableDate = (value) => value === null || validDate(value);
const nullableString = (value) => value === null || typeof value === 'string';
const validServer = (server) => (
server &&
typeof server.id === 'string' &&
typeof server.label === 'string' &&
typeof server.host === 'string' &&
Number.isInteger(server.port) &&
server.port >= 0 &&
typeof server.protocol === 'string'
);
const validRouteRule = (rule) => (
rule &&
['domain', 'domain_suffix', 'domain_keyword'].includes(rule.type) &&
typeof rule.value === 'string' &&
Boolean(rule.value) &&
typeof rule.enabled === 'boolean'
);
if (
!snapshot ||
snapshot.apiVersion !== 1 ||
!Number.isSafeInteger(snapshot.revision) ||
snapshot.revision < 0 ||
!validDate(snapshot.generatedAt) ||
!MODES.has(snapshot.mode) ||
!snapshot.subscription ||
!['missing', 'ready'].includes(snapshot.subscription.status) ||
typeof snapshot.subscription.host !== 'string' ||
Object.hasOwn(snapshot.subscription, 'url') ||
!nullableDate(snapshot.subscription.fetchedAt) ||
!snapshot.subscription.userInfo ||
typeof snapshot.subscription.userInfo !== 'object' ||
!snapshot.selection ||
typeof snapshot.selection.desiredServerId !== 'string' ||
typeof snapshot.selection.appliedServerId !== 'string' ||
!snapshot.connection ||
!CONNECTION_STATES.has(snapshot.connection.desired) ||
!CONNECTION_STATES.has(snapshot.connection.process) ||
!nullableDate(snapshot.connection.startedAt) ||
!nullableString(snapshot.connection.lastError) ||
!snapshot.route ||
typeof snapshot.route.mode !== 'string' ||
!nullableString(snapshot.route.gatewayAddress) ||
!nullableString(snapshot.route.gatewayUiOrigin) ||
!nullableDate(snapshot.route.lastVerifiedAt) ||
typeof snapshot.route.autoEnabled !== 'boolean' ||
typeof snapshot.route.fallbackPreference !== 'string' ||
typeof snapshot.route.reason !== 'string' ||
!Array.isArray(snapshot.route.localRules) ||
!snapshot.route.localRules.every(validRouteRule) ||
!Array.isArray(snapshot.route.activeLocalRules) ||
!snapshot.route.activeLocalRules.every(validRouteRule) ||
!Number.isSafeInteger(snapshot.route.localRulesRevision) ||
snapshot.route.localRulesRevision < 0 ||
typeof snapshot.route.localRulesPendingRestart !== 'boolean' ||
!snapshot.operation ||
!nullableString(snapshot.operation.kind) ||
!OPERATION_STATES.has(snapshot.operation.status) ||
!nullableDate(snapshot.operation.startedAt) ||
!nullableString(snapshot.operation.error) ||
!Array.isArray(snapshot.servers) ||
!snapshot.servers.every(validServer)
) {
throw new TypeError('Invalid Harbor state snapshot v1');
}
return snapshot;
}
function isSameRules(left, right) {
return JSON.stringify(left) === JSON.stringify(right);
}

37
src/shared/errors.js Normal file
View File

@@ -0,0 +1,37 @@
export const ERROR_DEFINITIONS = Object.freeze({
CONTROL_UNREACHABLE: { status: 503, message: 'Harbor сейчас недоступен.', retryable: true },
REQUEST_INVALID: { status: 400, message: 'Запрос содержит некорректные данные.', retryable: false },
ENDPOINT_NOT_FOUND: { status: 404, message: 'Запрошенный API-метод не найден.', retryable: false },
SUBSCRIPTION_INVALID: { status: 400, message: 'Ссылка подписки недействительна.', retryable: false },
SUBSCRIPTION_EXPIRED: { status: 400, message: 'Срок действия подписки истёк.', retryable: false },
SUBSCRIPTION_TRAFFIC_EXHAUSTED: { status: 400, message: 'Трафик по подписке закончился.', retryable: false },
SUBSCRIPTION_DISABLED: { status: 400, message: 'Подписка отключена провайдером.', retryable: false },
SUBSCRIPTION_REJECTED: { status: 400, message: 'Провайдер отклонил подписку.', retryable: false },
PROVIDER_UNAVAILABLE: { status: 502, message: 'Провайдер подписки временно недоступен.', retryable: true },
STATE_CONFLICT: { status: 409, message: 'Данные изменились во время операции.', retryable: true },
SERVER_NOT_FOUND: { status: 404, message: 'Выбранный сервер больше недоступен.', retryable: false },
CONFIG_INVALID: { status: 422, message: 'Конфигурация VPN недействительна.', retryable: false },
PROCESS_START_FAILED: { status: 503, message: 'Не удалось запустить VPN-процесс.', retryable: true },
OPERATION_IN_PROGRESS: { status: 409, message: 'Другая операция ещё выполняется.', retryable: true },
UNKNOWN: { status: 500, message: 'Не удалось выполнить действие.', retryable: false },
});
export function errorDefinition(code) {
return ERROR_DEFINITIONS[code] || ERROR_DEFINITIONS.UNKNOWN;
}
export class HarborError extends Error {
constructor(code, { cause, details } = {}) {
const definition = errorDefinition(code);
super(definition.message, { cause });
this.name = 'HarborError';
this.code = ERROR_DEFINITIONS[code] ? code : 'UNKNOWN';
this.status = definition.status;
this.retryable = definition.retryable;
this.details = details;
}
}
export function normalizeHarborError(error) {
return error instanceof HarborError ? error : new HarborError('UNKNOWN', { cause: error });
}

View File

@@ -0,0 +1,61 @@
export const INITIAL_ROUTE_RULES = Object.freeze([
Object.freeze({ type: 'domain_suffix', value: 'ru', enabled: true }),
]);
const RULE_TYPES = new Set(['domain', 'domain_suffix', 'domain_keyword']);
export const MAX_ROUTE_RULES = 200;
function hostname(value) {
const input = String(value || '').trim().replace(/^\*\./, '').replace(/^\./, '');
if (!input) throw new TypeError('Domain rule value is required');
const url = new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(input) ? input : `https://${input}`);
const normalized = url.hostname.replace(/\.$/, '').toLowerCase();
if (!normalized || normalized.length > 253) throw new TypeError('Invalid domain rule value');
return normalized;
}
function normalizeRule(rule) {
const type = String(rule?.type || '').trim();
if (!RULE_TYPES.has(type)) throw new TypeError('Invalid domain rule type');
if (Object.hasOwn(rule || {}, 'enabled') && typeof rule.enabled !== 'boolean') {
throw new TypeError('Invalid domain rule enabled state');
}
const value = type === 'domain_keyword'
? String(rule?.value || '').trim().toLowerCase()
: hostname(rule?.value);
if (!value || value.length > 253 || /[\s/:?#]/.test(value)) {
throw new TypeError('Invalid domain rule value');
}
return { type, value, enabled: rule?.enabled !== false };
}
export function normalizeRouteRules(value, { strict = false } = {}) {
if (!Array.isArray(value)) {
if (strict) throw new TypeError('Route rules must be an array');
return [];
}
if (strict && value.length > MAX_ROUTE_RULES) {
throw new TypeError(`Route rules limit is ${MAX_ROUTE_RULES}`);
}
const seen = new Set();
const normalized = [];
for (const candidate of value.slice(0, MAX_ROUTE_RULES)) {
try {
const rule = normalizeRule(candidate);
const key = `${rule.type}:${rule.value}`;
if (seen.has(key)) continue;
seen.add(key);
normalized.push(rule);
} catch (error) {
if (strict) throw error;
}
}
return normalized;
}
export function canAppendRouteRule(rules) {
return Array.isArray(rules) &&
rules.length < MAX_ROUTE_RULES &&
rules.every((rule) => String(rule?.value || '').trim());
}

View File

@@ -0,0 +1,67 @@
const text = (value) => String(value || '').trim();
function hash64(value) {
let hash = 0xcbf29ce484222325n;
for (let index = 0; index < value.length; index += 1) {
hash ^= BigInt(value.charCodeAt(index));
hash = BigInt.asUintN(64, hash * 0x100000001b3n);
}
return hash.toString(16).padStart(16, '0');
}
export function serverIdentityKey(server) {
const protocol = text(server?.protocol || server?.type).toLowerCase();
const host = text(server?.host || server?.server).toLowerCase();
const port = Number(server?.port || server?.server_port) || 0;
return `${protocol}\u0000${host}\u0000${port}`;
}
export function createServerId(server) {
return `srv_${hash64(`endpoint\u0000${serverIdentityKey(server)}`)}`;
}
export function normalizeServer(server) {
const source = server && typeof server === 'object' ? server : {};
const protocol = text(source.protocol || source.type).toLowerCase();
const host = text(source.host || source.server);
const port = Number(source.port || source.server_port) || 0;
const id = text(source.id) || createServerId(source);
const label = text(source.label || source.tag) || host;
const metadata = Object.fromEntries([
['country', text(source.country)],
['city', text(source.city)],
['provider', text(source.provider)],
].filter(([, value]) => value));
return {
id,
label,
host,
port,
protocol,
...metadata,
// v0 aliases remain until old clients no longer consume this API.
tag: label,
server: host,
server_port: port,
type: protocol,
};
}
export function normalizeServers(servers) {
const seen = new Set();
return (Array.isArray(servers) ? servers : []).flatMap((server) => {
const normalized = normalizeServer(server);
if (!normalized.id || seen.has(normalized.id)) return [];
seen.add(normalized.id);
return [normalized];
});
}
export function resolveServerId(servers, serverId, legacyTag = '') {
const id = text(serverId);
if (id) return servers.some((server) => server.id === id) ? id : '';
const tag = text(legacyTag);
const matches = tag ? servers.filter((server) => server.label === tag) : [];
return matches.length === 1 ? matches[0].id : '';
}

27
src/shared/versions.js Normal file
View File

@@ -0,0 +1,27 @@
export const HARBOR_VERSIONS = Object.freeze({
macClient: '0.8.12',
gatewayClient: '0.8.10',
gatewayBackend: '0.8.1',
});
export function parseVersion(value) {
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(String(value || ''));
return match ? {
major: Number(match[1]),
minor: Number(match[2]),
hotfix: Number(match[3]),
} : null;
}
export function versionCompatibility(versions) {
const mac = parseVersion(versions?.macClient);
const client = parseVersion(versions?.gatewayClient);
const backend = parseVersion(versions?.gatewayBackend);
const major = Boolean(mac && client && backend
&& mac.major === client.major
&& client.major === backend.major);
const gateway = Boolean(client && backend
&& client.major === backend.major
&& client.minor === backend.minor);
return { compatible: major && gateway, major, gateway };
}

View File

@@ -1,93 +1,184 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect, useReducer, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';
import './styles.css';
import { api } from './api.js';
import { api, HarborApiError } from './api.js';
import { ClientOverviewPage } from './components/ClientOverviewPage.jsx';
import { BootStatePage, StaleBanner } from './components/SyncStatus.jsx';
import {
compatibleSnapshot,
harborReducer,
initialHarborState,
} from './state/harborReducer.js';
import { createOperationRegistry } from './state/operations.js';
function App() {
const [state, setState] = useState(null);
const previewReady = new URLSearchParams(window.location.search).has('preview-ready');
const [{ snapshot: state, pendingServerId, transport }, dispatch] = useReducer(
harborReducer,
initialHarborState,
);
const [subscriptionUrl, setSubscriptionUrl] = useState('');
const [servers, setServers] = useState([]);
const [pendingTag, setPendingTag] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
async function loadState() {
const data = await api.state();
setState(data);
setServers(data.servers || []);
setPendingTag((current) => current || data.selectedTag || '');
const [operations, setOperations] = useState({});
const [error, setError] = useState(null);
const [versionInfo, setVersionInfo] = useState(null);
const pollGeneration = useRef(0);
const operationRegistry = useRef(null);
if (!operationRegistry.current) {
operationRegistry.current = createOperationRegistry(setOperations);
}
useEffect(() => {
loadState().catch((err) => setError(err.message));
const timer = setInterval(() => loadState().catch(() => {}), 5000);
return () => clearInterval(timer);
}, []);
function setPendingServerId(serverId) {
dispatch({ type: 'select-server', serverId });
}
async function run(action) {
setBusy(true);
setError('');
async function loadState({ retry = false } = {}) {
if (retry) dispatch({ type: 'retry-sync' });
const generation = pollGeneration.current;
try {
await action();
await loadState();
} catch (err) {
setError(err.message);
throw err;
} finally {
setBusy(false);
const snapshot = await api.state();
if (!compatibleSnapshot(snapshot)) {
const incompatible = new Error('Ожидался Harbor state apiVersion 1');
incompatible.code = 'INCOMPATIBLE_API';
throw incompatible;
}
if (generation === pollGeneration.current) {
dispatch({ type: 'sync-succeeded', snapshot, receivedAt: new Date().toISOString() });
}
} catch (requestError) {
if (generation === pollGeneration.current) {
dispatch({ type: 'sync-failed', error: requestError });
}
}
}
async function fetchSubscription() {
return run(async () => {
const data = await api.subscription.fetch(subscriptionUrl);
setServers(data.servers || []);
setPendingTag('');
useEffect(() => {
loadState();
const timer = setInterval(loadState, 5000);
return () => clearInterval(timer);
}, []);
useEffect(() => {
let cancelled = false;
api.version().then((info) => {
if (!cancelled) setVersionInfo(info);
}).catch((requestError) => {
console.warn(`[version] Не удалось получить runtime-версию: ${requestError.message}`);
if (!cancelled) setVersionInfo(null);
});
return () => { cancelled = true; };
}, []);
useEffect(() => {
if (!state?.mode) return;
const isGateway = state.mode === 'gateway';
document.title = isGateway ? 'Harbor Gateway' : 'Harbor Connect';
document.getElementById('harbor-favicon').href = isGateway
? '/harbor-gateway.svg?v=2'
: '/harbor-connect.svg?v=2';
}, [state?.mode]);
function run(key, action, context) {
setError(null);
return operationRegistry.current.run(key, async () => {
try {
return await applyMutation(action);
} catch (err) {
const safeError = err instanceof HarborApiError
? err
: new HarborApiError({ code: err?.code }, err?.status);
setError({
context,
message: context === 'routing' && safeError.code === 'STATE_CONFLICT'
? 'Правила уже изменились в другом окне. Проверьте статусы строк и сохраните ещё раз.'
: safeError.message,
code: safeError.code,
correlationId: safeError.correlationId,
retry: safeError.retryable && safeError.code !== 'STATE_CONFLICT'
? () => run(key, action, context)
: null,
});
return false;
}
});
}
async function refreshSubscriptionInfo() {
const data = await api.subscription.refreshInfo();
setState((current) => current ? {
...current,
userInfo: data.userInfo,
fetchedAt: data.fetchedAt,
} : current);
return data;
async function applyMutation(action) {
pollGeneration.current += 1;
const result = await action();
if (!result?.state) throw new Error('Harbor API не вернул state snapshot');
if (!compatibleSnapshot(result.state)) throw new Error('Harbor API не вернул state snapshot v1');
dispatch({
type: 'sync-succeeded',
snapshot: result.state,
receivedAt: new Date().toISOString(),
});
return result;
}
async function fetchSubscription() {
return run('subscriptionImport', async () => {
const data = await api.subscription.fetch(subscriptionUrl);
dispatch({ type: 'clear-pending-server' });
return data;
}, 'subscription');
}
async function refreshSubscription() {
return run('subscriptionRefresh', api.subscription.refresh, 'subscription');
}
async function forgetSubscription() {
if (!confirm('Удалить подписку и остановить VPN?')) return;
return run(async () => {
await api.subscription.forget();
return run('subscriptionDelete', async () => {
const data = await api.subscription.forget();
setSubscriptionUrl('');
setServers([]);
setPendingTag('');
});
dispatch({ type: 'clear-pending-server' });
return data;
}, 'subscription');
}
if (!state) return <div className="app-loading">VPN</div>;
if (!state) return <BootStatePage transport={transport} onRetry={() => loadState({ retry: true })} />;
return (
<div className="app client-app">
<div className={`app client-app${state.mode === 'gateway' ? ' is-gateway-app' : ''}`}>
<StaleBanner transport={transport} onRetry={() => loadState({ retry: true })} />
<div className="app-body client-mode">
<main className="app-main">
<ClientOverviewPage
state={state}
busy={busy}
state={previewReady ? {
...state,
mode: 'client',
hasSubscription: true,
subscriptionHost: 'harbor.example',
selection: { desiredServerId: 'preview-amsterdam', appliedServerId: 'preview-amsterdam' },
proxyPort: 8082,
} : state}
versionInfo={versionInfo}
operations={operations}
error={error}
subscriptionUrl={subscriptionUrl}
setSubscriptionUrl={setSubscriptionUrl}
servers={servers}
pendingTag={pendingTag}
setPendingTag={setPendingTag}
servers={previewReady ? [{
id: 'preview-amsterdam',
label: 'Amsterdam',
host: '127.0.0.1',
port: 443,
protocol: 'vless',
}] : state.servers || []}
pendingServerId={previewReady ? 'preview-amsterdam' : pendingServerId}
setPendingServerId={setPendingServerId}
onFetchSubscription={fetchSubscription}
onRefreshSubscriptionInfo={refreshSubscriptionInfo}
onRefreshSubscription={refreshSubscription}
onForgetSubscription={forgetSubscription}
onApply={(tag) => run(() => api.apply(tag))}
onRestart={() => run(api.singbox.restart)}
onStop={() => run(api.singbox.stop)}
onApply={(serverId) => run('serverApply', () => api.apply(serverId), 'connection')}
onRestart={() => run('connection', api.singbox.restart, 'connection')}
onStop={() => run('connection', api.singbox.stop, 'connection')}
onSetGatewayAuto={(enabled) => run('gatewayAuto', () => api.gatewayAuto.setEnabled(enabled), 'connection')}
onSaveRouteRules={(rules, expectedRevision) => run(
'routeRules',
() => api.routeRules.update(rules, expectedRevision),
'routing',
)}
onDismissError={() => setError(null)}
/>
</main>
</div>

View File

@@ -1,37 +1,92 @@
async function request(url, options = {}) {
const response = await fetch(url, {
...options,
headers: {
'content-type': 'application/json',
...(options.headers || {}),
},
});
const data = await response.json().catch(() => ({}));
import { ERROR_DEFINITIONS, errorDefinition } from '../shared/errors.js';
export class HarborApiError extends Error {
constructor(payload = {}, status = 0) {
const code = ERROR_DEFINITIONS[payload.code] ? payload.code : 'UNKNOWN';
const definition = errorDefinition(code);
super(definition.message);
this.name = 'HarborApiError';
this.code = code;
this.status = status >= 400 ? status : definition.status;
this.retryable = definition.retryable;
this.details = payload.details;
this.correlationId = payload.correlationId
|| globalThis.crypto?.randomUUID?.()
|| new Date().toISOString();
}
}
export async function request(url, options = {}, fetchImpl = fetch) {
let response;
try {
response = await fetchImpl(url, {
...options,
headers: {
'content-type': 'application/json',
...(options.headers || {}),
},
});
} catch (error) {
if (error?.name === 'AbortError') throw error;
throw new HarborApiError({ code: 'CONTROL_UNREACHABLE' });
}
let data = {};
try {
data = await response.json();
} catch {
if (response.ok) throw new HarborApiError({ code: 'UNKNOWN' }, response.status);
}
if (!response.ok || data?.success === false) {
throw new Error(data?.error || `Запрос ${url} завершился ошибкой ${response.status}`);
const payload = data?.error && typeof data.error === 'object'
? data.error
: { code: response.status >= 500 ? 'CONTROL_UNREACHABLE' : 'UNKNOWN' };
throw new HarborApiError(payload, response.status);
}
return data;
}
export const api = {
state: () => request('/api/state'),
version: () => request('/api/version'),
subscription: {
validate: (url, { signal } = {}) => request('/api/subscription/validate', {
method: 'POST',
body: JSON.stringify({ url }),
signal,
}),
fetch: (url) => request('/api/subscription/fetch', {
method: 'POST',
body: JSON.stringify({ url }),
}),
refreshInfo: () => request('/api/subscription/refresh-info', { method: 'POST' }),
refresh: () => request('/api/subscription/refresh', { method: 'POST' }),
forget: () => request('/api/subscription', { method: 'DELETE' }),
},
apply: (selectedTag) => request('/api/apply', {
apply: (serverId) => request('/api/apply', {
method: 'POST',
body: JSON.stringify({ selectedTag }),
// selectedTag keeps this client compatible with pre-ID Harbor backends.
body: JSON.stringify({ serverId, selectedTag: serverId }),
}),
gatewayAuto: {
setEnabled: (enabled) => request('/api/gateway-auto', {
method: 'POST',
body: JSON.stringify({ enabled }),
}),
},
routeRules: {
update: (rules, expectedRulesRevision) => request('/api/route-rules', {
method: 'PUT',
body: JSON.stringify({ rules, expectedRulesRevision }),
}),
},
singbox: {
stop: () => request('/api/singbox/stop', { method: 'POST' }),
restart: () => request('/api/singbox/restart', { method: 'POST' }),
},
servers: {
pingAll: () => request('/api/servers/ping-all', { method: 'POST' }),
ping: (serverIds) => request('/api/servers/ping-all', {
method: 'POST',
body: JSON.stringify({ serverIds }),
}),
},
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,98 @@
import React, { useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
const FOCUSABLE = 'button:not(:disabled), [href], input:not(:disabled), [tabindex]:not([tabindex="-1"])';
export function ConfirmationPopup({
open,
id,
kicker,
title,
description,
cancelLabel,
confirmLabel,
busy = false,
onCancel,
onConfirm,
}) {
const overlayRef = useRef(null);
const dialogRef = useRef(null);
const cancelRef = useRef(null);
const busyRef = useRef(busy);
const onCancelRef = useRef(onCancel);
busyRef.current = busy;
onCancelRef.current = onCancel;
useEffect(() => {
if (!open) return undefined;
const previousFocus = document.activeElement;
const background = [...(overlayRef.current?.parentElement?.children || [])]
.filter((element) => !element.classList.contains('client-confirmation-popup'))
.map((element) => [element, element.inert]);
background.forEach(([element]) => { element.inert = true; });
const previousOverflow = document.body.style.overflow;
document.body.style.overflow = 'hidden';
const frame = requestAnimationFrame(() => cancelRef.current?.focus());
const onKeyDown = (event) => {
if (event.key === 'Escape' && !busyRef.current) {
event.preventDefault();
onCancelRef.current();
return;
}
if (event.key !== 'Tab') return;
const controls = [...(dialogRef.current?.querySelectorAll(FOCUSABLE) || [])];
if (!controls.length) return;
const first = controls[0];
const last = controls.at(-1);
if (!dialogRef.current?.contains(document.activeElement)) {
event.preventDefault();
first.focus();
} else if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
};
document.addEventListener('keydown', onKeyDown);
return () => {
cancelAnimationFrame(frame);
document.removeEventListener('keydown', onKeyDown);
background.forEach(([element, inert]) => { element.inert = inert; });
document.body.style.overflow = previousOverflow;
requestAnimationFrame(() => previousFocus?.focus?.());
};
}, [open]);
return createPortal(
<div
ref={overlayRef}
className={`client-confirmation-popup${open ? ' is-open' : ''}`}
aria-hidden={!open}
inert={!open ? true : undefined}
onPointerDown={(event) => {
if (event.target === event.currentTarget && !busy) onCancel();
}}
>
<section
ref={dialogRef}
className="client-confirmation-dialog"
role="alertdialog"
aria-modal="true"
aria-labelledby={`${id}-title`}
aria-describedby={`${id}-description`}
aria-busy={busy}
>
{kicker && <span className="client-confirmation-kicker">{kicker}</span>}
<h2 id={`${id}-title`}>{title}</h2>
<p id={`${id}-description`}>{description}</p>
<div className="client-confirmation-actions">
<button ref={cancelRef} type="button" disabled={busy} onClick={onCancel}>{cancelLabel}</button>
<button className="is-danger" type="button" disabled={busy} onClick={onConfirm}>{confirmLabel}</button>
</div>
</section>
</div>,
document.querySelector('.app.client-app') || document.body,
);
}

View File

@@ -0,0 +1,361 @@
import React, { useEffect, useMemo, useState } from 'react';
import { api } from '../api.js';
import {
autoServer,
filterServers,
groupServers,
SERVER_RESULT_WINDOW,
} from '../utils/serverPicker.js';
const FAVORITES_KEY = 'harbor-server-favorites';
const RECENT_KEY = 'harbor-server-recent';
const AUTO_KEY = 'harbor-server-auto';
const SIMPLE_SERVER_LIMIT = 5;
function readList(key) {
try {
const value = JSON.parse(localStorage.getItem(key) || '[]');
return Array.isArray(value) ? value.map(String) : [];
} catch {
return [];
}
}
function write(key, value) {
try {
localStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value));
} catch {
// Preferences remain available for this session.
}
}
function readAuto() {
try {
return localStorage.getItem(AUTO_KEY) === 'true';
} catch {
return false;
}
}
function serverHealthText(ping) {
if (ping?.error) return 'Проверка недоступна';
if (ping?.ok) return `${ping.latency} мс`;
return ping ? 'Недоступен' : null;
}
function ServerHealth({ ping, fallback }) {
const health = fallback || serverHealthText(ping);
if (!health && !ping?.checking) return null;
return <small
className={`client-server-health${ping?.checking ? ' is-checking' : ''}`}
title={ping?.checkedAt || undefined}
aria-label={ping?.checking ? 'Проверяем пинг' : health}
>
<span aria-hidden="true">{health}</span>
<svg className="client-server-health-checking" viewBox="0 0 24 24" aria-hidden="true">
<path d="M21 12a9 9 0 0 0-15.2-6.5L3 8m0-5v5h5M3 12a9 9 0 0 0 15.2 6.5L21 16m0 5v-5h-5" />
</svg>
</small>;
}
function ServerCheckButton({ checking, disabled, onClick }) {
return <button
className={`client-server-check client-tooltip-anchor${checking ? ' is-checking' : ''}`}
type="button"
aria-label={checking ? 'Проверяем пинг серверов' : 'Проверить пинг серверов'}
disabled={checking || disabled}
onClick={onClick}
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M21 12a9 9 0 0 0-15.2-6.5L3 8m0-5v5h5M3 12a9 9 0 0 0 15.2 6.5L21 16m0 5v-5h-5" />
</svg>
<span className="client-tooltip" role="tooltip">{checking ? 'Проверяем пинг…' : 'Проверить пинг'}</span>
</button>;
}
function ServerRow({ server, selected, favorite, ping, disabled, index, onSelect, onFavorite }) {
const health = ping?.checking ? 'Проверяем пинг' : serverHealthText(ping);
return <div className={`client-server-row${selected ? ' is-selected' : ''}${onFavorite ? ' has-favorite' : ''}`}>
<button
className={`client-server${selected ? ' is-selected' : ''}`}
type="button"
disabled={disabled}
aria-pressed={selected}
aria-label={`${server.label}, ${server.host}:${server.port}${health ? `, ${health}` : ''}`}
style={{ '--server-index': Math.min(index, 7) }}
onClick={() => onSelect(server.id)}
>
<strong>{server.label}</strong>
</button>
{(ping || onFavorite) && <div className="client-server-meta">
<ServerHealth ping={ping} />
{onFavorite && <button
className={`client-server-favorite${favorite ? ' is-active' : ''}`}
type="button"
aria-pressed={favorite}
aria-label={`${favorite ? 'Убрать из избранного' : 'Добавить в избранное'}: ${server.label}`}
onClick={() => onFavorite(server.id)}
></button>}
</div>}
</div>;
}
export function ServerPicker({
servers,
selectedServerId,
disabled,
prompt,
leaving,
revealVersion,
onSelect,
}) {
const [query, setQuery] = useState('');
const [advanced, setAdvanced] = useState(false);
const [view, setView] = useState('all');
const [page, setPage] = useState(0);
const [favorites, setFavorites] = useState(() => readList(FAVORITES_KEY));
const [recent, setRecent] = useState(() => readList(RECENT_KEY));
const [autoActive, setAutoActive] = useState(readAuto);
const [collapsed, setCollapsed] = useState([]);
const [pings, setPings] = useState({});
const [checking, setChecking] = useState(false);
const serverKey = servers.map(({ id }) => id).join('|');
useEffect(() => {
setPage(0);
}, [query, view, serverKey]);
const selected = servers.find(({ id }) => id === selectedServerId);
const filtered = useMemo(() => {
const found = filterServers(servers, query);
if (view === 'favorites') return found.filter(({ id }) => favorites.includes(id));
if (view === 'recent') return recent.flatMap((id) => found.find((server) => server.id === id) || []);
return found;
}, [servers, query, view, favorites, recent]);
const results = filtered.filter(({ id }) => id !== selectedServerId);
const pageCount = Math.max(1, Math.ceil(results.length / SERVER_RESULT_WINDOW));
const visible = results.slice(page * SERVER_RESULT_WINDOW, (page + 1) * SERVER_RESULT_WINDOW);
const grouped = servers.length >= 10;
useEffect(() => {
setPage((current) => Math.min(current, pageCount - 1));
}, [pageCount]);
function toggleFavorite(id) {
setFavorites((current) => {
const next = current.includes(id) ? current.filter((item) => item !== id) : [id, ...current];
write(FAVORITES_KEY, next);
return next;
});
}
function select(id, automatic = false) {
setAutoActive(automatic);
write(AUTO_KEY, String(automatic));
if (!automatic) {
setRecent((current) => {
const next = [id, ...current.filter((item) => item !== id)].slice(0, 5);
write(RECENT_KEY, next);
return next;
});
}
onSelect(id);
}
async function checkVisible() {
const ids = [...new Set([selectedServerId, ...visible.map(({ id }) => id)].filter(Boolean))].slice(0, 30);
if (!ids.length) return;
const startedAt = performance.now();
setChecking(true);
setPings((current) => ({
...current,
...Object.fromEntries(ids.map((id) => [id, { ...current[id], checking: true }])),
}));
try {
const data = await api.servers.ping(ids);
setPings((current) => ({
...current,
...Object.fromEntries((data.results || []).map((result) => [result.id, { ...result, checking: true }])),
}));
} catch {
setPings((current) => ({
...current,
...Object.fromEntries(ids.map((id) => [id, { error: true, checking: true, checkedAt: new Date().toISOString() }])),
}));
} finally {
await new Promise((resolve) => setTimeout(resolve, Math.max(0, 700 - (performance.now() - startedAt))));
setPings((current) => ({
...current,
...Object.fromEntries(ids.map((id) => [id, { ...current[id], checking: false }])),
}));
setChecking(false);
}
}
if (servers.length === 1) {
return <section className="client-servers" aria-label="Выберите сервер">
{prompt && <span className="client-server-prompt">Выберите сервер</span>}
<div className="client-server-toolbar is-single">
<span className="client-server-toolbar-title">Список серверов</span>
<ServerCheckButton checking={checking} onClick={checkVisible} />
</div>
<div className="client-server-grid">
<ServerRow
server={servers[0]}
selected={servers[0].id === selectedServerId}
favorite={false}
ping={pings[servers[0].id]}
disabled={disabled}
index={0}
onSelect={onSelect}
/>
</div>
</section>;
}
const renderRows = (items, offset = 0) => items.map((server, index) => (
<ServerRow
key={server.id}
server={server}
selected={!autoActive && server.id === selectedServerId}
favorite={favorites.includes(server.id)}
ping={pings[server.id]}
disabled={disabled}
index={offset + index}
onSelect={select}
onFavorite={toggleFavorite}
/>
));
const simpleServers = [
...(selected ? [selected] : []),
...servers.filter(({ id }) => id !== selectedServerId),
].slice(0, SIMPLE_SERVER_LIMIT);
return <section className="client-servers is-scalable" aria-label="Выберите сервер">
{prompt && <span className="client-server-prompt">Выберите сервер</span>}
<div className="client-server-toolbar">
<span className="client-server-toolbar-title">Список серверов</span>
<ServerCheckButton checking={checking} disabled={!servers.length} onClick={checkVisible} />
<button
className={`client-server-mode-toggle${advanced ? ' is-open' : ''}`}
type="button"
aria-expanded={advanced}
aria-label={advanced ? 'Скрыть поиск и фильтры' : 'Показать поиск и фильтры'}
onClick={() => setAdvanced((current) => !current)}
>
<span>Поиск и фильтры</span>
<svg viewBox="0 0 12 8" aria-hidden="true"><path d="m1 1 5 5 5-5" /></svg>
</button>
</div>
<div className="client-server-mode-panels">
<div
className={`client-server-mode-panel is-simple${advanced ? '' : ' is-open'}`}
aria-hidden={advanced}
inert={advanced ? true : undefined}
>
<div className="client-server-mode-panel-inner">
<div className={`client-server-scroll${leaving ? ' is-leaving' : ''}`} key={`simple:${serverKey}:${revealVersion}`}>
<div className="client-server-grid">
{simpleServers.map((server, index) => <ServerRow
key={server.id}
server={server}
selected={server.id === selectedServerId}
ping={pings[server.id]}
disabled={disabled}
index={index}
onSelect={select}
/>)}
</div>
{servers.length > simpleServers.length && <p className="client-server-overflow-note">
Ещё {servers.length - simpleServers.length} доступны через поиск
</p>}
</div>
</div>
</div>
<div
className={`client-server-mode-panel is-advanced${advanced ? ' is-open' : ''}`}
aria-hidden={!advanced}
inert={!advanced ? true : undefined}
>
<div className="client-server-mode-panel-inner">
<div className="client-server-tools">
<input
type="search"
value={query}
aria-label="Найти сервер"
placeholder="Поиск сервера"
onChange={(event) => setQuery(event.target.value)}
/>
<div className="client-server-filters" aria-label="Фильтр серверов">
{[
['all', 'Все'],
['favorites', '★'],
['recent', 'Недавние'],
].map(([id, label]) => <button
type="button"
className={view === id ? 'is-active' : ''}
aria-pressed={view === id}
key={id}
onClick={() => setView(id)}
>{label}</button>)}
</div>
</div>
<div className="client-server-pinned">
<button
className={`client-server-auto${autoActive ? ' is-selected' : ''}`}
type="button"
aria-pressed={autoActive}
disabled={disabled || !servers.length}
onClick={() => select(autoServer(servers)?.id, true)}
>
<strong>Auto</strong>
<ServerHealth
ping={autoActive ? pings[selectedServerId] : undefined}
fallback={autoActive ? undefined : 'Первый стабильный сервер'}
/>
</button>
{selected && <ServerRow
server={selected}
selected
favorite={favorites.includes(selected.id)}
ping={pings[selected.id]}
disabled={disabled}
index={0}
onSelect={select}
onFavorite={toggleFavorite}
/>}
</div>
<div className={`client-server-scroll${leaving ? ' is-leaving' : ''}`} key={`advanced:${serverKey}:${revealVersion}`}>
{!visible.length && <p className="client-server-empty">Серверы не найдены</p>}
{grouped ? groupServers(visible).map(([group, items]) => {
const isCollapsed = collapsed.includes(group);
return <section className="client-server-group" key={group}>
<button
className="client-server-group-toggle"
type="button"
aria-expanded={!isCollapsed}
onClick={() => setCollapsed((current) => current.includes(group)
? current.filter((item) => item !== group)
: [...current, group])}
>{group} <small>{items.length}</small></button>
{!isCollapsed && <div className="client-server-grid">{renderRows(items)}</div>}
</section>;
}) : <div className="client-server-grid">{renderRows(visible)}</div>}
{pageCount > 1 && <nav className="client-server-pages" aria-label="Страницы серверов">
<button className="client-server-more" type="button" disabled={page === 0} onClick={() => setPage((current) => current - 1)}>Назад</button>
<span>{page + 1} / {pageCount}</span>
<button className="client-server-more" type="button" disabled={page + 1 === pageCount} onClick={() => setPage((current) => current + 1)}>Дальше</button>
</nav>}
</div>
</div>
</div>
</div>
</section>;
}

View File

@@ -0,0 +1,51 @@
import React from 'react';
const bootCopy = {
'control-unreachable': {
title: 'Harbor недоступен',
message: 'Control plane не ответил. Проверьте, что контейнер запущен, и повторите запрос.',
},
'incompatible-api': {
title: 'Версия Harbor несовместима',
message: 'Интерфейс получил state неизвестной версии. Обновите frontend и control plane вместе.',
},
fatal: {
title: 'Harbor не удалось запустить',
message: 'Произошла непредвиденная ошибка. Технические детали помогут найти причину.',
},
};
export function BootStatePage({ transport, onRetry }) {
if (transport.bootStatus === 'loading') return <div className="app-loading">Harbor</div>;
const copy = bootCopy[transport.bootStatus] || bootCopy.fatal;
return (
<main className="app-boot">
<span>Harbor</span>
<h1>{copy.title}</h1>
<p>{copy.message}</p>
<button type="button" onClick={onRetry}>Повторить</button>
<details>
<summary>Технические детали</summary>
<code>{transport.error?.message}</code>
<pre>{`curl -i ${window.location.origin}/api/state\ndocker compose logs --tail=100`}</pre>
</details>
</main>
);
}
export function StaleBanner({ transport, onRetry }) {
if (!transport.stale) return null;
const lastSync = transport.lastSuccessfulSyncAt
? new Date(transport.lastSuccessfulSyncAt).toLocaleTimeString('ru-RU')
: 'неизвестно';
const incompatible = transport.error?.kind === 'incompatible-api';
return (
<aside className="client-stale-banner" role="status">
<strong>{incompatible ? 'API несовместим' : 'Показано последнее известное состояние'}</strong>
<span>Последняя синхронизация: {lastSync}</span>
<button type="button" onClick={onRetry}>Повторить</button>
</aside>
);
}

87
src/web/instructions.js Normal file
View File

@@ -0,0 +1,87 @@
export function instructionBlocks({ isGateway, host, port }) {
const httpProxy = `http://${host}:${port}`;
const socksProxy = `socks5://${host}:${port}`;
return [
{
id: 'about',
label: 'Основы',
title: isGateway ? 'Gateway и прокси' : 'Что такое прокси',
summary: isGateway
? 'Два способа направить трафик через это устройство.'
: 'Способ направить трафик выбранного приложения через VPN.',
paragraphs: isGateway
? [
`Gateway (${host}) заменяет основной шлюз устройства и проводит через VPN весь его интернет-трафик.`,
`Gateway Proxy (${host}:${port}) работает точечно: его указывают в браузере, редакторе или другом приложении. Если приложение не умеет работать с прокси, можно использовать ProxyBridge.`,
]
: [
`Локальный прокси (${host}:${port}) не перенаправляет приложения автоматически. Каждое приложение должно использовать этот адрес само — напрямую или через ProxyBridge.`,
'HTTP обычно проще для браузеров и редакторов. SOCKS5 подходит приложениям и инструментам, которым нужен более универсальный транспорт.',
],
},
{
id: 'proxybridge',
label: 'Приложения',
title: 'ProxyBridge',
summary: 'Направляет через прокси отдельные приложения, даже если у них нет своей настройки.',
steps: [
{
link: ['Установите ProxyBridge', 'https://interceptsuite.com/download/proxybridge'],
after: ' с официальной страницы проекта.',
},
`Добавьте прокси типа SOCKS5: сервер ${host}, порт ${port}.`,
'Создайте правило, выберите нужное приложение и действие Proxy.',
'Включите ProxyBridge и запустите приложение заново.',
],
note: 'Не добавляйте в правило сам ProxyBridge и VPN-клиент: это может создать прокси-цикл.',
},
{
id: 'switchyomega',
label: 'Браузер',
title: 'SwitchyOmega',
summary: 'Переключает прокси-профили только для браузера.',
steps: [
{
link: ['Установите расширение', 'https://chromewebstore.google.com/detail/proxy-switchyomega/padekgcemlokbadohgkifijomclgjgif'],
after: ' и откройте его настройки.',
},
'Создайте профиль Proxy Profile.',
`Выберите HTTP, укажите сервер ${host} и порт ${port}.`,
'Создайте профиль Auto Switch, выберите созданный прокси для нужных сайтов, а для остальных оставьте Direct.',
'Если сайт не загрузился, откройте SwitchyOmega: расширение покажет проблемные ресурсы. Добавьте домен текущего сайта в Auto Switch и назначьте ему прокси-профиль.',
],
note: 'Проект больше не поддерживается. Используйте его только если расширение уже подходит вашему браузеру.',
},
{
id: 'vscode',
label: 'Редактор',
title: 'Visual Studio Code',
summary: 'VS Code использует системный прокси или адрес, переданный при запуске.',
steps: [
'Если прокси уже настроен в системе, полностью перезапустите VS Code — обычно он подхватит настройку автоматически.',
'Для отдельного запуска через SOCKS5 используйте команду ниже.',
{
link: ['Документация VS Code', 'https://code.visualstudio.com/docs/setup/network'],
after: ' описывает также системный прокси, HTTP и параметры исключений.',
},
],
code: `code --proxy-server="${socksProxy}"`,
note: `VS Code не поддерживает логин и пароль для SOCKS5. Здесь прокси ${host}:${port} локальный и без авторизации, поэтому этот вариант подходит. HTTP-адрес ${httpProxy} остаётся альтернативой.`,
},
...(isGateway ? [{
id: 'router',
label: 'Вся сеть',
title: 'Заменить Gateway в роутере',
summary: 'Роутер будет выдавать этот Gateway устройствам как основной шлюз.',
steps: [
`Закрепите за Gateway постоянный адрес ${host} в настройках DHCP роутера.`,
'Откройте настройки локальной сети или DHCP. Не меняйте шлюз WAN/интернет-подключения.',
`В поле Default Gateway, Router или Основной шлюз укажите ${host}.`,
'Сохраните настройки и переподключите устройства к сети, чтобы они получили новый маршрут.',
`Для отката верните в это поле локальный адрес самого роутера вместо ${host}.`,
],
note: 'Gateway и устройства должны находиться в одной локальной сети. Сначала проверьте настройку на одном устройстве вручную.',
}] : []),
];
}

View File

@@ -0,0 +1,92 @@
export const initialHarborState = {
snapshot: null,
pendingServerId: '',
transport: {
bootStatus: 'loading',
lastSuccessfulSyncAt: null,
consecutiveFailures: 0,
stale: false,
error: null,
},
};
export const STALE_FAILURE_THRESHOLD = 3;
export function compatibleSnapshot(snapshot) {
return snapshot?.apiVersion === 1 &&
Number.isSafeInteger(snapshot.revision) &&
typeof snapshot.selection?.desiredServerId === 'string' &&
Array.isArray(snapshot.servers);
}
export function classifySyncError(error) {
const status = Number(error?.status) || 0;
if (error?.code === 'INCOMPATIBLE_API' || status === 404) return 'incompatible-api';
if (error?.code === 'CONTROL_UNREACHABLE' || error?.name === 'TypeError' || status >= 500) return 'control-unreachable';
return 'fatal';
}
function reconcilePendingServer(pendingServerId, snapshot) {
if (!pendingServerId || snapshot.selection.desiredServerId === pendingServerId) return '';
return snapshot.servers.some((server) => server.id === pendingServerId)
? pendingServerId
: '';
}
export function harborReducer(current, action) {
if (action.type === 'select-server') {
return action.serverId === current.pendingServerId
? current
: { ...current, pendingServerId: action.serverId };
}
if (action.type === 'clear-pending-server') {
return current.pendingServerId ? { ...current, pendingServerId: '' } : current;
}
if (action.type === 'retry-sync') {
return current.snapshot ? current : {
...current,
transport: { ...current.transport, bootStatus: 'loading', error: null },
};
}
if (action.type === 'sync-failed') {
const consecutiveFailures = current.transport.consecutiveFailures + 1;
const bootStatus = classifySyncError(action.error);
return {
...current,
transport: {
...current.transport,
bootStatus: current.snapshot ? 'ready' : bootStatus,
consecutiveFailures,
stale: Boolean(current.snapshot) && (
bootStatus === 'incompatible-api' || consecutiveFailures >= STALE_FAILURE_THRESHOLD
),
error: {
kind: bootStatus,
message: action.error?.message || 'Неизвестная ошибка',
},
},
};
}
if (action.type !== 'sync-succeeded') return current;
const snapshot = action.snapshot;
const newer = !current.snapshot || snapshot.revision > current.snapshot.revision;
return {
snapshot: newer ? snapshot : current.snapshot,
pendingServerId: newer
? reconcilePendingServer(current.pendingServerId, snapshot)
: current.pendingServerId,
transport: {
bootStatus: 'ready',
lastSuccessfulSyncAt: action.receivedAt,
consecutiveFailures: 0,
stale: false,
error: null,
},
};
}

View File

@@ -0,0 +1,42 @@
export const OPERATION_CONFLICTS = Object.freeze({
connection: ['serverApply', 'subscriptionImport', 'subscriptionRefresh', 'subscriptionDelete', 'gatewayAuto', 'routeRules'],
serverApply: ['connection', 'subscriptionImport', 'subscriptionRefresh', 'subscriptionDelete', 'gatewayAuto', 'routeRules'],
subscriptionImport: ['connection', 'serverApply', 'subscriptionRefresh', 'subscriptionDelete', 'gatewayAuto', 'routeRules'],
subscriptionRefresh: ['connection', 'serverApply', 'subscriptionImport', 'subscriptionDelete', 'gatewayAuto', 'routeRules'],
subscriptionDelete: ['connection', 'serverApply', 'subscriptionImport', 'subscriptionRefresh', 'gatewayAuto', 'routeRules'],
gatewayAuto: ['connection', 'serverApply', 'subscriptionImport', 'subscriptionRefresh', 'subscriptionDelete', 'routeRules'],
routeRules: ['connection', 'serverApply', 'subscriptionImport', 'subscriptionRefresh', 'subscriptionDelete', 'gatewayAuto'],
});
export function operationBlocked(operations, key) {
if (operations[key]?.status === 'running') return true;
return (OPERATION_CONFLICTS[key] || []).some(
(conflict) => operations[conflict]?.status === 'running',
);
}
export function createOperationRegistry(onChange = () => {}, now = () => new Date().toISOString()) {
let operations = {};
const inFlight = new Map();
function run(key, action) {
if (inFlight.has(key)) return inFlight.get(key);
if (operationBlocked(operations, key)) return Promise.resolve(false);
operations = { ...operations, [key]: { status: 'running', startedAt: now() } };
onChange(operations);
const promise = Promise.resolve()
.then(action)
.finally(() => {
const { [key]: completed, ...remaining } = operations;
operations = remaining;
inFlight.delete(key);
onChange(operations);
});
inFlight.set(key, promise);
return promise;
}
return { run, getSnapshot: () => operations };
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,22 +1,55 @@
export function connectionAction({ connected, selectedTag, configExists }) {
export function connectionAction({ connected, selectedServerId, configExists }) {
if (connected) return { type: 'stop' };
if (selectedTag) return { type: 'apply', selectedTag };
if (selectedServerId) return { type: 'apply', serverId: selectedServerId };
if (configExists) return { type: 'restart' };
return null;
}
export function formatConnectionDuration(startedAt, now = Date.now()) {
const { totalHours, minutes, seconds } = connectionDurationParts(startedAt, now);
return [totalHours, minutes.value, seconds.value]
.map((part) => String(part).padStart(2, '0'))
.join(':');
}
function durationLabel(value, forms) {
const mod10 = value % 10;
const mod100 = value % 100;
return mod10 === 1 && mod100 !== 11
? forms[0]
: mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14) ? forms[1] : forms[2];
}
export function connectionDurationParts(startedAt, now = Date.now()) {
const started = Date.parse(startedAt);
const totalSeconds = Number.isFinite(started)
? Math.max(0, Math.floor((now - started) / 1000))
: 0;
const hours = Math.floor(totalSeconds / 3600);
const days = Math.floor(totalSeconds / 86_400);
const totalHours = Math.floor(totalSeconds / 3600);
const hours = Math.floor((totalSeconds % 86_400) / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
return [hours, minutes, seconds]
.map((part) => String(part).padStart(2, '0'))
.join(':');
return {
totalHours,
days: { value: days, label: durationLabel(days, ['день', 'дня', 'дней']) },
hours: { value: hours, label: durationLabel(hours, ['час', 'часа', 'часов']) },
minutes: { value: minutes, label: durationLabel(minutes, ['минута', 'минуты', 'минут']) },
seconds: { value: seconds, label: durationLabel(seconds, ['секунда', 'секунды', 'секунд']) },
};
}
export function formatConnectionDurationWords(startedAt, now = Date.now()) {
const { days, hours, minutes, seconds } = connectionDurationParts(startedAt, now);
return [
days.value && `${days.value} ${days.label}`,
hours.value && `${hours.value} ${hours.label}`,
minutes.value && `${minutes.value} ${minutes.label}`,
`${seconds.value} ${seconds.label}`,
].filter(Boolean).join(' ');
}
export function subscriptionDomain(subscriptionHost) {
@@ -28,6 +61,14 @@ export function subscriptionDomain(subscriptionHost) {
}
}
export function isSubscriptionUrlValid(value) {
try {
return ['http:', 'https:'].includes(new URL(String(value).trim()).protocol);
} catch {
return false;
}
}
export function localProxyUrls(port = 8082, host = '127.0.0.1') {
const urlHost = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
return {
@@ -36,6 +77,27 @@ export function localProxyUrls(port = 8082, host = '127.0.0.1') {
};
}
export async function copyText(text, options = {}) {
const clipboard = options.clipboard ?? globalThis.navigator?.clipboard;
const documentRef = options.documentRef ?? globalThis.document;
if (documentRef?.execCommand) {
const textarea = documentRef.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
documentRef.body.append(textarea);
textarea.select();
const copied = documentRef.execCommand('copy');
textarea.remove();
if (copied) return;
}
if (!clipboard?.writeText) throw new Error('Copy failed');
await clipboard.writeText(text);
}
export function subscriptionUsage(userInfo = {}) {
const upload = Math.max(0, Number(userInfo.upload) || 0);
const download = Math.max(0, Number(userInfo.download) || 0);

View File

@@ -0,0 +1,31 @@
export const SERVER_RESULT_WINDOW = 60;
const searchable = (server) => [
server.label,
server.host,
server.country,
server.city,
server.provider,
server.protocol,
].filter(Boolean).join(' ').toLocaleLowerCase('ru');
export function filterServers(servers, query) {
const needle = String(query || '').trim().toLocaleLowerCase('ru');
return needle ? servers.filter((server) => searchable(server).includes(needle)) : servers;
}
export function serverGroup(server) {
return server.country || server.provider || 'Другие';
}
export function groupServers(servers) {
return [...servers.reduce((groups, server) => {
const name = serverGroup(server);
groups.set(name, [...(groups.get(name) || []), server]);
return groups;
}, new Map())];
}
export function autoServer(servers) {
return [...servers].sort((left, right) => left.id.localeCompare(right.id))[0] || null;
}

View File

@@ -0,0 +1,54 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { parseSubscriptionBody } from '../src/server/subscription.js';
import { createStateSnapshot, normalizeStoredState } from '../src/shared/contracts/state.js';
const outbound = (index) => ({
type: 'vless',
tag: index % 2 ? 'Amsterdam' : 'Frankfurt',
server: `vpn-${index}.example.test`,
server_port: 443,
});
const parse = (outbounds) => parseSubscriptionBody(JSON.stringify({ outbounds }));
test('data invariant: 1, 30 and 300 servers keep unique IDs across reorder and duplicate labels', () => {
for (const size of [1, 30, 300]) {
const source = Array.from({ length: size }, (_, index) => outbound(index));
const before = parse(source).servers;
const after = parse([...source].reverse()).servers;
assert.equal(before.length, size);
assert.equal(new Set(before.map((server) => server.id)).size, size);
assert.deepEqual(
after.map((server) => server.id).sort(),
before.map((server) => server.id).sort(),
);
}
});
test('data invariant: one canonical snapshot owns server selection and never exposes the subscription URL', () => {
const servers = parse(Array.from({ length: 30 }, (_, index) => outbound(index))).servers;
const selectedServerId = servers[17].id;
const stored = normalizeStoredState({
revision: 9,
subscriptionUrl: 'https://provider.example/private-token',
servers,
selectedServerId,
appliedServerId: selectedServerId,
});
const snapshot = createStateSnapshot({
storedState: stored,
runtime: { running: false },
appMode: 'client',
configExists: true,
subscriptionHost: 'provider.example/…',
now: new Date('2026-07-12T12:00:00.000Z'),
});
assert.equal(snapshot.revision, 9);
assert.deepEqual(snapshot.selection, { desiredServerId: selectedServerId, appliedServerId: selectedServerId });
assert.equal(snapshot.servers.find((server) => server.id === selectedServerId)?.host, 'vpn-17.example.test');
assert.equal(JSON.stringify(snapshot).includes('private-token'), false);
});

View File

@@ -0,0 +1,42 @@
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
const root = path.resolve(import.meta.dirname, '..');
test('one-line installer extracts the archive and hands it to the macOS installer', () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'harbor-install-'));
try {
const source = path.join(tmp, 'fixture', 'harbor-net');
fs.mkdirSync(path.join(source, 'scripts'), { recursive: true });
fs.writeFileSync(path.join(source, 'marker'), 'ok');
fs.writeFileSync(path.join(source, 'scripts', 'install-macos-client.sh'), [
'#!/bin/bash',
'set -eu',
'test "$(cat "$VPN_PROXY_SOURCE_DIR/marker")" = ok',
'printf bootstrap-ok',
].join('\n'));
const archive = path.join(tmp, 'source.tar.gz');
execFileSync('tar', ['-czf', archive, '-C', path.dirname(source), path.basename(source)]);
const bin = path.join(tmp, 'bin');
fs.mkdirSync(bin);
fs.writeFileSync(path.join(bin, 'curl'), '#!/bin/sh\ncat "$FIXTURE_ARCHIVE"\n', { mode: 0o755 });
const output = execFileSync('sh', [path.join(root, 'install.sh')], {
encoding: 'utf8',
env: {
...process.env,
FIXTURE_ARCHIVE: archive,
PATH: `${bin}:/usr/bin:/bin`,
VPN_PROXY_ARCHIVE_URL: 'https://example.invalid/source.tar.gz',
},
});
assert.equal(output, 'bootstrap-ok');
} finally {
fs.rmSync(tmp, { recursive: true, force: true });
}
});

View File

@@ -0,0 +1,31 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createDataplaneClient } from '../../src/server/dataplaneClient.js';
test('control uses the dataplane socket protocol', async () => {
const requests = [];
const send = async (socketPath, pathname, method) => {
requests.push(`${method} ${pathname} ${socketPath}`);
return {
running: pathname !== '/stop',
startedAt: 'now',
gatewayBackendVersion: '0.1.0',
singBoxVersion: '1.12.13',
};
};
const client = createDataplaneClient('/run/dataplane.sock', send);
const status = await client.refresh();
assert.equal(status.running, true);
assert.equal(status.gatewayBackendVersion, '0.1.0');
assert.equal(status.singBoxVersion, '1.12.13');
await client.apply();
await client.restart();
assert.equal((await client.stop()).running, false);
assert.deepEqual(requests, [
'GET /status /run/dataplane.sock',
'POST /apply /run/dataplane.sock',
'POST /restart /run/dataplane.sock',
'POST /stop /run/dataplane.sock',
]);
});

View File

@@ -0,0 +1,28 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
const root = path.resolve(import.meta.dirname, '../..');
const compose = fs.readFileSync(path.join(root, 'docker-compose.gateway.yml'), 'utf8');
const deploy = fs.readFileSync(path.join(root, 'scripts/deploy-gateway.sh'), 'utf8');
const workflow = fs.readFileSync(path.join(root, '.gitea/workflows/gateway-build.yml'), 'utf8');
const dockerfiles = ['Dockerfile', 'Dockerfile.client']
.map((file) => fs.readFileSync(path.join(root, file), 'utf8'));
test('gateway deploy updates control without recreating dataplane', () => {
assert.match(compose, /vpn-proxy-control:/);
assert.match(compose, /vpn-proxy-dataplane:/);
assert.match(compose, /DATAPLANE_SOCKET: \/run\/vpn-proxy\/dataplane\.sock/);
assert.match(deploy, /up -d --no-deps --wait[^\n]+vpn-proxy-control/);
assert.match(workflow, /UPDATE_DATAPLANE="\$\{UPDATE_DATAPLANE\}"/);
assert.match(workflow, /src\/server\/\(config\|dataplane\|gatewayRouting\|singboxRuntime\|version\)/);
assert.match(workflow, /src\/shared\/errors/);
assert.doesNotMatch(workflow, /dataplaneClient/);
});
test('runtime images include shared server modules', () => {
for (const dockerfile of dockerfiles) {
assert.match(dockerfile, /COPY src\/shared \/app\/src\/shared/);
}
});

View File

@@ -8,8 +8,19 @@ const entrypoint = fs.readFileSync(
'utf8',
);
test('gateway intercepts all public TCP and UDP traffic without source bypasses', () => {
test('gateway keeps direct forwarding active while TProxy interception is switchable', () => {
assert.match(entrypoint, /-p tcp -j TPROXY --on-port "\$TPROXY_PORT"/);
assert.match(entrypoint, /-p udp -j TPROXY --on-port "\$TPROXY_PORT"/);
assert.match(entrypoint, /-I FORWARD 1 -j "\$GATEWAY_FORWARD_CHAIN"/);
assert.match(entrypoint, /-I POSTROUTING 1 -j "\$GATEWAY_NAT_CHAIN"/);
assert.match(entrypoint, /-A "\$TPROXY_CHAIN" -i 'br-\+' -j RETURN/);
assert.doesNotMatch(entrypoint, /-A PREROUTING -j "\$TPROXY_CHAIN"/);
assert.doesNotMatch(entrypoint, /TPROXY_BYPASS_SOURCE_CIDRS|DIRECT_BYPASS_CACHE|ipset/);
});
test('control bypasses host routing while dataplane owns it', () => {
assert.match(entrypoint, /APP_COMPONENT.*control/);
assert.match(entrypoint, /exec node \/app\/src\/server\/index\.js/);
assert.match(entrypoint, /APP_COMPONENT.*dataplane/);
assert.match(entrypoint, /node \/app\/src\/server\/dataplane\.js/);
});

View File

@@ -0,0 +1,28 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
ERROR_DEFINITIONS,
HarborError,
normalizeHarborError,
} from '../../src/shared/errors.js';
test('every Harbor error code has stable Russian copy and retry policy', () => {
for (const [code, definition] of Object.entries(ERROR_DEFINITIONS)) {
const error = new HarborError(code);
assert.equal(error.code, code);
assert.equal(error.message, definition.message);
assert.equal(error.retryable, definition.retryable);
assert.match(error.message, /[А-Яа-яЁё]/);
assert.equal(typeof error.status, 'number');
}
});
test('unknown failures use the safe non-retryable fallback', () => {
const error = normalizeHarborError(new Error('secret internal failure'));
assert.equal(error.code, 'UNKNOWN');
assert.equal(error.message, ERROR_DEFINITIONS.UNKNOWN.message);
assert.equal(error.retryable, false);
assert.equal(error.message.includes('secret'), false);
});

View File

@@ -0,0 +1,188 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import {
applyGatewayPreference,
buildGatewayPresence,
createGatewayAutoState,
nextGatewayAutoState,
probeGatewayPresence,
readHostNetworkState,
verifyGatewayPresence,
} from '../../src/server/gatewayPresence.js';
import { createStateSnapshot } from '../../src/shared/contracts/state.js';
const subscriptionUrl = 'https://subscription.example/0123456789abcdef0123456789abcdef';
const nonce = '0123456789abcdef0123456789abcdef';
test('Gateway presence is authenticated by the shared subscription secret', async () => {
const payload = buildGatewayPresence({
appMode: 'gateway',
subscriptionUrl,
gatewayId: 'gateway-1',
nonce,
});
assert.equal(verifyGatewayPresence(payload, { subscriptionUrl, nonce }), true);
assert.equal(verifyGatewayPresence(payload, {
subscriptionUrl: 'https://subscription.example/fedcba9876543210fedcba9876543210',
nonce,
}), false);
const result = await probeGatewayPresence({
gateway: '192.168.50.111',
subscriptionUrl,
port: 4567,
nonce,
fetchImpl: async (url) => {
assert.equal(
url,
`http://192.168.50.111:4567/api/gateway-presence?nonce=${nonce}`,
);
return { ok: true, json: async () => payload };
},
});
assert.equal(result.gatewayId, 'gateway-1');
assert.equal(result.uiOrigin, 'http://192.168.50.111:4567');
assert.equal(Number.isFinite(Date.parse(result.verifiedAt)), true);
assert.equal(buildGatewayPresence({
appMode: 'gateway',
subscriptionUrl: 'https://subscription.example/public-feed',
gatewayId: 'gateway-1',
nonce,
}).available, false);
assert.equal(buildGatewayPresence({
appMode: 'gateway',
subscriptionUrl: 'https://subscription.example/0123456789abcdef',
gatewayId: 'gateway-1',
nonce,
}).available, true);
const sharedPublicValue = 'https://public.example/sing-box-configuration-v1';
const firstUrl = `${subscriptionUrl}?redirect=${encodeURIComponent(sharedPublicValue)}`;
const secondUrl = `https://subscription.example/fedcba9876543210fedcba9876543210?redirect=${encodeURIComponent(sharedPublicValue)}`;
const firstPayload = buildGatewayPresence({
appMode: 'gateway',
subscriptionUrl: firstUrl,
gatewayId: 'gateway-1',
nonce,
});
assert.equal(verifyGatewayPresence(firstPayload, {
subscriptionUrl: secondUrl,
nonce,
}), false);
});
test('verified Gateway stays active through transient discovery failures', () => {
const now = Date.now();
const statePath = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'harbor-route-')), 'network.json');
fs.writeFileSync(statePath, JSON.stringify({
gateway: '192.168.50.111',
interface: 'en0',
mac: 'aa:bb:cc:dd:ee:ff',
observedAt: new Date(now).toISOString(),
}));
const network = readHostNetworkState(statePath, { now });
assert.equal(network.gateway, '192.168.50.111');
let state = nextGatewayAutoState(createGatewayAutoState(), {
network,
verifiedGateway: {
gatewayId: 'gateway-1',
uiOrigin: 'http://192.168.50.111:4567',
verifiedAt: new Date(now).toISOString(),
},
});
assert.equal(state.mode, 'gateway-direct');
assert.equal(state.uiOrigin, 'http://192.168.50.111:4567');
assert.equal(state.lastVerifiedAt, new Date(now).toISOString());
state = nextGatewayAutoState(state, { network });
state = nextGatewayAutoState(state, { network });
assert.equal(state.mode, 'gateway-direct');
state = nextGatewayAutoState(state, { network });
assert.equal(state.mode, 'gateway-direct');
assert.equal(state.gatewayId, 'gateway-1');
assert.equal(state.failures, 3);
state = nextGatewayAutoState(state, {
network: null,
error: 'host snapshot stale',
});
assert.equal(state.mode, 'gateway-direct');
assert.equal(state.gatewayId, 'gateway-1');
assert.equal(state.lastError, 'host snapshot stale');
assert.equal(applyGatewayPreference(state, false).mode, 'local-vpn');
const newNetwork = { ...network, mac: '11:22:33:44:55:66' };
state = nextGatewayAutoState(state, { network: newNetwork });
assert.equal(state.mode, 'local-vpn');
assert.equal(state.gatewayId, '');
assert.equal(readHostNetworkState(statePath, { now: now + 16_000 }), null);
fs.writeFileSync(statePath, JSON.stringify({
gateway: '192.168.50.111',
interface: 'en0',
mac: '',
observedAt: new Date(now).toISOString(),
}));
assert.equal(readHostNetworkState(statePath, { now }), null);
});
test('canonical route distinguishes fresh, stale, lost, disabled and local states', () => {
const storedState = {
revision: 1,
subscriptionUrl,
gatewayAutoEnabled: true,
};
const snapshot = (gatewayAuto, stored = storedState) => createStateSnapshot({
storedState: stored,
runtime: { running: true },
gatewayAuto,
appMode: 'client',
configExists: true,
subscriptionHost: 'subscription.example/…',
now: new Date('2026-07-13T12:00:00.000Z'),
}).route;
const fresh = {
...createGatewayAutoState(),
mode: 'gateway-direct',
gateway: { gateway: '192.168.50.111' },
gatewayId: 'gateway-1',
uiOrigin: 'http://192.168.50.111:4567',
lastVerifiedAt: '2026-07-13T11:59:59.000Z',
};
const found = snapshot(fresh);
assert.equal(found.mode, 'gateway-direct');
assert.equal(found.reason, 'gateway-found');
assert.equal(found.gatewayAddress, '192.168.50.111');
assert.equal(found.gatewayUiOrigin, 'http://192.168.50.111:4567');
assert.equal(found.lastVerifiedAt, '2026-07-13T11:59:59.000Z');
assert.equal(found.autoEnabled, true);
assert.equal(found.fallbackPreference, 'local-vpn');
assert.equal(snapshot({ ...fresh, failures: 1 }).reason, 'gateway-stale');
assert.equal(snapshot({ ...fresh, mode: 'local-vpn', gatewayId: '', lastError: 'lost' }).reason, 'gateway-lost');
assert.equal(snapshot(fresh, { ...storedState, gatewayAutoEnabled: false }).reason, 'disabled');
assert.equal(snapshot(createGatewayAutoState()).reason, 'local');
});
test('client can ignore and restore a verified Gateway without losing discovery', () => {
const detected = {
...createGatewayAutoState(),
mode: 'gateway-direct',
gatewayId: 'gateway-1',
};
const ignored = applyGatewayPreference(detected, false);
assert.equal(ignored.mode, 'local-vpn');
assert.equal(ignored.gatewayId, 'gateway-1');
assert.equal(applyGatewayPreference(ignored, true).mode, 'gateway-direct');
assert.equal(applyGatewayPreference(createGatewayAutoState(), true).mode, 'local-vpn');
});

View File

@@ -0,0 +1,28 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { setGatewayInterception } from '../../src/server/gatewayRouting.js';
test('gateway switches only the TProxy PREROUTING jump', () => {
const calls = [];
const missing = (command, args) => {
calls.push([command, args]);
return { status: args.includes('-C') ? 1 : 0, stderr: '' };
};
setGatewayInterception(true, 'VPN_PROXY_TPROXY', missing);
assert.deepEqual(calls.map(([, args]) => args), [
['-w', '-t', 'mangle', '-C', 'PREROUTING', '-j', 'VPN_PROXY_TPROXY'],
['-w', '-t', 'mangle', '-I', 'PREROUTING', '1', '-j', 'VPN_PROXY_TPROXY'],
]);
calls.length = 0;
const existing = (command, args) => {
calls.push([command, args]);
return { status: 0, stderr: '' };
};
setGatewayInterception(false, 'VPN_PROXY_TPROXY', existing);
assert.deepEqual(calls.map(([, args]) => args), [
['-w', '-t', 'mangle', '-C', 'PREROUTING', '-j', 'VPN_PROXY_TPROXY'],
['-w', '-t', 'mangle', '-D', 'PREROUTING', '-j', 'VPN_PROXY_TPROXY'],
]);
});

View File

@@ -0,0 +1,26 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { checkServerHealth } from '../../src/server/serverHealth.js';
test('server health checks cap count and concurrency', async () => {
const servers = Array.from({ length: 300 }, (_, index) => ({
id: `srv-${index}`,
label: `Server ${index}`,
host: `server-${index}.example`,
port: 443,
}));
let active = 0;
let peak = 0;
const results = await checkServerHealth(servers, async () => {
active += 1;
peak = Math.max(peak, active);
await new Promise((resolve) => setImmediate(resolve));
active -= 1;
return { ok: true, latency: 1 };
});
assert.equal(results.length, 30);
assert.equal(peak, 4);
assert.deepEqual(results.map(({ id }) => id), servers.slice(0, 30).map(({ id }) => id));
});

View File

@@ -3,7 +3,6 @@ import test from "node:test";
const {
buildSharedProxyInfo,
checkSharedProxyGateway,
} = await import("../../src/server/sharedProxy.js");
test("gateway shared proxy info exposes host and socks proxy when running", () => {
@@ -23,33 +22,3 @@ test("gateway shared proxy info exposes host and socks proxy when running", () =
socksUrl: "socks5://192.168.50.111:8080",
});
});
test("client shared proxy check normalizes gateway response into settings patch", async () => {
const patch = await checkSharedProxyGateway(
"http://192.168.50.111:3456",
async (url) => {
assert.equal(url, "http://192.168.50.111:3456/api/shared-proxy");
return {
ok: true,
status: 200,
json: async () => ({
success: true,
available: true,
proxy: {
host: "192.168.50.111",
port: 8080,
protocol: "socks5",
},
}),
};
},
);
assert.equal(patch.sharedProxyEnabled, true);
assert.equal(patch.sharedProxyControlUrl, "http://192.168.50.111:3456");
assert.deepEqual(patch.sharedProxy, {
host: "192.168.50.111",
port: 8080,
protocol: "socks5",
});
});

View File

@@ -21,14 +21,36 @@ const subscriptionConfig = {
}],
};
test('client exposes one local proxy and routes it through the selected VPN', () => {
const config = buildGatewayConfig(subscriptionConfig, 'test-vpn');
test('client exposes one local proxy and routes local exceptions before the selected VPN', () => {
const config = buildGatewayConfig(subscriptionConfig, 'test-vpn', {
routeRules: [
{ type: 'domain_suffix', value: 'ru', enabled: true },
{ type: 'domain', value: 'example.com', enabled: true },
{ type: 'domain_keyword', value: 'cdn', enabled: false },
],
});
assert.deepEqual(config.inbounds.map((inbound) => inbound.tag), ['mixed-in']);
assert.equal(config.inbounds[0].listen_port, 8082);
assert.deepEqual(config.route.rules, [
{ domain_suffix: ['ru'], outbound: 'direct' },
{ domain: ['example.com'], outbound: 'direct' },
{ inbound: ['mixed-in'], outbound: 'test-vpn' },
]);
assert.equal(config.route.final, 'test-vpn');
assert.equal(config.route.auto_detect_interface, undefined);
});
test('client keeps its local proxy but routes directly when Harbor Gateway is ahead', () => {
const config = buildGatewayConfig(subscriptionConfig, 'test-vpn', {
clientDirect: true,
routeRules: [{ type: 'domain_suffix', value: 'ru', enabled: true }],
});
assert.deepEqual(config.route.rules, [
{ domain_suffix: ['ru'], outbound: 'direct' },
{ inbound: ['mixed-in'], outbound: 'direct' },
]);
assert.equal(config.route.final, 'direct');
assert.deepEqual(config.outbounds.map((outbound) => outbound.tag), ['direct', 'block']);
});

View File

@@ -21,11 +21,14 @@ const subscriptionConfig = {
}],
};
test('gateway routes transparent and proxy traffic only through the selected VPN', () => {
const config = buildGatewayConfig(subscriptionConfig, 'test-vpn');
test('gateway routes .ru domains directly and other traffic through the selected VPN', () => {
const config = buildGatewayConfig(subscriptionConfig, 'test-vpn', {
routeRules: [{ type: 'domain_suffix', value: 'ru', enabled: true }],
});
assert.deepEqual(config.route.rule_set, []);
assert.deepEqual(config.route.rules, [
{ domain_suffix: ['ru'], outbound: 'direct' },
{ inbound: ['tproxy-in'], outbound: 'test-vpn' },
{ inbound: ['mixed-in'], outbound: 'test-vpn' },
]);

View File

@@ -0,0 +1,51 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { createSingboxRuntime } from '../../src/server/singboxRuntime.js';
async function waitForStarts(filePath, count) {
for (let attempt = 0; attempt < 100; attempt += 1) {
if (fs.existsSync(filePath) && fs.readFileSync(filePath, 'utf8').length >= count) return;
await new Promise((resolve) => setTimeout(resolve, 10));
}
throw new Error(`sing-box did not start ${count} time(s)`);
}
test('dataplane keeps sing-box running when the applied config is unchanged', async (t) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'harbor-dataplane-'));
const binDir = path.join(dir, 'bin');
const configPath = path.join(dir, 'config.json');
const startsPath = path.join(dir, 'starts');
fs.mkdirSync(binDir);
fs.writeFileSync(configPath, '{}');
fs.writeFileSync(path.join(binDir, 'sing-box'), `#!/usr/bin/env node
if (process.argv[2] === 'check') process.exit(0);
require('node:fs').appendFileSync(process.env.SINGBOX_TEST_STARTS, 'x');
process.on('SIGTERM', () => process.exit(0));
setInterval(() => {}, 60_000);
`);
fs.chmodSync(path.join(binDir, 'sing-box'), 0o755);
const previousPath = process.env.PATH;
process.env.PATH = `${binDir}:${previousPath}`;
process.env.SINGBOX_TEST_STARTS = startsPath;
const runtime = createSingboxRuntime({ configPath });
t.after(async () => {
await runtime.stop();
process.env.PATH = previousPath;
delete process.env.SINGBOX_TEST_STARTS;
fs.rmSync(dir, { recursive: true, force: true });
});
await runtime.apply();
await waitForStarts(startsPath, 1);
await runtime.apply();
assert.equal(fs.readFileSync(startsPath, 'utf8'), 'x');
fs.writeFileSync(configPath, '{"changed":true}');
await runtime.apply();
await waitForStarts(startsPath, 2);
assert.equal(fs.readFileSync(startsPath, 'utf8'), 'xx');
});

View File

@@ -0,0 +1,543 @@
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import {
assertStateSnapshot,
createStateSnapshot,
normalizeStoredState,
} from '../../src/shared/contracts/state.js';
import { createServerId } from '../../src/shared/serverIdentity.js';
import { HARBOR_VERSIONS } from '../../src/shared/versions.js';
const root = path.resolve(import.meta.dirname, '../..');
function listen(server) {
return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server.address().port)));
}
function close(server) {
return new Promise((resolve) => server.close(resolve));
}
async function freePort() {
const server = http.createServer();
const port = await listen(server);
await close(server);
return port;
}
async function rawRequest(port, pathname, method = 'GET', body) {
const response = await fetch(`http://127.0.0.1:${port}${pathname}`, {
method,
headers: { 'content-type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
const payload = await response.json();
return { response, payload };
}
async function request(port, pathname, method = 'GET', body) {
const { response, payload } = await rawRequest(port, pathname, method, body);
assert.equal(response.ok, true, JSON.stringify(payload));
return payload;
}
async function waitForState(port, child, stderr) {
for (let attempt = 0; attempt < 100; attempt += 1) {
if (child.exitCode !== null) throw new Error(`Harbor exited early: ${stderr()}`);
try {
return await request(port, '/api/state');
} catch {
await new Promise((resolve) => setTimeout(resolve, 20));
}
}
throw new Error(`Harbor did not start: ${stderr()}`);
}
test('state v1 normalizes legacy storage and validates the canonical snapshot', () => {
const legacyServer = { tag: ' legacy ', type: 'vless', server: 'vpn.example', server_port: 443 };
const legacyServerId = createServerId(legacyServer);
const stored = normalizeStoredState({
subscriptionUrl: 'https://provider.example/subscription/test',
selectedTag: ' legacy ',
servers: [legacyServer],
});
const snapshot = createStateSnapshot({
storedState: stored,
runtime: { running: true, startedAt: '2026-07-11T10:00:00.000Z' },
gatewayAuto: null,
appMode: 'gateway',
configExists: true,
subscriptionHost: 'provider.example/…',
now: new Date('2026-07-11T12:00:00.000Z'),
});
assert.equal(snapshot.apiVersion, 1);
assert.deepEqual(snapshot.selection, {
desiredServerId: legacyServerId,
appliedServerId: legacyServerId,
});
assert.equal(snapshot.connection.process, 'running');
assert.equal(JSON.stringify(snapshot).includes(stored.subscriptionUrl), false);
assert.throws(
() => assertStateSnapshot({ ...snapshot, revision: -1 }),
/Invalid Harbor state snapshot v1/,
);
});
test('startup discards a rejected cached subscription and returns to first-run', async (t) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'harbor-rejected-cache-'));
const port = await freePort();
const subscriptionUrl = 'https://provider.example/disabled';
const rejectedServer = {
type: 'vless',
tag: '🚫 Subscription disabled',
server: '0.0.0.0',
server_port: 1,
};
const routeRules = [{ type: 'domain_suffix', value: 'example.org', enabled: true }];
fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify({
subscriptionUrl,
selectedTag: rejectedServer.tag,
servers: [rejectedServer],
routeRules,
}));
fs.writeFileSync(path.join(dir, 'subscription-cache.json'), JSON.stringify({
url: subscriptionUrl,
config: { outbounds: [rejectedServer] },
}));
fs.writeFileSync(path.join(dir, 'sing-box-config.json'), '{}');
const child = spawn(process.execPath, ['src/server/index.js'], {
cwd: root,
env: {
...process.env,
APP_MODE: 'client',
DATA_DIR: dir,
PORT: String(port),
HARBOR_HOST_NETWORK_STATE: path.join(dir, 'missing-network.json'),
},
stdio: ['ignore', 'ignore', 'pipe'],
});
let stderr = '';
child.stderr.on('data', (chunk) => { stderr += chunk; });
t.after(async () => {
child.kill('SIGTERM');
if (child.exitCode === null) await new Promise((resolve) => child.once('exit', resolve));
fs.rmSync(dir, { recursive: true, force: true });
});
const state = await waitForState(port, child, () => stderr);
assert.equal(state.subscription.status, 'missing');
assert.equal(state.hasSubscription, false);
assert.deepEqual(state.servers, []);
assert.ok(state.route.localRules.some((rule) => (
rule.type === 'domain_suffix' && rule.value === 'example.org' && rule.enabled
)));
assert.equal(fs.existsSync(path.join(dir, 'subscription-cache.json')), false);
assert.equal(fs.existsSync(path.join(dir, 'sing-box-config.json')), false);
assert.equal(child.exitCode, null);
});
test('data invariant: API mutations return one snapshot, increase revision and roll back subscription failures', async (t) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'harbor-state-contract-'));
const binDir = path.join(dir, 'bin');
const config = {
outbounds: [{
type: 'vless',
tag: 'test-vpn',
server: 'vpn.example.test',
server_port: 443,
uuid: '00000000-0000-4000-8000-000000000000',
tls: { enabled: true },
}],
};
const testServerId = createServerId(config.outbounds[0]);
fs.mkdirSync(binDir);
const singboxPath = path.join(binDir, 'sing-box');
const workingSingbox = `#!/usr/bin/env node
if (process.argv[2] === 'check') process.exit(0);
if (process.argv[2] === 'version') {
console.log('sing-box version 1.12.13');
process.exit(0);
}
process.on('SIGTERM', () => process.exit(0));
setInterval(() => {}, 60_000);
`;
fs.writeFileSync(singboxPath, workingSingbox);
fs.chmodSync(singboxPath, 0o755);
let providerFetchCount = 0;
let delayedPath = '';
let invalidNextPath = '';
let trafficExhaustedNextPath = '';
let delayedRequestStarted = null;
let releaseDelayedRequest = null;
const subscriptionServer = http.createServer(async (req, res) => {
providerFetchCount += 1;
if (req.url === '/timeout') return;
if (req.url === '/unavailable') {
res.writeHead(503);
return res.end('unavailable');
}
if (req.url === '/invalid') {
res.writeHead(200, { 'content-type': 'text/plain' });
return res.end('not a subscription');
}
if (req.url === '/traffic' || req.url === trafficExhaustedNextPath) {
trafficExhaustedNextPath = '';
res.writeHead(200, {
'content-type': 'application/json',
'subscription-userinfo': 'upload=60; download=40; total=100; expire=4102444800',
});
return res.end(JSON.stringify({
outbounds: [{
type: 'vless',
tag: 'Account unavailable',
server: '0.0.0.0',
server_port: 1,
}],
}));
}
if (req.url === '/expired') {
res.writeHead(200, {
'content-type': 'application/json',
'subscription-userinfo': 'upload=10; download=20; total=100; expire=1',
});
return res.end(JSON.stringify(config));
}
if (req.url === '/disabled') {
res.writeHead(200, {
'content-type': 'application/json',
'subscription-userinfo': 'upload=0; download=0; total=100; expire=4102444800',
});
return res.end(JSON.stringify({
outbounds: [{
type: 'vless',
tag: '🚫 Subscription disabled',
server: '0.0.0.0',
server_port: 1,
}],
}));
}
if (req.url === invalidNextPath) {
invalidNextPath = '';
res.writeHead(200, { 'content-type': 'text/plain' });
return res.end('not a subscription');
}
if (req.url === delayedPath) {
delayedRequestStarted?.();
await new Promise((resolve) => { releaseDelayedRequest = resolve; });
delayedPath = '';
}
res.writeHead(200, {
'content-type': 'application/json',
'subscription-userinfo': 'upload=10; download=20; total=100',
});
res.end(JSON.stringify(config));
});
const subscriptionPort = await listen(subscriptionServer);
const subscriptionUrl = `http://127.0.0.1:${subscriptionPort}/subscription/test`;
fs.writeFileSync(path.join(dir, 'state.json'), JSON.stringify({
subscriptionUrl,
selectedTag: 'test-vpn',
servers: [{ tag: 'test-vpn', type: 'vless', server: 'vpn.example.test', server_port: 443 }],
}));
fs.writeFileSync(path.join(dir, 'subscription-cache.json'), JSON.stringify({
url: subscriptionUrl,
config,
}));
const port = await freePort();
const child = spawn(process.execPath, ['src/server/index.js'], {
cwd: root,
env: {
...process.env,
APP_MODE: 'client',
DATA_DIR: dir,
PORT: String(port),
PATH: `${binDir}:${process.env.PATH}`,
HARBOR_HOST_NETWORK_STATE: path.join(dir, 'missing-network.json'),
SUBSCRIPTION_TIMEOUT_MS: '50',
},
stdio: ['ignore', 'ignore', 'pipe'],
});
let stderr = '';
child.stderr.on('data', (chunk) => { stderr += chunk; });
t.after(async () => {
child.kill('SIGTERM');
if (child.exitCode === null) await new Promise((resolve) => child.once('exit', resolve));
await close(subscriptionServer);
fs.rmSync(dir, { recursive: true, force: true });
});
const initial = await waitForState(port, child, () => stderr);
const version = await request(port, '/api/version');
assert.deepEqual(version, {
apiVersion: 1,
location: 'mac',
components: { macClient: HARBOR_VERSIONS.macClient },
runtime: { singBox: '1.12.13' },
});
assertStateSnapshot(initial);
assert.equal(initial.selection.appliedServerId, testServerId);
assert.deepEqual(initial.route.localRules, [
{ type: 'domain_suffix', value: 'ru', enabled: true },
]);
assert.deepEqual(initial.route.activeLocalRules, initial.route.localRules);
assert.equal(initial.route.localRulesRevision, 0);
assert.equal(initial.route.localRulesPendingRestart, false);
assert.equal(JSON.stringify(initial).includes(subscriptionUrl), false);
const stateKeys = Object.keys(initial).sort();
let revision = initial.revision;
let rulesRevision = initial.route.localRulesRevision;
const invalidSubscription = await rawRequest(
port,
'/api/subscription/validate',
'POST',
{ url: 'not-a-url' },
);
assert.equal(invalidSubscription.response.status, 400);
assert.deepEqual(
{
code: invalidSubscription.payload.error.code,
retryable: invalidSubscription.payload.error.retryable,
},
{ code: 'SUBSCRIPTION_INVALID', retryable: false },
);
assert.equal(typeof invalidSubscription.payload.error.correlationId, 'string');
const providerUnavailable = await rawRequest(
port,
'/api/subscription/validate',
'POST',
{ url: `http://127.0.0.1:${subscriptionPort}/unavailable` },
);
assert.equal(providerUnavailable.response.status, 502);
assert.equal(providerUnavailable.payload.error.code, 'PROVIDER_UNAVAILABLE');
assert.equal(providerUnavailable.payload.error.retryable, true);
const preservedSubscription = {
state: JSON.parse(fs.readFileSync(path.join(dir, 'state.json'), 'utf8')),
cache: fs.readFileSync(path.join(dir, 'subscription-cache.json'), 'utf8'),
config: fs.readFileSync(path.join(dir, 'sing-box-config.json'), 'utf8'),
};
for (const [pathname, expectedCode] of [
['/timeout', 'PROVIDER_UNAVAILABLE'],
['/invalid', 'SUBSCRIPTION_INVALID'],
['/expired', 'SUBSCRIPTION_EXPIRED'],
['/traffic', 'SUBSCRIPTION_TRAFFIC_EXHAUSTED'],
['/disabled', 'SUBSCRIPTION_DISABLED'],
]) {
const failedImport = await rawRequest(
port,
'/api/subscription/fetch',
'POST',
{ url: `http://127.0.0.1:${subscriptionPort}${pathname}` },
);
assert.equal(failedImport.payload.error.code, expectedCode);
const storedAfterFailure = JSON.parse(fs.readFileSync(path.join(dir, 'state.json'), 'utf8'));
assert.equal(storedAfterFailure.subscriptionUrl, preservedSubscription.state.subscriptionUrl);
assert.equal(storedAfterFailure.selectedTag, preservedSubscription.state.selectedTag);
assert.deepEqual(storedAfterFailure.servers, preservedSubscription.state.servers);
assert.equal(
fs.readFileSync(path.join(dir, 'subscription-cache.json'), 'utf8'),
preservedSubscription.cache,
);
assert.equal(
fs.readFileSync(path.join(dir, 'sing-box-config.json'), 'utf8'),
preservedSubscription.config,
);
}
trafficExhaustedNextPath = '/subscription/test';
const exhaustedRefresh = await rawRequest(port, '/api/subscription/refresh', 'POST');
assert.equal(exhaustedRefresh.response.status, 400);
assert.equal(exhaustedRefresh.payload.error.code, 'SUBSCRIPTION_TRAFFIC_EXHAUSTED');
const stateAfterExhaustedRefresh = await request(port, '/api/state');
assert.equal(stateAfterExhaustedRefresh.hasSubscription, true);
assert.equal(fs.readFileSync(path.join(dir, 'subscription-cache.json'), 'utf8'), preservedSubscription.cache);
assert.equal(fs.readFileSync(path.join(dir, 'sing-box-config.json'), 'utf8'), preservedSubscription.config);
revision = stateAfterExhaustedRefresh.revision;
const missingServer = await rawRequest(
port,
'/api/apply',
'POST',
{ selectedTag: 'missing-server' },
);
assert.equal(missingServer.response.status, 404);
assert.equal(missingServer.payload.error.code, 'SERVER_NOT_FOUND');
assert.equal((await request(port, '/api/state')).selection.desiredServerId, testServerId);
async function stateResponse(pathname, method = 'POST', body) {
const result = await request(port, pathname, method, body);
assert.deepEqual(Object.keys(result.state).sort(), stateKeys);
assertStateSnapshot(result.state);
return result;
}
async function mutation(pathname, method = 'POST', body) {
const result = await stateResponse(pathname, method, body);
assert.ok(result.state.revision > revision, `${pathname} did not increase revision`);
revision = result.state.revision;
return result;
}
const fetchesBeforeImport = providerFetchCount;
await mutation('/api/subscription/fetch', 'POST', { url: subscriptionUrl });
assert.equal(providerFetchCount, fetchesBeforeImport + 1);
assert.equal(
JSON.parse(fs.readFileSync(path.join(dir, 'subscription-cache.json'))).config.outbounds[0].tag,
'test-vpn',
);
const applied = await mutation('/api/apply', 'POST', { serverId: testServerId });
assert.deepEqual(applied.state.selection, {
desiredServerId: testServerId,
appliedServerId: testServerId,
});
assert.equal(applied.state.connection.process, 'running');
const cacheBeforeFailedRefresh = fs.readFileSync(path.join(dir, 'subscription-cache.json'), 'utf8');
const configBeforeFailedRefresh = fs.readFileSync(path.join(dir, 'sing-box-config.json'), 'utf8');
invalidNextPath = '/subscription/test';
const failedRefresh = await rawRequest(port, '/api/subscription/refresh', 'POST');
assert.equal(failedRefresh.response.status, 400);
assert.equal(failedRefresh.payload.error.code, 'SUBSCRIPTION_INVALID');
assert.equal(JSON.parse(fs.readFileSync(path.join(dir, 'state.json'), 'utf8')).selectedTag, 'test-vpn');
assert.equal(fs.readFileSync(path.join(dir, 'subscription-cache.json'), 'utf8'), cacheBeforeFailedRefresh);
assert.equal(fs.readFileSync(path.join(dir, 'sing-box-config.json'), 'utf8'), configBeforeFailedRefresh);
revision = (await request(port, '/api/state')).revision;
assert.equal((await mutation('/api/singbox/stop')).state.connection.desired, 'stopped');
assert.equal((await mutation('/api/singbox/restart')).state.connection.desired, 'running');
let routed = await mutation('/api/route-rules', 'PUT', {
expectedRulesRevision: rulesRevision,
rules: [
{ type: 'domain_suffix', value: 'ru', enabled: false },
{ type: 'domain', value: 'https://Example.com/private?q=1', enabled: true },
{ type: 'domain_suffix', value: '*.Example.org', enabled: true },
],
});
rulesRevision = routed.state.route.localRulesRevision;
assert.deepEqual(routed.state.route.localRules, [
{ type: 'domain_suffix', value: 'ru', enabled: false },
{ type: 'domain', value: 'example.com', enabled: true },
{ type: 'domain_suffix', value: 'example.org', enabled: true },
]);
assert.equal(routed.state.route.localRulesPendingRestart, false);
assert.deepEqual(routed.state.route.activeLocalRules, routed.state.route.localRules);
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir, 'sing-box-config.json'))).route.rules.slice(0, 3), [
{ domain: ['example.com'], outbound: 'direct' },
{ domain_suffix: ['example.org'], outbound: 'direct' },
{ inbound: ['mixed-in'], outbound: testServerId },
]);
await mutation('/api/singbox/stop');
routed = await mutation('/api/route-rules', 'PUT', {
expectedRulesRevision: rulesRevision,
rules: [
...routed.state.route.localRules,
{ type: 'domain_keyword', value: 'media', enabled: true },
],
});
rulesRevision = routed.state.route.localRulesRevision;
assert.equal(routed.state.connection.process, 'stopped');
assert.equal(routed.state.route.localRulesPendingRestart, true);
assert.deepEqual(routed.state.route.activeLocalRules, []);
const restartedRules = await mutation('/api/singbox/restart');
assert.equal(restartedRules.state.route.localRulesPendingRestart, false);
assert.deepEqual(restartedRules.state.route.activeLocalRules, routed.state.route.localRules);
const invalidRules = await rawRequest(port, '/api/route-rules', 'PUT', {
expectedRulesRevision: rulesRevision,
rules: [{ type: 'domain_regex', value: '.*' }],
});
assert.equal(invalidRules.response.status, 400);
assert.equal(invalidRules.payload.error.code, 'REQUEST_INVALID');
assert.equal((await request(port, '/api/state')).revision, revision);
const staleRules = await rawRequest(port, '/api/route-rules', 'PUT', {
expectedRulesRevision: 0,
rules: [],
});
assert.equal(staleRules.response.status, 409);
assert.equal(staleRules.payload.error.code, 'STATE_CONFLICT');
assert.deepEqual((await request(port, '/api/state')).route.localRules, routed.state.route.localRules);
const legacyNoop = await rawRequest(port, '/api/route-rules', 'PUT', {
expectedRevision: revision,
rules: routed.state.route.localRules,
});
assert.equal(legacyNoop.response.status, 200);
const workingConfig = fs.readFileSync(path.join(dir, 'sing-box-config.json'), 'utf8');
fs.writeFileSync(singboxPath, `#!/usr/bin/env node
const fs = require('node:fs');
if (process.argv[2] === 'check') {
const config = fs.readFileSync(process.argv[4], 'utf8');
process.exit(config.includes('broken.example') ? 1 : 0);
}
if (process.argv[2] === 'version') process.exit(0);
process.on('SIGTERM', () => process.exit(0));
setInterval(() => {}, 60_000);
`);
fs.chmodSync(singboxPath, 0o755);
const failedRules = await rawRequest(port, '/api/route-rules', 'PUT', {
expectedRulesRevision: rulesRevision,
rules: [{ type: 'domain', value: 'broken.example' }],
});
assert.equal(failedRules.response.status, 422);
assert.equal(failedRules.payload.error.code, 'CONFIG_INVALID');
const rolledBack = await request(port, '/api/state');
assert.deepEqual(rolledBack.route.localRules, routed.state.route.localRules);
assert.equal(rolledBack.connection.process, 'running');
assert.equal(fs.readFileSync(path.join(dir, 'sing-box-config.json'), 'utf8'), workingConfig);
revision = rolledBack.revision;
fs.writeFileSync(singboxPath, workingSingbox);
fs.chmodSync(singboxPath, 0o755);
fs.writeFileSync(singboxPath, `#!/usr/bin/env node
if (process.argv[2] === 'check') {
require('node:fs').unlinkSync(process.argv[1]);
process.exit(0);
}
`);
fs.chmodSync(singboxPath, 0o755);
const processFailure = await rawRequest(port, '/api/singbox/restart', 'POST');
assert.equal(processFailure.response.status, 503);
assert.equal(processFailure.payload.error.code, 'PROCESS_START_FAILED');
assert.equal(processFailure.payload.error.retryable, true);
fs.writeFileSync(singboxPath, workingSingbox);
fs.chmodSync(singboxPath, 0o755);
const delayedRequest = new Promise((resolve) => { delayedRequestStarted = resolve; });
delayedPath = '/subscription/test';
const staleRefresh = rawRequest(port, '/api/subscription/refresh', 'POST');
await delayedRequest;
const replacementUrl = `http://127.0.0.1:${subscriptionPort}/subscription/replacement`;
await mutation('/api/subscription/fetch', 'POST', { url: replacementUrl });
releaseDelayedRequest();
const staleRefreshResult = await staleRefresh;
assert.equal(staleRefreshResult.response.status, 409);
assert.equal(staleRefreshResult.payload.error.code, 'STATE_CONFLICT');
assert.equal(JSON.parse(fs.readFileSync(path.join(dir, 'state.json'), 'utf8')).subscriptionUrl, replacementUrl);
assert.equal(JSON.parse(fs.readFileSync(path.join(dir, 'subscription-cache.json'), 'utf8')).url, replacementUrl);
revision = (await request(port, '/api/state')).revision;
assert.equal((await mutation('/api/gateway-auto', 'POST', { enabled: false })).state.gatewayAuto.enabled, false);
const forgotten = await mutation('/api/subscription', 'DELETE');
assert.equal(forgotten.state.subscription.status, 'missing');
assert.equal(forgotten.state.servers.length, 0);
assert.deepEqual(forgotten.state.route.localRules, routed.state.route.localRules);
assert.deepEqual((await stateResponse('/api/servers/ping-all')).results, []);
const missingConfig = await rawRequest(port, '/api/singbox/restart', 'POST');
assert.equal(missingConfig.response.status, 422);
assert.equal(missingConfig.payload.error.code, 'CONFIG_INVALID');
assert.equal(missingConfig.payload.error.retryable, false);
});

View File

@@ -0,0 +1,108 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import {
atomicWriteJson,
createStateStore,
STATE_SCHEMA_VERSION,
} from '../../src/server/services/stateStore.js';
import { createServerId } from '../../src/shared/serverIdentity.js';
const fixture = (t) => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'harbor-state-store-'));
t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
return path.join(directory, 'state.json');
};
test('data invariant: failure before rename preserves the last successful file', (t) => {
const filePath = fixture(t);
atomicWriteJson(filePath, { revision: 1 });
assert.throws(
() => atomicWriteJson(filePath, { revision: 2 }, {
beforeRename: () => { throw new Error('injected failure'); },
}),
/injected failure/,
);
assert.deepEqual(JSON.parse(fs.readFileSync(filePath, 'utf8')), { revision: 1 });
assert.equal(
fs.readdirSync(path.dirname(filePath)).some((name) => name.endsWith('.tmp')),
false,
);
});
test('schema v2 state migrates built-in .ru into a normal enabled rule', (t) => {
const filePath = fixture(t);
const legacy = {
schemaVersion: 2,
revision: 7,
selectedTag: 'nl',
servers: [{ tag: 'nl', type: 'vless', server: 'nl.example', server_port: 443 }],
};
fs.writeFileSync(filePath, JSON.stringify(legacy));
const store = createStateStore(filePath, {
now: () => new Date('2026-07-11T12:00:00.000Z'),
});
const migrated = store.read();
assert.equal(migrated.schemaVersion, STATE_SCHEMA_VERSION);
assert.deepEqual(migrated.routeRules, [
{ type: 'domain_suffix', value: 'ru', enabled: true },
]);
assert.equal(migrated.appliedTag, 'nl');
assert.equal(migrated.selectedServerId, createServerId(legacy.servers[0]));
assert.equal(migrated.appliedServerId, migrated.selectedServerId);
assert.equal(store.migration.fromVersion, 2);
assert.deepEqual(JSON.parse(fs.readFileSync(store.migration.backupPath, 'utf8')), legacy);
assert.equal(JSON.parse(fs.readFileSync(filePath, 'utf8')).schemaVersion, STATE_SCHEMA_VERSION);
});
test('ambiguous legacy selectedTag explicitly requires a new choice', (t) => {
const filePath = fixture(t);
fs.writeFileSync(filePath, JSON.stringify({
schemaVersion: 3,
selectedTag: 'Amsterdam',
servers: [
{ tag: 'Amsterdam', type: 'vless', server: 'nl-1.example', server_port: 443 },
{ tag: 'Amsterdam', type: 'vless', server: 'nl-2.example', server_port: 443 },
],
}));
const migrated = createStateStore(filePath).read();
assert.equal(migrated.selectedServerId, '');
assert.equal(migrated.appliedServerId, '');
assert.equal(migrated.servers.length, 2);
});
test('data invariant: corrupt JSON preserves original bytes and returns explicit recovery state', (t) => {
const filePath = fixture(t);
fs.writeFileSync(filePath, '{broken');
const store = createStateStore(filePath, {
now: () => new Date('2026-07-11T12:00:00.000Z'),
});
const recovered = store.read();
assert.equal(recovered.schemaVersion, STATE_SCHEMA_VERSION);
assert.equal(recovered.revision, 0);
assert.equal(store.recovery.kind, 'corrupt-json');
assert.equal(fs.readFileSync(store.recovery.backupPath, 'utf8'), '{broken');
assert.equal(JSON.parse(fs.readFileSync(filePath, 'utf8')).schemaVersion, STATE_SCHEMA_VERSION);
});
test('concurrent updates are serialized without lost values', async (t) => {
const store = createStateStore(fixture(t));
store.read();
await Promise.all(Array.from({ length: 50 }, () => Promise.resolve().then(() => (
store.update((state) => ({ ...state, counter: (state.counter || 0) + 1 }))
))));
assert.equal(store.read().counter, 50);
assert.throws(() => store.update(async (state) => state), /must be synchronous/);
});

View File

@@ -1,12 +1,78 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { parseSubscriptionBody } from '../../src/server/subscription.js';
import {
parseSubscriptionBody,
selectRefreshedServer,
} from '../../src/server/subscription.js';
test('subscription server tags are trimmed for selection', () => {
const { servers } = parseSubscriptionBody(JSON.stringify({
outbounds: [{ type: 'vless', tag: 'de-frankfurt ', server: 'de.example', server_port: 443 }],
}));
assert.equal(servers[0].tag, 'de-frankfurt');
const parse = (outbounds) => parseSubscriptionBody(JSON.stringify({ outbounds }));
const outbound = (tag, server, server_port = 443) => ({
type: 'vless',
tag,
server,
server_port,
});
test('duplicate labels remain independently addressable by stable ID', () => {
const { config, servers } = parse([
outbound('Amsterdam', 'nl-1.example'),
outbound('Amsterdam', 'nl-2.example'),
]);
assert.equal(servers.length, 2);
assert.equal(servers[0].label, 'Amsterdam');
assert.equal(servers[1].label, 'Amsterdam');
assert.notEqual(servers[0].id, servers[1].id);
assert.deepEqual(config.outbounds.map((item) => item.tag), servers.map((server) => server.id));
});
test('provider reorder does not change server IDs or selection', () => {
const before = parse([outbound('DE', 'de.example'), outbound('NL', 'nl.example')]).servers;
const after = parse([outbound('NL', 'nl.example'), outbound('DE', 'de.example')]).servers;
const selectedId = before[1].id;
assert.deepEqual(
new Map(after.map((server) => [server.host, server.id])),
new Map(before.map((server) => [server.host, server.id])),
);
assert.equal(selectRefreshedServer(selectedId, before, after), selectedId);
});
test('cosmetic rename keeps selection for the same endpoint', () => {
const before = parse([outbound('Old name', 'nl.example')]).servers;
const after = parse([outbound('New name', 'nl.example')]).servers;
assert.equal(after[0].id, before[0].id);
assert.equal(selectRefreshedServer(before[0].id, before, after), before[0].id);
});
test('removed selected server requires an explicit new choice', () => {
const before = parse([outbound('DE', 'de.example'), outbound('NL', 'nl.example')]).servers;
const after = parse([outbound('DE', 'de.example')]).servers;
assert.equal(selectRefreshedServer(before[1].id, before, after), '');
assert.equal(selectRefreshedServer('', before, after), '');
});
test('provider placeholders never become selectable servers', () => {
const disabled = outbound('🚫 Subscription disabled', '0.0.0.0', 1);
const trafficExhausted = outbound('🚫 Traffic limit exceeded', '0.0.0.0', 1);
assert.throws(
() => parse([disabled]),
(error) => error.code === 'SUBSCRIPTION_DISABLED',
);
assert.throws(
() => parse([outbound('Account error', '::', 1)]),
(error) => error.code === 'SUBSCRIPTION_REJECTED',
);
assert.throws(
() => parse([trafficExhausted]),
(error) => error.code === 'SUBSCRIPTION_TRAFFIC_EXHAUSTED',
);
const parsed = parse([disabled, outbound('Amsterdam', 'nl.example')]);
assert.deepEqual(parsed.servers.map((server) => server.label), ['Amsterdam']);
assert.equal(parsed.config.outbounds.length, 1);
});

View File

@@ -0,0 +1,51 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { buildGatewayVersionInfo, buildVersionInfo } from '../../src/server/version.js';
import { HARBOR_VERSIONS, versionCompatibility } from '../../src/shared/versions.js';
test('component versions enforce one Harbor major and one Gateway major.minor', () => {
assert.deepEqual(versionCompatibility(HARBOR_VERSIONS), {
compatible: true,
major: true,
gateway: true,
});
assert.equal(versionCompatibility({
macClient: '1.9.4',
gatewayClient: '1.3.1',
gatewayBackend: '1.3.8',
}).compatible, true);
assert.equal(versionCompatibility({
macClient: '1.0.0',
gatewayClient: '1.3.0',
gatewayBackend: '1.4.0',
}).compatible, false);
});
test('gateway reports control backend and deployed dataplane separately', () => {
const control = {
apiVersion: 1,
location: 'gateway',
components: { gatewayBackend: '0.4.0' },
runtime: { singBox: '1.12.13' },
};
assert.deepEqual(buildGatewayVersionInfo(control, {
gatewayBackendVersion: '0.3.0',
singBoxVersion: '1.12.13',
}), {
apiVersion: 1,
location: 'gateway',
components: { gatewayBackend: '0.4.0' },
runtime: { dataplaneVersion: '0.3.0', singBox: '1.12.13' },
});
});
test('runtime version info reports the installed sing-box binary', () => {
const run = () => ({ stdout: 'sing-box version 1.12.13\n', stderr: '' });
assert.deepEqual(buildVersionInfo('gateway', run), {
apiVersion: 1,
location: 'gateway',
components: { gatewayBackend: HARBOR_VERSIONS.gatewayBackend },
runtime: { singBox: '1.12.13' },
});
});

View File

@@ -0,0 +1,32 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { canAppendRouteRule, normalizeRouteRules } from '../../src/shared/routingRules.js';
test('local route rules normalize URLs, suffixes and duplicates', () => {
assert.deepEqual(normalizeRouteRules([
{ type: 'domain', value: 'https://Example.com/news?id=1' },
{ type: 'domain_suffix', value: '*.Example.org' },
{ type: 'domain_keyword', value: ' CDN ' },
{ type: 'domain', value: 'example.com' },
{ type: 'domain_suffix', value: '.ru', enabled: false },
], { strict: true }), [
{ type: 'domain', value: 'example.com', enabled: true },
{ type: 'domain_suffix', value: 'example.org', enabled: true },
{ type: 'domain_keyword', value: 'cdn', enabled: true },
{ type: 'domain_suffix', value: 'ru', enabled: false },
]);
assert.equal(canAppendRouteRule([{ value: 'filled' }]), true);
assert.equal(canAppendRouteRule([{ value: '' }]), false);
});
test('invalid local route rules fail at the strict boundary', () => {
assert.throws(
() => normalizeRouteRules([{ type: 'domain_regex', value: '.*' }], { strict: true }),
/Invalid domain rule type/,
);
assert.throws(
() => normalizeRouteRules([{ type: 'domain_keyword', value: 'bad/path' }], { strict: true }),
/Invalid domain rule value/,
);
});

View File

@@ -0,0 +1,41 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { affectedComponents, bumpVersions } from '../scripts/harbor-version.mjs';
const versions = {
macClient: '2.4.3',
gatewayClient: '2.7.1',
gatewayBackend: '2.7.8',
};
test('version paths map to the components actually shipped by this repository', () => {
assert.deepEqual(affectedComponents(['src/web/App.jsx']), ['macClient', 'gatewayClient']);
assert.deepEqual(affectedComponents(['src/server/index.js']), ['macClient', 'gatewayBackend']);
assert.deepEqual(affectedComponents(['docker-compose.client.local.yml']), ['macClient']);
assert.deepEqual(affectedComponents(['install.sh']), ['macClient']);
assert.deepEqual(affectedComponents(['package-lock.json']), [
'macClient',
'gatewayClient',
'gatewayBackend',
]);
assert.deepEqual(affectedComponents(['README.md', 'test/server/version.test.js']), []);
});
test('version bumps follow ecosystem, linked-component and local scopes', () => {
assert.deepEqual(bumpVersions(versions, 'major'), {
macClient: '3.0.0',
gatewayClient: '3.0.0',
gatewayBackend: '3.0.0',
});
assert.deepEqual(bumpVersions(versions, 'minor', ['gateway-backend']), {
macClient: '2.4.3',
gatewayClient: '2.8.0',
gatewayBackend: '2.8.0',
});
assert.deepEqual(bumpVersions(versions, 'hotfix', ['mac']), {
macClient: '2.4.4',
gatewayClient: '2.7.1',
gatewayBackend: '2.7.8',
});
});

View File

@@ -0,0 +1,55 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
HarborApiError,
request,
} from '../../src/web/api.js';
const response = (status, error) => ({
ok: status >= 200 && status < 300,
status,
json: async () => ({ success: false, error }),
});
test('frontend exposes retry only for retryable structured errors', async () => {
await assert.rejects(
request('/api/test', {}, async () => response(502, {
code: 'PROVIDER_UNAVAILABLE',
message: 'untrusted server copy',
retryable: false,
correlationId: 'provider-reference',
})),
(error) => {
assert.ok(error instanceof HarborApiError);
assert.equal(error.message, 'Провайдер подписки временно недоступен.');
assert.equal(error.retryable, true);
assert.equal(error.correlationId, 'provider-reference');
return true;
},
);
await assert.rejects(
request('/api/test', {}, async () => response(400, {
code: 'SUBSCRIPTION_INVALID',
retryable: true,
})),
(error) => error.retryable === false,
);
});
test('network failures become retryable control errors', async () => {
await assert.rejects(
request('/api/state', {}, async () => { throw new TypeError('fetch failed'); }),
(error) => error.code === 'CONTROL_UNREACHABLE' && error.retryable === true,
);
});
test('local unknown errors get a safe message and diagnostic reference', () => {
const error = new HarborApiError({ code: 'NOT_A_REAL_CODE' });
assert.equal(error.code, 'UNKNOWN');
assert.equal(error.message, 'Не удалось выполнить действие.');
assert.equal(typeof error.correlationId, 'string');
assert.ok(error.correlationId.length >= 8);
});

View File

@@ -3,18 +3,22 @@ import test from 'node:test';
import {
connectionAction,
copyText,
formatConnectionDuration,
formatConnectionDurationWords,
isSubscriptionUrlValid,
localProxyUrls,
subscriptionDomain,
subscriptionDaysLeft,
subscriptionUsage,
} from '../../src/web/utils/clientControls.js';
import { instructionBlocks } from '../../src/web/instructions.js';
test('connection button chooses the only valid client action', () => {
assert.deepEqual(connectionAction({ connected: true }), { type: 'stop' });
assert.deepEqual(connectionAction({ selectedTag: 'nl-amsterdam' }), {
assert.deepEqual(connectionAction({ selectedServerId: 'srv_nl' }), {
type: 'apply',
selectedTag: 'nl-amsterdam',
serverId: 'srv_nl',
});
assert.deepEqual(connectionAction({ configExists: true }), { type: 'restart' });
assert.equal(connectionAction({}), null);
@@ -28,11 +32,26 @@ test('connection duration is derived from the backend start time', () => {
assert.equal(formatConnectionDuration(null, now), '00:00:00');
});
test('connection duration can be written with Russian units', () => {
const startedAt = '2026-07-10T10:00:00.000Z';
const now = Date.parse('2026-07-11T12:03:04.900Z');
assert.equal(formatConnectionDurationWords(startedAt, now), '1 день 2 часа 3 минуты 4 секунды');
assert.equal(formatConnectionDurationWords(null, now), '0 секунд');
});
test('saved subscription is reduced to its public domain', () => {
assert.equal(subscriptionDomain('sub.example.com/…'), 'sub.example.com');
assert.equal(subscriptionDomain(''), '');
});
test('subscription URL is validated locally by shape', () => {
assert.equal(isSubscriptionUrlValid(' https://sub.example/token '), true);
assert.equal(isSubscriptionUrlValid('http://127.0.0.1/subscription'), true);
assert.equal(isSubscriptionUrlValid('ftp://sub.example/token'), false);
assert.equal(isSubscriptionUrlValid('not-a-url'), false);
});
test('local proxy exposes both supported URLs', () => {
assert.deepEqual(localProxyUrls(18080), {
socks5: 'socks5://127.0.0.1:18080',
@@ -54,6 +73,26 @@ test('gateway proxy URLs use its network address', () => {
});
});
test('copy uses the synchronous native path available on gateway HTTP', async () => {
const textarea = {
style: {},
setAttribute() {},
select() { this.selected = true; },
remove() { this.removed = true; },
};
const documentRef = {
body: { append(node) { node.appended = true; } },
createElement: () => textarea,
execCommand: (command) => command === 'copy',
};
await copyText('192.168.50.111', { documentRef });
assert.equal(textarea.value, '192.168.50.111');
assert.equal(textarea.selected, true);
assert.equal(textarea.removed, true);
});
test('subscription usage combines traffic and caps progress', () => {
assert.deepEqual(subscriptionUsage({ upload: 30, download: 80, total: 100, expire: 2 }), {
upload: 30,
@@ -71,3 +110,12 @@ test('subscription expiry uses Russian day forms', () => {
assert.equal(subscriptionDaysLeft(new Date('2026-07-13T00:00:00Z'), now), 'осталось 2 дня');
assert.equal(subscriptionDaysLeft(new Date('2026-07-16T00:00:00Z'), now), 'осталось 5 дней');
});
test('gateway receives router instructions while local client does not', () => {
const gateway = instructionBlocks({ isGateway: true, host: '192.168.1.20', port: 8080 });
const client = instructionBlocks({ isGateway: false, host: '127.0.0.1', port: 8082 });
assert.equal(gateway.at(-1).id, 'router');
assert.equal(client.some((block) => block.id === 'router'), false);
assert.match(client.find((block) => block.id === 'vscode').code, /127\.0\.0\.1:8082/);
});

View File

@@ -0,0 +1,98 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
classifySyncError,
harborReducer,
initialHarborState,
} from '../../src/web/state/harborReducer.js';
const snapshot = (revision, desiredServerId = '', serverIds = ['one', 'two']) => ({
apiVersion: 1,
revision,
selection: { desiredServerId },
servers: serverIds.map((id) => ({ id })),
});
const receive = (state, value) => harborReducer(state, {
type: 'sync-succeeded',
snapshot: value,
receivedAt: `2026-07-11T12:00:0${value.revision}.000Z`,
});
function deferred() {
let resolve;
const promise = new Promise((done) => { resolve = done; });
return { promise, resolve };
}
test('data invariant: an older polling promise cannot replace a newer mutation snapshot', async () => {
let state = receive(initialHarborState, snapshot(1, 'one'));
const poll = deferred();
const mutation = deferred();
const apply = (promise) => promise.then((value) => { state = receive(state, value); });
const pollApplied = apply(poll.promise);
const mutationApplied = apply(mutation.promise);
mutation.resolve(snapshot(3, 'two'));
await mutationApplied;
poll.resolve(snapshot(2, 'one'));
await pollApplied;
assert.equal(state.snapshot.revision, 3);
assert.equal(state.snapshot.selection.desiredServerId, 'two');
});
test('an equal revision keeps the current snapshot identity', () => {
const state = receive(initialHarborState, snapshot(4, 'one'));
const next = receive(state, snapshot(4, 'two'));
assert.equal(next.snapshot, state.snapshot);
assert.equal(next.snapshot.selection.desiredServerId, 'one');
});
test('pending selection survives polling until canonical state acknowledges it', () => {
let state = receive(initialHarborState, snapshot(1, 'one'));
state = harborReducer(state, { type: 'select-server', serverId: 'two' });
state = receive(state, snapshot(2, 'one'));
assert.equal(state.pendingServerId, 'two');
state = receive(state, snapshot(3, 'two'));
assert.equal(state.pendingServerId, '');
});
test('pending selection is cleared when its server disappears', () => {
let state = receive(initialHarborState, snapshot(1, 'one'));
state = harborReducer(state, { type: 'select-server', serverId: 'two' });
assert.equal(receive(state, snapshot(2, 'one', ['one'])).pendingServerId, '');
});
test('data invariant: initial control outage is retryable without a fabricated snapshot', () => {
const serverError = Object.assign(new Error('Internal Server Error'), { status: 500 });
const refused = new TypeError('fetch failed');
assert.equal(classifySyncError(serverError), 'control-unreachable');
assert.equal(classifySyncError(refused), 'control-unreachable');
const failed = harborReducer(initialHarborState, { type: 'sync-failed', error: serverError });
assert.equal(failed.transport.bootStatus, 'control-unreachable');
assert.equal(failed.snapshot, null);
});
test('ready state becomes stale after three failures and recovers on success', () => {
const known = snapshot(1, 'one');
let state = receive(initialHarborState, known);
const error = new TypeError('fetch failed');
for (let attempt = 0; attempt < 3; attempt += 1) {
state = harborReducer(state, { type: 'sync-failed', error });
}
assert.equal(state.snapshot, known);
assert.equal(state.transport.stale, true);
assert.equal(state.transport.consecutiveFailures, 3);
state = receive(state, snapshot(2, 'two'));
assert.equal(state.transport.stale, false);
assert.equal(state.transport.consecutiveFailures, 0);
assert.equal(state.snapshot.selection.desiredServerId, 'two');
});

View File

@@ -0,0 +1,73 @@
import assert from 'node:assert/strict';
import http from 'node:http';
import test from 'node:test';
import {
createOperationRegistry,
OPERATION_CONFLICTS,
operationBlocked,
} from '../../src/web/state/operations.js';
const deferred = () => {
let resolve;
const promise = new Promise((done) => { resolve = done; });
return { promise, resolve };
};
test('operation conflicts block domain controls but leave copy and navigation alone', () => {
for (const [key, conflicts] of Object.entries(OPERATION_CONFLICTS)) {
for (const conflict of conflicts) {
assert.ok(OPERATION_CONFLICTS[conflict].includes(key), `${key} -> ${conflict} is not symmetric`);
}
}
const refreshing = { subscriptionRefresh: { status: 'running' } };
assert.equal(operationBlocked(refreshing, 'connection'), true);
assert.equal(operationBlocked(refreshing, 'serverApply'), true);
assert.equal(operationBlocked(refreshing, 'subscriptionDelete'), true);
assert.equal(operationBlocked(refreshing, 'copy'), false);
assert.equal(operationBlocked(refreshing, 'navigation'), false);
const applying = { serverApply: { status: 'running' } };
assert.equal(operationBlocked(applying, 'connection'), true);
assert.equal(operationBlocked(applying, 'subscriptionRefresh'), true);
assert.equal(operationBlocked(applying, 'copy'), false);
});
test('double click shares one in-flight request end to end', async (t) => {
let requests = 0;
const server = http.createServer((request, response) => {
requests += 1;
setTimeout(() => {
response.writeHead(200, { 'content-type': 'application/json' });
response.end('{"success":true}');
}, 20);
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
t.after(() => new Promise((resolve) => server.close(resolve)));
const registry = createOperationRegistry();
const action = () => fetch(`http://127.0.0.1:${server.address().port}/apply`).then((response) => response.json());
const first = registry.run('serverApply', action);
const second = registry.run('serverApply', action);
assert.equal(second, first);
assert.equal(registry.getSnapshot().serverApply.status, 'running');
assert.deepEqual(await first, { success: true });
assert.equal(requests, 1);
assert.deepEqual(registry.getSnapshot(), {});
});
test('a conflicting operation is rejected before its action starts', async () => {
const connection = deferred();
const registry = createOperationRegistry();
const running = registry.run('connection', () => connection.promise);
let applyCalls = 0;
const result = registry.run('serverApply', () => { applyCalls += 1; });
assert.equal(await result, false);
assert.equal(applyCalls, 0);
connection.resolve(true);
await running;
});

View File

@@ -0,0 +1,154 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
const root = path.resolve(import.meta.dirname, '../..');
const styles = fs.readFileSync(path.join(root, 'src/web/styles.css'), 'utf8');
const component = fs.readFileSync(path.join(root, 'src/web/components/ClientOverviewPage.jsx'), 'utf8');
function rule(selector, source = styles) {
const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return new RegExp(`^${escaped}\\s*\\{([\\s\\S]*?)\\n\\}`, 'm').exec(source)?.[1] || '';
}
test('desktop layout keeps the power control on a symmetric center axis', () => {
const panel = rule('.client-panel');
const power = rule('.client-power-section');
const form = rule('.client-form');
assert.match(panel, /grid-template-columns:\s*minmax\(0, 1fr\) minmax\(240px, 280px\) minmax\(0, 1fr\)/);
assert.match(power, /grid-column:\s*2/);
assert.match(form, /grid-column:\s*3/);
assert.match(form, /position:\s*static/);
assert.match(form, /overflow:\s*visible/);
assert.doesNotMatch(form, /\bleft\s*:|translateX|transition:[^;]*(?:left|width|transform)/);
assert.match(styles, /\.client-panel\.has-subscription \.client-form \{[\s\S]*height:\s*var\(--client-work-height\)/);
assert.match(rule('.client-form-content'), /align-content:\s*start/);
assert.match(styles, /--client-power-top:\s*calc\(\(var\(--client-work-height\) - 96px\) \/ 2\)/);
assert.match(styles, /\.client-panel\.has-subscription \{[\s\S]*transform:\s*translateY\(-9vh\)/);
assert.match(styles, /\.client-panel\.has-subscription \.client-power-section \{[\s\S]*height:\s*var\(--client-work-height\);[\s\S]*padding-top:\s*var\(--client-power-top\)/);
assert.match(styles, /\.client-panel\.has-subscription \.client-form-content \{[\s\S]*padding-top:\s*var\(--client-power-top\)/);
});
test('server rows scroll without moving the subscription column or showing a scrollbar', () => {
const scroll = rule('.client-server-scroll');
const simpleScroll = rule('.client-server-mode-panel.is-simple .client-server-scroll');
const grid = rule('.client-server-grid');
assert.match(scroll, /overflow-y:\s*auto/);
assert.match(scroll, /scrollbar-width:\s*none/);
assert.match(styles, /\.client-server-scroll::-webkit-scrollbar\s*\{[\s\S]*display:\s*none/);
assert.match(simpleScroll, /max-height:\s*none/);
assert.match(simpleScroll, /overflow:\s*visible/);
assert.match(grid, /width:\s*min\(100%, 220px\)/);
assert.match(rule('.client-form-content'), /gap:\s*24px/);
assert.match(rule('.client-server-toolbar-title'), /grid-column:\s*2/);
assert.match(rule('.client-server-mode-toggle'), /grid-row:\s*2/);
assert.match(rule('.client-server-check'), /grid-column:\s*3/);
assert.doesNotMatch(rule('.client-servers.is-scalable .client-server-grid'), /width:/);
});
test('tablet and mobile regions use normal flow with viewport-safe widths', () => {
const responsive = /@media \(max-width: 920px\) \{([\s\S]*?)\n\}\n\n@media \(max-width: 560px\)/.exec(styles)?.[1] || '';
const mobile = /@media \(max-width: 560px\) \{([\s\S]*?)\n\}\n\n@media \(prefers-reduced-motion/.exec(styles)?.[1] || '';
assert.match(responsive, /grid-template-columns:\s*minmax\(0, 1fr\)/);
assert.match(responsive, /\.client-power-section,[\s\S]*\.client-form,[\s\S]*grid-column:\s*1/);
assert.match(responsive, /width:\s*min\(100%, 380px\)/);
assert.match(responsive, /max-height:\s*none/);
assert.match(responsive, /overflow-y:\s*visible/);
assert.match(responsive, /\.harbor-brand,[\s\S]*position:\s*absolute/);
assert.match(responsive, /\.client-inline-error\.is-connection,[\s\S]*position:\s*static/);
assert.match(rule('.client-duration-toggle'), /width:\s*min\(290px, 100%\)/);
assert.match(mobile, /\.client-server-toolbar \{[\s\S]*grid-template-rows:\s*44px 44px/);
assert.match(mobile, /\.client-form-content \{[\s\S]*gap:\s*24px/);
assert.match(mobile, /\.client-server-check \{[\s\S]*width:\s*44px/);
assert.match(styles, /\.client-instructions\s*\{[\s\S]*width:\s*min\(470px, 100vw\)/);
assert.match(styles, /\.client-local-rules\s*\{[\s\S]*width:\s*min\(480px, 100vw\)/);
assert.match(styles, /\.client-confirmation-dialog\s*\{[\s\S]*width:\s*min\(430px, calc\(100vw - 48px\)\)/);
for (const viewport of [320, 390, 768]) {
const pagePadding = viewport <= 560 ? 28 : 48;
const panelPadding = 12;
const available = viewport - pagePadding - panelPadding;
assert.ok(Math.min(380, available) <= viewport, `form fits ${viewport}px viewport`);
assert.ok(Math.min(290, available) <= viewport, `duration control fits ${viewport}px viewport`);
}
const desktopOuterColumn = (1100 - 280) / 2;
assert.ok(Math.min(360, desktopOuterColumn) <= desktopOuterColumn, 'details fit the 1440px desktop grid');
});
test('secondary menus share one right rail and both drawers open from the right', () => {
const disabledRulesLabel = rule('.client-local-rules-toggle:disabled span');
assert.match(component, /<nav className="client-secondary-menu" aria-label="Дополнительные меню">/);
assert.match(component, /client-instructions-toggle[\s\S]*client-local-rules-toggle/);
assert.match(component, /Локальные правила недоступны: сейчас работают правила Gateway/);
assert.match(rule('.client-secondary-menu'), /right:\s*max\(14px, env\(safe-area-inset-right\)\)/);
assert.match(rule('.client-secondary-menu'), /display:\s*grid/);
assert.match(disabledRulesLabel, /opacity:\s*0/);
assert.match(disabledRulesLabel, /filter:\s*blur\(5px\)/);
assert.match(styles, /\.client-local-rules-toggle:disabled:hover span\s*\{[\s\S]*opacity:\s*1/);
assert.match(rule('.client-instructions'), /inset:\s*0 0 0 auto/);
assert.match(rule('.client-instructions'), /transform:\s*translateX\(104%\)/);
assert.match(rule('.client-local-rules'), /inset:\s*0 0 0 auto/);
assert.match(rule('.client-local-rules'), /transform:\s*translateX\(104%\)/);
});
test('duration and Gateway access keep stable geometry without tabs', () => {
assert.match(rule('.client-state-detail'), /min-height:\s*44px/);
assert.match(rule('.client-duration-toggle'), /min-height:\s*44px/);
assert.match(component, /client-duration-word-row is-calendar/);
assert.match(component, /client-duration-word-row is-clock/);
assert.match(rule('.client-duration-toggle > .client-tooltip'), /right:\s*calc\(100% \+ 12px\)/);
assert.match(component, /\['gateway', 'GATEWAY'\]/);
assert.match(component, /\['socks5', 'SOCKS5'\]/);
assert.match(component, /\['http', 'HTTP'\]/);
assert.doesNotMatch(component, /client-access-tabs|role="tab"|role="tabpanel"/);
assert.match(rule('.client-proxies.is-gateway'), /width:\s*270px/);
});
test('responsive motion has a reduced-motion fallback', () => {
const reducedMotion = /@media \(prefers-reduced-motion: reduce\) \{([\s\S]*)\n\}/.exec(styles)?.[1] || '';
assert.match(reducedMotion, /\.client-power-section/);
assert.match(reducedMotion, /\.client-form/);
assert.match(reducedMotion, /\.harbor-brand/);
assert.match(reducedMotion, /transition:\s*none/);
assert.match(reducedMotion, /animation:\s*none/);
});
test('tooltips stay opaque, above adjacent content, and do not stick after pointer clicks', () => {
const tooltip = rule('.client-tooltip');
assert.match(tooltip, /z-index:\s*1000/);
assert.match(tooltip, /background:\s*oklch\(0\.14 0\.012 145\)/);
assert.doesNotMatch(tooltip, /transparent|backdrop-filter/);
assert.match(styles, /\.client-power-section:has\(\.client-tooltip-anchor:hover\)[\s\S]*z-index:\s*90/);
assert.match(styles, /\.client-tooltip-anchor:focus-visible > \.client-tooltip/);
assert.match(styles, /\.client-tooltip-anchor:has\(> :focus-visible\) > \.client-tooltip/);
assert.doesNotMatch(styles, /\.client-tooltip-anchor:focus-within > \.client-tooltip/);
assert.match(rule('.harbor-version-tooltip'), /background:\s*oklch\(0\.14 0\.012 145\)/);
assert.match(rule('.harbor-mode-tooltip'), /background:\s*oklch\(0\.14 0\.012 145\)/);
});
test('subscription validation waits for the provider and keeps diagnostics below errors', () => {
assert.match(component, /api\.subscription\.validate\(normalizedSubscriptionUrl/);
assert.match(component, /status: 'checking'/);
assert.match(component, /status: 'valid'/);
assert.match(component, /message: ERROR_DEFINITIONS\.SUBSCRIPTION_INVALID\.message/);
assert.match(component, /subscriptionValidationStatus === 'checking' \? '…' : '×'/);
assert.match(component, /if \(error\?\.context === 'subscription'\) onDismissError\(\)/);
assert.match(component, /error\.retry[\s\S]*error\.correlationId/);
assert.match(rule('.client-inline-error.is-subscription small'), /flex-basis:\s*100%/);
assert.match(rule('.client-inline-error.is-subscription small'), /opacity:\s*0\.45/);
assert.match(styles, /@keyframes client-subscription-error-in[\s\S]*filter:\s*blur\(7px\)/);
assert.match(styles, /@keyframes client-subscription-code-in[\s\S]*transform:\s*translateY\(-2px\)/);
assert.match(
/@media \(prefers-reduced-motion: reduce\) \{([\s\S]*)\n\}/.exec(styles)?.[1] || '',
/\.client-inline-error\.is-subscription > \*/,
);
});

View File

@@ -0,0 +1,76 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
const root = path.resolve(import.meta.dirname, '../..');
const component = fs.readFileSync(path.join(root, 'src/web/components/ClientOverviewPage.jsx'), 'utf8');
const popup = fs.readFileSync(path.join(root, 'src/web/components/ConfirmationPopup.jsx'), 'utf8');
const styles = fs.readFileSync(path.join(root, 'src/web/styles.css'), 'utf8');
test('rule editor add latency stays constant and dirty exits are guarded', () => {
const rowRule = /\.client-local-rule \{([\s\S]*?)\n\}/.exec(styles)?.[1] || '';
assert.doesNotMatch(rowRule, /--rule-index|calc\(/);
assert.match(component, /addEventListener\('beforeunload', warnBeforeUnload\)/);
assert.match(component, /requestCloseLocalRules\(\)/);
assert.match(component, /localRulesPendingRestart/);
assert.match(component, /activeLocalRules/);
assert.match(component, /localRulesRevision/);
assert.match(component, /Не сохранено/);
assert.match(component, /if \(!runtimeActive\) return \['saved', 'Сохранено'\]/);
assert.match(component, /Ждёт перезапуска/);
assert.match(component, /Перезапустить VPN/);
assert.match(component, /const localRulesPendingRestart = connected && state\?\.route\?\.localRulesPendingRestart === true/);
assert.match(component, /if \(!connected \|\| !result\.state\.route\.localRulesPendingRestart\) setLocalRulesOpen\(false\)/);
assert.match(component, /client-deletable-row/);
assert.match(component, /className="client-delete-strike"[\s\S]*onAnimationEnd/);
assert.doesNotMatch(component, /client-rule-delete-cross/);
assert.match(component, /className="client-local-rule-delete"/);
assert.match(styles, /\.client-deletable-row\.is-removing > \.client-delete-strike[\s\S]*client-delete-strike/);
assert.match(styles, /\.client-delete-strike \{[\s\S]*z-index: 100[\s\S]*background: transparent/);
assert.match(styles, /\.client-deletable-row\.is-removing > :not\(\.client-delete-strike\)[\s\S]*z-index: 0/);
assert.match(styles, /clip-path: polygon\(0 24%, 100% 50%, 0 76%\)/);
assert.doesNotMatch(styles, /\.client-delete-strike::before/);
assert.doesNotMatch(styles, /client-local-rule > button:last-child/);
assert.match(styles, /@keyframes client-delete-strike[\s\S]*scaleX\(0\)[\s\S]*scaleX\(1\)/);
assert.match(styles, /53%[\s\S]*transform-origin: right center[\s\S]*100%[\s\S]*scaleX\(0\)/);
assert.match(styles, /@keyframes client-local-rule-leave[\s\S]*translateX\(28px\)/);
assert.match(styles, /@keyframes client-delete-content-dim[\s\S]*opacity: 0\.58[\s\S]*blur\(1\.4px\)[\s\S]*opacity: 0/);
assert.match(styles, /\.client-local-rule:has\(\.client-rule-type\.is-open\)[\s\S]*z-index: 5/);
});
test('critical confirmations share one accessible blocking popup', () => {
assert.match(component, /id="stop-connection"/);
assert.match(component, /id="discard-local-rules"/);
assert.match(component, /id="delete-subscription"/);
assert.doesNotMatch(component, /client-local-rules-discard|client-delete-confirmation/);
assert.match(popup, /role="alertdialog"/);
assert.match(popup, /aria-modal="true"/);
assert.match(popup, /querySelectorAll\(FOCUSABLE\)/);
assert.match(popup, /element\.inert = true/);
assert.match(popup, /requestAnimationFrame\(\(\) => cancelRef\.current\?\.focus\(\)\)/);
assert.match(styles, /\.client-confirmation-popup\.is-open[\s\S]*backdrop-filter: blur\(18px\)/);
});
test('power click and native Enter cannot stop VPN without a separate confirmation', () => {
assert.match(component, /className="client-power"[\s\S]*type="button"[\s\S]*onClick=\{toggleConnection\}/);
assert.match(component, /if \(action\?\.type === 'stop'\) \{[\s\S]*setConfirmingStop\(true\);[\s\S]*return;[\s\S]*\}/);
assert.doesNotMatch(component, /if \(action\?\.type === 'stop'\) return onStop\(\)/);
assert.match(component, /id="stop-connection"[\s\S]*cancelLabel="Оставить включённым"[\s\S]*confirmLabel="Отключить VPN"[\s\S]*onConfirm=\{stopConnection\}/);
});
test('copy feedback, drawers and Gateway access actions expose complete semantics', () => {
assert.match(component, /className="client-live-region" role="status" aria-live="polite" aria-atomic="true"/);
assert.match(component, /Не удалось скопировать/);
assert.match(component, /Скопировано/);
assert.doesNotMatch(component, />Error<|>Copied</);
assert.match(component, /aria-label="Закрыть инструкции"/);
assert.match(component, /aria-label="Закрыть локальные правила"/);
assert.match(component, /instructionsCloseRef\.current\?\.focus\(\)/);
assert.match(component, /localRulesCloseRef\.current\?\.focus\(\)/);
assert.match(component, /aria-label={`Скопировать \$\{label\}: \$\{kind === 'gateway' \? gatewayAddress : proxyUrls\[kind\]\}`}/);
assert.doesNotMatch(component, /client-access-tabs|role="tab"|role="tabpanel"/);
assert.match(styles, /\.client-drawer-close \{[\s\S]*width: 44px;[\s\S]*height: 44px/);
assert.match(styles, /@media \(max-width: 560px\)[\s\S]*\.client-copy-button \{[\s\S]*min-height: 44px/);
assert.match(styles, /@media \(max-width: 560px\)[\s\S]*\.client-local-rule-enabled,[\s\S]*\.client-local-rule-delete \{[\s\S]*width: 44px;[\s\S]*height: 44px/);
});

View File

@@ -0,0 +1,94 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import {
autoServer,
filterServers,
groupServers,
SERVER_RESULT_WINDOW,
} from '../../src/web/utils/serverPicker.js';
const root = path.resolve(import.meta.dirname, '../..');
const picker = fs.readFileSync(path.join(root, 'src/web/components/ServerPicker.jsx'), 'utf8');
const overview = fs.readFileSync(path.join(root, 'src/web/components/ClientOverviewPage.jsx'), 'utf8');
const styles = fs.readFileSync(path.join(root, 'src/web/styles.css'), 'utf8');
const fixtures = (count) => Array.from({ length: count }, (_, index) => ({
id: `srv-${String(count - index).padStart(3, '0')}`,
label: index < 2 ? 'Duplicate' : `Server ${index}`,
host: `node-${index}.example`,
country: index % 2 ? 'NL' : 'DE',
provider: index % 3 ? 'Harbor' : 'Other',
protocol: index % 2 ? 'vless' : 'trojan',
}));
test('server picker handles 1, 30 and 300 stable-ID servers with duplicate labels', () => {
for (const count of [1, 30, 300]) {
const servers = fixtures(count);
assert.equal(filterServers(servers, '').length, count);
assert.equal(new Set(servers.map(({ id }) => id)).size, count);
}
assert.equal(filterServers(fixtures(30), 'node-12.example')[0].id, 'srv-018');
assert.equal(filterServers(fixtures(30), 'trojan').length, 15);
assert.equal(groupServers(fixtures(30)).length, 2);
assert.equal(autoServer(fixtures(30)).id, 'srv-001');
assert.equal(SERVER_RESULT_WINDOW, 60);
});
test('server picker checks health only on manual refresh and bounds the result window', () => {
assert.doesNotMatch(overview, /pingAll|servers\.ping/);
assert.doesNotMatch(picker, /checkVisible\(\);/);
assert.match(picker, /onClick={checkVisible}/);
assert.match(picker, /\{ \.\.\.current\[id\], checking: true \}/);
assert.match(picker, /700 - \(performance\.now\(\) - startedAt\)/);
assert.match(picker, /\{ \.\.\.current\[id\], checking: false \}/);
assert.match(picker, /\.slice\(page \* SERVER_RESULT_WINDOW, \(page \+ 1\) \* SERVER_RESULT_WINDOW\)/);
assert.match(picker, /\.slice\(0, 30\)/);
assert.match(picker, /Math\.min\(index, 7\)/);
assert.match(picker, /type="search"/);
assert.match(picker, /harbor-server-favorites/);
assert.match(picker, /harbor-server-recent/);
assert.match(picker, /aria-expanded={!isCollapsed}/);
});
test('manual ping uses plain language and keeps results beside server names', () => {
assert.match(picker, /function ServerHealth/);
assert.match(picker, /<svg className="client-server-health-checking"/);
assert.doesNotMatch(picker, />Проверяем…<\/span>/);
assert.match(picker, /function ServerCheckButton/);
assert.match(picker, /client-server-check client-tooltip-anchor/);
assert.match(picker, /<span className="client-tooltip" role="tooltip">/);
assert.doesNotMatch(picker, /TCP|Не проверен/);
assert.match(picker, /<strong>\{server\.label\}<\/strong>[\s\S]*?<\/button>[\s\S]*?client-server-meta/);
assert.match(styles, /\.client-server-row \{[\s\S]*?grid-template-columns: minmax\(0, 1fr\) 120px minmax\(0, 1fr\);/);
assert.match(styles, /\.client-server-row \.client-server \{[\s\S]*?width: 120px;/);
assert.match(styles, /\.client-server-health \{[\s\S]*?font-size: 9px;[\s\S]*?font-variant-numeric: tabular-nums;/);
assert.match(styles, /\.client-server-meta \.client-server-health \{[\s\S]*?place-items: end start;[\s\S]*?padding-bottom: 7px;/);
assert.match(styles, /\.client-server-health\.is-checking \.client-server-health-checking \{[\s\S]*?animation: client-server-check-spin 700ms linear infinite;/);
assert.match(styles, /\.client-server-meta \{[\s\S]*?width: 42px;[\s\S]*?margin-left: 4px;/);
assert.match(styles, /\.client-server-favorite \{[\s\S]*?position: absolute;[\s\S]*?width: 44px;/);
assert.match(picker, /server={servers\[0\]}[\s\S]*?ping={pings\[servers\[0\]\.id\]}/);
assert.match(picker, /simpleServers\.map[\s\S]*?ping={pings\[server\.id\]}/);
});
test('server picker starts simple and reveals advanced controls on demand', () => {
assert.match(picker, /const \[advanced, setAdvanced\] = useState\(false\)/);
assert.match(picker, /aria-expanded={advanced}/);
assert.match(picker, /setAdvanced\(\(current\) => !current\)/);
assert.match(picker, /<span>Поиск и фильтры<\/span>/);
assert.match(picker, /client-server-toolbar-title">Список серверов/);
assert.doesNotMatch(picker, /client-server-toolbar-actions/);
assert.match(styles, /\.client-servers\.is-scalable \{[\s\S]*?width: min\(100%, 300px\);/);
assert.match(styles, /\.client-server-mode-toggle \{[\s\S]*?grid-row: 2;/);
assert.match(styles, /\.client-server-check \{[\s\S]*?grid-column: 3;[\s\S]*?grid-row: 1;/);
assert.match(styles, /\.client-server-auto \{[\s\S]*?width: 220px;[\s\S]*?margin-inline: auto;/);
assert.match(picker, /client-server-mode-panel is-simple/);
assert.match(picker, /client-server-mode-panel is-advanced/);
assert.match(picker, /inert={advanced \? true : undefined}/);
assert.match(picker, /inert={!advanced \? true : undefined}/);
assert.match(picker, /const SIMPLE_SERVER_LIMIT = 5/);
assert.match(picker, /\.slice\(0, SIMPLE_SERVER_LIMIT\)/);
assert.match(picker, /\{selected && <ServerRow/);
});