feat: Add Wild Central web app (Central-only UI)
Extract Central pages from the wild-cloud web app into a standalone React app for Wild Central. Includes: - Central overview, DNS, DHCP, Firewall, VPN, Ingress, CrowdSec pages - Simplified sidebar with Central-only navigation - Branding updated to "Wild Central" - All Cloud-specific pages, components, hooks, and API services removed - TypeScript type-check and production build pass Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
27
web/.gitignore
vendored
Normal file
27
web/.gitignore
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Environment variables
|
||||
.env.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
380
web/BUILDING_WILD_APP.md
Normal file
380
web/BUILDING_WILD_APP.md
Normal file
@@ -0,0 +1,380 @@
|
||||
# Building Wild App
|
||||
|
||||
This document describes the architecture and tooling used to build the Wild App, the web-based interface for managing Wild Cloud instances, hosted on Wild Central.
|
||||
|
||||
## Principles
|
||||
|
||||
- Stick with well known standards.
|
||||
- Keep it simple.
|
||||
- Use popular, well-maintained libraries.
|
||||
- Use components wherever possible to avoid reinventing the wheel.
|
||||
- Use TypeScript for type safety.
|
||||
|
||||
### Tooling
|
||||
## Dev Environment Requirements
|
||||
|
||||
- Node.js 20+
|
||||
- pnpm for package management
|
||||
- vite for build tooling
|
||||
- React + TypeScript
|
||||
- Tailwind CSS for styling
|
||||
- shadcn/ui for ready-made components
|
||||
- radix-ui for accessible components
|
||||
- eslint for linting
|
||||
- tsc for type checking
|
||||
- vitest for unit tests
|
||||
|
||||
#### Makefile commands
|
||||
|
||||
- Build application: `make app-build`
|
||||
- Run locally: `make app-run`
|
||||
- Format code: `make app-fmt`
|
||||
- Lint and typecheck: `make app-check`
|
||||
- Test installation: `make app-test`
|
||||
|
||||
### Scaffolding apps
|
||||
|
||||
It is important to start an app with a good base structure to avoid difficult to debug config issues.
|
||||
|
||||
This is a recommended setup.
|
||||
|
||||
#### Install pnpm if necessary:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://get.pnpm.io/install.sh | sh -
|
||||
```
|
||||
|
||||
#### Install a React + Speedy Web Compiler (SWC) + TypeScript + TailwindCSS app with vite:
|
||||
|
||||
```
|
||||
pnpm create vite@latest my-app -- --template react-swc-ts
|
||||
```
|
||||
|
||||
#### Reconfigure to use shadcn/ui (radix + tailwind components) (see https://ui.shadcn.com/docs/installation/vite)
|
||||
|
||||
##### Add tailwind.
|
||||
|
||||
```bash
|
||||
pnpm add tailwindcss @tailwindcss/vite
|
||||
```
|
||||
|
||||
##### Replace everything in src/index.css with a tailwind import:
|
||||
|
||||
```bash
|
||||
echo "@import \"tailwindcss\";" > src/index.css
|
||||
```
|
||||
|
||||
##### Edit tsconfig files
|
||||
|
||||
The current version of Vite splits TypeScript configuration into three files, two of which need to be edited. Add the baseUrl and paths properties to the compilerOptions section of the tsconfig.json and tsconfig.app.json files:
|
||||
|
||||
tsconfig.json
|
||||
|
||||
```json
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.node.json"
|
||||
}
|
||||
],
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
tsconfig.app.json
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
// ...
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./src/*"
|
||||
]
|
||||
}
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
##### Update vite.config.ts
|
||||
|
||||
```bash
|
||||
pnpm add -D @types/node
|
||||
```
|
||||
Then edit vite.config.ts to include the node types:
|
||||
|
||||
```ts
|
||||
import path from "path"
|
||||
import tailwindcss from "@tailwindcss/vite"
|
||||
import react from "@vitejs/plugin-react"
|
||||
import { defineConfig } from "vite"
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": path.resolve(__dirname, "./src"),
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
##### Run the cli
|
||||
|
||||
```bash
|
||||
pnpm dlx shadcn@latest init
|
||||
```
|
||||
|
||||
##### Add components
|
||||
|
||||
```bash
|
||||
pnpm dlx shadcn@latest add button
|
||||
pnpm dlx shadcn@latest add alert-dialog
|
||||
```
|
||||
|
||||
You can then use components with `import { Button } from "@/components/ui/button"`
|
||||
|
||||
### UX Principles
|
||||
|
||||
These principles ensure consistent, intuitive interfaces that align with Wild Cloud's philosophy of simplicity and clarity. Use them as quality control when building new components.
|
||||
|
||||
#### Navigation & Structure
|
||||
|
||||
- **Use shadcn AppSideBar** as the main navigation: https://ui.shadcn.com/docs/components/sidebar
|
||||
- **Card-Based Layout**: Group related content in Card components
|
||||
- Primary cards: `p-6` padding
|
||||
- Nested cards: `p-4` padding with subtle shadows
|
||||
- Use cards to create visual hierarchy through nesting
|
||||
- **Spacing Rhythm**: Maintain consistent vertical spacing
|
||||
- Major sections: `space-y-6`
|
||||
- Related items: `space-y-4`
|
||||
- Form fields: `space-y-3`
|
||||
- Inline elements: `gap-2`, `gap-3`, or `gap-4`
|
||||
|
||||
#### Visual Design
|
||||
|
||||
- **Dark Mode**: Support both light and dark modes using Tailwind's `dark:` prefix
|
||||
- Test all components in both modes for contrast and readability
|
||||
- Use semantic color tokens that adapt to theme
|
||||
- **Status Color System**: Use semantic left border colors to categorize content
|
||||
- Blue (`border-l-blue-500`): Configuration sections
|
||||
- Green (`border-l-green-500`): Network/infrastructure
|
||||
- Red (`border-l-red-500`): Errors and warnings
|
||||
- Cyan: Educational content
|
||||
- **Icon-Text Pairing**: Pair important text with Lucide icons
|
||||
- Place icons in colored containers: `p-2 bg-primary/10 rounded-lg`
|
||||
- Provides visual anchors and improves scannability
|
||||
- **Technical Data Display**: Show technical information clearly
|
||||
- Use `font-mono` class for IPs, domains, configuration values
|
||||
- Display in `bg-muted rounded-md p-2` containers
|
||||
|
||||
#### Component Patterns
|
||||
|
||||
- **Edit/View Mode Toggle**: For configuration sections
|
||||
- Read-only: Display in `bg-muted rounded-md font-mono` containers with Edit button
|
||||
- Edit mode: Replace with form inputs in-place
|
||||
- Provides lightweight editing without context switching
|
||||
- **Drawers for Complex Forms**: Use side panels for detailed input
|
||||
- Maintains context with main content
|
||||
- Better than modals for forms that benefit from seeing related data
|
||||
- **Educational Content**: Use gradient cards for helpful information
|
||||
- Background: `from-cyan-50 to-blue-50 dark:from-cyan-900/20 dark:to-blue-900/20`
|
||||
- Include book icon and clear, concise guidance
|
||||
- Makes learning feel integrated, not intrusive
|
||||
- **Empty States**: Center content with clear next actions
|
||||
- Large icon: `h-12 w-12 text-muted-foreground`
|
||||
- Descriptive title and explanation
|
||||
- Suggest action to resolve empty state
|
||||
|
||||
#### Section Headers
|
||||
|
||||
Structure all major section headers consistently:
|
||||
|
||||
```tsx
|
||||
<div className="flex items-center gap-4 mb-6">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<IconComponent className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">Section Title</h2>
|
||||
<p className="text-muted-foreground">
|
||||
Brief description of section purpose
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
#### Status & Feedback
|
||||
|
||||
- **Status Badges**: Use colored badges with icons for state indication
|
||||
- Keep compact but descriptive
|
||||
- Include hover/expansion for additional detail
|
||||
- **Alert Positioning**: Place alerts near related content
|
||||
- Use semantic colors and icons (CheckCircle, AlertCircle, XCircle)
|
||||
- Include dismissible X button for manual dismissal
|
||||
- **Success Messages**: Auto-dismiss after 5 seconds
|
||||
- Green color with CheckCircle icon
|
||||
- Clear, affirmative message
|
||||
- **Error Messages**: Structured and actionable
|
||||
- Title in bold, detailed message below
|
||||
- Red color with AlertCircle icon
|
||||
- Suggest resolution when possible
|
||||
- **Loading States**: Context-appropriate indicators
|
||||
- Inline: Use `Loader2` spinner in buttons/actions
|
||||
- Full section: Card with centered spinner and descriptive text
|
||||
|
||||
#### Form Components
|
||||
|
||||
Use react-hook-form for all forms. Never duplicate component styling.
|
||||
|
||||
**Standard Form Pattern**:
|
||||
```tsx
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
import { Input, Label, Button } from '@/components/ui';
|
||||
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@/components/ui/select';
|
||||
|
||||
const { register, handleSubmit, control, formState: { errors } } = useForm({
|
||||
defaultValues: { /* ... */ }
|
||||
});
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-3">
|
||||
<div>
|
||||
<Label htmlFor="text">Text Field</Label>
|
||||
<Input {...register('text', { required: 'Required' })} className="mt-1" />
|
||||
{errors.text && <p className="text-sm text-red-600 mt-1">{errors.text.message}</p>}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="select">Select Field</Label>
|
||||
<Controller
|
||||
name="select"
|
||||
control={control}
|
||||
rules={{ required: 'Required' }}
|
||||
render={({ field }) => (
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Choose..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="option1">Option 1</SelectItem>
|
||||
<SelectItem value="option2">Option 2</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
{errors.select && <p className="text-sm text-red-600 mt-1">{errors.select.message}</p>}
|
||||
</div>
|
||||
</form>
|
||||
```
|
||||
|
||||
**Rules**:
|
||||
- **Text inputs**: Use `Input` with `register()`
|
||||
- **Select dropdowns**: Use `Select` components with `Controller` (never native `<select>`)
|
||||
- **All labels**: Use `Label` with `htmlFor` attribute
|
||||
- **Never copy classes**: Components provide default styling, only add spacing like `mt-1`
|
||||
- **Form spacing**: `space-y-3` on form containers
|
||||
- **Error messages**: `text-sm text-red-600 mt-1`
|
||||
- **Multi-action forms**: Place buttons side-by-side with `flex gap-2`
|
||||
|
||||
#### Accessibility
|
||||
|
||||
- **Focus Indicators**: All interactive elements must have visible focus states
|
||||
- Use consistent `focus-visible:ring-*` styles
|
||||
- Test keyboard navigation on all new components
|
||||
- **Screen Reader Support**: Proper semantic HTML and ARIA labels
|
||||
- Use Label components for form inputs
|
||||
- Provide descriptive text for icon-only buttons
|
||||
- Test with screen readers when adding complex interactions
|
||||
|
||||
#### Progressive Disclosure
|
||||
|
||||
- **Just-in-Time Information**: Start simple, reveal details on demand
|
||||
- Summary view by default
|
||||
- Details through drawers, accordions, or inline expansion
|
||||
- Reduces initial cognitive load
|
||||
- **Educational Context**: Provide help without interrupting flow
|
||||
- Use gradient educational cards in logical places
|
||||
- Include "Learn more" links to external documentation
|
||||
- Keep content concise and actionable
|
||||
|
||||
### App Layout
|
||||
|
||||
- The sidebar let's you select which cloud instance you are curently managing from a dropdown.
|
||||
- The sidebar is divided into Central, Cluster, and Apps.
|
||||
- Central: Utilities for managing Wild Central itself.
|
||||
- Cluster: Utilities for managing the current Wild Cloud instance.
|
||||
- Managing nodes.
|
||||
- Managing services.
|
||||
- Apps: Managing the apps deployed on the current Wild Cloud instance.
|
||||
- List of apps.
|
||||
- App details.
|
||||
- App logs.
|
||||
- App metrics.
|
||||
|
||||
## Real-Time Updates with SSE
|
||||
|
||||
The web app uses Server-Sent Events for real-time updates instead of polling. This reduces server load and provides instant updates.
|
||||
|
||||
### Using the SSE Hooks
|
||||
|
||||
```typescript
|
||||
import { useFilteredSSE } from '@/hooks/useGlobalSSE';
|
||||
|
||||
// Listen to specific events for an instance
|
||||
const { isConnected } = useFilteredSSE(
|
||||
instanceName, // Filter by instance
|
||||
['pod:modified', 'pod:deleted'], // Event types to listen for
|
||||
{ enabled: !!instanceName } // Only connect when instance is selected
|
||||
);
|
||||
```
|
||||
|
||||
### How It Works
|
||||
|
||||
1. **Global Connection**: A single SSE connection is established to `/api/v1/events` and shared across all components
|
||||
2. **Client-Side Filtering**: Events are filtered on the client based on instance and event type
|
||||
3. **Automatic Query Invalidation**: When events arrive, relevant React Query caches are automatically invalidated
|
||||
4. **No Polling**: Remove `refetchInterval` from useQuery hooks - SSE handles all updates
|
||||
|
||||
### Event-Driven Patterns
|
||||
|
||||
```typescript
|
||||
// Hook automatically subscribes to relevant events
|
||||
export function useDeployedApps(instanceName: string | null | undefined) {
|
||||
// SSE handles real-time updates for these event types
|
||||
useFilteredSSE(
|
||||
instanceName,
|
||||
['pod:added', 'pod:modified', 'pod:deleted', 'deployment:modified'],
|
||||
{ enabled: !!instanceName }
|
||||
);
|
||||
|
||||
// Query has no refetchInterval - SSE triggers invalidation
|
||||
return useQuery({
|
||||
queryKey: ['instances', instanceName, 'apps'],
|
||||
queryFn: () => appsApi.listDeployed(instanceName!),
|
||||
enabled: !!instanceName,
|
||||
refetchInterval: false, // No polling!
|
||||
staleTime: 120000, // Keep data fresh longer
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Key Principles
|
||||
|
||||
- **Single Connection**: One SSE connection serves the entire app
|
||||
- **Remove Polling**: Set `refetchInterval: false` on all queries
|
||||
- **Increase staleTime**: Set longer stale times (e.g., 120000ms) since SSE provides updates
|
||||
- **Filter Events**: Use `useFilteredSSE` to subscribe only to relevant events
|
||||
- **Automatic Cleanup**: Hooks handle connection lifecycle automatically
|
||||
|
||||
2
web/CLAUDE.md
Normal file
2
web/CLAUDE.md
Normal file
@@ -0,0 +1,2 @@
|
||||
- @README.md
|
||||
- @BUILDING_WILD_APP.md
|
||||
661
web/LICENSE
Normal file
661
web/LICENSE
Normal file
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
67
web/README.md
Normal file
67
web/README.md
Normal file
@@ -0,0 +1,67 @@
|
||||
# Wild Cloud Web App
|
||||
|
||||
The Wild Cloud Web App is a web-based interface for managing Wild Cloud instances. It allows users to view and control their Wild Cloud environments, including deploying applications, monitoring resources, and configuring settings.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before starting the web app, ensure the Wild Central API is running:
|
||||
|
||||
```bash
|
||||
cd ../api
|
||||
make dev
|
||||
```
|
||||
|
||||
The API should be accessible at `http://localhost:5055`.
|
||||
|
||||
## Development
|
||||
|
||||
### Initial Setup
|
||||
|
||||
1. Copy the example environment file:
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
2. Update `.env` if your API is running on a different host/port:
|
||||
```bash
|
||||
VITE_API_BASE_URL=http://localhost:5055
|
||||
```
|
||||
|
||||
3. Install dependencies:
|
||||
```bash
|
||||
pnpm install
|
||||
```
|
||||
|
||||
4. Start the development server:
|
||||
```bash
|
||||
pnpm run dev
|
||||
```
|
||||
|
||||
The web app will be available at `http://localhost:5173` (or the next available port).
|
||||
|
||||
## Other Scripts
|
||||
|
||||
```bash
|
||||
pnpm run build # Build the project
|
||||
pnpm run lint # Lint the codebase
|
||||
pnpm run preview # Preview the production build
|
||||
pnpm run type-check # Type check the codebase
|
||||
pnpm run test # Run tests
|
||||
pnpm run test:ui # Run tests with UI
|
||||
pnpm run test:coverage # Run tests with coverage report
|
||||
pnpm run build:css # Build the CSS using Tailwind
|
||||
pnpm run check # Run lint, type-check, and tests
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
### `VITE_API_BASE_URL`
|
||||
|
||||
The base URL of the Wild Central API server.
|
||||
|
||||
- **Default:** `http://localhost:5055`
|
||||
- **Example:** `http://192.168.1.100:5055`
|
||||
- **Usage:** Set in `.env` file (see `.env.example` for template)
|
||||
|
||||
This variable is used by the API client to connect to the Wild Central API. If not set, it defaults to `http://localhost:5055`.
|
||||
|
||||
21
web/components.json
Normal file
21
web/components.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/index.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
470
web/docs/specs/routing-contract.md
Normal file
470
web/docs/specs/routing-contract.md
Normal file
@@ -0,0 +1,470 @@
|
||||
# Wild Cloud Web App Routing Contract
|
||||
|
||||
## Front Matter
|
||||
|
||||
**Module Name**: `routing`
|
||||
**Module Type**: Infrastructure
|
||||
**Version**: 1.0.0
|
||||
**Status**: Draft
|
||||
**Last Updated**: 2025-10-12
|
||||
**Owner**: Wild Cloud Development Team
|
||||
|
||||
### Dependencies
|
||||
|
||||
- `react`: ^19.1.0
|
||||
- `react-router`: ^7.0.0 (to be added)
|
||||
|
||||
### Consumers
|
||||
|
||||
- All page components within Wild Cloud Web App
|
||||
- Navigation components (AppSidebar)
|
||||
- Instance context management
|
||||
- External navigation links
|
||||
|
||||
## Purpose
|
||||
|
||||
This module defines the routing system for the Wild Cloud web application, providing declarative navigation between pages, URL-based state management, and integration with the existing instance context system.
|
||||
|
||||
## Public API
|
||||
|
||||
### Router Configuration
|
||||
|
||||
The routing system provides a centralized router configuration that manages all application routes.
|
||||
|
||||
#### Primary Routes
|
||||
|
||||
```typescript
|
||||
interface RouteDefinition {
|
||||
path: string;
|
||||
element: React.ComponentType;
|
||||
loader?: () => Promise<unknown>;
|
||||
errorElement?: React.ComponentType;
|
||||
}
|
||||
```
|
||||
|
||||
**Root Route**:
|
||||
- **Path**: `/`
|
||||
- **Purpose**: Landing page and instance selector
|
||||
- **Authentication**: None required
|
||||
- **Data Loading**: None
|
||||
|
||||
**Instance Routes**:
|
||||
- **Path Pattern**: `/instances/:instanceId/*`
|
||||
- **Purpose**: All instance-specific pages
|
||||
- **Authentication**: Instance must exist
|
||||
- **Data Loading**: Instance configuration loaded at this level
|
||||
|
||||
#### Instance-Scoped Routes
|
||||
|
||||
All routes under `/instances/:instanceId/`:
|
||||
|
||||
| Path | Purpose | Data Dependencies |
|
||||
|------|---------|-------------------|
|
||||
| `dashboard` | Overview and quick status | Instance config, cluster status |
|
||||
| `operations` | Operation monitoring and logs | Active operations list |
|
||||
| `cluster/health` | Cluster health metrics | Node status, etcd health |
|
||||
| `cluster/access` | Kubeconfig/Talosconfig download | Instance credentials |
|
||||
| `secrets` | Secrets management interface | Instance secrets (redacted) |
|
||||
| `services` | Base services management | Installed services list |
|
||||
| `utilities` | Utilities panel | Available utilities |
|
||||
| `cloud` | Cloud configuration | Cloud settings |
|
||||
| `dns` | DNS management | DNS configuration |
|
||||
| `dhcp` | DHCP management | DHCP configuration |
|
||||
| `pxe` | PXE boot configuration | PXE assets and config |
|
||||
| `infrastructure` | Cluster nodes | Node list and status |
|
||||
| `cluster` | Cluster services | Kubernetes services |
|
||||
| `apps` | Application management | Installed apps |
|
||||
| `advanced` | Advanced settings | System configuration |
|
||||
|
||||
### Navigation Hooks
|
||||
|
||||
#### useNavigate
|
||||
|
||||
```typescript
|
||||
function useNavigate(): NavigateFunction;
|
||||
|
||||
interface NavigateFunction {
|
||||
(to: string | number, options?: NavigateOptions): void;
|
||||
}
|
||||
|
||||
interface NavigateOptions {
|
||||
replace?: boolean;
|
||||
state?: unknown;
|
||||
}
|
||||
```
|
||||
|
||||
**Purpose**: Programmatic navigation within the application.
|
||||
|
||||
**Examples**:
|
||||
```typescript
|
||||
// Navigate to a specific instance dashboard
|
||||
navigate('/instances/prod-cluster/dashboard');
|
||||
|
||||
// Navigate back
|
||||
navigate(-1);
|
||||
|
||||
// Replace current history entry
|
||||
navigate('/instances/prod-cluster/operations', { replace: true });
|
||||
```
|
||||
|
||||
**Error Conditions**:
|
||||
- Invalid paths are handled by error boundary
|
||||
- Missing instance IDs redirect to root
|
||||
|
||||
#### useParams
|
||||
|
||||
```typescript
|
||||
function useParams<T extends Record<string, string>>(): T;
|
||||
```
|
||||
|
||||
**Purpose**: Access URL parameters, primarily for extracting instance ID.
|
||||
|
||||
**Example**:
|
||||
```typescript
|
||||
const { instanceId } = useParams<{ instanceId: string }>();
|
||||
```
|
||||
|
||||
**Error Conditions**:
|
||||
- Returns undefined for missing parameters
|
||||
- Type safety through TypeScript generics
|
||||
|
||||
#### useLocation
|
||||
|
||||
```typescript
|
||||
interface Location {
|
||||
pathname: string;
|
||||
search: string;
|
||||
hash: string;
|
||||
state: unknown;
|
||||
key: string;
|
||||
}
|
||||
|
||||
function useLocation(): Location;
|
||||
```
|
||||
|
||||
**Purpose**: Access current location information for conditional rendering or analytics.
|
||||
|
||||
#### useSearchParams
|
||||
|
||||
```typescript
|
||||
function useSearchParams(): [
|
||||
URLSearchParams,
|
||||
(nextInit: URLSearchParams | ((prev: URLSearchParams) => URLSearchParams)) => void
|
||||
];
|
||||
```
|
||||
|
||||
**Purpose**: Read and write URL query parameters for filters, sorting, and view state.
|
||||
|
||||
**Example**:
|
||||
```typescript
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const view = searchParams.get('view') || 'grid';
|
||||
setSearchParams({ view: 'list' });
|
||||
```
|
||||
|
||||
### Link Component
|
||||
|
||||
```typescript
|
||||
interface LinkProps {
|
||||
to: string;
|
||||
replace?: boolean;
|
||||
state?: unknown;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function Link(props: LinkProps): JSX.Element;
|
||||
```
|
||||
|
||||
**Purpose**: Declarative navigation component for user-triggered navigation.
|
||||
|
||||
**Example**:
|
||||
```typescript
|
||||
<Link to="/instances/prod-cluster/dashboard">
|
||||
Go to Dashboard
|
||||
</Link>
|
||||
```
|
||||
|
||||
**Behavior**:
|
||||
- Prevents default browser navigation
|
||||
- Supports keyboard navigation (Enter)
|
||||
- Maintains browser history
|
||||
- Supports Ctrl/Cmd+Click to open in new tab
|
||||
|
||||
### NavLink Component
|
||||
|
||||
```typescript
|
||||
interface NavLinkProps extends LinkProps {
|
||||
caseSensitive?: boolean;
|
||||
end?: boolean;
|
||||
className?: string | ((props: { isActive: boolean; isPending: boolean }) => string);
|
||||
style?: React.CSSProperties | ((props: { isActive: boolean; isPending: boolean }) => React.CSSProperties);
|
||||
}
|
||||
|
||||
function NavLink(props: NavLinkProps): JSX.Element;
|
||||
```
|
||||
|
||||
**Purpose**: Navigation links that are aware of their active state.
|
||||
|
||||
**Example**:
|
||||
```typescript
|
||||
<NavLink
|
||||
to="/instances/prod-cluster/dashboard"
|
||||
className={({ isActive }) => isActive ? 'active-nav-link' : 'nav-link'}
|
||||
>
|
||||
Dashboard
|
||||
</NavLink>
|
||||
```
|
||||
|
||||
## Data Models
|
||||
|
||||
### Route Parameters
|
||||
|
||||
```typescript
|
||||
interface InstanceRouteParams {
|
||||
instanceId: string;
|
||||
}
|
||||
```
|
||||
|
||||
**Field Specifications**:
|
||||
- `instanceId`: String identifier for the instance
|
||||
- **Required**: Yes
|
||||
- **Format**: Alphanumeric with hyphens, 1-64 characters
|
||||
- **Validation**: Must correspond to an existing instance
|
||||
- **Example**: `"prod-cluster"`, `"staging-env"`
|
||||
|
||||
### Navigation State
|
||||
|
||||
```typescript
|
||||
interface NavigationState {
|
||||
from?: string;
|
||||
returnTo?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
```
|
||||
|
||||
**Purpose**: Preserve state across navigation, such as return URLs or form data.
|
||||
|
||||
**Example**:
|
||||
```typescript
|
||||
navigate('/instances/prod-cluster/secrets', {
|
||||
state: { returnTo: '/instances/prod-cluster/dashboard' }
|
||||
});
|
||||
```
|
||||
|
||||
## Error Model
|
||||
|
||||
### Route Errors
|
||||
|
||||
| Error Code | Condition | User Impact | Recovery Action |
|
||||
|------------|-----------|-------------|-----------------|
|
||||
| `ROUTE_NOT_FOUND` | Path does not match any route | 404 page displayed | Redirect to root or show available routes |
|
||||
| `INSTANCE_NOT_FOUND` | Instance ID in URL does not exist | Error boundary with message | Redirect to instance selector at `/` |
|
||||
| `INVALID_INSTANCE_ID` | Instance ID format invalid | Validation error displayed | Show error message, redirect to `/` |
|
||||
| `NAVIGATION_CANCELLED` | User cancelled pending navigation | No visible change | Continue at current route |
|
||||
| `LOADER_ERROR` | Route data loader failed | Error boundary with retry option | Show error, allow retry or navigate away |
|
||||
|
||||
### Error Response Format
|
||||
|
||||
```typescript
|
||||
interface RouteError {
|
||||
code: string;
|
||||
message: string;
|
||||
status?: number;
|
||||
cause?: Error;
|
||||
}
|
||||
```
|
||||
|
||||
**Example**:
|
||||
```typescript
|
||||
{
|
||||
code: "INSTANCE_NOT_FOUND",
|
||||
message: "Instance 'unknown-instance' does not exist",
|
||||
status: 404
|
||||
}
|
||||
```
|
||||
|
||||
## Performance Characteristics
|
||||
|
||||
### Route Transition Times
|
||||
|
||||
- **Static Routes**: < 50ms (no data loading)
|
||||
- **Instance Routes**: < 200ms (with instance config loading)
|
||||
- **Heavy Data Routes**: < 500ms (with large data sets)
|
||||
|
||||
### Bundle Size
|
||||
|
||||
- **Router Core**: ~45KB (minified)
|
||||
- **Navigation Components**: ~5KB
|
||||
- **Per-Route Code Splitting**: Enabled by default
|
||||
|
||||
### Memory Usage
|
||||
|
||||
- **History Stack**: O(n) where n is number of navigation entries
|
||||
- **Route Cache**: Configurable, default 10 entries
|
||||
- **Cleanup**: Automatic on unmount
|
||||
|
||||
## Configuration Requirements
|
||||
|
||||
### Environment Variables
|
||||
|
||||
None required. All routing is handled client-side.
|
||||
|
||||
### Route Configuration
|
||||
|
||||
```typescript
|
||||
interface RouterConfig {
|
||||
basename?: string;
|
||||
future?: {
|
||||
v7_startTransition?: boolean;
|
||||
v7_relativeSplatPath?: boolean;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**basename**: Optional base path for deployment in subdirectories
|
||||
- **Default**: `"/"`
|
||||
- **Example**: `"/app"` if deployed to `example.com/app/`
|
||||
|
||||
## Conformance Criteria
|
||||
|
||||
### Functional Requirements
|
||||
|
||||
1. **F-ROUTE-01**: Router SHALL render correct component for each defined route
|
||||
2. **F-ROUTE-02**: Router SHALL extract instance ID from URL parameters
|
||||
3. **F-ROUTE-03**: Navigation hooks SHALL update browser history
|
||||
4. **F-ROUTE-04**: Back/forward browser buttons SHALL work correctly
|
||||
5. **F-ROUTE-05**: Invalid routes SHALL display error boundary
|
||||
6. **F-ROUTE-06**: Instance routes SHALL validate instance existence
|
||||
7. **F-ROUTE-07**: Link components SHALL support keyboard navigation
|
||||
8. **F-ROUTE-08**: Routes SHALL support lazy loading of components
|
||||
|
||||
### Non-Functional Requirements
|
||||
|
||||
1. **NF-ROUTE-01**: Route transitions SHALL complete in < 200ms for cached routes
|
||||
2. **NF-ROUTE-02**: Router SHALL support browser back/forward without page reload
|
||||
3. **NF-ROUTE-03**: Navigation SHALL preserve scroll position when appropriate
|
||||
4. **NF-ROUTE-04**: Router SHALL be compatible with React 19.1+
|
||||
5. **NF-ROUTE-05**: Routes SHALL be defined declaratively in configuration
|
||||
6. **NF-ROUTE-06**: Router SHALL integrate with existing ErrorBoundary
|
||||
7. **NF-ROUTE-07**: Navigation SHALL work with InstanceContext
|
||||
|
||||
### Integration Requirements
|
||||
|
||||
1. **I-ROUTE-01**: Router SHALL integrate with InstanceContext
|
||||
2. **I-ROUTE-02**: AppSidebar SHALL use routing for navigation
|
||||
3. **I-ROUTE-03**: All page components SHALL be routed
|
||||
4. **I-ROUTE-04**: Router SHALL integrate with React Query for data loading
|
||||
5. **I-ROUTE-05**: Router SHALL support Vite code splitting
|
||||
|
||||
## API Stability
|
||||
|
||||
**Versioning Scheme**: Semantic Versioning (SemVer)
|
||||
|
||||
**Stability Level**: Stable (1.0.0+)
|
||||
|
||||
**Breaking Changes**:
|
||||
- Route path changes require major version bump
|
||||
- Hook signature changes require major version bump
|
||||
- Added routes or optional parameters are minor version bumps
|
||||
|
||||
**Deprecation Policy**:
|
||||
- Deprecated routes supported for 2 minor versions
|
||||
- Console warnings for deprecated route usage
|
||||
- Migration guide provided for breaking changes
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Route Protection
|
||||
|
||||
Instance routes SHALL verify:
|
||||
1. Instance ID exists in available instances
|
||||
2. User has permission to access instance (future)
|
||||
|
||||
### XSS Prevention
|
||||
|
||||
- All route parameters SHALL be sanitized
|
||||
- User-provided navigation state SHALL be validated
|
||||
- No executable code in route parameters
|
||||
|
||||
### CSRF Protection
|
||||
|
||||
Not applicable - all navigation is client-side without authentication tokens.
|
||||
|
||||
## Browser Compatibility
|
||||
|
||||
**Supported Browsers**:
|
||||
- Chrome/Edge: Last 2 versions
|
||||
- Firefox: Last 2 versions
|
||||
- Safari: Last 2 versions
|
||||
|
||||
**Required Browser APIs**:
|
||||
- History API
|
||||
- URL API
|
||||
- ES6+ JavaScript features
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Navigation
|
||||
|
||||
```typescript
|
||||
// In a component
|
||||
import { useNavigate } from 'react-router';
|
||||
|
||||
function InstanceCard({ instance }) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleClick = () => {
|
||||
navigate(`/instances/${instance.id}/dashboard`);
|
||||
};
|
||||
|
||||
return <button onClick={handleClick}>Open {instance.name}</button>;
|
||||
}
|
||||
```
|
||||
|
||||
### Using Route Parameters
|
||||
|
||||
```typescript
|
||||
// In an instance page
|
||||
import { useParams } from 'react-router';
|
||||
import { useInstanceContext } from '../hooks';
|
||||
|
||||
function DashboardPage() {
|
||||
const { instanceId } = useParams<{ instanceId: string }>();
|
||||
const { setCurrentInstance } = useInstanceContext();
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentInstance(instanceId);
|
||||
}, [instanceId, setCurrentInstance]);
|
||||
|
||||
return <div>Dashboard for {instanceId}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
### Sidebar Integration
|
||||
|
||||
```typescript
|
||||
// AppSidebar using NavLink
|
||||
import { NavLink } from 'react-router';
|
||||
|
||||
function AppSidebar() {
|
||||
const { instanceId } = useParams();
|
||||
|
||||
return (
|
||||
<nav>
|
||||
<NavLink
|
||||
to={`/instances/${instanceId}/dashboard`}
|
||||
className={({ isActive }) => isActive ? 'active' : ''}
|
||||
>
|
||||
Dashboard
|
||||
</NavLink>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0.0 | 2025-10-12 | Initial contract definition |
|
||||
28
web/eslint.config.js
Normal file
28
web/eslint.config.js
Normal file
@@ -0,0 +1,28 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ['dist'] },
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
plugins: {
|
||||
'react-hooks': reactHooks,
|
||||
'react-refresh': reactRefresh,
|
||||
},
|
||||
rules: {
|
||||
...reactHooks.configs.recommended.rules,
|
||||
'react-refresh/only-export-components': [
|
||||
'warn',
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
20
web/index.html
Normal file
20
web/index.html
Normal file
@@ -0,0 +1,20 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#0ea5e9" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Wild Cloud Central Management"
|
||||
/>
|
||||
<link rel="manifest" href="/manifest.json" />
|
||||
<title>Wild Cloud Central</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
75
web/package.json
Normal file
75
web/package.json
Normal file
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"name": "wild-cloud-central",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview",
|
||||
"type-check": "tsc -p tsconfig.app.json --noEmit",
|
||||
"test": "vitest --run",
|
||||
"test:ui": "vitest --ui",
|
||||
"test:coverage": "vitest --coverage",
|
||||
"build:css": "tailwindcss -i src/index.css -o ./output.css --config ./tailwind.config.js",
|
||||
"check": "pnpm run lint && pnpm run type-check && pnpm run test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^5.2.2",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-collapsible": "^1.1.12",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-label": "^2.1.8",
|
||||
"@radix-ui/react-select": "^2.2.6",
|
||||
"@radix-ui/react-separator": "^1.1.8",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@radix-ui/react-switch": "^1.2.6",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"@tailwindcss/vite": "^4.1.18",
|
||||
"@tanstack/react-query": "^5.90.20",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-serialize": "^0.14.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"lucide-react": "^0.516.0",
|
||||
"qrcode.react": "^4.2.0",
|
||||
"radix-ui": "^1.4.3",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
"react-hook-form": "^7.71.1",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-router": "^7.13.0",
|
||||
"react-router-dom": "^7.13.0",
|
||||
"recharts": "^3.9.2",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"tailwindcss": "^4.1.18",
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.2",
|
||||
"@tailwindcss/typography": "^0.5.19",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/node": "^24.10.11",
|
||||
"@types/react": "^19.2.13",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^4.7.0",
|
||||
"eslint": "^9.39.2",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.26",
|
||||
"globals": "^16.5.0",
|
||||
"jsdom": "^27.4.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "~5.8.3",
|
||||
"typescript-eslint": "^8.54.0",
|
||||
"vite": "^6.4.1",
|
||||
"vitest": "^3.2.4"
|
||||
},
|
||||
"packageManager": "pnpm@10.9.0+sha512.0486e394640d3c1fb3c9d43d49cf92879ff74f8516959c235308f5a8f62e2e19528a65cdc2a3058f587cde71eba3d5b56327c8c33a97e4c4051ca48a10ca2d5f"
|
||||
}
|
||||
6194
web/pnpm-lock.yaml
generated
Normal file
6194
web/pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
7
web/public/favicon.svg
Normal file
7
web/public/favicon.svg
Normal file
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
||||
<rect width="32" height="32" rx="6" fill="#0ea5e9"/>
|
||||
<g transform="translate(4, 4)" stroke="white" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M6 16.326A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 .5 8.973"/>
|
||||
<path d="M13 11l-3 5h4l-3 5"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 361 B |
15
web/public/manifest.json
Normal file
15
web/public/manifest.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"short_name": "Wild Cloud",
|
||||
"name": "Wild Cloud Central",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.svg",
|
||||
"sizes": "any",
|
||||
"type": "image/svg+xml"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#0ea5e9",
|
||||
"background_color": "#ffffff"
|
||||
}
|
||||
1
web/public/vite.svg
Normal file
1
web/public/vite.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
42
web/src/App.css
Normal file
42
web/src/App.css
Normal file
@@ -0,0 +1,42 @@
|
||||
#root {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
14
web/src/App.tsx
Normal file
14
web/src/App.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
import { RouterProvider } from 'react-router';
|
||||
import { router } from './router';
|
||||
import { Toaster } from 'sonner';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<>
|
||||
<RouterProvider router={router} />
|
||||
<Toaster />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
1
web/src/assets/react.svg
Normal file
1
web/src/assets/react.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
134
web/src/components/AppSidebar.tsx
Normal file
134
web/src/components/AppSidebar.tsx
Normal file
@@ -0,0 +1,134 @@
|
||||
import { NavLink } from 'react-router';
|
||||
import { Sun, Moon, Monitor, Shield, Lock, Network, ShieldAlert, Router, Cloud, Wifi, Server } from 'lucide-react';
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarRail,
|
||||
useSidebar,
|
||||
} from './ui/sidebar';
|
||||
import { useTheme } from '../contexts/ThemeContext';
|
||||
|
||||
export function AppSidebar() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const { state } = useSidebar();
|
||||
|
||||
const cycleTheme = () => {
|
||||
if (theme === 'light') {
|
||||
setTheme('dark');
|
||||
} else if (theme === 'dark') {
|
||||
setTheme('system');
|
||||
} else {
|
||||
setTheme('light');
|
||||
}
|
||||
};
|
||||
|
||||
const getThemeIcon = () => {
|
||||
switch (theme) {
|
||||
case 'light':
|
||||
return <Sun className="h-4 w-4" />;
|
||||
case 'dark':
|
||||
return <Moon className="h-4 w-4" />;
|
||||
default:
|
||||
return <Monitor className="h-4 w-4" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getThemeLabel = () => {
|
||||
switch (theme) {
|
||||
case 'light':
|
||||
return 'Light mode';
|
||||
case 'dark':
|
||||
return 'Dark mode';
|
||||
default:
|
||||
return 'System theme';
|
||||
}
|
||||
};
|
||||
|
||||
const centralItems = [
|
||||
{ to: '/central', icon: Server, label: 'Overview', end: true },
|
||||
{ to: '/central/cloudflare', icon: Cloud, label: 'Cloudflare' },
|
||||
{ to: '/central/dns', icon: Router, label: 'DNS' },
|
||||
{ to: '/central/ingress', icon: Network, label: 'Ingress Proxy' },
|
||||
{ to: '/central/firewall', icon: Shield, label: 'Firewall' },
|
||||
{ to: '/central/vpn', icon: Lock, label: 'VPN' },
|
||||
{ to: '/central/crowdsec', icon: ShieldAlert, label: 'CrowdSec' },
|
||||
{ to: '/central/dhcp', icon: Wifi, label: 'DHCP' },
|
||||
];
|
||||
|
||||
return (
|
||||
<Sidebar variant="sidebar" collapsible="icon">
|
||||
<SidebarHeader>
|
||||
<div className="flex items-center justify-center pb-2">
|
||||
<div className="p-1 bg-primary/10 rounded-lg">
|
||||
<Server className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div className="overflow-hidden transition-all duration-200 ease-linear ml-2 max-w-[200px] opacity-100 group-data-[collapsible=icon]:ml-0 group-data-[collapsible=icon]:max-w-0 group-data-[collapsible=icon]:opacity-0">
|
||||
<h2 className="text-lg font-bold text-foreground whitespace-nowrap">Wild Central</h2>
|
||||
</div>
|
||||
</div>
|
||||
</SidebarHeader>
|
||||
|
||||
<SidebarContent>
|
||||
{state === 'collapsed' ? (
|
||||
<SidebarMenu>
|
||||
{centralItems.map(({ to, icon: Icon, label, end }) => (
|
||||
<SidebarMenuItem key={to}>
|
||||
<NavLink to={to} end={end}>
|
||||
{({ isActive }) => (
|
||||
<SidebarMenuButton isActive={isActive} tooltip={label}>
|
||||
<Icon className="h-4 w-4" />
|
||||
<span>{label}</span>
|
||||
</SidebarMenuButton>
|
||||
)}
|
||||
</NavLink>
|
||||
</SidebarMenuItem>
|
||||
))}
|
||||
</SidebarMenu>
|
||||
) : (
|
||||
<SidebarGroup>
|
||||
<SidebarGroupLabel>Central</SidebarGroupLabel>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{centralItems.map(({ to, icon: Icon, label, end }) => (
|
||||
<SidebarMenuItem key={to}>
|
||||
<NavLink to={to} end={end}>
|
||||
{({ isActive }) => (
|
||||
<SidebarMenuButton isActive={isActive}>
|
||||
<Icon className="h-4 w-4" />
|
||||
<span className="truncate">{label}</span>
|
||||
</SidebarMenuButton>
|
||||
)}
|
||||
</NavLink>
|
||||
</SidebarMenuItem>
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
)}
|
||||
</SidebarContent>
|
||||
|
||||
<SidebarFooter>
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
onClick={cycleTheme}
|
||||
tooltip={`Current: ${getThemeLabel()}. Click to cycle themes.`}
|
||||
>
|
||||
{getThemeIcon()}
|
||||
<span>{getThemeLabel()}</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarFooter>
|
||||
<SidebarRail/>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
219
web/src/components/CentralComponent.tsx
Normal file
219
web/src/components/CentralComponent.tsx
Normal file
@@ -0,0 +1,219 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Card } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input, Label } from './ui';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import { HardDrive, Settings, CheckCircle, BookOpen, ExternalLink, Loader2, AlertCircle, Mail, Edit2, Check, X, RotateCw } from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useCentralStatus } from '../hooks/useCentralStatus';
|
||||
import { useConfig } from '../hooks';
|
||||
import { usePageHelp } from '../hooks/usePageHelp';
|
||||
|
||||
export function CentralComponent() {
|
||||
const { data: centralStatus, isLoading: statusLoading, error: statusError, restart: restartDaemon, isRestarting: isDaemonRestarting } = useCentralStatus();
|
||||
const { config: globalConfig, updateConfig: updateGlobalConfig, isUpdating } = useConfig();
|
||||
|
||||
const [editingOperator, setEditingOperator] = useState(false);
|
||||
const [operatorEmail, setOperatorEmail] = useState('');
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
const showSuccess = (msg: string) => {
|
||||
setSuccessMessage(msg);
|
||||
setErrorMessage(null);
|
||||
setTimeout(() => setSuccessMessage(null), 5000);
|
||||
};
|
||||
|
||||
const showError = (msg: string) => {
|
||||
setErrorMessage(msg);
|
||||
setSuccessMessage(null);
|
||||
setTimeout(() => setErrorMessage(null), 8000);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (globalConfig?.operator?.email) {
|
||||
setOperatorEmail(globalConfig.operator.email);
|
||||
}
|
||||
}, [globalConfig]);
|
||||
|
||||
const handleOperatorSave = async () => {
|
||||
if (!globalConfig || !operatorEmail) return;
|
||||
try {
|
||||
await updateGlobalConfig({
|
||||
...globalConfig,
|
||||
operator: { ...globalConfig.operator, email: operatorEmail },
|
||||
});
|
||||
setEditingOperator(false);
|
||||
showSuccess('Operator email saved');
|
||||
} catch (err) {
|
||||
showError(`Failed to save operator: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleOperatorCancel = () => {
|
||||
setOperatorEmail(globalConfig?.operator?.email || '');
|
||||
setEditingOperator(false);
|
||||
};
|
||||
|
||||
usePageHelp({
|
||||
title: 'What is the Central Service?',
|
||||
description: (
|
||||
<>
|
||||
<p className="mb-3 leading-relaxed">
|
||||
The Central Service is the "brain" of your personal cloud. It acts as the main coordinator that manages
|
||||
all the different services running on your network. Think of it like the control tower at an airport -
|
||||
it keeps track of what's happening, routes traffic between services, and ensures everything works together smoothly.
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
This service handles configuration management, service discovery, and provides the web interface you're using right now.
|
||||
</p>
|
||||
</>
|
||||
),
|
||||
icon: <BookOpen className="h-6 w-6 text-blue-600 dark:text-blue-400" />,
|
||||
color: 'bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-950/20 dark:to-indigo-950/20',
|
||||
actions: (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-blue-700 border-blue-300 hover:bg-blue-100 dark:text-blue-300 dark:border-blue-700 dark:hover:bg-blue-900/20"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
Learn more about service orchestration
|
||||
</Button>
|
||||
),
|
||||
});
|
||||
|
||||
if (statusError) {
|
||||
return (
|
||||
<Card className="p-8 text-center">
|
||||
<AlertCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-medium mb-2">Error Loading Central Status</h3>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
{(statusError as Error)?.message || 'An error occurred'}
|
||||
</p>
|
||||
<Button onClick={() => window.location.reload()}>Reload Page</Button>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold tracking-tight">Wild Central</h2>
|
||||
<p className="text-muted-foreground">Manage your Wild Central server</p>
|
||||
</div>
|
||||
{centralStatus && (
|
||||
<Badge variant="success" className="gap-1">
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
{centralStatus.status === 'running' ? 'Running' : centralStatus.status}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{centralStatus?.pendingRestart && (
|
||||
<div className="flex items-center justify-between gap-3 rounded-md border border-amber-300 bg-amber-50 dark:bg-amber-950/30 dark:border-amber-700 px-4 py-3 text-sm text-amber-800 dark:text-amber-300">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertCircle className="h-4 w-4 shrink-0" />
|
||||
<span>Configuration changed — restart Wild Central for changes to take effect.</span>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="shrink-0 border-amber-400 text-amber-800 dark:text-amber-300 hover:bg-amber-100 dark:hover:bg-amber-900/30"
|
||||
onClick={restartDaemon}
|
||||
disabled={isDaemonRestarting}
|
||||
>
|
||||
{isDaemonRestarting ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : <RotateCw className="h-3 w-3 mr-1" />}
|
||||
{isDaemonRestarting ? 'Restarting...' : 'Restart Now'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{successMessage && (
|
||||
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
|
||||
<CheckCircle className="h-4 w-4 text-green-600" />
|
||||
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{errorMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{statusLoading ? (
|
||||
<Card className="p-6">
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="p-4 border-l-4 border-l-blue-500">
|
||||
<div className="flex items-start gap-3">
|
||||
<Settings className="h-5 w-5 text-blue-500 mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<div className="text-sm text-muted-foreground mb-1">Version</div>
|
||||
<div className="font-medium font-mono">{centralStatus?.version || 'Unknown'}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<HardDrive className="h-5 w-5 text-indigo-500 mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<div className="text-sm text-muted-foreground mb-1">Data Directory</div>
|
||||
<div className="font-medium font-mono text-sm break-all">
|
||||
{centralStatus?.dataDir || '/var/lib/wild-central'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card className="p-4 border-l-4 border-l-amber-500">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Mail className="h-5 w-5 text-amber-500" />
|
||||
<div className="text-sm text-muted-foreground">Operator Email</div>
|
||||
</div>
|
||||
{!editingOperator && (
|
||||
<Button variant="ghost" size="sm" onClick={() => setEditingOperator(true)} disabled={isUpdating}>
|
||||
<Edit2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{editingOperator ? (
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<Label htmlFor="operator-email">Email</Label>
|
||||
<Input
|
||||
id="operator-email"
|
||||
type="email"
|
||||
value={operatorEmail}
|
||||
onChange={(e) => setOperatorEmail(e.target.value)}
|
||||
placeholder="email@example.com"
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" size="sm" onClick={handleOperatorCancel} disabled={isUpdating}>
|
||||
<X className="h-4 w-4 mr-1" />Cancel
|
||||
</Button>
|
||||
<Button size="sm" onClick={handleOperatorSave} disabled={isUpdating || !operatorEmail}>
|
||||
{isUpdating ? <Loader2 className="h-4 w-4 mr-1 animate-spin" /> : <Check className="h-4 w-4 mr-1" />}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="font-medium font-mono text-sm ml-7">
|
||||
{globalConfig?.operator?.email || (
|
||||
<span className="text-muted-foreground italic">Not configured</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
426
web/src/components/CloudflareComponent.tsx
Normal file
426
web/src/components/CloudflareComponent.tsx
Normal file
@@ -0,0 +1,426 @@
|
||||
import { useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Card, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input, Label } from './ui';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import {
|
||||
Cloud, CheckCircle, XCircle, AlertCircle, Loader2, Edit2,
|
||||
RefreshCw, ExternalLink, BookOpen, Globe, Key, Shield, Check, X, KeyRound,
|
||||
} from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useCloudflare } from '../hooks/useCloudflare';
|
||||
import { useConfig } from '../hooks';
|
||||
import { useDdns } from '../hooks/useDdns';
|
||||
import { useCert } from '../hooks/useCert';
|
||||
import { secretsApi } from '../services/api';
|
||||
import { usePageHelp } from '../hooks/usePageHelp';
|
||||
|
||||
export function CloudflareComponent() {
|
||||
const { verification, isLoading: isVerifying, refetch: reverify } = useCloudflare();
|
||||
const { config: globalConfig, updateConfig: updateGlobalConfig, isUpdating } = useConfig();
|
||||
const { status: ddnsStatus } = useDdns();
|
||||
const { status: certStatus, isLoading: certLoading, provision: provisionCert, isProvisioning, provisionError } = useCert();
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const { data: globalSecrets } = useQuery({
|
||||
queryKey: ['globalSecrets'],
|
||||
queryFn: () => secretsApi.get(),
|
||||
});
|
||||
const updateSecretsMutation = useMutation({
|
||||
mutationFn: (values: Record<string, unknown>) => secretsApi.update(values),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['globalSecrets'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['cloudflare', 'verify'] });
|
||||
setEditingToken(false);
|
||||
setTokenValue('');
|
||||
showSuccess('Cloudflare API token saved');
|
||||
},
|
||||
onError: (err) => {
|
||||
showError(String(err));
|
||||
},
|
||||
});
|
||||
|
||||
const cfTokenIsSet = !!(globalSecrets as Record<string, unknown> | undefined)
|
||||
&& !!(globalSecrets as { cloudflare?: { apiToken?: string } })?.cloudflare?.apiToken;
|
||||
|
||||
const [editingToken, setEditingToken] = useState(false);
|
||||
const [tokenValue, setTokenValue] = useState('');
|
||||
const [editingDomain, setEditingDomain] = useState(false);
|
||||
const [domainInput, setDomainInput] = useState('');
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
const showSuccess = (msg: string) => {
|
||||
setSuccessMessage(msg);
|
||||
setErrorMessage(null);
|
||||
setTimeout(() => setSuccessMessage(null), 5000);
|
||||
};
|
||||
|
||||
const showError = (msg: string) => {
|
||||
setErrorMessage(msg);
|
||||
setSuccessMessage(null);
|
||||
setTimeout(() => setErrorMessage(null), 8000);
|
||||
};
|
||||
|
||||
usePageHelp({
|
||||
title: 'Why Cloudflare?',
|
||||
description: (
|
||||
<>
|
||||
<p className="mb-3 leading-relaxed">
|
||||
Wild Cloud uses Cloudflare to manage DNS records and provision TLS certificates for your domains.
|
||||
A Cloudflare API token enables three key features: <strong>Dynamic DNS</strong> keeps your domain
|
||||
pointed at your changing public IP, <strong>TLS certificates</strong> are provisioned via
|
||||
Let's Encrypt DNS-01 challenges, and <strong>ExternalDNS</strong> automatically creates DNS records
|
||||
when you deploy apps.
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Create an API token in your Cloudflare dashboard with <strong>Zone:DNS:Edit</strong> and{' '}
|
||||
<strong>Zone:Zone:Read</strong> permissions, scoped to your domain's zone.
|
||||
</p>
|
||||
</>
|
||||
),
|
||||
icon: <BookOpen className="h-6 w-6 text-orange-600 dark:text-orange-400" />,
|
||||
color: 'bg-gradient-to-r from-orange-50 to-amber-50 dark:from-orange-950/20 dark:to-amber-950/20',
|
||||
actions: (
|
||||
<a
|
||||
href="https://developers.cloudflare.com/fundamentals/api/get-started/create-token/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-orange-700 border-orange-300 hover:bg-orange-100 dark:text-orange-300 dark:border-orange-700 dark:hover:bg-orange-900/20"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
Create a Cloudflare API token
|
||||
</Button>
|
||||
</a>
|
||||
),
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Page Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold tracking-tight">Cloudflare</h2>
|
||||
<p className="text-muted-foreground">Manage your Cloudflare integration for DNS and TLS</p>
|
||||
</div>
|
||||
{verification?.tokenValid && (
|
||||
<Badge variant="success" className="gap-1">
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
Connected
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Alerts */}
|
||||
{successMessage && (
|
||||
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
|
||||
<CheckCircle className="h-4 w-4 text-green-600" />
|
||||
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{errorMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* API Token Card */}
|
||||
<Card className="p-4 border-l-4 border-l-orange-500">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Key className="h-5 w-5 text-orange-500" />
|
||||
<div className="font-medium">API Token</div>
|
||||
</div>
|
||||
{!editingToken && (
|
||||
<Button variant="outline" size="sm" onClick={() => setEditingToken(true)} className="gap-1">
|
||||
<Edit2 className="h-3 w-3" />
|
||||
{cfTokenIsSet ? 'Update' : 'Set'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{!editingToken && (
|
||||
cfTokenIsSet
|
||||
? <p className="text-sm text-green-600 dark:text-green-400 ml-7">Configured</p>
|
||||
: <p className="text-sm text-muted-foreground ml-7">Not set — required for DNS and TLS features</p>
|
||||
)}
|
||||
{editingToken && (
|
||||
<div className="space-y-2 ml-7">
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="Cloudflare API token..."
|
||||
value={tokenValue}
|
||||
onChange={(e) => setTokenValue(e.target.value)}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => updateSecretsMutation.mutate({ cloudflare: { apiToken: tokenValue } })}
|
||||
disabled={updateSecretsMutation.isPending || !tokenValue}
|
||||
>
|
||||
{updateSecretsMutation.isPending ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
|
||||
Save
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => { setEditingToken(false); setTokenValue(''); }}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Central Domain & TLS Card */}
|
||||
<Card className="p-4 border-l-4 border-l-green-500">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Globe className="h-5 w-5 text-green-500" />
|
||||
<div className="font-medium">Central Domain</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{certStatus?.cert?.exists && (
|
||||
<Badge variant="success" className="gap-1">
|
||||
<Shield className="h-3 w-3" />
|
||||
TLS
|
||||
</Badge>
|
||||
)}
|
||||
{!editingDomain && (
|
||||
<Button variant="ghost" size="sm" onClick={() => {
|
||||
setDomainInput(globalConfig?.cloud?.central?.domain || '');
|
||||
setEditingDomain(true);
|
||||
}} disabled={isUpdating}>
|
||||
<Edit2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{editingDomain ? (
|
||||
<div className="space-y-3 ml-7">
|
||||
<div>
|
||||
<Label htmlFor="central-domain">Domain</Label>
|
||||
<Input
|
||||
id="central-domain"
|
||||
value={domainInput}
|
||||
onChange={(e) => setDomainInput(e.target.value)}
|
||||
placeholder="central.example.com"
|
||||
className="mt-1 font-mono"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Must resolve to this server (via internal DNS or VPN).
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => setEditingDomain(false)} disabled={isUpdating}>
|
||||
<X className="h-4 w-4 mr-1" />Cancel
|
||||
</Button>
|
||||
<Button size="sm" onClick={async () => {
|
||||
if (!globalConfig) return;
|
||||
try {
|
||||
await updateGlobalConfig({
|
||||
...globalConfig,
|
||||
cloud: {
|
||||
...globalConfig.cloud,
|
||||
central: { domain: domainInput },
|
||||
},
|
||||
});
|
||||
setEditingDomain(false);
|
||||
showSuccess('Central domain saved');
|
||||
} catch (err) {
|
||||
showError(`Failed to save domain: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}} disabled={isUpdating}>
|
||||
{isUpdating ? <Loader2 className="h-4 w-4 mr-1 animate-spin" /> : <Check className="h-4 w-4 mr-1" />}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="font-mono text-sm ml-7">
|
||||
{globalConfig?.cloud?.central?.domain ? (
|
||||
<a
|
||||
href={`https://${globalConfig.cloud.central.domain}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
{globalConfig.cloud.central.domain}
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-muted-foreground italic">Not configured</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{globalConfig?.cloud?.central?.domain && (
|
||||
<div className="ml-7 space-y-2">
|
||||
{certLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : certStatus?.cert?.exists ? (
|
||||
<div className="text-sm space-y-1">
|
||||
<div className="flex items-center gap-2 text-green-600 dark:text-green-400">
|
||||
<Shield className="h-4 w-4" />
|
||||
<span>Valid TLS certificate</span>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Expires in {certStatus.cert.daysLeft} days
|
||||
{certStatus.cert.issuerCN && <> · {certStatus.cert.issuerCN}</>}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2 text-amber-600 dark:text-amber-400 text-sm">
|
||||
<KeyRound className="h-4 w-4" />
|
||||
<span>No TLS certificate</span>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
try { await provisionCert(); } catch { /* error shown below */ }
|
||||
}}
|
||||
disabled={isProvisioning}
|
||||
className="gap-1"
|
||||
>
|
||||
{isProvisioning ? <Loader2 className="h-3 w-3 animate-spin" /> : <Shield className="h-3 w-3" />}
|
||||
{isProvisioning ? 'Provisioning...' : 'Provision TLS Certificate'}
|
||||
</Button>
|
||||
{provisionError && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">{(provisionError as Error).message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Verification Checklist Card */}
|
||||
<Card className="p-4 border-l-4 border-l-blue-500">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="h-5 w-5 text-blue-500" />
|
||||
<div className="font-medium">Token Verification</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => reverify()}
|
||||
disabled={isVerifying}
|
||||
className="gap-1"
|
||||
>
|
||||
{isVerifying ? <Loader2 className="h-3 w-3 animate-spin" /> : <RefreshCw className="h-3 w-3" />}
|
||||
Verify
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isVerifying && !verification ? (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground ml-7">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Verifying token...
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2 ml-7">
|
||||
{/* Token configured */}
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
{verification?.tokenConfigured
|
||||
? <CheckCircle className="h-4 w-4 text-green-500" />
|
||||
: <XCircle className="h-4 w-4 text-muted-foreground" />}
|
||||
<span>Token configured</span>
|
||||
</div>
|
||||
|
||||
{/* Token valid */}
|
||||
{verification?.tokenConfigured && (
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
{verification?.tokenValid
|
||||
? <CheckCircle className="h-4 w-4 text-green-500" />
|
||||
: <XCircle className="h-4 w-4 text-red-500" />}
|
||||
<span>Token valid{verification?.tokenStatus ? ` (${verification.tokenStatus})` : ''}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Accessible zones */}
|
||||
{verification?.tokenValid && verification.zones && verification.zones.length > 0 && (
|
||||
<div className="flex items-start gap-2 text-sm">
|
||||
<CheckCircle className="h-4 w-4 text-green-500 mt-0.5" />
|
||||
<div>
|
||||
<span>Accessible zones: </span>
|
||||
<span className="inline-flex flex-wrap gap-1 mt-1">
|
||||
{verification.zones.map((zone) => (
|
||||
<span key={zone.id} className="font-mono bg-muted px-2 py-0.5 rounded text-xs">
|
||||
{zone.name}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error */}
|
||||
{verification?.error && (
|
||||
<div className="flex items-center gap-2 text-sm text-red-600 dark:text-red-400">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<span>{verification.error}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Feature Status Card */}
|
||||
<Card className="p-4 border-l-4 border-l-green-500">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Globe className="h-5 w-5 text-green-500" />
|
||||
<div className="font-medium">Features Using This Token</div>
|
||||
</div>
|
||||
</div>
|
||||
<CardContent className="p-0 ml-7">
|
||||
<div className="space-y-3">
|
||||
{/* DDNS */}
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Cloud className="h-4 w-4 text-muted-foreground" />
|
||||
<span>Dynamic DNS</span>
|
||||
</div>
|
||||
{ddnsStatus?.enabled
|
||||
? <Badge variant="success" className="text-xs">Active</Badge>
|
||||
: <Badge variant="secondary" className="text-xs">Disabled</Badge>}
|
||||
</div>
|
||||
|
||||
{/* TLS Certificates */}
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||
<span>TLS Certificate</span>
|
||||
</div>
|
||||
{certStatus?.cert?.exists
|
||||
? <Badge variant="success" className="text-xs">
|
||||
Valid ({certStatus.cert.daysLeft}d left)
|
||||
</Badge>
|
||||
: certStatus?.configured
|
||||
? <Badge variant="secondary" className="text-xs">Not provisioned</Badge>
|
||||
: <Badge variant="secondary" className="text-xs">Not configured</Badge>}
|
||||
</div>
|
||||
|
||||
{/* ExternalDNS note */}
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Globe className="h-4 w-4 text-muted-foreground" />
|
||||
<span>ExternalDNS</span>
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground">Per-instance</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
49
web/src/components/CopyButton.tsx
Normal file
49
web/src/components/CopyButton.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
import { useState } from 'react';
|
||||
import { Copy, Check } from 'lucide-react';
|
||||
import { Button } from './ui/button';
|
||||
|
||||
interface CopyButtonProps {
|
||||
content: string;
|
||||
label?: string;
|
||||
variant?: 'default' | 'outline' | 'secondary' | 'ghost';
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function CopyButton({
|
||||
content,
|
||||
label = 'Copy',
|
||||
variant = 'outline',
|
||||
disabled = false,
|
||||
}: CopyButtonProps) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const handleCopy = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(content);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
onClick={handleCopy}
|
||||
variant={variant}
|
||||
disabled={disabled}
|
||||
>
|
||||
{copied ? (
|
||||
<>
|
||||
<Check className="h-4 w-4" />
|
||||
Copied
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Copy className="h-4 w-4" />
|
||||
{label}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
760
web/src/components/CrowdSecComponent.tsx
Normal file
760
web/src/components/CrowdSecComponent.tsx
Normal file
@@ -0,0 +1,760 @@
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from 'recharts';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input } from './ui/input';
|
||||
import { Label } from './ui/label';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
|
||||
import {
|
||||
ShieldAlert, Loader2, AlertCircle, CheckCircle, Ban, X, Trash2,
|
||||
BookOpen, Shield, Activity, Zap, RefreshCw, Globe,
|
||||
} from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
// Instance provisioning removed — Central-only mode
|
||||
import { useCrowdSec } from '../hooks/useCrowdSec';
|
||||
import type { AddDecisionRequest, CrowdSecAlert } from '../services/api/networking';
|
||||
|
||||
type Timescale = '1h' | '6h' | '24h' | '7d';
|
||||
|
||||
const TIMESCALES: { key: Timescale; label: string; ms: number; bucketMs: number }[] = [
|
||||
{ key: '1h', label: '1h', ms: 60 * 60 * 1000, bucketMs: 5 * 60 * 1000 },
|
||||
{ key: '6h', label: '6h', ms: 6 * 60 * 60 * 1000, bucketMs: 30 * 60 * 1000 },
|
||||
{ key: '24h', label: '24h', ms: 24 * 60 * 60 * 1000, bucketMs: 2 * 60 * 60 * 1000 },
|
||||
{ key: '7d', label: '7d', ms: 7 * 24 * 60 * 60 * 1000, bucketMs: 24 * 60 * 60 * 1000 },
|
||||
];
|
||||
|
||||
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
|
||||
function formatBucketLabel(ts: number, scale: Timescale): string {
|
||||
const d = new Date(ts);
|
||||
if (scale === '7d') return d.toLocaleDateString(undefined, { timeZone: tz, weekday: 'short', month: 'short', day: 'numeric' });
|
||||
return d.toLocaleTimeString(undefined, { timeZone: tz, hour: '2-digit', minute: '2-digit', hour12: false });
|
||||
}
|
||||
|
||||
function binAlerts(alerts: CrowdSecAlert[], scale: Timescale) {
|
||||
const cfg = TIMESCALES.find(t => t.key === scale)!;
|
||||
const now = Date.now();
|
||||
// Align start to a clean bucket boundary so labels fall on round times
|
||||
const rawStart = now - cfg.ms;
|
||||
const alignedStart = Math.floor(rawStart / cfg.bucketMs) * cfg.bucketMs;
|
||||
const numBuckets = Math.ceil((now - alignedStart) / cfg.bucketMs);
|
||||
const buckets = Array.from({ length: numBuckets }, (_, i) => ({
|
||||
label: formatBucketLabel(alignedStart + i * cfg.bucketMs, scale),
|
||||
detections: 0,
|
||||
}));
|
||||
for (const a of alerts) {
|
||||
const t = new Date(a.createdAt).getTime();
|
||||
if (t < alignedStart) continue;
|
||||
const idx = Math.floor((t - alignedStart) / cfg.bucketMs);
|
||||
if (idx >= 0 && idx < numBuckets) buckets[idx].detections++;
|
||||
}
|
||||
return buckets;
|
||||
}
|
||||
|
||||
function formatRelativeTime(isoString?: string): string {
|
||||
if (!isoString) return 'unknown';
|
||||
const diff = Date.now() - new Date(isoString).getTime();
|
||||
const minutes = Math.floor(diff / 60000);
|
||||
if (minutes < 1) return 'just now';
|
||||
if (minutes < 60) return `${minutes}m ago`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
if (hours < 24) return `${hours}h ago`;
|
||||
return `${Math.floor(hours / 24)}d ago`;
|
||||
}
|
||||
|
||||
function scenarioHubUrl(scenario: string): string | null {
|
||||
if (!scenario) return null;
|
||||
const parts = scenario.split('/');
|
||||
// Only link hub scenarios in author/name format (e.g. crowdsecurity/http-probing-classb)
|
||||
// CAPI category labels (http:scan, ssh:bruteforce) have no individual hub pages
|
||||
if (parts.length === 2 && parts[0] !== 'custom') {
|
||||
return `https://app.crowdsec.net/hub/author/${parts[0]}/configurations/name/${parts[1]}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const KNOWN_ABBREV = new Set(['ssh', 'http', 'https', 'tcp', 'udp', 'ftp', 'ip', 'dns', 'tls', 'dos', 'ddos', 'bf']);
|
||||
|
||||
function titleCaseScenario(s: string): string {
|
||||
return s.replace(/[:\-_]/g, ' ').split(' ').filter(Boolean).map(w =>
|
||||
KNOWN_ABBREV.has(w.toLowerCase()) ? w.toUpperCase() : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()
|
||||
).join(' ');
|
||||
}
|
||||
|
||||
function friendlyReason(reason: string): string {
|
||||
if (!reason) return 'Community blocklist';
|
||||
const map: Record<string, string> = {
|
||||
'crowdsecurity/http-scan-classb': 'HTTP Scanner',
|
||||
'crowdsecurity/ssh-slow-bruteforce': 'SSH Brute Force (slow)',
|
||||
'crowdsecurity/ssh-bf': 'SSH Brute Force',
|
||||
'crowdsecurity/ssh-bruteforce': 'SSH Brute Force',
|
||||
'crowdsecurity/http-dos': 'HTTP DoS',
|
||||
'crowdsecurity/http-bruteforce': 'HTTP Brute Force',
|
||||
'crowdsecurity/http-exploit': 'HTTP Exploit',
|
||||
'crowdsecurity/http-crawl': 'HTTP Crawler',
|
||||
'crowdsecurity/http-bad-user-agent': 'Bad User Agent',
|
||||
'crowdsecurity/iptables-scan-multi_ports': 'Port Scanner',
|
||||
};
|
||||
if (map[reason]) return map[reason];
|
||||
const short = reason.includes('/') ? reason.split('/').slice(1).join(' ') : reason;
|
||||
return titleCaseScenario(short);
|
||||
}
|
||||
|
||||
function parseDuration(dur?: string): string {
|
||||
if (!dur) return '';
|
||||
// Go duration: "164h1m31s" → "6d 20h"
|
||||
const h = dur.match(/(\d+)h/);
|
||||
const m = dur.match(/(\d+)m/);
|
||||
const hours = h ? parseInt(h[1]) : 0;
|
||||
const mins = m ? parseInt(m[1]) : 0;
|
||||
if (hours >= 24) {
|
||||
const days = Math.floor(hours / 24);
|
||||
const rem = hours % 24;
|
||||
return rem > 0 ? `${days}d ${rem}h` : `${days}d`;
|
||||
}
|
||||
if (hours > 0) return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
|
||||
return `${mins}m`;
|
||||
}
|
||||
|
||||
interface BlockFormValues {
|
||||
ip: string;
|
||||
type: 'ban' | 'allow';
|
||||
duration: string;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export function CrowdSecComponent() {
|
||||
const instances: string[] = [];
|
||||
const {
|
||||
status,
|
||||
isLoadingStatus,
|
||||
summary,
|
||||
isLoadingSummary,
|
||||
alerts,
|
||||
isLoadingAlerts,
|
||||
refetchAlerts,
|
||||
graphAlerts,
|
||||
isLoadingGraphAlerts,
|
||||
decisions,
|
||||
addDecision,
|
||||
isAddingDecision,
|
||||
addDecisionError,
|
||||
deleteDecision,
|
||||
deleteBouncer,
|
||||
deleteMachine,
|
||||
provision,
|
||||
isProvisioning,
|
||||
} = useCrowdSec();
|
||||
|
||||
const [provisionResults, setProvisionResults] = useState<Record<string, { ok: boolean; message: string }>>({});
|
||||
const [provisioningInstance, setProvisioningInstance] = useState<string | null>(null);
|
||||
const [blockSuccess, setBlockSuccess] = useState<string | null>(null);
|
||||
const [timescale, setTimescale] = useState<Timescale>('24h');
|
||||
|
||||
const { register, handleSubmit, reset, setValue, watch, formState: { errors } } = useForm<BlockFormValues>({
|
||||
defaultValues: { ip: '', type: 'ban', duration: '24h', reason: 'manual' },
|
||||
});
|
||||
const selectedType = watch('type');
|
||||
|
||||
function handleProvision(instanceName: string) {
|
||||
setProvisioningInstance(instanceName);
|
||||
provision(instanceName, {
|
||||
onSuccess: (data) => {
|
||||
setProvisionResults((prev) => ({ ...prev, [instanceName]: { ok: true, message: data.message } }));
|
||||
setProvisioningInstance(null);
|
||||
},
|
||||
onError: (err) => {
|
||||
setProvisionResults((prev) => ({ ...prev, [instanceName]: { ok: false, message: (err as Error).message } }));
|
||||
setProvisioningInstance(null);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function onBlockSubmit(values: BlockFormValues) {
|
||||
setBlockSuccess(null);
|
||||
const req: AddDecisionRequest = { ip: values.ip, type: values.type, reason: values.reason, duration: values.duration };
|
||||
addDecision(req, {
|
||||
onSuccess: (data) => {
|
||||
setBlockSuccess(data.message);
|
||||
reset();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const sortedReasons = summary
|
||||
? Object.entries(summary.byReason).sort(([, a], [, b]) => b - a)
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4 mb-6">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<ShieldAlert className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">CrowdSec</h2>
|
||||
<p className="text-muted-foreground">Collaborative intrusion detection — protecting your infrastructure with community threat intelligence</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Educational card */}
|
||||
<Card className="bg-gradient-to-br from-cyan-50 to-blue-50 dark:from-cyan-900/20 dark:to-blue-900/20 border-cyan-200 dark:border-cyan-800">
|
||||
<CardContent className="pt-4">
|
||||
<div className="flex gap-3">
|
||||
<BookOpen className="h-5 w-5 text-cyan-600 dark:text-cyan-400 shrink-0 mt-0.5" />
|
||||
<div className="space-y-1 text-sm text-cyan-900 dark:text-cyan-100">
|
||||
<p>
|
||||
<strong>CrowdSec</strong> analyzes logs from your k8s clusters, detects attacks, and shares threat
|
||||
intelligence with the community. Wild Central runs the <strong>LAPI</strong> — the hub that agents
|
||||
report to and that bouncers query for the live blocklist. Your cluster contributes to and benefits
|
||||
from a shared blocklist of millions of known malicious IPs.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* LAPI Status */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>LAPI Status</CardTitle>
|
||||
</div>
|
||||
{isLoadingStatus ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<Badge variant={status?.active ? 'success' : 'warning'} className="gap-1">
|
||||
{status?.active && <CheckCircle className="h-3 w-3" />}
|
||||
{status?.active ? 'Running' : 'Stopped'}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{!status?.active && !isLoadingStatus && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
CrowdSec is not running on Wild Central. Install it with{' '}
|
||||
<code className="font-mono text-xs bg-muted px-1 rounded">apt install crowdsec crowdsec-firewall-bouncer</code>
|
||||
{' '}or reinstall wild-cloud-central.
|
||||
</p>
|
||||
)}
|
||||
{status?.active && (
|
||||
<>
|
||||
<div className="flex items-center justify-between py-2 px-3 rounded bg-muted">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||
<span>Perimeter firewall enforcement</span>
|
||||
<span className="text-xs text-muted-foreground">(nftables on Wild Central)</span>
|
||||
</div>
|
||||
<Badge variant={status.firewallBouncer ? 'success' : 'warning'} className="gap-1">
|
||||
{status.firewallBouncer && <CheckCircle className="h-3 w-3" />}
|
||||
{status.firewallBouncer ? 'Active' : 'Stopped'}
|
||||
</Badge>
|
||||
</div>
|
||||
{!status.firewallBouncer && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Install the firewall bouncer to block threats at the perimeter:{' '}
|
||||
<code className="font-mono bg-muted px-1 rounded">apt install crowdsec-firewall-bouncer</code>
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{status.machines.length > 0 && `${status.machines.length} k8s agent${status.machines.length !== 1 ? 's' : ''} reporting. `}
|
||||
{status.bouncers.length > 0 && `${status.bouncers.length} enforcement point${status.bouncers.length !== 1 ? 's' : ''} active.`}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{status?.active && (
|
||||
<>
|
||||
{/* Active Protection Summary */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Activity className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Active Protection</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
IPs currently blocked by the community blocklist (CAPI) and local decisions, enforced by your bouncers.
|
||||
</p>
|
||||
{isLoadingSummary ? (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />Loading ban statistics…
|
||||
</div>
|
||||
) : summary ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Ban className="h-5 w-5 text-red-500" />
|
||||
<span className="text-2xl font-bold">{summary.total.toLocaleString()}</span>
|
||||
</div>
|
||||
<span className="text-sm text-muted-foreground">IPs blocked right now</span>
|
||||
</div>
|
||||
{sortedReasons.length > 0 && (
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">By threat type</p>
|
||||
{sortedReasons.slice(0, 8).map(([reason, count]) => {
|
||||
const pct = Math.round((count / summary.total) * 100);
|
||||
return (
|
||||
<div key={reason} className="flex items-center gap-2 text-sm">
|
||||
<div className="flex-1 flex items-center gap-2">
|
||||
<div
|
||||
className="h-1.5 bg-red-400 rounded"
|
||||
style={{ width: `${Math.max(pct, 2)}%`, maxWidth: '60%' }}
|
||||
/>
|
||||
{scenarioHubUrl(reason) ? (
|
||||
<a href={scenarioHubUrl(reason)!} target="_blank" rel="noopener noreferrer" className="text-muted-foreground hover:text-foreground hover:underline">
|
||||
{friendlyReason(reason)}
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-muted-foreground">{friendlyReason(reason)}</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="font-mono text-xs tabular-nums">{count.toLocaleString()}</span>
|
||||
<span className="text-xs text-muted-foreground w-8 text-right">{pct}%</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{sortedReasons.length > 8 && (
|
||||
<p className="text-xs text-muted-foreground">+{sortedReasons.length - 8} more categories</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Detections Over Time */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Activity className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Detections Over Time</CardTitle>
|
||||
</div>
|
||||
<div className="flex gap-1">
|
||||
{TIMESCALES.map(t => (
|
||||
<Button
|
||||
key={t.key}
|
||||
variant={timescale === t.key ? 'default' : 'ghost'}
|
||||
size="sm"
|
||||
className="h-7 px-2 text-xs"
|
||||
onClick={() => setTimescale(t.key)}
|
||||
>
|
||||
{t.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoadingGraphAlerts ? (
|
||||
<div className="flex items-center justify-center h-40 gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />Loading…
|
||||
</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height={160}>
|
||||
<BarChart data={binAlerts(graphAlerts, timescale)} margin={{ top: 4, right: 8, left: -20, bottom: 0 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
|
||||
<XAxis dataKey="label" tick={{ fontSize: 10 }} interval="preserveStartEnd" className="fill-muted-foreground" />
|
||||
<YAxis allowDecimals={false} tick={{ fontSize: 10 }} className="fill-muted-foreground" />
|
||||
<Tooltip
|
||||
contentStyle={{ fontSize: 12 }}
|
||||
formatter={(v) => [v, 'detections']}
|
||||
/>
|
||||
<Bar dataKey="detections" fill="#ef4444" radius={[2, 2, 0, 0]} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Recent Alert Feed */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Activity className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Recent Detections</CardTitle>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={() => refetchAlerts()} className="h-7 gap-1.5 text-xs">
|
||||
<RefreshCw className="h-3 w-3" />Refresh
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
Attack events detected by your k8s agents and reported to this LAPI. Each event results in a ban
|
||||
that is shared with the CrowdSec community.
|
||||
</p>
|
||||
{isLoadingAlerts ? (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />Loading…
|
||||
</div>
|
||||
) : alerts.length === 0 ? (
|
||||
<div className="text-center py-6">
|
||||
<Shield className="h-10 w-10 text-muted-foreground mx-auto mb-2" />
|
||||
<p className="text-sm text-muted-foreground">No detections yet.</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Events appear here when k8s agents detect and report attacks. The community blocklist
|
||||
(CAPI) is already protecting you even before local detections.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1 max-h-72 overflow-y-auto">
|
||||
<div className="grid grid-cols-[1fr_auto_auto_auto] gap-x-3 text-xs text-muted-foreground font-medium px-2 pb-1">
|
||||
<span>Source IP</span>
|
||||
<span>Threat</span>
|
||||
<span>Agent</span>
|
||||
<span>When</span>
|
||||
</div>
|
||||
{alerts.map((alert) => (
|
||||
<div key={alert.id} className="grid grid-cols-[1fr_auto_auto_auto] gap-x-3 items-center py-1.5 px-2 bg-muted rounded text-sm">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<span className="font-mono text-xs truncate">{alert.sourceIP || '—'}</span>
|
||||
{alert.country && (
|
||||
<span className="text-xs text-muted-foreground flex items-center gap-0.5 shrink-0">
|
||||
<Globe className="h-3 w-3" />{alert.country}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{scenarioHubUrl(alert.scenario) ? (
|
||||
<a href={scenarioHubUrl(alert.scenario)!} target="_blank" rel="noopener noreferrer" className="text-xs text-muted-foreground whitespace-nowrap hover:text-foreground hover:underline">
|
||||
{friendlyReason(alert.scenario)}
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">{friendlyReason(alert.scenario)}</span>
|
||||
)}
|
||||
<span className="text-xs font-mono text-muted-foreground whitespace-nowrap">{alert.machineId?.replace(/^wc-/, '') ?? '—'}</span>
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">{formatRelativeTime(alert.createdAt)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Manual Decisions: Block / Allow */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Ban className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Block or Allow an IP</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Manually ban an IP (e.g. an attacker you've identified) or add a local allowlist entry
|
||||
to prevent a legitimate IP from being blocked by the community list.
|
||||
</p>
|
||||
|
||||
<form onSubmit={handleSubmit(onBlockSubmit)} className="space-y-3">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label htmlFor="ip">IP Address</Label>
|
||||
<Input
|
||||
id="ip"
|
||||
placeholder="1.2.3.4"
|
||||
className="mt-1 font-mono"
|
||||
{...register('ip', {
|
||||
required: 'Required',
|
||||
pattern: { value: /^[\d.:/a-fA-F]+$/, message: 'Invalid IP' },
|
||||
})}
|
||||
/>
|
||||
{errors.ip && <p className="text-xs text-red-600 mt-1">{errors.ip.message}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="reason">Reason</Label>
|
||||
<Input
|
||||
id="reason"
|
||||
placeholder="manual"
|
||||
className="mt-1"
|
||||
{...register('reason')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label>Action</Label>
|
||||
<Select value={selectedType} onValueChange={(v) => setValue('type', v as 'ban' | 'allow')}>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="ban">Ban (block)</SelectItem>
|
||||
<SelectItem value="allow">Allow (whitelist)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Duration</Label>
|
||||
<Select defaultValue="24h" onValueChange={(v) => setValue('duration', v)}>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="1h">1 hour</SelectItem>
|
||||
<SelectItem value="24h">24 hours</SelectItem>
|
||||
<SelectItem value="168h">7 days</SelectItem>
|
||||
<SelectItem value="720h">30 days</SelectItem>
|
||||
<SelectItem value="8760h">1 year</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{blockSuccess && (
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">{blockSuccess}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{addDecisionError && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">{(addDecisionError as Error).message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Button type="submit" size="sm" disabled={isAddingDecision} className="gap-2">
|
||||
{isAddingDecision ? <Loader2 className="h-4 w-4 animate-spin" /> : <Ban className="h-4 w-4" />}
|
||||
{selectedType === 'allow' ? 'Add to Allowlist' : 'Block IP'}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{/* Local decisions list */}
|
||||
{decisions.length > 0 && (
|
||||
<div className="border-t pt-3 space-y-2">
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Active local decisions</p>
|
||||
<div className="space-y-1 max-h-48 overflow-y-auto">
|
||||
{decisions.map((d) => (
|
||||
<div key={d.id} className="flex items-center justify-between py-1.5 px-2 bg-muted rounded text-xs">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{d.type === 'allow'
|
||||
? <CheckCircle className="h-3 w-3 text-green-500 shrink-0" />
|
||||
: <Ban className="h-3 w-3 text-red-500 shrink-0" />
|
||||
}
|
||||
<span className="font-mono truncate">{d.value}</span>
|
||||
<Badge variant="outline" className="text-xs h-4 shrink-0">{d.type}</Badge>
|
||||
<span className="text-muted-foreground truncate">{friendlyReason(d.reason)}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{d.duration && (
|
||||
<span className="text-muted-foreground">{parseDuration(d.duration)}</span>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-5 w-5 p-0 text-muted-foreground hover:text-red-500"
|
||||
onClick={() => deleteDecision(d.id)}
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Registered Agents */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Zap className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Registered Agents</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<strong>Agents</strong> are CrowdSec engines running inside your k8s clusters. They analyze
|
||||
logs, detect threats, and report to this LAPI. Each provisioned Wild Cloud instance registers
|
||||
one agent here.
|
||||
</p>
|
||||
{status.machines.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-3">No agents registered. Provision an instance below.</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{status.machines.map((m) => (
|
||||
<div key={m.machineId} className="flex items-center justify-between py-2 px-3 bg-muted rounded">
|
||||
<div className="space-y-0.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-sm">{m.machineId}</span>
|
||||
<Badge variant={m.isValidated ? 'default' : 'secondary'} className="text-xs h-4">
|
||||
{m.isValidated ? 'validated' : 'pending'}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-xs text-muted-foreground">
|
||||
{m.last_heartbeat && <span>heartbeat {formatRelativeTime(m.last_heartbeat)}</span>}
|
||||
{m.version && <span>{m.version}</span>}
|
||||
{m.ipAddress && <span className="font-mono">{m.ipAddress}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0 text-muted-foreground hover:text-red-500"
|
||||
onClick={() => deleteMachine(m.machineId)}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Registered Bouncers */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Registered Bouncers</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<strong>Bouncers</strong> enforce the blocklist. Wild Central's nftables bouncer blocks at
|
||||
the network perimeter. Each k8s cluster also runs a Traefik bouncer as a second layer.
|
||||
</p>
|
||||
{status.bouncers.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-3">No bouncers registered. Provision an instance to add them.</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{status.bouncers.map((b) => {
|
||||
const isFirewallBouncer = b.type === 'crowdsec-firewall-bouncer';
|
||||
return (
|
||||
<div key={b.name} className="flex items-center justify-between py-2 px-3 bg-muted rounded">
|
||||
<div className="space-y-0.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-sm truncate max-w-64">{b.name}</span>
|
||||
<Badge variant={b.revoked ? 'secondary' : 'default'} className="text-xs h-4">
|
||||
{b.revoked ? 'revoked' : 'active'}
|
||||
</Badge>
|
||||
{isFirewallBouncer && (
|
||||
<Badge variant="outline" className="text-xs h-4 border-orange-400 text-orange-600 dark:text-orange-400">
|
||||
perimeter
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isFirewallBouncer ? 'Crowdsec Firewall Bouncer' : b.type?.replace(/-/g, ' ') || ''}
|
||||
</p>
|
||||
</div>
|
||||
{!isFirewallBouncer && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0 text-muted-foreground hover:text-red-500"
|
||||
onClick={() => deleteBouncer(b.name)}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Provision Instances */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Zap className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Provision Instances</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<strong>Provisioning</strong> connects a Wild Cloud instance's CrowdSec agent to this LAPI —
|
||||
generating credentials, registering agent and bouncer, and writing the LAPI URL into the
|
||||
instance's app config. After provisioning, redeploy the CrowdSec app on the instance.
|
||||
Safe to re-run.
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
{instances.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No instances found.</p>
|
||||
) : (
|
||||
instances.map((instanceName) => {
|
||||
const agentName = `wc-${instanceName}`;
|
||||
const bouncerName = `wc-bouncer-${instanceName}`;
|
||||
const agent = status.machines.find((m) => m.machineId === agentName);
|
||||
const bouncer = status.bouncers.find((b) => b.name === bouncerName);
|
||||
const isActive = provisioningInstance === instanceName;
|
||||
const result = provisionResults[instanceName];
|
||||
|
||||
return (
|
||||
<div key={instanceName} className="rounded border p-3 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-mono text-sm font-medium">{instanceName}</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant={agent ? 'outline' : 'default'}
|
||||
onClick={() => handleProvision(instanceName)}
|
||||
disabled={isProvisioning || isActive}
|
||||
className="gap-2 h-7"
|
||||
>
|
||||
{isActive
|
||||
? <><Loader2 className="h-3 w-3 animate-spin" />Provisioning…</>
|
||||
: agent
|
||||
? <><Zap className="h-3 w-3" />Re-provision</>
|
||||
: <><Zap className="h-3 w-3" />Provision</>
|
||||
}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-xs">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-muted-foreground">Agent:</span>
|
||||
{agent ? (
|
||||
<Badge variant={agent.isValidated ? 'default' : 'secondary'} className="text-xs h-4">
|
||||
{agent.isValidated ? 'validated' : 'pending'}
|
||||
{agent.last_heartbeat && ` · ${formatRelativeTime(agent.last_heartbeat)}`}
|
||||
</Badge>
|
||||
) : (
|
||||
<span className="text-muted-foreground italic">not provisioned</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-muted-foreground">Bouncer:</span>
|
||||
{bouncer ? (
|
||||
<Badge variant={bouncer.revoked ? 'secondary' : 'default'} className="text-xs h-4">
|
||||
{bouncer.revoked ? 'revoked' : 'active'}
|
||||
</Badge>
|
||||
) : (
|
||||
<span className="text-muted-foreground italic">not provisioned</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{result && (
|
||||
<Alert variant={result.ok ? 'default' : 'error'} className="py-2">
|
||||
{result.ok ? <CheckCircle className="h-3 w-3" /> : <AlertCircle className="h-3 w-3" />}
|
||||
<AlertDescription className="text-xs">{result.message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
280
web/src/components/DdnsComponent.tsx
Normal file
280
web/src/components/DdnsComponent.tsx
Normal file
@@ -0,0 +1,280 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input, Label } from './ui';
|
||||
import { Textarea } from './ui/textarea';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import { Globe, Loader2, AlertCircle, CheckCircle, XCircle, RefreshCw, Edit2 } from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useConfig } from '../hooks';
|
||||
import { useDdns } from '../hooks/useDdns';
|
||||
import { secretsApi } from '../services/api';
|
||||
import type { DdnsRecordStatus } from '../services/api/networking';
|
||||
|
||||
export function DdnsComponent() {
|
||||
const { config: globalConfig, updateConfig, isUpdating } = useConfig();
|
||||
const { status: ddnsStatus, isLoadingStatus: isDdnsLoading, trigger: triggerDdns, isTriggering: isDdnsTriggering } = useDdns();
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const { data: globalSecrets } = useQuery({
|
||||
queryKey: ['globalSecrets'],
|
||||
queryFn: () => secretsApi.get(),
|
||||
});
|
||||
const updateSecretsMutation = useMutation({
|
||||
mutationFn: (values: Record<string, unknown>) => secretsApi.update(values),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['globalSecrets'] });
|
||||
setEditingToken(false);
|
||||
setTokenValue('');
|
||||
},
|
||||
});
|
||||
const cfTokenIsSet = !!(globalSecrets as Record<string, unknown> | undefined)
|
||||
&& !!(globalSecrets as { ddns?: { cloudflare?: { apiToken?: string } } })?.ddns?.cloudflare?.apiToken;
|
||||
|
||||
const [editingDdnsConfig, setEditingDdnsConfig] = useState(false);
|
||||
const [ddnsConfigForm, setDdnsConfigForm] = useState({ enabled: false, records: '', intervalMinutes: 5 });
|
||||
const [editingToken, setEditingToken] = useState(false);
|
||||
const [tokenValue, setTokenValue] = useState('');
|
||||
|
||||
const handleDdnsConfigEdit = () => {
|
||||
setDdnsConfigForm({
|
||||
enabled: globalConfig?.cloud?.ddns?.enabled ?? false,
|
||||
records: (globalConfig?.cloud?.ddns?.records ?? []).join('\n'),
|
||||
intervalMinutes: globalConfig?.cloud?.ddns?.intervalMinutes ?? 5,
|
||||
});
|
||||
setEditingDdnsConfig(true);
|
||||
};
|
||||
|
||||
const handleDdnsConfigSave = async () => {
|
||||
if (!globalConfig) return;
|
||||
const records = ddnsConfigForm.records.split('\n').map(r => r.trim()).filter(Boolean);
|
||||
await updateConfig({
|
||||
...globalConfig,
|
||||
cloud: {
|
||||
...globalConfig.cloud,
|
||||
ddns: {
|
||||
enabled: ddnsConfigForm.enabled,
|
||||
provider: 'cloudflare',
|
||||
records,
|
||||
intervalMinutes: ddnsConfigForm.intervalMinutes,
|
||||
},
|
||||
},
|
||||
});
|
||||
setEditingDdnsConfig(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Globe className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">Dynamic DNS</h2>
|
||||
<p className="text-muted-foreground">Keeps your Cloudflare A records pointed at your current public IP</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Status</CardTitle>
|
||||
{isDdnsLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : ddnsStatus?.enabled ? (
|
||||
<Badge variant="success" className="gap-1">
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
Active
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">Disabled</Badge>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{ddnsStatus?.enabled && (
|
||||
<div className="space-y-3">
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-muted-foreground">Public IP</span>
|
||||
<div className="font-mono font-medium mt-0.5">{ddnsStatus.currentIP || '—'}</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">Last checked</span>
|
||||
<div className="font-mono mt-0.5">
|
||||
{ddnsStatus.lastChecked ? new Date(ddnsStatus.lastChecked).toLocaleTimeString() : '—'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{ddnsStatus.lastError && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">{ddnsStatus.lastError}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => triggerDdns()}
|
||||
disabled={isDdnsTriggering}
|
||||
className="gap-2"
|
||||
>
|
||||
{isDdnsTriggering ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
|
||||
Check Now
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Configuration</CardTitle>
|
||||
{!editingDdnsConfig && (
|
||||
<Button variant="outline" size="sm" onClick={handleDdnsConfigEdit} className="gap-1">
|
||||
<Edit2 className="h-3 w-3" />
|
||||
Edit
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{editingDdnsConfig ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="ddns-enabled"
|
||||
checked={ddnsConfigForm.enabled}
|
||||
onChange={e => setDdnsConfigForm(prev => ({ ...prev, enabled: e.target.checked }))}
|
||||
/>
|
||||
<Label htmlFor="ddns-enabled">Enabled</Label>
|
||||
</div>
|
||||
<div>
|
||||
<Label>A Records (one per line)</Label>
|
||||
<Textarea
|
||||
value={ddnsConfigForm.records}
|
||||
onChange={e => setDdnsConfigForm(prev => ({ ...prev, records: e.target.value }))}
|
||||
placeholder={'cloud.example.com\ncloud2.example.com'}
|
||||
className="text-sm h-20 mt-1 font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Check interval (minutes)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={ddnsConfigForm.intervalMinutes}
|
||||
onChange={e => setDdnsConfigForm(prev => ({ ...prev, intervalMinutes: parseInt(e.target.value) || 5 }))}
|
||||
className="h-9 mt-1 w-24"
|
||||
min={1}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={handleDdnsConfigSave} disabled={isUpdating}>
|
||||
{isUpdating ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
|
||||
Save
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => setEditingDdnsConfig(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-muted-foreground">Status:</span>
|
||||
<span>{globalConfig?.cloud?.ddns?.enabled ? 'Enabled' : 'Disabled'}</span>
|
||||
</div>
|
||||
{globalConfig?.cloud?.ddns?.records?.length ? (
|
||||
<div>
|
||||
<span className="text-muted-foreground">Records:</span>
|
||||
<div className="mt-1 space-y-1">
|
||||
{globalConfig.cloud.ddns.records.map(r => {
|
||||
const rs: DdnsRecordStatus | undefined = ddnsStatus?.records?.find(s => s.name === r);
|
||||
return (
|
||||
<div key={r} className="flex items-center gap-2 text-xs">
|
||||
{rs?.ok ? (
|
||||
<CheckCircle className="h-3.5 w-3.5 text-green-500 shrink-0" />
|
||||
) : rs && !rs.ok ? (
|
||||
<XCircle className="h-3.5 w-3.5 text-red-500 shrink-0" />
|
||||
) : null}
|
||||
<span className="font-mono bg-muted px-2 py-0.5 rounded">{r}</span>
|
||||
{rs?.ok && rs.ip && (
|
||||
<span className="text-muted-foreground font-mono">{rs.ip}</span>
|
||||
)}
|
||||
{rs && !rs.ok && rs.error && (
|
||||
<span className="text-red-500 truncate" title={rs.error}>{rs.error}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-muted-foreground text-xs">No A records configured</div>
|
||||
)}
|
||||
{(globalConfig?.cloud?.ddns?.intervalMinutes ?? 0) > 0 && (
|
||||
<div className="text-muted-foreground text-xs">
|
||||
Checks every {globalConfig!.cloud!.ddns!.intervalMinutes} min
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Cloudflare API Token</CardTitle>
|
||||
{!editingToken && (
|
||||
<Button variant="outline" size="sm" onClick={() => setEditingToken(true)} className="gap-1">
|
||||
<Edit2 className="h-3 w-3" />
|
||||
{cfTokenIsSet ? 'Update' : 'Set'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{cfTokenIsSet ? (
|
||||
<p className="text-sm text-green-600 dark:text-green-400">Configured</p>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">Not set — required for DDNS to work</p>
|
||||
)}
|
||||
{editingToken && (
|
||||
<div className="mt-3 space-y-2">
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="Cloudflare API token..."
|
||||
value={tokenValue}
|
||||
onChange={(e) => setTokenValue(e.target.value)}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => updateSecretsMutation.mutate({ ddns: { cloudflare: { apiToken: tokenValue } } })}
|
||||
disabled={updateSecretsMutation.isPending || !tokenValue}
|
||||
>
|
||||
{updateSecretsMutation.isPending ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
|
||||
Save
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => { setEditingToken(false); setTokenValue(''); }}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
{updateSecretsMutation.isError && (
|
||||
<p className="text-xs text-red-500">{String(updateSecretsMutation.error)}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
350
web/src/components/DhcpComponent.tsx
Normal file
350
web/src/components/DhcpComponent.tsx
Normal file
@@ -0,0 +1,350 @@
|
||||
import { useState } from 'react';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input, Label } from './ui';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import { Wifi, Loader2, Edit2, Check, X, Trash2, Plus, RotateCw, CheckCircle, AlertCircle } from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useConfig } from '../hooks';
|
||||
import { useDhcp } from '../hooks/useDhcp';
|
||||
import { useDnsmasq } from '../hooks/useDnsmasq';
|
||||
import type { DhcpStaticLease } from '../services/api/networking';
|
||||
|
||||
export function DhcpComponent() {
|
||||
const { config: globalConfig, updateConfig, isUpdating } = useConfig();
|
||||
const { leases, isLoadingLeases, refetchLeases, addStatic, isAddingStatic, deleteStatic } = useDhcp();
|
||||
const { generateConfig: generateDnsConfig } = useDnsmasq();
|
||||
|
||||
const [editingDhcpConfig, setEditingDhcpConfig] = useState(false);
|
||||
const [dhcpConfigForm, setDhcpConfigForm] = useState({ enabled: false, rangeStart: '', rangeEnd: '', leaseTime: '24h', gateway: '' });
|
||||
const [showAddLease, setShowAddLease] = useState(false);
|
||||
const [newLease, setNewLease] = useState<DhcpStaticLease>({ mac: '', ip: '', hostname: '' });
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
const showSuccess = (msg: string) => {
|
||||
setSuccessMessage(msg);
|
||||
setErrorMessage(null);
|
||||
setTimeout(() => setSuccessMessage(null), 5000);
|
||||
};
|
||||
|
||||
const showError = (msg: string) => {
|
||||
setErrorMessage(msg);
|
||||
setSuccessMessage(null);
|
||||
setTimeout(() => setErrorMessage(null), 8000);
|
||||
};
|
||||
|
||||
const handleDhcpConfigEdit = () => {
|
||||
setDhcpConfigForm({
|
||||
enabled: globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ?? false,
|
||||
rangeStart: globalConfig?.cloud?.dnsmasq?.dhcp?.rangeStart ?? '',
|
||||
rangeEnd: globalConfig?.cloud?.dnsmasq?.dhcp?.rangeEnd ?? '',
|
||||
leaseTime: globalConfig?.cloud?.dnsmasq?.dhcp?.leaseTime ?? '24h',
|
||||
gateway: globalConfig?.cloud?.dnsmasq?.dhcp?.gateway ?? '',
|
||||
});
|
||||
setEditingDhcpConfig(true);
|
||||
};
|
||||
|
||||
const handleDhcpConfigSave = async () => {
|
||||
if (!globalConfig) return;
|
||||
try {
|
||||
await updateConfig({
|
||||
...globalConfig,
|
||||
cloud: {
|
||||
...globalConfig.cloud,
|
||||
dnsmasq: {
|
||||
...globalConfig.cloud?.dnsmasq,
|
||||
dhcp: {
|
||||
enabled: dhcpConfigForm.enabled,
|
||||
rangeStart: dhcpConfigForm.rangeStart,
|
||||
rangeEnd: dhcpConfigForm.rangeEnd,
|
||||
leaseTime: dhcpConfigForm.leaseTime,
|
||||
gateway: dhcpConfigForm.gateway || undefined,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
setEditingDhcpConfig(false);
|
||||
if (dhcpConfigForm.enabled) {
|
||||
generateDnsConfig(true);
|
||||
}
|
||||
showSuccess(dhcpConfigForm.enabled ? 'DHCP configuration saved and applied' : 'DHCP disabled');
|
||||
} catch (e) {
|
||||
showError(`Failed to save DHCP config: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Wifi className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">DHCP</h2>
|
||||
<p className="text-muted-foreground">Assigns IP addresses to devices on your local network</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{successMessage && (
|
||||
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
|
||||
<CheckCircle className="h-4 w-4 text-green-600" />
|
||||
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{errorMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Configuration</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ? 'success' : 'secondary'} className="gap-1">
|
||||
{globalConfig?.cloud?.dnsmasq?.dhcp?.enabled && <CheckCircle className="h-3 w-3" />}
|
||||
{globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ? 'Enabled' : 'Disabled'}
|
||||
</Badge>
|
||||
{!editingDhcpConfig && (
|
||||
<Button variant="outline" size="sm" onClick={handleDhcpConfigEdit} className="gap-1 h-7 text-xs">
|
||||
<Edit2 className="h-3 w-3" />
|
||||
Configure
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{editingDhcpConfig ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="dhcp-enabled"
|
||||
checked={dhcpConfigForm.enabled}
|
||||
onChange={e => setDhcpConfigForm(prev => ({ ...prev, enabled: e.target.checked }))}
|
||||
/>
|
||||
<Label htmlFor="dhcp-enabled">Enable DHCP server</Label>
|
||||
</div>
|
||||
{dhcpConfigForm.enabled && (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label htmlFor="dhcp-range-start">Range Start</Label>
|
||||
<Input
|
||||
id="dhcp-range-start"
|
||||
value={dhcpConfigForm.rangeStart}
|
||||
onChange={e => setDhcpConfigForm(prev => ({ ...prev, rangeStart: e.target.value }))}
|
||||
placeholder="192.168.8.100"
|
||||
className="mt-1 font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="dhcp-range-end">Range End</Label>
|
||||
<Input
|
||||
id="dhcp-range-end"
|
||||
value={dhcpConfigForm.rangeEnd}
|
||||
onChange={e => setDhcpConfigForm(prev => ({ ...prev, rangeEnd: e.target.value }))}
|
||||
placeholder="192.168.8.200"
|
||||
className="mt-1 font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label htmlFor="dhcp-lease-time">Lease Time</Label>
|
||||
<Input
|
||||
id="dhcp-lease-time"
|
||||
value={dhcpConfigForm.leaseTime}
|
||||
onChange={e => setDhcpConfigForm(prev => ({ ...prev, leaseTime: e.target.value }))}
|
||||
placeholder="24h"
|
||||
className="mt-1 font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="dhcp-gateway">Gateway (optional)</Label>
|
||||
<Input
|
||||
id="dhcp-gateway"
|
||||
value={dhcpConfigForm.gateway}
|
||||
onChange={e => setDhcpConfigForm(prev => ({ ...prev, gateway: e.target.value }))}
|
||||
placeholder="192.168.8.1"
|
||||
className="mt-1 font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={handleDhcpConfigSave} disabled={isUpdating}>
|
||||
{isUpdating ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
|
||||
Save
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => setEditingDhcpConfig(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2 text-sm">
|
||||
{globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ? (
|
||||
<>
|
||||
<div className="flex items-center gap-4">
|
||||
<div>
|
||||
<span className="text-muted-foreground">Range: </span>
|
||||
<span className="font-mono">
|
||||
{globalConfig.cloud.dnsmasq.dhcp.rangeStart} – {globalConfig.cloud.dnsmasq.dhcp.rangeEnd}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">Lease: </span>
|
||||
<span className="font-mono">{globalConfig.cloud.dnsmasq.dhcp.leaseTime || '24h'}</span>
|
||||
</div>
|
||||
</div>
|
||||
{globalConfig.cloud.dnsmasq.dhcp.gateway && (
|
||||
<div>
|
||||
<span className="text-muted-foreground">Gateway: </span>
|
||||
<span className="font-mono">{globalConfig.cloud.dnsmasq.dhcp.gateway}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-xs">DHCP is disabled. Enable it to assign IPs to LAN devices.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Leases</CardTitle>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => refetchLeases()} className="gap-1">
|
||||
<RotateCw className="h-3 w-3" />
|
||||
Refresh
|
||||
</Button>
|
||||
<Button size="sm" onClick={() => setShowAddLease(!showAddLease)} className="gap-1">
|
||||
<Plus className="h-3 w-3" />
|
||||
Static
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{showAddLease && (
|
||||
<Card className="p-3 border-dashed">
|
||||
<div className="grid grid-cols-3 gap-2 mb-2">
|
||||
<div>
|
||||
<Label htmlFor="lease-mac" className="text-xs">MAC Address</Label>
|
||||
<Input
|
||||
id="lease-mac"
|
||||
value={newLease.mac}
|
||||
onChange={(e) => setNewLease(l => ({ ...l, mac: e.target.value }))}
|
||||
placeholder="aa:bb:cc:dd:ee:ff"
|
||||
className="mt-1 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="lease-ip" className="text-xs">IP Address</Label>
|
||||
<Input
|
||||
id="lease-ip"
|
||||
value={newLease.ip}
|
||||
onChange={(e) => setNewLease(l => ({ ...l, ip: e.target.value }))}
|
||||
placeholder="192.168.8.10"
|
||||
className="mt-1 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="lease-hostname" className="text-xs">Hostname (optional)</Label>
|
||||
<Input
|
||||
id="lease-hostname"
|
||||
value={newLease.hostname ?? ''}
|
||||
onChange={(e) => setNewLease(l => ({ ...l, hostname: e.target.value }))}
|
||||
placeholder="node1"
|
||||
className="mt-1 text-xs"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => setShowAddLease(false)}>
|
||||
<X className="h-3 w-3 mr-1" />Cancel
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={!newLease.mac || !newLease.ip || isAddingStatic}
|
||||
onClick={() => {
|
||||
addStatic(newLease, {
|
||||
onSuccess: () => {
|
||||
showSuccess(`Static lease added for ${newLease.ip}`);
|
||||
setShowAddLease(false);
|
||||
setNewLease({ mac: '', ip: '', hostname: '' });
|
||||
},
|
||||
onError: (e: Error) => {
|
||||
showError(`Failed to add lease: ${e.message}`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
{isAddingStatic ? <Loader2 className="h-3 w-3 mr-1 animate-spin" /> : <Check className="h-3 w-3 mr-1" />}
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
{isLoadingLeases ? (
|
||||
<div className="flex items-center justify-center py-4">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : leases.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">
|
||||
No active leases. DHCP must be enabled in config.
|
||||
</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-xs">
|
||||
<thead>
|
||||
<tr className="text-muted-foreground border-b">
|
||||
<th className="text-left pb-1">MAC</th>
|
||||
<th className="text-left pb-1">IP</th>
|
||||
<th className="text-left pb-1">Hostname</th>
|
||||
<th className="text-left pb-1">Expires</th>
|
||||
<th className="pb-1" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{leases.map((lease) => (
|
||||
<tr key={lease.mac} className="border-b last:border-0">
|
||||
<td className="py-1 font-mono">{lease.mac}</td>
|
||||
<td className="py-1 font-mono">{lease.ip}</td>
|
||||
<td className="py-1">{lease.hostname || '—'}</td>
|
||||
<td className="py-1 text-muted-foreground">
|
||||
{lease.expiry ? new Date(lease.expiry).toLocaleString() : '—'}
|
||||
</td>
|
||||
<td className="py-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 text-muted-foreground hover:text-red-500"
|
||||
onClick={() => deleteStatic(lease.mac, {
|
||||
onSuccess: () => showSuccess(`Lease for ${lease.mac} deleted`),
|
||||
onError: (e: Error) => showError(`Failed to delete lease: ${e.message}`),
|
||||
})}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
484
web/src/components/DnsComponent.tsx
Normal file
484
web/src/components/DnsComponent.tsx
Normal file
@@ -0,0 +1,484 @@
|
||||
import { useState } from 'react';
|
||||
import { NavLink } from 'react-router';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input, Label } from './ui';
|
||||
import { Textarea } from './ui/textarea';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import {
|
||||
Router, Globe, Loader2, AlertCircle, CheckCircle, XCircle,
|
||||
Play, RotateCw, Copy, ChevronDown, ChevronUp, Edit2,
|
||||
RefreshCw, ExternalLink, TestTube2,
|
||||
} from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useConfig } from '../hooks';
|
||||
import { useCloudflare } from '../hooks/useCloudflare';
|
||||
import { useDnsmasq } from '../hooks/useDnsmasq';
|
||||
import { useDdns } from '../hooks/useDdns';
|
||||
import { apiService } from '../services/api-legacy';
|
||||
import type { DdnsRecordStatus } from '../services/api/networking';
|
||||
|
||||
export function DnsComponent() {
|
||||
const { config: globalConfig, updateConfig, isUpdating } = useConfig();
|
||||
|
||||
// ── LAN DNS (dnsmasq) ──
|
||||
const {
|
||||
status: dnsStatus,
|
||||
isLoadingStatus: isDnsStatusLoading,
|
||||
config: dnsConfig,
|
||||
fetchConfig: fetchDnsConfig,
|
||||
generateConfig: generateDnsConfig,
|
||||
isGenerating: isDnsGenerating,
|
||||
generateData: dnsGenerateData,
|
||||
restart: restartDns,
|
||||
isRestarting: isDnsRestarting,
|
||||
restartData: dnsRestartData,
|
||||
generateError: dnsGenerateError,
|
||||
restartError: dnsRestartError,
|
||||
} = useDnsmasq();
|
||||
|
||||
const [showDnsAdvanced, setShowDnsAdvanced] = useState(false);
|
||||
const [editedDnsConfig, setEditedDnsConfig] = useState('');
|
||||
const [originalDnsConfig, setOriginalDnsConfig] = useState('');
|
||||
const [copiedDnsIp, setCopiedDnsIp] = useState(false);
|
||||
|
||||
const isDnsRunning = dnsStatus?.status === 'active';
|
||||
const dnsIp = dnsStatus?.ip;
|
||||
|
||||
const handleCopyDnsIp = () => {
|
||||
if (dnsIp) {
|
||||
navigator.clipboard.writeText(dnsIp);
|
||||
setCopiedDnsIp(true);
|
||||
setTimeout(() => setCopiedDnsIp(false), 2000);
|
||||
}
|
||||
};
|
||||
|
||||
const handleShowDnsAdvanced = async () => {
|
||||
if (!showDnsAdvanced) {
|
||||
const result = await fetchDnsConfig();
|
||||
const content = result.data?.content || dnsConfig?.content || '';
|
||||
setEditedDnsConfig(content);
|
||||
setOriginalDnsConfig(content);
|
||||
}
|
||||
setShowDnsAdvanced(!showDnsAdvanced);
|
||||
};
|
||||
|
||||
const handleSaveDnsConfig = async () => {
|
||||
try {
|
||||
await apiService.writeDnsmasqConfig(editedDnsConfig);
|
||||
fetchDnsConfig();
|
||||
} catch (error) {
|
||||
console.error('Failed to save config:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveAndRestartDns = async () => {
|
||||
try {
|
||||
await apiService.writeDnsmasqConfig(editedDnsConfig);
|
||||
await apiService.restartDnsmasq();
|
||||
fetchDnsConfig();
|
||||
} catch (error) {
|
||||
console.error('Failed to save config and restart:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// ── Dynamic DNS ──
|
||||
const { status: ddnsStatus, isLoadingStatus: isDdnsLoading, trigger: triggerDdns, isTriggering: isDdnsTriggering } = useDdns();
|
||||
const { verification: cfVerification } = useCloudflare();
|
||||
|
||||
const [editingDdnsConfig, setEditingDdnsConfig] = useState(false);
|
||||
const [ddnsConfigForm, setDdnsConfigForm] = useState({ enabled: false, records: '', intervalMinutes: 5 });
|
||||
|
||||
const handleDdnsConfigEdit = () => {
|
||||
setDdnsConfigForm({
|
||||
enabled: globalConfig?.cloud?.ddns?.enabled ?? false,
|
||||
records: (globalConfig?.cloud?.ddns?.records ?? []).join('\n'),
|
||||
intervalMinutes: globalConfig?.cloud?.ddns?.intervalMinutes ?? 5,
|
||||
});
|
||||
setEditingDdnsConfig(true);
|
||||
};
|
||||
|
||||
const handleDdnsConfigSave = async () => {
|
||||
if (!globalConfig) return;
|
||||
const records = ddnsConfigForm.records.split('\n').map(r => r.trim()).filter(Boolean);
|
||||
await updateConfig({
|
||||
...globalConfig,
|
||||
cloud: {
|
||||
...globalConfig.cloud,
|
||||
ddns: {
|
||||
enabled: ddnsConfigForm.enabled,
|
||||
provider: 'cloudflare',
|
||||
records,
|
||||
intervalMinutes: ddnsConfigForm.intervalMinutes,
|
||||
},
|
||||
},
|
||||
});
|
||||
setEditingDdnsConfig(false);
|
||||
};
|
||||
|
||||
// ── DNS Lookup ──
|
||||
const [lookupDomain, setLookupDomain] = useState('');
|
||||
const [lookupTesting, setLookupTesting] = useState<'external' | 'internal' | null>(null);
|
||||
const [lookupResult, setLookupResult] = useState<{ type: string; success: boolean; message: string } | null>(null);
|
||||
|
||||
const handleLookup = async (type: 'external' | 'internal') => {
|
||||
const domain = lookupDomain.trim();
|
||||
if (!domain) return;
|
||||
setLookupTesting(type);
|
||||
setLookupResult(null);
|
||||
try {
|
||||
if (type === 'external') {
|
||||
const response = await fetch(`https://cloudflare-dns.com/dns-query?name=${domain}&type=A`, {
|
||||
headers: { accept: 'application/dns-json' },
|
||||
});
|
||||
const data = await response.json();
|
||||
if (data.Status === 0 && data.Answer?.length > 0) {
|
||||
const aRecord = data.Answer.find((a: { type: number; data: string }) => a.type === 1);
|
||||
const ip = aRecord ? aRecord.data : data.Answer[data.Answer.length - 1].data;
|
||||
setLookupResult({ type: 'External', success: true, message: `Resolves to ${ip}` });
|
||||
} else {
|
||||
setLookupResult({ type: 'External', success: false, message: 'No public DNS record found' });
|
||||
}
|
||||
} else {
|
||||
const response = await fetch(`/api/v1/network/resolve?domain=${domain}`);
|
||||
const data = await response.json();
|
||||
if (data.success && data.ip) {
|
||||
setLookupResult({ type: 'LAN', success: true, message: `Resolves to ${data.ip}` });
|
||||
} else {
|
||||
setLookupResult({ type: 'LAN', success: false, message: data.error || 'Not resolved on LAN' });
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
setLookupResult({ type: type === 'external' ? 'External' : 'LAN', success: false, message: 'Lookup failed' });
|
||||
} finally {
|
||||
setLookupTesting(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Globe className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">DNS</h2>
|
||||
<p className="text-muted-foreground">LAN name resolution and public DNS record management</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── LAN DNS ── */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Router className="h-5 w-5 text-muted-foreground" />
|
||||
<CardTitle>LAN DNS</CardTitle>
|
||||
</div>
|
||||
<Badge variant={isDnsRunning ? 'success' : 'warning'} className="gap-1">
|
||||
{isDnsStatusLoading ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : isDnsRunning ? (
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
) : null}
|
||||
{isDnsStatusLoading ? 'Checking...' : isDnsRunning ? 'Running' : 'Stopped'}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between p-3 bg-muted/30 rounded-lg">
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground mb-0.5">Set as primary DNS in your router</div>
|
||||
<code className="text-lg font-mono font-bold">{dnsIp || 'Auto-detecting...'}</code>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={handleCopyDnsIp} disabled={!dnsIp} className="gap-2">
|
||||
<Copy className="h-4 w-4" />
|
||||
{copiedDnsIp ? 'Copied!' : 'Copy'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{globalConfig?.cloud?.router?.ip && (
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-muted-foreground">
|
||||
Router: <span className="font-mono">{globalConfig.cloud.router.ip}</span>
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => window.open(`http://${globalConfig?.cloud?.router?.ip}`, '_blank')}
|
||||
className="gap-1 text-xs"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
Open Admin
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
{!isDnsRunning ? (
|
||||
<Button onClick={() => generateDnsConfig(true)} disabled={isDnsGenerating} className="gap-2">
|
||||
{isDnsGenerating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
|
||||
Start DNS
|
||||
</Button>
|
||||
) : (
|
||||
<Button onClick={() => restartDns()} disabled={isDnsRestarting} variant="outline" className="gap-2">
|
||||
{isDnsRestarting ? <Loader2 className="h-4 w-4 animate-spin" /> : <RotateCw className="h-4 w-4" />}
|
||||
Restart
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={handleShowDnsAdvanced} variant="outline" className="gap-2">
|
||||
{showDnsAdvanced ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
||||
Advanced
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{(dnsGenerateData || dnsRestartData) && (
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>{dnsGenerateData?.message || dnsRestartData?.message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{(dnsGenerateError || dnsRestartError) && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{(dnsGenerateError || dnsRestartError)?.toString()}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{showDnsAdvanced && (
|
||||
<div className="border-t pt-4 space-y-3">
|
||||
<span className="text-sm font-medium">Config file</span>
|
||||
<Textarea
|
||||
value={editedDnsConfig}
|
||||
onChange={(e) => setEditedDnsConfig(e.target.value)}
|
||||
className="font-mono text-xs min-h-[300px]"
|
||||
placeholder="# dnsmasq configuration"
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" onClick={handleSaveDnsConfig} className="gap-2">
|
||||
Save
|
||||
</Button>
|
||||
<Button size="sm" onClick={handleSaveAndRestartDns} className="gap-2">
|
||||
Save & Restart
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setEditedDnsConfig(originalDnsConfig)} disabled={editedDnsConfig === originalDnsConfig} className="gap-2">
|
||||
Reset
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* ── Dynamic DNS ── */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Globe className="h-5 w-5 text-muted-foreground" />
|
||||
<CardTitle>Dynamic DNS</CardTitle>
|
||||
</div>
|
||||
{isDdnsLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : ddnsStatus?.enabled ? (
|
||||
<Badge variant="success" className="gap-1">
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
Active
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">Disabled</Badge>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{ddnsStatus?.enabled && (
|
||||
<div className="space-y-3">
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-muted-foreground">Public IP</span>
|
||||
<div className="font-mono font-medium mt-0.5">{ddnsStatus.currentIP || '—'}</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">Last checked</span>
|
||||
<div className="font-mono mt-0.5">
|
||||
{ddnsStatus.lastChecked ? new Date(ddnsStatus.lastChecked).toLocaleTimeString() : '—'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{ddnsStatus.lastError && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">{ddnsStatus.lastError}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => triggerDdns()}
|
||||
disabled={isDdnsTriggering}
|
||||
className="gap-2"
|
||||
>
|
||||
{isDdnsTriggering ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
|
||||
Check Now
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={ddnsStatus?.enabled ? 'border-t pt-4' : ''}>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<span className="text-sm font-medium">A Records</span>
|
||||
{!editingDdnsConfig && (
|
||||
<Button variant="outline" size="sm" onClick={handleDdnsConfigEdit} className="gap-1">
|
||||
<Edit2 className="h-3 w-3" />
|
||||
Edit
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{editingDdnsConfig ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="ddns-enabled"
|
||||
checked={ddnsConfigForm.enabled}
|
||||
onChange={e => setDdnsConfigForm(prev => ({ ...prev, enabled: e.target.checked }))}
|
||||
/>
|
||||
<Label htmlFor="ddns-enabled">Enabled</Label>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Domains (one per line)</Label>
|
||||
<Textarea
|
||||
value={ddnsConfigForm.records}
|
||||
onChange={e => setDdnsConfigForm(prev => ({ ...prev, records: e.target.value }))}
|
||||
placeholder={'cloud.example.com\nexample.org'}
|
||||
className="text-sm h-24 mt-1 font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Check interval (minutes)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={ddnsConfigForm.intervalMinutes}
|
||||
onChange={e => setDdnsConfigForm(prev => ({ ...prev, intervalMinutes: parseInt(e.target.value) || 5 }))}
|
||||
className="h-9 mt-1 w-24"
|
||||
min={1}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={handleDdnsConfigSave} disabled={isUpdating}>
|
||||
{isUpdating ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
|
||||
Save
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => setEditingDdnsConfig(false)}>Cancel</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{(globalConfig?.cloud?.ddns?.records ?? []).length > 0 ? (
|
||||
<>
|
||||
{(globalConfig?.cloud?.ddns?.records ?? []).map(r => {
|
||||
const rs: DdnsRecordStatus | undefined = ddnsStatus?.records?.find(s => s.name === r);
|
||||
return (
|
||||
<div key={r} className="flex items-center gap-2 text-xs">
|
||||
{rs?.ok ? (
|
||||
<CheckCircle className="h-3.5 w-3.5 text-green-500 shrink-0" />
|
||||
) : rs && !rs.ok ? (
|
||||
<XCircle className="h-3.5 w-3.5 text-red-500 shrink-0" />
|
||||
) : (
|
||||
<div className="h-3.5 w-3.5 shrink-0" />
|
||||
)}
|
||||
<span className="font-mono bg-muted px-2 py-0.5 rounded">{r}</span>
|
||||
{rs?.ok && rs.ip && <span className="text-muted-foreground font-mono">{rs.ip}</span>}
|
||||
{rs && !rs.ok && rs.error && (
|
||||
<span className="text-red-500 truncate" title={rs.error}>{rs.error}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{(globalConfig?.cloud?.ddns?.intervalMinutes ?? 0) > 0 && (
|
||||
<div className="text-muted-foreground text-xs pt-1">
|
||||
Checks every {globalConfig!.cloud!.ddns!.intervalMinutes} min
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">No records configured</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{cfVerification && !cfVerification.tokenConfigured && (
|
||||
<div className="flex items-center gap-3 rounded-md border border-amber-300 bg-amber-50 dark:bg-amber-950/30 dark:border-amber-700 px-4 py-3 text-sm text-amber-800 dark:text-amber-300">
|
||||
<AlertCircle className="h-4 w-4 shrink-0" />
|
||||
<span>
|
||||
Cloudflare API token not configured. DDNS requires a valid token.{' '}
|
||||
<NavLink to="/central/cloudflare" className="underline font-medium">Configure token</NavLink>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* ── DNS Lookup ── */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
<TestTube2 className="h-5 w-5 text-muted-foreground" />
|
||||
<CardTitle>DNS Lookup</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="cloud.example.com"
|
||||
value={lookupDomain}
|
||||
onChange={e => { setLookupDomain(e.target.value); setLookupResult(null); }}
|
||||
onKeyDown={e => e.key === 'Enter' && handleLookup('external')}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleLookup('external')}
|
||||
disabled={!lookupDomain.trim() || !!lookupTesting}
|
||||
className="gap-1 shrink-0"
|
||||
>
|
||||
{lookupTesting === 'external' ? <Loader2 className="h-3 w-3 animate-spin" /> : <Globe className="h-3 w-3" />}
|
||||
External
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleLookup('internal')}
|
||||
disabled={!lookupDomain.trim() || !!lookupTesting}
|
||||
className="gap-1 shrink-0"
|
||||
>
|
||||
{lookupTesting === 'internal' ? <Loader2 className="h-3 w-3 animate-spin" /> : <Router className="h-3 w-3" />}
|
||||
LAN
|
||||
</Button>
|
||||
</div>
|
||||
{lookupResult && (
|
||||
<Alert className={lookupResult.success
|
||||
? 'border-green-500 bg-green-50 dark:bg-green-950'
|
||||
: 'border-amber-500 bg-amber-50 dark:bg-amber-950'
|
||||
}>
|
||||
{lookupResult.success
|
||||
? <CheckCircle className="h-4 w-4 text-green-600" />
|
||||
: <AlertCircle className="h-4 w-4 text-amber-600" />
|
||||
}
|
||||
<AlertDescription className={lookupResult.success
|
||||
? 'text-green-800 dark:text-green-200'
|
||||
: 'text-amber-800 dark:text-amber-200'
|
||||
}>
|
||||
<span className="font-medium">{lookupResult.type}: </span>
|
||||
{lookupResult.message}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
86
web/src/components/DnsmasqSection.tsx
Normal file
86
web/src/components/DnsmasqSection.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
import { Settings, RotateCcw, AlertCircle } from 'lucide-react';
|
||||
import { useDnsmasq, useMessages } from '../hooks';
|
||||
import { Message } from './Message';
|
||||
import { Card, CardHeader, CardTitle, CardContent, Button } from './ui';
|
||||
|
||||
export const DnsmasqSection = () => {
|
||||
const {
|
||||
config: dnsmasqConfig,
|
||||
generateConfig,
|
||||
isGenerating,
|
||||
generateError,
|
||||
restart,
|
||||
isRestarting,
|
||||
restartError,
|
||||
restartData
|
||||
} = useDnsmasq();
|
||||
const { messages, setMessage } = useMessages();
|
||||
|
||||
// Handle success/error messaging
|
||||
if (generateError) {
|
||||
setMessage('dnsmasq', `Failed to generate dnsmasq config: ${generateError.message}`, 'error');
|
||||
} else if (dnsmasqConfig) {
|
||||
setMessage('dnsmasq', 'Dnsmasq config generated successfully', 'success');
|
||||
}
|
||||
|
||||
if (restartError) {
|
||||
setMessage('dnsmasq', `Failed to restart dnsmasq: ${restartError.message}`, 'error');
|
||||
} else if (restartData) {
|
||||
setMessage('dnsmasq', `Dnsmasq restart: ${restartData.status}`, 'success');
|
||||
}
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>DNS/DHCP Management</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={() => generateConfig(false)} disabled={isGenerating} variant="outline">
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
{isGenerating ? 'Generating...' : 'Generate Dnsmasq Config'}
|
||||
</Button>
|
||||
<Button onClick={() => restart()} disabled={isRestarting} variant="outline">
|
||||
<RotateCcw className={`mr-2 h-4 w-4 ${isRestarting ? 'animate-spin' : ''}`} />
|
||||
{isRestarting ? 'Restarting...' : 'Restart Dnsmasq'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{generateError && (
|
||||
<div className="p-3 bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 rounded-md flex items-start gap-2">
|
||||
<AlertCircle className="h-4 w-4 text-red-600 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-red-800 dark:text-red-200">Generation Error</p>
|
||||
<p className="text-sm text-red-700 dark:text-red-300">{generateError.message}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{restartError && (
|
||||
<div className="p-3 bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 rounded-md flex items-start gap-2">
|
||||
<AlertCircle className="h-4 w-4 text-red-600 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-red-800 dark:text-red-200">Restart Error</p>
|
||||
<p className="text-sm text-red-700 dark:text-red-300">{restartError.message}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{restartData && (
|
||||
<div className="p-3 bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded-md">
|
||||
<p className="text-sm text-green-800 dark:text-green-200">
|
||||
✓ Dnsmasq restart: {restartData.status}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Message message={messages.dnsmasq} />
|
||||
|
||||
{dnsmasqConfig && (
|
||||
<pre className="p-4 bg-muted rounded-md text-sm overflow-auto max-h-96">
|
||||
{dnsmasqConfig.content || JSON.stringify(dnsmasqConfig, null, 2)}
|
||||
</pre>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
41
web/src/components/DownloadButton.tsx
Normal file
41
web/src/components/DownloadButton.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import { Download } from 'lucide-react';
|
||||
import { Button } from './ui/button';
|
||||
|
||||
interface DownloadButtonProps {
|
||||
content: string;
|
||||
filename: string;
|
||||
label?: string;
|
||||
variant?: 'default' | 'outline' | 'secondary' | 'ghost';
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function DownloadButton({
|
||||
content,
|
||||
filename,
|
||||
label = 'Download',
|
||||
variant = 'default',
|
||||
disabled = false,
|
||||
}: DownloadButtonProps) {
|
||||
const handleDownload = () => {
|
||||
const blob = new Blob([content], { type: 'text/plain' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
onClick={handleDownload}
|
||||
variant={variant}
|
||||
disabled={disabled}
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
167
web/src/components/ErrorBoundary.tsx
Normal file
167
web/src/components/ErrorBoundary.tsx
Normal file
@@ -0,0 +1,167 @@
|
||||
import React, { Component as ReactComponent } from 'react';
|
||||
import type { ErrorInfo, ReactNode } from 'react';
|
||||
import { AlertTriangle, RefreshCw, Home } from 'lucide-react';
|
||||
import { Button } from './ui/button';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
|
||||
interface Props {
|
||||
children?: ReactNode;
|
||||
fallback?: ReactNode;
|
||||
onError?: (error: Error, errorInfo: ErrorInfo) => void;
|
||||
}
|
||||
|
||||
interface State {
|
||||
hasError: boolean;
|
||||
error?: Error;
|
||||
errorInfo?: ErrorInfo;
|
||||
}
|
||||
|
||||
export class ErrorBoundary extends ReactComponent<Props, State> {
|
||||
public state: State = {
|
||||
hasError: false,
|
||||
};
|
||||
|
||||
public static getDerivedStateFromError(error: Error): State {
|
||||
// Update state so the next render will show the fallback UI
|
||||
return { hasError: true, error };
|
||||
}
|
||||
|
||||
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
|
||||
console.error('ErrorBoundary caught an error:', error, errorInfo);
|
||||
|
||||
this.setState({
|
||||
error,
|
||||
errorInfo,
|
||||
});
|
||||
|
||||
// Call optional error handler
|
||||
if (this.props.onError) {
|
||||
this.props.onError(error, errorInfo);
|
||||
}
|
||||
}
|
||||
|
||||
private handleReset = () => {
|
||||
this.setState({ hasError: false, error: undefined, errorInfo: undefined });
|
||||
};
|
||||
|
||||
private handleReload = () => {
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
public render() {
|
||||
if (this.state.hasError) {
|
||||
// If a custom fallback is provided, use it
|
||||
if (this.props.fallback) {
|
||||
return this.props.fallback;
|
||||
}
|
||||
|
||||
// Default error UI
|
||||
return <ErrorFallback
|
||||
error={this.state.error}
|
||||
errorInfo={this.state.errorInfo}
|
||||
onReset={this.handleReset}
|
||||
onReload={this.handleReload}
|
||||
/>;
|
||||
}
|
||||
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
interface ErrorFallbackProps {
|
||||
error?: Error;
|
||||
errorInfo?: ErrorInfo;
|
||||
onReset: () => void;
|
||||
onReload: () => void;
|
||||
}
|
||||
|
||||
export const ErrorFallback: React.FC<ErrorFallbackProps> = ({
|
||||
error,
|
||||
errorInfo,
|
||||
onReset,
|
||||
onReload
|
||||
}) => {
|
||||
const isDev = process.env.NODE_ENV === 'development';
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex items-center justify-center p-4">
|
||||
<Card className="w-full max-w-2xl">
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 rounded-lg">
|
||||
<AlertTriangle className="h-6 w-6 text-red-600 dark:text-red-400" />
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-red-800 dark:text-red-200">
|
||||
Something went wrong
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
The application encountered an unexpected error
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Don't worry, your data is safe. You can try the following options:
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={onReset} variant="outline" size="sm">
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
Try Again
|
||||
</Button>
|
||||
<Button onClick={onReload} variant="outline" size="sm">
|
||||
<Home className="h-4 w-4 mr-2" />
|
||||
Reload Page
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isDev && error && (
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-medium text-red-800 dark:text-red-200">
|
||||
Error Details (Development Mode)
|
||||
</h4>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground">Error Message:</p>
|
||||
<p className="text-xs bg-red-50 p-2 rounded border font-mono">
|
||||
{error.message}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error.stack && (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground">Stack Trace:</p>
|
||||
<pre className="text-xs p-2 rounded border overflow-auto max-h-40 font-mono">
|
||||
{error.stack}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{errorInfo?.componentStack && (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground">Component Stack:</p>
|
||||
<pre className="text-xs p-2 rounded border overflow-auto max-h-40 font-mono">
|
||||
{errorInfo.componentStack}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isDev && (
|
||||
<div className="p-3 bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-md">
|
||||
<p className="text-sm text-blue-800 dark:text-blue-200">
|
||||
If this problem persists, please contact support with details about what you were doing when the error occurred.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
530
web/src/components/FirewallComponent.tsx
Normal file
530
web/src/components/FirewallComponent.tsx
Normal file
@@ -0,0 +1,530 @@
|
||||
import { useState } from 'react';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input } from './ui/input';
|
||||
import { Label } from './ui/label';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
|
||||
import { Shield, Loader2, AlertCircle, CheckCircle, Check, X, Plus, Trash2, BookOpen, ChevronDown, ChevronUp, Lock } from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useConfig } from '../hooks';
|
||||
import { useNftables } from '../hooks/useNftables';
|
||||
import { useVpn } from '../hooks/useVpn';
|
||||
|
||||
type ExtraPort = { port: number; protocol?: string; label?: string };
|
||||
|
||||
const WELL_KNOWN_PORTS: Record<number, string> = {
|
||||
22: 'SSH',
|
||||
53: 'DNS',
|
||||
67: 'DHCP Server',
|
||||
68: 'DHCP Client',
|
||||
80: 'HTTP',
|
||||
443: 'HTTPS',
|
||||
3389: 'RDP',
|
||||
5353: 'mDNS',
|
||||
5900: 'VNC',
|
||||
8404: 'HAProxy Stats',
|
||||
};
|
||||
|
||||
// Ports that are always included automatically
|
||||
const AUTO_TCP_PORTS = [80, 443, 8404];
|
||||
const AUTO_UDP_PORTS = [53, 67, 68];
|
||||
|
||||
interface PortEntry {
|
||||
port: number;
|
||||
protocol: string;
|
||||
label: string;
|
||||
source: 'auto' | 'haproxy-custom' | 'user';
|
||||
}
|
||||
|
||||
export function FirewallComponent() {
|
||||
const { config: globalConfig, updateConfig } = useConfig();
|
||||
const { status: nftablesStatus, isLoadingStatus: isNftablesLoading, interfaces, refetchStatus } = useNftables();
|
||||
const { config: vpnConfig } = useVpn();
|
||||
|
||||
const nftCfg = globalConfig?.cloud?.nftables;
|
||||
const isEnabled = nftCfg?.enabled !== false;
|
||||
const currentWan = nftCfg?.wanInterface ?? '';
|
||||
const currentExtraPorts: ExtraPort[] = nftCfg?.extraPorts ?? [];
|
||||
const customRoutes = globalConfig?.cloud?.haproxy?.customRoutes ?? [];
|
||||
|
||||
const [editingWan, setEditingWan] = useState(false);
|
||||
const [wanValue, setWanValue] = useState('');
|
||||
const [savingWan, setSavingWan] = useState(false);
|
||||
const [togglingFirewall, setTogglingFirewall] = useState(false);
|
||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
const [newPort, setNewPort] = useState('');
|
||||
const [newProtocol, setNewProtocol] = useState('tcp');
|
||||
const [newLabel, setNewLabel] = useState('');
|
||||
const [portError, setPortError] = useState('');
|
||||
const [savingPorts, setSavingPorts] = useState(false);
|
||||
|
||||
const showSuccess = (msg: string) => {
|
||||
setSuccessMessage(msg);
|
||||
setErrorMessage(null);
|
||||
setTimeout(() => setSuccessMessage(null), 5000);
|
||||
};
|
||||
|
||||
const showError = (msg: string) => {
|
||||
setErrorMessage(msg);
|
||||
setSuccessMessage(null);
|
||||
setTimeout(() => setErrorMessage(null), 8000);
|
||||
};
|
||||
|
||||
// Build unified port list from all sources
|
||||
function buildPortList(): PortEntry[] {
|
||||
const entries: PortEntry[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
const addEntry = (port: number, protocol: string, label: string, source: PortEntry['source']) => {
|
||||
const key = `${port}/${protocol}`;
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
entries.push({ port, protocol, label, source });
|
||||
}
|
||||
};
|
||||
|
||||
// Auto TCP ports (HAProxy base)
|
||||
for (const port of AUTO_TCP_PORTS) {
|
||||
addEntry(port, 'tcp', WELL_KNOWN_PORTS[port] || '', 'auto');
|
||||
}
|
||||
|
||||
// HAProxy custom route ports
|
||||
for (const route of customRoutes) {
|
||||
addEntry(route.port, 'tcp', `HAProxy: ${route.name}`, 'haproxy-custom');
|
||||
}
|
||||
|
||||
// Auto UDP ports (DNS/DHCP)
|
||||
for (const port of AUTO_UDP_PORTS) {
|
||||
addEntry(port, 'udp', WELL_KNOWN_PORTS[port] || '', 'auto');
|
||||
}
|
||||
|
||||
// VPN listen port (when enabled)
|
||||
if (vpnConfig?.enabled && vpnConfig.listenPort) {
|
||||
addEntry(vpnConfig.listenPort, 'udp', 'WireGuard VPN', 'auto');
|
||||
}
|
||||
|
||||
// User extra ports
|
||||
for (const ep of currentExtraPorts) {
|
||||
const proto = ep.protocol || 'tcp';
|
||||
addEntry(ep.port, proto, ep.label || WELL_KNOWN_PORTS[ep.port] || '', 'user');
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
const allPorts = buildPortList();
|
||||
const tcpPorts = allPorts.filter(p => p.protocol === 'tcp');
|
||||
const udpPorts = allPorts.filter(p => p.protocol === 'udp');
|
||||
|
||||
async function saveNftConfig(patch: NonNullable<NonNullable<typeof globalConfig>['cloud']>['nftables']) {
|
||||
if (!globalConfig) return;
|
||||
await updateConfig({
|
||||
...globalConfig,
|
||||
cloud: {
|
||||
...globalConfig.cloud,
|
||||
nftables: { ...nftCfg, ...patch },
|
||||
},
|
||||
});
|
||||
refetchStatus();
|
||||
}
|
||||
|
||||
async function toggleFirewall() {
|
||||
setTogglingFirewall(true);
|
||||
try {
|
||||
await saveNftConfig({ enabled: !isEnabled });
|
||||
showSuccess(`Firewall ${isEnabled ? 'disabled' : 'enabled'}`);
|
||||
} catch (e) {
|
||||
showError(`Failed to toggle firewall: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
setTogglingFirewall(false);
|
||||
}
|
||||
|
||||
async function saveWan(value: string) {
|
||||
setSavingWan(true);
|
||||
try {
|
||||
await saveNftConfig({ wanInterface: value || undefined });
|
||||
showSuccess(value ? `WAN interface set to ${value}` : 'Strict mode disabled');
|
||||
} catch (e) {
|
||||
showError(`Failed to save WAN interface: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
setSavingWan(false);
|
||||
setEditingWan(false);
|
||||
}
|
||||
|
||||
async function addPort() {
|
||||
const port = parseInt(newPort, 10);
|
||||
if (isNaN(port) || port < 1 || port > 65535) {
|
||||
setPortError('Enter a valid port (1–65535)');
|
||||
return;
|
||||
}
|
||||
if (currentExtraPorts.some((p) => p.port === port && (p.protocol || 'tcp') === newProtocol)) {
|
||||
setPortError('Port/protocol already in list');
|
||||
return;
|
||||
}
|
||||
setPortError('');
|
||||
setSavingPorts(true);
|
||||
try {
|
||||
const entry: ExtraPort = { port, protocol: newProtocol };
|
||||
if (newLabel.trim()) entry.label = newLabel.trim();
|
||||
await saveNftConfig({ extraPorts: [...currentExtraPorts, entry] });
|
||||
showSuccess(`Port ${port}/${newProtocol} added`);
|
||||
setNewPort('');
|
||||
setNewLabel('');
|
||||
} catch (e) {
|
||||
showError(`Failed to add port: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
setSavingPorts(false);
|
||||
}
|
||||
|
||||
async function removePort(port: number, protocol: string) {
|
||||
try {
|
||||
await saveNftConfig({
|
||||
extraPorts: currentExtraPorts.filter(
|
||||
(ep) => !(ep.port === port && (ep.protocol || 'tcp') === protocol)
|
||||
),
|
||||
});
|
||||
showSuccess(`Port ${port}/${protocol} removed`);
|
||||
} catch (e) {
|
||||
showError(`Failed to remove port: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
function renderPortRow(entry: PortEntry) {
|
||||
const isAuto = entry.source !== 'user';
|
||||
return (
|
||||
<div
|
||||
key={`${entry.port}/${entry.protocol}`}
|
||||
className={`flex items-center gap-3 px-3 py-2 rounded-md ${isAuto ? 'bg-muted/50' : 'bg-muted'}`}
|
||||
>
|
||||
<span className="font-mono text-sm w-16">{entry.port}</span>
|
||||
<span className="text-xs text-muted-foreground uppercase w-8">{entry.protocol}</span>
|
||||
<span className="text-sm flex-1 truncate">
|
||||
{entry.label}
|
||||
</span>
|
||||
{isAuto ? (
|
||||
<span title="Managed automatically"><Lock className="h-3 w-3 text-muted-foreground shrink-0" /></span>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => removePort(entry.port, entry.protocol)}
|
||||
className="text-muted-foreground hover:text-red-500 shrink-0"
|
||||
title="Remove port"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header with enable/disable toggle */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Shield className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">Firewall</h2>
|
||||
<p className="text-muted-foreground">nftables rules protecting Wild Central itself</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge variant={isEnabled ? 'success' : 'secondary'} className="gap-1">
|
||||
{isEnabled && <CheckCircle className="h-3 w-3" />}
|
||||
{isEnabled ? 'Enabled' : 'Disabled'}
|
||||
</Badge>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs gap-1"
|
||||
onClick={toggleFirewall}
|
||||
disabled={togglingFirewall}
|
||||
>
|
||||
{togglingFirewall ? <Loader2 className="h-3 w-3 animate-spin" /> : null}
|
||||
{isEnabled ? 'Disable' : 'Enable'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Educational card */}
|
||||
<Card className="bg-gradient-to-br from-cyan-50 to-blue-50 dark:from-cyan-900/20 dark:to-blue-900/20 border-cyan-200 dark:border-cyan-800">
|
||||
<CardContent className="pt-4">
|
||||
<div className="flex gap-3">
|
||||
<BookOpen className="h-5 w-5 text-cyan-600 dark:text-cyan-400 shrink-0 mt-0.5" />
|
||||
<div className="space-y-1 text-sm text-cyan-900 dark:text-cyan-100">
|
||||
<p>
|
||||
Wild Central uses <strong>nftables</strong> to protect itself. Rules are generated
|
||||
automatically from your HAProxy ingress configuration — the ports HAProxy listens
|
||||
on are always allowed. The firewall is permissive by default; set a{' '}
|
||||
<strong>WAN interface</strong> to enable strict filtering that drops anything not
|
||||
explicitly listed. Make sure to add <strong>extra ports</strong> for any services
|
||||
you need to reach directly (like SSH) before enabling strict mode.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{successMessage && (
|
||||
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
|
||||
<CheckCircle className="h-4 w-4 text-green-600" />
|
||||
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{errorMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Allowed Ports */}
|
||||
<Card className={!isEnabled ? 'opacity-50 pointer-events-none' : ''}>
|
||||
<CardHeader>
|
||||
<CardTitle>Allowed Ports</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
All ports the firewall allows through. Ports managed by HAProxy and system services are
|
||||
locked — add your own with the form below.
|
||||
</p>
|
||||
|
||||
{/* TCP ports */}
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">TCP</h4>
|
||||
<div className="space-y-1">
|
||||
{tcpPorts.map(renderPortRow)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* UDP ports */}
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">UDP</h4>
|
||||
<div className="space-y-1">
|
||||
{udpPorts.map(renderPortRow)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Add port form */}
|
||||
<div className="border-t pt-4 space-y-3">
|
||||
<h4 className="text-sm font-medium">Add Port</h4>
|
||||
<div className="flex flex-wrap gap-2 items-end">
|
||||
<div>
|
||||
<Label htmlFor="new-port" className="text-xs">Port</Label>
|
||||
<Input
|
||||
id="new-port"
|
||||
value={newPort}
|
||||
onChange={(e) => { setNewPort(e.target.value); setPortError(''); }}
|
||||
onKeyDown={(e) => e.key === 'Enter' && addPort()}
|
||||
placeholder="e.g. 22"
|
||||
className="font-mono h-8 text-sm w-24 mt-1"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">Protocol</Label>
|
||||
<Select value={newProtocol} onValueChange={setNewProtocol}>
|
||||
<SelectTrigger className="h-8 text-sm w-20 mt-1 font-mono">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="tcp">TCP</SelectItem>
|
||||
<SelectItem value="udp">UDP</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="new-label" className="text-xs">Label (optional)</Label>
|
||||
<Input
|
||||
id="new-label"
|
||||
value={newLabel}
|
||||
onChange={(e) => setNewLabel(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && addPort()}
|
||||
placeholder="e.g. SSH"
|
||||
className="h-8 text-sm w-32 mt-1"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-8 gap-1"
|
||||
onClick={addPort}
|
||||
disabled={savingPorts || !newPort}
|
||||
>
|
||||
{savingPorts ? <Loader2 className="h-3 w-3 animate-spin" /> : <Plus className="h-3 w-3" />}
|
||||
Add
|
||||
</Button>
|
||||
{!currentExtraPorts.some((p) => p.port === 22) && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 gap-1 text-xs"
|
||||
onClick={() => { setNewPort('22'); setNewProtocol('tcp'); setNewLabel('SSH'); }}
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
Add SSH (22)
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{portError && <p className="text-xs text-red-600">{portError}</p>}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* WAN Interface */}
|
||||
<Card className={!isEnabled ? 'opacity-50 pointer-events-none' : ''}>
|
||||
<CardHeader>
|
||||
<CardTitle>WAN Interface</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Your <strong>WAN interface</strong> is the network port that faces the internet — the
|
||||
one your router sends traffic to. When set, the firewall drops all inbound connections
|
||||
on that interface except for the ports listed above. Leave unset to keep the firewall
|
||||
permissive (safe default while you're getting started).
|
||||
</p>
|
||||
|
||||
{!editingWan ? (
|
||||
<div className="flex items-center gap-3">
|
||||
{currentWan ? (
|
||||
<span className="font-mono bg-muted px-2 py-0.5 rounded text-sm">{currentWan}</span>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground italic">
|
||||
Not set — permissive mode (all inbound allowed)
|
||||
</span>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs gap-1"
|
||||
onClick={() => { setWanValue(currentWan); setEditingWan(true); }}
|
||||
>
|
||||
{currentWan ? 'Change' : 'Enable strict mode'}
|
||||
</Button>
|
||||
{currentWan && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 text-xs gap-1 text-muted-foreground hover:text-red-500"
|
||||
onClick={() => saveWan('')}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
Disable
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{currentWan === '' && !currentExtraPorts.some((p) => p.port === 22) && (
|
||||
<Alert variant="warning">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">
|
||||
SSH (port 22) is not in your extra ports list. Enabling strict mode will
|
||||
block SSH access to Wild Central.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">Select interface</Label>
|
||||
{interfaces.length > 0 ? (
|
||||
<Select value={wanValue} onValueChange={setWanValue}>
|
||||
<SelectTrigger className="w-64 h-8 text-sm font-mono">
|
||||
<SelectValue placeholder="Choose an interface…" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{interfaces.map((iface) => (
|
||||
<SelectItem key={iface.name} value={iface.name}>
|
||||
<span className="font-mono">{iface.name}</span>
|
||||
{iface.addresses.length > 0 && (
|
||||
<span className="text-muted-foreground ml-2 text-xs">
|
||||
{iface.addresses[0].split('/')[0]}
|
||||
</span>
|
||||
)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : (
|
||||
<Input
|
||||
value={wanValue}
|
||||
onChange={(e) => setWanValue(e.target.value)}
|
||||
placeholder="e.g. eth0"
|
||||
className="font-mono h-8 text-sm w-32"
|
||||
/>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Pick the interface that faces your router/internet. Typically the one with your
|
||||
external IP address.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-8 gap-1"
|
||||
onClick={() => saveWan(wanValue)}
|
||||
disabled={savingWan || !wanValue}
|
||||
>
|
||||
{savingWan ? <Loader2 className="h-3 w-3 animate-spin" /> : <Check className="h-3 w-3" />}
|
||||
Save
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 gap-1"
|
||||
onClick={() => setEditingWan(false)}
|
||||
>
|
||||
<X className="h-3 w-3" />Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Advanced: raw rules */}
|
||||
<Card className={!isEnabled ? 'opacity-50' : ''}>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Active Ruleset</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
{isNftablesLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<Badge variant={nftablesStatus?.rules ? 'success' : isEnabled ? 'warning' : 'secondary'} className="gap-1">
|
||||
{nftablesStatus?.rules && <CheckCircle className="h-3 w-3" />}
|
||||
{nftablesStatus?.rules ? 'Active' : 'Not loaded'}
|
||||
</Badge>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs gap-1"
|
||||
onClick={() => setShowAdvanced(!showAdvanced)}
|
||||
>
|
||||
{showAdvanced ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
|
||||
Advanced
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
{showAdvanced && (
|
||||
<CardContent>
|
||||
{nftablesStatus?.rules ? (
|
||||
<pre className="bg-muted p-3 rounded-lg overflow-x-auto text-xs font-mono">
|
||||
{nftablesStatus.rules}
|
||||
</pre>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No rules loaded yet. Rules are generated when you apply an HAProxy configuration.
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
41
web/src/components/HelpPanel.tsx
Normal file
41
web/src/components/HelpPanel.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import { useHelp } from '../contexts/HelpContext';
|
||||
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription } from './ui/sheet';
|
||||
import { Card } from './ui/card';
|
||||
|
||||
export function HelpPanel() {
|
||||
const { helpContent, isHelpOpen, setIsHelpOpen } = useHelp();
|
||||
|
||||
if (!helpContent) return null;
|
||||
|
||||
return (
|
||||
<Sheet open={isHelpOpen} onOpenChange={setIsHelpOpen}>
|
||||
<SheetContent className="w-full sm:max-w-lg overflow-y-auto p-6">
|
||||
<SheetHeader className="mb-6">
|
||||
<SheetTitle className="flex items-center gap-3">
|
||||
{helpContent.icon && (
|
||||
<div className={`p-2 rounded-lg ${helpContent.color || 'bg-primary/10'}`}>
|
||||
{helpContent.icon}
|
||||
</div>
|
||||
)}
|
||||
{helpContent.title}
|
||||
</SheetTitle>
|
||||
<SheetDescription className="sr-only">
|
||||
Help information for {helpContent.title}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="space-y-4">
|
||||
<Card className={`p-4 ${helpContent.color || 'bg-muted/50'}`}>
|
||||
<div className="prose dark:prose-invert max-w-none text-sm">
|
||||
{helpContent.description}
|
||||
</div>
|
||||
</Card>
|
||||
{helpContent.actions && (
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
{helpContent.actions}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
342
web/src/components/IngressProxyComponent.tsx
Normal file
342
web/src/components/IngressProxyComponent.tsx
Normal file
@@ -0,0 +1,342 @@
|
||||
import { useState } from 'react';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input, Label } from './ui';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import { Textarea } from './ui/textarea';
|
||||
import { Network, Loader2, AlertCircle, CheckCircle, Play, RotateCw, Plus, Trash2, X, Check, Activity, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useConfig } from '../hooks';
|
||||
import { useHaproxy } from '../hooks/useHaproxy';
|
||||
import type { HAProxyCustomRoute } from '../types';
|
||||
import type { HaproxyInstanceRoute } from '../services/api/networking';
|
||||
import { haproxyApi } from '../services/api/networking';
|
||||
|
||||
export function IngressProxyComponent() {
|
||||
const { config: globalConfig, updateConfig, isUpdating } = useConfig();
|
||||
const {
|
||||
status: haproxyStatus,
|
||||
isLoadingStatus: isHaproxyLoading,
|
||||
stats: haproxyStats,
|
||||
isLoadingStats: isHaproxyStatsLoading,
|
||||
generate: generateHaproxy,
|
||||
isGenerating: isHaproxyGenerating,
|
||||
generateData: haproxyGenerateData,
|
||||
generateError: haproxyGenerateError,
|
||||
restart: restartHaproxy,
|
||||
isRestarting: isHaproxyRestarting,
|
||||
} = useHaproxy();
|
||||
|
||||
const [showAddCustomRoute, setShowAddCustomRoute] = useState(false);
|
||||
const [newCustomRoute, setNewCustomRoute] = useState<HAProxyCustomRoute>({ name: '', port: 0, backend: '' });
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||
const [advancedConfig, setAdvancedConfig] = useState('');
|
||||
const [loadingAdvanced, setLoadingAdvanced] = useState(false);
|
||||
|
||||
const showSuccess = (msg: string) => {
|
||||
setSuccessMessage(msg);
|
||||
setErrorMessage(null);
|
||||
setTimeout(() => setSuccessMessage(null), 5000);
|
||||
};
|
||||
|
||||
const showError = (msg: string) => {
|
||||
setErrorMessage(msg);
|
||||
setSuccessMessage(null);
|
||||
setTimeout(() => setErrorMessage(null), 8000);
|
||||
};
|
||||
|
||||
const handleShowAdvanced = async () => {
|
||||
if (!showAdvanced) {
|
||||
setLoadingAdvanced(true);
|
||||
try {
|
||||
const result = await haproxyApi.getConfig();
|
||||
setAdvancedConfig(result.content || '');
|
||||
} catch {
|
||||
setAdvancedConfig('# Could not load HAProxy config');
|
||||
}
|
||||
setLoadingAdvanced(false);
|
||||
}
|
||||
setShowAdvanced(!showAdvanced);
|
||||
};
|
||||
|
||||
const handleAddCustomRoute = async () => {
|
||||
if (!globalConfig || !newCustomRoute.name || !newCustomRoute.port || !newCustomRoute.backend) return;
|
||||
try {
|
||||
const existing = globalConfig.cloud?.haproxy?.customRoutes ?? [];
|
||||
await updateConfig({
|
||||
...globalConfig,
|
||||
cloud: {
|
||||
...globalConfig.cloud,
|
||||
haproxy: {
|
||||
...globalConfig.cloud?.haproxy,
|
||||
customRoutes: [...existing, newCustomRoute],
|
||||
},
|
||||
},
|
||||
});
|
||||
setNewCustomRoute({ name: '', port: 0, backend: '' });
|
||||
setShowAddCustomRoute(false);
|
||||
generateHaproxy();
|
||||
showSuccess(`Custom route "${newCustomRoute.name}" added`);
|
||||
} catch (e) {
|
||||
showError(`Failed to add route: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteCustomRoute = async (name: string) => {
|
||||
if (!globalConfig) return;
|
||||
try {
|
||||
const updated = (globalConfig.cloud?.haproxy?.customRoutes ?? []).filter(r => r.name !== name);
|
||||
await updateConfig({
|
||||
...globalConfig,
|
||||
cloud: {
|
||||
...globalConfig.cloud,
|
||||
haproxy: {
|
||||
...globalConfig.cloud?.haproxy,
|
||||
customRoutes: updated,
|
||||
},
|
||||
},
|
||||
});
|
||||
generateHaproxy();
|
||||
showSuccess(`Custom route "${name}" removed`);
|
||||
} catch (e) {
|
||||
showError(`Failed to delete route: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Network className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">Ingress Proxy</h2>
|
||||
<p className="text-muted-foreground">Routes external traffic to your Wild Cloud instances by domain name (HAProxy)</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{successMessage && (
|
||||
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
|
||||
<CheckCircle className="h-4 w-4 text-green-600" />
|
||||
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{errorMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Instance Routes</CardTitle>
|
||||
{isHaproxyLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<Badge variant={haproxyStatus?.status === 'active' ? 'success' : 'warning'} className="gap-1">
|
||||
{haproxyStatus?.status === 'active' && <CheckCircle className="h-3 w-3" />}
|
||||
{haproxyStatus?.status === 'active' ? 'Active' : haproxyStatus?.status ?? 'Stopped'}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{(() => {
|
||||
const routes: HaproxyInstanceRoute[] = haproxyStatus?.routes ?? [];
|
||||
return routes.length > 0 ? (
|
||||
<div className="border rounded-lg divide-y text-sm">
|
||||
{routes.map(r => (
|
||||
<div key={r.name} className="px-3 py-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircle className="h-3.5 w-3.5 text-green-500 shrink-0" />
|
||||
<span className="font-mono text-xs">*.{r.domain}</span>
|
||||
</div>
|
||||
<span className="font-mono text-xs text-muted-foreground">{r.backendIP}</span>
|
||||
</div>
|
||||
{r.extraDomains && r.extraDomains.length > 0 && (
|
||||
<div className="mt-1 ml-5 flex flex-wrap gap-1">
|
||||
{r.extraDomains.map(d => (
|
||||
<span key={d} className="font-mono text-xs text-muted-foreground bg-muted rounded px-1.5 py-0.5">
|
||||
{d}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
No instances registered — click Generate & Apply to configure.
|
||||
</p>
|
||||
);
|
||||
})()}
|
||||
|
||||
{haproxyGenerateData && (
|
||||
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
|
||||
<CheckCircle className="h-4 w-4 text-green-600" />
|
||||
<AlertDescription className="text-green-700 dark:text-green-300">
|
||||
{haproxyGenerateData.message}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{haproxyGenerateError && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{(haproxyGenerateError as Error).message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={() => generateHaproxy()} disabled={isHaproxyGenerating} className="gap-2">
|
||||
{isHaproxyGenerating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
|
||||
Generate & Apply
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => restartHaproxy()} disabled={isHaproxyRestarting} className="gap-2">
|
||||
{isHaproxyRestarting ? <Loader2 className="h-4 w-4 animate-spin" /> : <RotateCw className="h-4 w-4" />}
|
||||
Restart
|
||||
</Button>
|
||||
<Button variant="outline" onClick={handleShowAdvanced} disabled={loadingAdvanced} className="gap-2">
|
||||
{loadingAdvanced ? <Loader2 className="h-4 w-4 animate-spin" /> : showAdvanced ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
||||
Advanced
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{showAdvanced && (
|
||||
<div className="border-t pt-4 space-y-3">
|
||||
<span className="text-sm font-medium">Generated config file</span>
|
||||
<Textarea
|
||||
value={advancedConfig}
|
||||
readOnly
|
||||
className="font-mono text-xs min-h-[300px]"
|
||||
placeholder="# haproxy configuration"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{(haproxyStats.length > 0 || isHaproxyStatsLoading) && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Activity className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Backend Status</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isHaproxyStatsLoading ? (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />Loading…
|
||||
</div>
|
||||
) : (
|
||||
<div className="border rounded-lg divide-y text-sm">
|
||||
{haproxyStats.map(s => (
|
||||
<div key={s.name} className="flex items-center justify-between px-3 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={s.status === 'UP' ? 'default' : 'secondary'} className="text-xs h-4">
|
||||
{s.status}
|
||||
</Badge>
|
||||
<span className="font-mono text-xs">{s.name.replace(/^be_https?_/, '')}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-xs text-muted-foreground">
|
||||
<span><span className="font-medium text-foreground">{s.activeConns}</span> active</span>
|
||||
<span><span className="font-medium text-foreground">{s.rate}</span> /s <span className="text-muted-foreground/60">(peak {s.peakRate})</span></span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Custom TCP Routes</CardTitle>
|
||||
<Button size="sm" variant="outline" onClick={() => setShowAddCustomRoute(!showAddCustomRoute)} className="gap-1">
|
||||
<Plus className="h-3 w-3" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{showAddCustomRoute && (
|
||||
<Card className="p-3 border-dashed">
|
||||
<div className="grid grid-cols-3 gap-2 mb-2">
|
||||
<div>
|
||||
<Label className="text-xs">Name</Label>
|
||||
<Input
|
||||
value={newCustomRoute.name}
|
||||
onChange={e => setNewCustomRoute(r => ({ ...r, name: e.target.value }))}
|
||||
placeholder="e.g. civil_ssh"
|
||||
className="mt-1 text-xs font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">Listen Port</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={newCustomRoute.port || ''}
|
||||
onChange={e => setNewCustomRoute(r => ({ ...r, port: parseInt(e.target.value) || 0 }))}
|
||||
placeholder="2222"
|
||||
className="mt-1 text-xs font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">Backend (host:port)</Label>
|
||||
<Input
|
||||
value={newCustomRoute.backend}
|
||||
onChange={e => setNewCustomRoute(r => ({ ...r, backend: e.target.value }))}
|
||||
placeholder="192.168.8.10:22"
|
||||
className="mt-1 text-xs font-mono"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button variant="outline" size="sm" onClick={() => setShowAddCustomRoute(false)}>
|
||||
<X className="h-3 w-3 mr-1" />Cancel
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleAddCustomRoute}
|
||||
disabled={!newCustomRoute.name || !newCustomRoute.port || !newCustomRoute.backend || isUpdating}
|
||||
>
|
||||
{isUpdating ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : <Check className="h-3 w-3 mr-1" />}
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
{(globalConfig?.cloud?.haproxy?.customRoutes ?? []).length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">No custom routes configured.</p>
|
||||
) : (
|
||||
<div className="border rounded-lg divide-y text-xs">
|
||||
{(globalConfig?.cloud?.haproxy?.customRoutes ?? []).map(r => (
|
||||
<div key={r.name} className="flex items-center justify-between px-3 py-1.5">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="font-mono font-medium">{r.name}</span>
|
||||
<span className="text-muted-foreground font-mono">:{r.port} → {r.backend}</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 text-muted-foreground hover:text-red-500"
|
||||
onClick={() => handleDeleteCustomRoute(r.name)}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
259
web/src/components/LanDnsComponent.tsx
Normal file
259
web/src/components/LanDnsComponent.tsx
Normal file
@@ -0,0 +1,259 @@
|
||||
import { useState } from 'react';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Textarea } from './ui/textarea';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from './ui/dialog';
|
||||
import { Router, CheckCircle, ExternalLink, Loader2, AlertCircle, Play, RotateCw, Copy, ChevronDown, ChevronUp, Edit } from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useConfig } from '../hooks';
|
||||
import { useDnsmasq } from '../hooks/useDnsmasq';
|
||||
import { apiService } from '../services/api-legacy';
|
||||
|
||||
export function LanDnsComponent() {
|
||||
const { config: globalConfig } = useConfig();
|
||||
const {
|
||||
status: dnsStatus,
|
||||
isLoadingStatus: isDnsStatusLoading,
|
||||
config: dnsConfig,
|
||||
fetchConfig: fetchDnsConfig,
|
||||
generateConfig: generateDnsConfig,
|
||||
isGenerating: isDnsGenerating,
|
||||
generateData: dnsGenerateData,
|
||||
restart: restartDns,
|
||||
isRestarting: isDnsRestarting,
|
||||
restartData: dnsRestartData,
|
||||
generateError: dnsGenerateError,
|
||||
restartError: dnsRestartError,
|
||||
} = useDnsmasq();
|
||||
|
||||
const [showDnsAdvanced, setShowDnsAdvanced] = useState(false);
|
||||
const [showDnsEditDialog, setShowDnsEditDialog] = useState(false);
|
||||
const [editedDnsConfig, setEditedDnsConfig] = useState('');
|
||||
const [copiedDnsIp, setCopiedDnsIp] = useState(false);
|
||||
|
||||
const isDnsRunning = dnsStatus?.status === 'active';
|
||||
const dnsIp = dnsStatus?.ip;
|
||||
|
||||
const handleCopyDnsIp = () => {
|
||||
if (dnsIp) {
|
||||
navigator.clipboard.writeText(dnsIp);
|
||||
setCopiedDnsIp(true);
|
||||
setTimeout(() => setCopiedDnsIp(false), 2000);
|
||||
}
|
||||
};
|
||||
|
||||
const handleShowDnsAdvanced = () => {
|
||||
if (!showDnsAdvanced && !dnsConfig) {
|
||||
fetchDnsConfig();
|
||||
}
|
||||
setShowDnsAdvanced(!showDnsAdvanced);
|
||||
};
|
||||
|
||||
const handleEditDnsConfig = () => {
|
||||
if (dnsConfig?.content) {
|
||||
setEditedDnsConfig(dnsConfig.content);
|
||||
} else if (dnsGenerateData?.config || dnsGenerateData?.content) {
|
||||
setEditedDnsConfig(dnsGenerateData.config || dnsGenerateData.content || '');
|
||||
} else {
|
||||
setEditedDnsConfig('');
|
||||
}
|
||||
setShowDnsEditDialog(true);
|
||||
};
|
||||
|
||||
const handleSaveDnsConfig = async () => {
|
||||
try {
|
||||
await apiService.writeDnsmasqConfig(editedDnsConfig);
|
||||
setShowDnsEditDialog(false);
|
||||
fetchDnsConfig();
|
||||
} catch (error) {
|
||||
console.error('Failed to save config:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveAndRestartDns = async () => {
|
||||
try {
|
||||
await apiService.writeDnsmasqConfig(editedDnsConfig);
|
||||
await apiService.restartDnsmasq();
|
||||
setShowDnsEditDialog(false);
|
||||
fetchDnsConfig();
|
||||
} catch (error) {
|
||||
console.error('Failed to save config and restart:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Router className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">LAN DNS</h2>
|
||||
<p className="text-muted-foreground">Resolves Wild Cloud domains on your local network via dnsmasq</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>DNS Service</CardTitle>
|
||||
<Badge variant={isDnsRunning ? 'success' : 'warning'} className="gap-1">
|
||||
{isDnsStatusLoading ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : isDnsRunning ? (
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
) : null}
|
||||
{isDnsStatusLoading ? 'Checking...' : isDnsRunning ? 'Running' : 'Stopped'}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between p-4 bg-muted/30 rounded-lg">
|
||||
<div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Set this as the primary DNS server in your router
|
||||
</div>
|
||||
<code className="text-xl font-mono font-bold mt-1 inline-block">
|
||||
{dnsIp || 'Auto-detecting...'}
|
||||
</code>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleCopyDnsIp}
|
||||
disabled={!dnsIp}
|
||||
className="gap-2"
|
||||
>
|
||||
<Copy className="h-4 w-4" />
|
||||
{copiedDnsIp ? 'Copied!' : 'Copy'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{globalConfig?.cloud?.router?.ip && (
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-muted-foreground">
|
||||
Router: <span className="font-mono">{globalConfig.cloud.router.ip}</span>
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => window.open(`http://${globalConfig?.cloud?.router?.ip}`, '_blank')}
|
||||
className="gap-1 text-xs"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
Open Admin
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
{!isDnsRunning ? (
|
||||
<Button onClick={() => generateDnsConfig(true)} disabled={isDnsGenerating} className="gap-2">
|
||||
{isDnsGenerating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
|
||||
Start DNS
|
||||
</Button>
|
||||
) : (
|
||||
<Button onClick={() => restartDns()} disabled={isDnsRestarting} variant="outline" className="gap-2">
|
||||
{isDnsRestarting ? <Loader2 className="h-4 w-4 animate-spin" /> : <RotateCw className="h-4 w-4" />}
|
||||
Restart
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={handleShowDnsAdvanced} variant="outline" className="gap-2">
|
||||
{showDnsAdvanced ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
||||
Advanced
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{(dnsGenerateData || dnsRestartData) && (
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
{dnsGenerateData?.message || dnsRestartData?.message}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{(dnsGenerateError || dnsRestartError) && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
{(dnsGenerateError || dnsRestartError)?.toString()}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{showDnsAdvanced && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Advanced DNS Configuration</CardTitle>
|
||||
<Button variant="outline" size="sm" onClick={handleEditDnsConfig} className="gap-2">
|
||||
<Edit className="h-4 w-4" />
|
||||
Edit Config
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<pre className="bg-muted p-4 rounded-lg overflow-x-auto text-xs font-mono">
|
||||
{isDnsGenerating && !dnsConfig && !dnsGenerateData && (
|
||||
<div className="flex items-center justify-center py-4">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
{(dnsConfig?.content || dnsGenerateData?.config || dnsGenerateData?.content) && (
|
||||
dnsConfig?.content || dnsGenerateData?.config || dnsGenerateData?.content
|
||||
)}
|
||||
{!isDnsGenerating && !dnsGenerateData && !dnsConfig && (
|
||||
<div className="text-center p-8 text-sm text-muted-foreground">
|
||||
<p>Configuration preview will appear here</p>
|
||||
</div>
|
||||
)}
|
||||
</pre>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Dialog open={showDnsEditDialog} onOpenChange={setShowDnsEditDialog}>
|
||||
<DialogContent className="max-w-4xl max-h-[80vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit DNS Configuration</DialogTitle>
|
||||
<DialogDescription>
|
||||
Modify the dnsmasq configuration. Changes will take effect after saving and restarting.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="py-4">
|
||||
<Textarea
|
||||
value={editedDnsConfig}
|
||||
onChange={(e) => setEditedDnsConfig(e.target.value)}
|
||||
className="font-mono text-xs min-h-[400px]"
|
||||
placeholder="# dnsmasq configuration"
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter className="gap-2">
|
||||
<Button variant="outline" onClick={() => setShowDnsEditDialog(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="outline" onClick={handleSaveDnsConfig}>
|
||||
Save
|
||||
</Button>
|
||||
<Button onClick={handleSaveAndRestartDns}>
|
||||
Save & Restart
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
Save: Write config without restarting | Save & Restart: Write config and restart service
|
||||
</p>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
43
web/src/components/Message.tsx
Normal file
43
web/src/components/Message.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
import { AlertCircle, CheckCircle, Info } from 'lucide-react';
|
||||
import type { Message as MessageType } from '../types';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface MessageProps {
|
||||
message?: MessageType;
|
||||
}
|
||||
|
||||
export const Message = ({ message }: MessageProps) => {
|
||||
if (!message) return null;
|
||||
|
||||
const getIcon = () => {
|
||||
switch (message.type) {
|
||||
case 'error':
|
||||
return <AlertCircle className="h-4 w-4" />;
|
||||
case 'success':
|
||||
return <CheckCircle className="h-4 w-4" />;
|
||||
default:
|
||||
return <Info className="h-4 w-4" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getVariantStyles = () => {
|
||||
switch (message.type) {
|
||||
case 'error':
|
||||
return 'border-destructive/50 text-destructive bg-destructive/10';
|
||||
case 'success':
|
||||
return 'border-green-500/50 text-green-700 bg-green-50 dark:bg-green-950 dark:text-green-400';
|
||||
default:
|
||||
return 'border-blue-500/50 text-blue-700 bg-blue-50 dark:bg-blue-950 dark:text-blue-400';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn(
|
||||
'flex items-center gap-2 p-3 rounded-md border text-sm',
|
||||
getVariantStyles()
|
||||
)}>
|
||||
{getIcon()}
|
||||
<span>{message.message}</span>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
52
web/src/components/ThemeToggle.tsx
Normal file
52
web/src/components/ThemeToggle.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
import { Moon, Sun, Monitor } from 'lucide-react';
|
||||
import { Button } from './ui/button';
|
||||
import { useTheme } from '../contexts/ThemeContext';
|
||||
|
||||
export function ThemeToggle() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
|
||||
const cycleTheme = () => {
|
||||
if (theme === 'light') {
|
||||
setTheme('dark');
|
||||
} else if (theme === 'dark') {
|
||||
setTheme('system');
|
||||
} else {
|
||||
setTheme('light');
|
||||
}
|
||||
};
|
||||
|
||||
const getIcon = () => {
|
||||
switch (theme) {
|
||||
case 'light':
|
||||
return <Sun className="h-4 w-4" />;
|
||||
case 'dark':
|
||||
return <Moon className="h-4 w-4" />;
|
||||
default:
|
||||
return <Monitor className="h-4 w-4" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getLabel = () => {
|
||||
switch (theme) {
|
||||
case 'light':
|
||||
return 'Light mode';
|
||||
case 'dark':
|
||||
return 'Dark mode';
|
||||
default:
|
||||
return 'System theme';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={cycleTheme}
|
||||
title={`Current: ${getLabel()}. Click to cycle themes.`}
|
||||
className="gap-2"
|
||||
>
|
||||
{getIcon()}
|
||||
<span className="text-xs font-medium">{getLabel()}</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
583
web/src/components/VpnComponent.tsx
Normal file
583
web/src/components/VpnComponent.tsx
Normal file
@@ -0,0 +1,583 @@
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { Shield, Loader2, Edit2, Plus, Trash2, Copy, Check, CheckCircle, RefreshCw, KeyRound, Play, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import { QRCodeSVG } from 'qrcode.react';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input } from './ui/input';
|
||||
import { Label } from './ui/label';
|
||||
import { Badge } from './ui/badge';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from './ui/dialog';
|
||||
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from './ui/sheet';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from './ui/alert-dialog';
|
||||
import { useVpn } from '../hooks/useVpn';
|
||||
import { vpnApi, type VpnPeer, type VpnPeerConfig } from '../services/api/vpn';
|
||||
|
||||
interface ConfigFormValues {
|
||||
enabled: boolean;
|
||||
listenPort: number;
|
||||
address: string;
|
||||
endpoint: string;
|
||||
dns: string;
|
||||
lanCIDR: string;
|
||||
}
|
||||
|
||||
function CopyButton({ text }: { text: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const handleCopy = async () => {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
return (
|
||||
<Button variant="ghost" size="sm" onClick={handleCopy} className="h-7 w-7 p-0">
|
||||
{copied ? <Check className="h-3.5 w-3.5 text-green-500" /> : <Copy className="h-3.5 w-3.5" />}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
export function VpnComponent() {
|
||||
const {
|
||||
status, isLoadingStatus,
|
||||
config, isLoadingConfig,
|
||||
peers, isLoadingPeers,
|
||||
updateConfig, isUpdatingConfig,
|
||||
generateKeypair, isGeneratingKeypair,
|
||||
apply, isApplying, applyError,
|
||||
addPeer, isAddingPeer, addPeerError,
|
||||
deletePeer,
|
||||
} = useVpn();
|
||||
|
||||
const [editingConfig, setEditingConfig] = useState(false);
|
||||
const [confirmKeygen, setConfirmKeygen] = useState(false);
|
||||
const [addPeerOpen, setAddPeerOpen] = useState(false);
|
||||
const [newPeerName, setNewPeerName] = useState('');
|
||||
const [peerConfigModal, setPeerConfigModal] = useState<VpnPeerConfig | null>(null);
|
||||
const [loadingPeerConfig, setLoadingPeerConfig] = useState<string | null>(null);
|
||||
const [deleteConfirmPeer, setDeleteConfirmPeer] = useState<VpnPeer | null>(null);
|
||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
const { register, handleSubmit, reset, formState: { errors } } = useForm<ConfigFormValues>();
|
||||
|
||||
const showSuccess = (msg: string) => {
|
||||
setSuccessMessage(msg);
|
||||
setTimeout(() => setSuccessMessage(null), 5000);
|
||||
};
|
||||
|
||||
const showError = (msg: string) => {
|
||||
setErrorMessage(msg);
|
||||
setTimeout(() => setErrorMessage(null), 8000);
|
||||
};
|
||||
|
||||
const handleEditConfig = () => {
|
||||
reset({
|
||||
enabled: config?.enabled ?? false,
|
||||
listenPort: config?.listenPort ?? 51820,
|
||||
address: config?.address ?? '10.8.0.1/24',
|
||||
endpoint: config?.endpoint ?? '',
|
||||
dns: config?.dns ?? '',
|
||||
lanCIDR: config?.lanCIDR ?? '',
|
||||
});
|
||||
setEditingConfig(true);
|
||||
};
|
||||
|
||||
const handleSaveConfig = async (values: ConfigFormValues) => {
|
||||
try {
|
||||
await updateConfig({ ...values, listenPort: Number(values.listenPort) });
|
||||
setEditingConfig(false);
|
||||
if (values.enabled) {
|
||||
await apply();
|
||||
showSuccess('Configuration saved and applied');
|
||||
} else {
|
||||
showSuccess('Configuration saved');
|
||||
}
|
||||
} catch (e) {
|
||||
showError(`Save failed: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleGenerateKeypair = async () => {
|
||||
setConfirmKeygen(false);
|
||||
try {
|
||||
await generateKeypair();
|
||||
showSuccess('Server keypair generated — re-add all peers to update their configs');
|
||||
} catch (e) {
|
||||
showError(`Keygen failed: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleApply = async () => {
|
||||
try {
|
||||
await apply();
|
||||
showSuccess('WireGuard interface applied');
|
||||
} catch (e) {
|
||||
showError(`Apply failed: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddPeer = async () => {
|
||||
if (!newPeerName.trim()) return;
|
||||
try {
|
||||
await addPeer(newPeerName.trim());
|
||||
setNewPeerName('');
|
||||
setAddPeerOpen(false);
|
||||
showSuccess(`Peer "${newPeerName.trim()}" added`);
|
||||
} catch (e) {
|
||||
showError(`Add peer failed: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleShowPeerConfig = async (peer: VpnPeer) => {
|
||||
setLoadingPeerConfig(peer.id);
|
||||
try {
|
||||
const cfg = await vpnApi.getPeerConfig(peer.id);
|
||||
setPeerConfigModal(cfg);
|
||||
} catch (e) {
|
||||
showError(`Failed to get peer config: ${e instanceof Error ? e.message : String(e)}`);
|
||||
} finally {
|
||||
setLoadingPeerConfig(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeletePeer = async () => {
|
||||
if (!deleteConfirmPeer) return;
|
||||
try {
|
||||
await deletePeer(deleteConfirmPeer.id);
|
||||
setDeleteConfirmPeer(null);
|
||||
showSuccess(`Peer "${deleteConfirmPeer.name}" deleted`);
|
||||
} catch (e) {
|
||||
showError(`Delete failed: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoadingStatus && isLoadingConfig) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-48">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Page header */}
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Shield className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">VPN</h2>
|
||||
<p className="text-muted-foreground">WireGuard remote access to your Wild Cloud network</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Alerts */}
|
||||
{successMessage && (
|
||||
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
|
||||
<Check className="h-4 w-4 text-green-600" />
|
||||
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{(errorMessage || applyError || addPeerError) && (
|
||||
<Alert variant="error">
|
||||
<AlertDescription>{errorMessage ?? String(applyError ?? addPeerError)}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Status card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Status</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={status?.running ? 'success' : config?.enabled ? 'warning' : 'secondary'} className="gap-1">
|
||||
{status?.running && <CheckCircle className="h-3 w-3" />}
|
||||
{status?.running ? 'Running' : 'Stopped'}
|
||||
</Badge>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleApply}
|
||||
disabled={isApplying || !config?.enabled}
|
||||
className="gap-1 h-7 text-xs"
|
||||
>
|
||||
{isApplying ? <Loader2 className="h-3 w-3 animate-spin" /> : <Play className="h-3 w-3" />}
|
||||
Apply
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-4 text-sm sm:grid-cols-3">
|
||||
<div>
|
||||
<p className="text-muted-foreground">Interface</p>
|
||||
<p className="font-mono">{status?.interface ?? 'wg0'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Connected peers</p>
|
||||
<p className="font-mono">{status?.peerCount ?? 0}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Listen port</p>
|
||||
<p className="font-mono">{status?.listenPort ?? config?.listenPort ?? 51820}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2 pt-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-1 h-7 text-xs"
|
||||
onClick={() => setShowAdvanced(!showAdvanced)}
|
||||
>
|
||||
{showAdvanced ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
|
||||
Advanced
|
||||
</Button>
|
||||
</div>
|
||||
{showAdvanced && status?.rawOutput && (
|
||||
<div className="border-t pt-3">
|
||||
<span className="text-sm font-medium">WireGuard interface status</span>
|
||||
<pre className="bg-muted p-3 rounded-lg overflow-x-auto text-xs font-mono mt-2">
|
||||
{status.rawOutput}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Server configuration card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Server Configuration</CardTitle>
|
||||
{!editingConfig && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setConfirmKeygen(true)}
|
||||
disabled={isGeneratingKeypair}
|
||||
className="gap-1 h-7 text-xs"
|
||||
>
|
||||
{isGeneratingKeypair ? <Loader2 className="h-3 w-3 animate-spin" /> : <KeyRound className="h-3 w-3" />}
|
||||
Generate Keys
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleEditConfig}
|
||||
className="gap-1 h-7 text-xs"
|
||||
>
|
||||
<Edit2 className="h-3 w-3" />
|
||||
Configure
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoadingConfig ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : editingConfig ? (
|
||||
<form onSubmit={handleSubmit(handleSaveConfig)} className="space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="enabled"
|
||||
{...register('enabled')}
|
||||
className="h-4 w-4"
|
||||
/>
|
||||
<Label htmlFor="enabled">Enabled</Label>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="endpoint">Public Endpoint</Label>
|
||||
<Input
|
||||
id="endpoint"
|
||||
{...register('endpoint')}
|
||||
placeholder="vpn.example.com or 1.2.3.4"
|
||||
className="mt-1"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Public hostname or IP clients use to connect. Port appended automatically if omitted.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="listenPort">Listen Port</Label>
|
||||
<Input
|
||||
id="listenPort"
|
||||
type="number"
|
||||
{...register('listenPort', { required: 'Required', min: { value: 1, message: 'Invalid port' }, max: { value: 65535, message: 'Invalid port' } })}
|
||||
className="mt-1"
|
||||
/>
|
||||
{errors.listenPort && <p className="text-sm text-red-600 mt-1">{errors.listenPort.message}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="address">Server VPN Address</Label>
|
||||
<Input
|
||||
id="address"
|
||||
{...register('address', { required: 'Required' })}
|
||||
placeholder="10.8.0.1/24"
|
||||
className="mt-1 font-mono"
|
||||
/>
|
||||
{errors.address && <p className="text-sm text-red-600 mt-1">{errors.address.message}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="dns">DNS for Clients</Label>
|
||||
<Input
|
||||
id="dns"
|
||||
{...register('dns')}
|
||||
placeholder="10.8.0.1"
|
||||
className="mt-1 font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="lanCIDR">LAN CIDR (optional)</Label>
|
||||
<Input
|
||||
id="lanCIDR"
|
||||
{...register('lanCIDR')}
|
||||
placeholder="192.168.8.0/24"
|
||||
className="mt-1 font-mono"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Routes LAN traffic through the VPN and enables masquerade on the server.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2 pt-2">
|
||||
<Button type="submit" size="sm" disabled={isUpdatingConfig}>
|
||||
{isUpdatingConfig && <Loader2 className="h-3 w-3 animate-spin mr-1" />}
|
||||
Save
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setEditingConfig(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<div className="space-y-3 text-sm">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<p className="text-muted-foreground">Status</p>
|
||||
<Badge variant={config?.enabled ? 'success' : 'secondary'} className="mt-0.5 gap-1">
|
||||
{config?.enabled && <CheckCircle className="h-3 w-3" />}
|
||||
{config?.enabled ? 'Enabled' : 'Disabled'}
|
||||
</Badge>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Public Endpoint</p>
|
||||
<p className="font-mono bg-muted rounded px-2 py-1 mt-0.5">
|
||||
{config?.endpoint || <span className="text-muted-foreground italic">not set</span>}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Listen Port</p>
|
||||
<p className="font-mono bg-muted rounded px-2 py-1 mt-0.5">{config?.listenPort ?? 51820}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">VPN Subnet</p>
|
||||
<p className="font-mono bg-muted rounded px-2 py-1 mt-0.5">{config?.address || '—'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">DNS for Clients</p>
|
||||
<p className="font-mono bg-muted rounded px-2 py-1 mt-0.5">{config?.dns || '—'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">LAN CIDR</p>
|
||||
<p className="font-mono bg-muted rounded px-2 py-1 mt-0.5">{config?.lanCIDR || '—'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Public Key</p>
|
||||
<div className="flex items-center gap-1 mt-0.5">
|
||||
<p className="font-mono bg-muted rounded px-2 py-1 truncate text-xs flex-1">
|
||||
{config?.publicKey || <span className="italic">not generated</span>}
|
||||
</p>
|
||||
{config?.publicKey && <CopyButton text={config.publicKey} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{!config?.publicKey && (
|
||||
<Alert>
|
||||
<KeyRound className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
No server keypair yet. Click <strong>Generate Keys</strong> before adding peers.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Peers card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Peers</CardTitle>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => setAddPeerOpen(true)}
|
||||
disabled={!config?.publicKey}
|
||||
className="gap-1 h-7 text-xs"
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
Add Peer
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoadingPeers ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : peers.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<Shield className="h-10 w-10 mx-auto mb-2 opacity-30" />
|
||||
<p className="text-sm">No peers yet. Add a peer to get started.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y">
|
||||
{peers.map((peer) => (
|
||||
<div key={peer.id} className="flex items-center justify-between py-3">
|
||||
<div>
|
||||
<p className="font-medium text-sm">{peer.name}</p>
|
||||
<p className="text-xs text-muted-foreground font-mono">{peer.allowedIPs}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-1 h-7 text-xs"
|
||||
disabled={loadingPeerConfig === peer.id}
|
||||
onClick={() => handleShowPeerConfig(peer)}
|
||||
>
|
||||
{loadingPeerConfig === peer.id
|
||||
? <Loader2 className="h-3 w-3 animate-spin" />
|
||||
: <RefreshCw className="h-3 w-3" />}
|
||||
Config
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0 text-destructive hover:text-destructive"
|
||||
onClick={() => setDeleteConfirmPeer(peer)}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Add peer drawer */}
|
||||
<Sheet open={addPeerOpen} onOpenChange={setAddPeerOpen}>
|
||||
<SheetContent>
|
||||
<SheetHeader>
|
||||
<SheetTitle>Add Peer</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="space-y-4 py-6">
|
||||
<div>
|
||||
<Label htmlFor="peerName">Peer Name</Label>
|
||||
<Input
|
||||
id="peerName"
|
||||
value={newPeerName}
|
||||
onChange={(e) => setNewPeerName(e.target.value)}
|
||||
placeholder="e.g. my-phone, laptop"
|
||||
className="mt-1"
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleAddPeer()}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
A VPN IP will be assigned automatically from the server subnet.
|
||||
</p>
|
||||
</div>
|
||||
{addPeerError && (
|
||||
<Alert variant="error">
|
||||
<AlertDescription>{String(addPeerError)}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
<SheetFooter>
|
||||
<Button onClick={handleAddPeer} disabled={isAddingPeer || !newPeerName.trim()}>
|
||||
{isAddingPeer && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
||||
Add Peer
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setAddPeerOpen(false)}>Cancel</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
{/* Peer config modal */}
|
||||
<Dialog open={!!peerConfigModal} onOpenChange={(open) => !open && setPeerConfigModal(null)}>
|
||||
<DialogContent className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{peerConfigModal?.name} — Client Config</DialogTitle>
|
||||
</DialogHeader>
|
||||
{peerConfigModal && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-center">
|
||||
<QRCodeSVG value={peerConfigModal.config} size={220} />
|
||||
</div>
|
||||
<p className="text-xs text-center text-muted-foreground">
|
||||
Scan with the WireGuard mobile app
|
||||
</p>
|
||||
<div className="relative">
|
||||
<pre className="text-xs font-mono bg-muted rounded-md p-3 overflow-x-auto whitespace-pre-wrap break-all">
|
||||
{peerConfigModal.config}
|
||||
</pre>
|
||||
<div className="absolute top-2 right-2">
|
||||
<CopyButton text={peerConfigModal.config} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setPeerConfigModal(null)}>Close</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Generate keypair confirmation */}
|
||||
<AlertDialog open={confirmKeygen} onOpenChange={setConfirmKeygen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Regenerate Server Keypair?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This will generate a new server private and public key. All existing peer configs
|
||||
will become invalid — you'll need to regenerate and redistribute them.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleGenerateKeypair}>Generate</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* Delete peer confirmation */}
|
||||
<AlertDialog open={!!deleteConfirmPeer} onOpenChange={(open) => !open && setDeleteConfirmPeer(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete peer "{deleteConfirmPeer?.name}"?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This will remove the peer configuration. The peer will no longer be able to connect
|
||||
after you apply the VPN config.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleDeletePeer}>Delete</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
11
web/src/components/index.ts
Normal file
11
web/src/components/index.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
export { Message } from './Message';
|
||||
export { DnsmasqSection } from './DnsmasqSection';
|
||||
export { AppSidebar } from './AppSidebar';
|
||||
export { ErrorBoundary, ErrorFallback } from './ErrorBoundary';
|
||||
export { CentralComponent } from './CentralComponent';
|
||||
export { CloudflareComponent } from './CloudflareComponent';
|
||||
export { DnsComponent } from './DnsComponent';
|
||||
export { DhcpComponent } from './DhcpComponent';
|
||||
export { DownloadButton } from './DownloadButton';
|
||||
export { CopyButton } from './CopyButton';
|
||||
export { HelpPanel } from './HelpPanel';
|
||||
194
web/src/components/ui/alert-dialog.tsx
Normal file
194
web/src/components/ui/alert-dialog.tsx
Normal file
@@ -0,0 +1,194 @@
|
||||
import * as React from "react"
|
||||
import { AlertDialog as AlertDialogPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
function AlertDialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
|
||||
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
|
||||
}
|
||||
|
||||
function AlertDialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Overlay
|
||||
data-slot="alert-dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogContent({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {
|
||||
size?: "default" | "sm"
|
||||
}) {
|
||||
return (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
data-slot="alert-dialog-content"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/alert-dialog-content fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 data-[size=sm]:max-w-xs data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[size=default]:sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogHeader({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-header"
|
||||
className={cn(
|
||||
"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogFooter({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Title
|
||||
data-slot="alert-dialog-title"
|
||||
className={cn(
|
||||
"text-lg font-semibold sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Description
|
||||
data-slot="alert-dialog-description"
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogMedia({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-media"
|
||||
className={cn(
|
||||
"mb-2 inline-flex size-16 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogAction({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
|
||||
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
|
||||
return (
|
||||
<Button variant={variant} size={size} asChild>
|
||||
<AlertDialogPrimitive.Action
|
||||
data-slot="alert-dialog-action"
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogCancel({
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
|
||||
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
|
||||
return (
|
||||
<Button variant={variant} size={size} asChild>
|
||||
<AlertDialogPrimitive.Cancel
|
||||
data-slot="alert-dialog-cancel"
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogMedia,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogPortal,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
}
|
||||
76
web/src/components/ui/alert.tsx
Normal file
76
web/src/components/ui/alert.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { X } from 'lucide-react';
|
||||
|
||||
const alertVariants = cva(
|
||||
'relative w-full rounded-lg border p-4 [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg+div]:translate-y-[-3px] [&:has(svg)]:pl-11',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'bg-background text-foreground border-border',
|
||||
success: 'bg-green-50 text-green-900 border-green-200 dark:bg-green-950/20 dark:text-green-100 dark:border-green-800',
|
||||
error: 'bg-red-50 text-red-900 border-red-200 dark:bg-red-950/20 dark:text-red-100 dark:border-red-800',
|
||||
warning: 'bg-yellow-50 text-yellow-900 border-yellow-200 dark:bg-yellow-950/20 dark:text-yellow-100 dark:border-yellow-800',
|
||||
info: 'bg-blue-50 text-blue-900 border-blue-200 dark:bg-blue-950/20 dark:text-blue-100 dark:border-blue-800',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export interface AlertProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof alertVariants> {
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
const Alert = React.forwardRef<HTMLDivElement, AlertProps>(
|
||||
({ className, variant, onClose, children, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
role="alert"
|
||||
className={alertVariants({ variant, className })}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{onClose && (
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-offset-2"
|
||||
aria-label="Close"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
Alert.displayName = 'Alert';
|
||||
|
||||
const AlertTitle = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLHeadingElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<h5
|
||||
ref={ref}
|
||||
className={`mb-1 font-medium leading-none tracking-tight ${className || ''}`}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertTitle.displayName = 'AlertTitle';
|
||||
|
||||
const AlertDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={`text-sm [&_p]:leading-relaxed ${className || ''}`}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertDescription.displayName = 'AlertDescription';
|
||||
|
||||
export { Alert, AlertTitle, AlertDescription };
|
||||
50
web/src/components/ui/badge.tsx
Normal file
50
web/src/components/ui/badge.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-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 transition-[color,box-shadow] overflow-hidden",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
success:
|
||||
"border-transparent bg-green-500 text-white [a&]:hover:bg-green-600 dark:bg-green-600 dark:[a&]:hover:bg-green-700",
|
||||
warning:
|
||||
"border-transparent bg-yellow-500 text-white [a&]:hover:bg-yellow-600 dark:bg-yellow-600 dark:[a&]:hover:bg-yellow-700",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "span"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
59
web/src/components/ui/button.tsx
Normal file
59
web/src/components/ui/button.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
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",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
92
web/src/components/ui/card.tsx
Normal file
92
web/src/components/ui/card.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
30
web/src/components/ui/checkbox.tsx
Normal file
30
web/src/components/ui/checkbox.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import * as React from "react"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="grid place-content-center text-current transition-none"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
31
web/src/components/ui/collapsible.tsx
Normal file
31
web/src/components/ui/collapsible.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
|
||||
|
||||
function Collapsible({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
|
||||
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
|
||||
}
|
||||
|
||||
function CollapsibleTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleTrigger
|
||||
data-slot="collapsible-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CollapsibleContent({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleContent
|
||||
data-slot="collapsible-content"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
|
||||
141
web/src/components/ui/dialog.tsx
Normal file
141
web/src/components/ui/dialog.tsx
Normal file
@@ -0,0 +1,141 @@
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||
>
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
95
web/src/components/ui/drawer.tsx
Normal file
95
web/src/components/ui/drawer.tsx
Normal file
@@ -0,0 +1,95 @@
|
||||
import { useEffect, type ReactNode } from 'react';
|
||||
|
||||
interface DrawerProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
footer?: ReactNode;
|
||||
}
|
||||
|
||||
export function Drawer({ open, onClose, title, children, footer }: DrawerProps) {
|
||||
useEffect(() => {
|
||||
const handleEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && open) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleEscape);
|
||||
return () => document.removeEventListener('keydown', handleEscape);
|
||||
}, [open, onClose]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
document.body.style.overflow = 'hidden';
|
||||
} else {
|
||||
document.body.style.overflow = '';
|
||||
}
|
||||
return () => {
|
||||
document.body.style.overflow = '';
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Overlay with fade transition */}
|
||||
<div
|
||||
className={`
|
||||
fixed inset-0 z-50
|
||||
bg-black/50 backdrop-blur-sm
|
||||
transition-opacity duration-300 ease-in-out
|
||||
${open ? 'opacity-100' : 'opacity-0 pointer-events-none'}
|
||||
`}
|
||||
onClick={onClose}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
|
||||
{/* Drawer panel with slide transition */}
|
||||
<div
|
||||
className={`
|
||||
fixed inset-y-0 right-0 z-50
|
||||
w-full max-w-md
|
||||
transform transition-transform duration-300 ease-in-out
|
||||
${open ? 'translate-x-0' : 'translate-x-full'}
|
||||
`}
|
||||
>
|
||||
<div className="flex h-full flex-col bg-background shadow-xl">
|
||||
{/* Header */}
|
||||
<div className="border-b border-border px-6 py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold text-foreground">{title}</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="rounded-md text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
aria-label="Close drawer"
|
||||
>
|
||||
<svg
|
||||
className="h-6 w-6"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
strokeWidth={2}
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 overflow-y-auto px-6 py-6">
|
||||
{children}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
{footer && (
|
||||
<div className="border-t border-border px-6 py-4">
|
||||
{footer}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
97
web/src/components/ui/entity-tile.tsx
Normal file
97
web/src/components/ui/entity-tile.tsx
Normal file
@@ -0,0 +1,97 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
|
||||
interface EntityTileProps extends React.ComponentProps<"div"> {
|
||||
icon?: React.ReactNode
|
||||
title: string
|
||||
version?: string
|
||||
description?: React.ReactNode
|
||||
statusIndicator?: React.ReactNode
|
||||
onClick?: () => void
|
||||
disabled?: boolean
|
||||
loading?: boolean
|
||||
tint?: string
|
||||
}
|
||||
|
||||
function EntityTile({
|
||||
icon,
|
||||
title,
|
||||
version,
|
||||
description,
|
||||
statusIndicator,
|
||||
onClick,
|
||||
disabled = false,
|
||||
loading = false,
|
||||
tint,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: EntityTileProps) {
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (disabled || !onClick) return
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault()
|
||||
onClick()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center w-full sm:w-[240px]">
|
||||
<div
|
||||
role={onClick ? "button" : undefined}
|
||||
tabIndex={onClick && !disabled ? 0 : undefined}
|
||||
onClick={!disabled && !loading ? onClick : undefined}
|
||||
onKeyDown={onClick ? handleKeyDown : undefined}
|
||||
aria-disabled={disabled || undefined}
|
||||
className={cn(
|
||||
"relative w-full aspect-square text-black border border-border/60 p-4 flex flex-col rounded-none",
|
||||
"transition-all duration-200",
|
||||
onClick && !disabled && !loading && [
|
||||
"cursor-pointer",
|
||||
"hover:shadow-md hover:border-primary/50",
|
||||
"hover:scale-[1.02] hover:-translate-y-0.5",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
],
|
||||
loading && "ring-2 ring-primary/60 scale-[0.97] brightness-95",
|
||||
disabled && "opacity-50 pointer-events-none",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
style={tint ? { backgroundColor: `${tint}FF` } : undefined}
|
||||
>
|
||||
{loading && (
|
||||
<div className="absolute inset-0 bg-black/10 animate-pulse rounded-[inherit]" />
|
||||
)}
|
||||
<div className="flex flex-col gap-3 flex-1">
|
||||
<div className="flex items-start gap-3">
|
||||
{icon && (
|
||||
<div className="h-10 w-10 rounded-lg bg-white/70 flex items-center justify-center overflow-hidden shrink-0">
|
||||
{icon}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1 min-w-0">
|
||||
<h4 className="font-medium truncate mb-1">{title}</h4>
|
||||
{version && (
|
||||
<Badge variant="outline" className="text-xs text-black/70 border-black/20">
|
||||
{version}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{description && (
|
||||
<p className="text-sm text-black/60 line-clamp-2">{description}</p>
|
||||
)}
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
<div className="flex justify-center mt-2 h-3">
|
||||
{statusIndicator}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { EntityTile }
|
||||
export type { EntityTileProps }
|
||||
167
web/src/components/ui/form.tsx
Normal file
167
web/src/components/ui/form.tsx
Normal file
@@ -0,0 +1,167 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import {
|
||||
Controller,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
useFormState,
|
||||
type ControllerProps,
|
||||
type FieldPath,
|
||||
type FieldValues,
|
||||
} from "react-hook-form"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Label } from "@/components/ui/label"
|
||||
|
||||
const Form = FormProvider
|
||||
|
||||
type FormFieldContextValue<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
> = {
|
||||
name: TName
|
||||
}
|
||||
|
||||
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||
{} as FormFieldContextValue
|
||||
)
|
||||
|
||||
const FormField = <
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
>({
|
||||
...props
|
||||
}: ControllerProps<TFieldValues, TName>) => {
|
||||
return (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
</FormFieldContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const useFormField = () => {
|
||||
const fieldContext = React.useContext(FormFieldContext)
|
||||
const itemContext = React.useContext(FormItemContext)
|
||||
const { getFieldState } = useFormContext()
|
||||
const formState = useFormState({ name: fieldContext.name })
|
||||
const fieldState = getFieldState(fieldContext.name, formState)
|
||||
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>")
|
||||
}
|
||||
|
||||
const { id } = itemContext
|
||||
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
}
|
||||
}
|
||||
|
||||
type FormItemContextValue = {
|
||||
id: string
|
||||
}
|
||||
|
||||
const FormItemContext = React.createContext<FormItemContextValue>(
|
||||
{} as FormItemContextValue
|
||||
)
|
||||
|
||||
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const id = React.useId()
|
||||
|
||||
return (
|
||||
<FormItemContext.Provider value={{ id }}>
|
||||
<div
|
||||
data-slot="form-item"
|
||||
className={cn("grid gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
</FormItemContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function FormLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
const { error, formItemId } = useFormField()
|
||||
|
||||
return (
|
||||
<Label
|
||||
data-slot="form-label"
|
||||
data-error={!!error}
|
||||
className={cn("data-[error=true]:text-destructive", className)}
|
||||
htmlFor={formItemId}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
|
||||
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
||||
|
||||
return (
|
||||
<Slot
|
||||
data-slot="form-control"
|
||||
id={formItemId}
|
||||
aria-describedby={
|
||||
!error
|
||||
? `${formDescriptionId}`
|
||||
: `${formDescriptionId} ${formMessageId}`
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { formDescriptionId } = useFormField()
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-description"
|
||||
id={formDescriptionId}
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { error, formMessageId } = useFormField()
|
||||
const body = error ? String(error?.message ?? "") : props.children
|
||||
|
||||
if (!body) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-message"
|
||||
id={formMessageId}
|
||||
className={cn("text-destructive text-sm", className)}
|
||||
{...props}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
useFormField,
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
FormField,
|
||||
}
|
||||
28
web/src/components/ui/index.ts
Normal file
28
web/src/components/ui/index.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
export { Button, buttonVariants } from './button';
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } from './card';
|
||||
export { Badge, badgeVariants } from './badge';
|
||||
export { Alert, AlertTitle, AlertDescription } from './alert';
|
||||
export { Input } from './input';
|
||||
export { Label } from './label';
|
||||
export { Textarea } from './textarea';
|
||||
export {
|
||||
Dialog,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogClose,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from './dialog';
|
||||
export {
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
FormField,
|
||||
} from './form';
|
||||
26
web/src/components/ui/input.tsx
Normal file
26
web/src/components/ui/input.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
ref={ref}
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-transparent dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border 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",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] focus-visible:bg-transparent dark:focus-visible:bg-input/30",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
Input.displayName = 'Input'
|
||||
|
||||
export { Input }
|
||||
22
web/src/components/ui/label.tsx
Normal file
22
web/src/components/ui/label.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
158
web/src/components/ui/select.tsx
Normal file
158
web/src/components/ui/select.tsx
Normal file
@@ -0,0 +1,158 @@
|
||||
import * as React from "react"
|
||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
||||
import { Check, ChevronDown, ChevronUp } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Select = SelectPrimitive.Root
|
||||
|
||||
const SelectGroup = SelectPrimitive.Group
|
||||
|
||||
const SelectValue = SelectPrimitive.Value
|
||||
|
||||
const SelectTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
))
|
||||
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
|
||||
|
||||
const SelectScrollUpButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
))
|
||||
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
|
||||
|
||||
const SelectScrollDownButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
))
|
||||
SelectScrollDownButton.displayName =
|
||||
SelectPrimitive.ScrollDownButton.displayName
|
||||
|
||||
const SelectContent = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
|
||||
>(({ className, children, position = "popper", ...props }, ref) => (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
))
|
||||
SelectContent.displayName = SelectPrimitive.Content.displayName
|
||||
|
||||
const SelectLabel = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SelectLabel.displayName = SelectPrimitive.Label.displayName
|
||||
|
||||
const SelectItem = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
))
|
||||
SelectItem.displayName = SelectPrimitive.Item.displayName
|
||||
|
||||
const SelectSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 my-1 h-px bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectGroup,
|
||||
SelectValue,
|
||||
SelectTrigger,
|
||||
SelectContent,
|
||||
SelectLabel,
|
||||
SelectItem,
|
||||
SelectSeparator,
|
||||
SelectScrollUpButton,
|
||||
SelectScrollDownButton,
|
||||
}
|
||||
28
web/src/components/ui/separator.tsx
Normal file
28
web/src/components/ui/separator.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
137
web/src/components/ui/sheet.tsx
Normal file
137
web/src/components/ui/sheet.tsx
Normal file
@@ -0,0 +1,137 @@
|
||||
import * as React from "react"
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||
return <SheetPrimitive.Root data-slot="sheet" {...props} />
|
||||
}
|
||||
|
||||
function SheetTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
|
||||
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
|
||||
}
|
||||
|
||||
function SheetClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
|
||||
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
|
||||
}
|
||||
|
||||
function SheetPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
|
||||
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
|
||||
}
|
||||
|
||||
function SheetOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
|
||||
return (
|
||||
<SheetPrimitive.Overlay
|
||||
data-slot="sheet-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetContent({
|
||||
className,
|
||||
children,
|
||||
side = "right",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
||||
side?: "top" | "right" | "bottom" | "left"
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content
|
||||
data-slot="sheet-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
||||
side === "right" &&
|
||||
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
|
||||
side === "left" &&
|
||||
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
|
||||
side === "top" &&
|
||||
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
|
||||
side === "bottom" &&
|
||||
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
|
||||
<XIcon className="size-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-header"
|
||||
className={cn("flex flex-col gap-1.5 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-footer"
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
|
||||
return (
|
||||
<SheetPrimitive.Title
|
||||
data-slot="sheet-title"
|
||||
className={cn("text-foreground font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
|
||||
return (
|
||||
<SheetPrimitive.Description
|
||||
data-slot="sheet-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
}
|
||||
727
web/src/components/ui/sidebar.tsx
Normal file
727
web/src/components/ui/sidebar.tsx
Normal file
@@ -0,0 +1,727 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva } from "class-variance-authority"
|
||||
import type { VariantProps } from "class-variance-authority"
|
||||
import { PanelLeftIcon } from "lucide-react"
|
||||
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar_state"
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
|
||||
const SIDEBAR_WIDTH = "16rem"
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem"
|
||||
const SIDEBAR_WIDTH_ICON = "3rem"
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
|
||||
|
||||
type SidebarContextProps = {
|
||||
state: "expanded" | "collapsed"
|
||||
open: boolean
|
||||
setOpen: (open: boolean) => void
|
||||
openMobile: boolean
|
||||
setOpenMobile: (open: boolean) => void
|
||||
isMobile: boolean
|
||||
toggleSidebar: () => void
|
||||
}
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext)
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function SidebarProvider({
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
defaultOpen?: boolean
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}) {
|
||||
const isMobile = useIsMobile()
|
||||
const [openMobile, setOpenMobile] = React.useState(false)
|
||||
|
||||
// This is the internal state of the sidebar.
|
||||
// We use openProp and setOpenProp for control from outside the component.
|
||||
const [_open, _setOpen] = React.useState(defaultOpen)
|
||||
const open = openProp ?? _open
|
||||
const setOpen = React.useCallback(
|
||||
(value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState)
|
||||
} else {
|
||||
_setOpen(openState)
|
||||
}
|
||||
|
||||
// This sets the cookie to keep the sidebar state.
|
||||
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
|
||||
},
|
||||
[setOpenProp, open]
|
||||
)
|
||||
|
||||
// Helper to toggle the sidebar.
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
|
||||
}, [isMobile, setOpen, setOpenMobile])
|
||||
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
|
||||
(event.metaKey || event.ctrlKey)
|
||||
) {
|
||||
event.preventDefault()
|
||||
toggleSidebar()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [toggleSidebar])
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed"
|
||||
|
||||
const contextValue = React.useMemo<SidebarContextProps>(
|
||||
() => ({
|
||||
state,
|
||||
open,
|
||||
setOpen,
|
||||
isMobile,
|
||||
openMobile,
|
||||
setOpenMobile,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
|
||||
)
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<div
|
||||
data-slot="sidebar-wrapper"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH,
|
||||
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||
...style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</SidebarContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function Sidebar({
|
||||
side = "left",
|
||||
variant = "sidebar",
|
||||
collapsible = "offcanvas",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right"
|
||||
variant?: "sidebar" | "floating" | "inset"
|
||||
collapsible?: "offcanvas" | "icon" | "none"
|
||||
}) {
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar"
|
||||
className={cn(
|
||||
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
|
||||
<SheetContent
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar"
|
||||
data-mobile="true"
|
||||
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
side={side}
|
||||
>
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>Sidebar</SheetTitle>
|
||||
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex h-full w-full flex-col">{children}</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="group peer text-sidebar-foreground hidden md:block"
|
||||
data-state={state}
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
data-variant={variant}
|
||||
data-side={side}
|
||||
data-slot="sidebar"
|
||||
>
|
||||
{/* This is what handles the sidebar gap on desktop */}
|
||||
<div
|
||||
data-slot="sidebar-gap"
|
||||
className={cn(
|
||||
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
|
||||
"group-data-[collapsible=offcanvas]:w-0",
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
data-slot="sidebar-container"
|
||||
className={cn(
|
||||
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
|
||||
side === "left"
|
||||
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
|
||||
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
|
||||
// Adjust the padding for floating and inset variants.
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar-inner"
|
||||
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarTrigger({
|
||||
className,
|
||||
onClick,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-sidebar="trigger"
|
||||
data-slot="sidebar-trigger"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={cn("size-7", className)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event)
|
||||
toggleSidebar()
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<PanelLeftIcon />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<button
|
||||
data-sidebar="rail"
|
||||
data-slot="sidebar-rail"
|
||||
aria-label="Toggle Sidebar"
|
||||
tabIndex={-1}
|
||||
onClick={toggleSidebar}
|
||||
title="Toggle Sidebar"
|
||||
className={cn(
|
||||
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
|
||||
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
||||
return (
|
||||
<main
|
||||
data-slot="sidebar-inset"
|
||||
className={cn(
|
||||
"bg-background relative flex w-full flex-1 flex-col",
|
||||
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Input>) {
|
||||
return (
|
||||
<Input
|
||||
data-slot="sidebar-input"
|
||||
data-sidebar="input"
|
||||
className={cn("bg-background h-8 w-full shadow-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-header"
|
||||
data-sidebar="header"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-footer"
|
||||
data-sidebar="footer"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
data-slot="sidebar-separator"
|
||||
data-sidebar="separator"
|
||||
className={cn("bg-sidebar-border mx-2 w-auto", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-content"
|
||||
data-sidebar="content"
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group"
|
||||
data-sidebar="group"
|
||||
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupLabel({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "div"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-label"
|
||||
data-sidebar="group-label"
|
||||
className={cn(
|
||||
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupAction({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-action"
|
||||
data-sidebar="group-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group-content"
|
||||
data-sidebar="group-content"
|
||||
className={cn("w-full text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu"
|
||||
data-sidebar="menu"
|
||||
className={cn("flex w-full min-w-0 flex-col gap-1 group-data-[collapsible=icon]:items-center group-data-[state=expanded]:px-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-item"
|
||||
data-sidebar="menu-item"
|
||||
className={cn("group/menu-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
sm: "h-7 text-xs",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function SidebarMenuButton({
|
||||
asChild = false,
|
||||
isActive = false,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
tooltip,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
isActive?: boolean
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const { isMobile, state } = useSidebar()
|
||||
|
||||
const button = (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-button"
|
||||
data-sidebar="menu-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
|
||||
if (!tooltip) {
|
||||
return button
|
||||
}
|
||||
|
||||
if (typeof tooltip === "string") {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="right"
|
||||
align="center"
|
||||
hidden={state !== "collapsed" || isMobile}
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuAction({
|
||||
className,
|
||||
asChild = false,
|
||||
showOnHover = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
showOnHover?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-action"
|
||||
data-sidebar="menu-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
showOnHover &&
|
||||
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuBadge({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-badge"
|
||||
data-sidebar="menu-badge"
|
||||
className={cn(
|
||||
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
|
||||
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSkeleton({
|
||||
className,
|
||||
showIcon = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean
|
||||
}) {
|
||||
// Random width between 50 to 90%.
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-skeleton"
|
||||
data-sidebar="menu-skeleton"
|
||||
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
|
||||
{...props}
|
||||
>
|
||||
{showIcon && (
|
||||
<Skeleton
|
||||
className="size-4 rounded-md"
|
||||
data-sidebar="menu-skeleton-icon"
|
||||
/>
|
||||
)}
|
||||
<Skeleton
|
||||
className="h-4 max-w-(--skeleton-width) flex-1"
|
||||
data-sidebar="menu-skeleton-text"
|
||||
style={
|
||||
{
|
||||
"--skeleton-width": width,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu-sub"
|
||||
data-sidebar="menu-sub"
|
||||
className={cn(
|
||||
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-sub-item"
|
||||
data-sidebar="menu-sub-item"
|
||||
className={cn("group/menu-sub-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubButton({
|
||||
asChild = false,
|
||||
size = "md",
|
||||
isActive = false,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"a"> & {
|
||||
asChild?: boolean
|
||||
size?: "sm" | "md"
|
||||
isActive?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-sub-button"
|
||||
data-sidebar="menu-sub-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupAction,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarInput,
|
||||
SidebarInset,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSkeleton,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarProvider,
|
||||
SidebarRail,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
}
|
||||
13
web/src/components/ui/skeleton.tsx
Normal file
13
web/src/components/ui/skeleton.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="skeleton"
|
||||
className={cn("bg-accent animate-pulse rounded-md", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Skeleton }
|
||||
29
web/src/components/ui/switch.tsx
Normal file
29
web/src/components/ui/switch.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import * as React from "react"
|
||||
import * as SwitchPrimitive from "@radix-ui/react-switch"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Switch({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
|
||||
return (
|
||||
<SwitchPrimitive.Root
|
||||
data-slot="switch"
|
||||
className={cn(
|
||||
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
data-slot="switch-thumb"
|
||||
className={cn(
|
||||
"bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Switch }
|
||||
64
web/src/components/ui/tabs.tsx
Normal file
64
web/src/components/ui/tabs.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import * as React from "react"
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Tabs({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||
return (
|
||||
<TabsPrimitive.Root
|
||||
data-slot="tabs"
|
||||
className={cn("flex flex-col gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.List>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
className={cn(
|
||||
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
return (
|
||||
<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",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
||||
return (
|
||||
<TabsPrimitive.Content
|
||||
data-slot="tabs-content"
|
||||
className={cn("flex-1 outline-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent }
|
||||
18
web/src/components/ui/textarea.tsx
Normal file
18
web/src/components/ui/textarea.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Textarea }
|
||||
59
web/src/components/ui/tooltip.tsx
Normal file
59
web/src/components/ui/tooltip.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import * as React from "react"
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Tooltip({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
</TooltipProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function TooltipTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
sideOffset = 0,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
38
web/src/contexts/HelpContext.tsx
Normal file
38
web/src/contexts/HelpContext.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import { createContext, useContext, useState } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
interface HelpContent {
|
||||
title: string;
|
||||
description: ReactNode;
|
||||
icon?: ReactNode;
|
||||
color?: string;
|
||||
actions?: ReactNode;
|
||||
}
|
||||
|
||||
interface HelpContextType {
|
||||
helpContent: HelpContent | null;
|
||||
setHelpContent: (content: HelpContent | null) => void;
|
||||
isHelpOpen: boolean;
|
||||
setIsHelpOpen: (open: boolean) => void;
|
||||
}
|
||||
|
||||
const HelpContext = createContext<HelpContextType | undefined>(undefined);
|
||||
|
||||
export function HelpProvider({ children }: { children: ReactNode }) {
|
||||
const [helpContent, setHelpContent] = useState<HelpContent | null>(null);
|
||||
const [isHelpOpen, setIsHelpOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<HelpContext.Provider value={{ helpContent, setHelpContent, isHelpOpen, setIsHelpOpen }}>
|
||||
{children}
|
||||
</HelpContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useHelp() {
|
||||
const context = useContext(HelpContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useHelp must be used within a HelpProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
73
web/src/contexts/ThemeContext.tsx
Normal file
73
web/src/contexts/ThemeContext.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
import { createContext, useContext, useEffect, useState } from 'react';
|
||||
|
||||
type Theme = 'dark' | 'light' | 'system';
|
||||
|
||||
type ThemeProviderProps = {
|
||||
children: React.ReactNode;
|
||||
defaultTheme?: Theme;
|
||||
storageKey?: string;
|
||||
};
|
||||
|
||||
type ThemeProviderState = {
|
||||
theme: Theme;
|
||||
setTheme: (theme: Theme) => void;
|
||||
};
|
||||
|
||||
const initialState: ThemeProviderState = {
|
||||
theme: 'system',
|
||||
setTheme: () => null,
|
||||
};
|
||||
|
||||
const ThemeProviderContext = createContext<ThemeProviderState>(initialState);
|
||||
|
||||
export function ThemeProvider({
|
||||
children,
|
||||
defaultTheme = 'system',
|
||||
storageKey = 'wild-central-theme',
|
||||
...props
|
||||
}: ThemeProviderProps) {
|
||||
const [theme, setTheme] = useState<Theme>(
|
||||
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const root = window.document.documentElement;
|
||||
|
||||
root.classList.remove('light', 'dark');
|
||||
|
||||
if (theme === 'system') {
|
||||
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
.matches
|
||||
? 'dark'
|
||||
: 'light';
|
||||
|
||||
root.classList.add(systemTheme);
|
||||
return;
|
||||
}
|
||||
|
||||
root.classList.add(theme);
|
||||
}, [theme]);
|
||||
|
||||
const value = {
|
||||
theme,
|
||||
setTheme: (theme: Theme) => {
|
||||
localStorage.setItem(storageKey, theme);
|
||||
setTheme(theme);
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<ThemeProviderContext.Provider {...props} value={value}>
|
||||
{children}
|
||||
</ThemeProviderContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export const useTheme = () => {
|
||||
const context = useContext(ThemeProviderContext);
|
||||
|
||||
if (context === undefined)
|
||||
throw new Error('useTheme must be used within a ThemeProvider');
|
||||
|
||||
return context;
|
||||
};
|
||||
127
web/src/hooks/__tests__/useMessages.test.ts
Normal file
127
web/src/hooks/__tests__/useMessages.test.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { useMessages } from '../useMessages';
|
||||
|
||||
describe('useMessages', () => {
|
||||
it('should initialize with empty messages', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
expect(result.current.messages).toEqual({});
|
||||
});
|
||||
|
||||
it('should set a message', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test', 'Test message', 'success');
|
||||
});
|
||||
|
||||
expect(result.current.messages).toEqual({
|
||||
test: { message: 'Test message', type: 'success' }
|
||||
});
|
||||
});
|
||||
|
||||
it('should set multiple messages', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('success', 'Success message', 'success');
|
||||
result.current.setMessage('error', 'Error message', 'error');
|
||||
result.current.setMessage('info', 'Info message', 'info');
|
||||
});
|
||||
|
||||
expect(result.current.messages).toEqual({
|
||||
success: { message: 'Success message', type: 'success' },
|
||||
error: { message: 'Error message', type: 'error' },
|
||||
info: { message: 'Info message', type: 'info' },
|
||||
});
|
||||
});
|
||||
|
||||
it('should update existing message', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test', 'First message', 'info');
|
||||
});
|
||||
|
||||
expect(result.current.messages.test).toEqual({
|
||||
message: 'First message',
|
||||
type: 'info'
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test', 'Updated message', 'error');
|
||||
});
|
||||
|
||||
expect(result.current.messages.test).toEqual({
|
||||
message: 'Updated message',
|
||||
type: 'error'
|
||||
});
|
||||
});
|
||||
|
||||
it('should clear a specific message', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test1', 'Message 1', 'info');
|
||||
result.current.setMessage('test2', 'Message 2', 'success');
|
||||
});
|
||||
|
||||
expect(Object.keys(result.current.messages)).toHaveLength(2);
|
||||
|
||||
act(() => {
|
||||
result.current.clearMessage('test1');
|
||||
});
|
||||
|
||||
expect(result.current.messages).toEqual({
|
||||
test2: { message: 'Message 2', type: 'success' }
|
||||
});
|
||||
});
|
||||
|
||||
it('should clear message by setting to null', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test', 'Test message', 'info');
|
||||
});
|
||||
|
||||
expect(result.current.messages.test).toBeDefined();
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test', null);
|
||||
});
|
||||
|
||||
expect(result.current.messages.test).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should clear all messages', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test1', 'Message 1', 'info');
|
||||
result.current.setMessage('test2', 'Message 2', 'success');
|
||||
result.current.setMessage('test3', 'Message 3', 'error');
|
||||
});
|
||||
|
||||
expect(Object.keys(result.current.messages)).toHaveLength(3);
|
||||
|
||||
act(() => {
|
||||
result.current.clearAllMessages();
|
||||
});
|
||||
|
||||
expect(result.current.messages).toEqual({});
|
||||
});
|
||||
|
||||
it('should default to info type when type not specified', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test', 'Test message');
|
||||
});
|
||||
|
||||
expect(result.current.messages.test).toEqual({
|
||||
message: 'Test message',
|
||||
type: 'info'
|
||||
});
|
||||
});
|
||||
});
|
||||
104
web/src/hooks/__tests__/useStatus.test.ts
Normal file
104
web/src/hooks/__tests__/useStatus.test.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import React from 'react';
|
||||
import { useStatus } from '../useStatus';
|
||||
import { apiService } from '../../services/api-legacy';
|
||||
|
||||
// Mock the API service
|
||||
vi.mock('../../services/api-legacy', () => ({
|
||||
apiService: {
|
||||
getStatus: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
gcTime: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
React.createElement(QueryClientProvider, { client: queryClient }, children)
|
||||
);
|
||||
};
|
||||
|
||||
describe('useStatus', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should fetch status successfully', async () => {
|
||||
const mockStatus = {
|
||||
status: 'running',
|
||||
version: '1.0.0',
|
||||
uptime: '2 hours',
|
||||
timestamp: '2024-01-01T00:00:00Z',
|
||||
};
|
||||
|
||||
(apiService.getStatus as ReturnType<typeof vi.fn>).mockResolvedValue(mockStatus);
|
||||
|
||||
const { result } = renderHook(() => useStatus(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
expect(result.current.isLoading).toBe(true);
|
||||
expect(result.current.data).toBeUndefined();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.data).toEqual(mockStatus);
|
||||
expect(result.current.error).toBeNull();
|
||||
expect(apiService.getStatus).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should handle error when fetching status fails', async () => {
|
||||
const mockError = new Error('Network error');
|
||||
(apiService.getStatus as ReturnType<typeof vi.fn>).mockRejectedValue(mockError);
|
||||
|
||||
const { result } = renderHook(() => useStatus(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.data).toBeUndefined();
|
||||
expect(result.current.error).toEqual(mockError);
|
||||
});
|
||||
|
||||
it('should refetch data when refetch is called', async () => {
|
||||
const mockStatus = {
|
||||
status: 'running',
|
||||
version: '1.0.0',
|
||||
uptime: '2 hours',
|
||||
timestamp: '2024-01-01T00:00:00Z',
|
||||
};
|
||||
|
||||
(apiService.getStatus as ReturnType<typeof vi.fn>).mockResolvedValue(mockStatus);
|
||||
|
||||
const { result } = renderHook(() => useStatus(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(apiService.getStatus).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Trigger refetch
|
||||
result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(apiService.getStatus).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
7
web/src/hooks/index.ts
Normal file
7
web/src/hooks/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export { useMessages } from './useMessages';
|
||||
export { useStatus } from './useStatus';
|
||||
export { useHealth } from './useHealth';
|
||||
export { useConfig } from './useConfig';
|
||||
export { useDnsmasq } from './useDnsmasq';
|
||||
export { useCentralStatus } from './useCentralStatus';
|
||||
export { useCloudflare } from './useCloudflare';
|
||||
19
web/src/hooks/use-mobile.ts
Normal file
19
web/src/hooks/use-mobile.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import * as React from "react"
|
||||
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
|
||||
export function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||
|
||||
React.useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
}
|
||||
mql.addEventListener("change", onChange)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
return () => mql.removeEventListener("change", onChange)
|
||||
}, [])
|
||||
|
||||
return !!isMobile
|
||||
}
|
||||
53
web/src/hooks/useCentralStatus.ts
Normal file
53
web/src/hooks/useCentralStatus.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { apiClient } from '../services/api/client';
|
||||
|
||||
interface CentralStatus {
|
||||
status: string;
|
||||
version: string;
|
||||
uptime: string;
|
||||
uptimeSeconds: number;
|
||||
dataDir: string;
|
||||
appsDir: string;
|
||||
setupFiles: string;
|
||||
pendingRestart: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to fetch Wild Central server status and trigger restarts
|
||||
*/
|
||||
export function useCentralStatus() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: ['central', 'status'],
|
||||
queryFn: async (): Promise<CentralStatus> => {
|
||||
return apiClient.get('/api/v1/status');
|
||||
},
|
||||
refetchInterval: 30000,
|
||||
staleTime: 10000,
|
||||
});
|
||||
|
||||
const restartMutation = useMutation({
|
||||
mutationFn: () => apiClient.post('/api/v1/daemon/restart'),
|
||||
onSuccess: () => {
|
||||
// Poll until the daemon comes back up
|
||||
const poll = setInterval(async () => {
|
||||
try {
|
||||
await apiClient.get('/api/v1/health');
|
||||
clearInterval(poll);
|
||||
queryClient.invalidateQueries({ queryKey: ['central', 'status'] });
|
||||
} catch {
|
||||
// still restarting
|
||||
}
|
||||
}, 1000);
|
||||
// Give up after 30s
|
||||
setTimeout(() => clearInterval(poll), 30000);
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
...statusQuery,
|
||||
restart: () => restartMutation.mutate(),
|
||||
isRestarting: restartMutation.isPending,
|
||||
};
|
||||
}
|
||||
39
web/src/hooks/useCert.ts
Normal file
39
web/src/hooks/useCert.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { certApi } from '../services/api/cert';
|
||||
|
||||
export function useCert() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: ['cert', 'status'],
|
||||
queryFn: () => certApi.getStatus(),
|
||||
refetchInterval: false,
|
||||
staleTime: 60000,
|
||||
});
|
||||
|
||||
const provisionMutation = useMutation({
|
||||
mutationFn: () => certApi.provision(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['cert', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
const renewMutation = useMutation({
|
||||
mutationFn: () => certApi.renew(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['cert', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
status: statusQuery.data,
|
||||
isLoading: statusQuery.isLoading,
|
||||
|
||||
provision: provisionMutation.mutateAsync,
|
||||
isProvisioning: provisionMutation.isPending,
|
||||
provisionError: provisionMutation.error,
|
||||
|
||||
renew: renewMutation.mutateAsync,
|
||||
isRenewing: renewMutation.isPending,
|
||||
};
|
||||
}
|
||||
18
web/src/hooks/useCloudflare.ts
Normal file
18
web/src/hooks/useCloudflare.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { cloudflareApi } from '../services/api/cloudflare';
|
||||
|
||||
export const useCloudflare = () => {
|
||||
const verifyQuery = useQuery({
|
||||
queryKey: ['cloudflare', 'verify'],
|
||||
queryFn: () => cloudflareApi.verify(),
|
||||
refetchInterval: false,
|
||||
staleTime: 60000,
|
||||
});
|
||||
|
||||
return {
|
||||
verification: verifyQuery.data,
|
||||
isLoading: verifyQuery.isLoading,
|
||||
error: verifyQuery.error,
|
||||
refetch: verifyQuery.refetch,
|
||||
};
|
||||
};
|
||||
62
web/src/hooks/useConfig.ts
Normal file
62
web/src/hooks/useConfig.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { apiService } from '../services/api-legacy';
|
||||
import type { GlobalConfig, GlobalConfigResponse } from '../types';
|
||||
|
||||
interface CreateConfigResponse {
|
||||
status: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for managing Wild Central global configuration
|
||||
* Endpoint: /api/v1/config
|
||||
* File: {dataDir}/config.yaml
|
||||
*/
|
||||
export const useConfig = () => {
|
||||
const queryClient = useQueryClient();
|
||||
const [showConfigSetup, setShowConfigSetup] = useState(false);
|
||||
|
||||
const configQuery = useQuery<GlobalConfigResponse>({
|
||||
queryKey: ['globalConfig'],
|
||||
queryFn: () => apiService.getConfig(),
|
||||
});
|
||||
|
||||
// Update showConfigSetup based on query data
|
||||
useEffect(() => {
|
||||
if (configQuery.data) {
|
||||
setShowConfigSetup(configQuery.data.configured === false);
|
||||
}
|
||||
}, [configQuery.data]);
|
||||
|
||||
const createConfigMutation = useMutation<CreateConfigResponse, Error, GlobalConfig>({
|
||||
mutationFn: (config) => apiService.createConfig(config),
|
||||
onSuccess: () => {
|
||||
// Invalidate and refetch config after successful creation
|
||||
queryClient.invalidateQueries({ queryKey: ['globalConfig'] });
|
||||
setShowConfigSetup(false);
|
||||
},
|
||||
});
|
||||
|
||||
const updateConfigMutation = useMutation<CreateConfigResponse, Error, GlobalConfig>({
|
||||
mutationFn: (config) => apiService.updateConfig(config),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['globalConfig'] });
|
||||
// Immediately re-check daemon status so the pending-restart banner appears
|
||||
queryClient.invalidateQueries({ queryKey: ['central', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
config: configQuery.data?.config || null,
|
||||
isConfigured: configQuery.data?.configured || false,
|
||||
showConfigSetup,
|
||||
setShowConfigSetup,
|
||||
isLoading: configQuery.isLoading,
|
||||
isCreating: createConfigMutation.isPending,
|
||||
isUpdating: updateConfigMutation.isPending,
|
||||
error: configQuery.error || createConfigMutation.error || updateConfigMutation.error,
|
||||
createConfig: createConfigMutation.mutate,
|
||||
updateConfig: updateConfigMutation.mutateAsync,
|
||||
refetch: configQuery.refetch,
|
||||
};
|
||||
};
|
||||
128
web/src/hooks/useCrowdSec.ts
Normal file
128
web/src/hooks/useCrowdSec.ts
Normal file
@@ -0,0 +1,128 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { crowdSecApi, type AddDecisionRequest } from '../services/api/networking';
|
||||
|
||||
export const useCrowdSec = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: ['crowdsec', 'status'],
|
||||
queryFn: () => crowdSecApi.getStatus(),
|
||||
refetchInterval: false,
|
||||
staleTime: 30000,
|
||||
});
|
||||
|
||||
const summaryQuery = useQuery({
|
||||
queryKey: ['crowdsec', 'summary'],
|
||||
queryFn: () => crowdSecApi.getSummary(),
|
||||
refetchInterval: false,
|
||||
staleTime: 300000, // 5 minutes — CAPI bans change slowly
|
||||
enabled: statusQuery.data?.active ?? false,
|
||||
});
|
||||
|
||||
const alertsQuery = useQuery({
|
||||
queryKey: ['crowdsec', 'alerts'],
|
||||
queryFn: () => crowdSecApi.getAlerts(50),
|
||||
refetchInterval: false,
|
||||
staleTime: 60000,
|
||||
enabled: statusQuery.data?.active ?? false,
|
||||
});
|
||||
|
||||
const alertsGraphQuery = useQuery({
|
||||
queryKey: ['crowdsec', 'alerts-graph'],
|
||||
queryFn: () => crowdSecApi.getAlerts(500),
|
||||
refetchInterval: false,
|
||||
staleTime: 120000,
|
||||
enabled: statusQuery.data?.active ?? false,
|
||||
});
|
||||
|
||||
const decisionsQuery = useQuery({
|
||||
queryKey: ['crowdsec', 'decisions'],
|
||||
queryFn: () => crowdSecApi.getDecisions(),
|
||||
refetchInterval: false,
|
||||
staleTime: 30000,
|
||||
enabled: statusQuery.data?.active ?? false,
|
||||
});
|
||||
|
||||
const addDecisionMutation = useMutation({
|
||||
mutationFn: (req: AddDecisionRequest) => crowdSecApi.addDecision(req),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'decisions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'summary'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteDecisionMutation = useMutation({
|
||||
mutationFn: (id: number) => crowdSecApi.deleteDecision(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'decisions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'summary'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteDecisionByIPMutation = useMutation({
|
||||
mutationFn: (ip: string) => crowdSecApi.deleteDecisionByIP(ip),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'decisions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'summary'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteBouncerMutation = useMutation({
|
||||
mutationFn: (name: string) => crowdSecApi.deleteBouncer(name),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMachineMutation = useMutation({
|
||||
mutationFn: (name: string) => crowdSecApi.deleteMachine(name),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
const provisionMutation = useMutation({
|
||||
mutationFn: (instanceName: string) => crowdSecApi.provision(instanceName),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
status: statusQuery.data,
|
||||
isLoadingStatus: statusQuery.isLoading,
|
||||
statusError: statusQuery.error,
|
||||
|
||||
summary: summaryQuery.data,
|
||||
isLoadingSummary: summaryQuery.isLoading,
|
||||
|
||||
alerts: alertsQuery.data?.alerts ?? [],
|
||||
isLoadingAlerts: alertsQuery.isLoading,
|
||||
refetchAlerts: alertsQuery.refetch,
|
||||
|
||||
graphAlerts: alertsGraphQuery.data?.alerts ?? [],
|
||||
isLoadingGraphAlerts: alertsGraphQuery.isLoading,
|
||||
|
||||
decisions: decisionsQuery.data?.decisions ?? [],
|
||||
isLoadingDecisions: decisionsQuery.isLoading,
|
||||
|
||||
addDecision: addDecisionMutation.mutate,
|
||||
isAddingDecision: addDecisionMutation.isPending,
|
||||
addDecisionError: addDecisionMutation.error,
|
||||
|
||||
deleteDecision: deleteDecisionMutation.mutate,
|
||||
isDeletingDecision: deleteDecisionMutation.isPending,
|
||||
|
||||
deleteDecisionByIP: deleteDecisionByIPMutation.mutate,
|
||||
isDeletingByIP: deleteDecisionByIPMutation.isPending,
|
||||
|
||||
deleteBouncer: deleteBouncerMutation.mutate,
|
||||
isDeletingBouncer: deleteBouncerMutation.isPending,
|
||||
|
||||
deleteMachine: deleteMachineMutation.mutate,
|
||||
isDeletingMachine: deleteMachineMutation.isPending,
|
||||
|
||||
provision: provisionMutation.mutate,
|
||||
isProvisioning: provisionMutation.isPending,
|
||||
};
|
||||
};
|
||||
33
web/src/hooks/useDdns.ts
Normal file
33
web/src/hooks/useDdns.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { ddnsApi } from '../services/api/networking';
|
||||
|
||||
export const useDdns = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: ['ddns', 'status'],
|
||||
queryFn: () => ddnsApi.getStatus(),
|
||||
refetchInterval: false,
|
||||
staleTime: 30000,
|
||||
});
|
||||
|
||||
const triggerMutation = useMutation({
|
||||
mutationFn: () => ddnsApi.trigger(),
|
||||
onSuccess: () => {
|
||||
// Refresh status shortly after trigger
|
||||
setTimeout(() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['ddns', 'status'] });
|
||||
}, 2000);
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
status: statusQuery.data,
|
||||
isLoadingStatus: statusQuery.isLoading,
|
||||
|
||||
trigger: triggerMutation.mutate,
|
||||
isTriggering: triggerMutation.isPending,
|
||||
triggerData: triggerMutation.data,
|
||||
triggerError: triggerMutation.error,
|
||||
};
|
||||
};
|
||||
42
web/src/hooks/useDhcp.ts
Normal file
42
web/src/hooks/useDhcp.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { dhcpApi } from '../services/api/networking';
|
||||
import type { DhcpStaticLease } from '../services/api/networking';
|
||||
|
||||
export const useDhcp = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const leasesQuery = useQuery({
|
||||
queryKey: ['dhcp', 'leases'],
|
||||
queryFn: () => dhcpApi.getLeases(),
|
||||
refetchInterval: 30000,
|
||||
staleTime: 20000,
|
||||
});
|
||||
|
||||
const addStaticMutation = useMutation({
|
||||
mutationFn: (lease: DhcpStaticLease) => dhcpApi.addStatic(lease),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['dhcp', 'leases'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteStaticMutation = useMutation({
|
||||
mutationFn: (mac: string) => dhcpApi.deleteStatic(mac),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['dhcp', 'leases'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
leases: leasesQuery.data?.leases ?? [],
|
||||
isLoadingLeases: leasesQuery.isLoading,
|
||||
leasesError: leasesQuery.error,
|
||||
refetchLeases: leasesQuery.refetch,
|
||||
|
||||
addStatic: addStaticMutation.mutate,
|
||||
isAddingStatic: addStaticMutation.isPending,
|
||||
addStaticError: addStaticMutation.error,
|
||||
|
||||
deleteStatic: deleteStaticMutation.mutate,
|
||||
isDeletingStatic: deleteStaticMutation.isPending,
|
||||
};
|
||||
};
|
||||
63
web/src/hooks/useDnsmasq.ts
Normal file
63
web/src/hooks/useDnsmasq.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
import { apiService } from '../services/api-legacy';
|
||||
import type { DnsmasqStatus, DnsmasqConfigResponse, StatusResponse } from '../types';
|
||||
|
||||
export const useDnsmasq = () => {
|
||||
// Query for status
|
||||
const statusQuery = useQuery<DnsmasqStatus>({
|
||||
queryKey: ['dnsmasq', 'status'],
|
||||
queryFn: () => apiService.getDnsmasqStatus(),
|
||||
refetchInterval: 30000,
|
||||
staleTime: 10000,
|
||||
});
|
||||
|
||||
// Query for config
|
||||
const configQuery = useQuery<DnsmasqConfigResponse>({
|
||||
queryKey: ['dnsmasq', 'config'],
|
||||
queryFn: () => apiService.getDnsmasqConfig(),
|
||||
enabled: false, // Only fetch when explicitly called
|
||||
});
|
||||
|
||||
// Mutation for generating config (with optional overwrite)
|
||||
const generateMutation = useMutation<DnsmasqConfigResponse, Error, boolean>({
|
||||
mutationFn: (overwrite = false) => apiService.generateDnsmasqConfig(overwrite),
|
||||
onSuccess: () => {
|
||||
statusQuery.refetch();
|
||||
configQuery.refetch();
|
||||
},
|
||||
});
|
||||
|
||||
// Mutation for restarting service
|
||||
const restartMutation = useMutation<StatusResponse>({
|
||||
mutationFn: () => apiService.restartDnsmasq(),
|
||||
onSuccess: () => {
|
||||
statusQuery.refetch();
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
// Status
|
||||
status: statusQuery.data,
|
||||
isLoadingStatus: statusQuery.isLoading,
|
||||
statusError: statusQuery.error,
|
||||
refetchStatus: statusQuery.refetch,
|
||||
|
||||
// Config
|
||||
config: configQuery.data,
|
||||
isLoadingConfig: configQuery.isLoading,
|
||||
configError: configQuery.error,
|
||||
fetchConfig: configQuery.refetch,
|
||||
|
||||
// Generate
|
||||
generateConfig: generateMutation.mutate,
|
||||
generateData: generateMutation.data,
|
||||
isGenerating: generateMutation.isPending,
|
||||
generateError: generateMutation.error,
|
||||
|
||||
// Restart
|
||||
restart: restartMutation.mutate,
|
||||
restartData: restartMutation.data,
|
||||
isRestarting: restartMutation.isPending,
|
||||
restartError: restartMutation.error,
|
||||
};
|
||||
};
|
||||
52
web/src/hooks/useHaproxy.ts
Normal file
52
web/src/hooks/useHaproxy.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { haproxyApi } from '../services/api/networking';
|
||||
|
||||
export const useHaproxy = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: ['haproxy', 'status'],
|
||||
queryFn: () => haproxyApi.getStatus(),
|
||||
refetchInterval: 30000,
|
||||
staleTime: 10000,
|
||||
});
|
||||
|
||||
const statsQuery = useQuery({
|
||||
queryKey: ['haproxy', 'stats'],
|
||||
queryFn: () => haproxyApi.getStats(),
|
||||
refetchInterval: 30000,
|
||||
staleTime: 10000,
|
||||
});
|
||||
|
||||
const generateMutation = useMutation({
|
||||
mutationFn: () => haproxyApi.generate(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['haproxy', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
const restartMutation = useMutation({
|
||||
mutationFn: () => haproxyApi.restart(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['haproxy', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
status: statusQuery.data,
|
||||
isLoadingStatus: statusQuery.isLoading,
|
||||
statusError: statusQuery.error,
|
||||
|
||||
stats: statsQuery.data?.backends ?? [],
|
||||
isLoadingStats: statsQuery.isLoading,
|
||||
|
||||
generate: generateMutation.mutate,
|
||||
isGenerating: generateMutation.isPending,
|
||||
generateData: generateMutation.data,
|
||||
generateError: generateMutation.error,
|
||||
|
||||
restart: restartMutation.mutate,
|
||||
isRestarting: restartMutation.isPending,
|
||||
restartError: restartMutation.error,
|
||||
};
|
||||
};
|
||||
13
web/src/hooks/useHealth.ts
Normal file
13
web/src/hooks/useHealth.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { apiService } from '../services/api-legacy';
|
||||
|
||||
interface HealthResponse {
|
||||
service: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export const useHealth = () => {
|
||||
return useMutation<HealthResponse>({
|
||||
mutationFn: apiService.getHealth,
|
||||
});
|
||||
};
|
||||
33
web/src/hooks/useMessages.ts
Normal file
33
web/src/hooks/useMessages.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { useState } from 'react';
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const useMessages = () => {
|
||||
const [messages, setMessages] = useState<Messages>({});
|
||||
|
||||
const setMessage = (key: string, message: string | null, type: 'info' | 'success' | 'error' = 'info') => {
|
||||
if (message === null) {
|
||||
setMessages(prev => {
|
||||
const newMessages = { ...prev };
|
||||
delete newMessages[key];
|
||||
return newMessages;
|
||||
});
|
||||
} else {
|
||||
setMessages(prev => ({ ...prev, [key]: { message, type } }));
|
||||
}
|
||||
};
|
||||
|
||||
const clearMessage = (key: string) => {
|
||||
setMessage(key, null);
|
||||
};
|
||||
|
||||
const clearAllMessages = () => {
|
||||
setMessages({});
|
||||
};
|
||||
|
||||
return {
|
||||
messages,
|
||||
setMessage,
|
||||
clearMessage,
|
||||
clearAllMessages,
|
||||
};
|
||||
};
|
||||
39
web/src/hooks/useNftables.ts
Normal file
39
web/src/hooks/useNftables.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { nftablesApi } from '../services/api/networking';
|
||||
|
||||
export const useNftables = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: ['nftables', 'status'],
|
||||
queryFn: () => nftablesApi.getStatus(),
|
||||
refetchInterval: false,
|
||||
staleTime: 30000,
|
||||
});
|
||||
|
||||
const interfacesQuery = useQuery({
|
||||
queryKey: ['nftables', 'interfaces'],
|
||||
queryFn: () => nftablesApi.getInterfaces(),
|
||||
refetchInterval: false,
|
||||
staleTime: 60000,
|
||||
});
|
||||
|
||||
const applyMutation = useMutation({
|
||||
mutationFn: () => nftablesApi.apply(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['nftables', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
status: statusQuery.data,
|
||||
isLoadingStatus: statusQuery.isLoading,
|
||||
refetchStatus: statusQuery.refetch,
|
||||
|
||||
interfaces: interfacesQuery.data?.interfaces ?? [],
|
||||
|
||||
apply: applyMutation.mutate,
|
||||
isApplying: applyMutation.isPending,
|
||||
applyError: applyMutation.error,
|
||||
};
|
||||
};
|
||||
25
web/src/hooks/usePageHelp.tsx
Normal file
25
web/src/hooks/usePageHelp.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useHelp } from '../contexts/HelpContext';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
interface PageHelpOptions {
|
||||
title: string;
|
||||
description: ReactNode;
|
||||
icon?: ReactNode;
|
||||
color?: string;
|
||||
actions?: ReactNode;
|
||||
}
|
||||
|
||||
export function usePageHelp(options: PageHelpOptions | null) {
|
||||
const { setHelpContent } = useHelp();
|
||||
|
||||
useEffect(() => {
|
||||
setHelpContent(options);
|
||||
|
||||
// Clear help content when component unmounts
|
||||
return () => {
|
||||
setHelpContent(null);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []); // Only run on mount/unmount
|
||||
}
|
||||
11
web/src/hooks/useStatus.ts
Normal file
11
web/src/hooks/useStatus.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { apiService } from '../services/api-legacy';
|
||||
import type { Status } from '../types';
|
||||
|
||||
export const useStatus = () => {
|
||||
return useQuery<Status>({
|
||||
queryKey: ['status'],
|
||||
queryFn: apiService.getStatus,
|
||||
refetchInterval: 30000, // Refetch every 30 seconds
|
||||
});
|
||||
};
|
||||
93
web/src/hooks/useVpn.ts
Normal file
93
web/src/hooks/useVpn.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { vpnApi, type VpnConfig } from '../services/api/vpn';
|
||||
|
||||
export function useVpn() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: ['vpn', 'status'],
|
||||
queryFn: () => vpnApi.getStatus(),
|
||||
refetchInterval: 10000,
|
||||
staleTime: 5000,
|
||||
});
|
||||
|
||||
const configQuery = useQuery({
|
||||
queryKey: ['vpn', 'config'],
|
||||
queryFn: () => vpnApi.getConfig(),
|
||||
refetchInterval: false,
|
||||
staleTime: 60000,
|
||||
});
|
||||
|
||||
const peersQuery = useQuery({
|
||||
queryKey: ['vpn', 'peers'],
|
||||
queryFn: () => vpnApi.listPeers(),
|
||||
refetchInterval: false,
|
||||
staleTime: 30000,
|
||||
});
|
||||
|
||||
const updateConfigMutation = useMutation({
|
||||
mutationFn: (cfg: Omit<VpnConfig, 'publicKey'>) => vpnApi.updateConfig(cfg),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['vpn', 'config'] });
|
||||
},
|
||||
});
|
||||
|
||||
const generateKeypairMutation = useMutation({
|
||||
mutationFn: () => vpnApi.generateKeypair(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['vpn', 'config'] });
|
||||
},
|
||||
});
|
||||
|
||||
const applyMutation = useMutation({
|
||||
mutationFn: () => vpnApi.apply(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['vpn', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
const addPeerMutation = useMutation({
|
||||
mutationFn: (name: string) => vpnApi.addPeer(name),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['vpn', 'peers'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deletePeerMutation = useMutation({
|
||||
mutationFn: (id: string) => vpnApi.deletePeer(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['vpn', 'peers'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
status: statusQuery.data,
|
||||
isLoadingStatus: statusQuery.isLoading,
|
||||
statusError: statusQuery.error,
|
||||
|
||||
config: configQuery.data,
|
||||
isLoadingConfig: configQuery.isLoading,
|
||||
configError: configQuery.error,
|
||||
|
||||
peers: peersQuery.data?.peers ?? [],
|
||||
isLoadingPeers: peersQuery.isLoading,
|
||||
|
||||
updateConfig: updateConfigMutation.mutateAsync,
|
||||
isUpdatingConfig: updateConfigMutation.isPending,
|
||||
updateConfigError: updateConfigMutation.error,
|
||||
|
||||
generateKeypair: generateKeypairMutation.mutateAsync,
|
||||
isGeneratingKeypair: generateKeypairMutation.isPending,
|
||||
|
||||
apply: applyMutation.mutateAsync,
|
||||
isApplying: applyMutation.isPending,
|
||||
applyError: applyMutation.error,
|
||||
|
||||
addPeer: addPeerMutation.mutateAsync,
|
||||
isAddingPeer: addPeerMutation.isPending,
|
||||
addPeerError: addPeerMutation.error,
|
||||
|
||||
deletePeer: deletePeerMutation.mutateAsync,
|
||||
isDeletingPeer: deletePeerMutation.isPending,
|
||||
};
|
||||
}
|
||||
160
web/src/index.css
Normal file
160
web/src/index.css
Normal file
@@ -0,0 +1,160 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@plugin "@tailwindcss/typography";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(50.59% 0.12582 244.557);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
|
||||
/* Page transitions via View Transitions API (React Router v7) */
|
||||
::view-transition-old(root) {
|
||||
animation: fade-and-slide-out 200ms ease-in forwards;
|
||||
}
|
||||
|
||||
::view-transition-new(root) {
|
||||
animation: fade-and-slide-in 200ms ease-out forwards;
|
||||
}
|
||||
|
||||
@keyframes fade-and-slide-out {
|
||||
from {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: translateY(-8px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fade-and-slide-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(8px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Respect reduced motion preferences */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
::view-transition-old(root),
|
||||
::view-transition-new(root) {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
15
web/src/lib/queryClient.ts
Normal file
15
web/src/lib/queryClient.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { QueryClient } from '@tanstack/react-query';
|
||||
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: 1,
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
gcTime: 10 * 60 * 1000, // 10 minutes
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
mutations: {
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
6
web/src/lib/utils.ts
Normal file
6
web/src/lib/utils.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
24
web/src/main.tsx
Normal file
24
web/src/main.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { StrictMode } from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { QueryClientProvider } from '@tanstack/react-query';
|
||||
import './index.css';
|
||||
import App from './App';
|
||||
import { ThemeProvider } from './contexts/ThemeContext';
|
||||
import { queryClient } from './lib/queryClient';
|
||||
import { ErrorBoundary } from './components/ErrorBoundary';
|
||||
|
||||
const root = ReactDOM.createRoot(
|
||||
document.getElementById('root') as HTMLElement
|
||||
);
|
||||
|
||||
root.render(
|
||||
<StrictMode>
|
||||
<ErrorBoundary>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ThemeProvider defaultTheme="light" storageKey="wild-central-theme">
|
||||
<App />
|
||||
</ThemeProvider>
|
||||
</QueryClientProvider>
|
||||
</ErrorBoundary>
|
||||
</StrictMode>
|
||||
);
|
||||
61
web/src/router/CentralLayout.tsx
Normal file
61
web/src/router/CentralLayout.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
import { useState } from 'react';
|
||||
import { Outlet } from 'react-router';
|
||||
import { AppSidebar } from '../components/AppSidebar';
|
||||
import { SidebarProvider, SidebarInset, SidebarTrigger } from '../components/ui/sidebar';
|
||||
import { HelpProvider, useHelp } from '../contexts/HelpContext';
|
||||
import { HelpPanel } from '../components/HelpPanel';
|
||||
import { Button } from '../components/ui/button';
|
||||
import { HelpCircle } from 'lucide-react';
|
||||
|
||||
function CentralLayoutContent() {
|
||||
const { helpContent, setIsHelpOpen } = useHelp();
|
||||
|
||||
return (
|
||||
<>
|
||||
<AppSidebar />
|
||||
<SidebarInset className="min-w-0">
|
||||
<header className="flex h-16 shrink-0 items-center gap-2 px-4">
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<div className="flex items-center gap-2 flex-1">
|
||||
<h1 className="text-lg font-semibold">Wild Central</h1>
|
||||
</div>
|
||||
{helpContent && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsHelpOpen(true)}
|
||||
className="ml-auto"
|
||||
>
|
||||
<HelpCircle className="h-5 w-5" />
|
||||
<span className="sr-only">Help</span>
|
||||
</Button>
|
||||
)}
|
||||
</header>
|
||||
<div className="flex flex-1 flex-col gap-4 p-4">
|
||||
<Outlet />
|
||||
</div>
|
||||
</SidebarInset>
|
||||
<HelpPanel />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function CentralLayout() {
|
||||
const [sidebarOpen, setSidebarOpen] = useState(
|
||||
() => localStorage.getItem('sidebar_state') !== 'false'
|
||||
);
|
||||
|
||||
return (
|
||||
<HelpProvider>
|
||||
<SidebarProvider
|
||||
open={sidebarOpen}
|
||||
onOpenChange={(open) => {
|
||||
setSidebarOpen(open);
|
||||
localStorage.setItem('sidebar_state', String(open));
|
||||
}}
|
||||
>
|
||||
<CentralLayoutContent />
|
||||
</SidebarProvider>
|
||||
</HelpProvider>
|
||||
);
|
||||
}
|
||||
12
web/src/router/index.tsx
Normal file
12
web/src/router/index.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
import { createBrowserRouter } from 'react-router';
|
||||
import { routes } from './routes';
|
||||
|
||||
export const router = createBrowserRouter(routes, {
|
||||
future: {
|
||||
v7_startTransition: true,
|
||||
v7_relativeSplatPath: true,
|
||||
},
|
||||
});
|
||||
|
||||
export { routes };
|
||||
export * from './pages/NotFoundPage';
|
||||
10
web/src/router/pages/CentralPage.tsx
Normal file
10
web/src/router/pages/CentralPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { CentralComponent } from '../../components/CentralComponent';
|
||||
|
||||
export function CentralPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<CentralComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/CloudflarePage.tsx
Normal file
10
web/src/router/pages/CloudflarePage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { CloudflareComponent } from '../../components/CloudflareComponent';
|
||||
|
||||
export function CloudflarePage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<CloudflareComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/CrowdSecPage.tsx
Normal file
10
web/src/router/pages/CrowdSecPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { CrowdSecComponent } from '../../components/CrowdSecComponent';
|
||||
|
||||
export function CrowdSecPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<CrowdSecComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/DdnsPage.tsx
Normal file
10
web/src/router/pages/DdnsPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { DdnsComponent } from '../../components/DdnsComponent';
|
||||
|
||||
export function DdnsPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<DdnsComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/DhcpPage.tsx
Normal file
10
web/src/router/pages/DhcpPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { DhcpComponent } from '../../components/DhcpComponent';
|
||||
|
||||
export function DhcpPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<DhcpComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/DnsPage.tsx
Normal file
10
web/src/router/pages/DnsPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { DnsComponent } from '../../components/DnsComponent';
|
||||
|
||||
export function DnsPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<DnsComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/FirewallPage.tsx
Normal file
10
web/src/router/pages/FirewallPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { FirewallComponent } from '../../components/FirewallComponent';
|
||||
|
||||
export function FirewallPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<FirewallComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/IngressProxyPage.tsx
Normal file
10
web/src/router/pages/IngressProxyPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { IngressProxyComponent } from '../../components/IngressProxyComponent';
|
||||
|
||||
export function IngressProxyPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<IngressProxyComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/LanDnsPage.tsx
Normal file
10
web/src/router/pages/LanDnsPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components/ErrorBoundary';
|
||||
import { LanDnsComponent } from '../../components/LanDnsComponent';
|
||||
|
||||
export function LanDnsPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<LanDnsComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
30
web/src/router/pages/NotFoundPage.tsx
Normal file
30
web/src/router/pages/NotFoundPage.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import { Link } from 'react-router';
|
||||
import { AlertCircle, Home } from 'lucide-react';
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from '../../components/ui/card';
|
||||
import { Button } from '../../components/ui/button';
|
||||
|
||||
export function NotFoundPage() {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[600px]">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<AlertCircle className="h-16 w-16 text-destructive" />
|
||||
</div>
|
||||
<CardTitle className="text-2xl">Page Not Found</CardTitle>
|
||||
<CardDescription>
|
||||
The page you're looking for doesn't exist or has been moved.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex justify-center">
|
||||
<Link to="/">
|
||||
<Button>
|
||||
<Home className="mr-2 h-4 w-4" />
|
||||
Go to Home
|
||||
</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/VpnPage.tsx
Normal file
10
web/src/router/pages/VpnPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { VpnComponent } from '../../components/VpnComponent';
|
||||
|
||||
export function VpnPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<VpnComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
41
web/src/router/routes.tsx
Normal file
41
web/src/router/routes.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import { Navigate } from 'react-router';
|
||||
import type { RouteObject } from 'react-router';
|
||||
import { CentralLayout } from './CentralLayout';
|
||||
import { NotFoundPage } from './pages/NotFoundPage';
|
||||
import { CentralPage } from './pages/CentralPage';
|
||||
import { DhcpPage } from './pages/DhcpPage';
|
||||
import { FirewallPage } from './pages/FirewallPage';
|
||||
import { IngressProxyPage } from './pages/IngressProxyPage';
|
||||
import { DnsPage } from './pages/DnsPage';
|
||||
import { CrowdSecPage } from './pages/CrowdSecPage';
|
||||
import { VpnPage } from './pages/VpnPage';
|
||||
import { CloudflarePage } from './pages/CloudflarePage';
|
||||
import { DdnsPage } from './pages/DdnsPage';
|
||||
import { LanDnsPage } from './pages/LanDnsPage';
|
||||
|
||||
export const routes: RouteObject[] = [
|
||||
{
|
||||
path: '/',
|
||||
element: <Navigate to="/central" replace />,
|
||||
},
|
||||
{
|
||||
path: '/central',
|
||||
element: <CentralLayout />,
|
||||
children: [
|
||||
{ index: true, element: <CentralPage /> },
|
||||
{ path: 'cloudflare', element: <CloudflarePage /> },
|
||||
{ path: 'firewall', element: <FirewallPage /> },
|
||||
{ path: 'dhcp', element: <DhcpPage /> },
|
||||
{ path: 'crowdsec', element: <CrowdSecPage /> },
|
||||
{ path: 'ingress', element: <IngressProxyPage /> },
|
||||
{ path: 'dns', element: <DnsPage /> },
|
||||
{ path: 'ddns', element: <DdnsPage /> },
|
||||
{ path: 'lan-dns', element: <LanDnsPage /> },
|
||||
{ path: 'vpn', element: <VpnPage /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
path: '*',
|
||||
element: <NotFoundPage />,
|
||||
},
|
||||
];
|
||||
330
web/src/schemas/__tests__/config.test.ts
Normal file
330
web/src/schemas/__tests__/config.test.ts
Normal file
@@ -0,0 +1,330 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { configFormSchema, defaultConfigValues } from '../config';
|
||||
|
||||
describe('config schema validation', () => {
|
||||
describe('valid configurations', () => {
|
||||
it('should validate default configuration', () => {
|
||||
const result = configFormSchema.safeParse(defaultConfigValues);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should validate complete configuration', () => {
|
||||
const validConfig = {
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 5055,
|
||||
},
|
||||
cloud: {
|
||||
domain: 'wildcloud.local',
|
||||
internalDomain: 'cluster.local',
|
||||
dhcpRange: '192.168.8.100,192.168.8.200',
|
||||
dns: { ip: '192.168.8.50' },
|
||||
router: { ip: '192.168.8.1' },
|
||||
dnsmasq: { interface: 'eth0' },
|
||||
},
|
||||
cluster: {
|
||||
endpointIp: '192.168.8.60',
|
||||
nodes: { talos: { version: 'v1.8.0' } },
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(validConfig);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('server validation', () => {
|
||||
it('should reject empty host', () => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
server: { ...defaultConfigValues.server, host: '' },
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success) {
|
||||
expect(result.error.errors[0].path).toEqual(['server', 'host']);
|
||||
expect(result.error.errors[0].message).toBe('Host is required');
|
||||
}
|
||||
});
|
||||
|
||||
it('should reject invalid port ranges', () => {
|
||||
const invalidPorts = [0, -1, 65536, 99999];
|
||||
|
||||
invalidPorts.forEach(port => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
server: { ...defaultConfigValues.server, port },
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should accept valid port ranges', () => {
|
||||
const validPorts = [1, 80, 443, 5055, 65535];
|
||||
|
||||
validPorts.forEach(port => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
server: { ...defaultConfigValues.server, port },
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('IP address validation', () => {
|
||||
it('should reject invalid IP addresses', () => {
|
||||
const invalidIPs = [
|
||||
'256.1.1.1',
|
||||
'192.168.1',
|
||||
'192.168.1.256',
|
||||
'not-an-ip',
|
||||
'192.168.1.1.1',
|
||||
'',
|
||||
];
|
||||
|
||||
invalidIPs.forEach(ip => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
dns: { ip },
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should accept valid IP addresses', () => {
|
||||
const validIPs = [
|
||||
'192.168.1.1',
|
||||
'10.0.0.1',
|
||||
'172.16.0.1',
|
||||
'127.0.0.1',
|
||||
'0.0.0.0',
|
||||
'255.255.255.255',
|
||||
];
|
||||
|
||||
validIPs.forEach(ip => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
dns: { ip },
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('domain validation', () => {
|
||||
it('should reject invalid domains', () => {
|
||||
const invalidDomains = [
|
||||
'',
|
||||
'.com',
|
||||
'domain.',
|
||||
'domain..com',
|
||||
'domain-.com',
|
||||
'-domain.com',
|
||||
'domain.c',
|
||||
'very-long-domain-name-that-exceeds-the-maximum-allowed-length-for-a-domain-label.com',
|
||||
];
|
||||
|
||||
invalidDomains.forEach(domain => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
domain,
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success, `Domain "${domain}" should be invalid but passed validation`).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should accept valid domains', () => {
|
||||
const validDomains = [
|
||||
'wildcloud.local',
|
||||
'example.com',
|
||||
'sub.domain.com',
|
||||
'localhost',
|
||||
'test123.example.org',
|
||||
'my-domain.net',
|
||||
];
|
||||
|
||||
validDomains.forEach(domain => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
domain,
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('DHCP range validation', () => {
|
||||
it('should reject invalid DHCP ranges', () => {
|
||||
const invalidRanges = [
|
||||
'',
|
||||
'192.168.1.1',
|
||||
'192.168.1.1,',
|
||||
',192.168.1.200',
|
||||
'192.168.1.1-192.168.1.200',
|
||||
'192.168.1.1,192.168.1.256',
|
||||
'start,end',
|
||||
];
|
||||
|
||||
invalidRanges.forEach(dhcpRange => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
dhcpRange,
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should accept valid DHCP ranges', () => {
|
||||
const validRanges = [
|
||||
'192.168.1.100,192.168.1.200',
|
||||
'10.0.0.10,10.0.0.100',
|
||||
'172.16.1.1,172.16.1.254',
|
||||
];
|
||||
|
||||
validRanges.forEach(dhcpRange => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
dhcpRange,
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('version validation', () => {
|
||||
it('should reject invalid versions', () => {
|
||||
const invalidVersions = [
|
||||
'',
|
||||
'1.8.0',
|
||||
'v1.8',
|
||||
'v1.8.0.1',
|
||||
'version1.8.0',
|
||||
'v1.8.0-beta',
|
||||
];
|
||||
|
||||
invalidVersions.forEach(version => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cluster: {
|
||||
...defaultConfigValues.cluster,
|
||||
nodes: {
|
||||
talos: { version },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should accept valid versions', () => {
|
||||
const validVersions = [
|
||||
'v1.8.0',
|
||||
'v1.0.0',
|
||||
'v10.20.30',
|
||||
'v0.0.1',
|
||||
];
|
||||
|
||||
validVersions.forEach(version => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cluster: {
|
||||
...defaultConfigValues.cluster,
|
||||
nodes: {
|
||||
talos: { version },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('network interface validation', () => {
|
||||
it('should reject invalid interfaces', () => {
|
||||
const invalidInterfaces = [
|
||||
'',
|
||||
'eth-0',
|
||||
'eth.0',
|
||||
'eth 0',
|
||||
'eth/0',
|
||||
];
|
||||
|
||||
invalidInterfaces.forEach(interfaceName => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
dnsmasq: { interface: interfaceName },
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should accept valid interfaces', () => {
|
||||
const validInterfaces = [
|
||||
'eth0',
|
||||
'eth1',
|
||||
'enp0s3',
|
||||
'wlan0',
|
||||
'lo',
|
||||
'br0',
|
||||
];
|
||||
|
||||
validInterfaces.forEach(interfaceName => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
dnsmasq: { interface: interfaceName },
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
187
web/src/schemas/config.ts
Normal file
187
web/src/schemas/config.ts
Normal file
@@ -0,0 +1,187 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
// Network validation helpers
|
||||
const ipAddressSchema = z.string().regex(
|
||||
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
|
||||
'Must be a valid IP address'
|
||||
);
|
||||
|
||||
const domainSchema = z.string().regex(
|
||||
/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9]))*$/,
|
||||
'Must be a valid domain name'
|
||||
);
|
||||
|
||||
const dhcpRangeSchema = z.string().regex(
|
||||
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?),(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
|
||||
'Must be in format: start_ip,end_ip (e.g., 192.168.1.100,192.168.1.200)'
|
||||
);
|
||||
|
||||
const interfaceSchema = z.string().regex(
|
||||
/^[a-zA-Z0-9]+$/,
|
||||
'Must be a valid network interface name (e.g., eth0, enp0s3)'
|
||||
);
|
||||
|
||||
const versionSchema = z.string().regex(
|
||||
/^v\d+\.\d+\.\d+$/,
|
||||
'Must be a valid version format (e.g., v1.8.0)'
|
||||
);
|
||||
|
||||
// Server configuration schema
|
||||
const serverConfigSchema = z.object({
|
||||
host: z.string().min(1, 'Host is required').default('0.0.0.0'),
|
||||
port: z.number()
|
||||
.int('Port must be an integer')
|
||||
.min(1, 'Port must be at least 1')
|
||||
.max(65535, 'Port must be at most 65535')
|
||||
.default(5055),
|
||||
});
|
||||
|
||||
// Cloud DNS configuration schema
|
||||
const cloudDnsSchema = z.object({
|
||||
ip: ipAddressSchema,
|
||||
});
|
||||
|
||||
// Cloud router configuration schema
|
||||
const cloudRouterSchema = z.object({
|
||||
ip: ipAddressSchema,
|
||||
});
|
||||
|
||||
// Cloud dnsmasq configuration schema
|
||||
const cloudDnsmasqSchema = z.object({
|
||||
interface: interfaceSchema,
|
||||
});
|
||||
|
||||
// Cloud configuration schema
|
||||
const cloudConfigSchema = z.object({
|
||||
domain: domainSchema,
|
||||
internalDomain: domainSchema,
|
||||
dhcpRange: dhcpRangeSchema,
|
||||
dns: cloudDnsSchema,
|
||||
router: cloudRouterSchema,
|
||||
dnsmasq: cloudDnsmasqSchema,
|
||||
});
|
||||
|
||||
// Talos configuration schema
|
||||
const talosConfigSchema = z.object({
|
||||
version: versionSchema,
|
||||
});
|
||||
|
||||
// Nodes configuration schema
|
||||
const nodesConfigSchema = z.object({
|
||||
talos: talosConfigSchema,
|
||||
});
|
||||
|
||||
// Cluster configuration schema
|
||||
const clusterConfigSchema = z.object({
|
||||
endpointIp: ipAddressSchema,
|
||||
hostnamePrefix: z.string().optional(),
|
||||
nodes: nodesConfigSchema,
|
||||
});
|
||||
|
||||
// Wildcloud configuration schema (optional)
|
||||
const wildcloudConfigSchema = z.object({
|
||||
repository: z.string().min(1, 'Repository is required'),
|
||||
currentPhase: z.enum(['setup', 'infrastructure', 'cluster', 'apps']).optional(),
|
||||
completedPhases: z.array(z.enum(['setup', 'infrastructure', 'cluster', 'apps'])).optional(),
|
||||
}).optional();
|
||||
|
||||
// Main configuration schema
|
||||
export const configSchema = z.object({
|
||||
server: serverConfigSchema,
|
||||
cloud: cloudConfigSchema,
|
||||
cluster: clusterConfigSchema,
|
||||
wildcloud: wildcloudConfigSchema,
|
||||
});
|
||||
|
||||
// Form schema for creating new configurations (some fields can be optional for partial updates)
|
||||
export const configFormSchema = z.object({
|
||||
server: z.object({
|
||||
host: z.string().min(1, 'Host is required'),
|
||||
port: z.coerce.number()
|
||||
.int('Port must be an integer')
|
||||
.min(1, 'Port must be at least 1')
|
||||
.max(65535, 'Port must be at most 65535'),
|
||||
}),
|
||||
cloud: z.object({
|
||||
domain: z.string().min(1, 'Domain is required').refine(
|
||||
(val) => domainSchema.safeParse(val).success,
|
||||
'Must be a valid domain name'
|
||||
),
|
||||
internalDomain: z.string().min(1, 'Internal domain is required').refine(
|
||||
(val) => domainSchema.safeParse(val).success,
|
||||
'Must be a valid domain name'
|
||||
),
|
||||
dhcpRange: z.string().min(1, 'DHCP range is required').refine(
|
||||
(val) => dhcpRangeSchema.safeParse(val).success,
|
||||
'Must be in format: start_ip,end_ip'
|
||||
),
|
||||
dns: z.object({
|
||||
ip: z.string().min(1, 'DNS IP is required').refine(
|
||||
(val) => ipAddressSchema.safeParse(val).success,
|
||||
'Must be a valid IP address'
|
||||
),
|
||||
}),
|
||||
router: z.object({
|
||||
ip: z.string().min(1, 'Router IP is required').refine(
|
||||
(val) => ipAddressSchema.safeParse(val).success,
|
||||
'Must be a valid IP address'
|
||||
),
|
||||
}),
|
||||
dnsmasq: z.object({
|
||||
interface: z.string().min(1, 'Interface is required').refine(
|
||||
(val) => interfaceSchema.safeParse(val).success,
|
||||
'Must be a valid network interface name'
|
||||
),
|
||||
}),
|
||||
}),
|
||||
cluster: z.object({
|
||||
endpointIp: z.string().min(1, 'Endpoint IP is required').refine(
|
||||
(val) => ipAddressSchema.safeParse(val).success,
|
||||
'Must be a valid IP address'
|
||||
),
|
||||
hostnamePrefix: z.string().optional(),
|
||||
nodes: z.object({
|
||||
talos: z.object({
|
||||
version: z.string().min(1, 'Talos version is required').refine(
|
||||
(val) => versionSchema.safeParse(val).success,
|
||||
'Must be a valid version format (e.g., v1.8.0)'
|
||||
),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
// Type exports
|
||||
export type Config = z.infer<typeof configSchema>;
|
||||
export type ConfigFormData = z.infer<typeof configFormSchema>;
|
||||
|
||||
// Default values for the form
|
||||
export const defaultConfigValues: ConfigFormData = {
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 5055,
|
||||
},
|
||||
cloud: {
|
||||
domain: 'wildcloud.local',
|
||||
internalDomain: 'cluster.local',
|
||||
dhcpRange: '192.168.8.100,192.168.8.200',
|
||||
dns: {
|
||||
ip: '192.168.8.50',
|
||||
},
|
||||
router: {
|
||||
ip: '192.168.8.1',
|
||||
},
|
||||
dnsmasq: {
|
||||
interface: 'eth0',
|
||||
},
|
||||
},
|
||||
cluster: {
|
||||
endpointIp: '192.168.8.60',
|
||||
hostnamePrefix: '',
|
||||
nodes: {
|
||||
talos: {
|
||||
version: 'v1.8.0',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user