feat: Enhanced security, UI improvements, and animations (#432)

* fix: Remove empty catch blocks and add error logging

* refactor: Modularize server stats widget collectors

* feat: Add i18n support for terminal customization and login stats

- Add comprehensive terminal customization translations (60+ keys) for appearance, behavior, and advanced settings across all 4 languages
- Add SSH login statistics translations
- Update HostManagerEditor to use i18n for all terminal customization UI elements
- Update LoginStatsWidget to use i18n for all UI text
- Add missing logger imports in backend files for improved debugging

* feat: Add keyboard shortcut enhancements with Kbd component

- Add shadcn kbd component for displaying keyboard shortcuts
- Enhance file manager context menu to display shortcuts with Kbd component
- Add 5 new keyboard shortcuts to file manager:
  - Ctrl+D: Download selected files
  - Ctrl+N: Create new file
  - Ctrl+Shift+N: Create new folder
  - Ctrl+U: Upload files
  - Enter: Open/run selected file
- Add keyboard shortcut hints to command palette footer
- Create helper function to parse and render keyboard shortcuts

* feat: Add i18n support for command palette

- Add commandPalette translation section with 22 keys to all 4 languages
- Update CommandPalette component to use i18n for all UI text
- Translate search placeholder, group headings, menu items, and shortcut hints
- Support multilingual command palette interface

* feat: Add smooth transitions and animations to UI

- Add fade-in/fade-out transition to command palette (200ms)
- Add scale animation to command palette on open/close
- Add smooth popup animation to context menu (150ms)
- Add visual feedback for file selection with ring effect
- Add hover scale effect to file grid items
- Add transition-all to list view items for consistent behavior
- Zero JavaScript overhead, pure CSS transitions
- All animations under 200ms for instant feel

* feat: Add button active state and dashboard card animations

- Add active:scale-95 to all buttons for tactile click feedback
- Add hover border effect to dashboard cards (150ms transition)
- Add pulse animation to dashboard loading states
- Pure CSS transitions with zero JavaScript overhead
- Improves enterprise-level feel of UI

* feat: Add smooth macOS-style page transitions

- Add fullscreen crossfade transition for login/logout (300ms fade-out + 400ms fade-in)
- Add slide-in-from-right animation for all page switches (Dashboard, Terminal, SSH Manager, Admin, Profile)
- Fix TypeScript compilation by adding esModuleInterop to tsconfig.node.json
- Pass handleLogout from DesktopApp to LeftSidebar for consistent transition behavior

All page transitions now use Tailwind animate-in utilities with 300ms duration for smooth, native-feeling UX

* fix: Add key prop to force animation re-trigger on tab switch

Each page container now has key={currentTab} to ensure React unmounts and remounts the element on every tab switch, properly triggering the slide-in animation

* revert: Remove page transition animations

Page switching animations were not noticeable enough and felt unnecessary.
Keep only the login/logout fullscreen crossfade transitions which provide clear visual feedback for authentication state changes

* feat: Add ripple effect to login/logout transitions

Add three-layer expanding ripple animation during fadeOut phase:
- Ripples expand from screen center using primary theme color
- Each layer has staggered delay (0ms, 150ms, 300ms) for wave effect
- Ripples fade out as they expand to create elegant visual feedback
- Uses pure CSS keyframe animation, no external libraries

Total animation: 800ms ripple + 300ms screen fade

* feat: Add smooth TERMIX logo animation to transitions

Changes:
- Extend transition duration from 300ms/400ms to 800ms/600ms for more elegant feel
- Reduce ripple intensity from /20,/15,/10 to /8,/5 for subtlety
- Slow down ripple animation from 0.8s to 2s with cubic-bezier easing
- Add centered TERMIX logo with monospace font and subtitle
- Logo fades in from 80% scale, holds, then fades out at 110% scale
- Total effect: 1.2s logo animation synced with 2s ripple waves

Creates a premium, branded transition experience

* feat: Enhance transition animation with premium details

Timing adjustments:
- Extend fadeOut from 800ms to 1200ms
- Extend fadeIn from 600ms to 800ms
- Slow background fade to 700ms for elegance

Visual enhancements:
- Add 4-layer ripple waves (10%, 7%, 5%, 3% opacity) with staggered delays
- Ripple animation extended to 2.5s with refined opacity curve
- Logo blur effect: starts at 8px, sharpens to 0px, exits at 4px
- Logo glow effect: triple-layer text-shadow using primary theme color
- Increase logo size from text-6xl to text-7xl
- Subtitle delayed fade-in from bottom with smooth slide animation

Creates a cinematic, polished brand experience

* feat: Redesign login page with split-screen cinematic layout

Major redesign of authentication page:

Left Side (40% width):
- Full-height gradient background using primary theme color
- Large TERMIX logo with glow effect
- Subtitle and tagline
- Infinite animated ripple waves (3 layers)
- Hidden on mobile, shows brand identity

Right Side (60% width):
- Centered glassmorphism card with backdrop blur
- Refined tab switcher with pill-style active state
- Enlarged title with gradient text effect
- Added welcome subtitles for better UX
- Card slides in from bottom on load
- All existing functionality preserved

Visual enhancements:
- Tab navigation: segmented control style in muted container
- Active tab: white background with subtle shadow
- Smooth 200ms transitions on all interactions
- Card: rounded-2xl, shadow-xl, semi-transparent border

Creates premium, modern login experience matching transition animations

* feat: Update login page theme colors and add i18n support

- Changed login page gradient from blue to match dark theme colors
- Updated ripple effects to use theme primary color
- Added i18n translation keys for login page (auth.tagline, auth.description, auth.welcomeBack, auth.createAccount, auth.continueExternal)
- Updated all language files (en, zh, de, ru, pt-BR) with new translations
- Fixed TypeScript compilation issues by clearing build cache

* refactor: Use shadcn Tabs component and fix modal styling

- Replace custom tab navigation with shadcn Tabs component
- Restore border-2 border-dark-border for modal consistency
- Remove circular icon from login success message
- Simplify authentication success display

* refactor: Remove ripple effects and gradient from login page

- Remove animated ripple background effects
- Remove gradient background, use solid color (bg-dark-bg-darker)
- Remove text-shadow glow effect from logo
- Simplify brand showcase to clean, minimal design

* feat: Add decorative slash and remove subtitle from login page

- Add decorative slash divider with gradient lines below TERMIX logo
- Remove subtitle text (welcomeBack and createAccount)
- Simplify page title to show only the main heading

* feat: Add diagonal line pattern background to login page

- Replace decorative slash with subtle diagonal line pattern background
- Use repeating-linear-gradient at 45deg angle
- Set very low opacity (0.03) for subtle effect
- Pattern uses theme primary color

* fix: Display diagonal line pattern on login background

- Combine background color and pattern in single style attribute
- Use white semi-transparent lines (rgba 0.03 opacity)
- 45deg angle, 35px spacing, 2px width
- Remove separate overlay div to ensure pattern visibility

* security: Fix user enumeration vulnerability in login

- Unify error messages for invalid username and incorrect password
- Both return 401 status with 'Invalid username or password'
- Prevent attackers from enumerating valid usernames
- Maintain detailed logging for debugging purposes
- Changed from 404 'User not found' to generic auth failure message

* security: Add login rate limiting to prevent brute force attacks

- Implement LoginRateLimiter with IP and username-based tracking
- Block after 5 failed attempts within 15 minutes
- Lock account/IP for 15 minutes after threshold
- Automatic cleanup of expired entries every 5 minutes
- Track remaining attempts in logs for monitoring
- Return 429 status with remaining time on rate limit
- Reset counters on successful login
- Dual protection: both IP-based and username-based limits
This commit was merged in pull request #432.
This commit is contained in:
ZacharyZcR
2025-11-09 09:48:32 +08:00
committed by GitHub
parent b43e98073f
commit 5fc2ec3dc0
55 changed files with 2081 additions and 649 deletions

60
package-lock.json generated
View File

@@ -154,7 +154,6 @@
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.27.1",
"@babel/generator": "^7.28.5",
@@ -440,7 +439,6 @@
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.19.1.tgz",
"integrity": "sha512-q6NenYkEy2fn9+JyjIxMWcNjzTL/IhwqfzOut1/G3PrIFkrbl4AL7Wkse5tLrQUUyqGoAKU5+Pi5jnnXxH5HGw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
@@ -489,7 +487,6 @@
"resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",
"integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.0.0",
@@ -516,7 +513,6 @@
"resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.11.tgz",
"integrity": "sha512-9NsXp7Nwp891pQchI7gPdTwBuSuT3K65NGTHWHNJ55HjYcHLllr0rbIZNdOzas9ztc1EUVBlHou85FFZS4BNnw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/lang-css": "^6.0.0",
@@ -544,7 +540,6 @@
"resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.4.tgz",
"integrity": "sha512-0WVmhp1QOqZ4Rt6GlVGwKJN3KW7Xh4H2q8ZZNGZaP6lRdxXJzmjm4FqvmOojVj6khWJHIb9sp7U/72W7xQgqAA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.6.0",
@@ -745,7 +740,6 @@
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.11.3.tgz",
"integrity": "sha512-9HBM2XnwDj7fnu0551HkGdrUrrqmYq/WC5iv6nbY2WdicXdGbhR/gfbZOH73Aqj4351alY1+aoG9rCNfiwS1RA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.23.0",
@@ -822,7 +816,6 @@
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.5.2.tgz",
"integrity": "sha512-FVqsPqtPWKVVL3dPSxy8wEF/ymIEuVzF1PK3VbUgrxXpJUSHQWWZz4JMToquRxnkw+36LTamCZG2iua2Ptq0fA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@marijn/find-cluster-break": "^1.0.0"
}
@@ -844,7 +837,6 @@
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.38.6.tgz",
"integrity": "sha512-qiS0z1bKs5WOvHIAC0Cybmv4AJSkAXgX5aD6Mqd2epSLlVJsQl8NG23jCVouIgkh4All/mrbdsf2UOLFnJw0tw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@codemirror/state": "^6.5.0",
"crelt": "^1.0.6",
@@ -1172,7 +1164,6 @@
"integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"fast-json-stable-stringify": "^2.0.0",
@@ -1559,6 +1550,7 @@
"dev": true,
"license": "BSD-2-Clause",
"optional": true,
"peer": true,
"dependencies": {
"cross-dirname": "^0.1.0",
"debug": "^4.3.4",
@@ -1580,6 +1572,7 @@
"dev": true,
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
@@ -2536,8 +2529,7 @@
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.3.0.tgz",
"integrity": "sha512-L9X8uHCYU310o99L3/MpJKYxPzXPOS7S0NmBaM7UO/x2Kb2WbmMLSkfvdr1KxRIFYOpbY0Jhn7CfLSUDzL8arQ==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/@lezer/cpp": {
"version": "1.1.3",
@@ -2577,7 +2569,6 @@
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz",
"integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==",
"license": "MIT",
"peer": true,
"dependencies": {
"@lezer/common": "^1.3.0"
}
@@ -2609,7 +2600,6 @@
"resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.4.tgz",
"integrity": "sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.1.3",
@@ -2632,7 +2622,6 @@
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.2.tgz",
"integrity": "sha512-pu0K1jCIdnQ12aWNaAVU5bzi7Bd1w54J3ECgANPmYLtQKP0HBj2cE/5coBD66MT10xbtIuUr7tg0Shbsvk0mDA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@lezer/common": "^1.0.0"
}
@@ -4856,7 +4845,6 @@
"integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@types/node": "*"
}
@@ -5014,7 +5002,6 @@
"resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.5.tgz",
"integrity": "sha512-LuIQOcb6UmnF7C1PCFmEU1u2hmiHL43fgFQX67sN3H4Z+0Yk0Neo++mFsBjhOAuLzvlQeqAAkeDOZrJs9rzumQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/body-parser": "*",
"@types/express-serve-static-core": "^5.0.0",
@@ -5137,7 +5124,6 @@
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.9.2.tgz",
"integrity": "sha512-uWN8YqxXxqFMX2RqGOrumsKeti4LlmIMIyV0lgut4jx7KQBcBiW6vkDtIBvHnHIquwNfJhk8v2OtmO8zXWHfPA==",
"license": "MIT",
"peer": true,
"dependencies": {
"undici-types": "~7.16.0"
}
@@ -5180,7 +5166,6 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.2.tgz",
"integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==",
"license": "MIT",
"peer": true,
"dependencies": {
"csstype": "^3.0.2"
}
@@ -5191,7 +5176,6 @@
"integrity": "sha512-9KQPoO6mZCi7jcIStSnlOWn2nEF3mNmyr3rIAsGnAbQKYbRLyqmeSc39EVgtxXVia+LMT8j3knZLAZAh+xLmrw==",
"devOptional": true,
"license": "MIT",
"peer": true,
"peerDependencies": {
"@types/react": "^19.2.0"
}
@@ -5359,7 +5343,6 @@
"integrity": "sha512-BnOroVl1SgrPLywqxyqdJ4l3S2MsKVLDVxZvjI1Eoe8ev2r3kGDo+PcMihNmDE+6/KjkTubSJnmqGZZjQSBq/g==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.46.2",
"@typescript-eslint/types": "8.46.2",
@@ -5736,8 +5719,7 @@
"version": "5.5.0",
"resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz",
"integrity": "sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/7zip-bin": {
"version": "5.2.0",
@@ -5772,7 +5754,6 @@
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -6195,7 +6176,6 @@
"integrity": "sha512-3yVdyZhklTiNrtg+4WqHpJpFDd+WHTg2oM7UcR80GqL05AOV0xEJzc6qNvFYoEtE+hRp1n9MpN6/+4yhlGkDXQ==",
"hasInstallScript": true,
"license": "MIT",
"peer": true,
"dependencies": {
"bindings": "^1.5.0",
"prebuild-install": "^7.1.1"
@@ -6330,7 +6310,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.8.19",
"caniuse-lite": "^1.0.30001751",
@@ -7334,7 +7313,6 @@
"integrity": "sha512-itvL5h8RETACmOTFc4UfIyB2RfEHi71Ax6E/PivVxq9NseKbOWpeyHEOIbmAw1rs8Ak0VursQNww7lf7YtUwzg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"env-paths": "^2.2.1",
"import-fresh": "^3.3.0",
@@ -7411,7 +7389,8 @@
"integrity": "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==",
"dev": true,
"license": "MIT",
"optional": true
"optional": true,
"peer": true
},
"node_modules/cross-spawn": {
"version": "7.0.6",
@@ -7870,7 +7849,6 @@
"integrity": "sha512-59CAAjAhTaIMCN8y9kD573vDkxbs1uhDcrFLHSgutYdPcGOU35Rf95725snvzEOy4BFB7+eLJ8djCNPmGwG67w==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"app-builder-lib": "26.0.12",
"builder-util": "26.0.11",
@@ -7968,7 +7946,8 @@
"version": "3.1.7",
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.1.7.tgz",
"integrity": "sha512-VaTstWtsneJY8xzy7DekmYWEOZcmzIe3Qb3zPd4STve1OBTa+e+WmS1ITQec1fZYXI3HCsOZZiSMpG6oxoWMWQ==",
"license": "(MPL-2.0 OR Apache-2.0)"
"license": "(MPL-2.0 OR Apache-2.0)",
"peer": true
},
"node_modules/dot-prop": {
"version": "5.3.0",
@@ -8320,6 +8299,7 @@
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@electron/asar": "^3.2.1",
"debug": "^4.1.1",
@@ -8340,6 +8320,7 @@
"integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"graceful-fs": "^4.1.2",
"jsonfile": "^4.0.0",
@@ -8355,6 +8336,7 @@
"integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",
"dev": true,
"license": "MIT",
"peer": true,
"optionalDependencies": {
"graceful-fs": "^4.1.6"
}
@@ -8365,6 +8347,7 @@
"integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">= 4.0.0"
}
@@ -8627,7 +8610,6 @@
"integrity": "sha512-iy2GE3MHrYTL5lrCtMZ0X1KLEKKUjmK0kzwcnefhR66txcEmXZD2YWgR5GNdcEwkNx3a0siYkSvl0vIC+Svjmg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.1",
@@ -10226,7 +10208,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/runtime": "^7.27.6"
},
@@ -11768,6 +11749,7 @@
"resolved": "https://registry.npmjs.org/marked/-/marked-14.0.0.tgz",
"integrity": "sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==",
"license": "MIT",
"peer": true,
"bin": {
"marked": "bin/marked.js"
},
@@ -13795,6 +13777,7 @@
"dev": true,
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"commander": "^9.4.0"
},
@@ -13812,6 +13795,7 @@
"dev": true,
"license": "MIT",
"optional": true,
"peer": true,
"engines": {
"node": "^12.20.0 || >=14"
}
@@ -14263,7 +14247,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.0.tgz",
"integrity": "sha512-tmbWg6W31tQLeB5cdIBOicJDJRR2KzXsV7uSK9iNfLWQ5bIZfxuPEHp7M8wiHyHnn0DD1i7w3Zmin0FtkrwoCQ==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -14273,7 +14256,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.0.tgz",
"integrity": "sha512-UlbRu4cAiGaIewkPyiRGJk0imDN2T3JjieT6spoL2UeSf5od4n5LB/mQ4ejmxhCFT1tYe8IvaFulzynWovsEFQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"scheduler": "^0.27.0"
},
@@ -14300,7 +14282,6 @@
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.66.0.tgz",
"integrity": "sha512-xXBqsWGKrY46ZqaHDo+ZUYiMUgi8suYu5kdrS20EG8KiL7VRQitEbNjm+UcrDYrNi1YLyfpmAeGjCZYXLT9YBw==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18.0.0"
},
@@ -14448,7 +14429,6 @@
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",
"integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/use-sync-external-store": "^0.0.6",
"use-sync-external-store": "^1.4.0"
@@ -14657,8 +14637,7 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/redux-thunk": {
"version": "3.1.0",
@@ -15979,6 +15958,7 @@
"integrity": "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"mkdirp": "^0.5.1",
"rimraf": "~2.6.2"
@@ -16019,6 +15999,7 @@
"integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"minimist": "^1.2.6"
},
@@ -16033,6 +16014,7 @@
"deprecated": "Rimraf versions prior to v4 are no longer supported",
"dev": true,
"license": "ISC",
"peer": true,
"dependencies": {
"glob": "^7.1.3"
},
@@ -16137,7 +16119,6 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -16343,7 +16324,6 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -16756,7 +16736,6 @@
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.12.tgz",
"integrity": "sha512-ZWyE8YXEXqJrrSLvYgrRP7p62OziLW7xI5HYGWFzOvupfAlrLvURSzv/FyGyy0eidogEM3ujU+kUG1zuHgb6Ug==",
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.5.0",
@@ -16848,7 +16827,6 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},

View File

@@ -1480,13 +1480,17 @@ app.get(
if (status.hasUnencryptedDb) {
try {
unencryptedSize = fs.statSync(dbPath).size;
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", { error });
}
}
if (status.hasEncryptedDb) {
try {
encryptedSize = fs.statSync(encryptedDbPath).size;
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", { error });
}
}
res.json({

View File

@@ -22,11 +22,12 @@ import { nanoid } from "nanoid";
import speakeasy from "speakeasy";
import QRCode from "qrcode";
import type { Request, Response } from "express";
import { authLogger } from "../../utils/logger.js";
import { authLogger, databaseLogger } from "../../utils/logger.js";
import { AuthManager } from "../../utils/auth-manager.js";
import { DataCrypto } from "../../utils/data-crypto.js";
import { LazyFieldEncryption } from "../../utils/lazy-field-encryption.js";
import { parseUserAgent } from "../../utils/user-agent-parser.js";
import { loginRateLimiter } from "../../utils/login-rate-limiter.js";
const authManager = AuthManager.getInstance();
@@ -885,6 +886,7 @@ router.get("/oidc/callback", async (req, res) => {
// POST /users/login
router.post("/login", async (req, res) => {
const { username, password } = req.body;
const clientIp = req.ip || req.socket.remoteAddress || "unknown";
if (!isNonEmptyString(username) || !isNonEmptyString(password)) {
authLogger.warn("Invalid traditional login attempt", {
@@ -895,6 +897,21 @@ router.post("/login", async (req, res) => {
return res.status(400).json({ error: "Invalid username or password" });
}
// Check rate limiting
const lockStatus = loginRateLimiter.isLocked(clientIp, username);
if (lockStatus.locked) {
authLogger.warn("Login attempt blocked due to rate limiting", {
operation: "user_login_blocked",
username,
ip: clientIp,
remainingTime: lockStatus.remainingTime,
});
return res.status(429).json({
error: "Too many login attempts. Please try again later.",
remainingTime: lockStatus.remainingTime,
});
}
try {
const row = db.$client
.prepare("SELECT value FROM settings WHERE key = 'allow_password_login'")
@@ -919,11 +936,14 @@ router.post("/login", async (req, res) => {
.where(eq(users.username, username));
if (!user || user.length === 0) {
authLogger.warn(`User not found: ${username}`, {
loginRateLimiter.recordFailedAttempt(clientIp, username);
authLogger.warn(`Login failed: user not found`, {
operation: "user_login",
username,
ip: clientIp,
remainingAttempts: loginRateLimiter.getRemainingAttempts(clientIp, username),
});
return res.status(404).json({ error: "User not found" });
return res.status(401).json({ error: "Invalid username or password" });
}
const userRecord = user[0];
@@ -941,12 +961,15 @@ router.post("/login", async (req, res) => {
const isMatch = await bcrypt.compare(password, userRecord.password_hash);
if (!isMatch) {
authLogger.warn(`Incorrect password for user: ${username}`, {
loginRateLimiter.recordFailedAttempt(clientIp, username);
authLogger.warn(`Login failed: incorrect password`, {
operation: "user_login",
username,
userId: userRecord.id,
ip: clientIp,
remainingAttempts: loginRateLimiter.getRemainingAttempts(clientIp, username),
});
return res.status(401).json({ error: "Incorrect password" });
return res.status(401).json({ error: "Invalid username or password" });
}
try {
@@ -958,7 +981,9 @@ router.post("/login", async (req, res) => {
if (kekSalt.length === 0) {
await authManager.registerUser(userRecord.id, password);
}
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", { error });
}
const dataUnlocked = await authManager.authenticateUser(
userRecord.id,
@@ -986,6 +1011,9 @@ router.post("/login", async (req, res) => {
deviceInfo: deviceInfo.deviceInfo,
});
// Reset rate limiter on successful login
loginRateLimiter.resetAttempts(clientIp, username);
authLogger.success(`User logged in successfully: ${username}`, {
operation: "user_login_success",
username,
@@ -993,6 +1021,7 @@ router.post("/login", async (req, res) => {
dataUnlocked: true,
deviceType: deviceInfo.type,
deviceInfo: deviceInfo.deviceInfo,
ip: clientIp,
});
const response: Record<string, unknown> = {
@@ -1039,7 +1068,15 @@ router.post("/logout", authenticateJWT, async (req, res) => {
try {
const payload = await authManager.verifyJWTToken(token);
sessionId = payload?.sessionId;
} catch (error) {}
} catch (error) {
authLogger.debug(
"Token verification failed during logout (expected if token expired)",
{
operation: "logout_token_verify_failed",
userId,
},
);
}
}
await authManager.logoutUser(userId, sessionId);

View File

@@ -6,7 +6,7 @@ import { Client as SSHClient } from "ssh2";
import { getDb } from "../database/db/index.js";
import { sshCredentials, sshData } from "../database/db/schema.js";
import { eq, and } from "drizzle-orm";
import { fileLogger } from "../utils/logger.js";
import { fileLogger, sshLogger } from "../utils/logger.js";
import { SimpleDBOps } from "../utils/simple-db-ops.js";
import { AuthManager } from "../utils/auth-manager.js";
import type { AuthenticatedRequest } from "../../types/index.js";
@@ -120,7 +120,9 @@ function cleanupSession(sessionId: string) {
if (session) {
try {
session.client.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
clearTimeout(session.timeout);
delete sshSessions[sessionId];
}
@@ -663,7 +665,9 @@ app.post("/ssh/file_manager/ssh/connect-totp", async (req, res) => {
delete pendingTOTPSessions[sessionId];
try {
session.client.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
fileLogger.warn("TOTP session timeout before code submission", {
operation: "file_totp_verify",
sessionId,

View File

@@ -6,10 +6,18 @@ import { Client, type ConnectConfig } from "ssh2";
import { getDb } from "../database/db/index.js";
import { sshData, sshCredentials } from "../database/db/schema.js";
import { eq, and } from "drizzle-orm";
import { statsLogger } from "../utils/logger.js";
import { statsLogger, sshLogger } from "../utils/logger.js";
import { SimpleDBOps } from "../utils/simple-db-ops.js";
import { AuthManager } from "../utils/auth-manager.js";
import type { AuthenticatedRequest } from "../../types/index.js";
import { collectCpuMetrics } from "./widgets/cpu-collector.js";
import { collectMemoryMetrics } from "./widgets/memory-collector.js";
import { collectDiskMetrics } from "./widgets/disk-collector.js";
import { collectNetworkMetrics } from "./widgets/network-collector.js";
import { collectUptimeMetrics } from "./widgets/uptime-collector.js";
import { collectProcessesMetrics } from "./widgets/processes-collector.js";
import { collectSystemMetrics } from "./widgets/system-collector.js";
import { collectLoginStats } from "./widgets/login-stats-collector.js";
interface PooledConnection {
client: Client;
@@ -156,7 +164,9 @@ class SSHConnectionPool {
if (!conn.inUse && now - conn.lastUsed > maxAge) {
try {
conn.client.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
return false;
}
return true;
@@ -176,7 +186,9 @@ class SSHConnectionPool {
for (const conn of connections) {
try {
conn.client.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
}
}
this.connections.clear();
@@ -214,7 +226,9 @@ class RequestQueue {
if (request) {
try {
await request();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
}
}
@@ -518,7 +532,14 @@ class PollingManager {
data: metrics,
timestamp: Date.now(),
});
} catch (error) {}
} catch (error) {
statsLogger.warn("Failed to collect metrics for host", {
operation: "metrics_poll_failed",
hostId: host.id,
hostName: host.name,
error: error instanceof Error ? error.message : String(error),
});
}
}
stopPollingForHost(hostId: number, clearData = true): void {
@@ -932,59 +953,6 @@ async function withSshConnection<T>(
}
}
function execCommand(
client: Client,
command: string,
): Promise<{
stdout: string;
stderr: string;
code: number | null;
}> {
return new Promise((resolve, reject) => {
client.exec(command, { pty: false }, (err, stream) => {
if (err) return reject(err);
let stdout = "";
let stderr = "";
let exitCode: number | null = null;
stream
.on("close", (code: number | undefined) => {
exitCode = typeof code === "number" ? code : null;
resolve({ stdout, stderr, code: exitCode });
})
.on("data", (data: Buffer) => {
stdout += data.toString("utf8");
})
.stderr.on("data", (data: Buffer) => {
stderr += data.toString("utf8");
});
});
});
}
function parseCpuLine(
cpuLine: string,
): { total: number; idle: number } | undefined {
const parts = cpuLine.trim().split(/\s+/);
if (parts[0] !== "cpu") return undefined;
const nums = parts
.slice(1)
.map((n) => Number(n))
.filter((n) => Number.isFinite(n));
if (nums.length < 4) return undefined;
const idle = (nums[3] ?? 0) + (nums[4] ?? 0);
const total = nums.reduce((a, b) => a + b, 0);
return { total, idle };
}
function toFixedNum(n: number | null | undefined, digits = 2): number | null {
if (typeof n !== "number" || !Number.isFinite(n)) return null;
return Number(n.toFixed(digits));
}
function kibToGiB(kib: number): number {
return kib / (1024 * 1024);
}
async function collectMetrics(host: SSHHostWithCredentials): Promise<{
cpu: {
percent: number | null;
@@ -1047,298 +1015,38 @@ async function collectMetrics(host: SSHHostWithCredentials): Promise<{
return requestQueue.queueRequest(host.id, async () => {
try {
return await withSshConnection(host, async (client) => {
let cpuPercent: number | null = null;
let cores: number | null = null;
let loadTriplet: [number, number, number] | null = null;
const cpu = await collectCpuMetrics(client);
const memory = await collectMemoryMetrics(client);
const disk = await collectDiskMetrics(client);
const network = await collectNetworkMetrics(client);
const uptime = await collectUptimeMetrics(client);
const processes = await collectProcessesMetrics(client);
const system = await collectSystemMetrics(client);
let login_stats = {
recentLogins: [],
failedLogins: [],
totalLogins: 0,
uniqueIPs: 0,
};
try {
const [stat1, loadAvgOut, coresOut] = await Promise.all([
execCommand(client, "cat /proc/stat"),
execCommand(client, "cat /proc/loadavg"),
execCommand(
client,
"nproc 2>/dev/null || grep -c ^processor /proc/cpuinfo",
),
]);
await new Promise((r) => setTimeout(r, 500));
const stat2 = await execCommand(client, "cat /proc/stat");
const cpuLine1 = (
stat1.stdout.split("\n").find((l) => l.startsWith("cpu ")) || ""
).trim();
const cpuLine2 = (
stat2.stdout.split("\n").find((l) => l.startsWith("cpu ")) || ""
).trim();
const a = parseCpuLine(cpuLine1);
const b = parseCpuLine(cpuLine2);
if (a && b) {
const totalDiff = b.total - a.total;
const idleDiff = b.idle - a.idle;
const used = totalDiff - idleDiff;
if (totalDiff > 0)
cpuPercent = Math.max(0, Math.min(100, (used / totalDiff) * 100));
}
const laParts = loadAvgOut.stdout.trim().split(/\s+/);
if (laParts.length >= 3) {
loadTriplet = [
Number(laParts[0]),
Number(laParts[1]),
Number(laParts[2]),
].map((v) => (Number.isFinite(v) ? Number(v) : 0)) as [
number,
number,
number,
];
}
const coresNum = Number((coresOut.stdout || "").trim());
cores = Number.isFinite(coresNum) && coresNum > 0 ? coresNum : null;
login_stats = await collectLoginStats(client);
} catch (e) {
cpuPercent = null;
cores = null;
loadTriplet = null;
statsLogger.debug("Failed to collect login stats", {
operation: "login_stats_failed",
error: e instanceof Error ? e.message : String(e),
});
}
let memPercent: number | null = null;
let usedGiB: number | null = null;
let totalGiB: number | null = null;
try {
const memInfo = await execCommand(client, "cat /proc/meminfo");
const lines = memInfo.stdout.split("\n");
const getVal = (key: string) => {
const line = lines.find((l) => l.startsWith(key));
if (!line) return null;
const m = line.match(/\d+/);
return m ? Number(m[0]) : null;
};
const totalKb = getVal("MemTotal:");
const availKb = getVal("MemAvailable:");
if (totalKb && availKb && totalKb > 0) {
const usedKb = totalKb - availKb;
memPercent = Math.max(0, Math.min(100, (usedKb / totalKb) * 100));
usedGiB = kibToGiB(usedKb);
totalGiB = kibToGiB(totalKb);
}
} catch (e) {
memPercent = null;
usedGiB = null;
totalGiB = null;
}
let diskPercent: number | null = null;
let usedHuman: string | null = null;
let totalHuman: string | null = null;
let availableHuman: string | null = null;
try {
const [diskOutHuman, diskOutBytes] = await Promise.all([
execCommand(client, "df -h -P / | tail -n +2"),
execCommand(client, "df -B1 -P / | tail -n +2"),
]);
const humanLine =
diskOutHuman.stdout
.split("\n")
.map((l) => l.trim())
.filter(Boolean)[0] || "";
const bytesLine =
diskOutBytes.stdout
.split("\n")
.map((l) => l.trim())
.filter(Boolean)[0] || "";
const humanParts = humanLine.split(/\s+/);
const bytesParts = bytesLine.split(/\s+/);
if (humanParts.length >= 6 && bytesParts.length >= 6) {
totalHuman = humanParts[1] || null;
usedHuman = humanParts[2] || null;
availableHuman = humanParts[3] || null;
const totalBytes = Number(bytesParts[1]);
const usedBytes = Number(bytesParts[2]);
if (
Number.isFinite(totalBytes) &&
Number.isFinite(usedBytes) &&
totalBytes > 0
) {
diskPercent = Math.max(
0,
Math.min(100, (usedBytes / totalBytes) * 100),
);
}
}
} catch (e) {
diskPercent = null;
usedHuman = null;
totalHuman = null;
availableHuman = null;
}
const interfaces: Array<{
name: string;
ip: string;
state: string;
rxBytes: string | null;
txBytes: string | null;
}> = [];
try {
const ifconfigOut = await execCommand(
client,
"ip -o addr show | awk '{print $2,$4}' | grep -v '^lo'",
);
const netStatOut = await execCommand(
client,
"ip -o link show | awk '{gsub(/:/, \"\", $2); print $2,$9}'",
);
const addrs = ifconfigOut.stdout
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
const states = netStatOut.stdout
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
const ifMap = new Map<string, { ip: string; state: string }>();
for (const line of addrs) {
const parts = line.split(/\s+/);
if (parts.length >= 2) {
const name = parts[0];
const ip = parts[1].split("/")[0];
if (!ifMap.has(name)) ifMap.set(name, { ip, state: "UNKNOWN" });
}
}
for (const line of states) {
const parts = line.split(/\s+/);
if (parts.length >= 2) {
const name = parts[0];
const state = parts[1];
const existing = ifMap.get(name);
if (existing) {
existing.state = state;
}
}
}
for (const [name, data] of ifMap.entries()) {
interfaces.push({
name,
ip: data.ip,
state: data.state,
rxBytes: null,
txBytes: null,
});
}
} catch (e) {}
let uptimeSeconds: number | null = null;
let uptimeFormatted: string | null = null;
try {
const uptimeOut = await execCommand(client, "cat /proc/uptime");
const uptimeParts = uptimeOut.stdout.trim().split(/\s+/);
if (uptimeParts.length >= 1) {
uptimeSeconds = Number(uptimeParts[0]);
if (Number.isFinite(uptimeSeconds)) {
const days = Math.floor(uptimeSeconds / 86400);
const hours = Math.floor((uptimeSeconds % 86400) / 3600);
const minutes = Math.floor((uptimeSeconds % 3600) / 60);
uptimeFormatted = `${days}d ${hours}h ${minutes}m`;
}
}
} catch (e) {}
let totalProcesses: number | null = null;
let runningProcesses: number | null = null;
const topProcesses: Array<{
pid: string;
user: string;
cpu: string;
mem: string;
command: string;
}> = [];
try {
const psOut = await execCommand(
client,
"ps aux --sort=-%cpu | head -n 11",
);
const psLines = psOut.stdout
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
if (psLines.length > 1) {
for (let i = 1; i < Math.min(psLines.length, 11); i++) {
const parts = psLines[i].split(/\s+/);
if (parts.length >= 11) {
topProcesses.push({
pid: parts[1],
user: parts[0],
cpu: parts[2],
mem: parts[3],
command: parts.slice(10).join(" ").substring(0, 50),
});
}
}
}
const procCount = await execCommand(client, "ps aux | wc -l");
const runningCount = await execCommand(
client,
"ps aux | grep -c ' R '",
);
totalProcesses = Number(procCount.stdout.trim()) - 1;
runningProcesses = Number(runningCount.stdout.trim());
} catch (e) {}
let hostname: string | null = null;
let kernel: string | null = null;
let os: string | null = null;
try {
const hostnameOut = await execCommand(client, "hostname");
const kernelOut = await execCommand(client, "uname -r");
const osOut = await execCommand(
client,
"cat /etc/os-release | grep '^PRETTY_NAME=' | cut -d'\"' -f2",
);
hostname = hostnameOut.stdout.trim() || null;
kernel = kernelOut.stdout.trim() || null;
os = osOut.stdout.trim() || null;
} catch (e) {}
const result = {
cpu: { percent: toFixedNum(cpuPercent, 0), cores, load: loadTriplet },
memory: {
percent: toFixedNum(memPercent, 0),
usedGiB: usedGiB ? toFixedNum(usedGiB, 2) : null,
totalGiB: totalGiB ? toFixedNum(totalGiB, 2) : null,
},
disk: {
percent: toFixedNum(diskPercent, 0),
usedHuman,
totalHuman,
availableHuman,
},
network: {
interfaces,
},
uptime: {
seconds: uptimeSeconds,
formatted: uptimeFormatted,
},
processes: {
total: totalProcesses,
running: runningProcesses,
top: topProcesses,
},
system: {
hostname,
kernel,
os,
},
cpu,
memory,
disk,
network,
uptime,
processes,
system,
login_stats,
};
metricsCache.set(host.id, result);
@@ -1386,7 +1094,9 @@ function tcpPing(
settled = true;
try {
socket.destroy();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
resolve(result);
};

View File

@@ -15,7 +15,7 @@ import type {
ErrorType,
} from "../../types/index.js";
import { CONNECTION_STATES } from "../../types/index.js";
import { tunnelLogger } from "../utils/logger.js";
import { tunnelLogger, sshLogger } from "../utils/logger.js";
import { SystemCrypto } from "../utils/system-crypto.js";
import { SimpleDBOps } from "../utils/simple-db-ops.js";
import { DataCrypto } from "../utils/data-crypto.js";
@@ -217,7 +217,9 @@ function cleanupTunnelResources(
if (verification?.timeout) clearTimeout(verification.timeout);
try {
verification?.conn.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
tunnelVerifications.delete(tunnelName);
}
@@ -282,7 +284,9 @@ function handleDisconnect(
const verification = tunnelVerifications.get(tunnelName);
if (verification?.timeout) clearTimeout(verification.timeout);
verification?.conn.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
tunnelVerifications.delete(tunnelName);
}
@@ -638,7 +642,9 @@ async function connectSSHTunnel(
try {
conn.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
activeTunnels.delete(tunnelName);
@@ -778,7 +784,9 @@ async function connectSSHTunnel(
const verification = tunnelVerifications.get(tunnelName);
if (verification?.timeout) clearTimeout(verification.timeout);
verification?.conn.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
tunnelVerifications.delete(tunnelName);
}

View File

@@ -0,0 +1,39 @@
import type { Client } from "ssh2";
export function execCommand(
client: Client,
command: string,
): Promise<{
stdout: string;
stderr: string;
code: number | null;
}> {
return new Promise((resolve, reject) => {
client.exec(command, { pty: false }, (err, stream) => {
if (err) return reject(err);
let stdout = "";
let stderr = "";
let exitCode: number | null = null;
stream
.on("close", (code: number | undefined) => {
exitCode = typeof code === "number" ? code : null;
resolve({ stdout, stderr, code: exitCode });
})
.on("data", (data: Buffer) => {
stdout += data.toString("utf8");
})
.stderr.on("data", (data: Buffer) => {
stderr += data.toString("utf8");
});
});
});
}
export function toFixedNum(n: number | null | undefined, digits = 2): number | null {
if (typeof n !== "number" || !Number.isFinite(n)) return null;
return Number(n.toFixed(digits));
}
export function kibToGiB(kib: number): number {
return kib / (1024 * 1024);
}

View File

@@ -0,0 +1,83 @@
import type { Client } from "ssh2";
import { execCommand, toFixedNum } from "./common-utils.js";
function parseCpuLine(
cpuLine: string,
): { total: number; idle: number } | undefined {
const parts = cpuLine.trim().split(/\s+/);
if (parts[0] !== "cpu") return undefined;
const nums = parts
.slice(1)
.map((n) => Number(n))
.filter((n) => Number.isFinite(n));
if (nums.length < 4) return undefined;
const idle = (nums[3] ?? 0) + (nums[4] ?? 0);
const total = nums.reduce((a, b) => a + b, 0);
return { total, idle };
}
export async function collectCpuMetrics(client: Client): Promise<{
percent: number | null;
cores: number | null;
load: [number, number, number] | null;
}> {
let cpuPercent: number | null = null;
let cores: number | null = null;
let loadTriplet: [number, number, number] | null = null;
try {
const [stat1, loadAvgOut, coresOut] = await Promise.all([
execCommand(client, "cat /proc/stat"),
execCommand(client, "cat /proc/loadavg"),
execCommand(
client,
"nproc 2>/dev/null || grep -c ^processor /proc/cpuinfo",
),
]);
await new Promise((r) => setTimeout(r, 500));
const stat2 = await execCommand(client, "cat /proc/stat");
const cpuLine1 = (
stat1.stdout.split("\n").find((l) => l.startsWith("cpu ")) || ""
).trim();
const cpuLine2 = (
stat2.stdout.split("\n").find((l) => l.startsWith("cpu ")) || ""
).trim();
const a = parseCpuLine(cpuLine1);
const b = parseCpuLine(cpuLine2);
if (a && b) {
const totalDiff = b.total - a.total;
const idleDiff = b.idle - a.idle;
const used = totalDiff - idleDiff;
if (totalDiff > 0)
cpuPercent = Math.max(0, Math.min(100, (used / totalDiff) * 100));
}
const laParts = loadAvgOut.stdout.trim().split(/\s+/);
if (laParts.length >= 3) {
loadTriplet = [
Number(laParts[0]),
Number(laParts[1]),
Number(laParts[2]),
].map((v) => (Number.isFinite(v) ? Number(v) : 0)) as [
number,
number,
number,
];
}
const coresNum = Number((coresOut.stdout || "").trim());
cores = Number.isFinite(coresNum) && coresNum > 0 ? coresNum : null;
} catch (e) {
cpuPercent = null;
cores = null;
loadTriplet = null;
}
return {
percent: toFixedNum(cpuPercent, 0),
cores,
load: loadTriplet,
};
}

View File

@@ -0,0 +1,67 @@
import type { Client } from "ssh2";
import { execCommand, toFixedNum } from "./common-utils.js";
export async function collectDiskMetrics(client: Client): Promise<{
percent: number | null;
usedHuman: string | null;
totalHuman: string | null;
availableHuman: string | null;
}> {
let diskPercent: number | null = null;
let usedHuman: string | null = null;
let totalHuman: string | null = null;
let availableHuman: string | null = null;
try {
const [diskOutHuman, diskOutBytes] = await Promise.all([
execCommand(client, "df -h -P / | tail -n +2"),
execCommand(client, "df -B1 -P / | tail -n +2"),
]);
const humanLine =
diskOutHuman.stdout
.split("\n")
.map((l) => l.trim())
.filter(Boolean)[0] || "";
const bytesLine =
diskOutBytes.stdout
.split("\n")
.map((l) => l.trim())
.filter(Boolean)[0] || "";
const humanParts = humanLine.split(/\s+/);
const bytesParts = bytesLine.split(/\s+/);
if (humanParts.length >= 6 && bytesParts.length >= 6) {
totalHuman = humanParts[1] || null;
usedHuman = humanParts[2] || null;
availableHuman = humanParts[3] || null;
const totalBytes = Number(bytesParts[1]);
const usedBytes = Number(bytesParts[2]);
if (
Number.isFinite(totalBytes) &&
Number.isFinite(usedBytes) &&
totalBytes > 0
) {
diskPercent = Math.max(
0,
Math.min(100, (usedBytes / totalBytes) * 100),
);
}
}
} catch (e) {
diskPercent = null;
usedHuman = null;
totalHuman = null;
availableHuman = null;
}
return {
percent: toFixedNum(diskPercent, 0),
usedHuman,
totalHuman,
availableHuman,
};
}

View File

@@ -0,0 +1,117 @@
import type { Client } from "ssh2";
import { execCommand } from "./common-utils.js";
export interface LoginRecord {
user: string;
ip: string;
time: string;
status: "success" | "failed";
}
export interface LoginStats {
recentLogins: LoginRecord[];
failedLogins: LoginRecord[];
totalLogins: number;
uniqueIPs: number;
}
export async function collectLoginStats(client: Client): Promise<LoginStats> {
const recentLogins: LoginRecord[] = [];
const failedLogins: LoginRecord[] = [];
const ipSet = new Set<string>();
try {
const lastOut = await execCommand(
client,
"last -n 20 -F -w | grep -v 'reboot' | grep -v 'wtmp' | head -20",
);
const lastLines = lastOut.stdout
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
for (const line of lastLines) {
const parts = line.split(/\s+/);
if (parts.length >= 10) {
const user = parts[0];
const tty = parts[1];
const ip = parts[2] === ":" || parts[2].startsWith(":") ? "local" : parts[2];
const timeStart = parts.indexOf(parts.find(p => /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)/.test(p)) || "");
if (timeStart > 0 && parts.length > timeStart + 4) {
const timeStr = parts.slice(timeStart, timeStart + 5).join(" ");
if (user && user !== "wtmp" && tty !== "system") {
recentLogins.push({
user,
ip,
time: new Date(timeStr).toISOString(),
status: "success",
});
if (ip !== "local") {
ipSet.add(ip);
}
}
}
}
}
} catch (e) {
// Ignore errors
}
try {
const failedOut = await execCommand(
client,
"grep 'Failed password' /var/log/auth.log 2>/dev/null | tail -10 || grep 'authentication failure' /var/log/secure 2>/dev/null | tail -10 || echo ''",
);
const failedLines = failedOut.stdout
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
for (const line of failedLines) {
let user = "unknown";
let ip = "unknown";
let timeStr = "";
const userMatch = line.match(/for (?:invalid user )?(\S+)/);
if (userMatch) {
user = userMatch[1];
}
const ipMatch = line.match(/from (\d+\.\d+\.\d+\.\d+)/);
if (ipMatch) {
ip = ipMatch[1];
}
const dateMatch = line.match(/^(\w+\s+\d+\s+\d+:\d+:\d+)/);
if (dateMatch) {
const currentYear = new Date().getFullYear();
timeStr = `${currentYear} ${dateMatch[1]}`;
}
if (user && ip) {
failedLogins.push({
user,
ip,
time: timeStr ? new Date(timeStr).toISOString() : new Date().toISOString(),
status: "failed",
});
if (ip !== "unknown") {
ipSet.add(ip);
}
}
}
} catch (e) {
// Ignore errors
}
return {
recentLogins: recentLogins.slice(0, 10),
failedLogins: failedLogins.slice(0, 10),
totalLogins: recentLogins.length,
uniqueIPs: ipSet.size,
};
}

View File

@@ -0,0 +1,41 @@
import type { Client } from "ssh2";
import { execCommand, toFixedNum, kibToGiB } from "./common-utils.js";
export async function collectMemoryMetrics(client: Client): Promise<{
percent: number | null;
usedGiB: number | null;
totalGiB: number | null;
}> {
let memPercent: number | null = null;
let usedGiB: number | null = null;
let totalGiB: number | null = null;
try {
const memInfo = await execCommand(client, "cat /proc/meminfo");
const lines = memInfo.stdout.split("\n");
const getVal = (key: string) => {
const line = lines.find((l) => l.startsWith(key));
if (!line) return null;
const m = line.match(/\d+/);
return m ? Number(m[0]) : null;
};
const totalKb = getVal("MemTotal:");
const availKb = getVal("MemAvailable:");
if (totalKb && availKb && totalKb > 0) {
const usedKb = totalKb - availKb;
memPercent = Math.max(0, Math.min(100, (usedKb / totalKb) * 100));
usedGiB = kibToGiB(usedKb);
totalGiB = kibToGiB(totalKb);
}
} catch (e) {
memPercent = null;
usedGiB = null;
totalGiB = null;
}
return {
percent: toFixedNum(memPercent, 0),
usedGiB: usedGiB ? toFixedNum(usedGiB, 2) : null,
totalGiB: totalGiB ? toFixedNum(totalGiB, 2) : null,
};
}

View File

@@ -0,0 +1,79 @@
import type { Client } from "ssh2";
import { execCommand } from "./common-utils.js";
import { statsLogger } from "../../utils/logger.js";
export async function collectNetworkMetrics(client: Client): Promise<{
interfaces: Array<{
name: string;
ip: string;
state: string;
rxBytes: string | null;
txBytes: string | null;
}>;
}> {
const interfaces: Array<{
name: string;
ip: string;
state: string;
rxBytes: string | null;
txBytes: string | null;
}> = [];
try {
const ifconfigOut = await execCommand(
client,
"ip -o addr show | awk '{print $2,$4}' | grep -v '^lo'",
);
const netStatOut = await execCommand(
client,
"ip -o link show | awk '{gsub(/:/, \"\", $2); print $2,$9}'",
);
const addrs = ifconfigOut.stdout
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
const states = netStatOut.stdout
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
const ifMap = new Map<string, { ip: string; state: string }>();
for (const line of addrs) {
const parts = line.split(/\s+/);
if (parts.length >= 2) {
const name = parts[0];
const ip = parts[1].split("/")[0];
if (!ifMap.has(name)) ifMap.set(name, { ip, state: "UNKNOWN" });
}
}
for (const line of states) {
const parts = line.split(/\s+/);
if (parts.length >= 2) {
const name = parts[0];
const state = parts[1];
const existing = ifMap.get(name);
if (existing) {
existing.state = state;
}
}
}
for (const [name, data] of ifMap.entries()) {
interfaces.push({
name,
ip: data.ip,
state: data.state,
rxBytes: null,
txBytes: null,
});
}
} catch (e) {
statsLogger.debug("Failed to collect network interface stats", {
operation: "network_stats_failed",
error: e instanceof Error ? e.message : String(e),
});
}
return { interfaces };
}

View File

@@ -0,0 +1,69 @@
import type { Client } from "ssh2";
import { execCommand } from "./common-utils.js";
import { statsLogger } from "../../utils/logger.js";
export async function collectProcessesMetrics(client: Client): Promise<{
total: number | null;
running: number | null;
top: Array<{
pid: string;
user: string;
cpu: string;
mem: string;
command: string;
}>;
}> {
let totalProcesses: number | null = null;
let runningProcesses: number | null = null;
const topProcesses: Array<{
pid: string;
user: string;
cpu: string;
mem: string;
command: string;
}> = [];
try {
const psOut = await execCommand(
client,
"ps aux --sort=-%cpu | head -n 11",
);
const psLines = psOut.stdout
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
if (psLines.length > 1) {
for (let i = 1; i < Math.min(psLines.length, 11); i++) {
const parts = psLines[i].split(/\s+/);
if (parts.length >= 11) {
topProcesses.push({
pid: parts[1],
user: parts[0],
cpu: parts[2],
mem: parts[3],
command: parts.slice(10).join(" ").substring(0, 50),
});
}
}
}
const procCount = await execCommand(client, "ps aux | wc -l");
const runningCount = await execCommand(
client,
"ps aux | grep -c ' R '",
);
totalProcesses = Number(procCount.stdout.trim()) - 1;
runningProcesses = Number(runningCount.stdout.trim());
} catch (e) {
statsLogger.debug("Failed to collect process stats", {
operation: "process_stats_failed",
error: e instanceof Error ? e.message : String(e),
});
}
return {
total: totalProcesses,
running: runningProcesses,
top: topProcesses,
};
}

View File

@@ -0,0 +1,37 @@
import type { Client } from "ssh2";
import { execCommand } from "./common-utils.js";
import { statsLogger } from "../../utils/logger.js";
export async function collectSystemMetrics(client: Client): Promise<{
hostname: string | null;
kernel: string | null;
os: string | null;
}> {
let hostname: string | null = null;
let kernel: string | null = null;
let os: string | null = null;
try {
const hostnameOut = await execCommand(client, "hostname");
const kernelOut = await execCommand(client, "uname -r");
const osOut = await execCommand(
client,
"cat /etc/os-release | grep '^PRETTY_NAME=' | cut -d'\"' -f2",
);
hostname = hostnameOut.stdout.trim() || null;
kernel = kernelOut.stdout.trim() || null;
os = osOut.stdout.trim() || null;
} catch (e) {
statsLogger.debug("Failed to collect system info", {
operation: "system_info_failed",
error: e instanceof Error ? e.message : String(e),
});
}
return {
hostname,
kernel,
os,
};
}

View File

@@ -0,0 +1,35 @@
import type { Client } from "ssh2";
import { execCommand } from "./common-utils.js";
import { statsLogger } from "../../utils/logger.js";
export async function collectUptimeMetrics(client: Client): Promise<{
seconds: number | null;
formatted: string | null;
}> {
let uptimeSeconds: number | null = null;
let uptimeFormatted: string | null = null;
try {
const uptimeOut = await execCommand(client, "cat /proc/uptime");
const uptimeParts = uptimeOut.stdout.trim().split(/\s+/);
if (uptimeParts.length >= 1) {
uptimeSeconds = Number(uptimeParts[0]);
if (Number.isFinite(uptimeSeconds)) {
const days = Math.floor(uptimeSeconds / 86400);
const hours = Math.floor((uptimeSeconds % 86400) / 3600);
const minutes = Math.floor((uptimeSeconds % 3600) / 60);
uptimeFormatted = `${days}d ${hours}h ${minutes}m`;
}
}
} catch (e) {
statsLogger.debug("Failed to collect uptime", {
operation: "uptime_failed",
error: e instanceof Error ? e.message : String(e),
});
}
return {
seconds: uptimeSeconds,
formatted: uptimeFormatted,
};
}

View File

@@ -21,7 +21,11 @@ import { systemLogger, versionLogger } from "./utils/logger.js";
if (persistentConfig.parsed) {
Object.assign(process.env, persistentConfig.parsed);
}
} catch {}
} catch (error) {
systemLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
let version = "unknown";

View File

@@ -233,7 +233,11 @@ IP.3 = 0.0.0.0
let envContent = "";
try {
envContent = await fs.readFile(this.ENV_FILE, "utf8");
} catch {}
} catch (error) {
systemLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
let updatedContent = envContent;
let hasChanges = false;

View File

@@ -327,7 +327,11 @@ class DatabaseFileEncryption {
fs.accessSync(envPath, fs.constants.R_OK);
envFileReadable = true;
}
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
databaseLogger.error(
"Database decryption authentication failed - possible causes: wrong DATABASE_KEY, corrupted files, or interrupted write",
@@ -628,7 +632,11 @@ class DatabaseFileEncryption {
try {
fs.accessSync(envPath, fs.constants.R_OK);
result.environment.envFileReadable = true;
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
}
if (

View File

@@ -82,7 +82,11 @@ export class LazyFieldEncryption {
legacyFieldName,
);
return decrypted;
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
}
const sensitiveFields = [
@@ -174,7 +178,11 @@ export class LazyFieldEncryption {
wasPlaintext: false,
wasLegacyEncryption: true,
};
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
}
return {
encrypted: fieldValue,

View File

@@ -0,0 +1,146 @@
interface LoginAttempt {
count: number;
firstAttempt: number;
lockedUntil?: number;
}
class LoginRateLimiter {
private ipAttempts = new Map<string, LoginAttempt>();
private usernameAttempts = new Map<string, LoginAttempt>();
private readonly MAX_ATTEMPTS = 5;
private readonly WINDOW_MS = 15 * 60 * 1000; // 15 minutes
private readonly LOCKOUT_MS = 15 * 60 * 1000; // 15 minutes
// Clean up old entries periodically
constructor() {
setInterval(() => this.cleanup(), 5 * 60 * 1000); // Clean every 5 minutes
}
private cleanup(): void {
const now = Date.now();
// Clean IP attempts
for (const [ip, attempt] of this.ipAttempts.entries()) {
if (attempt.lockedUntil && attempt.lockedUntil < now) {
this.ipAttempts.delete(ip);
} else if (!attempt.lockedUntil && (now - attempt.firstAttempt) > this.WINDOW_MS) {
this.ipAttempts.delete(ip);
}
}
// Clean username attempts
for (const [username, attempt] of this.usernameAttempts.entries()) {
if (attempt.lockedUntil && attempt.lockedUntil < now) {
this.usernameAttempts.delete(username);
} else if (!attempt.lockedUntil && (now - attempt.firstAttempt) > this.WINDOW_MS) {
this.usernameAttempts.delete(username);
}
}
}
recordFailedAttempt(ip: string, username?: string): void {
const now = Date.now();
// Record IP attempt
const ipAttempt = this.ipAttempts.get(ip);
if (!ipAttempt) {
this.ipAttempts.set(ip, {
count: 1,
firstAttempt: now,
});
} else if ((now - ipAttempt.firstAttempt) > this.WINDOW_MS) {
// Reset if outside window
this.ipAttempts.set(ip, {
count: 1,
firstAttempt: now,
});
} else {
ipAttempt.count++;
if (ipAttempt.count >= this.MAX_ATTEMPTS) {
ipAttempt.lockedUntil = now + this.LOCKOUT_MS;
}
}
// Record username attempt if provided
if (username) {
const userAttempt = this.usernameAttempts.get(username);
if (!userAttempt) {
this.usernameAttempts.set(username, {
count: 1,
firstAttempt: now,
});
} else if ((now - userAttempt.firstAttempt) > this.WINDOW_MS) {
// Reset if outside window
this.usernameAttempts.set(username, {
count: 1,
firstAttempt: now,
});
} else {
userAttempt.count++;
if (userAttempt.count >= this.MAX_ATTEMPTS) {
userAttempt.lockedUntil = now + this.LOCKOUT_MS;
}
}
}
}
resetAttempts(ip: string, username?: string): void {
this.ipAttempts.delete(ip);
if (username) {
this.usernameAttempts.delete(username);
}
}
isLocked(ip: string, username?: string): { locked: boolean; remainingTime?: number } {
const now = Date.now();
// Check IP lockout
const ipAttempt = this.ipAttempts.get(ip);
if (ipAttempt?.lockedUntil && ipAttempt.lockedUntil > now) {
return {
locked: true,
remainingTime: Math.ceil((ipAttempt.lockedUntil - now) / 1000),
};
}
// Check username lockout
if (username) {
const userAttempt = this.usernameAttempts.get(username);
if (userAttempt?.lockedUntil && userAttempt.lockedUntil > now) {
return {
locked: true,
remainingTime: Math.ceil((userAttempt.lockedUntil - now) / 1000),
};
}
}
return { locked: false };
}
getRemainingAttempts(ip: string, username?: string): number {
const now = Date.now();
let minRemaining = this.MAX_ATTEMPTS;
// Check IP attempts
const ipAttempt = this.ipAttempts.get(ip);
if (ipAttempt && (now - ipAttempt.firstAttempt) <= this.WINDOW_MS) {
const ipRemaining = Math.max(0, this.MAX_ATTEMPTS - ipAttempt.count);
minRemaining = Math.min(minRemaining, ipRemaining);
}
// Check username attempts
if (username) {
const userAttempt = this.usernameAttempts.get(username);
if (userAttempt && (now - userAttempt.firstAttempt) <= this.WINDOW_MS) {
const userRemaining = Math.max(0, this.MAX_ATTEMPTS - userAttempt.count);
minRemaining = Math.min(minRemaining, userRemaining);
}
}
return minRemaining;
}
}
// Export singleton instance
export const loginRateLimiter = new LoginRateLimiter();

View File

@@ -1,4 +1,5 @@
import ssh2Pkg from "ssh2";
import { sshLogger } from "./logger.js";
const ssh2Utils = ssh2Pkg.utils;
function detectKeyTypeFromContent(keyContent: string): string {
@@ -84,7 +85,11 @@ function detectKeyTypeFromContent(keyContent: string): string {
} else if (decodedString.includes("1.3.101.112")) {
return "ssh-ed25519";
}
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
if (content.length < 800) {
return "ssh-ed25519";
@@ -140,7 +145,11 @@ function detectPublicKeyTypeFromContent(publicKeyContent: string): string {
} else if (decodedString.includes("1.3.101.112")) {
return "ssh-ed25519";
}
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
if (content.length < 400) {
return "ssh-ed25519";
@@ -242,7 +251,11 @@ export function parseSSHKey(
useSSH2 = true;
}
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
}
if (!useSSH2) {
@@ -268,7 +281,11 @@ export function parseSSHKey(
success: true,
};
}
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
return {
privateKey: privateKeyData,

View File

@@ -51,7 +51,15 @@ class SystemCrypto {
},
);
}
} catch (fileError) {}
} catch (fileError) {
// OK: .env file not found or unreadable, will generate new JWT secret
databaseLogger.debug(
".env file not accessible, will generate new JWT secret",
{
operation: "jwt_env_not_found",
},
);
}
await this.generateAndGuideUser();
} catch (error) {
@@ -102,7 +110,15 @@ class SystemCrypto {
return;
} else {
}
} catch (fileError) {}
} catch (fileError) {
// OK: .env file not found or unreadable, will generate new database key
databaseLogger.debug(
".env file not accessible, will generate new database key",
{
operation: "db_key_env_not_found",
},
);
}
await this.generateAndGuideDatabaseKey();
} catch (error) {
@@ -140,7 +156,11 @@ class SystemCrypto {
process.env.INTERNAL_AUTH_TOKEN = tokenMatch[1];
return;
}
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
await this.generateAndGuideInternalAuthToken();
} catch (error) {

View File

@@ -6,7 +6,7 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all duration-100 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive active:scale-95",
{
variants: {
variant: {

View File

@@ -8,7 +8,7 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] duration-200 outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className,

28
src/components/ui/kbd.tsx Normal file
View File

@@ -0,0 +1,28 @@
import { cn } from "@/lib/utils"
function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
return (
<kbd
data-slot="kbd"
className={cn(
"bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none",
"[&_svg:not([class*='size-'])]:size-3",
"[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",
className
)}
{...props}
/>
)
}
function KbdGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<kbd
data-slot="kbd-group"
className={cn("inline-flex items-center gap-1", className)}
{...props}
/>
)
}
export { Kbd, KbdGroup }

View File

@@ -40,7 +40,7 @@ function TabsTrigger({
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] duration-200 focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
@@ -55,7 +55,13 @@ function TabsContent({
return (
<TabsPrimitive.Content
data-slot="tabs-content"
className={cn("flex-1 outline-none", className)}
className={cn(
"flex-1 outline-none",
"data-[state=active]:animate-in data-[state=inactive]:animate-out",
"data-[state=inactive]:fade-out-0 data-[state=active]:fade-in-0",
"duration-150",
className
)}
{...props}
/>
);

View File

@@ -706,6 +706,69 @@
"statusMonitoring": "Status",
"metricsMonitoring": "Metriken",
"terminalCustomizationNotice": "Hinweis: Terminal-Anpassungen funktionieren nur in der Desktop-Website-Version. Mobile und Electron-Apps verwenden die Standard-Terminaleinstellungen des Systems.",
"terminalCustomization": "Terminal-Anpassung",
"appearance": "Aussehen",
"behavior": "Verhalten",
"advanced": "Erweitert",
"themePreview": "Themen-Vorschau",
"theme": "Thema",
"selectTheme": "Thema auswählen",
"chooseColorTheme": "Wählen Sie ein Farbthema für das Terminal",
"fontFamily": "Schriftfamilie",
"selectFont": "Schriftart auswählen",
"selectFontDesc": "Wählen Sie die im Terminal zu verwendende Schriftart",
"fontSize": "Schriftgröße",
"fontSizeValue": "Schriftgröße: {{value}}px",
"adjustFontSize": "Terminal-Schriftgröße anpassen",
"letterSpacing": "Zeichenabstand",
"letterSpacingValue": "Zeichenabstand: {{value}}px",
"adjustLetterSpacing": "Abstand zwischen Zeichen anpassen",
"lineHeight": "Zeilenhöhe",
"lineHeightValue": "Zeilenhöhe: {{value}}",
"adjustLineHeight": "Abstand zwischen Zeilen anpassen",
"cursorStyle": "Cursor-Stil",
"selectCursorStyle": "Cursor-Stil auswählen",
"cursorStyleBlock": "Block",
"cursorStyleUnderline": "Unterstrich",
"cursorStyleBar": "Balken",
"chooseCursorAppearance": "Cursor-Erscheinungsbild wählen",
"cursorBlink": "Cursor-Blinken",
"enableCursorBlink": "Cursor-Blinkanimation aktivieren",
"scrollbackBuffer": "Rückwärts-Puffer",
"scrollbackBufferValue": "Rückwärts-Puffer: {{value}} Zeilen",
"scrollbackBufferDesc": "Anzahl der Zeilen im Rückwärtsverlauf",
"bellStyle": "Signalton-Stil",
"selectBellStyle": "Signalton-Stil auswählen",
"bellStyleNone": "Keine",
"bellStyleSound": "Ton",
"bellStyleVisual": "Visuell",
"bellStyleBoth": "Beides",
"bellStyleDesc": "Behandlung des Terminal-Signaltons (BEL-Zeichen, \\x07). Programme lösen dies aus, wenn Aufgaben abgeschlossen werden, Fehler auftreten oder für Benachrichtigungen. \"Ton\" spielt einen akustischen Signalton ab, \"Visuell\" lässt den Bildschirm kurz aufblinken, \"Beides\" macht beides, \"Keine\" deaktiviert Signalton-Benachrichtigungen.",
"rightClickSelectsWord": "Rechtsklick wählt Wort",
"rightClickSelectsWordDesc": "Rechtsklick wählt das Wort unter dem Cursor aus",
"fastScrollModifier": "Schnellscroll-Modifikator",
"selectModifier": "Modifikator auswählen",
"modifierAlt": "Alt",
"modifierCtrl": "Strg",
"modifierShift": "Umschalt",
"fastScrollModifierDesc": "Modifikatortaste für schnelles Scrollen",
"fastScrollSensitivity": "Schnellscroll-Empfindlichkeit",
"fastScrollSensitivityValue": "Schnellscroll-Empfindlichkeit: {{value}}",
"fastScrollSensitivityDesc": "Scroll-Geschwindigkeitsmultiplikator bei gedrücktem Modifikator",
"minimumContrastRatio": "Minimales Kontrastverhältnis",
"minimumContrastRatioValue": "Minimales Kontrastverhältnis: {{value}}",
"minimumContrastRatioDesc": "Farben automatisch für bessere Lesbarkeit anpassen",
"sshAgentForwarding": "SSH-Agent-Weiterleitung",
"sshAgentForwardingDesc": "SSH-Authentifizierungsagent an Remote-Host weiterleiten",
"backspaceMode": "Rücktaste-Modus",
"selectBackspaceMode": "Rücktaste-Modus auswählen",
"backspaceModeNormal": "Normal (DEL)",
"backspaceModeControlH": "Control-H (^H)",
"backspaceModeDesc": "Rücktasten-Verhalten für Kompatibilität",
"startupSnippet": "Start-Snippet",
"selectSnippet": "Snippet auswählen",
"searchSnippets": "Snippets durchsuchen...",
"snippetNone": "Keine",
"noneAuthTitle": "Keyboard-Interactive-Authentifizierung",
"noneAuthDescription": "Diese Authentifizierungsmethode verwendet beim Herstellen der Verbindung zum SSH-Server die Keyboard-Interactive-Authentifizierung.",
"noneAuthDetails": "Keyboard-Interactive-Authentifizierung ermöglicht dem Server, Sie während der Verbindung zur Eingabe von Anmeldeinformationen aufzufordern. Dies ist nützlich für Server, die eine Multi-Faktor-Authentifizierung oder eine dynamische Passworteingabe erfordern.",
@@ -1119,9 +1182,21 @@
"noInterfacesFound": "Keine Netzwerkschnittstellen gefunden",
"totalProcesses": "Gesamtprozesse",
"running": "läuft",
"noProcessesFound": "Keine Prozesse gefunden"
"noProcessesFound": "Keine Prozesse gefunden",
"loginStats": "SSH-Anmeldestatistiken",
"totalLogins": "Gesamtanmeldungen",
"uniqueIPs": "Eindeutige IPs",
"recentSuccessfulLogins": "Letzte erfolgreiche Anmeldungen",
"recentFailedAttempts": "Letzte fehlgeschlagene Versuche",
"noRecentLoginData": "Keine aktuellen Anmeldedaten",
"from": "von"
},
"auth": {
"tagline": "SSH TERMINAL MANAGER",
"description": "Sichere, leistungsstarke und intuitive SSH-Verbindungsverwaltung",
"welcomeBack": "Willkommen zurück bei TERMIX",
"createAccount": "Erstellen Sie Ihr TERMIX-Konto",
"continueExternal": "Mit externem Anbieter fortfahren",
"loginTitle": "Melden Sie sich bei Termix an",
"registerTitle": "Benutzerkonto erstellen",
"loginButton": "Anmelden",
@@ -1501,5 +1576,28 @@
"cpu": "CPU",
"ram": "RAM",
"notAvailable": "Nicht verfügbar"
},
"commandPalette": {
"searchPlaceholder": "Nach Hosts oder Schnellaktionen suchen...",
"recentActivity": "Kürzliche Aktivität",
"navigation": "Navigation",
"addHost": "Host hinzufügen",
"addCredential": "Anmeldedaten hinzufügen",
"adminSettings": "Admin-Einstellungen",
"userProfile": "Benutzerprofil",
"updateLog": "Aktualisierungsprotokoll",
"hosts": "Hosts",
"openServerDetails": "Serverdetails öffnen",
"openFileManager": "Dateimanager öffnen",
"edit": "Bearbeiten",
"links": "Links",
"github": "GitHub",
"support": "Support",
"discord": "Discord",
"donate": "Spenden",
"press": "Drücken Sie",
"toToggle": "zum Umschalten",
"close": "Schließen",
"hostManager": "Host-Manager"
}
}

View File

@@ -779,6 +779,69 @@
"statusMonitoring": "Status",
"metricsMonitoring": "Metrics",
"terminalCustomizationNotice": "Note: Terminal customizations only work on desktop (website and Electron app). Mobile apps and mobile website use system default terminal settings.",
"terminalCustomization": "Terminal Customization",
"appearance": "Appearance",
"behavior": "Behavior",
"advanced": "Advanced",
"themePreview": "Theme Preview",
"theme": "Theme",
"selectTheme": "Select theme",
"chooseColorTheme": "Choose a color theme for the terminal",
"fontFamily": "Font Family",
"selectFont": "Select font",
"selectFontDesc": "Select the font to use in the terminal",
"fontSize": "Font Size",
"fontSizeValue": "Font Size: {{value}}px",
"adjustFontSize": "Adjust the terminal font size",
"letterSpacing": "Letter Spacing",
"letterSpacingValue": "Letter Spacing: {{value}}px",
"adjustLetterSpacing": "Adjust spacing between characters",
"lineHeight": "Line Height",
"lineHeightValue": "Line Height: {{value}}",
"adjustLineHeight": "Adjust spacing between lines",
"cursorStyle": "Cursor Style",
"selectCursorStyle": "Select cursor style",
"cursorStyleBlock": "Block",
"cursorStyleUnderline": "Underline",
"cursorStyleBar": "Bar",
"chooseCursorAppearance": "Choose the cursor appearance",
"cursorBlink": "Cursor Blink",
"enableCursorBlink": "Enable cursor blinking animation",
"scrollbackBuffer": "Scrollback Buffer",
"scrollbackBufferValue": "Scrollback Buffer: {{value}} lines",
"scrollbackBufferDesc": "Number of lines to keep in scrollback history",
"bellStyle": "Bell Style",
"selectBellStyle": "Select bell style",
"bellStyleNone": "None",
"bellStyleSound": "Sound",
"bellStyleVisual": "Visual",
"bellStyleBoth": "Both",
"bellStyleDesc": "How to handle terminal bell (BEL character, \\x07). Programs trigger this when completing tasks, encountering errors, or for notifications. \"Sound\" plays an audio beep, \"Visual\" flashes the screen briefly, \"Both\" does both, \"None\" disables bell alerts.",
"rightClickSelectsWord": "Right Click Selects Word",
"rightClickSelectsWordDesc": "Right-clicking selects the word under cursor",
"fastScrollModifier": "Fast Scroll Modifier",
"selectModifier": "Select modifier",
"modifierAlt": "Alt",
"modifierCtrl": "Ctrl",
"modifierShift": "Shift",
"fastScrollModifierDesc": "Modifier key for fast scrolling",
"fastScrollSensitivity": "Fast Scroll Sensitivity",
"fastScrollSensitivityValue": "Fast Scroll Sensitivity: {{value}}",
"fastScrollSensitivityDesc": "Scroll speed multiplier when modifier is held",
"minimumContrastRatio": "Minimum Contrast Ratio",
"minimumContrastRatioValue": "Minimum Contrast Ratio: {{value}}",
"minimumContrastRatioDesc": "Automatically adjust colors for better readability",
"sshAgentForwarding": "SSH Agent Forwarding",
"sshAgentForwardingDesc": "Forward SSH authentication agent to remote host",
"backspaceMode": "Backspace Mode",
"selectBackspaceMode": "Select backspace mode",
"backspaceModeNormal": "Normal (DEL)",
"backspaceModeControlH": "Control-H (^H)",
"backspaceModeDesc": "Backspace key behavior for compatibility",
"startupSnippet": "Startup Snippet",
"selectSnippet": "Select snippet",
"searchSnippets": "Search snippets...",
"snippetNone": "None",
"noneAuthTitle": "Keyboard-Interactive Authentication",
"noneAuthDescription": "This authentication method will use keyboard-interactive authentication when connecting to the SSH server.",
"noneAuthDetails": "Keyboard-interactive authentication allows the server to prompt you for credentials during connection. This is useful for servers that require multi-factor authentication or if you do not want to save credentials locally.",
@@ -1231,9 +1294,21 @@
"noInterfacesFound": "No network interfaces found",
"totalProcesses": "Total Processes",
"running": "Running",
"noProcessesFound": "No processes found"
"noProcessesFound": "No processes found",
"loginStats": "SSH Login Statistics",
"totalLogins": "Total Logins",
"uniqueIPs": "Unique IPs",
"recentSuccessfulLogins": "Recent Successful Logins",
"recentFailedAttempts": "Recent Failed Attempts",
"noRecentLoginData": "No recent login data",
"from": "from"
},
"auth": {
"tagline": "SSH TERMINAL MANAGER",
"description": "Secure, powerful, and intuitive SSH connection management",
"welcomeBack": "Welcome back to TERMIX",
"createAccount": "Create your TERMIX account",
"continueExternal": "Continue with external provider",
"loginTitle": "Login to Termix",
"registerTitle": "Create Account",
"loginButton": "Login",
@@ -1622,5 +1697,28 @@
"cpu": "CPU",
"ram": "RAM",
"notAvailable": "N/A"
},
"commandPalette": {
"searchPlaceholder": "Search for hosts or quick actions...",
"recentActivity": "Recent Activity",
"navigation": "Navigation",
"addHost": "Add Host",
"addCredential": "Add Credential",
"adminSettings": "Admin Settings",
"userProfile": "User Profile",
"updateLog": "Update Log",
"hosts": "Hosts",
"openServerDetails": "Open Server Details",
"openFileManager": "Open File Manager",
"edit": "Edit",
"links": "Links",
"github": "GitHub",
"support": "Support",
"discord": "Discord",
"donate": "Donate",
"press": "Press",
"toToggle": "to toggle",
"close": "Close",
"hostManager": "Host Manager"
}
}

View File

@@ -1143,6 +1143,11 @@
"available": "Disponível"
},
"auth": {
"tagline": "GERENCIADOR DE TERMINAL SSH",
"description": "Gerenciamento de conexão SSH seguro, poderoso e intuitivo",
"welcomeBack": "Bem-vindo de volta ao TERMIX",
"createAccount": "Crie sua conta TERMIX",
"continueExternal": "Continuar com provedor externo",
"loginTitle": "Entrar no Termix",
"registerTitle": "Criar Conta",
"loginButton": "Entrar",

View File

@@ -766,6 +766,69 @@
"statusMonitoring": "Статус",
"metricsMonitoring": "Метрики",
"terminalCustomizationNotice": "Примечание: Настройки терминала работают только на рабочем столе (веб-сайт и Electron-приложение). Мобильные приложения и мобильный веб-сайт используют системные настройки терминала по умолчанию.",
"terminalCustomization": "Настройка терминала",
"appearance": "Внешний вид",
"behavior": "Поведение",
"advanced": "Расширенные",
"themePreview": "Предпросмотр темы",
"theme": "Тема",
"selectTheme": "Выбрать тему",
"chooseColorTheme": "Выберите цветовую тему для терминала",
"fontFamily": "Семейство шрифтов",
"selectFont": "Выбрать шрифт",
"selectFontDesc": "Выберите шрифт для использования в терминале",
"fontSize": "Размер шрифта",
"fontSizeValue": "Размер шрифта: {{value}}px",
"adjustFontSize": "Настроить размер шрифта терминала",
"letterSpacing": "Межбуквенный интервал",
"letterSpacingValue": "Межбуквенный интервал: {{value}}px",
"adjustLetterSpacing": "Настроить расстояние между символами",
"lineHeight": "Высота строки",
"lineHeightValue": "Высота строки: {{value}}",
"adjustLineHeight": "Настроить расстояние между строками",
"cursorStyle": "Стиль курсора",
"selectCursorStyle": "Выбрать стиль курсора",
"cursorStyleBlock": "Блок",
"cursorStyleUnderline": "Подчеркивание",
"cursorStyleBar": "Полоса",
"chooseCursorAppearance": "Выбрать внешний вид курсора",
"cursorBlink": "Мигание курсора",
"enableCursorBlink": "Включить анимацию мигания курсора",
"scrollbackBuffer": "Буфер прокрутки",
"scrollbackBufferValue": "Буфер прокрутки: {{value}} строк",
"scrollbackBufferDesc": "Количество строк для хранения в истории прокрутки",
"bellStyle": "Стиль звонка",
"selectBellStyle": "Выбрать стиль звонка",
"bellStyleNone": "Нет",
"bellStyleSound": "Звук",
"bellStyleVisual": "Визуальный",
"bellStyleBoth": "Оба",
"bellStyleDesc": "Как обрабатывать звонок терминала (символ BEL, \\x07). Программы вызывают его при завершении задач, возникновении ошибок или для уведомлений. \"Звук\" воспроизводит звуковой сигнал, \"Визуальный\" кратковременно мигает экран, \"Оба\" делает и то, и другое, \"Нет\" отключает звуковые оповещения.",
"rightClickSelectsWord": "Правый клик выбирает слово",
"rightClickSelectsWordDesc": "Правый клик выбирает слово под курсором",
"fastScrollModifier": "Модификатор быстрой прокрутки",
"selectModifier": "Выбрать модификатор",
"modifierAlt": "Alt",
"modifierCtrl": "Ctrl",
"modifierShift": "Shift",
"fastScrollModifierDesc": "Клавиша-модификатор для быстрой прокрутки",
"fastScrollSensitivity": "Чувствительность быстрой прокрутки",
"fastScrollSensitivityValue": "Чувствительность быстрой прокрутки: {{value}}",
"fastScrollSensitivityDesc": "Множитель скорости прокрутки при удержании модификатора",
"minimumContrastRatio": "Минимальная контрастность",
"minimumContrastRatioValue": "Минимальная контрастность: {{value}}",
"minimumContrastRatioDesc": "Автоматически настраивать цвета для лучшей читаемости",
"sshAgentForwarding": "Переадресация SSH-агента",
"sshAgentForwardingDesc": "Переадресовать агент SSH-аутентификации на удаленный хост",
"backspaceMode": "Режим Backspace",
"selectBackspaceMode": "Выбрать режим Backspace",
"backspaceModeNormal": "Обычный (DEL)",
"backspaceModeControlH": "Control-H (^H)",
"backspaceModeDesc": "Поведение клавиши Backspace для совместимости",
"startupSnippet": "Сниппет запуска",
"selectSnippet": "Выбрать сниппет",
"searchSnippets": "Поиск сниппетов...",
"snippetNone": "Нет",
"noneAuthTitle": "Интерактивная аутентификация по клавиатуре",
"noneAuthDescription": "Этот метод аутентификации будет использовать интерактивную аутентификацию по клавиатуре при подключении к SSH-серверу.",
"noneAuthDetails": "Интерактивная аутентификация по клавиатуре позволяет серверу запрашивать у вас учетные данные во время подключения. Это полезно для серверов, которые требуют многофакторную аутентификацию или динамический ввод пароля."
@@ -1215,9 +1278,21 @@
"noInterfacesFound": "Сетевые интерфейсы не найдены",
"totalProcesses": "Всего процессов",
"running": "Запущено",
"noProcessesFound": "Процессы не найдены"
"noProcessesFound": "Процессы не найдены",
"loginStats": "Статистика входов SSH",
"totalLogins": "Всего входов",
"uniqueIPs": "Уникальные IP",
"recentSuccessfulLogins": "Последние успешные входы",
"recentFailedAttempts": "Последние неудачные попытки",
"noRecentLoginData": "Нет данных о недавних входах",
"from": "с"
},
"auth": {
"tagline": "SSH ТЕРМИНАЛ МЕНЕДЖЕР",
"description": "Безопасное, мощное и интуитивное управление SSH-соединениями",
"welcomeBack": "Добро пожаловать обратно в TERMIX",
"createAccount": "Создайте вашу учетную запись TERMIX",
"continueExternal": "Продолжить с внешним провайдером",
"loginTitle": "Вход в Termix",
"registerTitle": "Создать учетную запись",
"loginButton": "Войти",
@@ -1587,5 +1662,28 @@
"cpu": "CPU",
"ram": "RAM",
"notAvailable": "N/A"
},
"commandPalette": {
"searchPlaceholder": "Поиск хостов или быстрых действий...",
"recentActivity": "Недавняя активность",
"navigation": "Навигация",
"addHost": "Добавить хост",
"addCredential": "Добавить учетные данные",
"adminSettings": "Настройки администратора",
"userProfile": "Профиль пользователя",
"updateLog": "Журнал обновлений",
"hosts": "Хосты",
"openServerDetails": "Открыть детали сервера",
"openFileManager": "Открыть файловый менеджер",
"edit": "Редактировать",
"links": "Ссылки",
"github": "GitHub",
"support": "Поддержка",
"discord": "Discord",
"donate": "Пожертвовать",
"press": "Нажмите",
"toToggle": "для переключения",
"close": "Закрыть",
"hostManager": "Менеджер хостов"
}
}

View File

@@ -790,6 +790,69 @@
"statusMonitoring": "状态",
"metricsMonitoring": "指标",
"terminalCustomizationNotice": "注意:终端自定义仅在桌面网站版本中有效。移动和 Electron 应用程序使用系统默认终端设置。",
"terminalCustomization": "终端自定义",
"appearance": "外观",
"behavior": "行为",
"advanced": "高级",
"themePreview": "主题预览",
"theme": "主题",
"selectTheme": "选择主题",
"chooseColorTheme": "选择终端的颜色主题",
"fontFamily": "字体系列",
"selectFont": "选择字体",
"selectFontDesc": "选择终端使用的字体",
"fontSize": "字体大小",
"fontSizeValue": "字体大小:{{value}}px",
"adjustFontSize": "调整终端字体大小",
"letterSpacing": "字母间距",
"letterSpacingValue": "字母间距:{{value}}px",
"adjustLetterSpacing": "调整字符之间的间距",
"lineHeight": "行高",
"lineHeightValue": "行高:{{value}}",
"adjustLineHeight": "调整行之间的间距",
"cursorStyle": "光标样式",
"selectCursorStyle": "选择光标样式",
"cursorStyleBlock": "块状",
"cursorStyleUnderline": "下划线",
"cursorStyleBar": "竖线",
"chooseCursorAppearance": "选择光标外观",
"cursorBlink": "光标闪烁",
"enableCursorBlink": "启用光标闪烁动画",
"scrollbackBuffer": "回滚缓冲区",
"scrollbackBufferValue": "回滚缓冲区:{{value}} 行",
"scrollbackBufferDesc": "保留在回滚历史记录中的行数",
"bellStyle": "铃声样式",
"selectBellStyle": "选择铃声样式",
"bellStyleNone": "无",
"bellStyleSound": "声音",
"bellStyleVisual": "视觉",
"bellStyleBoth": "两者",
"bellStyleDesc": "如何处理终端铃声BEL字符\\x07。程序在完成任务、遇到错误或通知时会触发此功能。\"声音\"播放音频提示音,\"视觉\"短暂闪烁屏幕,\"两者\"同时执行,\"无\"禁用铃声提醒。",
"rightClickSelectsWord": "右键选择单词",
"rightClickSelectsWordDesc": "右键单击选择光标下的单词",
"fastScrollModifier": "快速滚动修饰键",
"selectModifier": "选择修饰键",
"modifierAlt": "Alt",
"modifierCtrl": "Ctrl",
"modifierShift": "Shift",
"fastScrollModifierDesc": "快速滚动的修饰键",
"fastScrollSensitivity": "快速滚动灵敏度",
"fastScrollSensitivityValue": "快速滚动灵敏度:{{value}}",
"fastScrollSensitivityDesc": "按住修饰键时的滚动速度倍数",
"minimumContrastRatio": "最小对比度",
"minimumContrastRatioValue": "最小对比度:{{value}}",
"minimumContrastRatioDesc": "自动调整颜色以获得更好的可读性",
"sshAgentForwarding": "SSH 代理转发",
"sshAgentForwardingDesc": "将 SSH 身份验证代理转发到远程主机",
"backspaceMode": "退格模式",
"selectBackspaceMode": "选择退格模式",
"backspaceModeNormal": "正常 (DEL)",
"backspaceModeControlH": "Control-H (^H)",
"backspaceModeDesc": "退格键行为兼容性",
"startupSnippet": "启动代码片段",
"selectSnippet": "选择代码片段",
"searchSnippets": "搜索代码片段...",
"snippetNone": "无",
"noneAuthTitle": "键盘交互式认证",
"noneAuthDescription": "此认证方法在连接到 SSH 服务器时将使用键盘交互式认证。",
"noneAuthDetails": "键盘交互式认证允许服务器在连接期间提示您输入凭据。这对于需要多因素认证或动态密码输入的服务器很有用。",
@@ -1199,9 +1262,21 @@
"noInterfacesFound": "未找到网络接口",
"totalProcesses": "总进程数",
"running": "运行中",
"noProcessesFound": "未找到进程"
"noProcessesFound": "未找到进程",
"loginStats": "SSH 登录统计",
"totalLogins": "总登录次数",
"uniqueIPs": "唯一 IP 数",
"recentSuccessfulLogins": "最近成功登录",
"recentFailedAttempts": "最近失败尝试",
"noRecentLoginData": "无最近登录数据",
"from": "来自"
},
"auth": {
"tagline": "SSH 终端管理器",
"description": "安全、强大、直观的 SSH 连接管理",
"welcomeBack": "欢迎回到 TERMIX",
"createAccount": "创建您的 TERMIX 账户",
"continueExternal": "使用外部提供商继续",
"loginTitle": "登录 Termix",
"registerTitle": "创建账户",
"loginButton": "登录",
@@ -1512,5 +1587,28 @@
"cpu": "CPU",
"ram": "内存",
"notAvailable": "不可用"
},
"commandPalette": {
"searchPlaceholder": "搜索主机或快速操作...",
"recentActivity": "最近活动",
"navigation": "导航",
"addHost": "添加主机",
"addCredential": "添加凭据",
"adminSettings": "管理员设置",
"userProfile": "用户资料",
"updateLog": "更新日志",
"hosts": "主机",
"openServerDetails": "打开服务器详情",
"openFileManager": "打开文件管理器",
"edit": "编辑",
"links": "链接",
"github": "GitHub",
"support": "支持",
"discord": "Discord",
"donate": "捐赠",
"press": "按下",
"toToggle": "来切换",
"close": "关闭",
"hostManager": "主机管理器"
}
}

View File

@@ -5,7 +5,8 @@ export type WidgetType =
| "network"
| "uptime"
| "processes"
| "system";
| "system"
| "login_stats";
export interface StatsConfig {
enabledWidgets: WidgetType[];
@@ -16,7 +17,15 @@ export interface StatsConfig {
}
export const DEFAULT_STATS_CONFIG: StatsConfig = {
enabledWidgets: ["cpu", "memory", "disk", "network", "uptime", "system"],
enabledWidgets: [
"cpu",
"memory",
"disk",
"network",
"uptime",
"system",
"login_stats",
],
statusCheckEnabled: true,
statusCheckInterval: 30,
metricsEnabled: true,

View File

@@ -23,6 +23,8 @@ function AppContent() {
const saved = localStorage.getItem("topNavbarOpen");
return saved !== null ? JSON.parse(saved) : true;
});
const [isTransitioning, setIsTransitioning] = useState(false);
const [transitionPhase, setTransitionPhase] = useState<'idle' | 'fadeOut' | 'fadeIn'>('idle');
const { currentTab, tabs } = useTabs();
const [isCommandPaletteOpen, setIsCommandPaletteOpen] = useState(false);
@@ -98,13 +100,44 @@ function AppContent() {
username: string | null;
userId: string | null;
}) => {
setIsAuthenticated(true);
setIsAdmin(authData.isAdmin);
setUsername(authData.username);
setIsTransitioning(true);
setTransitionPhase('fadeOut');
setTimeout(() => {
setIsAuthenticated(true);
setIsAdmin(authData.isAdmin);
setUsername(authData.username);
setTransitionPhase('fadeIn');
setTimeout(() => {
setIsTransitioning(false);
setTransitionPhase('idle');
}, 800);
}, 1200);
},
[],
);
const handleLogout = useCallback(async () => {
setIsTransitioning(true);
setTransitionPhase('fadeOut');
setTimeout(async () => {
try {
const { logoutUser, isElectron } = await import("@/ui/main-axios.ts");
await logoutUser();
if (isElectron()) {
localStorage.removeItem("jwt");
}
} catch (error) {
console.error("Logout failed:", error);
}
window.location.reload();
}, 1200);
}, []);
const currentTabData = tabs.find((tab) => tab.id === currentTab);
const showTerminalView =
currentTabData?.type === "terminal" ||
@@ -135,11 +168,12 @@ function AppContent() {
{isAuthenticated && (
<LeftSidebar
onSelectView={handleSelectView}
disabled={!isAuthenticated || authLoading}
isAdmin={isAdmin}
username={username}
>
onSelectView={handleSelectView}
disabled={!isAuthenticated || authLoading}
isAdmin={isAdmin}
username={username}
onLogout={handleLogout}
>
<div
className="h-screen w-full visible pointer-events-auto static overflow-hidden"
style={{ display: showTerminalView ? "block" : "none" }}
@@ -189,6 +223,148 @@ function AppContent() {
/>
</LeftSidebar>
)}
{isTransitioning && (
<div
className={`fixed inset-0 bg-background z-[20000] transition-opacity duration-700 ${
transitionPhase === 'fadeOut' ? 'opacity-100' : 'opacity-0'
}`}
>
{transitionPhase === 'fadeOut' && (
<>
<div className="absolute inset-0 flex items-center justify-center overflow-hidden">
<div className="absolute w-0 h-0 bg-primary/10 rounded-full"
style={{
animation: 'ripple 2.5s cubic-bezier(0.4, 0, 0.2, 1) forwards',
animationDelay: '0ms'
}}
/>
<div className="absolute w-0 h-0 bg-primary/7 rounded-full"
style={{
animation: 'ripple 2.5s cubic-bezier(0.4, 0, 0.2, 1) forwards',
animationDelay: '200ms'
}}
/>
<div className="absolute w-0 h-0 bg-primary/5 rounded-full"
style={{
animation: 'ripple 2.5s cubic-bezier(0.4, 0, 0.2, 1) forwards',
animationDelay: '400ms'
}}
/>
<div className="absolute w-0 h-0 bg-primary/3 rounded-full"
style={{
animation: 'ripple 2.5s cubic-bezier(0.4, 0, 0.2, 1) forwards',
animationDelay: '600ms'
}}
/>
<div className="relative z-10 text-center"
style={{
animation: 'logoFade 1.6s cubic-bezier(0.4, 0, 0.2, 1) forwards'
}}>
<div className="text-7xl font-bold tracking-wider"
style={{
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
animation: 'logoGlow 1.6s cubic-bezier(0.4, 0, 0.2, 1) forwards'
}}>
TERMIX
</div>
<div className="text-sm text-muted-foreground mt-3 tracking-widest"
style={{
animation: 'subtitleFade 1.6s cubic-bezier(0.4, 0, 0.2, 1) forwards'
}}>
SSH TERMINAL MANAGER
</div>
</div>
</div>
<style>{`
@keyframes ripple {
0% {
width: 0;
height: 0;
opacity: 1;
}
30% {
opacity: 0.6;
}
70% {
opacity: 0.3;
}
100% {
width: 200vmax;
height: 200vmax;
opacity: 0;
}
}
@keyframes logoFade {
0% {
opacity: 0;
transform: scale(0.85);
filter: blur(8px);
}
25% {
opacity: 1;
transform: scale(1);
filter: blur(0px);
}
75% {
opacity: 1;
transform: scale(1);
filter: blur(0px);
}
100% {
opacity: 0;
transform: scale(1.05);
filter: blur(4px);
}
}
@keyframes logoGlow {
0% {
color: hsl(var(--primary));
text-shadow: none;
}
25% {
color: hsl(var(--primary));
text-shadow:
0 0 20px hsla(var(--primary), 0.3),
0 0 40px hsla(var(--primary), 0.2),
0 0 60px hsla(var(--primary), 0.1);
}
75% {
color: hsl(var(--primary));
text-shadow:
0 0 20px hsla(var(--primary), 0.3),
0 0 40px hsla(var(--primary), 0.2),
0 0 60px hsla(var(--primary), 0.1);
}
100% {
color: hsl(var(--primary));
text-shadow: none;
}
}
@keyframes subtitleFade {
0%, 30% {
opacity: 0;
transform: translateY(10px);
}
50% {
opacity: 1;
transform: translateY(0);
}
75% {
opacity: 1;
transform: translateY(0);
}
100% {
opacity: 0;
transform: translateY(-5px);
}
}
`}</style>
</>
)}
</div>
)}
<Toaster
position="bottom-right"
richColors={false}

View File

@@ -8,6 +8,7 @@ import {
} from "@/components/ui/command.tsx";
import React, { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
import { Kbd, KbdGroup } from "@/components/ui/kbd";
import {
Key,
Server,
@@ -19,6 +20,7 @@ import {
Pencil,
EllipsisVertical,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { BiMoney, BiSupport } from "react-icons/bi";
import { BsDiscord } from "react-icons/bs";
import { GrUpdate } from "react-icons/gr";
@@ -63,6 +65,7 @@ export function CommandPalette({
isOpen: boolean;
setIsOpen: (isOpen: boolean) => void;
}) {
const { t } = useTranslation();
const inputRef = useRef<HTMLInputElement>(null);
const { addTab, setCurrentTab, tabs: tabList, updateTab } = useTabs();
const [recentActivity, setRecentActivity] = useState<RecentActivityItem[]>(
@@ -90,7 +93,7 @@ export function CommandPalette({
} else {
const id = addTab({
type: "ssh_manager",
title: "Host Manager",
title: t("commandPalette.hostManager"),
initialTab: "add_host",
});
setCurrentTab(id);
@@ -106,7 +109,7 @@ export function CommandPalette({
} else {
const id = addTab({
type: "ssh_manager",
title: "Host Manager",
title: t("commandPalette.hostManager"),
initialTab: "add_credential",
});
setCurrentTab(id);
@@ -119,7 +122,7 @@ export function CommandPalette({
if (adminTab) {
setCurrentTab(adminTab.id);
} else {
const id = addTab({ type: "admin", title: "Admin Settings" });
const id = addTab({ type: "admin", title: t("commandPalette.adminSettings") });
setCurrentTab(id);
}
setIsOpen(false);
@@ -130,7 +133,7 @@ export function CommandPalette({
if (userProfileTab) {
setCurrentTab(userProfileTab.id);
} else {
const id = addTab({ type: "user_profile", title: "User Profile" });
const id = addTab({ type: "user_profile", title: t("commandPalette.userProfile") });
setCurrentTab(id);
}
setIsOpen(false);
@@ -213,7 +216,7 @@ export function CommandPalette({
: `${host.username}@${host.ip}:${host.port}`;
addTab({
type: "ssh_manager",
title: "Host Manager",
title: t("commandPalette.hostManager"),
hostConfig: host,
initialTab: "add_host",
});
@@ -223,18 +226,22 @@ export function CommandPalette({
return (
<div
className={cn(
"fixed inset-0 z-50 flex items-center justify-center bg-black/30",
!isOpen && "hidden",
"fixed inset-0 z-50 flex items-center justify-center bg-black/30 transition-opacity duration-200",
!isOpen && "opacity-0 pointer-events-none",
)}
onClick={() => setIsOpen(false)}
>
<Command
className="w-3/4 max-w-2xl max-h-[60vh] rounded-lg border-2 border-dark-border shadow-md flex flex-col"
className={cn(
"w-3/4 max-w-2xl max-h-[60vh] rounded-lg border-2 border-dark-border shadow-md flex flex-col",
"transition-all duration-200 ease-out",
!isOpen && "scale-95 opacity-0",
)}
onClick={(e) => e.stopPropagation()}
>
<CommandInput
ref={inputRef}
placeholder="Search for hosts or quick actions..."
placeholder={t("commandPalette.searchPlaceholder")}
/>
<CommandList
key={recentActivity.length}
@@ -243,7 +250,7 @@ export function CommandPalette({
>
{recentActivity.length > 0 && (
<>
<CommandGroup heading="Recent Activity">
<CommandGroup heading={t("commandPalette.recentActivity")}>
{recentActivity.map((item, index) => (
<CommandItem
key={`recent-activity-${index}-${item.type}-${item.hostId}-${item.timestamp}`}
@@ -258,30 +265,30 @@ export function CommandPalette({
<CommandSeparator />
</>
)}
<CommandGroup heading="Navigation">
<CommandGroup heading={t("commandPalette.navigation")}>
<CommandItem onSelect={handleAddHost}>
<Server />
<span>Add Host</span>
<span>{t("commandPalette.addHost")}</span>
</CommandItem>
<CommandItem onSelect={handleAddCredential}>
<Key />
<span>Add Credential</span>
<span>{t("commandPalette.addCredential")}</span>
</CommandItem>
<CommandItem onSelect={handleOpenAdminSettings}>
<Settings />
<span>Admin Settings</span>
<span>{t("commandPalette.adminSettings")}</span>
</CommandItem>
<CommandItem onSelect={handleOpenUserProfile}>
<User />
<span>User Profile</span>
<span>{t("commandPalette.userProfile")}</span>
</CommandItem>
<CommandItem onSelect={handleOpenUpdateLog}>
<GrUpdate />
<span>Update Log</span>
<span>{t("commandPalette.updateLog")}</span>
</CommandItem>
</CommandGroup>
<CommandSeparator />
<CommandGroup heading="Hosts">
<CommandGroup heading={t("commandPalette.hosts")}>
{hosts.map((host, index) => {
const title = host.name?.trim()
? host.name
@@ -328,7 +335,7 @@ export function CommandPalette({
className="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-dark-hover text-gray-300"
>
<Server className="h-4 w-4" />
<span className="flex-1">Open Server Details</span>
<span className="flex-1">{t("commandPalette.openServerDetails")}</span>
</DropdownMenuItem>
<DropdownMenuItem
onClick={(e) => {
@@ -338,7 +345,7 @@ export function CommandPalette({
className="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-dark-hover text-gray-300"
>
<FolderOpen className="h-4 w-4" />
<span className="flex-1">Open File Manager</span>
<span className="flex-1">{t("commandPalette.openFileManager")}</span>
</DropdownMenuItem>
<DropdownMenuItem
onClick={(e) => {
@@ -348,7 +355,7 @@ export function CommandPalette({
className="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-dark-hover text-gray-300"
>
<Pencil className="h-4 w-4" />
<span className="flex-1">Edit</span>
<span className="flex-1">{t("commandPalette.edit")}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -358,25 +365,39 @@ export function CommandPalette({
})}
</CommandGroup>
<CommandSeparator />
<CommandGroup heading="Links">
<CommandGroup heading={t("commandPalette.links")}>
<CommandItem onSelect={handleGitHub}>
<Github />
<span>GitHub</span>
<span>{t("commandPalette.github")}</span>
</CommandItem>
<CommandItem onSelect={handleSupport}>
<BiSupport />
<span>Support</span>
<span>{t("commandPalette.support")}</span>
</CommandItem>
<CommandItem onSelect={handleDiscord}>
<BsDiscord />
<span>Discord</span>
<span>{t("commandPalette.discord")}</span>
</CommandItem>
<CommandItem onSelect={handleDonate}>
<BiMoney />
<span>Donate</span>
<span>{t("commandPalette.donate")}</span>
</CommandItem>
</CommandGroup>
</CommandList>
<div className="border-t border-dark-border px-4 py-2 bg-dark-hover/50 flex items-center justify-between text-xs text-muted-foreground">
<div className="flex items-center gap-2">
<span>{t("commandPalette.press")}</span>
<KbdGroup>
<Kbd>Shift</Kbd>
<Kbd>Shift</Kbd>
</KbdGroup>
<span>{t("commandPalette.toToggle")}</span>
</div>
<div className="flex items-center gap-2">
<span>{t("commandPalette.close")}</span>
<Kbd>Esc</Kbd>
</div>
</div>
</Command>
</div>
);

View File

@@ -91,7 +91,9 @@ export function Dashboard({
try {
const sidebar = useSidebar();
sidebarState = sidebar.state;
} catch {}
} catch (error) {
console.error("Dashboard operation failed:", error);
}
const topMarginPx = isTopbarOpen ? 74 : 26;
const leftMarginPx = sidebarState === "collapsed" ? 26 : 8;
@@ -173,7 +175,9 @@ export function Dashboard({
if (Array.isArray(tunnelConnections)) {
totalTunnelsCount += tunnelConnections.length;
}
} catch {}
} catch (error) {
console.error("Dashboard operation failed:", error);
}
}
}
setTotalTunnels(totalTunnelsCount);
@@ -525,7 +529,7 @@ export function Dashboard({
</div>
</div>
</div>
<div className="flex-1 border-2 border-dark-border rounded-md bg-dark-bg-darker flex flex-col overflow-hidden">
<div className="flex-1 border-2 border-dark-border rounded-md bg-dark-bg-darker flex flex-col overflow-hidden transition-all duration-150 hover:border-primary/20">
<div className="flex flex-col mx-3 my-2 flex-1 overflow-hidden">
<div className="flex flex-row items-center justify-between mb-3 mt-1">
<p className="text-xl font-semibold flex flex-row items-center">
@@ -545,7 +549,7 @@ export function Dashboard({
className={`grid gap-4 grid-cols-[repeat(auto-fit,minmax(200px,1fr))] auto-rows-min overflow-x-hidden ${recentActivityLoading ? "overflow-y-hidden" : "overflow-y-auto"}`}
>
{recentActivityLoading ? (
<div className="flex flex-row items-center text-muted-foreground text-sm">
<div className="flex flex-row items-center text-muted-foreground text-sm animate-pulse">
<Loader2 className="animate-spin mr-2" size={16} />
<span>{t("dashboard.loadingRecentActivity")}</span>
</div>
@@ -577,7 +581,7 @@ export function Dashboard({
</div>
</div>
<div className="flex flex-row flex-1 gap-4 min-h-0">
<div className="flex-1 border-2 border-dark-border rounded-md bg-dark-bg-darker flex flex-col overflow-hidden">
<div className="flex-1 border-2 border-dark-border rounded-md bg-dark-bg-darker flex flex-col overflow-hidden transition-all duration-150 hover:border-primary/20">
<div className="flex flex-col mx-3 my-2 overflow-y-auto overflow-x-hidden">
<p className="text-xl font-semibold mb-3 mt-1 flex flex-row items-center">
<FastForward className="mr-3" />
@@ -641,7 +645,7 @@ export function Dashboard({
</div>
</div>
</div>
<div className="flex-1 border-2 border-dark-border rounded-md bg-dark-bg-darker flex flex-col overflow-hidden">
<div className="flex-1 border-2 border-dark-border rounded-md bg-dark-bg-darker flex flex-col overflow-hidden transition-all duration-150 hover:border-primary/20">
<div className="flex flex-col mx-3 my-2 flex-1 overflow-hidden">
<p className="text-xl font-semibold mb-3 mt-1 flex flex-row items-center">
<ChartLine className="mr-3" />
@@ -651,7 +655,7 @@ export function Dashboard({
className={`grid gap-4 grid-cols-[repeat(auto-fit,minmax(200px,1fr))] auto-rows-min overflow-x-hidden ${serverStatsLoading ? "overflow-y-hidden" : "overflow-y-auto"}`}
>
{serverStatsLoading ? (
<div className="flex flex-row items-center text-muted-foreground text-sm">
<div className="flex flex-row items-center text-muted-foreground text-sm animate-pulse">
<Loader2 className="animate-spin mr-2" size={16} />
<span>{t("dashboard.loadingServerStats")}</span>
</div>

View File

@@ -1907,6 +1907,8 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
createIntent={createIntent}
onConfirmCreate={handleConfirmCreate}
onCancelCreate={handleCancelCreate}
onNewFile={handleCreateNewFile}
onNewFolder={handleCreateNewFolder}
/>
<FileManagerContextMenu

View File

@@ -19,6 +19,7 @@ import {
Bookmark,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { Kbd, KbdGroup } from "@/components/ui/kbd";
interface FileItem {
name: string;
@@ -101,9 +102,15 @@ export function FileManagerContextMenu({
}: ContextMenuProps) {
const { t } = useTranslation();
const [menuPosition, setMenuPosition] = useState({ x, y });
const [isMounted, setIsMounted] = useState(false);
useEffect(() => {
if (!isVisible) return;
if (!isVisible) {
setIsMounted(false);
return;
}
setIsMounted(true);
const adjustPosition = () => {
const menuWidth = 200;
@@ -182,8 +189,6 @@ export function FileManagerContextMenu({
};
}, [isVisible, x, y, onClose]);
if (!isVisible) return null;
const isFileContext = files.length > 0;
const isSingleFile = files.length === 1;
const isMultipleFiles = files.length > 1;
@@ -425,13 +430,38 @@ export function FileManagerContextMenu({
return index > 0 && index < filteredMenuItems.length - 1;
});
const renderShortcut = (shortcut: string) => {
const keys = shortcut.split("+");
if (keys.length === 1) {
return <Kbd>{keys[0]}</Kbd>;
}
return (
<KbdGroup>
{keys.map((key, index) => (
<Kbd key={index}>{key}</Kbd>
))}
</KbdGroup>
);
};
if (!isVisible && !isMounted) return null;
return (
<>
<div className="fixed inset-0 z-[99990]" />
<div
className={cn(
"fixed inset-0 z-[99990] transition-opacity duration-150",
!isMounted && "opacity-0"
)}
/>
<div
data-context-menu
className="fixed bg-dark-bg border border-dark-border rounded-lg shadow-xl min-w-[180px] max-w-[250px] z-[99995] overflow-hidden"
className={cn(
"fixed bg-dark-bg border border-dark-border rounded-lg shadow-xl min-w-[180px] max-w-[250px] z-[99995] overflow-hidden",
"transition-all duration-150 ease-out origin-top-left",
isMounted ? "opacity-100 scale-100" : "opacity-0 scale-95"
)}
style={{
left: menuPosition.x,
top: menuPosition.y,
@@ -470,9 +500,9 @@ export function FileManagerContextMenu({
<span className="flex-1">{item.label}</span>
</div>
{item.shortcut && (
<span className="text-xs text-muted-foreground ml-2 flex-shrink-0">
{item.shortcut}
</span>
<div className="ml-2 flex-shrink-0">
{renderShortcut(item.shortcut)}
</div>
)}
</button>
);

View File

@@ -92,6 +92,8 @@ interface FileManagerGridProps {
createIntent?: CreateIntent | null;
onConfirmCreate?: (name: string) => void;
onCancelCreate?: () => void;
onNewFile?: () => void;
onNewFolder?: () => void;
}
const getFileIcon = (file: FileItem, viewMode: "grid" | "list" = "grid") => {
@@ -192,6 +194,8 @@ export function FileManagerGrid({
createIntent,
onConfirmCreate,
onCancelCreate,
onNewFile,
onNewFolder,
}: FileManagerGridProps) {
const { t } = useTranslation();
const gridRef = useRef<HTMLDivElement>(null);
@@ -772,6 +776,42 @@ export function FileManagerGrid({
onUndo();
}
break;
case "d":
case "D":
if (
(event.ctrlKey || event.metaKey) &&
selectedFiles.length > 0 &&
onDownload
) {
event.preventDefault();
onDownload(selectedFiles);
}
break;
case "n":
case "N":
if (event.ctrlKey || event.metaKey) {
event.preventDefault();
if (event.shiftKey && onNewFolder) {
onNewFolder();
} else if (!event.shiftKey && onNewFile) {
onNewFile();
}
}
break;
case "u":
case "U":
if ((event.ctrlKey || event.metaKey) && onUpload) {
event.preventDefault();
const input = document.createElement("input");
input.type = "file";
input.multiple = true;
input.onchange = (e) => {
const files = (e.target as HTMLInputElement).files;
if (files) onUpload(files);
};
input.click();
}
break;
case "Delete":
if (selectedFiles.length > 0 && onDelete) {
onDelete(selectedFiles);
@@ -783,6 +823,12 @@ export function FileManagerGrid({
onStartEdit(selectedFiles[0]);
}
break;
case "Enter":
if (selectedFiles.length === 1) {
event.preventDefault();
onFileOpen(selectedFiles[0]);
}
break;
case "y":
case "Y":
if (event.ctrlKey || event.metaKey) {
@@ -1003,8 +1049,9 @@ export function FileManagerGrid({
draggable={true}
className={cn(
"group p-3 rounded-lg cursor-pointer",
"hover:bg-accent hover:text-accent-foreground border-2 border-transparent",
isSelected && "bg-primary/20 border-primary",
"transition-all duration-150 ease-out",
"hover:bg-accent hover:text-accent-foreground hover:scale-[1.02] border-2 border-transparent",
isSelected && "bg-primary/20 border-primary ring-2 ring-primary/20",
dragState.target?.path === file.path &&
"bg-muted border-primary border-dashed relative z-10",
dragState.files.some((f) => f.path === file.path) &&
@@ -1092,8 +1139,9 @@ export function FileManagerGrid({
draggable={true}
className={cn(
"flex items-center gap-3 p-2 rounded cursor-pointer",
"transition-all duration-150 ease-out",
"hover:bg-accent hover:text-accent-foreground",
isSelected && "bg-primary/20",
isSelected && "bg-primary/20 ring-2 ring-primary/20",
dragState.target?.path === file.path &&
"bg-muted border-primary border-dashed relative z-10",
dragState.files.some((f) => f.path === file.path) &&

View File

@@ -167,7 +167,9 @@ export function HostManagerEditor({
setFolders(uniqueFolders);
setSshConfigurations(uniqueConfigurations);
} catch {}
} catch (error) {
console.error("Host manager operation failed:", error);
}
};
fetchData();
@@ -196,7 +198,9 @@ export function HostManagerEditor({
setFolders(uniqueFolders);
setSshConfigurations(uniqueConfigurations);
} catch {}
} catch (error) {
console.error("Host manager operation failed:", error);
}
};
window.addEventListener("credentials:changed", handleCredentialChange);
@@ -262,9 +266,18 @@ export function HostManagerEditor({
"uptime",
"processes",
"system",
"login_stats",
]),
)
.default(["cpu", "memory", "disk", "network", "uptime", "system"]),
.default([
"cpu",
"memory",
"disk",
"network",
"uptime",
"system",
"login_stats",
]),
statusCheckEnabled: z.boolean().default(true),
statusCheckInterval: z.number().min(5).max(3600).default(30),
metricsEnabled: z.boolean().default(true),
@@ -278,6 +291,7 @@ export function HostManagerEditor({
"network",
"uptime",
"system",
"login_stats",
],
statusCheckEnabled: true,
statusCheckInterval: 30,
@@ -1399,15 +1413,15 @@ export function HostManagerEditor({
</AlertDescription>
</Alert>
<h1 className="text-xl font-semibold mt-7">
Terminal Customization
{t("hosts.terminalCustomization")}
</h1>
<Accordion type="multiple" className="w-full">
<AccordionItem value="appearance">
<AccordionTrigger>Appearance</AccordionTrigger>
<AccordionTrigger>{t("hosts.appearance")}</AccordionTrigger>
<AccordionContent className="space-y-4 pt-4">
<div className="space-y-2">
<label className="text-sm font-medium">
Theme Preview
{t("hosts.themePreview")}
</label>
<TerminalPreview
theme={form.watch("terminalConfig.theme")}
@@ -1431,14 +1445,14 @@ export function HostManagerEditor({
name="terminalConfig.theme"
render={({ field }) => (
<FormItem>
<FormLabel>Theme</FormLabel>
<FormLabel>{t("hosts.theme")}</FormLabel>
<Select
onValueChange={field.onChange}
value={field.value}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select theme" />
<SelectValue placeholder={t("hosts.selectTheme")} />
</SelectTrigger>
</FormControl>
<SelectContent>
@@ -1452,7 +1466,7 @@ export function HostManagerEditor({
</SelectContent>
</Select>
<FormDescription>
Choose a color theme for the terminal
{t("hosts.chooseColorTheme")}
</FormDescription>
</FormItem>
)}
@@ -1463,14 +1477,14 @@ export function HostManagerEditor({
name="terminalConfig.fontFamily"
render={({ field }) => (
<FormItem>
<FormLabel>Font Family</FormLabel>
<FormLabel>{t("hosts.fontFamily")}</FormLabel>
<Select
onValueChange={field.onChange}
value={field.value}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select font" />
<SelectValue placeholder={t("hosts.selectFont")} />
</SelectTrigger>
</FormControl>
<SelectContent>
@@ -1485,7 +1499,7 @@ export function HostManagerEditor({
</SelectContent>
</Select>
<FormDescription>
Select the font to use in the terminal
{t("hosts.selectFontDesc")}
</FormDescription>
</FormItem>
)}
@@ -1496,7 +1510,7 @@ export function HostManagerEditor({
name="terminalConfig.fontSize"
render={({ field }) => (
<FormItem>
<FormLabel>Font Size: {field.value}px</FormLabel>
<FormLabel>{t("hosts.fontSizeValue", { value: field.value })}</FormLabel>
<FormControl>
<Slider
min={8}
@@ -1509,7 +1523,7 @@ export function HostManagerEditor({
/>
</FormControl>
<FormDescription>
Adjust the terminal font size
{t("hosts.adjustFontSize")}
</FormDescription>
</FormItem>
)}
@@ -1521,7 +1535,7 @@ export function HostManagerEditor({
render={({ field }) => (
<FormItem>
<FormLabel>
Letter Spacing: {field.value}px
{t("hosts.letterSpacingValue", { value: field.value })}
</FormLabel>
<FormControl>
<Slider
@@ -1535,7 +1549,7 @@ export function HostManagerEditor({
/>
</FormControl>
<FormDescription>
Adjust spacing between characters
{t("hosts.adjustLetterSpacing")}
</FormDescription>
</FormItem>
)}
@@ -1546,7 +1560,7 @@ export function HostManagerEditor({
name="terminalConfig.lineHeight"
render={({ field }) => (
<FormItem>
<FormLabel>Line Height: {field.value}</FormLabel>
<FormLabel>{t("hosts.lineHeightValue", { value: field.value })}</FormLabel>
<FormControl>
<Slider
min={1}
@@ -1559,7 +1573,7 @@ export function HostManagerEditor({
/>
</FormControl>
<FormDescription>
Adjust spacing between lines
{t("hosts.adjustLineHeight")}
</FormDescription>
</FormItem>
)}
@@ -1570,26 +1584,26 @@ export function HostManagerEditor({
name="terminalConfig.cursorStyle"
render={({ field }) => (
<FormItem>
<FormLabel>Cursor Style</FormLabel>
<FormLabel>{t("hosts.cursorStyle")}</FormLabel>
<Select
onValueChange={field.onChange}
value={field.value}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select cursor style" />
<SelectValue placeholder={t("hosts.selectCursorStyle")} />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="block">Block</SelectItem>
<SelectItem value="block">{t("hosts.cursorStyleBlock")}</SelectItem>
<SelectItem value="underline">
Underline
{t("hosts.cursorStyleUnderline")}
</SelectItem>
<SelectItem value="bar">Bar</SelectItem>
<SelectItem value="bar">{t("hosts.cursorStyleBar")}</SelectItem>
</SelectContent>
</Select>
<FormDescription>
Choose the cursor appearance
{t("hosts.chooseCursorAppearance")}
</FormDescription>
</FormItem>
)}
@@ -1601,9 +1615,9 @@ export function HostManagerEditor({
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3">
<div className="space-y-0.5">
<FormLabel>Cursor Blink</FormLabel>
<FormLabel>{t("hosts.cursorBlink")}</FormLabel>
<FormDescription>
Enable cursor blinking animation
{t("hosts.enableCursorBlink")}
</FormDescription>
</div>
<FormControl>
@@ -1619,7 +1633,7 @@ export function HostManagerEditor({
</AccordionItem>
<AccordionItem value="behavior">
<AccordionTrigger>Behavior</AccordionTrigger>
<AccordionTrigger>{t("hosts.behavior")}</AccordionTrigger>
<AccordionContent className="space-y-4 pt-4">
<FormField
control={form.control}
@@ -1627,7 +1641,7 @@ export function HostManagerEditor({
render={({ field }) => (
<FormItem>
<FormLabel>
Scrollback Buffer: {field.value} lines
{t("hosts.scrollbackBufferValue", { value: field.value })}
</FormLabel>
<FormControl>
<Slider
@@ -1641,7 +1655,7 @@ export function HostManagerEditor({
/>
</FormControl>
<FormDescription>
Number of lines to keep in scrollback history
{t("hosts.scrollbackBufferDesc")}
</FormDescription>
</FormItem>
)}
@@ -1652,30 +1666,25 @@ export function HostManagerEditor({
name="terminalConfig.bellStyle"
render={({ field }) => (
<FormItem>
<FormLabel>Bell Style</FormLabel>
<FormLabel>{t("hosts.bellStyle")}</FormLabel>
<Select
onValueChange={field.onChange}
value={field.value}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select bell style" />
<SelectValue placeholder={t("hosts.selectBellStyle")} />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="none">None</SelectItem>
<SelectItem value="sound">Sound</SelectItem>
<SelectItem value="visual">Visual</SelectItem>
<SelectItem value="both">Both</SelectItem>
<SelectItem value="none">{t("hosts.bellStyleNone")}</SelectItem>
<SelectItem value="sound">{t("hosts.bellStyleSound")}</SelectItem>
<SelectItem value="visual">{t("hosts.bellStyleVisual")}</SelectItem>
<SelectItem value="both">{t("hosts.bellStyleBoth")}</SelectItem>
</SelectContent>
</Select>
<FormDescription>
How to handle terminal bell (BEL character,
\x07). Programs trigger this when completing
tasks, encountering errors, or for
notifications. "Sound" plays an audio beep,
"Visual" flashes the screen briefly, "Both" does
both, "None" disables bell alerts.
{t("hosts.bellStyleDesc")}
</FormDescription>
</FormItem>
)}
@@ -1687,9 +1696,9 @@ export function HostManagerEditor({
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3">
<div className="space-y-0.5">
<FormLabel>Right Click Selects Word</FormLabel>
<FormLabel>{t("hosts.rightClickSelectsWord")}</FormLabel>
<FormDescription>
Right-clicking selects the word under cursor
{t("hosts.rightClickSelectsWordDesc")}
</FormDescription>
</div>
<FormControl>
@@ -1707,24 +1716,24 @@ export function HostManagerEditor({
name="terminalConfig.fastScrollModifier"
render={({ field }) => (
<FormItem>
<FormLabel>Fast Scroll Modifier</FormLabel>
<FormLabel>{t("hosts.fastScrollModifier")}</FormLabel>
<Select
onValueChange={field.onChange}
value={field.value}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select modifier" />
<SelectValue placeholder={t("hosts.selectModifier")} />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="alt">Alt</SelectItem>
<SelectItem value="ctrl">Ctrl</SelectItem>
<SelectItem value="shift">Shift</SelectItem>
<SelectItem value="alt">{t("hosts.modifierAlt")}</SelectItem>
<SelectItem value="ctrl">{t("hosts.modifierCtrl")}</SelectItem>
<SelectItem value="shift">{t("hosts.modifierShift")}</SelectItem>
</SelectContent>
</Select>
<FormDescription>
Modifier key for fast scrolling
{t("hosts.fastScrollModifierDesc")}
</FormDescription>
</FormItem>
)}
@@ -1736,7 +1745,7 @@ export function HostManagerEditor({
render={({ field }) => (
<FormItem>
<FormLabel>
Fast Scroll Sensitivity: {field.value}
{t("hosts.fastScrollSensitivityValue", { value: field.value })}
</FormLabel>
<FormControl>
<Slider
@@ -1750,7 +1759,7 @@ export function HostManagerEditor({
/>
</FormControl>
<FormDescription>
Scroll speed multiplier when modifier is held
{t("hosts.fastScrollSensitivityDesc")}
</FormDescription>
</FormItem>
)}
@@ -1762,7 +1771,7 @@ export function HostManagerEditor({
render={({ field }) => (
<FormItem>
<FormLabel>
Minimum Contrast Ratio: {field.value}
{t("hosts.minimumContrastRatioValue", { value: field.value })}
</FormLabel>
<FormControl>
<Slider
@@ -1776,8 +1785,7 @@ export function HostManagerEditor({
/>
</FormControl>
<FormDescription>
Automatically adjust colors for better
readability
{t("hosts.minimumContrastRatioDesc")}
</FormDescription>
</FormItem>
)}
@@ -1786,7 +1794,7 @@ export function HostManagerEditor({
</AccordionItem>
<AccordionItem value="advanced">
<AccordionTrigger>Advanced</AccordionTrigger>
<AccordionTrigger>{t("hosts.advanced")}</AccordionTrigger>
<AccordionContent className="space-y-4 pt-4">
<FormField
control={form.control}
@@ -1794,10 +1802,9 @@ export function HostManagerEditor({
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3">
<div className="space-y-0.5">
<FormLabel>SSH Agent Forwarding</FormLabel>
<FormLabel>{t("hosts.sshAgentForwarding")}</FormLabel>
<FormDescription>
Forward SSH authentication agent to remote
host
{t("hosts.sshAgentForwardingDesc")}
</FormDescription>
</div>
<FormControl>
@@ -1815,27 +1822,27 @@ export function HostManagerEditor({
name="terminalConfig.backspaceMode"
render={({ field }) => (
<FormItem>
<FormLabel>Backspace Mode</FormLabel>
<FormLabel>{t("hosts.backspaceMode")}</FormLabel>
<Select
onValueChange={field.onChange}
value={field.value}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select backspace mode" />
<SelectValue placeholder={t("hosts.selectBackspaceMode")} />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="normal">
Normal (DEL)
{t("hosts.backspaceModeNormal")}
</SelectItem>
<SelectItem value="control-h">
Control-H (^H)
{t("hosts.backspaceModeControlH")}
</SelectItem>
</SelectContent>
</Select>
<FormDescription>
Backspace key behavior for compatibility
{t("hosts.backspaceModeDesc")}
</FormDescription>
</FormItem>
)}
@@ -1846,7 +1853,7 @@ export function HostManagerEditor({
name="terminalConfig.startupSnippetId"
render={({ field }) => (
<FormItem>
<FormLabel>Startup Snippet</FormLabel>
<FormLabel>{t("hosts.startupSnippet")}</FormLabel>
<Select
onValueChange={(value) => {
field.onChange(
@@ -1858,13 +1865,13 @@ export function HostManagerEditor({
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select snippet" />
<SelectValue placeholder={t("hosts.selectSnippet")} />
</SelectTrigger>
</FormControl>
<SelectContent>
<div className="px-2 pb-2 sticky top-0 bg-popover z-10">
<Input
placeholder="Search snippets..."
placeholder={t("hosts.searchSnippets")}
value={snippetSearch}
onChange={(e) =>
setSnippetSearch(e.target.value)
@@ -1875,7 +1882,7 @@ export function HostManagerEditor({
/>
</div>
<div className="max-h-[200px] overflow-y-auto">
<SelectItem value="none">None</SelectItem>
<SelectItem value="none">{t("hosts.snippetNone")}</SelectItem>
{snippets
.filter((snippet) =>
snippet.name
@@ -2657,6 +2664,7 @@ export function HostManagerEditor({
"uptime",
"processes",
"system",
"login_stats",
] as const
).map((widget) => (
<div
@@ -2696,6 +2704,8 @@ export function HostManagerEditor({
t("serverStats.processes")}
{widget === "system" &&
t("serverStats.systemInfo")}
{widget === "login_stats" &&
t("serverStats.loginStats")}
</label>
</div>
))}

View File

@@ -25,6 +25,7 @@ import {
UptimeWidget,
ProcessesWidget,
SystemWidget,
LoginStatsWidget,
} from "./widgets";
interface HostConfig {
@@ -137,6 +138,11 @@ export function Server({
<SystemWidget metrics={metrics} metricsHistory={metricsHistory} />
);
case "login_stats":
return (
<LoginStatsWidget metrics={metrics} metricsHistory={metricsHistory} />
);
default:
return null;
}

View File

@@ -0,0 +1,138 @@
import React from "react";
import { UserCheck, UserX, MapPin, Activity } from "lucide-react";
import { useTranslation } from "react-i18next";
interface LoginRecord {
user: string;
ip: string;
time: string;
status: "success" | "failed";
}
interface LoginStatsMetrics {
recentLogins: LoginRecord[];
failedLogins: LoginRecord[];
totalLogins: number;
uniqueIPs: number;
}
interface ServerMetrics {
login_stats?: LoginStatsMetrics;
}
interface LoginStatsWidgetProps {
metrics: ServerMetrics | null;
metricsHistory: ServerMetrics[];
}
export function LoginStatsWidget({
metrics,
}: LoginStatsWidgetProps) {
const { t } = useTranslation();
const loginStats = metrics?.login_stats;
const recentLogins = loginStats?.recentLogins || [];
const failedLogins = loginStats?.failedLogins || [];
const totalLogins = loginStats?.totalLogins || 0;
const uniqueIPs = loginStats?.uniqueIPs || 0;
return (
<div className="h-full w-full p-4 rounded-lg bg-dark-bg/50 border border-dark-border/50 hover:bg-dark-bg/70 transition-colors duration-200 flex flex-col overflow-hidden">
<div className="flex items-center gap-2 flex-shrink-0 mb-3">
<UserCheck className="h-5 w-5 text-green-400" />
<h3 className="font-semibold text-lg text-white">
{t("serverStats.loginStats")}
</h3>
</div>
<div className="flex flex-col flex-1 min-h-0 gap-3">
<div className="grid grid-cols-2 gap-2 flex-shrink-0">
<div className="bg-dark-bg-darker p-2 rounded border border-dark-border/30">
<div className="flex items-center gap-1 text-xs text-gray-400 mb-1">
<Activity className="h-3 w-3" />
<span>{t("serverStats.totalLogins")}</span>
</div>
<div className="text-xl font-bold text-green-400">{totalLogins}</div>
</div>
<div className="bg-dark-bg-darker p-2 rounded border border-dark-border/30">
<div className="flex items-center gap-1 text-xs text-gray-400 mb-1">
<MapPin className="h-3 w-3" />
<span>{t("serverStats.uniqueIPs")}</span>
</div>
<div className="text-xl font-bold text-blue-400">{uniqueIPs}</div>
</div>
</div>
<div className="flex-1 min-h-0 overflow-y-auto space-y-2">
<div className="flex-shrink-0">
<div className="flex items-center gap-2 mb-1">
<UserCheck className="h-4 w-4 text-green-400" />
<span className="text-sm font-semibold text-gray-300">
{t("serverStats.recentSuccessfulLogins")}
</span>
</div>
{recentLogins.length === 0 ? (
<div className="text-xs text-gray-500 italic p-2">
{t("serverStats.noRecentLoginData")}
</div>
) : (
<div className="space-y-1">
{recentLogins.slice(0, 5).map((login, idx) => (
<div
key={idx}
className="text-xs bg-dark-bg-darker p-2 rounded border border-dark-border/30 flex justify-between items-center"
>
<div className="flex items-center gap-2 min-w-0">
<span className="text-green-400 font-mono truncate">
{login.user}
</span>
<span className="text-gray-500">{t("serverStats.from")}</span>
<span className="text-blue-400 font-mono truncate">
{login.ip}
</span>
</div>
<span className="text-gray-500 text-[10px] flex-shrink-0 ml-2">
{new Date(login.time).toLocaleString()}
</span>
</div>
))}
</div>
)}
</div>
{failedLogins.length > 0 && (
<div className="flex-shrink-0">
<div className="flex items-center gap-2 mb-1">
<UserX className="h-4 w-4 text-red-400" />
<span className="text-sm font-semibold text-gray-300">
{t("serverStats.recentFailedAttempts")}
</span>
</div>
<div className="space-y-1">
{failedLogins.slice(0, 3).map((login, idx) => (
<div
key={idx}
className="text-xs bg-red-900/20 p-2 rounded border border-red-500/30 flex justify-between items-center"
>
<div className="flex items-center gap-2 min-w-0">
<span className="text-red-400 font-mono truncate">
{login.user}
</span>
<span className="text-gray-500">{t("serverStats.from")}</span>
<span className="text-blue-400 font-mono truncate">
{login.ip}
</span>
</div>
<span className="text-gray-500 text-[10px] flex-shrink-0 ml-2">
{new Date(login.time).toLocaleString()}
</span>
</div>
))}
</div>
</div>
)}
</div>
</div>
</div>
);
}

View File

@@ -5,3 +5,4 @@ export { NetworkWidget } from "./NetworkWidget";
export { UptimeWidget } from "./UptimeWidget";
export { ProcessesWidget } from "./ProcessesWidget";
export { SystemWidget } from "./SystemWidget";
export { LoginStatsWidget } from "./LoginStatsWidget";

View File

@@ -194,7 +194,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
terminal as { refresh?: (start: number, end: number) => void }
).refresh(0, terminal.rows - 1);
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
}
function performFit() {
@@ -336,7 +338,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
scheduleNotify(cols, rows);
hardRefresh();
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
},
refresh: () => hardRefresh(),
}),
@@ -746,7 +750,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
await navigator.clipboard.writeText(text);
return;
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.position = "fixed";
@@ -766,7 +772,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
if (navigator.clipboard && navigator.clipboard.readText) {
return await navigator.clipboard.readText();
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
return "";
}
@@ -863,7 +871,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
const pasteText = await readTextFromClipboard();
if (pasteText) terminal.paste(pasteText);
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
};
element?.addEventListener("contextmenu", handleContextMenu);

View File

@@ -5,6 +5,7 @@ import { Input } from "@/components/ui/input.tsx";
import { PasswordInput } from "@/components/ui/password-input.tsx";
import { Label } from "@/components/ui/label.tsx";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert.tsx";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs.tsx";
import { useTranslation } from "react-i18next";
import { LanguageSwitcher } from "@/ui/desktop/user/LanguageSwitcher.tsx";
import { toast } from "sonner";
@@ -679,7 +680,7 @@ export function Auth({
if (showServerConfig === null && !isInElectronWebView()) {
return (
<div
className={`w-[420px] max-w-full p-6 flex flex-col bg-dark-bg border-2 border-dark-border rounded-md overflow-y-auto my-2 ${className || ""}`}
className={`w-[420px] max-w-full p-6 flex flex-col bg-dark-bg border-2 border-dark-border rounded-md overflow-y-auto my-2 animate-in fade-in zoom-in-95 duration-300 ${className || ""}`}
style={{ maxHeight: "calc(100vh - 1rem)" }}
{...props}
>
@@ -693,7 +694,7 @@ export function Auth({
if (showServerConfig && !isInElectronWebView()) {
return (
<div
className={`w-[420px] max-w-full p-6 flex flex-col bg-dark-bg border-2 border-dark-border rounded-md overflow-y-auto my-2 ${className || ""}`}
className={`w-[420px] max-w-full p-6 flex flex-col bg-dark-bg border-2 border-dark-border rounded-md overflow-y-auto my-2 animate-in fade-in zoom-in-95 duration-300 ${className || ""}`}
style={{ maxHeight: "calc(100vh - 1rem)" }}
{...props}
>
@@ -718,7 +719,7 @@ export function Auth({
) {
return (
<div
className={`w-[420px] max-w-full p-6 flex flex-col bg-dark-bg border-2 border-dark-border rounded-md overflow-y-auto my-2 ${className || ""}`}
className={`w-[420px] max-w-full p-6 flex flex-col bg-dark-bg border-2 border-dark-border rounded-md overflow-y-auto my-2 animate-in fade-in zoom-in-95 duration-300 ${className || ""}`}
style={{ maxHeight: "calc(100vh - 1rem)" }}
{...props}
>
@@ -751,7 +752,7 @@ export function Auth({
if (dbHealthChecking && !dbConnectionFailed) {
return (
<div
className={`w-[420px] max-w-full p-6 flex flex-col bg-dark-bg border-2 border-dark-border rounded-md overflow-y-auto my-2 ${className || ""}`}
className={`w-[420px] max-w-full p-6 flex flex-col bg-dark-bg border-2 border-dark-border rounded-md overflow-y-auto my-2 animate-in fade-in zoom-in-95 duration-300 ${className || ""}`}
style={{ maxHeight: "calc(100vh - 1rem)" }}
{...props}
>
@@ -770,7 +771,7 @@ export function Auth({
if (dbConnectionFailed) {
return (
<div
className={`w-[420px] max-w-full p-6 flex flex-col bg-dark-bg border-2 border-dark-border rounded-md overflow-y-auto my-2 ${className || ""}`}
className={`w-[420px] max-w-full p-6 flex flex-col bg-dark-bg border-2 border-dark-border rounded-md overflow-y-auto my-2 animate-in fade-in zoom-in-95 duration-300 ${className || ""}`}
style={{ maxHeight: "calc(100vh - 1rem)" }}
{...props}
>
@@ -830,10 +831,50 @@ export function Auth({
return (
<div
className={`w-[420px] max-w-full p-6 flex flex-col bg-dark-bg border-2 border-dark-border rounded-md overflow-y-auto my-2 ${className || ""}`}
style={{ maxHeight: "calc(100vh - 1rem)" }}
className={`fixed inset-0 flex items-center justify-center ${className || ""}`}
{...props}
>
{/* Split Screen Layout */}
<div className="w-full h-full flex flex-col md:flex-row">
{/* Left Side - Brand Showcase */}
<div
className="hidden md:flex md:w-2/5 items-center justify-center relative"
style={{
background: '#0e0e10',
backgroundImage: `repeating-linear-gradient(
45deg,
transparent,
transparent 35px,
rgba(255, 255, 255, 0.03) 35px,
rgba(255, 255, 255, 0.03) 37px
)`
}}
>
{/* Logo and Branding */}
<div className="relative text-center px-8">
<div
className="text-7xl font-bold tracking-wider mb-4 text-foreground"
style={{
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace'
}}
>
TERMIX
</div>
<div className="text-lg text-muted-foreground tracking-widest font-light">
{t("auth.tagline") || "SSH TERMINAL MANAGER"}
</div>
<div className="mt-8 text-sm text-muted-foreground/80 max-w-md">
{t("auth.description") || "Secure, powerful, and intuitive SSH connection management"}
</div>
</div>
</div>
{/* Right Side - Auth Form */}
<div className="flex-1 flex items-center justify-center p-6 md:p-12 bg-background overflow-y-auto">
<div className="w-full max-w-md backdrop-blur-sm bg-card/50 rounded-2xl p-8 shadow-xl border-2 border-dark-border animate-in fade-in slide-in-from-bottom-4 duration-500"
style={{ maxHeight: "calc(100vh - 3rem)" }}
>
{isInElectronWebView() && !webviewAuthSuccess && (
<Alert className="mb-4 border-blue-500 bg-blue-500/10">
<Monitor className="h-4 w-4" />
@@ -843,21 +884,6 @@ export function Auth({
)}
{isInElectronWebView() && webviewAuthSuccess && (
<div className="flex flex-col items-center justify-center h-64 gap-4">
<div className="w-16 h-16 rounded-full bg-green-500/20 flex items-center justify-center">
<svg
className="w-10 h-10 text-green-500"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M5 13l4 4L19 7"
/>
</svg>
</div>
<div className="text-center">
<h2 className="text-xl font-bold mb-2">
{t("messages.loginSuccess")}
@@ -944,72 +970,49 @@ export function Auth({
return (
<>
<div className="flex gap-2 mb-6">
{passwordLoginAllowed && (
<button
type="button"
className={cn(
"flex-1 py-2 text-base font-medium rounded-md transition-all",
tab === "login"
? "bg-primary text-primary-foreground shadow"
: "bg-muted text-muted-foreground hover:bg-accent",
)}
onClick={() => {
setTab("login");
if (tab === "reset") resetPasswordState();
if (tab === "signup") clearFormFields();
}}
aria-selected={tab === "login"}
disabled={loading || firstUser}
>
{t("common.login")}
</button>
)}
{(passwordLoginAllowed || firstUser) &&
registrationAllowed && (
<button
type="button"
className={cn(
"flex-1 py-2 text-base font-medium rounded-md transition-all",
tab === "signup"
? "bg-primary text-primary-foreground shadow"
: "bg-muted text-muted-foreground hover:bg-accent",
)}
onClick={() => {
setTab("signup");
if (tab === "reset") resetPasswordState();
if (tab === "login") clearFormFields();
}}
aria-selected={tab === "signup"}
{/* Tab Navigation */}
<Tabs value={tab} onValueChange={(value) => {
const newTab = value as "login" | "signup" | "external" | "reset";
setTab(newTab);
if (tab === "reset") resetPasswordState();
if ((tab === "login" && newTab === "signup") || (tab === "signup" && newTab === "login")) {
clearFormFields();
}
}} className="w-full mb-8">
<TabsList className="w-full">
{passwordLoginAllowed && (
<TabsTrigger
value="login"
disabled={loading || firstUser}
className="flex-1"
>
{t("common.login")}
</TabsTrigger>
)}
{(passwordLoginAllowed || firstUser) && registrationAllowed && (
<TabsTrigger
value="signup"
disabled={loading}
className="flex-1"
>
{t("common.register")}
</button>
</TabsTrigger>
)}
{oidcConfigured && (
<button
type="button"
className={cn(
"flex-1 py-2 text-base font-medium rounded-md transition-all",
tab === "external"
? "bg-primary text-primary-foreground shadow"
: "bg-muted text-muted-foreground hover:bg-accent",
)}
onClick={() => {
setTab("external");
if (tab === "reset") resetPasswordState();
if (tab === "login" || tab === "signup")
clearFormFields();
}}
aria-selected={tab === "external"}
disabled={oidcLoading}
>
{t("auth.external")}
</button>
)}
</div>
<div className="mb-6 text-center">
<h2 className="text-xl font-bold mb-1">
{oidcConfigured && (
<TabsTrigger
value="external"
disabled={oidcLoading}
className="flex-1"
>
{t("auth.external")}
</TabsTrigger>
)}
</TabsList>
</Tabs>
{/* Page Title */}
<div className="mb-8 text-center">
<h2 className="text-2xl font-bold">
{tab === "login"
? t("auth.loginTitle")
: tab === "signup"
@@ -1335,6 +1338,9 @@ export function Auth({
})()}
</>
)}
</div>
</div>
</div>
</div>
);
}

View File

@@ -63,7 +63,9 @@ export function ElectronLoginForm({
}
}
}
} catch (err) {}
} catch (err) {
console.error("Authentication operation failed:", err);
}
};
window.addEventListener("message", handleMessage);
@@ -190,8 +192,12 @@ export function ElectronLoginForm({
);
}
}
} catch (err) {}
} catch (err) {}
} catch (err) {
console.error("Authentication operation failed:", err);
}
} catch (err) {
console.error("Authentication operation failed:", err);
}
};
const handleError = () => {

View File

@@ -37,7 +37,9 @@ export function ElectronServerConfig({
if (config?.serverUrl) {
setServerUrl(config.serverUrl);
}
} catch {}
} catch (error) {
console.error("Server config operation failed:", error);
}
};
const handleSaveConfig = async () => {

View File

@@ -65,6 +65,7 @@ interface SidebarProps {
isAdmin?: boolean;
username?: string | null;
children?: React.ReactNode;
onLogout?: () => void;
}
async function handleLogout() {
@@ -87,6 +88,7 @@ export function LeftSidebar({
isAdmin,
username,
children,
onLogout,
}: SidebarProps): React.ReactElement {
const { t } = useTranslation();
@@ -486,7 +488,7 @@ export function LeftSidebar({
)}
<DropdownMenuItem
className="rounded px-2 py-1.5 hover:bg-white/15 hover:text-accent-foreground focus:bg-white/20 focus:text-accent-foreground cursor-pointer focus:outline-none"
onClick={handleLogout}
onClick={onLogout || handleLogout}
>
<span>{t("common.logout")}</span>
</DropdownMenuItem>

View File

@@ -137,10 +137,10 @@ export function SSHAuthDialog({
return (
<div
className="absolute inset-0 z-50 flex items-center justify-center bg-dark-bg"
className="absolute inset-0 z-50 flex items-center justify-center bg-dark-bg animate-in fade-in duration-200"
style={{ backgroundColor }}
>
<Card className="w-full max-w-2xl mx-4 border-2">
<Card className="w-full max-w-2xl mx-4 border-2 animate-in fade-in zoom-in-95 duration-200">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Shield className="w-5 h-5" />

View File

@@ -25,12 +25,12 @@ export function TOTPDialog({
if (!isOpen) return null;
return (
<div className="absolute inset-0 flex items-center justify-center z-50">
<div className="absolute inset-0 flex items-center justify-center z-50 animate-in fade-in duration-200">
<div
className="absolute inset-0 bg-dark-bg rounded-md"
style={{ backgroundColor: backgroundColor || undefined }}
/>
<div className="bg-dark-bg border-2 border-dark-border rounded-lg p-6 max-w-md w-full mx-4 relative z-10">
<div className="bg-dark-bg border-2 border-dark-border rounded-lg p-6 max-w-md w-full mx-4 relative z-10 animate-in fade-in zoom-in-95 duration-200">
<div className="mb-4 flex items-center gap-2">
<Shield className="w-5 h-5 text-primary" />
<h3 className="text-lg font-semibold">

View File

@@ -54,7 +54,9 @@ async function handleLogout() {
},
serverOrigin,
);
} catch (err) {}
} catch (err) {
console.error("User profile operation failed:", err);
}
}
}
}

View File

@@ -48,7 +48,9 @@ export function useDragToSystemDesktop({ sshSessionId }: UseDragToSystemProps) {
store.put({ handle: dirHandle }, "lastSaveDir");
};
}
} catch {}
} catch (error) {
console.error("Drag operation failed:", error);
}
};
const isFileSystemAPISupported = () => {

View File

@@ -101,7 +101,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
terminal as { refresh?: (start: number, end: number) => void }
).refresh(0, terminal.rows - 1);
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
}
function performFit() {
@@ -175,7 +177,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
scheduleNotify(cols, rows);
hardRefresh();
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
},
refresh: () => hardRefresh(),
}),
@@ -225,7 +229,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
`\r\n[${msg.message || t("terminal.disconnected")}]`,
);
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
});
ws.addEventListener("close", (event) => {

View File

@@ -110,7 +110,9 @@ export function TerminalKeyboard({
if (navigator.vibrate) {
navigator.vibrate(20);
}
} catch {}
} catch (error) {
console.error("Keyboard operation failed:", error);
}
onSendInput(input);
},

View File

@@ -52,7 +52,9 @@ function postJWTToWebView() {
timestamp: Date.now(),
}),
);
} catch (error) {}
} catch (error) {
console.error("Auth operation failed:", error);
}
}
interface AuthProps extends React.ComponentProps<"div"> {

View File

@@ -8,6 +8,7 @@
"moduleResolution": "nodenext",
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"esModuleInterop": true,
"noEmit": false,
"outDir": "./dist/backend",
"strict": false,