mirror of
https://github.com/coollabsio/coolify.git
synced 2026-08-24 02:24:11 -05:00
Merge remote-tracking branch 'origin/next' into reverb-realtime-migration
This commit is contained in:
@@ -0,0 +1,267 @@
|
||||
---
|
||||
name: shadcn
|
||||
description: Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI. Provides project context, component docs, and usage examples. Applies when working with shadcn/ui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for "shadcn init", "create an app with --preset", or "switch to --preset".
|
||||
user-invocable: false
|
||||
allowed-tools: Bash(npx shadcn@latest *), Bash(pnpm dlx shadcn@latest *), Bash(bunx --bun shadcn@latest *)
|
||||
---
|
||||
|
||||
# shadcn/ui
|
||||
|
||||
A framework for building ui, components and design systems. Components are added as source code to the user's project via the CLI.
|
||||
|
||||
> **IMPORTANT:** Run all CLI commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest` — based on the project's `packageManager`. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
|
||||
|
||||
## Current Project Context
|
||||
|
||||
```json
|
||||
!`npx shadcn@latest info --json`
|
||||
```
|
||||
|
||||
The JSON above contains the project config and installed components. Use `npx shadcn@latest docs <component>` to get documentation and example URLs for any component.
|
||||
|
||||
## Principles
|
||||
|
||||
1. **Use existing components first.** Use `npx shadcn@latest search` to check registries before writing custom UI. Check community registries too.
|
||||
2. **Compose, don't reinvent.** Settings page = Tabs + Card + form controls. Dashboard = Sidebar + Card + Chart + Table.
|
||||
3. **Use built-in variants before custom styles.** `variant="outline"`, `size="sm"`, etc.
|
||||
4. **Use semantic colors.** `bg-primary`, `text-muted-foreground` — never raw values like `bg-blue-500`.
|
||||
|
||||
## Critical Rules
|
||||
|
||||
These rules are **always enforced**. Each links to a file with Incorrect/Correct code pairs.
|
||||
|
||||
### Styling & Tailwind → [styling.md](./rules/styling.md)
|
||||
|
||||
- **`className` for layout, not styling.** Never override component colors or typography.
|
||||
- **No `space-x-*` or `space-y-*`.** Use `flex` with `gap-*`. For vertical stacks, `flex flex-col gap-*`.
|
||||
- **Use `size-*` when width and height are equal.** `size-10` not `w-10 h-10`.
|
||||
- **Use `truncate` shorthand.** Not `overflow-hidden text-ellipsis whitespace-nowrap`.
|
||||
- **No manual `dark:` color overrides.** Use semantic tokens (`bg-background`, `text-muted-foreground`).
|
||||
- **Use `cn()` for conditional classes.** Don't write manual template literal ternaries.
|
||||
- **No manual `z-index` on overlay components.** Dialog, Sheet, Popover, etc. handle their own stacking.
|
||||
|
||||
### Forms & Inputs → [forms.md](./rules/forms.md)
|
||||
|
||||
- **Forms use `FieldGroup` + `Field`.** Never use raw `div` with `space-y-*` or `grid gap-*` for form layout.
|
||||
- **`InputGroup` uses `InputGroupInput`/`InputGroupTextarea`.** Never raw `Input`/`Textarea` inside `InputGroup`.
|
||||
- **Buttons inside inputs use `InputGroup` + `InputGroupAddon`.**
|
||||
- **Option sets (2–7 choices) use `ToggleGroup`.** Don't loop `Button` with manual active state.
|
||||
- **`FieldSet` + `FieldLegend` for grouping related checkboxes/radios.** Don't use a `div` with a heading.
|
||||
- **Field validation uses `data-invalid` + `aria-invalid`.** `data-invalid` on `Field`, `aria-invalid` on the control. For disabled: `data-disabled` on `Field`, `disabled` on the control.
|
||||
|
||||
### Component Structure → [composition.md](./rules/composition.md)
|
||||
|
||||
- **Items always inside their Group.** `SelectItem` → `SelectGroup`. `DropdownMenuItem` → `DropdownMenuGroup`. `CommandItem` → `CommandGroup`.
|
||||
- **Use `asChild` (radix) or `render` (base) for custom triggers.** Check `base` field from `npx shadcn@latest info`. → [base-vs-radix.md](./rules/base-vs-radix.md)
|
||||
- **Dialog, Sheet, and Drawer always need a Title.** `DialogTitle`, `SheetTitle`, `DrawerTitle` required for accessibility. Use `className="sr-only"` if visually hidden.
|
||||
- **Use full Card composition.** `CardHeader`/`CardTitle`/`CardDescription`/`CardContent`/`CardFooter`. Don't dump everything in `CardContent`.
|
||||
- **Button has no `isPending`/`isLoading`.** Compose with `Spinner` + `data-icon` + `disabled`.
|
||||
- **`TabsTrigger` must be inside `TabsList`.** Never render triggers directly in `Tabs`.
|
||||
- **`Avatar` always needs `AvatarFallback`.** For when the image fails to load.
|
||||
|
||||
### Use Components, Not Custom Markup → [composition.md](./rules/composition.md)
|
||||
|
||||
- **Use existing components before custom markup.** Check if a component exists before writing a styled `div`.
|
||||
- **Callouts use `Alert`.** Don't build custom styled divs.
|
||||
- **Empty states use `Empty`.** Don't build custom empty state markup.
|
||||
- **Toast via `sonner`.** Use `toast()` from `sonner`.
|
||||
- **Use `Separator`** instead of `<hr>` or `<div className="border-t">`.
|
||||
- **Use `Skeleton`** for loading placeholders. No custom `animate-pulse` divs.
|
||||
- **Use `Badge`** instead of custom styled spans.
|
||||
|
||||
### Icons → [icons.md](./rules/icons.md)
|
||||
|
||||
- **Icons in `Button` use `data-icon`.** `data-icon="inline-start"` or `data-icon="inline-end"` on the icon.
|
||||
- **No sizing classes on icons inside components.** Components handle icon sizing via CSS. No `size-4` or `w-4 h-4`.
|
||||
- **Pass icons as objects, not string keys.** `icon={CheckIcon}`, not a string lookup.
|
||||
|
||||
### CLI
|
||||
|
||||
- **Never decode preset codes or build preset URLs manually.** Use `npx shadcn@latest preset decode <code>`, `preset url <code>`, or `preset open <code>`. For project-aware preset detection, use `npx shadcn@latest preset resolve`.
|
||||
- **Apply preset codes directly with the CLI.** Use `npx shadcn@latest apply <code>` for existing projects, or `npx shadcn@latest init --preset <code>` when initializing.
|
||||
|
||||
## Key Patterns
|
||||
|
||||
These are the most common patterns that differentiate correct shadcn/ui code. For edge cases, see the linked rule files above.
|
||||
|
||||
```tsx
|
||||
// Form layout: FieldGroup + Field, not div + Label.
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||
<Input id="email" />
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
|
||||
// Validation: data-invalid on Field, aria-invalid on the control.
|
||||
<Field data-invalid>
|
||||
<FieldLabel>Email</FieldLabel>
|
||||
<Input aria-invalid />
|
||||
<FieldDescription>Invalid email.</FieldDescription>
|
||||
</Field>
|
||||
|
||||
// Icons in buttons: data-icon, no sizing classes.
|
||||
<Button>
|
||||
<SearchIcon data-icon="inline-start" />
|
||||
Search
|
||||
</Button>
|
||||
|
||||
// Spacing: gap-*, not space-y-*.
|
||||
<div className="flex flex-col gap-4"> // correct
|
||||
<div className="space-y-4"> // wrong
|
||||
|
||||
// Equal dimensions: size-*, not w-* h-*.
|
||||
<Avatar className="size-10"> // correct
|
||||
<Avatar className="w-10 h-10"> // wrong
|
||||
|
||||
// Status colors: Badge variants or semantic tokens, not raw colors.
|
||||
<Badge variant="secondary">+20.1%</Badge> // correct
|
||||
<span className="text-emerald-600">+20.1%</span> // wrong
|
||||
```
|
||||
|
||||
## Component Selection
|
||||
|
||||
| Need | Use |
|
||||
| -------------------------- | --------------------------------------------------------------------------------------------------- |
|
||||
| Button/action | `Button` with appropriate variant |
|
||||
| Form inputs | `Input`, `Select`, `Combobox`, `Switch`, `Checkbox`, `RadioGroup`, `Textarea`, `InputOTP`, `Slider` |
|
||||
| Toggle between 2–5 options | `ToggleGroup` + `ToggleGroupItem` |
|
||||
| Data display | `Table`, `Card`, `Badge`, `Avatar` |
|
||||
| Navigation | `Sidebar`, `NavigationMenu`, `Breadcrumb`, `Tabs`, `Pagination` |
|
||||
| Overlays | `Dialog` (modal), `Sheet` (side panel), `Drawer` (bottom sheet), `AlertDialog` (confirmation) |
|
||||
| Feedback | `sonner` (toast), `Alert`, `Progress`, `Skeleton`, `Spinner` |
|
||||
| Command palette | `Command` inside `Dialog` |
|
||||
| Charts | `Chart` (wraps Recharts) |
|
||||
| Layout | `Card`, `Separator`, `Resizable`, `ScrollArea`, `Accordion`, `Collapsible` |
|
||||
| Empty states | `Empty` |
|
||||
| Menus | `DropdownMenu`, `ContextMenu`, `Menubar` |
|
||||
| Tooltips/info | `Tooltip`, `HoverCard`, `Popover` |
|
||||
|
||||
## Key Fields
|
||||
|
||||
The injected project context contains these key fields:
|
||||
|
||||
- **`aliases`** → use the actual alias prefix for imports (e.g. `@/`, `~/`), never hardcode.
|
||||
- **`isRSC`** → when `true`, components using `useState`, `useEffect`, event handlers, or browser APIs need `"use client"` at the top of the file. Always reference this field when advising on the directive.
|
||||
- **`tailwindVersion`** → `"v4"` uses `@theme inline` blocks; `"v3"` uses `tailwind.config.js`.
|
||||
- **`tailwindCssFile`** → the global CSS file where custom CSS variables are defined. Always edit this file, never create a new one.
|
||||
- **`style`** → component visual treatment (e.g. `nova`, `vega`).
|
||||
- **`base`** → primitive library (`radix` or `base`). Affects component APIs and available props.
|
||||
- **`iconLibrary`** → determines icon imports. Use `lucide-react` for `lucide`, `@tabler/icons-react` for `tabler`, etc. Never assume `lucide-react`.
|
||||
- **`resolvedPaths`** → exact file-system destinations for components, utils, hooks, etc.
|
||||
- **`framework`** → routing and file conventions (e.g. Next.js App Router vs Vite SPA).
|
||||
- **`packageManager`** → use this for any non-shadcn dependency installs (e.g. `pnpm add date-fns` vs `npm install date-fns`).
|
||||
- **`preset`** → resolved preset code and values for the current project. Use `npx shadcn@latest preset resolve --json` when you only need preset information.
|
||||
|
||||
See [cli.md — `info` command](./cli.md) for the full field reference.
|
||||
|
||||
## Component Docs, Examples, and Usage
|
||||
|
||||
Run `npx shadcn@latest docs <component>` to get the URLs for a component's documentation, examples, and API reference. Fetch these URLs to get the actual content.
|
||||
|
||||
```bash
|
||||
npx shadcn@latest docs button dialog select
|
||||
```
|
||||
|
||||
**When creating, fixing, debugging, or using a component, always run `npx shadcn@latest docs` and fetch the URLs first.** This ensures you're working with the correct API and usage patterns rather than guessing.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. **Get project context** — already injected above. Run `npx shadcn@latest info` again if you need to refresh.
|
||||
2. **Check installed components first** — before running `add`, always check the `components` list from project context or list the `resolvedPaths.ui` directory. Don't import components that haven't been added, and don't re-add ones already installed.
|
||||
3. **Find components** — `npx shadcn@latest search`.
|
||||
4. **Get docs and examples** — run `npx shadcn@latest docs <component>` to get URLs, then fetch them. Use `npx shadcn@latest view` to browse registry items you haven't installed. To preview changes to installed components, use `npx shadcn@latest add --diff`.
|
||||
5. **Install or update** — `npx shadcn@latest add`. When updating existing components, use `--dry-run` and `--diff` to preview changes first (see [Updating Components](#updating-components) below).
|
||||
6. **Fix imports in third-party components** — After adding components from community registries (e.g. `@bundui`, `@magicui`), check the added non-UI files for hardcoded import paths like `@/components/ui/...`. These won't match the project's actual aliases. Use `npx shadcn@latest info` to get the correct `ui` alias (e.g. `@workspace/ui/components`) and rewrite the imports accordingly. The CLI rewrites imports for its own UI files, but third-party registry components may use default paths that don't match the project.
|
||||
7. **Review added components** — After adding a component or block from any registry, **always read the added files and verify they are correct**. Check for missing sub-components (e.g. `SelectItem` without `SelectGroup`), missing imports, incorrect composition, or violations of the [Critical Rules](#critical-rules). Also replace any icon imports with the project's `iconLibrary` from the project context (e.g. if the registry item uses `lucide-react` but the project uses `hugeicons`, swap the imports and icon names accordingly). Fix all issues before moving on.
|
||||
8. **Registry must be explicit** — When the user asks to add a block or component, **do not guess the registry**. If no registry is specified (e.g. user says "add a login block" without specifying `@shadcn`, `@tailark`, `owner/repo`, etc.), ask which registry to use. Never default to a registry on behalf of the user.
|
||||
9. **Switching presets** — Ask the user first: **overwrite**, **partial**, **merge**, or **skip**?
|
||||
- **Inspect current preset**: `npx shadcn@latest preset resolve`. Use `--json` when you need structured values.
|
||||
- **Inspect incoming preset**: `npx shadcn@latest preset decode <code>`. Use `preset url <code>` or `preset open <code>` to share or open the preset builder.
|
||||
- **Overwrite**: `npx shadcn@latest apply <code>`. Overwrites detected components, fonts, and CSS variables.
|
||||
- **Partial**: `npx shadcn@latest apply <code> --only theme,font`. Updates only the selected preset parts without reinstalling UI components. Supported values are `theme` and `font`; comma-separated combinations are allowed. `icon` is intentionally not supported, because icon changes may require full component reinstall and transforms.
|
||||
- **Merge**: `npx shadcn@latest init --preset <code> --force --no-reinstall`, then run `npx shadcn@latest info` to list installed components, then for each installed component use `--dry-run` and `--diff` to [smart merge](#updating-components) it individually.
|
||||
- **Skip**: `npx shadcn@latest init --preset <code> --force --no-reinstall`. Only updates config and CSS, leaves components as-is.
|
||||
- **Important**: Always run preset commands inside the user's project directory. `apply` only works in an existing project with a `components.json` file. The CLI automatically preserves the current base (`base` vs `radix`) from `components.json`. If you must use a scratch/temp directory (e.g. for `--dry-run` comparisons), pass `--base <current-base>` explicitly — preset codes do not encode the base.
|
||||
|
||||
## Updating Components
|
||||
|
||||
When the user asks to update a component from upstream while keeping their local changes, use `--dry-run` and `--diff` to intelligently merge. **NEVER fetch raw files from GitHub manually — always use the CLI.**
|
||||
|
||||
1. Run `npx shadcn@latest add <component> --dry-run` to see all files that would be affected.
|
||||
2. For each file, run `npx shadcn@latest add <component> --diff <file>` to see what changed upstream vs local.
|
||||
3. Decide per file based on the diff:
|
||||
- No local changes → safe to overwrite.
|
||||
- Has local changes → read the local file, analyze the diff, and apply upstream updates while preserving local modifications.
|
||||
- User says "just update everything" → use `--overwrite`, but confirm first.
|
||||
4. **Never use `--overwrite` without the user's explicit approval.**
|
||||
|
||||
## Quick Reference
|
||||
|
||||
```bash
|
||||
# Create a new project.
|
||||
npx shadcn@latest init --name my-app --preset base-nova
|
||||
npx shadcn@latest init --name my-app --preset a2r6bw --template vite
|
||||
|
||||
# Create a monorepo project.
|
||||
npx shadcn@latest init --name my-app --preset base-nova --monorepo
|
||||
npx shadcn@latest init --name my-app --preset base-nova --template next --monorepo
|
||||
|
||||
# Initialize existing project.
|
||||
npx shadcn@latest init --preset base-nova
|
||||
npx shadcn@latest init --defaults # shortcut: --template=next --preset=nova (base style implied)
|
||||
|
||||
# Apply a preset to an existing project.
|
||||
npx shadcn@latest apply a2r6bw
|
||||
npx shadcn@latest apply a2r6bw --only theme
|
||||
npx shadcn@latest apply a2r6bw --only font
|
||||
npx shadcn@latest apply a2r6bw --only theme,font
|
||||
|
||||
# Inspect preset codes and project preset state.
|
||||
npx shadcn@latest preset decode a2r6bw
|
||||
npx shadcn@latest preset url a2r6bw
|
||||
npx shadcn@latest preset open a2r6bw
|
||||
npx shadcn@latest preset resolve
|
||||
npx shadcn@latest preset resolve --json
|
||||
|
||||
# Add components.
|
||||
npx shadcn@latest add button card dialog
|
||||
npx shadcn@latest add @magicui/shimmer-button
|
||||
npx shadcn@latest add owner/repo/item
|
||||
npx shadcn@latest add --all
|
||||
|
||||
# Preview changes before adding/updating.
|
||||
npx shadcn@latest add button --dry-run
|
||||
npx shadcn@latest add button --diff button.tsx
|
||||
npx shadcn@latest add @acme/form --view button.tsx
|
||||
npx shadcn@latest add owner/repo/item --dry-run
|
||||
|
||||
# Search registries.
|
||||
npx shadcn@latest search @shadcn -q "sidebar"
|
||||
npx shadcn@latest search @tailark -q "stats"
|
||||
npx shadcn@latest search owner/repo -q "login"
|
||||
npx shadcn@latest search # all configured registries
|
||||
npx shadcn@latest search @shadcn -q "menu" -t ui # filter by item type
|
||||
|
||||
# Get component docs and example URLs.
|
||||
npx shadcn@latest docs button dialog select
|
||||
|
||||
# View registry item details (for items not yet installed).
|
||||
npx shadcn@latest view @shadcn/button
|
||||
npx shadcn@latest view owner/repo/item
|
||||
```
|
||||
|
||||
**Named presets:** `nova`, `vega`, `maia`, `lyra`, `mira`, `luma`
|
||||
**Templates:** `next`, `vite`, `start`, `react-router`, `astro` (all support `--monorepo`) and `laravel` (not supported for monorepo)
|
||||
**Preset codes:** Version-prefixed base62 strings (e.g. `a2r6bw` or `b0`), from [ui.shadcn.com](https://ui.shadcn.com).
|
||||
|
||||
## Detailed References
|
||||
|
||||
- [rules/forms.md](./rules/forms.md) — FieldGroup, Field, InputGroup, ToggleGroup, FieldSet, validation states
|
||||
- [rules/composition.md](./rules/composition.md) — Groups, overlays, Card, Tabs, Avatar, Alert, Empty, Toast, Separator, Skeleton, Badge, Button loading
|
||||
- [rules/icons.md](./rules/icons.md) — data-icon, icon sizing, passing icons as objects
|
||||
- [rules/styling.md](./rules/styling.md) — Semantic colors, variants, className, spacing, size, truncate, dark mode, cn(), z-index
|
||||
- [rules/base-vs-radix.md](./rules/base-vs-radix.md) — asChild vs render, Select, ToggleGroup, Slider, Accordion
|
||||
- [cli.md](./cli.md) — Commands, flags, presets, templates
|
||||
- [registry.md](./registry.md) — Authoring source registries, `include`, item definitions, dependencies, GitHub registry rules
|
||||
- [customization.md](./customization.md) — Theming, CSS variables, extending components
|
||||
@@ -0,0 +1,5 @@
|
||||
interface:
|
||||
display_name: "shadcn/ui"
|
||||
short_description: "Manages shadcn/ui components — adding, searching, fixing, debugging, styling, and composing UI."
|
||||
icon_small: "./assets/shadcn-small.png"
|
||||
icon_large: "./assets/shadcn.png"
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
@@ -0,0 +1,290 @@
|
||||
# shadcn CLI Reference
|
||||
|
||||
Configuration is read from `components.json`.
|
||||
|
||||
> **IMPORTANT:** Always run commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest`. Check `packageManager` from project context to choose the right one. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
|
||||
|
||||
> **IMPORTANT:** Only use the flags documented below. Do not invent or guess flags — if a flag isn't listed here, it doesn't exist. The CLI auto-detects the package manager from the project's lockfile; there is no `--package-manager` flag.
|
||||
|
||||
## Contents
|
||||
|
||||
- Commands: init, apply, add (dry-run, smart merge), search, view, docs, info, build
|
||||
- Templates: next, vite, start, react-router, astro
|
||||
- Presets: named, code, URL formats and fields
|
||||
- Switching presets
|
||||
|
||||
---
|
||||
|
||||
## Commands
|
||||
|
||||
### `init` — Initialize or create a project
|
||||
|
||||
```bash
|
||||
npx shadcn@latest init [components...] [options]
|
||||
```
|
||||
|
||||
Initializes shadcn/ui in an existing project or creates a new project (when `--name` is provided). Optionally installs components in the same step.
|
||||
|
||||
| Flag | Short | Description | Default |
|
||||
| ----------------------- | ----- | --------------------------------------------------------- | ------- |
|
||||
| `--template <template>` | `-t` | Template (next, start, vite, next-monorepo, react-router) | — |
|
||||
| `--preset [name]` | `-p` | Preset configuration (named, code, or URL) | — |
|
||||
| `--yes` | `-y` | Skip confirmation prompt | `true` |
|
||||
| `--defaults` | `-d` | Use defaults (`--template=next --preset=base-nova`) | `false` |
|
||||
| `--force` | `-f` | Force overwrite existing configuration | `false` |
|
||||
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||
| `--name <name>` | `-n` | Name for new project | — |
|
||||
| `--silent` | `-s` | Mute output | `false` |
|
||||
| `--rtl` | | Enable RTL support | — |
|
||||
| `--reinstall` | | Re-install existing UI components | `false` |
|
||||
| `--monorepo` | | Scaffold a monorepo project | — |
|
||||
| `--no-monorepo` | | Skip the monorepo prompt | — |
|
||||
|
||||
`npx shadcn@latest create` is an alias for `npx shadcn@latest init`.
|
||||
|
||||
### `apply` — Apply a preset to an existing project
|
||||
|
||||
```bash
|
||||
npx shadcn@latest apply [preset] [options]
|
||||
```
|
||||
|
||||
Applies a preset to an existing project, overwriting preset-driven config, fonts, CSS variables, and detected UI components.
|
||||
|
||||
| Flag | Short | Description | Default |
|
||||
| ------------------- | ----- | ------------------------------------------ | ------- |
|
||||
| `--preset <preset>` | — | Preset configuration (named, code, or URL) | — |
|
||||
| `--yes` | `-y` | Skip confirmation prompt | `false` |
|
||||
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||
| `--silent` | `-s` | Mute output | `false` |
|
||||
|
||||
`[preset]` is a shorthand for `--preset <preset>`. If both are provided, they must match.
|
||||
If no preset is provided, the CLI offers to open the custom preset builder on `ui.shadcn.com/create`.
|
||||
|
||||
### `add` — Add components
|
||||
|
||||
> **IMPORTANT:** To compare local components against upstream or to preview changes, ALWAYS use `npx shadcn@latest add <component> --dry-run`, `--diff`, or `--view`. NEVER fetch raw files from GitHub or other sources manually. The CLI handles registry resolution, file paths, and CSS diffing automatically.
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add [components...] [options]
|
||||
```
|
||||
|
||||
Accepts component names, registry-prefixed names (`@magicui/shimmer-button`),
|
||||
GitHub item addresses (`owner/repo/item`), URLs, or local paths.
|
||||
|
||||
| Flag | Short | Description | Default |
|
||||
| --------------- | ----- | -------------------------------------------------------------------------------------------------------------------- | ------- |
|
||||
| `--yes` | `-y` | Skip confirmation prompt | `false` |
|
||||
| `--overwrite` | `-o` | Overwrite existing files | `false` |
|
||||
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||
| `--all` | `-a` | Add all available components | `false` |
|
||||
| `--path <path>` | `-p` | Target path for the component | — |
|
||||
| `--silent` | `-s` | Mute output | `false` |
|
||||
| `--dry-run` | | Preview all changes without writing files | `false` |
|
||||
| `--diff [path]` | | Show diffs. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — |
|
||||
| `--view [path]` | | Show file contents. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — |
|
||||
|
||||
#### Dry-Run Mode
|
||||
|
||||
Use `--dry-run` to preview what `add` would do without writing any files. `--diff` and `--view` both imply `--dry-run`.
|
||||
|
||||
```bash
|
||||
# Preview all changes.
|
||||
npx shadcn@latest add button --dry-run
|
||||
|
||||
# Show diffs for all files (top 5).
|
||||
npx shadcn@latest add button --diff
|
||||
|
||||
# Show the diff for a specific file.
|
||||
npx shadcn@latest add button --diff button.tsx
|
||||
|
||||
# Show contents for all files (top 5).
|
||||
npx shadcn@latest add button --view
|
||||
|
||||
# Show the full content of a specific file.
|
||||
npx shadcn@latest add button --view button.tsx
|
||||
|
||||
# Works with URLs too.
|
||||
npx shadcn@latest add https://api.npoint.io/abc123 --dry-run
|
||||
|
||||
# Works with public GitHub registries too.
|
||||
npx shadcn@latest add owner/repo/item --dry-run
|
||||
|
||||
# CSS diffs.
|
||||
npx shadcn@latest add button --diff globals.css
|
||||
```
|
||||
|
||||
**When to use dry-run:**
|
||||
|
||||
- When the user asks "what files will this add?" or "what will this change?" — use `--dry-run`.
|
||||
- Before overwriting existing components — use `--diff` to preview the changes first.
|
||||
- When the user wants to inspect component source code without installing — use `--view`.
|
||||
- When checking what CSS changes would be made to `globals.css` — use `--diff globals.css`.
|
||||
- When the user asks to review or audit third-party registry code before installing — use `--view` to inspect the source.
|
||||
|
||||
> **`npx shadcn@latest add --dry-run` vs `npx shadcn@latest view`:** Prefer `npx shadcn@latest add --dry-run/--diff/--view` over `npx shadcn@latest view` when the user wants to preview changes to their project. `npx shadcn@latest view` only shows raw registry metadata. `npx shadcn@latest add --dry-run` shows exactly what would happen in the user's project: resolved file paths, diffs against existing files, and CSS updates. Use `npx shadcn@latest view` only when the user wants to browse registry info without a project context.
|
||||
|
||||
#### Smart Merge from Upstream
|
||||
|
||||
See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full workflow.
|
||||
|
||||
### `search` — Search registries
|
||||
|
||||
```bash
|
||||
npx shadcn@latest search [registries...] [options]
|
||||
```
|
||||
|
||||
Fuzzy search across registries. Also aliased as `npx shadcn@latest list`.
|
||||
Supports namespaces (`@acme`), public GitHub registry sources (`owner/repo`),
|
||||
and registry catalog URLs. Without `-q`, lists all items. When no registries are
|
||||
passed, searches every registry configured in `components.json`.
|
||||
|
||||
| Flag | Short | Description | Default |
|
||||
| ------------------- | ----- | ------------------------------------------------- | ------- |
|
||||
| `--query <query>` | `-q` | Search query | — |
|
||||
| `--type <type>` | `-t` | Filter by item type (e.g. `ui`, `block`, `hook`); comma-separated | — |
|
||||
| `--limit <number>` | `-l` | Max items to display | `100` |
|
||||
| `--offset <number>` | `-o` | Items to skip | `0` |
|
||||
| `--json` | | Output as JSON | `false` |
|
||||
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||
|
||||
### `view` — View item details
|
||||
|
||||
```bash
|
||||
npx shadcn@latest view <items...> [options]
|
||||
```
|
||||
|
||||
Displays item info including file contents. Examples:
|
||||
`npx shadcn@latest view @shadcn/button`,
|
||||
`npx shadcn@latest view owner/repo/item`.
|
||||
|
||||
### `docs` — Get component documentation URLs
|
||||
|
||||
```bash
|
||||
npx shadcn@latest docs <components...> [options]
|
||||
```
|
||||
|
||||
Outputs resolved URLs for component documentation, examples, and API references. Accepts one or more component names. Fetch the URLs to get the actual content.
|
||||
|
||||
Example output for `npx shadcn@latest docs input button`:
|
||||
|
||||
```
|
||||
base radix
|
||||
|
||||
input
|
||||
docs https://ui.shadcn.com/docs/components/radix/input
|
||||
examples https://raw.githubusercontent.com/.../examples/input-example.tsx
|
||||
|
||||
button
|
||||
docs https://ui.shadcn.com/docs/components/radix/button
|
||||
examples https://raw.githubusercontent.com/.../examples/button-example.tsx
|
||||
```
|
||||
|
||||
Some components include an `api` link to the underlying library (e.g. `cmdk` for the command component).
|
||||
|
||||
### `diff` — Check for updates
|
||||
|
||||
Do not use this command. Use `npx shadcn@latest add --diff` instead.
|
||||
|
||||
### `info` — Project information
|
||||
|
||||
```bash
|
||||
npx shadcn@latest info [options]
|
||||
```
|
||||
|
||||
Displays project info and `components.json` configuration. Run this first to discover the project's framework, aliases, Tailwind version, and resolved paths.
|
||||
|
||||
| Flag | Short | Description | Default |
|
||||
| ------------- | ----- | ----------------- | ------- |
|
||||
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||
|
||||
**Project Info fields:**
|
||||
|
||||
| Field | Type | Meaning |
|
||||
| -------------------- | --------- | ------------------------------------------------------------------ |
|
||||
| `framework` | `string` | Detected framework (`next`, `vite`, `react-router`, `start`, etc.) |
|
||||
| `frameworkVersion` | `string` | Framework version (e.g. `15.2.4`) |
|
||||
| `isSrcDir` | `boolean` | Whether the project uses a `src/` directory |
|
||||
| `isRSC` | `boolean` | Whether React Server Components are enabled |
|
||||
| `isTsx` | `boolean` | Whether the project uses TypeScript |
|
||||
| `tailwindVersion` | `string` | `"v3"` or `"v4"` |
|
||||
| `tailwindConfigFile` | `string` | Path to the Tailwind config file |
|
||||
| `tailwindCssFile` | `string` | Path to the global CSS file |
|
||||
| `aliasPrefix` | `string` | Import alias prefix (e.g. `@`, `~`, `@/`) |
|
||||
| `packageManager` | `string` | Detected package manager (`npm`, `pnpm`, `yarn`, `bun`) |
|
||||
|
||||
**Components.json fields:**
|
||||
|
||||
| Field | Type | Meaning |
|
||||
| -------------------- | --------- | ------------------------------------------------------------------------------------------ |
|
||||
| `base` | `string` | Primitive library (`radix` or `base`) — determines component APIs and available props |
|
||||
| `style` | `string` | Visual style (e.g. `nova`, `vega`) |
|
||||
| `rsc` | `boolean` | RSC flag from config |
|
||||
| `tsx` | `boolean` | TypeScript flag |
|
||||
| `tailwind.config` | `string` | Tailwind config path |
|
||||
| `tailwind.css` | `string` | Global CSS path — this is where custom CSS variables go |
|
||||
| `iconLibrary` | `string` | Icon library — determines icon import package (e.g. `lucide-react`, `@tabler/icons-react`) |
|
||||
| `aliases.components` | `string` | Component import alias (e.g. `@/components`) |
|
||||
| `aliases.utils` | `string` | Utils import alias (e.g. `@/lib/utils`) |
|
||||
| `aliases.ui` | `string` | UI component alias (e.g. `@/components/ui`) |
|
||||
| `aliases.lib` | `string` | Lib alias (e.g. `@/lib`) |
|
||||
| `aliases.hooks` | `string` | Hooks alias (e.g. `@/hooks`) |
|
||||
| `resolvedPaths` | `object` | Absolute file-system paths for each alias |
|
||||
| `registries` | `object` | Configured custom registries |
|
||||
|
||||
**Links fields:**
|
||||
|
||||
The `info` output includes a **Links** section with templated URLs for component docs, source, and examples. For resolved URLs, use `npx shadcn@latest docs <component>` instead.
|
||||
|
||||
### `build` — Build a custom registry
|
||||
|
||||
```bash
|
||||
npx shadcn@latest build [registry] [options]
|
||||
```
|
||||
|
||||
Builds `registry.json` into individual JSON files for distribution. Default input: `./registry.json`, default output: `./public/r`.
|
||||
|
||||
For authoring rules, `include`, item definitions, `registryDependencies`, and
|
||||
GitHub registry behavior, see [registry.md](./registry.md).
|
||||
|
||||
| Flag | Short | Description | Default |
|
||||
| ----------------- | ----- | ----------------- | ------------ |
|
||||
| `--output <path>` | `-o` | Output directory | `./public/r` |
|
||||
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||
|
||||
---
|
||||
|
||||
## Templates
|
||||
|
||||
| Value | Framework | Monorepo support |
|
||||
| -------------- | -------------- | ---------------- |
|
||||
| `next` | Next.js | Yes |
|
||||
| `vite` | Vite | Yes |
|
||||
| `start` | TanStack Start | Yes |
|
||||
| `react-router` | React Router | Yes |
|
||||
| `astro` | Astro | Yes |
|
||||
| `laravel` | Laravel | No |
|
||||
|
||||
All templates support monorepo scaffolding via the `--monorepo` flag. When passed, the CLI uses a monorepo-specific template directory (e.g. `next-monorepo`, `vite-monorepo`). When neither `--monorepo` nor `--no-monorepo` is passed, the CLI prompts interactively. Laravel does not support monorepo scaffolding.
|
||||
|
||||
---
|
||||
|
||||
## Presets
|
||||
|
||||
Three ways to specify a preset via `--preset`:
|
||||
|
||||
1. **Named:** `--preset nova` or `--preset lyra`
|
||||
2. **Code:** `--preset a2r6bw` (version-prefixed base62 string, e.g. `a2r6bw` or `b0`)
|
||||
3. **URL:** `--preset "https://ui.shadcn.com/init?base=radix&style=nova&..."`
|
||||
|
||||
> **IMPORTANT:** Never try to decode, fetch, or resolve preset codes manually. Preset codes are opaque — pass them directly to `npx shadcn@latest init --preset <code>` and let the CLI handle resolution.
|
||||
> Use `npx shadcn@latest apply --preset <code>` when overwriting an existing project's preset.
|
||||
|
||||
## Switching Presets
|
||||
|
||||
Ask the user first: **overwrite**, **merge**, or **skip** existing components?
|
||||
|
||||
- **Overwrite / Re-install** → `npx shadcn@latest apply --preset <code>`. Overwrites all detected component files with the new preset styles. Use when the user hasn't customized components.
|
||||
- **Merge** → `npx shadcn@latest init --preset <code> --force --no-reinstall`, then run `npx shadcn@latest info` to get the list of installed components and use the [smart merge workflow](./SKILL.md#updating-components) to update them one by one, preserving local changes. Use when the user has customized components.
|
||||
- **Skip** → `npx shadcn@latest init --preset <code> --force --no-reinstall`. Only updates config and CSS variables, leaves existing components as-is.
|
||||
|
||||
Always run preset commands inside the user's project directory. `apply` only works in an existing project with a `components.json` file. The CLI automatically preserves the current base (`base` vs `radix`) from `components.json`. If you must use a scratch/temp directory (e.g. for `--dry-run` comparisons), pass `--base <current-base>` explicitly — preset codes do not encode the base.
|
||||
@@ -0,0 +1,209 @@
|
||||
# Customization & Theming
|
||||
|
||||
Components reference semantic CSS variable tokens. Change the variables to change every component.
|
||||
|
||||
## Contents
|
||||
|
||||
- How it works (CSS variables → Tailwind utilities → components)
|
||||
- Color variables and OKLCH format
|
||||
- Dark mode setup
|
||||
- Changing the theme (presets, CSS variables)
|
||||
- Adding custom colors (Tailwind v3 and v4)
|
||||
- Border radius
|
||||
- Customizing components (variants, className, wrappers)
|
||||
- Checking for updates
|
||||
|
||||
---
|
||||
|
||||
## How It Works
|
||||
|
||||
1. CSS variables defined in `:root` (light) and `.dark` (dark mode).
|
||||
2. Tailwind maps them to utilities: `bg-primary`, `text-muted-foreground`, etc.
|
||||
3. Components use these utilities — changing a variable changes all components that reference it.
|
||||
|
||||
---
|
||||
|
||||
## Color Variables
|
||||
|
||||
Every color follows the `name` / `name-foreground` convention. The base variable is for backgrounds, `-foreground` is for text/icons on that background.
|
||||
|
||||
| Variable | Purpose |
|
||||
| -------------------------------------------- | -------------------------------- |
|
||||
| `--background` / `--foreground` | Page background and default text |
|
||||
| `--card` / `--card-foreground` | Card surfaces |
|
||||
| `--primary` / `--primary-foreground` | Primary buttons and actions |
|
||||
| `--secondary` / `--secondary-foreground` | Secondary actions |
|
||||
| `--muted` / `--muted-foreground` | Muted/disabled states |
|
||||
| `--accent` / `--accent-foreground` | Hover and accent states |
|
||||
| `--destructive` / `--destructive-foreground` | Error and destructive actions |
|
||||
| `--border` | Default border color |
|
||||
| `--input` | Form input borders |
|
||||
| `--ring` | Focus ring color |
|
||||
| `--chart-1` through `--chart-5` | Chart/data visualization |
|
||||
| `--sidebar-*` | Sidebar-specific colors |
|
||||
| `--surface` / `--surface-foreground` | Secondary surface |
|
||||
|
||||
Colors use OKLCH: `--primary: oklch(0.205 0 0)` where values are lightness (0–1), chroma (0 = gray), and hue (0–360).
|
||||
|
||||
---
|
||||
|
||||
## Dark Mode
|
||||
|
||||
Class-based toggle via `.dark` on the root element. In Next.js, use `next-themes`:
|
||||
|
||||
```tsx
|
||||
import { ThemeProvider } from "next-themes"
|
||||
|
||||
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
|
||||
{children}
|
||||
</ThemeProvider>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Changing the Theme
|
||||
|
||||
```bash
|
||||
# Apply a preset code from ui.shadcn.com.
|
||||
npx shadcn@latest apply --preset a2r6bw
|
||||
|
||||
# Positional shorthand also works.
|
||||
npx shadcn@latest apply a2r6bw
|
||||
|
||||
# Switch to a named preset and overwrite existing components.
|
||||
npx shadcn@latest apply --preset nova
|
||||
|
||||
# Preserve existing components instead.
|
||||
npx shadcn@latest init --preset nova --force --no-reinstall
|
||||
|
||||
# Use a custom theme URL.
|
||||
npx shadcn@latest apply --preset "https://ui.shadcn.com/init?base=radix&style=nova&theme=blue&..."
|
||||
```
|
||||
|
||||
Or edit CSS variables directly in `globals.css`.
|
||||
|
||||
---
|
||||
|
||||
## Adding Custom Colors
|
||||
|
||||
Add variables to the file at `tailwindCssFile` from `npx shadcn@latest info` (typically `globals.css`). Never create a new CSS file for this.
|
||||
|
||||
```css
|
||||
/* 1. Define in the global CSS file. */
|
||||
:root {
|
||||
--warning: oklch(0.84 0.16 84);
|
||||
--warning-foreground: oklch(0.28 0.07 46);
|
||||
}
|
||||
.dark {
|
||||
--warning: oklch(0.41 0.11 46);
|
||||
--warning-foreground: oklch(0.99 0.02 95);
|
||||
}
|
||||
```
|
||||
|
||||
```css
|
||||
/* 2a. Register with Tailwind v4 (@theme inline). */
|
||||
@theme inline {
|
||||
--color-warning: var(--warning);
|
||||
--color-warning-foreground: var(--warning-foreground);
|
||||
}
|
||||
```
|
||||
|
||||
When `tailwindVersion` is `"v3"` (check via `npx shadcn@latest info`), register in `tailwind.config.js` instead:
|
||||
|
||||
```js
|
||||
// 2b. Register with Tailwind v3 (tailwind.config.js).
|
||||
module.exports = {
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
warning: "oklch(var(--warning) / <alpha-value>)",
|
||||
"warning-foreground":
|
||||
"oklch(var(--warning-foreground) / <alpha-value>)",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// 3. Use in components.
|
||||
<div className="bg-warning text-warning-foreground">Warning</div>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Border Radius
|
||||
|
||||
`--radius` controls border radius globally. Components derive values from it (`rounded-lg` = `var(--radius)`, `rounded-md` = `calc(var(--radius) - 2px)`).
|
||||
|
||||
---
|
||||
|
||||
## Customizing Components
|
||||
|
||||
See also: [rules/styling.md](./rules/styling.md) for Incorrect/Correct examples.
|
||||
|
||||
Prefer these approaches in order:
|
||||
|
||||
### 1. Built-in variants
|
||||
|
||||
```tsx
|
||||
<Button variant="outline" size="sm">
|
||||
Click
|
||||
</Button>
|
||||
```
|
||||
|
||||
### 2. Tailwind classes via `className`
|
||||
|
||||
```tsx
|
||||
<Card className="mx-auto max-w-md">...</Card>
|
||||
```
|
||||
|
||||
### 3. Add a new variant
|
||||
|
||||
Edit the component source to add a variant via `cva`:
|
||||
|
||||
```tsx
|
||||
// components/ui/button.tsx
|
||||
warning: "bg-warning text-warning-foreground hover:bg-warning/90",
|
||||
```
|
||||
|
||||
### 4. Wrapper components
|
||||
|
||||
Compose shadcn/ui primitives into higher-level components:
|
||||
|
||||
```tsx
|
||||
export function ConfirmDialog({ title, description, onConfirm, children }) {
|
||||
return (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>{children}</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{title}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{description}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={onConfirm}>Confirm</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Checking for Updates
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add button --diff
|
||||
```
|
||||
|
||||
To preview exactly what would change before updating, use `--dry-run` and `--diff`:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add button --dry-run # see all affected files
|
||||
npx shadcn@latest add button --diff button.tsx # see the diff for a specific file
|
||||
```
|
||||
|
||||
See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full smart merge workflow.
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"skill_name": "shadcn",
|
||||
"evals": [
|
||||
{
|
||||
"id": 1,
|
||||
"prompt": "I'm building a Next.js app with shadcn/ui (base-nova preset, lucide icons). Create a settings form component with fields for: full name, email address, and notification preferences (email, SMS, push notifications as toggle options). Add validation states for required fields.",
|
||||
"expected_output": "A React component using FieldGroup, Field, ToggleGroup, data-invalid/aria-invalid validation, gap-* spacing, and semantic colors.",
|
||||
"files": [],
|
||||
"expectations": [
|
||||
"Uses FieldGroup and Field components for form layout instead of raw div with space-y",
|
||||
"Uses Switch for independent on/off notification toggles (not looping Button with manual active state)",
|
||||
"Uses data-invalid on Field and aria-invalid on the input control for validation states",
|
||||
"Uses gap-* (e.g. gap-4, gap-6) instead of space-y-* or space-x-* for spacing",
|
||||
"Uses semantic color tokens (e.g. bg-background, text-muted-foreground, text-destructive) instead of raw colors like bg-red-500",
|
||||
"No manual dark: color overrides"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"prompt": "Create a dialog component for editing a user profile. It should have the user's avatar at the top, input fields for name and bio, and Save/Cancel buttons with appropriate icons. Using shadcn/ui with radix-nova preset and tabler icons.",
|
||||
"expected_output": "A React component with DialogTitle, Avatar+AvatarFallback, data-icon on icon buttons, no icon sizing classes, tabler icon imports.",
|
||||
"files": [],
|
||||
"expectations": [
|
||||
"Includes DialogTitle for accessibility (visible or with sr-only class)",
|
||||
"Avatar component includes AvatarFallback",
|
||||
"Icons on buttons use the data-icon attribute (data-icon=\"inline-start\" or data-icon=\"inline-end\")",
|
||||
"No sizing classes on icons inside components (no size-4, w-4, h-4, etc.)",
|
||||
"Uses tabler icons (@tabler/icons-react) instead of lucide-react",
|
||||
"Uses asChild for custom triggers (radix preset)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"prompt": "Create a dashboard component that shows 4 stat cards in a grid. Each card has a title, large number, percentage change badge, and a loading skeleton state. Using shadcn/ui with base-nova preset and lucide icons.",
|
||||
"expected_output": "A React component with full Card composition, Skeleton for loading, Badge for changes, semantic colors, gap-* spacing.",
|
||||
"files": [],
|
||||
"expectations": [
|
||||
"Uses full Card composition with CardHeader, CardTitle, CardContent (not dumping everything into CardContent)",
|
||||
"Uses Skeleton component for loading placeholders instead of custom animate-pulse divs",
|
||||
"Uses Badge component for percentage change instead of custom styled spans",
|
||||
"Uses semantic color tokens instead of raw color values like bg-green-500 or text-red-600",
|
||||
"Uses gap-* instead of space-y-* or space-x-* for spacing",
|
||||
"Uses size-* when width and height are equal instead of separate w-* h-*"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
# shadcn MCP Server
|
||||
|
||||
The CLI includes an MCP server that lets AI assistants search, browse, view, and install items from registries.
|
||||
|
||||
---
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
shadcn mcp # start the MCP server (stdio)
|
||||
shadcn mcp init # write config for your editor
|
||||
```
|
||||
|
||||
Editor config files:
|
||||
|
||||
| Editor | Config file |
|
||||
| ----------- | ------------------------------- |
|
||||
| Claude Code | `.mcp.json` |
|
||||
| Cursor | `.cursor/mcp.json` |
|
||||
| VS Code | `.vscode/mcp.json` |
|
||||
| OpenCode | `opencode.json` |
|
||||
| Codex | `~/.codex/config.toml` (manual) |
|
||||
|
||||
---
|
||||
|
||||
## Tools
|
||||
|
||||
> **Tip:** MCP tools handle registry operations (search, view, install). For project configuration (aliases, framework, Tailwind version), use `npx shadcn@latest info` — there is no MCP equivalent.
|
||||
|
||||
### `shadcn:get_project_registries`
|
||||
|
||||
Returns registry names from `components.json`. Errors if no `components.json` exists.
|
||||
|
||||
**Input:** none
|
||||
|
||||
### `shadcn:list_items_in_registries`
|
||||
|
||||
Lists all items from one or more registries. Registries can be configured
|
||||
namespaces such as `@acme`, public GitHub sources such as `owner/repo`, or
|
||||
registry catalog URLs. Omit `registries` to list from every registry configured
|
||||
in `components.json`.
|
||||
|
||||
**Input:** `registries` (string[], optional — omit for all configured), `types` (string[], optional — e.g. `["ui", "block"]`), `limit` (number, optional, defaults to 100), `offset` (number, optional)
|
||||
|
||||
### `shadcn:search_items_in_registries`
|
||||
|
||||
Fuzzy search across registries. Registries can be configured namespaces, public
|
||||
GitHub sources, or registry catalog URLs. Omit `registries` to search every
|
||||
registry configured in `components.json` — e.g. "find me a hero" across all
|
||||
configured registries.
|
||||
|
||||
**Input:** `registries` (string[], optional — omit for all configured), `query` (string), `types` (string[], optional — e.g. `["ui", "block"]`), `limit` (number, optional, defaults to 100), `offset` (number, optional)
|
||||
|
||||
### `shadcn:view_items_in_registries`
|
||||
|
||||
View item details including full file contents.
|
||||
|
||||
**Input:** `items` (string[]) — e.g.
|
||||
`["@shadcn/button", "@shadcn/card", "owner/repo/item"]`
|
||||
|
||||
### `shadcn:get_item_examples_from_registries`
|
||||
|
||||
Find usage examples and demos with source code. Omit `registries` to search
|
||||
every registry configured in `components.json`.
|
||||
|
||||
**Input:** `registries` (string[], optional — omit for all configured), `query` (string) — e.g. `"accordion-demo"`, `"button example"`
|
||||
|
||||
### `shadcn:get_add_command_for_items`
|
||||
|
||||
Returns the CLI install command.
|
||||
|
||||
**Input:** `items` (string[]) — e.g. `["@shadcn/button"]`
|
||||
|
||||
### `shadcn:get_audit_checklist`
|
||||
|
||||
Returns a checklist for verifying components (imports, deps, lint, TypeScript).
|
||||
|
||||
**Input:** none
|
||||
|
||||
---
|
||||
|
||||
## Configuring Registries
|
||||
|
||||
Namespaced and authenticated registries are set in `components.json`. The
|
||||
`@shadcn` registry is always built-in. Public GitHub registries can also be used
|
||||
directly as `owner/repo` registry sources when the repository has a root
|
||||
`registry.json`; they do not need `components.json` configuration.
|
||||
|
||||
```json
|
||||
{
|
||||
"registries": {
|
||||
"@acme": "https://acme.com/r/{name}.json",
|
||||
"@private": {
|
||||
"url": "https://private.com/r/{name}.json",
|
||||
"headers": { "Authorization": "Bearer ${MY_TOKEN}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- Names must start with `@`.
|
||||
- URLs must contain `{name}`.
|
||||
- `${VAR}` references are resolved from environment variables.
|
||||
|
||||
Community registry index: `https://ui.shadcn.com/r/registries.json`
|
||||
@@ -0,0 +1,277 @@
|
||||
# Registry Authoring and Addresses
|
||||
|
||||
Use this reference when the user wants to create, fix, publish, or reason about
|
||||
a shadcn registry.
|
||||
|
||||
## Mental Model
|
||||
|
||||
A registry has two forms:
|
||||
|
||||
- **Source registry**: an authored `registry.json` in a project or repository.
|
||||
It may use `include` and file paths that point at source files.
|
||||
- **Built registry**: generated JSON files served to CLI consumers, usually
|
||||
from `public/r`. Use `npx shadcn@latest build` to create this form.
|
||||
|
||||
The CLI installer consumes registry item payloads. A source registry is a way to
|
||||
author those payloads from real files.
|
||||
|
||||
Registry items are not limited to React components. They can distribute
|
||||
components, hooks, utilities, design tokens, pages, config files, docs, rules,
|
||||
workflows, templates, MCP files, and other project files.
|
||||
|
||||
## Root `registry.json`
|
||||
|
||||
The root registry file should define registry metadata and either `items` or
|
||||
`include`.
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry.json",
|
||||
"name": "acme",
|
||||
"homepage": "https://acme.com",
|
||||
"items": [
|
||||
{
|
||||
"name": "absolute-url",
|
||||
"type": "registry:lib",
|
||||
"title": "Absolute URL",
|
||||
"description": "A utility to turn any path into an absolute URL.",
|
||||
"files": [
|
||||
{
|
||||
"path": "lib/absolute-url.ts",
|
||||
"type": "registry:lib"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Root registry rules:
|
||||
|
||||
- Root `registry.json` must include `name` and `homepage`.
|
||||
- `items` is an array of registry item definitions.
|
||||
- `include` may be used to split the source registry into multiple files.
|
||||
- Included registry files may omit `name` and `homepage`.
|
||||
|
||||
## Include
|
||||
|
||||
Use `include` to keep large registries modular.
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry.json",
|
||||
"name": "acme",
|
||||
"homepage": "https://acme.com",
|
||||
"include": ["registry/ui/registry.json", "registry/blocks/registry.json"]
|
||||
}
|
||||
```
|
||||
|
||||
Include rules:
|
||||
|
||||
- Include paths are relative to the `registry.json` that declares them.
|
||||
- Include paths must explicitly point to a `registry.json` file.
|
||||
- Do not use remote URLs, absolute paths, or parent traversal (`..`).
|
||||
- Item file paths are relative to the registry file that declares the item.
|
||||
- Duplicate item names fail across the resolved registry.
|
||||
|
||||
Example included file:
|
||||
|
||||
```json
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"name": "button",
|
||||
"type": "registry:ui",
|
||||
"files": [
|
||||
{
|
||||
"path": "button.tsx",
|
||||
"type": "registry:ui"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
If this file is at `registry/ui/registry.json`, then `button.tsx` is read from
|
||||
`registry/ui/button.tsx`, and the built item path is emitted relative to the
|
||||
root registry.
|
||||
|
||||
## Item Definitions
|
||||
|
||||
Common item fields:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "login-form",
|
||||
"type": "registry:block",
|
||||
"title": "Login Form",
|
||||
"description": "A login form with email and password fields.",
|
||||
"dependencies": ["zod"],
|
||||
"registryDependencies": ["button", "input", "label"],
|
||||
"files": [
|
||||
{
|
||||
"path": "blocks/login-form.tsx",
|
||||
"type": "registry:block"
|
||||
}
|
||||
],
|
||||
"cssVars": {
|
||||
"light": {
|
||||
"brand": "oklch(0.62 0.18 250)"
|
||||
},
|
||||
"dark": {
|
||||
"brand": "oklch(0.72 0.16 250)"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Important fields:
|
||||
|
||||
- `name`: the installable item name. It is not necessarily a file path.
|
||||
- `type`: one of the registry item types, such as `registry:ui`,
|
||||
`registry:block`, `registry:lib`, `registry:hook`, `registry:file`,
|
||||
`registry:page`, `registry:theme`, `registry:style`, `registry:font`, or
|
||||
`registry:item`.
|
||||
- `files`: source files copied or generated by the item.
|
||||
- `dependencies`: npm runtime dependencies.
|
||||
- `devDependencies`: npm development dependencies.
|
||||
- `registryDependencies`: other registry items required by this item.
|
||||
- `cssVars`, `css`, `tailwind`, `envVars`, and `docs`: optional install-time
|
||||
additions.
|
||||
|
||||
File rules:
|
||||
|
||||
- File paths are relative to the declaring `registry.json`.
|
||||
- `registry:file` and `registry:page` files require a `target`.
|
||||
- Do not use remote file URLs in source registry file paths.
|
||||
- Keep source files copy-pasteable: no hidden app-only imports.
|
||||
|
||||
## Registry Dependencies
|
||||
|
||||
`registryDependencies` entries are item addresses, not file paths.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "login-form",
|
||||
"type": "registry:block",
|
||||
"registryDependencies": ["button", "@acme/input", "acme/ui/card#v1.2.0"],
|
||||
"files": [
|
||||
{
|
||||
"path": "blocks/login-form.tsx",
|
||||
"type": "registry:block"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Dependency rules:
|
||||
|
||||
- Bare names such as `"button"` mean official shadcn items.
|
||||
- Bare names never mean same-registry or same-repository items.
|
||||
- Namespaced dependencies use `@namespace/item-name`.
|
||||
- GitHub dependencies use `owner/repo/item-name`.
|
||||
- Pin GitHub dependencies with `owner/repo/item-name#ref` when needed.
|
||||
- Refs are not inherited. If `owner/repo/foo#v2` depends on `bar` from the same
|
||||
repo at `v2`, write `owner/repo/bar#v2`.
|
||||
- Do not use relative dependencies such as `"./bar"`.
|
||||
|
||||
## Address Schemes
|
||||
|
||||
When reasoning about a registry item string, classify it first.
|
||||
|
||||
| Address | Scheme | Meaning |
|
||||
| ----------------------------------- | --------- | ------------------------------------------------------------ |
|
||||
| `button` | shadcn | Official shadcn item named `button`. |
|
||||
| `@acme/button` | namespace | Item `button` from configured registry `@acme`. |
|
||||
| `@acme/ui/button` | namespace | Item `ui/button` from configured registry `@acme`. |
|
||||
| `https://example.com/r/button.json` | url | Built registry item JSON at that URL. |
|
||||
| `./button.json` | file | Built registry item JSON on disk. |
|
||||
| `acme/ui/button` | github | Item `button` from GitHub repo `acme/ui`. |
|
||||
| `acme/ui/forms/login#main` | github | Item `forms/login` from GitHub repo `acme/ui` at ref `main`. |
|
||||
|
||||
For namespace and GitHub addresses, slashful item names are allowed and are item
|
||||
names, not file paths. Addresses ending in `.json` keep file-address
|
||||
precedence, so `acme/ui/data/schema.json` is treated as a file path, not a
|
||||
GitHub item address.
|
||||
|
||||
## GitHub Registries
|
||||
|
||||
A public GitHub repository can act as a source registry when it has a root
|
||||
`registry.json`.
|
||||
|
||||
```txt
|
||||
owner/repo/item-name[#ref]
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- The first two path segments are GitHub owner and repo.
|
||||
- All remaining path segments are the registry item name.
|
||||
- The source entrypoint is always root `registry.json`.
|
||||
- GitHub registries are source registries consumed directly by the CLI. They do
|
||||
not require `shadcn build` or generated item JSON files.
|
||||
- `include` follows the same source-registry rules as local registries.
|
||||
- Currently, GitHub addresses support public `github.com` repositories only.
|
||||
- Private repos and GitHub Enterprise require explicit product decisions.
|
||||
|
||||
When implementing GitHub registry fetching, resolve refs to a commit SHA before
|
||||
reading source files. Do not read moving refs directly from
|
||||
`raw.githubusercontent.com`, because branch-like refs can be cached for several
|
||||
minutes.
|
||||
|
||||
Preferred flow:
|
||||
|
||||
```txt
|
||||
owner/repo[#ref]
|
||||
-> resolve ref with git ls-remote
|
||||
-> commit SHA
|
||||
-> read https://raw.githubusercontent.com/{owner}/{repo}/{sha}/registry.json
|
||||
-> read includes and item files from the same SHA
|
||||
```
|
||||
|
||||
This keeps a command on one consistent repository snapshot.
|
||||
|
||||
Full 40-character commit SHAs are already stable and can be used directly.
|
||||
Branches, tags, and short refs require Git so the CLI can resolve them to a
|
||||
commit SHA first.
|
||||
|
||||
## Build and Verify
|
||||
|
||||
Use the CLI to build source registries:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest build
|
||||
npx shadcn@latest build registry.json --output public/r
|
||||
```
|
||||
|
||||
Use CLI commands to inspect the result:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest list @acme
|
||||
npx shadcn@latest search @acme -q "login"
|
||||
npx shadcn@latest view @acme/login-form
|
||||
npx shadcn@latest add @acme/login-form --dry-run
|
||||
npx shadcn@latest registry validate ./registry.json
|
||||
```
|
||||
|
||||
Use GitHub addresses directly for public GitHub registries:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest list owner/repo
|
||||
npx shadcn@latest search owner/repo -q "login"
|
||||
npx shadcn@latest view owner/repo/item
|
||||
npx shadcn@latest add owner/repo/item --dry-run
|
||||
npx shadcn@latest registry validate owner/repo
|
||||
```
|
||||
|
||||
When working on registry implementation in the shadcn/ui codebase:
|
||||
|
||||
- Keep address parsing pure and testable.
|
||||
- Do not add side effects to validators.
|
||||
- Preserve existing behavior for official shadcn, namespace, URL, and file
|
||||
schemes.
|
||||
- Add tests for address parsing, source loading, dependency resolution, list,
|
||||
search, view, and add paths.
|
||||
- Prefer small source-reader abstractions over a plugin system until there are
|
||||
multiple real providers.
|
||||
@@ -0,0 +1,306 @@
|
||||
# Base vs Radix
|
||||
|
||||
API differences between `base` and `radix`. Check the `base` field from `npx shadcn@latest info`.
|
||||
|
||||
## Contents
|
||||
|
||||
- Composition: asChild vs render
|
||||
- Button / trigger as non-button element
|
||||
- Select (items prop, placeholder, positioning, multiple, object values)
|
||||
- ToggleGroup (type vs multiple)
|
||||
- Slider (scalar vs array)
|
||||
- Accordion (type and defaultValue)
|
||||
|
||||
---
|
||||
|
||||
## Composition: asChild (radix) vs render (base)
|
||||
|
||||
Radix uses `asChild` to replace the default element. Base uses `render`. Don't wrap triggers in extra elements.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<DialogTrigger>
|
||||
<div>
|
||||
<Button>Open</Button>
|
||||
</div>
|
||||
</DialogTrigger>
|
||||
```
|
||||
|
||||
**Correct (radix):**
|
||||
|
||||
```tsx
|
||||
<DialogTrigger asChild>
|
||||
<Button>Open</Button>
|
||||
</DialogTrigger>
|
||||
```
|
||||
|
||||
**Correct (base):**
|
||||
|
||||
```tsx
|
||||
<DialogTrigger render={<Button />}>Open</DialogTrigger>
|
||||
```
|
||||
|
||||
This applies to all trigger and close components: `DialogTrigger`, `SheetTrigger`, `AlertDialogTrigger`, `DropdownMenuTrigger`, `PopoverTrigger`, `TooltipTrigger`, `CollapsibleTrigger`, `DialogClose`, `SheetClose`, `NavigationMenuLink`, `BreadcrumbLink`, `SidebarMenuButton`, `Badge`, `Item`.
|
||||
|
||||
---
|
||||
|
||||
## Button / trigger as non-button element (base only)
|
||||
|
||||
When `render` changes an element to a non-button (`<a>`, `<span>`), add `nativeButton={false}`.
|
||||
|
||||
**Incorrect (base):** missing `nativeButton={false}`.
|
||||
|
||||
```tsx
|
||||
<Button render={<a href="/docs" />}>Read the docs</Button>
|
||||
```
|
||||
|
||||
**Correct (base):**
|
||||
|
||||
```tsx
|
||||
<Button render={<a href="/docs" />} nativeButton={false}>
|
||||
Read the docs
|
||||
</Button>
|
||||
```
|
||||
|
||||
**Correct (radix):**
|
||||
|
||||
```tsx
|
||||
<Button asChild>
|
||||
<a href="/docs">Read the docs</a>
|
||||
</Button>
|
||||
```
|
||||
|
||||
Same for triggers whose `render` is not a `Button`:
|
||||
|
||||
```tsx
|
||||
// base.
|
||||
<PopoverTrigger render={<InputGroupAddon />} nativeButton={false}>
|
||||
Pick date
|
||||
</PopoverTrigger>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Select
|
||||
|
||||
**items prop (base only).** Base requires an `items` prop on the root. Radix uses inline JSX only.
|
||||
|
||||
**Incorrect (base):**
|
||||
|
||||
```tsx
|
||||
<Select>
|
||||
<SelectTrigger><SelectValue placeholder="Select a fruit" /></SelectTrigger>
|
||||
</Select>
|
||||
```
|
||||
|
||||
**Correct (base):**
|
||||
|
||||
```tsx
|
||||
const items = [
|
||||
{ label: "Select a fruit", value: null },
|
||||
{ label: "Apple", value: "apple" },
|
||||
{ label: "Banana", value: "banana" },
|
||||
]
|
||||
|
||||
<Select items={items}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
{items.map((item) => (
|
||||
<SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
```
|
||||
|
||||
**Correct (radix):**
|
||||
|
||||
```tsx
|
||||
<Select>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a fruit" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectItem value="apple">Apple</SelectItem>
|
||||
<SelectItem value="banana">Banana</SelectItem>
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
```
|
||||
|
||||
**Placeholder.** Base uses a `{ value: null }` item in the items array. Radix uses `<SelectValue placeholder="...">`.
|
||||
|
||||
**Content positioning.** Base uses `alignItemWithTrigger`. Radix uses `position`.
|
||||
|
||||
```tsx
|
||||
// base.
|
||||
<SelectContent alignItemWithTrigger={false} side="bottom">
|
||||
|
||||
// radix.
|
||||
<SelectContent position="popper">
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Select — multiple selection and object values (base only)
|
||||
|
||||
Base supports `multiple`, render-function children on `SelectValue`, and object values with `itemToStringValue`. Radix is single-select with string values only.
|
||||
|
||||
**Correct (base — multiple selection):**
|
||||
|
||||
```tsx
|
||||
<Select items={items} multiple defaultValue={[]}>
|
||||
<SelectTrigger>
|
||||
<SelectValue>
|
||||
{(value: string[]) => value.length === 0 ? "Select fruits" : `${value.length} selected`}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
...
|
||||
</Select>
|
||||
```
|
||||
|
||||
**Correct (base — object values):**
|
||||
|
||||
```tsx
|
||||
<Select defaultValue={plans[0]} itemToStringValue={(plan) => plan.name}>
|
||||
<SelectTrigger>
|
||||
<SelectValue>{(value) => value.name}</SelectValue>
|
||||
</SelectTrigger>
|
||||
...
|
||||
</Select>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ToggleGroup
|
||||
|
||||
Base uses a `multiple` boolean prop. Radix uses `type="single"` or `type="multiple"`.
|
||||
|
||||
**Incorrect (base):**
|
||||
|
||||
```tsx
|
||||
<ToggleGroup type="single" defaultValue="daily">
|
||||
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
```
|
||||
|
||||
**Correct (base):**
|
||||
|
||||
```tsx
|
||||
// Single (no prop needed), defaultValue is always an array.
|
||||
<ToggleGroup defaultValue={["daily"]} spacing={2}>
|
||||
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
|
||||
<ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
|
||||
// Multi-selection.
|
||||
<ToggleGroup multiple>
|
||||
<ToggleGroupItem value="bold">Bold</ToggleGroupItem>
|
||||
<ToggleGroupItem value="italic">Italic</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
```
|
||||
|
||||
**Correct (radix):**
|
||||
|
||||
```tsx
|
||||
// Single, defaultValue is a string.
|
||||
<ToggleGroup type="single" defaultValue="daily" spacing={2}>
|
||||
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
|
||||
<ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
|
||||
// Multi-selection.
|
||||
<ToggleGroup type="multiple">
|
||||
<ToggleGroupItem value="bold">Bold</ToggleGroupItem>
|
||||
<ToggleGroupItem value="italic">Italic</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
```
|
||||
|
||||
**Controlled single value:**
|
||||
|
||||
```tsx
|
||||
// base — wrap/unwrap arrays.
|
||||
const [value, setValue] = React.useState("normal")
|
||||
<ToggleGroup value={[value]} onValueChange={(v) => setValue(v[0])}>
|
||||
|
||||
// radix — plain string.
|
||||
const [value, setValue] = React.useState("normal")
|
||||
<ToggleGroup type="single" value={value} onValueChange={setValue}>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Slider
|
||||
|
||||
Base accepts a plain number for a single thumb. Radix always requires an array.
|
||||
|
||||
**Incorrect (base):**
|
||||
|
||||
```tsx
|
||||
<Slider defaultValue={[50]} max={100} step={1} />
|
||||
```
|
||||
|
||||
**Correct (base):**
|
||||
|
||||
```tsx
|
||||
<Slider defaultValue={50} max={100} step={1} />
|
||||
```
|
||||
|
||||
**Correct (radix):**
|
||||
|
||||
```tsx
|
||||
<Slider defaultValue={[50]} max={100} step={1} />
|
||||
```
|
||||
|
||||
Both use arrays for range sliders. Controlled `onValueChange` in base may need a cast:
|
||||
|
||||
```tsx
|
||||
// base.
|
||||
const [value, setValue] = React.useState([0.3, 0.7])
|
||||
<Slider value={value} onValueChange={(v) => setValue(v as number[])} />
|
||||
|
||||
// radix.
|
||||
const [value, setValue] = React.useState([0.3, 0.7])
|
||||
<Slider value={value} onValueChange={setValue} />
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Accordion
|
||||
|
||||
Radix requires `type="single"` or `type="multiple"` and supports `collapsible`. `defaultValue` is a string. Base uses no `type` prop, uses `multiple` boolean, and `defaultValue` is always an array.
|
||||
|
||||
**Incorrect (base):**
|
||||
|
||||
```tsx
|
||||
<Accordion type="single" collapsible defaultValue="item-1">
|
||||
<AccordionItem value="item-1">...</AccordionItem>
|
||||
</Accordion>
|
||||
```
|
||||
|
||||
**Correct (base):**
|
||||
|
||||
```tsx
|
||||
<Accordion defaultValue={["item-1"]}>
|
||||
<AccordionItem value="item-1">...</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
// Multi-select.
|
||||
<Accordion multiple defaultValue={["item-1", "item-2"]}>
|
||||
<AccordionItem value="item-1">...</AccordionItem>
|
||||
<AccordionItem value="item-2">...</AccordionItem>
|
||||
</Accordion>
|
||||
```
|
||||
|
||||
**Correct (radix):**
|
||||
|
||||
```tsx
|
||||
<Accordion type="single" collapsible defaultValue="item-1">
|
||||
<AccordionItem value="item-1">...</AccordionItem>
|
||||
</Accordion>
|
||||
```
|
||||
@@ -0,0 +1,195 @@
|
||||
# Component Composition
|
||||
|
||||
## Contents
|
||||
|
||||
- Items always inside their Group component
|
||||
- Callouts use Alert
|
||||
- Empty states use Empty component
|
||||
- Toast notifications use sonner
|
||||
- Choosing between overlay components
|
||||
- Dialog, Sheet, and Drawer always need a Title
|
||||
- Card structure
|
||||
- Button has no isPending or isLoading prop
|
||||
- TabsTrigger must be inside TabsList
|
||||
- Avatar always needs AvatarFallback
|
||||
- Use Separator instead of raw hr or border divs
|
||||
- Use Skeleton for loading placeholders
|
||||
- Use Badge instead of custom styled spans
|
||||
|
||||
---
|
||||
|
||||
## Items always inside their Group component
|
||||
|
||||
Never render items directly inside the content container.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<SelectContent>
|
||||
<SelectItem value="apple">Apple</SelectItem>
|
||||
<SelectItem value="banana">Banana</SelectItem>
|
||||
</SelectContent>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectItem value="apple">Apple</SelectItem>
|
||||
<SelectItem value="banana">Banana</SelectItem>
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
```
|
||||
|
||||
This applies to all group-based components:
|
||||
|
||||
| Item | Group |
|
||||
|------|-------|
|
||||
| `SelectItem`, `SelectLabel` | `SelectGroup` |
|
||||
| `DropdownMenuItem`, `DropdownMenuLabel`, `DropdownMenuSub` | `DropdownMenuGroup` |
|
||||
| `MenubarItem` | `MenubarGroup` |
|
||||
| `ContextMenuItem` | `ContextMenuGroup` |
|
||||
| `CommandItem` | `CommandGroup` |
|
||||
|
||||
---
|
||||
|
||||
## Callouts use Alert
|
||||
|
||||
```tsx
|
||||
<Alert>
|
||||
<AlertTitle>Warning</AlertTitle>
|
||||
<AlertDescription>Something needs attention.</AlertDescription>
|
||||
</Alert>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Empty states use Empty component
|
||||
|
||||
```tsx
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyMedia variant="icon"><FolderIcon /></EmptyMedia>
|
||||
<EmptyTitle>No projects yet</EmptyTitle>
|
||||
<EmptyDescription>Get started by creating a new project.</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
<EmptyContent>
|
||||
<Button>Create Project</Button>
|
||||
</EmptyContent>
|
||||
</Empty>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Toast notifications use sonner
|
||||
|
||||
```tsx
|
||||
import { toast } from "sonner"
|
||||
|
||||
toast.success("Changes saved.")
|
||||
toast.error("Something went wrong.")
|
||||
toast("File deleted.", {
|
||||
action: { label: "Undo", onClick: () => undoDelete() },
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Choosing between overlay components
|
||||
|
||||
| Use case | Component |
|
||||
|----------|-----------|
|
||||
| Focused task that requires input | `Dialog` |
|
||||
| Destructive action confirmation | `AlertDialog` |
|
||||
| Side panel with details or filters | `Sheet` |
|
||||
| Mobile-first bottom panel | `Drawer` |
|
||||
| Quick info on hover | `HoverCard` |
|
||||
| Small contextual content on click | `Popover` |
|
||||
|
||||
---
|
||||
|
||||
## Dialog, Sheet, and Drawer always need a Title
|
||||
|
||||
`DialogTitle`, `SheetTitle`, `DrawerTitle` are required for accessibility. Use `className="sr-only"` if visually hidden.
|
||||
|
||||
```tsx
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit Profile</DialogTitle>
|
||||
<DialogDescription>Update your profile.</DialogDescription>
|
||||
</DialogHeader>
|
||||
...
|
||||
</DialogContent>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Card structure
|
||||
|
||||
Use full composition — don't dump everything into `CardContent`:
|
||||
|
||||
```tsx
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Team Members</CardTitle>
|
||||
<CardDescription>Manage your team.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>...</CardContent>
|
||||
<CardFooter>
|
||||
<Button>Invite</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Button has no isPending or isLoading prop
|
||||
|
||||
Compose with `Spinner` + `data-icon` + `disabled`:
|
||||
|
||||
```tsx
|
||||
<Button disabled>
|
||||
<Spinner data-icon="inline-start" />
|
||||
Saving...
|
||||
</Button>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## TabsTrigger must be inside TabsList
|
||||
|
||||
Never render `TabsTrigger` directly inside `Tabs` — always wrap in `TabsList`:
|
||||
|
||||
```tsx
|
||||
<Tabs defaultValue="account">
|
||||
<TabsList>
|
||||
<TabsTrigger value="account">Account</TabsTrigger>
|
||||
<TabsTrigger value="password">Password</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="account">...</TabsContent>
|
||||
</Tabs>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Avatar always needs AvatarFallback
|
||||
|
||||
Always include `AvatarFallback` for when the image fails to load:
|
||||
|
||||
```tsx
|
||||
<Avatar>
|
||||
<AvatarImage src="/avatar.png" alt="User" />
|
||||
<AvatarFallback>JD</AvatarFallback>
|
||||
</Avatar>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Use existing components instead of custom markup
|
||||
|
||||
| Instead of | Use |
|
||||
|---|---|
|
||||
| `<hr>` or `<div className="border-t">` | `<Separator />` |
|
||||
| `<div className="animate-pulse">` with styled divs | `<Skeleton className="h-4 w-3/4" />` |
|
||||
| `<span className="rounded-full bg-green-100 ...">` | `<Badge variant="secondary">` |
|
||||
@@ -0,0 +1,192 @@
|
||||
# Forms & Inputs
|
||||
|
||||
## Contents
|
||||
|
||||
- Forms use FieldGroup + Field
|
||||
- InputGroup requires InputGroupInput/InputGroupTextarea
|
||||
- Buttons inside inputs use InputGroup + InputGroupAddon
|
||||
- Option sets (2–7 choices) use ToggleGroup
|
||||
- FieldSet + FieldLegend for grouping related fields
|
||||
- Field validation and disabled states
|
||||
|
||||
---
|
||||
|
||||
## Forms use FieldGroup + Field
|
||||
|
||||
Always use `FieldGroup` + `Field` — never raw `div` with `space-y-*`:
|
||||
|
||||
```tsx
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||
<Input id="email" type="email" />
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="password">Password</FieldLabel>
|
||||
<Input id="password" type="password" />
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
```
|
||||
|
||||
Use `Field orientation="horizontal"` for settings pages. Use `FieldLabel className="sr-only"` for visually hidden labels.
|
||||
|
||||
**Choosing form controls:**
|
||||
|
||||
- Simple text input → `Input`
|
||||
- Dropdown with predefined options → `Select`
|
||||
- Searchable dropdown → `Combobox`
|
||||
- Native HTML select (no JS) → `native-select`
|
||||
- Boolean toggle → `Switch` (for settings) or `Checkbox` (for forms)
|
||||
- Single choice from few options → `RadioGroup`
|
||||
- Toggle between 2–5 options → `ToggleGroup` + `ToggleGroupItem`
|
||||
- OTP/verification code → `InputOTP`
|
||||
- Multi-line text → `Textarea`
|
||||
|
||||
---
|
||||
|
||||
## InputGroup requires InputGroupInput/InputGroupTextarea
|
||||
|
||||
Never use raw `Input` or `Textarea` inside an `InputGroup`.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<InputGroup>
|
||||
<Input placeholder="Search..." />
|
||||
</InputGroup>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
import { InputGroup, InputGroupInput } from "@/components/ui/input-group"
|
||||
|
||||
<InputGroup>
|
||||
<InputGroupInput placeholder="Search..." />
|
||||
</InputGroup>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Buttons inside inputs use InputGroup + InputGroupAddon
|
||||
|
||||
Never place a `Button` directly inside or adjacent to an `Input` with custom positioning.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<div className="relative">
|
||||
<Input placeholder="Search..." className="pr-10" />
|
||||
<Button className="absolute right-0 top-0" size="icon">
|
||||
<SearchIcon />
|
||||
</Button>
|
||||
</div>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
import { InputGroup, InputGroupInput, InputGroupAddon } from "@/components/ui/input-group"
|
||||
|
||||
<InputGroup>
|
||||
<InputGroupInput placeholder="Search..." />
|
||||
<InputGroupAddon>
|
||||
<Button size="icon">
|
||||
<SearchIcon data-icon="inline-start" />
|
||||
</Button>
|
||||
</InputGroupAddon>
|
||||
</InputGroup>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Option sets (2–7 choices) use ToggleGroup
|
||||
|
||||
Don't manually loop `Button` components with active state.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
const [selected, setSelected] = useState("daily")
|
||||
|
||||
<div className="flex gap-2">
|
||||
{["daily", "weekly", "monthly"].map((option) => (
|
||||
<Button
|
||||
key={option}
|
||||
variant={selected === option ? "default" : "outline"}
|
||||
onClick={() => setSelected(option)}
|
||||
>
|
||||
{option}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
|
||||
|
||||
<ToggleGroup spacing={2}>
|
||||
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
|
||||
<ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
|
||||
<ToggleGroupItem value="monthly">Monthly</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
```
|
||||
|
||||
Combine with `Field` for labelled toggle groups:
|
||||
|
||||
```tsx
|
||||
<Field orientation="horizontal">
|
||||
<FieldTitle id="theme-label">Theme</FieldTitle>
|
||||
<ToggleGroup aria-labelledby="theme-label" spacing={2}>
|
||||
<ToggleGroupItem value="light">Light</ToggleGroupItem>
|
||||
<ToggleGroupItem value="dark">Dark</ToggleGroupItem>
|
||||
<ToggleGroupItem value="system">System</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</Field>
|
||||
```
|
||||
|
||||
> **Note:** `defaultValue` and `type`/`multiple` props differ between base and radix. See [base-vs-radix.md](./base-vs-radix.md#togglegroup).
|
||||
|
||||
---
|
||||
|
||||
## FieldSet + FieldLegend for grouping related fields
|
||||
|
||||
Use `FieldSet` + `FieldLegend` for related checkboxes, radios, or switches — not `div` with a heading:
|
||||
|
||||
```tsx
|
||||
<FieldSet>
|
||||
<FieldLegend variant="label">Preferences</FieldLegend>
|
||||
<FieldDescription>Select all that apply.</FieldDescription>
|
||||
<FieldGroup className="gap-3">
|
||||
<Field orientation="horizontal">
|
||||
<Checkbox id="dark" />
|
||||
<FieldLabel htmlFor="dark" className="font-normal">Dark mode</FieldLabel>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</FieldSet>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Field validation and disabled states
|
||||
|
||||
Both attributes are needed — `data-invalid`/`data-disabled` styles the field (label, description), while `aria-invalid`/`disabled` styles the control.
|
||||
|
||||
```tsx
|
||||
// Invalid.
|
||||
<Field data-invalid>
|
||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||
<Input id="email" aria-invalid />
|
||||
<FieldDescription>Invalid email address.</FieldDescription>
|
||||
</Field>
|
||||
|
||||
// Disabled.
|
||||
<Field data-disabled>
|
||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||
<Input id="email" disabled />
|
||||
</Field>
|
||||
```
|
||||
|
||||
Works for all controls: `Input`, `Textarea`, `Select`, `Checkbox`, `RadioGroupItem`, `Switch`, `Slider`, `NativeSelect`, `InputOTP`.
|
||||
@@ -0,0 +1,101 @@
|
||||
# Icons
|
||||
|
||||
**Always use the project's configured `iconLibrary` for imports.** Check the `iconLibrary` field from project context: `lucide` → `lucide-react`, `tabler` → `@tabler/icons-react`, etc. Never assume `lucide-react`.
|
||||
|
||||
---
|
||||
|
||||
## Icons in Button use data-icon attribute
|
||||
|
||||
Add `data-icon="inline-start"` (prefix) or `data-icon="inline-end"` (suffix) to the icon. No sizing classes on the icon.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<Button>
|
||||
<SearchIcon className="mr-2 size-4" />
|
||||
Search
|
||||
</Button>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
<Button>
|
||||
<SearchIcon data-icon="inline-start"/>
|
||||
Search
|
||||
</Button>
|
||||
|
||||
<Button>
|
||||
Next
|
||||
<ArrowRightIcon data-icon="inline-end"/>
|
||||
</Button>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## No sizing classes on icons inside components
|
||||
|
||||
Components handle icon sizing via CSS. Don't add `size-4`, `w-4 h-4`, or other sizing classes to icons inside `Button`, `DropdownMenuItem`, `Alert`, `Sidebar*`, or other shadcn components. Unless the user explicitly asks for custom icon sizes.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<Button>
|
||||
<SearchIcon className="size-4" data-icon="inline-start" />
|
||||
Search
|
||||
</Button>
|
||||
|
||||
<DropdownMenuItem>
|
||||
<SettingsIcon className="mr-2 size-4" />
|
||||
Settings
|
||||
</DropdownMenuItem>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
<Button>
|
||||
<SearchIcon data-icon="inline-start" />
|
||||
Search
|
||||
</Button>
|
||||
|
||||
<DropdownMenuItem>
|
||||
<SettingsIcon />
|
||||
Settings
|
||||
</DropdownMenuItem>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pass icons as component objects, not string keys
|
||||
|
||||
Use `icon={CheckIcon}`, not a string key to a lookup map.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
const iconMap = {
|
||||
check: CheckIcon,
|
||||
alert: AlertIcon,
|
||||
}
|
||||
|
||||
function StatusBadge({ icon }: { icon: string }) {
|
||||
const Icon = iconMap[icon]
|
||||
return <Icon />
|
||||
}
|
||||
|
||||
<StatusBadge icon="check" />
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
// Import from the project's configured iconLibrary (e.g. lucide-react, @tabler/icons-react).
|
||||
import { CheckIcon } from "lucide-react"
|
||||
|
||||
function StatusBadge({ icon: Icon }: { icon: React.ComponentType }) {
|
||||
return <Icon />
|
||||
}
|
||||
|
||||
<StatusBadge icon={CheckIcon} />
|
||||
```
|
||||
@@ -0,0 +1,162 @@
|
||||
# Styling & Customization
|
||||
|
||||
See [customization.md](../customization.md) for theming, CSS variables, and adding custom colors.
|
||||
|
||||
## Contents
|
||||
|
||||
- Semantic colors
|
||||
- Built-in variants first
|
||||
- className for layout only
|
||||
- No space-x-* / space-y-*
|
||||
- Prefer size-* over w-* h-* when equal
|
||||
- Prefer truncate shorthand
|
||||
- No manual dark: color overrides
|
||||
- Use cn() for conditional classes
|
||||
- No manual z-index on overlay components
|
||||
|
||||
---
|
||||
|
||||
## Semantic colors
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<div className="bg-blue-500 text-white">
|
||||
<p className="text-gray-600">Secondary text</p>
|
||||
</div>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
<div className="bg-primary text-primary-foreground">
|
||||
<p className="text-muted-foreground">Secondary text</p>
|
||||
</div>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## No raw color values for status/state indicators
|
||||
|
||||
For positive, negative, or status indicators, use Badge variants, semantic tokens like `text-destructive`, or define custom CSS variables — don't reach for raw Tailwind colors.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<span className="text-emerald-600">+20.1%</span>
|
||||
<span className="text-green-500">Active</span>
|
||||
<span className="text-red-600">-3.2%</span>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
<Badge variant="secondary">+20.1%</Badge>
|
||||
<Badge>Active</Badge>
|
||||
<span className="text-destructive">-3.2%</span>
|
||||
```
|
||||
|
||||
If you need a success/positive color that doesn't exist as a semantic token, use a Badge variant or ask the user about adding a custom CSS variable to the theme (see [customization.md](../customization.md)).
|
||||
|
||||
---
|
||||
|
||||
## Built-in variants first
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<Button className="border border-input bg-transparent hover:bg-accent">
|
||||
Click me
|
||||
</Button>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
<Button variant="outline">Click me</Button>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## className for layout only
|
||||
|
||||
Use `className` for layout (e.g. `max-w-md`, `mx-auto`, `mt-4`), **not** for overriding component colors or typography. To change colors, use semantic tokens, built-in variants, or CSS variables.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<Card className="bg-blue-100 text-blue-900 font-bold">
|
||||
<CardContent>Dashboard</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
<Card className="max-w-md mx-auto">
|
||||
<CardContent>Dashboard</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
To customize a component's appearance, prefer these approaches in order:
|
||||
1. **Built-in variants** — `variant="outline"`, `variant="destructive"`, etc.
|
||||
2. **Semantic color tokens** — `bg-primary`, `text-muted-foreground`.
|
||||
3. **CSS variables** — define custom colors in the global CSS file (see [customization.md](../customization.md)).
|
||||
|
||||
---
|
||||
|
||||
## No space-x-* / space-y-*
|
||||
|
||||
Use `gap-*` instead. `space-y-4` → `flex flex-col gap-4`. `space-x-2` → `flex gap-2`.
|
||||
|
||||
```tsx
|
||||
<div className="flex flex-col gap-4">
|
||||
<Input />
|
||||
<Input />
|
||||
<Button>Submit</Button>
|
||||
</div>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Prefer size-* over w-* h-* when equal
|
||||
|
||||
`size-10` not `w-10 h-10`. Applies to icons, avatars, skeletons, etc.
|
||||
|
||||
---
|
||||
|
||||
## Prefer truncate shorthand
|
||||
|
||||
`truncate` not `overflow-hidden text-ellipsis whitespace-nowrap`.
|
||||
|
||||
---
|
||||
|
||||
## No manual dark: color overrides
|
||||
|
||||
Use semantic tokens — they handle light/dark via CSS variables. `bg-background text-foreground` not `bg-white dark:bg-gray-950`.
|
||||
|
||||
---
|
||||
|
||||
## Use cn() for conditional classes
|
||||
|
||||
Use the `cn()` utility from the project for conditional or merged class names. Don't write manual ternaries in className strings.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<div className={`flex items-center ${isActive ? "bg-primary text-primary-foreground" : "bg-muted"}`}>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
<div className={cn("flex items-center", isActive ? "bg-primary text-primary-foreground" : "bg-muted")}>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## No manual z-index on overlay components
|
||||
|
||||
`Dialog`, `Sheet`, `Drawer`, `AlertDialog`, `DropdownMenu`, `Popover`, `Tooltip`, `HoverCard` handle their own stacking. Never add `z-50` or `z-[999]`.
|
||||
@@ -0,0 +1,7 @@
|
||||
# Lessons
|
||||
|
||||
## Alpine x-transition + tw-animate-css exit animations flash at the end
|
||||
- Symptom: a modal/overlay fades out, then flashes fully visible for 1-2 frames before it disappears.
|
||||
- Cause: `animate-out` keyframes default to `animation-fill-mode: none`. The element snaps back to its natural state when the keyframe ends. Alpine hides the element (display: none) only after its own timer (read from `transition-duration`), which starts ~2 rAF later than the animation. The gap shows the element at full opacity.
|
||||
- Rule: every `x-transition:leave` that uses tw-animate-css `animate-out` MUST also include `fill-mode-forwards`.
|
||||
- Rule: when a user reports UI flicker, check ALL layers of the animation stack (state reset timing, spinner flash, keyframe fill mode, focus restore) before you report the fix as complete. My first fix covered state reset and spinner only; the fill-mode snap was the visible one.
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/shadcn
|
||||
@@ -0,0 +1,32 @@
|
||||
vmType: "vz"
|
||||
arch: "default"
|
||||
cpus: 2
|
||||
memory: "2GiB"
|
||||
disk: "20GiB"
|
||||
containerd:
|
||||
system: false
|
||||
user: false
|
||||
ssh:
|
||||
localPort: 60003
|
||||
images:
|
||||
- location: "https://cloud-images.ubuntu.com/releases/24.04/release/ubuntu-24.04-server-cloudimg-amd64.img"
|
||||
arch: "x86_64"
|
||||
- location: "https://cloud-images.ubuntu.com/releases/24.04/release/ubuntu-24.04-server-cloudimg-arm64.img"
|
||||
arch: "aarch64"
|
||||
mounts: []
|
||||
provision:
|
||||
- mode: system
|
||||
script: |
|
||||
#!/usr/bin/env bash
|
||||
set -euxo pipefail
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
install -d -m 700 /root/.ssh
|
||||
cat >/root/.ssh/authorized_keys <<'KEYS'
|
||||
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFuGmoeGq/pojrsyP1pszcNVuZx9iFkCELtxrh31QJ68 sail@76ff66d2e2dd
|
||||
KEYS
|
||||
chmod 600 /root/.ssh/authorized_keys
|
||||
sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin prohibit-password/' /etc/ssh/sshd_config
|
||||
sed -i 's/^#\?PubkeyAuthentication.*/PubkeyAuthentication yes/' /etc/ssh/sshd_config
|
||||
systemctl restart ssh || systemctl restart sshd
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends ca-certificates curl openssh-server sudo
|
||||
@@ -0,0 +1,7 @@
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevAAAAJi/QySHv0Mk
|
||||
hwAAAAtzc2gtZWQyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevA
|
||||
AAAECBQw4jg1WRT2IGHMncCiZhURCts2s24HoDS0thHnnRKVuGmoeGq/pojrsyP1pszcNV
|
||||
uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==
|
||||
-----END OPENSSH PRIVATE KEY-----
|
||||
@@ -0,0 +1 @@
|
||||
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFuGmoeGq/pojrsyP1pszcNVuZx9iFkCELtxrh31QJ68 sail@76ff66d2e2dd
|
||||
@@ -7,6 +7,8 @@ APP_URL=http://localhost
|
||||
APP_PORT=8000
|
||||
APP_DEBUG=true
|
||||
SSH_MUX_ENABLED=true
|
||||
COOLIFY_CONTAINER_ROLE=all
|
||||
DEV_SENTINEL_URL=
|
||||
|
||||
# PostgreSQL Database Configuration
|
||||
DB_DATABASE=coolify
|
||||
@@ -27,8 +29,17 @@ DB_PORT=5432
|
||||
# DB_WRITE_PASSWORD=
|
||||
# DB_STICKY=true
|
||||
|
||||
# Enable Laravel Telescope for debugging
|
||||
TELESCOPE_ENABLED=false
|
||||
|
||||
|
||||
# Server-Timing headers + on-screen HUD (defaults ON when APP_ENV=local).
|
||||
# Force on in any environment (including production): SERVER_TIMING_ENABLED=true
|
||||
# Force off even in local: SERVER_TIMING_ENABLED=false
|
||||
# SERVER_TIMING_ENABLED=true
|
||||
|
||||
# Vite dev server. Defaults to localhost. For phone/LAN/Tailscale access, set to
|
||||
# the host machine's reachable IP (e.g. VITE_HOST=100.75.155.70), then recreate vite.
|
||||
VITE_HOST=localhost
|
||||
VITE_PORT=5173
|
||||
|
||||
# Enable Laravel Nightwatch monitoring
|
||||
NIGHTWATCH_ENABLED=false
|
||||
|
||||
@@ -8,7 +8,6 @@ CACHE_DRIVER=array
|
||||
SESSION_DRIVER=array
|
||||
QUEUE_CONNECTION=sync
|
||||
MAIL_MAILER=array
|
||||
TELESCOPE_ENABLED=false
|
||||
|
||||
REDIS_HOST=127.0.0.1
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ body:
|
||||
value: |
|
||||
> [!IMPORTANT]
|
||||
> **Please ensure you are using the latest version of Coolify before submitting an issue, as the bug may have already been fixed in a recent update.** (Of course, if you're experiencing an issue on the latest version that wasn't present in a previous version, please let us know.)
|
||||
>
|
||||
> If you plan to submit a fix, branch from `main` and target `main` with your pull request.
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
|
||||
@@ -7,12 +7,12 @@ contact_links:
|
||||
|
||||
- name: 💡 Feature Request
|
||||
url: https://github.com/coollabsio/coolify/discussions/categories/feature-requests
|
||||
about: Suggest a new feature for Coolify.
|
||||
about: Suggest a new feature for Coolify. Feature code should branch from `next` and target `next`.
|
||||
|
||||
- name: ⚙️ Service Request
|
||||
url: https://github.com/coollabsio/coolify/discussions/categories/service-requests
|
||||
about: Request a new service integration for Coolify.
|
||||
about: Request a new service integration for Coolify. Service code should branch from `next` and target `next`.
|
||||
|
||||
- name: 🔧 Improvements
|
||||
url: https://github.com/coollabsio/coolify/discussions/categories/improvements
|
||||
about: Suggest improvements to existing features for Coolify.
|
||||
about: Suggest improvements to existing features. Small fixes should target `main`; larger changes should target `next`.
|
||||
|
||||
@@ -46,6 +46,6 @@
|
||||
|
||||
> [!IMPORTANT]
|
||||
>
|
||||
> - [ ] I have read and understood the [contributor guidelines](https://github.com/coollabsio/coolify/blob/v4.x/CONTRIBUTING.md). If I have failed to follow any guideline, I understand that this PR may be closed without review.
|
||||
> - [ ] I have read and understood the [contributor guidelines](https://github.com/coollabsio/coolify/blob/HEAD/CONTRIBUTING.md). If I have failed to follow any guideline, I understand that this PR may be closed without review.
|
||||
> - [ ] I have searched [existing issues](https://github.com/coollabsio/coolify/issues) and [pull requests](https://github.com/coollabsio/coolify/pulls) (including closed ones) to ensure this isn't a duplicate.
|
||||
> - [ ] I have tested all the changes thoroughly with a local development instance of Coolify and I am confident that they will work as expected when a maintainer tests them.
|
||||
|
||||
@@ -14,7 +14,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Lock threads after 30 days of inactivity
|
||||
uses: dessant/lock-threads@v5
|
||||
uses: dessant/lock-threads@89ae32b08ed1a541efecbab17912962a5e38981c # v6.0.2
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
issue-inactive-days: '30'
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
name: Manage PR Branch
|
||||
|
||||
# Runs *after* the "PR Quality" workflow finishes. This is required because
|
||||
# PR Quality may close a PR that fails its checks, so we must wait for it to
|
||||
# complete before deciding whether to retarget the PR's base branch.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["PR Quality"]
|
||||
types:
|
||||
- completed
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: manage-pr-branch-${{ github.event.workflow_run.head_sha }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
manage-branch:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Retarget PR base branch based on category
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const run = context.payload.workflow_run;
|
||||
|
||||
// Branch routing based on the "Category" section of the PR body.
|
||||
// Bug fixes and one-click service changes ship in patch releases -> main.
|
||||
// Everything else (features, improvements) -> next.
|
||||
const MAIN_BRANCH = 'main';
|
||||
const NEXT_BRANCH = 'next';
|
||||
|
||||
// Maintainers/collaborators are trusted to pick their own base branch.
|
||||
const EXEMPT_ASSOCIATIONS = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']);
|
||||
|
||||
// Resolve the open PR from the triggering run.
|
||||
//
|
||||
// PR Quality runs on `pull_request_target`, so `run.head_sha` is the
|
||||
// *base* branch tip, not the PR head — a commit-based lookup finds
|
||||
// nothing. Instead match on the source branch (`head_branch`) and its
|
||||
// owner (`head_repository.owner.login`), which uniquely identify the PR
|
||||
// via the `owner:branch` head filter. This also works for forked PRs,
|
||||
// where `workflow_run.pull_requests` is empty.
|
||||
const headOwner = run.head_repository?.owner?.login;
|
||||
const headBranch = run.head_branch;
|
||||
|
||||
let prRef;
|
||||
if (headOwner && headBranch) {
|
||||
const { data: openPrs } = await github.rest.pulls.list({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
state: 'open',
|
||||
head: `${headOwner}:${headBranch}`,
|
||||
per_page: 100,
|
||||
});
|
||||
prRef = openPrs[0];
|
||||
}
|
||||
|
||||
// Fallback: same-repo PRs may also be resolvable by commit association.
|
||||
if (!prRef) {
|
||||
const { data: associated } = await github.rest.repos.listPullRequestsAssociatedWithCommit({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
commit_sha: run.head_sha,
|
||||
});
|
||||
prRef = associated.find(pr => pr.state === 'open');
|
||||
}
|
||||
|
||||
if (!prRef) {
|
||||
core.info('No open PR associated with this run (possibly closed by PR Quality). Skipping.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch the full PR to get an up-to-date body, base ref, and state.
|
||||
const { data: pr } = await github.rest.pulls.get({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
pull_number: prRef.number,
|
||||
});
|
||||
|
||||
if (pr.state !== 'open') {
|
||||
core.info(`PR #${pr.number} is not open. Skipping.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip PRs opened by owners/members/collaborators — they choose their own base.
|
||||
if (EXEMPT_ASSOCIATIONS.has(pr.author_association)) {
|
||||
core.info(`PR #${pr.number} author association is ${pr.author_association}. Skipping.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip if a maintainer has already changed the base branch manually.
|
||||
const timeline = await github.paginate(github.rest.issues.listEventsForTimeline, {
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: pr.number,
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
const baseChanges = timeline.filter(e => e.event === 'base_ref_changed');
|
||||
for (const change of baseChanges) {
|
||||
const actor = change.actor?.login;
|
||||
if (!actor) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const { data: perm } = await github.rest.repos.getCollaboratorPermissionLevel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
username: actor,
|
||||
});
|
||||
// admin/maintain/write => trusted maintainer.
|
||||
if (['admin', 'maintain', 'write'].includes(perm.permission)) {
|
||||
core.info(`Base branch was changed manually by ${actor} (${perm.permission}). Skipping.`);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
core.info(`Could not resolve permission for ${actor}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse the checked category checkboxes from the PR body.
|
||||
const body = pr.body ?? '';
|
||||
const checked = [];
|
||||
const checkboxRegex = /^\s*-\s*\[([ xX])\]\s*(.+?)\s*$/gm;
|
||||
let match;
|
||||
while ((match = checkboxRegex.exec(body)) !== null) {
|
||||
if (match[1].toLowerCase() === 'x') {
|
||||
checked.push(match[2].toLowerCase());
|
||||
}
|
||||
}
|
||||
|
||||
const includesAny = (labels) => labels.some(label => checked.some(c => c.includes(label)));
|
||||
|
||||
const mainCategories = ['bug fix', 'adding new one click service', 'fixing or updating existing one click service'];
|
||||
const nextCategories = ['improvement', 'new feature'];
|
||||
|
||||
const wantsMain = includesAny(mainCategories);
|
||||
const wantsNext = includesAny(nextCategories);
|
||||
|
||||
if (!wantsMain && !wantsNext) {
|
||||
core.info('No category selected in the PR body. Skipping.');
|
||||
return;
|
||||
}
|
||||
|
||||
// If categories from both groups are checked, prefer next: features and
|
||||
// improvements can only be released from the development branch.
|
||||
const targetBranch = wantsNext ? NEXT_BRANCH : MAIN_BRANCH;
|
||||
|
||||
if (pr.base.ref === targetBranch) {
|
||||
core.info(`PR #${pr.number} already targets ${targetBranch}. Nothing to do.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const previousBranch = pr.base.ref;
|
||||
|
||||
await github.rest.pulls.update({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
pull_number: pr.number,
|
||||
base: targetBranch,
|
||||
});
|
||||
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: pr.number,
|
||||
body: [
|
||||
`Based on the selected category, this PR's base branch was automatically changed from \`${previousBranch}\` to \`${targetBranch}\`.`,
|
||||
'',
|
||||
targetBranch === MAIN_BRANCH
|
||||
? 'Bug fixes and one-click service changes target `main`.'
|
||||
: 'New features and improvements target `next`.',
|
||||
'',
|
||||
'If you believe this is incorrect, please let a maintainer know.',
|
||||
].join('\n'),
|
||||
});
|
||||
|
||||
core.info(`Retargeted PR #${pr.number}: ${previousBranch} -> ${targetBranch}.`);
|
||||
@@ -2,7 +2,7 @@ name: Coolify Helper Image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "v4.x" ]
|
||||
branches: [ "main" ]
|
||||
paths:
|
||||
- .github/workflows/coolify-helper.yml
|
||||
- docker/coolify-helper/Dockerfile
|
||||
@@ -16,8 +16,53 @@ env:
|
||||
DOCKER_REGISTRY: docker.io
|
||||
IMAGE_NAME: "coollabsio/coolify-helper"
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
check-version:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to ${{ env.GITHUB_REGISTRY }}
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.GITHUB_REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Login to ${{ env.DOCKER_REGISTRY }}
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.DOCKER_REGISTRY }}
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Ensure version is not published
|
||||
run: |
|
||||
BASE_VERSION=$(docker run --rm -v "$(pwd):/app" -w /app php:8.2-alpine3.16 php bootstrap/getHelperVersion.php)
|
||||
VERSION="${BASE_VERSION}"
|
||||
for registry in "${DOCKER_REGISTRY}" "${GITHUB_REGISTRY}"; do
|
||||
IMAGE="${registry}/${IMAGE_NAME}:${VERSION}"
|
||||
if output=$(docker buildx imagetools inspect "$IMAGE" 2>&1); then
|
||||
echo "::error::Version $VERSION already exists in $registry"
|
||||
exit 1
|
||||
fi
|
||||
if ! grep -Eqi 'manifest unknown|not found|no such manifest' <<< "$output"; then
|
||||
echo "::error::Could not verify $IMAGE: $output"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
echo "Version $VERSION is available in both registries"
|
||||
|
||||
build-push:
|
||||
needs: check-version
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
@@ -113,4 +158,3 @@ jobs:
|
||||
if: always()
|
||||
with:
|
||||
webhook: ${{ secrets.DISCORD_WEBHOOK_PROD_RELEASE_CHANNEL }}
|
||||
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
name: Release Coolify Stable
|
||||
run-name: ${{ inputs.tag }}
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Existing draft release tag (for example, v4.3.1)
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: coolify-fix-release
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
GITHUB_REGISTRY: ghcr.io
|
||||
DOCKER_REGISTRY: docker.io
|
||||
IMAGE_NAME: coollabsio/coolify
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: write
|
||||
outputs:
|
||||
release_id: ${{ steps.draft.outputs.release_id }}
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
steps:
|
||||
- name: Reject releases outside the production branch
|
||||
if: ${{ github.ref_name != 'main' }}
|
||||
run: |
|
||||
echo "Stable releases must run from main, not ${{ github.ref_name }}."
|
||||
exit 1
|
||||
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Validate version
|
||||
id: version
|
||||
env:
|
||||
TAG_NAME: ${{ inputs.tag }}
|
||||
run: |
|
||||
if [[ ! "${TAG_NAME}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "Unsupported fix release tag: ${TAG_NAME}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
VERSION="${TAG_NAME#v}"
|
||||
CONFIG_VERSION=$(docker run --rm -v "$(pwd):/app" -w /app php:8.2-alpine3.16 php bootstrap/getVersion.php)
|
||||
|
||||
if [[ "${CONFIG_VERSION}" != "${VERSION}" ]]; then
|
||||
echo "Release tag ${VERSION} does not match config version ${CONFIG_VERSION}."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Validate and pin draft release
|
||||
id: draft
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
TAG_NAME: ${{ inputs.tag }}
|
||||
with:
|
||||
script: |
|
||||
const releases = await github.paginate(github.rest.repos.listReleases, {
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
per_page: 100,
|
||||
});
|
||||
const release = releases.find((candidate) => candidate.tag_name === process.env.TAG_NAME);
|
||||
|
||||
if (!release) {
|
||||
core.setFailed(`Create a draft release for ${process.env.TAG_NAME} before running this workflow.`);
|
||||
return;
|
||||
}
|
||||
if (!release.draft) {
|
||||
core.setFailed(`Release ${process.env.TAG_NAME} must still be a draft.`);
|
||||
return;
|
||||
}
|
||||
if (release.prerelease) {
|
||||
core.setFailed(`Fix release ${process.env.TAG_NAME} cannot be marked as a prerelease.`);
|
||||
return;
|
||||
}
|
||||
if (!release.body?.trim()) {
|
||||
core.setFailed(`Draft release ${process.env.TAG_NAME} must contain reviewed release notes.`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.git.getRef({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
ref: `tags/${process.env.TAG_NAME}`,
|
||||
});
|
||||
core.setFailed(`Git tag ${process.env.TAG_NAME} already exists.`);
|
||||
return;
|
||||
} catch (error) {
|
||||
if (error.status !== 404) throw error;
|
||||
}
|
||||
|
||||
await github.rest.repos.updateRelease({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
release_id: release.id,
|
||||
tag_name: process.env.TAG_NAME,
|
||||
target_commitish: context.sha,
|
||||
});
|
||||
core.setOutput('release_id', release.id);
|
||||
|
||||
build:
|
||||
needs: validate
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- arch: amd64
|
||||
platform: linux/amd64
|
||||
runner: ubuntu-24.04
|
||||
- arch: aarch64
|
||||
platform: linux/aarch64
|
||||
runner: ubuntu-24.04-arm
|
||||
runs-on: ${{ matrix.runner }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to ${{ env.GITHUB_REGISTRY }}
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.GITHUB_REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Login to ${{ env.DOCKER_REGISTRY }}
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.DOCKER_REGISTRY }}
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Build and push release image (${{ matrix.arch }})
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: docker/production/Dockerfile
|
||||
platforms: ${{ matrix.platform }}
|
||||
push: true
|
||||
build-args: |
|
||||
COOLIFY_VERSION=${{ needs.validate.outputs.version }}
|
||||
tags: |
|
||||
${{ env.GITHUB_REGISTRY }}/${{ env.IMAGE_NAME }}:release-${{ needs.validate.outputs.version }}-${{ github.sha }}-${{ matrix.arch }}
|
||||
${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME }}:release-${{ needs.validate.outputs.version }}-${{ github.sha }}-${{ matrix.arch }}
|
||||
|
||||
publish:
|
||||
needs: [validate, build]
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
steps:
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to ${{ env.GITHUB_REGISTRY }}
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.GITHUB_REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Login to ${{ env.DOCKER_REGISTRY }}
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.DOCKER_REGISTRY }}
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Publish version and latest on ${{ env.GITHUB_REGISTRY }}
|
||||
env:
|
||||
REGISTRY: ${{ env.GITHUB_REGISTRY }}
|
||||
VERSION: ${{ needs.validate.outputs.version }}
|
||||
run: |
|
||||
IMAGE="${REGISTRY}/${IMAGE_NAME}"
|
||||
SOURCE="release-${VERSION}-${GITHUB_SHA}"
|
||||
docker buildx imagetools create \
|
||||
"${IMAGE}:${SOURCE}-amd64" \
|
||||
"${IMAGE}:${SOURCE}-aarch64" \
|
||||
--tag "${IMAGE}:${VERSION}" \
|
||||
--tag "${IMAGE}:latest"
|
||||
|
||||
- name: Publish version and latest on ${{ env.DOCKER_REGISTRY }}
|
||||
env:
|
||||
REGISTRY: ${{ env.DOCKER_REGISTRY }}
|
||||
VERSION: ${{ needs.validate.outputs.version }}
|
||||
run: |
|
||||
IMAGE="${REGISTRY}/${IMAGE_NAME}"
|
||||
SOURCE="release-${VERSION}-${GITHUB_SHA}"
|
||||
docker buildx imagetools create \
|
||||
"${IMAGE}:${SOURCE}-amd64" \
|
||||
"${IMAGE}:${SOURCE}-aarch64" \
|
||||
--tag "${IMAGE}:${VERSION}" \
|
||||
--tag "${IMAGE}:latest"
|
||||
|
||||
- name: Publish reviewed draft release
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
RELEASE_ID: ${{ needs.validate.outputs.release_id }}
|
||||
TAG_NAME: ${{ inputs.tag }}
|
||||
with:
|
||||
script: |
|
||||
const releaseId = Number(process.env.RELEASE_ID);
|
||||
const { data: release } = await github.rest.repos.getRelease({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
release_id: releaseId,
|
||||
});
|
||||
|
||||
if (release.tag_name !== process.env.TAG_NAME || !release.draft || release.prerelease) {
|
||||
core.setFailed(`Draft release ${process.env.TAG_NAME} changed while the images were building.`);
|
||||
return;
|
||||
}
|
||||
if (!release.body?.trim()) {
|
||||
core.setFailed(`Draft release ${process.env.TAG_NAME} no longer contains release notes.`);
|
||||
return;
|
||||
}
|
||||
if (release.target_commitish !== context.sha) {
|
||||
core.setFailed(`Draft release ${process.env.TAG_NAME} no longer targets ${context.sha}.`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.git.getRef({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
ref: `tags/${process.env.TAG_NAME}`,
|
||||
});
|
||||
core.setFailed(`Git tag ${process.env.TAG_NAME} was created while the images were building.`);
|
||||
return;
|
||||
} catch (error) {
|
||||
if (error.status !== 404) throw error;
|
||||
}
|
||||
|
||||
await github.rest.repos.updateRelease({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
release_id: Number(process.env.RELEASE_ID),
|
||||
tag_name: process.env.TAG_NAME,
|
||||
target_commitish: context.sha,
|
||||
draft: false,
|
||||
});
|
||||
+29
-39
@@ -1,16 +1,8 @@
|
||||
name: Production Build (v4)
|
||||
name: Build Coolify (SHA)
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["v4.x"]
|
||||
paths-ignore:
|
||||
- .github/workflows/coolify-helper.yml
|
||||
- .github/workflows/coolify-helper-next.yml
|
||||
- .github/workflows/pr-quality.yaml
|
||||
- docker/coolify-helper/Dockerfile
|
||||
- docker/testing-host/Dockerfile
|
||||
- templates/**
|
||||
- CHANGELOG.md
|
||||
branches: ["main"]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -23,6 +15,8 @@ env:
|
||||
|
||||
jobs:
|
||||
build-push:
|
||||
outputs:
|
||||
short_sha: ${{ steps.version.outputs.short_sha }}
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
@@ -38,6 +32,13 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Resolve internal version
|
||||
id: version
|
||||
run: |
|
||||
BASE_VERSION=$(docker run --rm -v "$(pwd):/app" -w /app php:8.2-alpine3.16 php bootstrap/getVersion.php)
|
||||
echo "version=${BASE_VERSION}-dev.${GITHUB_SHA::9}" >> "$GITHUB_OUTPUT"
|
||||
echo "short_sha=${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Login to ${{ env.GITHUB_REGISTRY }}
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
@@ -52,11 +53,6 @@ jobs:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Get Version
|
||||
id: version
|
||||
run: |
|
||||
echo "VERSION=$(docker run --rm -v "$(pwd):/app" -w /app php:8.2-alpine3.16 php bootstrap/getVersion.php)"|xargs >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Build and Push Image (${{ matrix.arch }})
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
@@ -64,18 +60,16 @@ jobs:
|
||||
file: docker/production/Dockerfile
|
||||
platforms: ${{ matrix.platform }}
|
||||
push: true
|
||||
build-args: |
|
||||
COOLIFY_VERSION=${{ steps.version.outputs.version }}
|
||||
tags: |
|
||||
${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.VERSION }}-${{ matrix.arch }}
|
||||
${{ env.GITHUB_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.VERSION }}-${{ matrix.arch }}
|
||||
${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME }}:sha-${{ steps.version.outputs.short_sha }}-${{ matrix.arch }}
|
||||
${{ env.GITHUB_REGISTRY }}/${{ env.IMAGE_NAME }}:sha-${{ steps.version.outputs.short_sha }}-${{ matrix.arch }}
|
||||
|
||||
merge-manifest:
|
||||
runs-on: ubuntu-24.04
|
||||
needs: build-push
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to ${{ env.GITHUB_REGISTRY }}
|
||||
@@ -92,28 +86,24 @@ jobs:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Get Version
|
||||
id: version
|
||||
run: |
|
||||
echo "VERSION=$(docker run --rm -v "$(pwd):/app" -w /app php:8.2-alpine3.16 php bootstrap/getVersion.php)"|xargs >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Create & publish manifest on ${{ env.GITHUB_REGISTRY }}
|
||||
env:
|
||||
REGISTRY: ${{ env.GITHUB_REGISTRY }}
|
||||
SHA: ${{ needs.build-push.outputs.short_sha }}
|
||||
run: |
|
||||
IMAGE="${REGISTRY}/${IMAGE_NAME}"
|
||||
docker buildx imagetools create \
|
||||
${{ env.GITHUB_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.VERSION }}-amd64 \
|
||||
${{ env.GITHUB_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.VERSION }}-aarch64 \
|
||||
--tag ${{ env.GITHUB_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.VERSION }} \
|
||||
--tag ${{ env.GITHUB_REGISTRY }}/${{ env.IMAGE_NAME }}:latest
|
||||
"${IMAGE}:sha-${SHA}-amd64" \
|
||||
"${IMAGE}:sha-${SHA}-aarch64" \
|
||||
--tag "${IMAGE}:sha-${SHA}"
|
||||
|
||||
- name: Create & publish manifest on ${{ env.DOCKER_REGISTRY }}
|
||||
env:
|
||||
REGISTRY: ${{ env.DOCKER_REGISTRY }}
|
||||
SHA: ${{ needs.build-push.outputs.short_sha }}
|
||||
run: |
|
||||
IMAGE="${REGISTRY}/${IMAGE_NAME}"
|
||||
docker buildx imagetools create \
|
||||
${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.VERSION }}-amd64 \
|
||||
${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.VERSION }}-aarch64 \
|
||||
--tag ${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.VERSION }} \
|
||||
--tag ${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME }}:latest
|
||||
|
||||
- uses: sarisia/actions-status-discord@v1
|
||||
if: always()
|
||||
with:
|
||||
webhook: ${{ secrets.DISCORD_WEBHOOK_PROD_RELEASE_CHANNEL }}
|
||||
"${IMAGE}:sha-${SHA}-amd64" \
|
||||
"${IMAGE}:sha-${SHA}-aarch64" \
|
||||
--tag "${IMAGE}:sha-${SHA}"
|
||||
@@ -3,7 +3,7 @@ name: Staging Build
|
||||
on:
|
||||
push:
|
||||
branches-ignore:
|
||||
- v4.x
|
||||
- main
|
||||
- v3.x
|
||||
- '**v5.x**'
|
||||
paths-ignore:
|
||||
|
||||
@@ -2,7 +2,7 @@ name: Generate Changelog
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ v4.x ]
|
||||
branches: [ main ]
|
||||
paths-ignore:
|
||||
- .github/workflows/coolify-helper.yml
|
||||
- .github/workflows/coolify-helper-next.yml
|
||||
@@ -37,4 +37,4 @@ jobs:
|
||||
git config user.email 'github-actions[bot]@users.noreply.github.com'
|
||||
git add CHANGELOG.md
|
||||
git commit -m "docs: update changelog"
|
||||
git push https://${{ secrets.GITHUB_TOKEN }}@github.com/${GITHUB_REPOSITORY}.git v4.x
|
||||
git push https://${{ secrets.GITHUB_TOKEN }}@github.com/${GITHUB_REPOSITORY}.git HEAD:${GITHUB_REF_NAME}
|
||||
|
||||
@@ -19,13 +19,10 @@ jobs:
|
||||
max-failures: 4
|
||||
|
||||
# PR Branch Checks
|
||||
allowed-target-branches: "next"
|
||||
allowed-target-branches: ""
|
||||
blocked-target-branches: ""
|
||||
allowed-source-branches: ""
|
||||
blocked-source-branches: |
|
||||
main
|
||||
master
|
||||
v4.x
|
||||
blocked-source-branches: ""
|
||||
|
||||
# PR Quality Checks
|
||||
max-negative-reactions: 0
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
name: Sync main to next
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: sync-main-to-next
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
name: Merge main into next
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout next
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
ref: next
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Merge main into next
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
git config user.name 'github-actions[bot]'
|
||||
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
|
||||
git fetch origin main next
|
||||
|
||||
if git merge --no-edit origin/main; then
|
||||
git push origin HEAD:next
|
||||
exit 0
|
||||
fi
|
||||
|
||||
conflicts=$(git diff --name-only --diff-filter=U)
|
||||
git merge --abort
|
||||
|
||||
if [ -z "$conflicts" ]; then
|
||||
echo 'The merge failed without conflicts, so no pull request was created.'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
existing_pr=$(gh pr list --base next --head main --state open --json url --jq '.[0].url')
|
||||
if [ -n "$existing_pr" ]; then
|
||||
echo "A main to next pull request already exists: $existing_pr"
|
||||
else
|
||||
gh pr create \
|
||||
--base next \
|
||||
--head main \
|
||||
--title 'chore: merge main into next' \
|
||||
--body 'This pull request was created automatically because main could not be merged into next without conflicts.'
|
||||
fi
|
||||
|
||||
echo 'main could not be merged into next without conflicts.'
|
||||
exit 1
|
||||
+13
@@ -38,5 +38,18 @@ docker/coolify-terminal/node_modules
|
||||
.DS_Store
|
||||
CHANGELOG.md
|
||||
/.workspaces
|
||||
/.superpowers/
|
||||
/docs/superpowers/plans/
|
||||
tests/Browser/Screenshots
|
||||
tests/v4/Browser/Screenshots
|
||||
ref
|
||||
|
||||
# Local generated Lima configs
|
||||
.dev/bin/
|
||||
.dev/coold-assets/
|
||||
.dev/lima/ssh.config
|
||||
.dev/lima/ssh_key
|
||||
.dev/lima/hosts
|
||||
|
||||
# Multi-instance local Coolify env files (scripts/dev-instances)
|
||||
.dev-instances/
|
||||
|
||||
@@ -8,7 +8,7 @@ Coolify is an open-source, self-hostable PaaS (alternative to Heroku/Netlify/Ver
|
||||
|
||||
## Design Reference
|
||||
|
||||
For UI/UX design specifications, principles, and visual standards, consult `DESIGN.md` in the [coollabsio/architecture](https://github.com/coollabsio/architecture) repo.
|
||||
For UI/UX design specifications, principles, and visual standards, consult the local [`DESIGN.md`](DESIGN.md). It is the source of truth for frontend design work in this repository.
|
||||
|
||||
## Development Environment
|
||||
|
||||
@@ -16,11 +16,38 @@ Docker Compose-based dev setup with services: coolify (app), postgres, redis, so
|
||||
|
||||
```bash
|
||||
# Start dev environment (uses docker-compose.dev.yml)
|
||||
spin up # or: docker compose -f docker-compose.dev.yml up -d
|
||||
spin down # stop services
|
||||
docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d
|
||||
docker compose -f docker-compose.yml -f docker-compose.dev.yml down # stop services
|
||||
|
||||
# Two local Coolify instances (isolated stacks; server transfer / multi-control-plane)
|
||||
./scripts/dev-instances up # a:8000 + b:8001 (uses npm run build for CSS/JS)
|
||||
./scripts/dev-instances up a --with vite # HMR only when starting a single instance
|
||||
./scripts/dev-instances urls
|
||||
./scripts/dev-instances down
|
||||
# Compose: docker-compose.dev-multi.yml Env: .dev-instances/{a,b}.env (gitignored)
|
||||
# Note: dual Vite HMR is unsupported (shared public/hot); multi-instance always uses public/build.
|
||||
```
|
||||
|
||||
The app runs at `localhost:8000` by default. Vite dev server on port 5173.
|
||||
The app runs at `localhost:8000` by default. Instance **b** is on `8001` (db `5433`, redis `6380`, …); see `./scripts/dev-instances`.
|
||||
|
||||
## Testing the Self-Hosted Upgrade Process
|
||||
|
||||
Use the following workflow to test a self-hosted upgrade:
|
||||
|
||||
1. Install the source version with the upgrade script:
|
||||
|
||||
```bash
|
||||
bash upgrade.sh sha-6492d081362c009519481ac70e50873e39ba1861
|
||||
```
|
||||
|
||||
2. Set the current Coolify version and rebuild the cached configuration:
|
||||
|
||||
```bash
|
||||
docker exec -e COOLIFY_VERSION=4.3.0 coolify php artisan config:cache
|
||||
```
|
||||
|
||||
3. In the Coolify UI, click **Check for Updates**.
|
||||
4. Confirm that an upgrade is available, then click **Upgrade** and verify that the upgrade completes successfully.
|
||||
|
||||
## Common Commands
|
||||
|
||||
@@ -114,6 +141,23 @@ function loginAsRoot(): mixed
|
||||
- **Project/Environment** — Organizational hierarchy: Team → Project → Environment → Resources.
|
||||
- **Proxy** — Traefik reverse proxy managed per server.
|
||||
|
||||
### Instance sentinels (`id = 0`)
|
||||
|
||||
Coolify seeds **instance-owned** rows at primary key `0`. That value is a sentinel meaning “this is the Coolify instance itself”, not a normal autoincrement id. Do not migrate, resequence, or “fix” these to a positive id.
|
||||
|
||||
| Record | Model / lookup | Meaning |
|
||||
|---|---|---|
|
||||
| Root team | `Team::find(0)`, `team_id === 0` | Instance / root team. Cloud billing and many skip-checks exempt `team_id === 0`. |
|
||||
| Localhost server | `Server::find(0)` / `findOrFail(0)` | The machine running Coolify. Upgrades, instance backups, and docker inspect target this server. |
|
||||
| Instance settings | `InstanceSettings` with `id = 0` | Singleton settings row. Tests must seed `InstanceSettings::create(['id' => 0])` (or `forceCreate`). |
|
||||
| Instance Postgres | `StandalonePostgresql` `id = 0`, name `coolify-db` | Coolify’s own database. UI treats `database_id === 0` as the instance DB (e.g. hide delete on backup screens). |
|
||||
| Local docker dest | `StandaloneDocker` `id = 0` | Destination on the localhost server (`destination_id = 0`). |
|
||||
| Root user / default GitHub App | seeders | First-install defaults. |
|
||||
|
||||
**Do not assign `id = 0` to new or non-instance rows.** In particular, `ScheduledDatabaseBackup` and `ScheduledTask` are ordinary schedules. Legacy installs may still have a `coolify-db` backup at `id = 0`; resolve that backup via the `coolify-db` relation / uuid, not `ScheduledDatabaseBackup::find(0)`.
|
||||
|
||||
`0` is a PHP/Eloquent landmine (`empty(0)` is true; keyset pagination `where('id', '>', $cursor)` starting at `0` skips the row). Queries that page by id must include `id = 0` on the first page (no lower bound, or cursor `< 0`). Prefer `chunkById()` over a hand-rolled `id > 0` cursor.
|
||||
|
||||
### Frontend
|
||||
- Livewire 3 components with Alpine.js for client-side interactivity
|
||||
- Blade templates in `resources/views/livewire/`
|
||||
@@ -135,12 +179,13 @@ function loginAsRoot(): mixed
|
||||
- Run `vendor/bin/pint --dirty --format agent` before finalizing changes
|
||||
- Every change must have tests — write or update tests, then run them. For bug fixes, follow TDD: write a failing test first, then fix the bug (see Test Enforcement below)
|
||||
- Check sibling files for conventions before creating new files
|
||||
- When adding remote shell commands, account for servers using non-root SSH users: commands pass through `parseCommandsByLineForSudo()`, so test pipelines, redirects, substitutions, and `sh -c`/`bash -c` scripts with the non-root sudo parser.
|
||||
|
||||
## Git Workflow
|
||||
|
||||
- Main branch: `v4.x`
|
||||
- Production branch: `main`
|
||||
- Development branch: `next`
|
||||
- PRs should target `v4.x`
|
||||
- Fix PRs should target the current production branch; feature PRs should target `next`
|
||||
|
||||
<laravel-boost-guidelines>
|
||||
=== foundation rules ===
|
||||
@@ -167,7 +212,6 @@ This application is a Laravel application and its main Laravel ecosystems packag
|
||||
- laravel/boost (BOOST) - v2
|
||||
- laravel/dusk (DUSK) - v8
|
||||
- laravel/pint (PINT) - v1
|
||||
- laravel/telescope (TELESCOPE) - v5
|
||||
- pestphp/pest (PEST) - v4
|
||||
- phpunit/phpunit (PHPUNIT) - v12
|
||||
- rector/rector (RECTOR) - v2
|
||||
|
||||
+14
-5
@@ -32,9 +32,7 @@ Coolify is currently at v4. While v4 is stable, it has some limitations, includi
|
||||
- A more complex user experience
|
||||
- Other smaller issues that need refinement
|
||||
|
||||
These limitations will be addressed in Coolify v5, which is in the planning stage. Because of this, major features, architectural changes, or significant UI changes will not be accepted for v4 at this stage.
|
||||
|
||||
We welcome contributions that help stabilize v4 for a bug free experience.
|
||||
These limitations will be addressed over time. Fixes and small improvements are accepted on the production line. New features and larger changes require prior discussion and must go through the development line.
|
||||
|
||||
|
||||
## What Makes a Strong Contribution
|
||||
@@ -188,8 +186,19 @@ If maintainers cannot reproduce working behavior, the PR will be closed without
|
||||
- GitHub will auto-populate the PR template
|
||||
- The contributor agreement in PR description must remain intact
|
||||
- Pull requests without the contributor agreement will be closed
|
||||
- All pull requests must target the `next` branch
|
||||
- PRs targeting other branches will be closed without review
|
||||
|
||||
Choose the branch based on the type of change:
|
||||
|
||||
| Change | Start from | Pull request target |
|
||||
| --- | --- | --- |
|
||||
| Fixes and small improvements | `main` | `main` |
|
||||
| Security fixes | `main` | `main` |
|
||||
| New features and larger changes | `next` | `next` |
|
||||
|
||||
- For a fix, branch from `main` and target `main`.
|
||||
- For a feature, branch from `next` and target `next`.
|
||||
- If a fix is discovered while developing a feature, submit it separately to `main`. Maintainers will merge `main` into `next` so the fix is included there too.
|
||||
- Pull requests targeting the wrong branch may be closed or asked to retarget.
|
||||
|
||||
|
||||
## FAQ
|
||||
|
||||
@@ -0,0 +1,747 @@
|
||||
# Coolify UI design system
|
||||
|
||||
This document defines Coolify's UI design system for its Livewire + Blade +
|
||||
Alpine + Tailwind v4 frontend. The visual system covers the global shell,
|
||||
project and environment pages, application navigation, settings surfaces,
|
||||
tables, modals, toasts, terminals, and metrics.
|
||||
|
||||
Use this file as the source of truth for frontend design work. Update it in the
|
||||
same change whenever a new shared visual pattern or component is introduced.
|
||||
|
||||
Onboarding validation and live server validation checkpoints share
|
||||
`<x-checkpoint-item>` (idle / pending / running / success / error) inside a
|
||||
compact divided list, not legacy green check SVGs or fixed-width status rows.
|
||||
|
||||
> **Maintainer rules**
|
||||
>
|
||||
> - Keep the work frontend-focused unless existing data must be exposed to the
|
||||
> view.
|
||||
> - Preserve routes, Livewire bindings, permissions, confirmations, and working
|
||||
> interactions while changing layout and presentation.
|
||||
> - Add or update tests when a UI change affects behavior. Follow the testing
|
||||
> requirements in `AGENTS.md`.
|
||||
> - Validate Blade with `docker exec coolify php artisan view:cache`, then clear
|
||||
> it with `docker exec coolify php artisan view:clear`.
|
||||
> - Build frontend assets in the Vite container with
|
||||
> `docker exec coolify-vite npm run build`.
|
||||
> - Use existing components before adding another styling abstraction.
|
||||
|
||||
---
|
||||
|
||||
## 1. Visual direction
|
||||
|
||||
The interface is compact and product-focused:
|
||||
|
||||
- near-neutral layered surfaces instead of large bordered boxes;
|
||||
- 13–14px UI typography and 32px controls;
|
||||
- hairline rings instead of heavy borders;
|
||||
- full-width data tables for dense collections;
|
||||
- outline Reicon glyphs through `<x-reicon>`;
|
||||
- the Coolify purple brand accent in light mode;
|
||||
- the readable Coolify yellow accent in dark mode;
|
||||
- solid active-item fills (neutral black/white opacity), not accent gradients;
|
||||
active state is the left accent rail plus a flat selected surface;
|
||||
- sentence-case labels and headings;
|
||||
- never use the em dash (`—`) in UI copy. Prefer a period, colon, comma, or
|
||||
ASCII hyphen (`-`) for empty cells and separators.
|
||||
|
||||
Avoid oversized titles, generic dashboard cards, strong shadows, thick
|
||||
dividers, native browser selects, and isolated colored buttons that do not
|
||||
match the current action styles.
|
||||
|
||||
---
|
||||
|
||||
## 2. Development and cascade notes
|
||||
|
||||
PHP runs in the `coolify` container. The development app is normally available
|
||||
at `http://localhost:8000`, with Vite on port `5173`.
|
||||
|
||||
`resources/css/app.css` still contains unlayered global element rules for
|
||||
headings, labels, and tables. Tailwind utilities are layered, so the
|
||||
unlayered rules can win unexpectedly.
|
||||
|
||||
The settings and dense-surface CSS therefore lives as plain unlayered CSS near
|
||||
the end of `resources/css/app.css`, beginning at:
|
||||
|
||||
```css
|
||||
/* Coollabs layer-card settings surfaces */
|
||||
```
|
||||
|
||||
Important consequences:
|
||||
|
||||
- scope settings forms with `.application-settings-form` or
|
||||
`.application-settings-workspace`;
|
||||
- add shared surface overrides to the unlayered block instead of stacking
|
||||
`!important` utilities;
|
||||
- listbox panels require ancestors with `overflow: visible`;
|
||||
- anchored cards use `scroll-margin-top: 7rem` to clear both fixed navigation
|
||||
layers;
|
||||
- modal shells reuse the layer-card classes but keep content-width sizing on
|
||||
desktop;
|
||||
- Alpine code inside quoted Blade attributes must not introduce conflicting
|
||||
quote characters.
|
||||
|
||||
---
|
||||
|
||||
## 3. Tokens and color behavior
|
||||
|
||||
The surface ladder is defined in `resources/css/app.css`.
|
||||
|
||||
| Token | Light | Dark | Use |
|
||||
|---|---|---|---|
|
||||
| `--coollabs-canvas` | near white | 10% neutral | page canvas |
|
||||
| `--coollabs-elevated` | 98% neutral | 15% neutral | shells and card headers |
|
||||
| `--coollabs-base` | white | 17% neutral | nested card bodies |
|
||||
| `--coollabs-recessed` | 96% neutral | 20% neutral | inputs and listboxes |
|
||||
| `--coollabs-fill` | 92.2% neutral | 26.9% neutral | dividers and passive fills |
|
||||
| `--coollabs-line` | translucent dark | 32% neutral | control borders |
|
||||
| `--coollabs-hairline` | 93.5% neutral | 26.9% neutral | shell rings |
|
||||
| `--coollabs-subtle` | 55.6% neutral | 70.8% neutral | labels and muted titles |
|
||||
|
||||
Accent behavior is intentionally theme-aware:
|
||||
|
||||
- **Light mode:** Coolify purple (`coollabs`) for active controls, focus,
|
||||
primary actions, and navigation accents.
|
||||
- **Dark mode:** Coolify yellow (`warning`) for the same states because the
|
||||
original purple did not provide sufficient text and ring contrast.
|
||||
|
||||
Do not hard-code blue focus rings or leave yellow accent utilities active in
|
||||
light mode. Primary action patterns should normally follow:
|
||||
|
||||
```html
|
||||
bg-coollabs/10 text-coollabs ring-coollabs/25
|
||||
dark:bg-warning/15 dark:text-warning dark:ring-warning/25
|
||||
```
|
||||
|
||||
The filled top-level action/tab treatment uses the same palette at a restrained
|
||||
opacity rather than a fully saturated fill.
|
||||
|
||||
---
|
||||
|
||||
## 4. Page shells and navigation
|
||||
|
||||
### Global shell
|
||||
|
||||
- Main sidebar groups are compact, use outline Reicons, and keep a 32px row
|
||||
height.
|
||||
- Active sidebar rows are rounded pills (`rounded-md`) with an accent rail on
|
||||
the left plus a solid neutral selected fill (`bg-black/5` light,
|
||||
`bg-white/6` dark). Hover rows use the same radius. Do not use accent-tinted
|
||||
gradients on nav rows; yellow washes look muddy on dark UI.
|
||||
- Nested items use a thin guide line with a visible active segment, not a thick
|
||||
box border.
|
||||
- The update badge sits on the version row and uses a tiny fully rounded
|
||||
primary-action pill.
|
||||
|
||||
### Layer-2 navigation
|
||||
|
||||
Application and server pages use the same fixed second navigation layer
|
||||
directly below the global topbar. Do not keep a large in-flow resource heading
|
||||
or legacy `.navbar-main` tabs on one resource type while using the compact
|
||||
layer-2 bar on another. Active tabs are a light brand fill:
|
||||
|
||||
- purple tint in light mode;
|
||||
- yellow tint in dark mode;
|
||||
- no fully saturated tab background.
|
||||
|
||||
Keep route-derived active state in Blade/Livewire. Do not rely only on Alpine
|
||||
state because it can disappear after polling or a Livewire morph.
|
||||
|
||||
The global topbar owns the current resource identity and its compact status
|
||||
badges. Layer 2 owns route tabs, resource links, and contextual action buttons
|
||||
only. If a resource is missing from `x-top-breadcrumb`, extend the global
|
||||
topbar instead of repeating its name or status summary in layer 2. Mobile
|
||||
resource navigation may repeat this context because the desktop global topbar
|
||||
is hidden there.
|
||||
|
||||
Desktop resource lifecycle actions dock in `#resource-action-hud-slot` and
|
||||
use `<x-resource-heading-overflow>`. Show primary actions (Deploy, Redeploy,
|
||||
Restart, Stop) as sibling header buttons. Collapse that group into an Actions
|
||||
dropdown only when the remaining top-bar width cannot fit them (breadcrumb
|
||||
keeps a 200px floor). Infrequent operations live in a separate Advanced
|
||||
dropdown with the grid icon: force restart / force deploy / force cleanup
|
||||
on services, and Traefik dashboard / refresh proxy status on servers. Place
|
||||
Advanced immediately after Links, or first in the action cluster when there
|
||||
is no Links control. Application Deploy is a dropdown with Deploy and
|
||||
Deploy (without cache). A running service Restart control is a dropdown with
|
||||
Restart current version and Pull latest and restart. Mobile
|
||||
headings keep a full-width Actions dropdown because the desktop HUD is hidden
|
||||
below `xl`. Do not hide primary actions behind a menu on a wide desktop. Links
|
||||
stay a separate dropdown because the URL list is unbounded.
|
||||
|
||||
Only add layer-2 tabs when they represent real sibling routes inside one
|
||||
context. Never repeat main-sidebar destinations such as Dashboard, Projects,
|
||||
Terminal, Servers, Sources, Destinations, or Storage as a second tab row. A
|
||||
single collection page does not need a tab just to fill the bar; keep its
|
||||
primary action in the page header instead. When tabs are useful, their left edge
|
||||
uses the same compact `pl-2` alignment as application navigation rather than
|
||||
the content container's wide horizontal padding.
|
||||
|
||||
A layer-2 tab must be active on the page that renders it. A bar whose only tab
|
||||
points at a different route reads as broken navigation, so project and
|
||||
environment pages (`project.show`, `project.edit`, `project.environment.edit`,
|
||||
`project.clone-me`) carry a plain page header with a 24px title and a 13px
|
||||
muted summary instead of a bar. The environment identity and the way back to
|
||||
its resources already live in `x-top-breadcrumb`; do not restate them in a
|
||||
sub-header.
|
||||
|
||||
The dashboard is a compact overview, not a metrics wall. Use two full-width
|
||||
sections that follow the projects-page grid pattern: projects first, then
|
||||
servers. Keep one `New` action in the page header and let its modal choose the
|
||||
resource type. Place active deployments above the resource grids as a compact,
|
||||
live-updating table rather than a metric card. Communicate server health with
|
||||
the shared status badge.
|
||||
|
||||
### Top-level dashboard destinations
|
||||
|
||||
Every page opened directly from the main sidebar uses the same compact content
|
||||
shell:
|
||||
|
||||
- 24px page title and a 13px muted summary;
|
||||
- the primary action at the top right using the restrained brand fill;
|
||||
- no legacy `coolbox`, `.navbar-main`, or oversized subtitle block;
|
||||
- four-column compact cards for small browsable collections;
|
||||
- a dense table instead of cards when the collection is expected to grow;
|
||||
- `x-empty` anatomy for empty states;
|
||||
- `x-status-badge` for state and `x-reicon` for all interface icons.
|
||||
|
||||
Collection cards are `min-h-28` or `min-h-32`, use a 32px icon tile, and keep
|
||||
secondary metadata at 11px. They must not grow into dashboard-sized summary
|
||||
cards. Sources, destinations, S3 storage, private keys, and shared-variable
|
||||
scopes use this pattern.
|
||||
|
||||
Top-level settings families such as Team, Notifications, Keys & Tokens, and
|
||||
instance Settings use a compact header followed by a small route-derived tab
|
||||
strip. The active tab uses the same purple-light/yellow-dark tint as resource
|
||||
tabs. Do not nest `<button>` elements inside tab links.
|
||||
|
||||
### Route-family consistency
|
||||
|
||||
Treat every route family as one cohesive experience rather than styling only
|
||||
its index or most visible route:
|
||||
|
||||
- index, create, detail, settings, logs, metrics, backup, execution, and danger
|
||||
routes must share the same navigation hierarchy and surface language;
|
||||
- main-sidebar collection routes use the global shell without duplicating those
|
||||
destinations in a layer-2 tab row;
|
||||
- resource detail families use resource identity and status in the global
|
||||
topbar, route tabs and actions in layer 2, and the grouped settings sidebar
|
||||
only for the third level;
|
||||
- create and edit routes stay inside the same layer-2 family instead of
|
||||
falling back to an isolated legacy page;
|
||||
- reusable partials, empty states, confirmation flows, and row editors must be
|
||||
updated with the page that exposes them;
|
||||
- audit the whole family for native selects, legacy heading blocks, old Save
|
||||
buttons, old status chips, and `coolbox`/`navbar-main`/`sub-menu-wrapper`
|
||||
to keep the family consistent.
|
||||
|
||||
Do not leave a sibling route using old tabs, a large in-flow title, a browser
|
||||
select, or a different modal anatomy.
|
||||
|
||||
The New Resource page keeps its filter controls in the top layer card, then
|
||||
renders Applications, Databases, and Services as separate layer-card sections.
|
||||
Do not leave category headings and resource grids floating as uncontained
|
||||
content below the filter card.
|
||||
|
||||
### Settings workspace
|
||||
|
||||
Application and server configuration pages use the same 210px grouped,
|
||||
icon-led sidebar and a full-width content column. The workspace is capped at
|
||||
1180px, the sidebar becomes sticky at `xl`, and the sidebar label and first
|
||||
content card start on the same visual line. Do not use the legacy
|
||||
`sub-menu-wrapper`, native mobile page selects, or an in-flow row of top-level
|
||||
tabs. Only show nested section anchors when a page has at least four useful
|
||||
sections.
|
||||
|
||||
The shared workspace grid is:
|
||||
|
||||
```blade
|
||||
<div
|
||||
class="application-settings-workspace mt-8 grid min-w-0 gap-8
|
||||
xl:mt-0 xl:grid-cols-[210px_minmax(0,1fr)] xl:gap-10">
|
||||
<aside class="application-settings-navigation min-w-0 xl:sticky xl:top-26 xl:self-start">
|
||||
...
|
||||
</aside>
|
||||
<div class="min-w-0 xl:mt-3">
|
||||
...
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
Instance Settings constrains both `x-settings.navbar` and the workspace to the
|
||||
same `max-w-[1180px]` shell.
|
||||
|
||||
**Page titles (global):** family H1s (`x-dashboard.navbar` with
|
||||
`titleOnDesktop="false"`, the default) hide at **lg+**, the same breakpoint as
|
||||
the desktop shell (main sidebar + fixed layer-2 tabs). Below `lg` the mobile
|
||||
topbar is used and the page title stays visible. Collection indexes (Servers,
|
||||
Projects, …) always keep their H1; stack title above actions on narrow widths
|
||||
so they never overlap. Resource in-flow names only render below `md` (when the
|
||||
fixed resource tab bar is hidden). Fixed layer-2 spacers must be `lg:h-12` to
|
||||
match the bar height. Do not put the H1 beside the settings sidebar.
|
||||
|
||||
Standard content stack:
|
||||
|
||||
```blade
|
||||
<div class="application-settings-workspace flex flex-col gap-6">
|
||||
<x-application.settings-section ... />
|
||||
<x-application.settings-section ... />
|
||||
</div>
|
||||
```
|
||||
|
||||
The current cross-page section gap is `gap-6`. Do not introduce extra top
|
||||
padding on an individual page unless its toolbar is intentionally separated
|
||||
from the first card.
|
||||
|
||||
Use a flex or grid stack with `gap-6`; do not use `space-y-*` between layer
|
||||
cards. The layer-card root intentionally resets its own margin, so margin-based
|
||||
spacing utilities can silently collapse.
|
||||
|
||||
---
|
||||
|
||||
## 5. Layer cards
|
||||
|
||||
Use `resources/views/components/application/settings-section.blade.php`.
|
||||
Older manual shells may use `.application-settings-section-header` and
|
||||
`.application-settings-section-body`; both must retain the same padded,
|
||||
action-aligned anatomy as the component. Use the component for new work and
|
||||
replace a manual shell when modifying it instead of creating another variant.
|
||||
|
||||
```blade
|
||||
<x-application.settings-section
|
||||
id="public-access-section"
|
||||
title="Public access"
|
||||
helper="How this section affects the resource.">
|
||||
<x-slot:actions>
|
||||
<x-forms.button>Action</x-forms.button>
|
||||
</x-slot:actions>
|
||||
|
||||
...
|
||||
</x-application.settings-section>
|
||||
```
|
||||
|
||||
Anatomy:
|
||||
|
||||
- 8px shell radius;
|
||||
- elevated header strip;
|
||||
- no divider below the header;
|
||||
- nested base-color body with its own fill ring;
|
||||
- 16px body padding;
|
||||
- optional `flush` mode for full-bleed tables;
|
||||
- card-level actions belong in the header slot.
|
||||
|
||||
Header actions use an 8px top/right inset while the title keeps its 16px left
|
||||
inset. Do not leave a larger empty strip between the final action and the
|
||||
card's top-right corner.
|
||||
|
||||
Do not split one collection into a summary card followed by a table or log
|
||||
card. Keep its status/action in the header, its view switcher or toolbar at the
|
||||
top of a flush body, and its data in that same layer card. Repeated file
|
||||
editors are the opposite case: each file gets its own titled layer card so its
|
||||
content and actions remain clearly associated.
|
||||
|
||||
### Nested radii
|
||||
|
||||
Concentric boxes must follow:
|
||||
|
||||
```text
|
||||
outer radius = inner radius + visible inset
|
||||
```
|
||||
|
||||
Examples:
|
||||
|
||||
- a 6px tab or listbox option inside 4px padding uses a 10px outer well;
|
||||
- an 8px button inside the unsaved pill's 8px padding uses a 16px outer pill.
|
||||
|
||||
Do not give visibly inset parent and child boxes the same radius. Flush or
|
||||
edge-to-edge children are exempt because there is no visible inset to add.
|
||||
|
||||
Use an empty state when the section has no usable controls:
|
||||
|
||||
```blade
|
||||
<x-empty size="sm" title="Nothing here" description="Explain what enables it.">
|
||||
<x-slot:icon>
|
||||
<x-reicon name="layers" class="size-8" />
|
||||
</x-slot:icon>
|
||||
</x-empty>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Controls
|
||||
|
||||
All normal controls are 32px high with an 8px radius.
|
||||
|
||||
### Field grids
|
||||
|
||||
The grid must match the controls visible in the current state:
|
||||
|
||||
- two visible peer controls use two columns, not a three-column grid with an
|
||||
empty track;
|
||||
- three visible peer controls may use three columns when their content stays
|
||||
readable;
|
||||
- conditional fields remain in the same grid when they are part of that field
|
||||
group, so a URL or text input does not become wider than its peer column;
|
||||
- collapse to one column at smaller breakpoints.
|
||||
|
||||
Do not pick a column count from the maximum possible state if the normal state
|
||||
shows fewer controls.
|
||||
|
||||
### Inputs
|
||||
|
||||
Use `x-forms.input` and `x-forms.textarea`. Fields need visible vertical spacing
|
||||
between the label and control. Password visibility uses the outline Reicon
|
||||
`eye`/`eye-off` treatment from the shared input component.
|
||||
|
||||
### Dropdowns
|
||||
|
||||
Do not use native `<select>` on application routes, including mobile fallbacks.
|
||||
Use:
|
||||
|
||||
```blade
|
||||
<x-forms.listbox id="property" label="Setting" :options="[
|
||||
['value' => true, 'label' => 'Enabled'],
|
||||
['value' => false, 'label' => 'Disabled'],
|
||||
]" onChange="instantSave" />
|
||||
```
|
||||
|
||||
Boolean checkboxes should normally become descriptive two-option listboxes.
|
||||
Use `.live` behavior only when the selection needs an immediate server
|
||||
rerender.
|
||||
|
||||
Keep checkboxes for compact permission matrices and multi-select lists. Those
|
||||
controls must use the shared `x-forms.checkbox` anatomy: an 18px rounded custom
|
||||
box, purple checked fill in light mode, yellow checked fill in dark mode, and a
|
||||
high-contrast check mark. Never expose the browser or Tailwind Forms default
|
||||
checkbox on application pages.
|
||||
|
||||
The popup panel uses a 10px radius around 6px options with a 4px inset. Keep
|
||||
the option content left-aligned and size the panel to its content or trigger;
|
||||
do not create an unnecessarily wide menu.
|
||||
|
||||
Toolbar filter and sort buttons keep static labels (`Filter`, `Sort`). The
|
||||
selected option is indicated inside the menu, not repeated on the trigger.
|
||||
|
||||
#### Livewire dropdown state synchronization
|
||||
|
||||
Instant-save listboxes must not flash back to an older value while Livewire is
|
||||
saving or morphing the DOM. Treat the Alpine selection as the current visual
|
||||
state until its request finishes:
|
||||
|
||||
- await the Livewire change handler and prevent overlapping selections while
|
||||
it is running;
|
||||
- when a client-managed listbox can be rerendered by an unrelated or stale
|
||||
Livewire response, use the listbox's `preserveValue` option so the morph does
|
||||
not replace its newer Alpine value;
|
||||
- scope `preserveValue` to controls whose value is owned by that interaction;
|
||||
do not use it when external server events must replace the displayed value;
|
||||
- after saving through a related model, refresh the parent component's loaded
|
||||
relationship before rendering the response. A database write alone does not
|
||||
update an already-loaded Eloquent collection;
|
||||
- use stable `wire:key` values for rows containing listboxes. Do not include the
|
||||
selected value in the key, because recreating the Alpine component causes a
|
||||
visible reset;
|
||||
- remember that a portalled options panel is teleported outside its visual
|
||||
wrapper. Guard selection in the Alpine handler itself rather than relying
|
||||
only on `pointer-events` or a disabled wrapper.
|
||||
|
||||
The failure mode to avoid is: selection B is shown optimistically, selection A
|
||||
is chosen next, the response for B morphs the listbox back to B, then the later
|
||||
response finally shows A. The control should remain on the newest accepted
|
||||
selection throughout the save sequence.
|
||||
|
||||
#### Multi-select filter dropdowns
|
||||
|
||||
Toolbar filters that can combine criteria use one multi-select listbox rather
|
||||
than separate dropdowns or a single selected value. Follow the deployment
|
||||
history filter in
|
||||
`resources/views/livewire/project/application/deployment/index.blade.php`:
|
||||
|
||||
- set `aria-multiselectable="true"` on the listbox;
|
||||
- group related options under compact uppercase labels;
|
||||
- keep the dropdown open while options are toggled;
|
||||
- use the shared 16px custom checkbox treatment: purple checked fill in light
|
||||
mode, yellow checked fill in dark mode, and a high-contrast check mark;
|
||||
- show the number of active selections in a small count pill on the static
|
||||
`Filter` trigger;
|
||||
- combine selections within one group with OR logic and combine different
|
||||
groups with AND logic;
|
||||
- constrain only the options area with `max-h-80 overflow-y-auto`;
|
||||
- place a persistent `Reset filters` action in a separate footer below the
|
||||
scrollable options, divided by a top border;
|
||||
- disable the reset action when no filter is active, and close the dropdown
|
||||
after resetting.
|
||||
|
||||
Do not represent the empty state as a selectable `All` option. The footer reset
|
||||
action is the single way to return the multi-select to its unfiltered state.
|
||||
|
||||
### Standard table controls
|
||||
|
||||
Dense tables use the shared `x-table.*` components so search, filters, sorting,
|
||||
and backend loading states remain visually and behaviorally consistent:
|
||||
|
||||
- `<x-table.toolbar>` owns the responsive search-left/actions-right layout;
|
||||
- `<x-table.search>` owns the search icon, optional loading indicator, clear
|
||||
action, sizing, and input anatomy;
|
||||
- `<x-table.filter>` owns the static Filter trigger, active-count pill,
|
||||
multi-select panel, scrollable options area, and Reset filters footer;
|
||||
- `<x-table.sort>` owns the static Sort trigger and single-select panel;
|
||||
- `<x-table.loading>` overlays only the changing table data for backend search,
|
||||
filter, sort, and pagination requests.
|
||||
|
||||
Tables continue to own their filter options, sort choices, headers, rows,
|
||||
queries, permissions, and empty states. Backend-filtered or paginated tables
|
||||
must use `x-table.loading`; frontend-only Alpine tables reuse the same toolbar
|
||||
and control anatomy but do not show an artificial loading state.
|
||||
|
||||
### Buttons
|
||||
|
||||
- neutral actions use the shared `.button`;
|
||||
- primary actions use the theme-aware purple/yellow tint;
|
||||
- destructive actions use the existing error treatment;
|
||||
- use outline Reicons where a matching glyph exists;
|
||||
- avoid raw browser-default buttons and old dark-mode purple fills.
|
||||
|
||||
### Unsaved changes
|
||||
|
||||
`resources/views/components/unsaved-bar.blade.php` is a compact floating
|
||||
bottom-center pill. It contains:
|
||||
|
||||
- “You have changes that haven't been saved yet.”
|
||||
- a subtle Reset action;
|
||||
- a theme-aware Save changes button matching the tab accent.
|
||||
|
||||
On small viewports the pill is inset (`inset-x-3`) and stacks: full label on
|
||||
the first line, Reset / Save on the second (right-aligned). From `sm` up it
|
||||
returns to the centered single-row nowrap pill.
|
||||
|
||||
Do not restore the old full-width footer.
|
||||
|
||||
Deferred fields in one Livewire component use one floating unsaved bar and one
|
||||
submit action. Do not add a separate “Save configuration” button to every
|
||||
card. Selectors that are safe to persist independently should use the existing
|
||||
instant-save pattern.
|
||||
|
||||
---
|
||||
|
||||
## 7. Dense tables
|
||||
|
||||
Collections with many rows should use the Cloudflare-inspired table pattern:
|
||||
|
||||
- toolbar above the table;
|
||||
- search on the left;
|
||||
- filters, sort, view toggles, and Add on the right;
|
||||
- 40px header row and roughly 48px data rows;
|
||||
- subtle row hover;
|
||||
- plain text or the shared status badge rather than large colored chips;
|
||||
- compact action at the far right;
|
||||
- no separate layer card for each item.
|
||||
|
||||
Do not add a summary card above a table when it only repeats the row count,
|
||||
current page, or refresh interval. Keep counts and pagination in the footer.
|
||||
Background polling stays silent unless its state is actionable; do not add a
|
||||
“Live updates” badge just to explain that a table refreshes. Filters only
|
||||
render meaningful values; use the shared listbox instead of a number input or
|
||||
browser-native control.
|
||||
|
||||
The footer is always inside the table shell:
|
||||
|
||||
- `Showing X–Y of Z` on the left;
|
||||
- first, previous, current page, next, and last controls on the right.
|
||||
|
||||
Hide the entire pagination footer when there is only one page (`totalPages > 1`).
|
||||
A lone “1–2 of 2” bar with disabled controls adds noise and is unnecessary.
|
||||
|
||||
Use `x-status-badge` for resource and execution state. It is a small neutral
|
||||
pill with a semantic dot, not a full colored rectangle.
|
||||
|
||||
Relevant classes:
|
||||
|
||||
- `.data-table`
|
||||
- `.data-table-header`
|
||||
- `.data-table-row`
|
||||
- `.table-badge`
|
||||
|
||||
Create a page-specific grid class when columns differ. Add responsive rules
|
||||
that hide secondary columns before allowing horizontal overflow.
|
||||
|
||||
---
|
||||
|
||||
## 8. Modals, confirmations, and toasts
|
||||
|
||||
### Modals
|
||||
|
||||
`x-modal-input` and confirmation dialogs reuse the layer-card shell:
|
||||
|
||||
- compact elevated header;
|
||||
- nested base-color body;
|
||||
- content-width desktop sizing;
|
||||
- shared 32px controls;
|
||||
- no redundant description below a self-explanatory title;
|
||||
- custom listboxes instead of native browser selects;
|
||||
- listbox and dropdown panels must render above the modal body and escape its
|
||||
scroll container. Never clip a panel at the modal boundary or make users
|
||||
scroll the modal to see its options;
|
||||
- when there is not enough viewport space below the trigger, open the panel
|
||||
above it while keeping the panel visually on top of the modal;
|
||||
- right-aligned footer actions below a divider;
|
||||
- compact action buttons, never a submit button stretched by a column layout.
|
||||
|
||||
Edit modals should use the same field layout and option set as their matching
|
||||
create modal.
|
||||
|
||||
### Command palette
|
||||
|
||||
The global search command palette (`livewire:global-search`) is a compact
|
||||
top-anchored overlay:
|
||||
|
||||
- elevated shell with hairline ring and modal shadow (not a heavy floating card);
|
||||
- recessed-neutral header strip with outline search glyph and 14px input;
|
||||
- compact OS-aware mod+K (`⌘K` on macOS, `Ctrl+K` on Windows/Linux) / `/` / `ESC` kbd chips matching the sidebar search trigger;
|
||||
- nested base-color results body with group labels in sentence case;
|
||||
- dense result rows as inset 6px-radius pills (listbox anatomy), not full-bleed
|
||||
bars with global focus rings;
|
||||
- hover uses neutral fill; keyboard focus uses a soft accent wash plus a 2px
|
||||
left rail — never the global `ring-2` / ring-offset treatment;
|
||||
- create rows use a neutral plus tile that only picks up the accent when the
|
||||
row is focused;
|
||||
- type pills and quickcommand chips stay recessed; they tint with the accent
|
||||
only on the focused row;
|
||||
- neutral thin scrollbar inside the results body (not brand-colored);
|
||||
- create-resource modals opened from the palette reuse the standard
|
||||
`application-settings-section` layer-card shell.
|
||||
|
||||
Preserve keyboard navigation (arrow keys, Enter via focused links, Escape to
|
||||
clear then close), `/` and mod+K (⌘K / Ctrl+K by OS) open shortcuts, and the multi-step
|
||||
server → destination → project → environment create flow.
|
||||
|
||||
### Toasts
|
||||
|
||||
`resources/views/components/toast.blade.php` provides the global
|
||||
`window.toast(message, options)` API and Livewire event handling.
|
||||
|
||||
Current toast behavior:
|
||||
|
||||
- compact layered card, maximum width 26rem;
|
||||
- Reicon status tile for success, info, warning, danger, or default;
|
||||
- title plus optional description;
|
||||
- dismiss and copy-details actions;
|
||||
- up to four stacked notifications;
|
||||
- four-second dismissal, paused while hovered;
|
||||
- support for all six screen positions and sanitized custom HTML.
|
||||
|
||||
Do not bring back the old oversized dark rectangle.
|
||||
|
||||
---
|
||||
|
||||
## 9. Terminals, logs, and metrics
|
||||
|
||||
### Terminals
|
||||
|
||||
Application and server browser terminals use the same browser-oriented console
|
||||
shell, theme picker, compact header controls, and outline `browser-terminal`
|
||||
Reicon. Hide a container switcher when only one container exists.
|
||||
|
||||
The themed console shell belongs to an open session. Before a target is
|
||||
selected, the global Terminal page stays a normal top-level destination: a
|
||||
full-width layer card titled `Start a terminal session`, its filter input in
|
||||
the card header actions, and grouped `Servers` / `Containers` rows reusing the
|
||||
command-palette row classes. Do not render an empty full-height console canvas
|
||||
just to host the target picker, and do not offer the console theme selector
|
||||
before a session owns that canvas. Rows show the target name, a muted server
|
||||
column that only appears when the team has more than one server, and the shared
|
||||
chevron. Group headers stick to the top of the scrolling list and carry a count.
|
||||
|
||||
### Logs
|
||||
|
||||
Runtime and deployment logs should feel like a clean terminal surface:
|
||||
|
||||
- keep a single log stream inside one layer card instead of adding an
|
||||
introductory card above it;
|
||||
- one compact toolbar;
|
||||
- a recessed monospace log viewport;
|
||||
- search and line-count controls aligned with icon actions;
|
||||
- clear live/follow state;
|
||||
- fullscreen support without changing the control language;
|
||||
- custom listbox-style menus instead of browser dropdowns.
|
||||
|
||||
### Metrics
|
||||
|
||||
Metrics pages use separate layer cards for range selection, CPU, and memory.
|
||||
Charts follow the application metrics implementation:
|
||||
|
||||
- 240px area chart;
|
||||
- smooth 2px stroke and restrained gradient fill;
|
||||
- dashed neutral grid;
|
||||
- no ApexCharts toolbar;
|
||||
- tooltip positioned at the hovered point;
|
||||
- UTC on both axes and tooltip;
|
||||
- 20% headroom above observed values;
|
||||
- downsample long time ranges before rendering.
|
||||
|
||||
Only add a metric if Sentinel exposes historical data for it. Current Sentinel
|
||||
history endpoints store CPU and memory. Root filesystem usage is included in
|
||||
the periodic push payload for threshold notifications, but it is not stored as
|
||||
a historical Sentinel metric and has no history endpoint, so it cannot power a
|
||||
disk-usage graph yet.
|
||||
|
||||
---
|
||||
|
||||
## 10. Current reference surfaces
|
||||
|
||||
Use these as implementation references:
|
||||
|
||||
| Surface | Reference |
|
||||
|---|---|
|
||||
| Dashboard overview | `resources/views/livewire/dashboard.blade.php` |
|
||||
| Top-level collection cards | `resources/views/livewire/project/index.blade.php`, `resources/views/source/all.blade.php` |
|
||||
| Top-level family tabs | `resources/views/components/team/navbar.blade.php`, `resources/views/components/notification/navbar.blade.php` |
|
||||
| General settings and form anatomy | `resources/views/livewire/project/application/general.blade.php` |
|
||||
| Advanced settings | `resources/views/livewire/project/application/advanced.blade.php` |
|
||||
| Fixed layer-2 resource navigation | `resources/views/livewire/project/application/heading.blade.php`, `resources/views/livewire/server/navbar.blade.php` |
|
||||
| Grouped settings sidebar | `resources/views/livewire/project/application/configuration.blade.php`, `resources/views/components/server/sidebar.blade.php` |
|
||||
| Dense environment table and footer | `resources/views/livewire/project/shared/environment-variable/all.blade.php` |
|
||||
| Standard table toolbar controls | `resources/views/components/table/*` |
|
||||
| Application metrics charts | `resources/views/livewire/project/shared/metrics.blade.php` |
|
||||
| Browser terminal workspace | `resources/views/livewire/terminal/index.blade.php` |
|
||||
| Layer card | `resources/views/components/application/settings-section.blade.php` |
|
||||
| Custom dropdown | `resources/views/components/forms/listbox.blade.php` |
|
||||
| Empty state | `resources/views/components/empty.blade.php` |
|
||||
| Status pill | `resources/views/components/status-badge.blade.php` |
|
||||
| Floating save pill | `resources/views/components/unsaved-bar.blade.php` |
|
||||
| Global toast | `resources/views/components/toast.blade.php` |
|
||||
| Command palette / global search | `resources/views/livewire/global-search.blade.php` |
|
||||
| Outline icons | `resources/views/components/reicon.blade.php` |
|
||||
| Shared styling | `resources/css/app.css`, `resources/css/utilities.css` |
|
||||
| HTTP error pages | `resources/views/components/error-page.blade.php`, `resources/views/errors/*` |
|
||||
|
||||
HTTP error pages (400, 401, 402, 403, 404, 419, 429, 500, 503) use the shared
|
||||
`<x-error-page>` component on the public auth-style canvas: theme-aware status
|
||||
code, compact title and muted description, neutral `.button` actions, and an
|
||||
`auth-text-link`-style Contact support link. Keep copy sentence-case and avoid
|
||||
oversized 200px status numbers.
|
||||
|
||||
---
|
||||
|
||||
## 11. UI implementation checklist
|
||||
|
||||
1. Inventory every route and reusable partial in the family before editing.
|
||||
2. Read the current Blade and Livewire class before changing presentation.
|
||||
3. Preserve every existing action, authorization check, loading state, and
|
||||
confirmation.
|
||||
4. Add the correct dual navigation and scoped workspace/form class.
|
||||
5. Convert meaningful groups to layer cards and use `gap-6`.
|
||||
6. Make the responsive column count match the controls visible in every state.
|
||||
7. Replace native selects and checkbox-style configuration with listboxes.
|
||||
8. Use one save model per component: instant-save or one floating dirty bar.
|
||||
9. Check nested radii using `outer = inner + inset`.
|
||||
10. Keep modal descriptions purposeful and footer actions compact/right-aligned.
|
||||
11. Use tables for dense collections and cards for forms or summaries.
|
||||
12. Use `x-status-badge`, `x-empty`, and `x-reicon`.
|
||||
13. Confirm light and dark accent behavior.
|
||||
14. Check fixed-nav anchor offsets and responsive stacking.
|
||||
15. Sweep every sibling route for legacy controls and shells.
|
||||
16. Run `git diff --check`.
|
||||
17. Compile Blade views in the `coolify` container.
|
||||
18. Build assets in `coolify-vite`.
|
||||
19. Hard-refresh and inspect the family routes in both themes.
|
||||
+22
-22
@@ -34,8 +34,6 @@ Follow the steps below for your operating system:
|
||||
- Download and install [Docker Desktop for Windows](https://docs.docker.com/desktop/install/windows-install/?ref=coolify)
|
||||
- Ensure WSL2 backend is enabled in Docker Desktop settings
|
||||
|
||||
2. Install Spin:
|
||||
- Follow the instructions to install Spin on Windows from the [Spin documentation](https://serversideup.net/open-source/spin/docs/installation/install-windows#download-and-install-spin-into-wsl2?ref=coolify)
|
||||
|
||||
</details>
|
||||
|
||||
@@ -48,8 +46,6 @@ Follow the steps below for your operating system:
|
||||
- Docker Desktop:
|
||||
- Download and install [Docker Desktop for Mac](https://docs.docker.com/desktop/install/mac-install/?ref=coolify)
|
||||
|
||||
2. Install Spin:
|
||||
- Follow the instructions to install Spin on MacOS from the [Spin documentation](https://serversideup.net/open-source/spin/docs/installation/install-macos/#download-and-install-spin?ref=coolify)
|
||||
|
||||
</details>
|
||||
|
||||
@@ -62,22 +58,20 @@ Follow the steps below for your operating system:
|
||||
- Docker Desktop:
|
||||
- If you want a GUI, you can use [Docker Desktop for Linux](https://docs.docker.com/desktop/install/linux-install/?ref=coolify)
|
||||
|
||||
2. Install Spin:
|
||||
- Follow the instructions to install Spin on Linux from the [Spin documentation](https://serversideup.net/open-source/spin/docs/installation/install-linux#configure-docker-permissions?ref=coolify)
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
## 2. Verify Installation (Optional)
|
||||
After installing Docker (or Orbstack) and Spin, verify the installation:
|
||||
After installing Docker (or Orbstack), verify the installation:
|
||||
|
||||
1. Open a terminal or command prompt
|
||||
2. Run the following commands:
|
||||
```bash
|
||||
docker --version
|
||||
spin --version
|
||||
docker compose version
|
||||
```
|
||||
You should see version information for both Docker and Spin.
|
||||
You should see version information for Docker and Docker Compose.
|
||||
|
||||
|
||||
## 3. Fork and Setup Local Repository
|
||||
@@ -105,7 +99,7 @@ After installing Docker (or Orbstack) and Spin, verify the installation:
|
||||
1. In the Code Editor, locate the `.env.development.example` file in the root directory of your local Coolify repository.
|
||||
2. Duplicate the `.env.development.example` file and rename the copy to `.env`.
|
||||
3. Open the new `.env` file and review its contents. Adjust any environment variables as needed for your development setup.
|
||||
4. If you encounter errors during database migrations, update the database connection settings in your `.env` file. Use the IP address or hostname of your PostgreSQL database container. You can find this information by running `docker ps` after executing `spin up`.
|
||||
4. If you encounter errors during database migrations, update the database connection settings in your `.env` file. Use the IP address or hostname of your PostgreSQL database container. You can find this information by running `docker ps` after executing `docker compose -f docker-compose.yml -f docker-compose.dev.yml up`.
|
||||
5. Save the changes to your `.env` file.
|
||||
|
||||
|
||||
@@ -113,7 +107,7 @@ After installing Docker (or Orbstack) and Spin, verify the installation:
|
||||
1. Open a terminal in the local Coolify directory.
|
||||
2. Run the following command in the terminal (leave that terminal open):
|
||||
```bash
|
||||
spin up
|
||||
docker compose -f docker-compose.yml -f docker-compose.dev.yml up
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
@@ -121,11 +115,11 @@ After installing Docker (or Orbstack) and Spin, verify the installation:
|
||||
|
||||
3. If you encounter permission errors, especially on macOS, use:
|
||||
```bash
|
||||
sudo spin up
|
||||
sudo docker compose -f docker-compose.yml -f docker-compose.dev.yml up
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> If you change environment variables afterwards or anything seems broken, press Ctrl + C to stop the process and run `spin up` again.
|
||||
> If you change environment variables afterwards or anything seems broken, press Ctrl + C to stop the process and run `docker compose -f docker-compose.yml -f docker-compose.dev.yml up` again.
|
||||
|
||||
|
||||
## 6. Start Development
|
||||
@@ -140,13 +134,19 @@ After installing Docker (or Orbstack) and Spin, verify the installation:
|
||||
|------|-----|------|
|
||||
| Laravel Horizon (scheduler) | `http://localhost:8000/horizon` | Only accessible when logged in as root user |
|
||||
| Mailpit (email catcher) | `http://localhost:8025` | |
|
||||
| Telescope (debugging tool) | `http://localhost:8000/telescope` | Disabled by default |
|
||||
|
||||
> [!NOTE]
|
||||
> To enable Telescope, add the following to your `.env` file:
|
||||
> ```env
|
||||
> TELESCOPE_ENABLED=true
|
||||
> ```
|
||||
**Server-Timing + HUD** (headers + bottom-right pill on full HTML pages):
|
||||
|
||||
| Setting | Effect |
|
||||
|---------|--------|
|
||||
| `APP_ENV=local` and `SERVER_TIMING_ENABLED` unset | **On** (default in dev) |
|
||||
| `SERVER_TIMING_ENABLED=true` | **On** in any env, including production |
|
||||
| `SERVER_TIMING_ENABLED=false` | **Off** even when `APP_ENV=local` |
|
||||
|
||||
Metrics: `app` / `db` / `php` / `dbslow` (ms), `queries`, `html` (bytes), `mem` (MB).
|
||||
HUD keeps a request log (click row → AI-ready dump). Production: enable only
|
||||
temporarily (`SERVER_TIMING_ENABLED=true`); if you use `config:cache`, rebuild
|
||||
or clear config after changing the env var.
|
||||
|
||||
|
||||
## Development Notes
|
||||
@@ -173,9 +173,9 @@ If you encounter issues or break your database or something else, follow these s
|
||||
|
||||
1. Stop all running containers `ctrl + c`.
|
||||
|
||||
2. Remove all Coolify containers:
|
||||
2. Force-remove all Coolify dev containers:
|
||||
```bash
|
||||
docker rm coolify coolify-db coolify-redis coolify-realtime coolify-testing-host coolify-minio coolify-vite-1 coolify-mail
|
||||
npm run clean
|
||||
```
|
||||
|
||||
3. Remove Coolify volumes (it is possible that the volumes have no `coolify` prefix on your machine, in that case remove the prefix from the command):
|
||||
@@ -190,7 +190,7 @@ If you encounter issues or break your database or something else, follow these s
|
||||
|
||||
5. Start Coolify again:
|
||||
```bash
|
||||
spin up
|
||||
docker compose -f docker-compose.yml -f docker-compose.dev.yml up
|
||||
```
|
||||
|
||||
6. Run database migrations and seeders:
|
||||
|
||||
+65
-124
@@ -1,133 +1,74 @@
|
||||
# Coolify Release Guide
|
||||
|
||||
This guide outlines the release process for Coolify, intended for developers and those interested in understanding how Coolify releases are managed and deployed.
|
||||
## Branches
|
||||
|
||||
## Table of Contents
|
||||
- [Release Process](#release-process)
|
||||
- [Version Types](#version-types)
|
||||
- [Stable](#stable)
|
||||
- [Nightly](#nightly)
|
||||
- [Beta](#beta)
|
||||
- [Version Availability](#version-availability)
|
||||
- [Self-Hosted](#self-hosted)
|
||||
- [Cloud](#cloud)
|
||||
- [Manually Update to Specific Versions](#manually-update-to-specific-versions)
|
||||
| Branch | Purpose |
|
||||
| --- | --- |
|
||||
| `main` | Latest production source |
|
||||
| `next` | Feature integration and RC releases |
|
||||
| `feature/*` | New features based on and merged into `next` |
|
||||
| `hotfix/X.Y.Z` | Production fixes based on `main` |
|
||||
|
||||
## Release Process
|
||||
Release workflows never edit or commit versions. Set the intended version in `config/constants.php` before running a release workflow.
|
||||
|
||||
1. **Development on `next` or Feature Branches**
|
||||
- Improvements, fixes, and new features are developed on the `next` branch or separate feature branches.
|
||||
## Where changes go
|
||||
|
||||
2. **Merging to `main`**
|
||||
- Once ready, changes are merged from the `next` branch into the `main` branch (via a pull request).
|
||||
- Fixes, security updates, and small improvements target `main`.
|
||||
- New features and larger changes target `next`.
|
||||
- Merge `main` into `next` regularly so every production fix is included in the next release.
|
||||
- Do not merge `next` into `main` until an RC is approved for a stable release.
|
||||
|
||||
3. **Building the Release**
|
||||
- After merging to `main`, GitHub Actions automatically builds release images for all architectures and pushes them to the GitHub Container Registry and Docker Hub with the specific version tag and the `latest` tag.
|
||||
## Feature and RC flow
|
||||
|
||||
4. **Creating a GitHub Release**
|
||||
- A new GitHub release is manually created with details of the changes made in the version.
|
||||
|
||||
5. **Updating the CDN**
|
||||
- To make a new version publicly available, the version information on the CDN needs to be updated manually. After that the new version number will be available at [https://cdn.coollabs.io/coolify/versions.json](https://cdn.coollabs.io/coolify/versions.json).
|
||||
|
||||
> [!NOTE]
|
||||
> The CDN update may not occur immediately after the GitHub release. It can take hours or even days due to additional testing, stability checks, or potential hotfixes. **The update becomes available only after the CDN is updated. After the CDN is updated, a discord announcement will be made in the Production Release channel.**
|
||||
|
||||
## Version Types
|
||||
|
||||
<details>
|
||||
<summary><strong>Stable (coming soon)</strong></summary>
|
||||
|
||||
- **Stable**
|
||||
- The production version suitable for stable, production environments (recommended).
|
||||
- **Update Frequency:** Every 2 to 4 weeks, with more frequent possible fixes.
|
||||
- **Release Size:** Larger but less frequent releases. Multiple nightly versions are consolidated into a single stable release.
|
||||
- **Versioning Scheme:** Follows semantic versioning (e.g., `v4.0.0`, `4.1.0`, etc.).
|
||||
- **Installation Command:**
|
||||
```bash
|
||||
curl -fsSL https://cdn.coollabs.io/coolify/install.sh | bash
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Nightly</strong></summary>
|
||||
|
||||
- **Nightly**
|
||||
- The latest development version, suitable for testing the latest changes and experimenting with new features.
|
||||
- **Update Frequency:** Daily or bi-weekly updates.
|
||||
- **Release Size:** Smaller, more frequent releases.
|
||||
- **Versioning Scheme:** Follows semantic versioning (e.g., `4.1.0-nightly.1`, `4.1.0-nightly.2`, etc.).
|
||||
- **Installation Command:**
|
||||
```bash
|
||||
curl -fsSL https://cdn.coollabs.io/coolify-nightly/install.sh | bash -s next
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Beta</strong></summary>
|
||||
|
||||
- **Beta**
|
||||
- Test releases for the upcoming stable version.
|
||||
- **Purpose:** Allows users to test and provide feedback on new features and changes before they become stable.
|
||||
- **Update Frequency:** Available if we think beta testing is necessary.
|
||||
- **Release Size:** Same size as stable release as it will become the next stabe release after some time.
|
||||
- **Versioning Scheme:** Follows semantic versioning (e.g., `4.1.0-beta.1`, `4.1.0-beta.2`, etc.).
|
||||
- **Installation Command:**
|
||||
```bash
|
||||
curl -fsSL https://cdn.coollabs.io/coolify/install.sh | bash
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
> [!WARNING]
|
||||
> Do not use nightly/beta builds in production as there is no guarantee of stability.
|
||||
|
||||
## Version Availability
|
||||
|
||||
When a new version is released and a new GitHub release is created, it doesn't immediately become available for your instance. Here's how version availability works for different instance types.
|
||||
|
||||
### Self-Hosted
|
||||
|
||||
- **Update Frequency:** More frequent updates, especially on the nightly release channel.
|
||||
- **Update Availability:** New versions are available once the CDN has been updated.
|
||||
- **Update Methods:**
|
||||
1. **Manual Update in Instance Settings:**
|
||||
- Go to `Settings > Update Check Frequency` and click the `Check Manually` button.
|
||||
- If an update is available, an upgrade button will appear on the sidebar.
|
||||
2. **Automatic Update:**
|
||||
- If enabled, the instance will update automatically at the time set in the settings.
|
||||
3. **Re-run Installation Script:**
|
||||
- Run the installation script again to upgrade to the latest version available on the CDN:
|
||||
```bash
|
||||
curl -fsSL https://cdn.coollabs.io/coolify/install.sh | bash
|
||||
```
|
||||
|
||||
> [!IMPORTANT]
|
||||
> If a new release is available on GitHub but your instance hasn't updated yet or no upgrade button is shown in the UI, the CDN might not have been updated yet. This intentional delay ensures stability and allows for hotfixes before official release.
|
||||
|
||||
### Cloud
|
||||
|
||||
- **Update Frequency:** Less frequent as it's a managed service.
|
||||
- **Update Availability:** New versions are available once Andras has updated the cloud version manually.
|
||||
- **Update Method:**
|
||||
- Updates are managed by Andras, who ensures each cloud version is thoroughly tested and stable before releasing it.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> The cloud version of Coolify may be several versions behind the latest GitHub releases even if the CDN is updated. This is intentional to ensure stability and reliability for cloud users and Andras will manully update the cloud version when the update is ready.
|
||||
|
||||
## Manually Update/ Downgrade to Specific Versions
|
||||
|
||||
> [!CAUTION]
|
||||
> Updating to unreleased versions is not recommended and can cause issues.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> Downgrading is supported but not recommended and can cause issues because of database migrations and other changes.
|
||||
|
||||
To update your Coolify instance to a specific version, use the following command:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://cdn.coollabs.io/coolify/install.sh | bash -s <version>
|
||||
```text
|
||||
feature/* → next → RC
|
||||
```
|
||||
Replace `<version>` with the version you want to update to (for example `4.0.0-beta.332`).
|
||||
|
||||
1. Merge feature branches into `next`.
|
||||
2. Set the intended RC version on `next`, such as `4.4-rc.1`.
|
||||
3. Regular builds publish `sha-<commit>`, `4.4-rc.1.<short-sha>`, and the moving `next` tag.
|
||||
4. Create a reviewed draft GitHub Release named `v4.4-rc.1` and mark it as a prerelease.
|
||||
5. Run the RC workflow from `next`. It publishes `4.4-rc.1`, updates `next`, and publishes the draft.
|
||||
6. Advance `next` to the next intended RC version.
|
||||
|
||||
## Stable release flow
|
||||
|
||||
```text
|
||||
next → main → stable release
|
||||
```
|
||||
|
||||
1. Temporarily stop merging features into `next`.
|
||||
2. Change the version on `next` from the approved RC to the stable version, such as `4.4.0`.
|
||||
3. Merge `next` into `main`.
|
||||
4. Create a reviewed draft GitHub Release named `v4.4.0`.
|
||||
5. Run the stable release workflow from `main`.
|
||||
6. The workflow rebuilds the exact stable version, publishes `4.4.0` and `latest`, then publishes the draft.
|
||||
7. Update the CDN only after the release is approved.
|
||||
8. Advance `next` to the next development version.
|
||||
|
||||
## Hotfix flow
|
||||
|
||||
```text
|
||||
main → hotfix/X.Y.Z → main → next
|
||||
```
|
||||
|
||||
1. Create `hotfix/X.Y.Z` from `main` when a patch needs an integration branch. A single fix may use a normal branch from `main` instead.
|
||||
2. Set the intended patch version.
|
||||
3. Implement and test the fix. SHA images report `X.Y.Z-dev.<short-sha>`.
|
||||
4. Merge the fix into `main`.
|
||||
5. Create a reviewed draft GitHub Release named `vX.Y.Z`.
|
||||
6. Run the stable release workflow from `main`.
|
||||
7. Merge `main` into `next`, resolve the version in favor of the next intended RC, and delete the hotfix branch if one was used.
|
||||
8. Update the CDN only after the release is approved.
|
||||
|
||||
## Image tags
|
||||
|
||||
| Tag | Meaning |
|
||||
| --- | --- |
|
||||
| `latest` | Latest stable release |
|
||||
| `next` | Latest successful `next` build |
|
||||
| `X.Y.Z` | Exact stable release |
|
||||
| `X.Y-rc.N` | Exact RC release |
|
||||
| `sha-<commit>` | Exact commit build |
|
||||
|
||||
Git tags use the `v` prefix, such as `v4.4.0`. Docker image tags do not.
|
||||
|
||||
@@ -54,6 +54,14 @@ class CleanupPreviewDeployment
|
||||
$server
|
||||
);
|
||||
|
||||
if ($result['cancelled_deployments'] > 0) {
|
||||
try {
|
||||
next_after_cancel($server);
|
||||
} catch (\Throwable $e) {
|
||||
\Log::warning("Failed to advance deployment queue after cleaning up preview for application {$application->id}: {$e->getMessage()}");
|
||||
}
|
||||
}
|
||||
|
||||
// Step 2: Stop and remove all running PR containers
|
||||
$result['killed_containers'] = $this->stopRunningContainers(
|
||||
$application,
|
||||
@@ -98,13 +106,13 @@ class CleanupPreviewDeployment
|
||||
$deployment->update([
|
||||
'status' => ApplicationDeploymentStatus::CANCELLED_BY_USER->value,
|
||||
]);
|
||||
$cancelled++;
|
||||
|
||||
// Add cancellation log entry
|
||||
$deployment->addLogEntry('Deployment cancelled: Pull request closed.', 'stderr');
|
||||
|
||||
// Try to kill helper container if it exists
|
||||
$this->killHelperContainer($deployment->deployment_uuid, $server);
|
||||
$cancelled++;
|
||||
} catch (\Throwable $e) {
|
||||
\Log::warning("Failed to cancel deployment {$deployment->id}: {$e->getMessage()}");
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ class StopApplication
|
||||
if ($server->isSwarm()) {
|
||||
instant_remote_process(["docker stack rm {$application->uuid}"], $server);
|
||||
|
||||
return;
|
||||
continue;
|
||||
}
|
||||
|
||||
$containers = $previewDeployments
|
||||
@@ -40,7 +40,7 @@ class StopApplication
|
||||
|
||||
foreach ($containersToStop as $containerName) {
|
||||
instant_remote_process(command: [
|
||||
"docker stop --time=$timeout $containerName",
|
||||
dockerStopCommand($timeout, $containerName, $server),
|
||||
"docker rm -f $containerName",
|
||||
], server: $server, throwError: false);
|
||||
}
|
||||
@@ -57,17 +57,15 @@ class StopApplication
|
||||
}
|
||||
}
|
||||
|
||||
$status = ['status' => 'exited'];
|
||||
if ($resetRestartCount) {
|
||||
$application->update([
|
||||
$status = array_merge($status, [
|
||||
'restart_count' => 0,
|
||||
'last_restart_at' => null,
|
||||
'last_restart_type' => null,
|
||||
]);
|
||||
} else {
|
||||
$application->update([
|
||||
'status' => 'exited',
|
||||
]);
|
||||
}
|
||||
$application->update($status);
|
||||
|
||||
ServiceStatusChanged::dispatch($application->environment->project->team->id);
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ class StopApplicationOneServer
|
||||
if ($containerName) {
|
||||
instant_remote_process(
|
||||
[
|
||||
"docker stop --time=$timeout $containerName",
|
||||
dockerStopCommand($timeout, $containerName, $server),
|
||||
"docker rm -f $containerName",
|
||||
],
|
||||
$server
|
||||
|
||||
@@ -104,7 +104,7 @@ class StartClickhouse
|
||||
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
|
||||
$this->commands[] = "echo 'Pulling {$database->image} image.'";
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
|
||||
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
|
||||
$this->commands[] = dockerStopCommand(10, $container_name, $this->database->destination->server).' 2>/dev/null || true';
|
||||
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
|
||||
$this->commands[] = "echo 'Database started.'";
|
||||
|
||||
@@ -191,7 +191,7 @@ class StartDragonfly
|
||||
if ($this->database->enable_ssl) {
|
||||
$this->commands[] = "chown -R 999:999 $this->configuration_dir/ssl/server.key $this->configuration_dir/ssl/server.crt";
|
||||
}
|
||||
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
|
||||
$this->commands[] = dockerStopCommand(10, $container_name, $this->database->destination->server).' 2>/dev/null || true';
|
||||
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
|
||||
$this->commands[] = "echo 'Database started.'";
|
||||
|
||||
@@ -209,7 +209,7 @@ class StartKeydb
|
||||
if (! is_null($this->database->keydb_conf) && ! empty($this->database->keydb_conf)) {
|
||||
$this->commands[] = "chown 999:999 $this->configuration_dir/keydb.conf";
|
||||
}
|
||||
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
|
||||
$this->commands[] = dockerStopCommand(10, $container_name, $this->database->destination->server).' 2>/dev/null || true';
|
||||
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
|
||||
$this->commands[] = "echo 'Database started.'";
|
||||
|
||||
@@ -208,13 +208,13 @@ class StartMariadb
|
||||
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
|
||||
$this->commands[] = "echo 'Pulling {$database->image} image.'";
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
|
||||
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
|
||||
if ($this->database->enable_ssl) {
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml run --rm --no-deps --user root --entrypoint chown $container_name mysql:mysql /etc/mysql/certs/server.key /etc/mysql/certs/server.crt < /dev/null";
|
||||
}
|
||||
$this->commands[] = dockerStopCommand(10, $container_name, $this->database->destination->server).' 2>/dev/null || true';
|
||||
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
|
||||
$this->commands[] = "echo 'Database started.'";
|
||||
if ($this->database->enable_ssl) {
|
||||
$this->commands[] = executeInDocker($this->database->uuid, 'chown mysql:mysql /etc/mysql/certs/server.crt /etc/mysql/certs/server.key');
|
||||
}
|
||||
|
||||
return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
|
||||
}
|
||||
|
||||
@@ -257,12 +257,12 @@ class StartMongodb
|
||||
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
|
||||
$this->commands[] = "echo 'Pulling {$database->image} image.'";
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
|
||||
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
|
||||
if ($this->database->enable_ssl) {
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml run --rm --no-deps --user root --entrypoint chown $container_name mongodb:mongodb /etc/mongo/certs/server.pem < /dev/null";
|
||||
}
|
||||
$this->commands[] = dockerStopCommand(10, $container_name, $this->database->destination->server).' 2>/dev/null || true';
|
||||
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
|
||||
if ($this->database->enable_ssl) {
|
||||
$this->commands[] = executeInDocker($this->database->uuid, 'chown mongodb:mongodb /etc/mongo/certs/server.pem');
|
||||
}
|
||||
$this->commands[] = "echo 'Database started.'";
|
||||
|
||||
return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
|
||||
|
||||
@@ -209,15 +209,13 @@ class StartMysql
|
||||
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
|
||||
$this->commands[] = "echo 'Pulling {$database->image} image.'";
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
|
||||
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
|
||||
if ($this->database->enable_ssl) {
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml run --rm --no-deps --user root --entrypoint chown $container_name mysql:mysql /etc/mysql/certs/server.key /etc/mysql/certs/server.crt < /dev/null";
|
||||
}
|
||||
$this->commands[] = dockerStopCommand(10, $container_name, $this->database->destination->server).' 2>/dev/null || true';
|
||||
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
|
||||
|
||||
if ($this->database->enable_ssl) {
|
||||
$mysqlUser = escapeshellarg($this->database->mysql_user);
|
||||
$this->commands[] = executeInDocker($this->database->uuid, "chown {$mysqlUser}:{$mysqlUser} /etc/mysql/certs/server.crt /etc/mysql/certs/server.key");
|
||||
}
|
||||
|
||||
$this->commands[] = "echo 'Database started.'";
|
||||
|
||||
return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
|
||||
|
||||
@@ -219,13 +219,12 @@ class StartPostgresql
|
||||
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
|
||||
$this->commands[] = "echo 'Pulling {$database->image} image.'";
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
|
||||
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
|
||||
if ($this->database->enable_ssl) {
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml run --rm --no-deps --user root --entrypoint chown $container_name postgres:postgres /var/lib/postgresql/certs/server.key /var/lib/postgresql/certs/server.crt < /dev/null";
|
||||
}
|
||||
$this->commands[] = dockerStopCommand(10, $container_name, $this->database->destination->server).' 2>/dev/null || true';
|
||||
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
|
||||
if ($this->database->enable_ssl) {
|
||||
$postgresUser = escapeshellarg($this->database->postgres_user);
|
||||
$this->commands[] = executeInDocker($this->database->uuid, "chown {$postgresUser}:{$postgresUser} /var/lib/postgresql/certs/server.key /var/lib/postgresql/certs/server.crt");
|
||||
}
|
||||
$this->commands[] = "echo 'Database started.'";
|
||||
|
||||
return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
|
||||
|
||||
@@ -204,7 +204,7 @@ class StartRedis
|
||||
if (! is_null($this->database->redis_conf) && ! empty($this->database->redis_conf)) {
|
||||
$this->commands[] = "chown 999:999 $this->configuration_dir/redis.conf";
|
||||
}
|
||||
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
|
||||
$this->commands[] = dockerStopCommand(10, $container_name, $this->database->destination->server).' 2>/dev/null || true';
|
||||
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
|
||||
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
|
||||
$this->commands[] = "echo 'Database started.'";
|
||||
|
||||
@@ -30,6 +30,7 @@ class StopDatabase
|
||||
|
||||
// Reset restart tracking when database is manually stopped
|
||||
$database->update([
|
||||
'status' => 'exited',
|
||||
'restart_count' => 0,
|
||||
'last_restart_at' => null,
|
||||
'last_restart_type' => null,
|
||||
@@ -56,7 +57,7 @@ class StopDatabase
|
||||
{
|
||||
$server = $database->destination->server;
|
||||
instant_remote_process(command: [
|
||||
"docker stop -t $timeout $containerName",
|
||||
dockerStopCommand($timeout, $containerName, $server),
|
||||
"docker rm -f $containerName",
|
||||
], server: $server, throwError: false);
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ class CreateNewUser implements CreatesNewUsers
|
||||
public function create(array $input): User
|
||||
{
|
||||
$settings = instanceSettings();
|
||||
if (! $settings->is_registration_enabled) {
|
||||
if (! $settings->isPasswordRegistrationAllowed()) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ class GetProxyConfiguration
|
||||
{
|
||||
use AsAction;
|
||||
|
||||
public const MAX_CONFIGURATION_SIZE_BYTES = 5 * 1024 * 1024;
|
||||
|
||||
public function handle(Server $server, bool $forceRegenerate = false): string
|
||||
{
|
||||
$proxyType = $server->proxyType();
|
||||
@@ -98,11 +100,17 @@ class GetProxyConfiguration
|
||||
private function backfillFromDisk(Server $server): ?string
|
||||
{
|
||||
$proxy_path = $server->proxyPath();
|
||||
$configurationPath = escapeshellarg("$proxy_path/docker-compose.yml");
|
||||
$readLimit = self::MAX_CONFIGURATION_SIZE_BYTES + 1;
|
||||
$result = instant_remote_process([
|
||||
"mkdir -p $proxy_path",
|
||||
"cat $proxy_path/docker-compose.yml 2>/dev/null",
|
||||
"if [ ! -f {$configurationPath} ]; then exit 0; elif [ \"$(wc -c < {$configurationPath})\" -gt ".self::MAX_CONFIGURATION_SIZE_BYTES." ]; then echo '__COOLIFY_PROXY_CONFIG_TOO_LARGE__'; else head -c {$readLimit} {$configurationPath}; fi",
|
||||
], $server, false);
|
||||
|
||||
if ($result === '__COOLIFY_PROXY_CONFIG_TOO_LARGE__' || strlen($result ?? '') > self::MAX_CONFIGURATION_SIZE_BYTES) {
|
||||
throw new \RuntimeException('Proxy configuration exceeds the 5 MiB size limit.');
|
||||
}
|
||||
|
||||
if (! empty(trim($result ?? ''))) {
|
||||
$server->proxy->last_saved_proxy_configuration = $result;
|
||||
$server->save();
|
||||
|
||||
@@ -24,7 +24,7 @@ class StopProxy
|
||||
}
|
||||
|
||||
instant_remote_process(command: [
|
||||
"docker stop -t=$timeout $containerName 2>/dev/null || true",
|
||||
dockerStopCommand($timeout, $containerName, $server).' 2>/dev/null || true',
|
||||
"docker rm -f $containerName 2>/dev/null || true",
|
||||
'# Wait for container to be fully removed',
|
||||
'for i in {1..10}; do',
|
||||
|
||||
@@ -106,6 +106,15 @@ class CheckUpdates
|
||||
$out['osId'] = $osId;
|
||||
$out['package_manager'] = $packageManager;
|
||||
|
||||
return $out;
|
||||
case 'apk':
|
||||
instant_remote_process(['apk update -q'], $server);
|
||||
$output = instant_remote_process(['LANG=C apk list --upgradable 2>/dev/null'], $server);
|
||||
|
||||
$out = $this->parseApkOutput($output);
|
||||
$out['osId'] = $osId;
|
||||
$out['package_manager'] = $packageManager;
|
||||
|
||||
return $out;
|
||||
default:
|
||||
return [
|
||||
@@ -273,4 +282,32 @@ class CheckUpdates
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function parseApkOutput(string $output): array
|
||||
{
|
||||
$updates = [];
|
||||
$lines = explode("\n", $output);
|
||||
|
||||
foreach ($lines as $line) {
|
||||
// Skip empty lines
|
||||
if (empty($line)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Example line: docker-cli-compose-2.31.0-r5 x86_64 {docker-cli-compose} (Apache-2.0) [upgradable from: docker-cli-compose-2.31.0-r4]
|
||||
if (preg_match('/^(.+)-([0-9]\S*) (\S+) \{\S+\} \([^)]+\) \[upgradable from: .+?-([0-9][^\]]+)\]$/', $line, $matches)) {
|
||||
$updates[] = [
|
||||
'package' => $matches[1],
|
||||
'new_version' => $matches[2],
|
||||
'architecture' => $matches[3],
|
||||
'current_version' => $matches[4],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'total_updates' => count($updates),
|
||||
'updates' => $updates,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,9 @@ class CleanupDocker
|
||||
$helperImageWithVersion = "$helperImage:$helperImageVersion";
|
||||
$helperImageWithoutPrefix = 'coollabsio/coolify-helper';
|
||||
$helperImageWithoutPrefixVersion = "coollabsio/coolify-helper:$helperImageVersion";
|
||||
$buildxMetadataVolume = isDev() && $server->isLocalhost()
|
||||
? 'coolify-buildx'
|
||||
: '$HOME/.docker/buildx';
|
||||
|
||||
$cleanupLog = [];
|
||||
|
||||
@@ -44,7 +47,7 @@ class CleanupDocker
|
||||
'docker container prune -f --filter "label=coolify.managed=true" --filter "label!=coolify.proxy=true" --filter "label!=coolify.type=database" --filter "label!=coolify.type=application" --filter "label!=coolify.type=service"',
|
||||
$imagePruneCmd,
|
||||
'docker builder prune -af',
|
||||
"docker run --rm -v \$HOME/.docker/buildx:/root/.docker/buildx -v /var/run/docker.sock:/var/run/docker.sock {$helperImageWithVersion} docker buildx prune --builder coolify-railpack -af 2>/dev/null || true",
|
||||
"docker run --rm -v {$buildxMetadataVolume}:/root/.docker/buildx -v /var/run/docker.sock:/var/run/docker.sock {$helperImageWithVersion} docker buildx prune --builder coolify-railpack -af 2>/dev/null || true",
|
||||
"docker images --filter before=$helperImageWithVersion --filter reference=$helperImage | grep $helperImage | awk '{print $3}' | xargs -r docker rmi -f",
|
||||
"docker images --filter before=$helperImageWithoutPrefixVersion --filter reference=$helperImageWithoutPrefix | grep $helperImageWithoutPrefix | awk '{print $3}' | xargs -r docker rmi -f",
|
||||
];
|
||||
@@ -117,7 +120,7 @@ class CleanupDocker
|
||||
|
||||
$commands[] = "docker images --format '{{.Repository}}:{{.Tag}}' | ".
|
||||
$grepCommands.' | '.
|
||||
"xargs -r -I {} sh -c 'docker inspect --format \"{{{{index .Config.Labels \\\"coolify.managed\\\"}}}}\" \"{}\" 2>/dev/null | grep -q true || docker rmi \"{}\" 2>/dev/null' || true";
|
||||
"xargs -r -I {} sh -c 'docker inspect --format \"{{index .Config.Labels \\\"coolify.managed\\\"}}\" \"{}\" 2>/dev/null | grep -q true || docker rmi \"{}\" 2>/dev/null' || true";
|
||||
|
||||
return implode(' && ', $commands);
|
||||
}
|
||||
|
||||
@@ -79,6 +79,8 @@ class InstallDocker
|
||||
$command = $command->merge([$this->getSuseDockerInstallCommand()]);
|
||||
} elseif ($supported_os_type->contains('arch')) {
|
||||
$command = $command->merge([$this->getArchDockerInstallCommand()]);
|
||||
} elseif ($supported_os_type->contains('alpine')) {
|
||||
$command = $command->merge([$this->getAlpineDockerInstallCommand()]);
|
||||
} else {
|
||||
$command = $command->merge([$this->getGenericDockerInstallCommand()]);
|
||||
}
|
||||
@@ -93,9 +95,8 @@ class InstallDocker
|
||||
"jq -s '.[0] * .[1]' /etc/docker/daemon.json.coolify /etc/docker/daemon.json | tee /etc/docker/daemon.json.appended > /dev/null",
|
||||
'mv /etc/docker/daemon.json.appended /etc/docker/daemon.json',
|
||||
"echo 'Restarting Docker Engine...'",
|
||||
'systemctl enable docker >/dev/null 2>&1 || true',
|
||||
'systemctl restart docker',
|
||||
]);
|
||||
$command = $command->merge($this->getDockerServiceCommands($supported_os_type->contains('alpine')));
|
||||
if ($server->isSwarm()) {
|
||||
$command = $command->merge([
|
||||
'docker network create --attachable --driver overlay coolify-overlay >/dev/null 2>&1 || true',
|
||||
@@ -154,6 +155,28 @@ class InstallDocker
|
||||
'systemctl start docker.service';
|
||||
}
|
||||
|
||||
private function getAlpineDockerInstallCommand(): string
|
||||
{
|
||||
return 'apk update && '.
|
||||
'apk add docker docker-cli-buildx docker-cli-compose && '.
|
||||
'mkdir -p /etc/docker';
|
||||
}
|
||||
|
||||
private function getDockerServiceCommands(bool $usesOpenRc): array
|
||||
{
|
||||
if ($usesOpenRc) {
|
||||
return [
|
||||
'rc-update add docker default',
|
||||
'rc-service docker restart',
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'systemctl enable docker >/dev/null 2>&1 || true',
|
||||
'systemctl restart docker',
|
||||
];
|
||||
}
|
||||
|
||||
private function getGenericDockerInstallCommand(): string
|
||||
{
|
||||
return 'curl -fsSL https://get.docker.com | sh';
|
||||
|
||||
@@ -53,6 +53,8 @@ class InstallPrerequisites
|
||||
"echo 'Installing Prerequisites for Arch Linux...'",
|
||||
'pacman -Syu --noconfirm --needed curl wget git jq',
|
||||
]);
|
||||
} elseif ($supported_os_type->contains('alpine')) {
|
||||
$command = $command->merge($this->getAlpinePrerequisiteCommands());
|
||||
} else {
|
||||
throw new \Exception('Unsupported OS type for prerequisites installation');
|
||||
}
|
||||
@@ -61,4 +63,18 @@ class InstallPrerequisites
|
||||
|
||||
return remote_process($command, $server);
|
||||
}
|
||||
|
||||
private function getAlpinePrerequisiteCommands(): array
|
||||
{
|
||||
return [
|
||||
"echo 'Installing Prerequisites for Alpine Linux...'",
|
||||
"sed -i '/^#.*\\/community/s/^#//' /etc/apk/repositories 2>/dev/null || true",
|
||||
'apk update',
|
||||
'command -v bash >/dev/null || apk add bash',
|
||||
'command -v curl >/dev/null || apk add curl',
|
||||
'command -v wget >/dev/null || apk add wget',
|
||||
'command -v git >/dev/null || apk add git',
|
||||
'command -v jq >/dev/null || apk add jq',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,13 +23,10 @@ class StartSentinel
|
||||
$refreshRate = data_get($server, 'settings.sentinel_metrics_refresh_rate_seconds');
|
||||
$pushInterval = data_get($server, 'settings.sentinel_push_interval_seconds');
|
||||
$token = $server->settings->ensureValidSentinelToken();
|
||||
$endpoint = data_get($server, 'settings.sentinel_custom_url');
|
||||
$endpoint = $server->settings->ensureSentinelUrl();
|
||||
$debug = data_get($server, 'settings.is_sentinel_debug_enabled');
|
||||
$mountDir = '/data/coolify/sentinel';
|
||||
$image = coolifyRegistryUrl().'/coollabsio/sentinel:'.$version;
|
||||
if (! $endpoint) {
|
||||
throw new \RuntimeException('You should set FQDN in Instance Settings.');
|
||||
}
|
||||
$environments = [
|
||||
'TOKEN' => $token,
|
||||
'DEBUG' => $debug ? 'true' : 'false',
|
||||
|
||||
@@ -58,6 +58,10 @@ class UpdatePackage
|
||||
$commandAll = 'pacman -Syu --noconfirm';
|
||||
$commandInstall = 'pacman -S --noconfirm '.$sanitizedPackage;
|
||||
break;
|
||||
case 'apk':
|
||||
$commandAll = 'apk update && apk upgrade';
|
||||
$commandInstall = 'apk upgrade '.$sanitizedPackage;
|
||||
break;
|
||||
default:
|
||||
return [
|
||||
'error' => 'OS not supported',
|
||||
|
||||
@@ -25,6 +25,15 @@ class ValidateServer
|
||||
|
||||
public function handle(Server $server)
|
||||
{
|
||||
if (! $server->canBeValidated()) {
|
||||
$this->error = 'This server was transferred to another Coolify instance and cannot be revalidated here.';
|
||||
$server->update([
|
||||
'validation_logs' => $this->error,
|
||||
'is_validating' => false,
|
||||
]);
|
||||
throw new \Exception($this->error);
|
||||
}
|
||||
|
||||
$server->update([
|
||||
'validation_logs' => null,
|
||||
]);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Actions\Service;
|
||||
|
||||
use App\Models\ServiceApplication;
|
||||
use App\Models\ServiceDatabase;
|
||||
use Lorisleiva\Actions\Concerns\AsAction;
|
||||
use Spatie\Activitylog\Contracts\Activity;
|
||||
|
||||
@@ -12,7 +13,7 @@ class DeployServiceApplication
|
||||
|
||||
public string $jobQueue = 'high';
|
||||
|
||||
public function handle(ServiceApplication $serviceApplication, bool $pullLatestImages = false, bool $forceRebuild = false): Activity
|
||||
public function handle(ServiceApplication|ServiceDatabase $serviceApplication, bool $pullLatestImages = false, bool $forceRebuild = false): Activity
|
||||
{
|
||||
$service = $serviceApplication->service;
|
||||
$composeServiceName = $serviceApplication->name;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Actions\Service;
|
||||
|
||||
use App\Models\ServiceApplication;
|
||||
use App\Models\ServiceDatabase;
|
||||
use Lorisleiva\Actions\Concerns\AsAction;
|
||||
|
||||
class RestartServiceApplication
|
||||
@@ -11,7 +12,7 @@ class RestartServiceApplication
|
||||
|
||||
public string $jobQueue = 'high';
|
||||
|
||||
public function handle(ServiceApplication $serviceApplication): void
|
||||
public function handle(ServiceApplication|ServiceDatabase $serviceApplication): void
|
||||
{
|
||||
$service = $serviceApplication->service;
|
||||
$server = $service->destination->server;
|
||||
|
||||
@@ -49,6 +49,9 @@ class StopService
|
||||
$this->stopContainersInParallel($containersToStop, $server);
|
||||
}
|
||||
|
||||
$applications->each->update(['status' => 'exited']);
|
||||
$dbs->each->update(['status' => 'exited']);
|
||||
|
||||
if ($deleteConnectedNetworks) {
|
||||
$service->deleteConnectedNetworks();
|
||||
}
|
||||
@@ -67,7 +70,7 @@ class StopService
|
||||
$timeout = count($containersToStop) > 5 ? 10 : 30;
|
||||
$commands = [];
|
||||
$containerList = implode(' ', $containersToStop);
|
||||
$commands[] = "docker stop -t $timeout $containerList";
|
||||
$commands[] = dockerStopCommand($timeout, $containerList, $server);
|
||||
$commands[] = "docker rm -f $containerList";
|
||||
instant_remote_process(
|
||||
command: $commands,
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
namespace App\Actions\Service;
|
||||
|
||||
use App\Events\ServiceStatusChanged;
|
||||
use App\Models\ServiceApplication;
|
||||
use App\Models\ServiceDatabase;
|
||||
use Lorisleiva\Actions\Concerns\AsAction;
|
||||
|
||||
class StopServiceApplication
|
||||
@@ -11,7 +13,7 @@ class StopServiceApplication
|
||||
|
||||
public string $jobQueue = 'high';
|
||||
|
||||
public function handle(ServiceApplication $serviceApplication): void
|
||||
public function handle(ServiceApplication|ServiceDatabase $serviceApplication): void
|
||||
{
|
||||
$service = $serviceApplication->service;
|
||||
$server = $service->destination->server;
|
||||
@@ -20,5 +22,8 @@ class StopServiceApplication
|
||||
instant_remote_process([
|
||||
"docker stop {$containerName}",
|
||||
], $server);
|
||||
|
||||
$serviceApplication->update(['status' => 'exited']);
|
||||
ServiceStatusChanged::dispatch($service->environment->project->team->id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +59,11 @@ class UpdateServiceApplicationFromApi
|
||||
$serviceApplication->fqdn = $parsed['normalized'];
|
||||
}
|
||||
|
||||
if (array_key_exists('noindex_domains', $payload)) {
|
||||
// Must run after fqdn is set above: flags are kept only for current domains.
|
||||
$serviceApplication->setNoindexDomains($payload['noindex_domains'] ?? []);
|
||||
}
|
||||
|
||||
if (array_key_exists('human_name', $payload)) {
|
||||
$serviceApplication->human_name = $payload['human_name'];
|
||||
}
|
||||
@@ -83,6 +88,10 @@ class UpdateServiceApplicationFromApi
|
||||
$serviceApplication->is_stripprefix_enabled = filter_var($payload['is_stripprefix_enabled'], FILTER_VALIDATE_BOOLEAN);
|
||||
}
|
||||
|
||||
if (array_key_exists('is_force_https_enabled', $payload)) {
|
||||
$serviceApplication->is_force_https_enabled = filter_var($payload['is_force_https_enabled'], FILTER_VALIDATE_BOOLEAN);
|
||||
}
|
||||
|
||||
if (array_key_exists('is_log_drain_enabled', $payload)) {
|
||||
$enabled = filter_var($payload['is_log_drain_enabled'], FILTER_VALIDATE_BOOLEAN);
|
||||
$server = $serviceApplication->service->destination->server;
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions\Shared;
|
||||
|
||||
use App\Jobs\VolumeBackupJob;
|
||||
use App\Models\ScheduledVolumeBackup;
|
||||
use App\Models\Server;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Lorisleiva\Actions\Concerns\AsAction;
|
||||
|
||||
class DeleteScheduledVolumeBackup
|
||||
{
|
||||
use AsAction;
|
||||
|
||||
public function handle(ScheduledVolumeBackup $backup, ?Server $server = null): void
|
||||
{
|
||||
$lock = Cache::lock(VolumeBackupJob::lockKey($backup->id), $backup->timeout + 300);
|
||||
|
||||
if (! $lock->get()) {
|
||||
throw new \RuntimeException('Wait for the queued or running storage backup to finish before deleting this schedule.');
|
||||
}
|
||||
|
||||
try {
|
||||
if ($backup->executions()
|
||||
->where(fn ($query) => $query
|
||||
->where('status', 'running')
|
||||
->orWhere('stop_recovery_pending', true)
|
||||
->orWhere('s3_cleanup_pending', true))
|
||||
->exists()) {
|
||||
throw new \RuntimeException('Wait for the running storage backup and recovery operations to finish before deleting this schedule.');
|
||||
}
|
||||
|
||||
$localFilenames = $backup->executions()
|
||||
->where('local_storage_deleted', false)
|
||||
->pluck('filename')
|
||||
->filter()
|
||||
->all();
|
||||
|
||||
if ($localFilenames !== []) {
|
||||
$server ??= $backup->server();
|
||||
if (! $server) {
|
||||
throw new \RuntimeException('The server is unavailable, so local backup archives cannot be deleted.');
|
||||
}
|
||||
|
||||
deleteBackupsLocally($localFilenames, $server, throwError: true);
|
||||
}
|
||||
|
||||
$s3Executions = $backup->executions()
|
||||
->with('s3')
|
||||
->where('s3_uploaded', true)
|
||||
->where('s3_storage_deleted', false)
|
||||
->get();
|
||||
|
||||
foreach ($s3Executions->groupBy('s3_storage_id') as $executions) {
|
||||
$s3 = $executions->first()->s3;
|
||||
if (! $s3) {
|
||||
throw new \RuntimeException('The S3 storage used by an existing backup is unavailable.');
|
||||
}
|
||||
|
||||
$filenames = $executions->pluck('filename')->filter()->all();
|
||||
if ($filenames !== []) {
|
||||
deleteBackupsS3($filenames, $s3);
|
||||
}
|
||||
}
|
||||
|
||||
$backup->delete();
|
||||
} finally {
|
||||
$lock->release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions\Shared;
|
||||
|
||||
use App\Actions\Application\StopApplication;
|
||||
use App\Actions\Database\StopDatabase;
|
||||
use App\Actions\Service\StopService;
|
||||
use App\Jobs\FinalizeResourceMigrationJob;
|
||||
use App\Jobs\HostPathCloneJob;
|
||||
use App\Jobs\ServerStorageSaveJob;
|
||||
use App\Jobs\VolumeCloneJob;
|
||||
use App\Models\Application;
|
||||
use App\Models\LocalPersistentVolume;
|
||||
use App\Models\Service;
|
||||
use App\Models\StandaloneClickhouse;
|
||||
use App\Models\StandaloneDocker;
|
||||
use App\Models\StandaloneDragonfly;
|
||||
use App\Models\StandaloneKeydb;
|
||||
use App\Models\StandaloneMariadb;
|
||||
use App\Models\StandaloneMongodb;
|
||||
use App\Models\StandaloneMysql;
|
||||
use App\Models\StandalonePostgresql;
|
||||
use App\Models\StandaloneRedis;
|
||||
use App\Models\SwarmDocker;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Bus;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Lorisleiva\Actions\Concerns\AsAction;
|
||||
|
||||
class MigrateResourceToDestination
|
||||
{
|
||||
use AsAction;
|
||||
|
||||
/**
|
||||
* @return array{async: bool, volume_jobs: int, message: string}
|
||||
*/
|
||||
public function handle(
|
||||
Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource,
|
||||
StandaloneDocker|SwarmDocker $destination,
|
||||
bool $migrateVolumes = true,
|
||||
): array {
|
||||
if (! isDev()) {
|
||||
throw ValidationException::withMessages([
|
||||
'destination_id' => 'Resource migration is only available in development mode.',
|
||||
]);
|
||||
}
|
||||
|
||||
$resource->loadMissing(['destination.server']);
|
||||
$sourceDestination = $resource->destination;
|
||||
|
||||
if (! $sourceDestination) {
|
||||
throw ValidationException::withMessages([
|
||||
'destination_id' => 'Resource has no destination to migrate from.',
|
||||
]);
|
||||
}
|
||||
|
||||
if (
|
||||
(int) $sourceDestination->id === (int) $destination->id
|
||||
&& $sourceDestination->getMorphClass() === $destination->getMorphClass()
|
||||
) {
|
||||
throw ValidationException::withMessages([
|
||||
'destination_id' => 'Resource is already on the selected destination.',
|
||||
]);
|
||||
}
|
||||
|
||||
$sourceServer = $sourceDestination->server;
|
||||
$targetServer = $destination->server;
|
||||
|
||||
if (! $targetServer) {
|
||||
throw ValidationException::withMessages([
|
||||
'destination_id' => 'Target destination has no server.',
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $targetServer->canHostResources()) {
|
||||
throw ValidationException::withMessages([
|
||||
'destination_id' => 'The selected server cannot host resources.',
|
||||
]);
|
||||
}
|
||||
|
||||
$targetServer->refresh();
|
||||
if (! $targetServer->isFunctional()) {
|
||||
throw ValidationException::withMessages([
|
||||
'destination_id' => 'Target server is not validated and reachable.',
|
||||
]);
|
||||
}
|
||||
|
||||
$crossServer = $sourceServer && (int) $sourceServer->id !== (int) $targetServer->id;
|
||||
|
||||
if (! $crossServer) {
|
||||
throw ValidationException::withMessages([
|
||||
'destination_id' => 'Migration requires a different server. Choose another server destination.',
|
||||
]);
|
||||
}
|
||||
|
||||
if ($migrateVolumes) {
|
||||
if (! $sourceServer?->isFunctional()) {
|
||||
throw ValidationException::withMessages([
|
||||
'destination_id' => 'Source server is not functional. Cannot migrate volume data.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$this->stopResource($resource);
|
||||
|
||||
$jobs = [];
|
||||
if ($migrateVolumes) {
|
||||
$jobs = $this->buildVolumeJobs($resource, $sourceServer, $targetServer);
|
||||
}
|
||||
|
||||
if ($jobs !== []) {
|
||||
Bus::chain([
|
||||
...$jobs,
|
||||
new FinalizeResourceMigrationJob($resource, $destination),
|
||||
])->dispatch();
|
||||
|
||||
return [
|
||||
'async' => true,
|
||||
'volume_jobs' => count($jobs),
|
||||
'message' => 'Migration started. The resource was stopped and volume data is being transferred. Destination will update when transfer completes. Redeploy afterwards.',
|
||||
];
|
||||
}
|
||||
|
||||
$this->applyDestination($resource, $destination);
|
||||
|
||||
return [
|
||||
'async' => false,
|
||||
'volume_jobs' => 0,
|
||||
'message' => $migrateVolumes
|
||||
? 'Resource migrated to the new server. Redeploy when ready.'
|
||||
: 'Resource migrated to the new server. Volume data was not transferred. Redeploy when ready.',
|
||||
];
|
||||
}
|
||||
|
||||
public function applyDestination(
|
||||
Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource,
|
||||
StandaloneDocker|SwarmDocker $destination,
|
||||
): void {
|
||||
$payload = [
|
||||
'destination_id' => $destination->id,
|
||||
'destination_type' => $destination->getMorphClass(),
|
||||
];
|
||||
|
||||
if ($resource instanceof Service) {
|
||||
$payload['server_id'] = $destination->server_id;
|
||||
} else {
|
||||
// Service status is computed from child containers, not a DB column.
|
||||
$payload['status'] = 'exited';
|
||||
$payload['started_at'] = null;
|
||||
}
|
||||
|
||||
$resource->fill($payload)->save();
|
||||
|
||||
if ($resource instanceof Application) {
|
||||
$resource->additional_networks()->detach();
|
||||
$this->regenerateApplicationLabels($resource->fresh(['destination.server', 'settings']));
|
||||
}
|
||||
|
||||
if ($resource instanceof Service) {
|
||||
foreach ($resource->applications() as $application) {
|
||||
$application->fill(['status' => 'exited'])->save();
|
||||
}
|
||||
foreach ($resource->databases() as $database) {
|
||||
$database->fill(['status' => 'exited'])->save();
|
||||
}
|
||||
}
|
||||
|
||||
$this->resaveFileStorages($resource->fresh());
|
||||
}
|
||||
|
||||
protected function stopResource(
|
||||
Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource,
|
||||
): void {
|
||||
try {
|
||||
if ($resource instanceof Application) {
|
||||
StopApplication::run($resource, previewDeployments: false, dockerCleanup: false);
|
||||
} elseif ($resource instanceof Service) {
|
||||
StopService::run($resource, deleteConnectedNetworks: false, dockerCleanup: false);
|
||||
} else {
|
||||
StopDatabase::run($resource, dockerCleanup: false);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
\Log::warning('Failed to stop resource during migration: '.$e->getMessage(), [
|
||||
'resource_type' => $resource->getMorphClass(),
|
||||
'resource_uuid' => $resource->uuid ?? null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, VolumeCloneJob|HostPathCloneJob>
|
||||
*/
|
||||
protected function buildVolumeJobs(
|
||||
Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource,
|
||||
$sourceServer,
|
||||
$targetServer,
|
||||
): array {
|
||||
$jobs = [];
|
||||
$seenNamedVolumes = [];
|
||||
$seenHostPaths = [];
|
||||
|
||||
foreach ($this->collectPersistentVolumes($resource) as $volume) {
|
||||
if (! $volume instanceof LocalPersistentVolume) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$hostPath = filled($volume->host_path) ? (string) $volume->host_path : null;
|
||||
|
||||
if ($hostPath) {
|
||||
if (isset($seenHostPaths[$hostPath])) {
|
||||
continue;
|
||||
}
|
||||
$seenHostPaths[$hostPath] = true;
|
||||
$jobs[] = new HostPathCloneJob($hostPath, $hostPath, $sourceServer, $targetServer);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = (string) $volume->name;
|
||||
if ($name === '' || isset($seenNamedVolumes[$name])) {
|
||||
continue;
|
||||
}
|
||||
$seenNamedVolumes[$name] = true;
|
||||
$jobs[] = new VolumeCloneJob($name, $name, $sourceServer, $targetServer, $volume);
|
||||
}
|
||||
|
||||
return $jobs;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, LocalPersistentVolume>
|
||||
*/
|
||||
protected function collectPersistentVolumes(
|
||||
Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource,
|
||||
) {
|
||||
if ($resource instanceof Service) {
|
||||
$volumes = collect();
|
||||
foreach ($resource->applications() as $application) {
|
||||
$volumes = $volumes->merge($application->persistentStorages()->get());
|
||||
}
|
||||
foreach ($resource->databases() as $database) {
|
||||
$volumes = $volumes->merge($database->persistentStorages()->get());
|
||||
}
|
||||
|
||||
return $volumes;
|
||||
}
|
||||
|
||||
return $resource->persistentStorages()->get();
|
||||
}
|
||||
|
||||
protected function regenerateApplicationLabels(Application $application): void
|
||||
{
|
||||
$settings = $application->settings;
|
||||
if (! $settings || ! $settings->is_container_label_readonly_enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($application->destination?->server?->proxyType() === 'NONE') {
|
||||
return;
|
||||
}
|
||||
|
||||
$customLabels = str(implode('|coolify|', generateLabelsApplication($application)))->replace('|coolify|', "\n");
|
||||
$application->custom_labels = base64_encode($customLabels);
|
||||
$application->save();
|
||||
}
|
||||
|
||||
protected function resaveFileStorages(
|
||||
Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource,
|
||||
): void {
|
||||
$fileStorages = collect();
|
||||
|
||||
if ($resource instanceof Service) {
|
||||
foreach ($resource->applications() as $application) {
|
||||
$fileStorages = $fileStorages->merge($application->fileStorages()->get());
|
||||
}
|
||||
foreach ($resource->databases() as $database) {
|
||||
$fileStorages = $fileStorages->merge($database->fileStorages()->get());
|
||||
}
|
||||
} elseif (method_exists($resource, 'fileStorages')) {
|
||||
$fileStorages = $resource->fileStorages()->get();
|
||||
}
|
||||
|
||||
foreach ($fileStorages as $storage) {
|
||||
if ($storage->is_host_file) {
|
||||
continue;
|
||||
}
|
||||
ServerStorageSaveJob::dispatch($storage);
|
||||
}
|
||||
}
|
||||
}
|
||||
+80
-35
@@ -1,30 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
namespace App\Actions\Stripe;
|
||||
|
||||
use App\Models\Subscription;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Lorisleiva\Actions\Concerns\AsAction;
|
||||
use Stripe\StripeClient;
|
||||
|
||||
class SyncStripeSubscriptionsJob implements ShouldBeEncrypted, ShouldQueue
|
||||
class SyncStripeSubscriptions
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
use AsAction;
|
||||
|
||||
public int $tries = 1;
|
||||
private const VALID_STRIPE_STATUSES = ['active', 'past_due'];
|
||||
|
||||
public int $timeout = 1800; // 30 minutes max
|
||||
|
||||
public function __construct(public bool $fix = false)
|
||||
{
|
||||
$this->onQueue('high');
|
||||
}
|
||||
|
||||
public function handle(?\Closure $onProgress = null): array
|
||||
public function handle(bool $fix = false, ?\Closure $onProgress = null): array
|
||||
{
|
||||
if (! isCloud() || ! isStripe()) {
|
||||
return ['error' => 'Not running on Cloud or Stripe not configured'];
|
||||
@@ -34,7 +22,9 @@ class SyncStripeSubscriptionsJob implements ShouldBeEncrypted, ShouldQueue
|
||||
->where('stripe_invoice_paid', true)
|
||||
->get();
|
||||
|
||||
$stripe = app(StripeClient::class);
|
||||
$stripe = app()->bound(StripeClient::class)
|
||||
? app(StripeClient::class)
|
||||
: new StripeClient(config('subscription.stripe_api_key'));
|
||||
|
||||
// Bulk fetch all valid subscription IDs from Stripe (active + past_due)
|
||||
$validStripeIds = $this->fetchValidStripeSubscriptionIds($stripe, $onProgress);
|
||||
@@ -43,13 +33,20 @@ class SyncStripeSubscriptionsJob implements ShouldBeEncrypted, ShouldQueue
|
||||
$staleSubscriptions = $subscriptions->filter(
|
||||
fn (Subscription $sub) => ! in_array($sub->stripe_subscription_id, $validStripeIds)
|
||||
);
|
||||
$staleSubscriptionCount = $staleSubscriptions->count();
|
||||
|
||||
$onProgress?->__invoke('checking', 0, $staleSubscriptionCount);
|
||||
|
||||
// For each stale subscription, get the exact Stripe status and check for resubscriptions
|
||||
$discrepancies = [];
|
||||
$resubscribed = [];
|
||||
$errors = [];
|
||||
$fixedCount = 0;
|
||||
$manualReviewCount = 0;
|
||||
|
||||
foreach ($staleSubscriptions->values() as $index => $subscription) {
|
||||
$onProgress?->__invoke('checking', $index + 1, $staleSubscriptionCount);
|
||||
|
||||
foreach ($staleSubscriptions as $subscription) {
|
||||
try {
|
||||
$stripeSubscription = $stripe->subscriptions->retrieve(
|
||||
$subscription->stripe_subscription_id
|
||||
@@ -66,8 +63,18 @@ class SyncStripeSubscriptionsJob implements ShouldBeEncrypted, ShouldQueue
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if this user resubscribed under a different customer/subscription
|
||||
if (in_array($stripeStatus, self::VALID_STRIPE_STATUSES, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$activeSub = $this->findActiveSubscriptionByEmail($stripe, $stripeSubscription->customer);
|
||||
$validReplacement = Subscription::query()
|
||||
->where('team_id', $subscription->team_id)
|
||||
->where('id', '!=', $subscription->id)
|
||||
->where('stripe_invoice_paid', true)
|
||||
->whereIn('stripe_subscription_id', $validStripeIds)
|
||||
->first();
|
||||
|
||||
if ($activeSub) {
|
||||
$resubscribed[] = [
|
||||
'subscription_id' => $subscription->id,
|
||||
@@ -78,33 +85,69 @@ class SyncStripeSubscriptionsJob implements ShouldBeEncrypted, ShouldQueue
|
||||
'new_stripe_subscription_id' => $activeSub['subscription_id'],
|
||||
'new_stripe_customer_id' => $activeSub['customer_id'],
|
||||
'new_status' => $activeSub['status'],
|
||||
'linked_to_team' => $validReplacement?->stripe_subscription_id === $activeSub['subscription_id'],
|
||||
];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$inactiveSubscription = null;
|
||||
if (! $validReplacement && ! $activeSub) {
|
||||
$inactiveSubscription = Subscription::query()
|
||||
->where('team_id', $subscription->team_id)
|
||||
->where('id', '!=', $subscription->id)
|
||||
->where('stripe_invoice_paid', false)
|
||||
->first();
|
||||
}
|
||||
|
||||
$resolution = match (true) {
|
||||
(bool) $validReplacement => 'delete_stale',
|
||||
(bool) $activeSub => 'manual_review',
|
||||
(bool) $inactiveSubscription => 'delete_stale',
|
||||
default => 'end_subscription',
|
||||
};
|
||||
|
||||
$discrepancies[] = [
|
||||
'subscription_id' => $subscription->id,
|
||||
'team_id' => $subscription->team_id,
|
||||
'stripe_subscription_id' => $subscription->stripe_subscription_id,
|
||||
'stripe_status' => $stripeStatus,
|
||||
'resolution' => $resolution,
|
||||
];
|
||||
|
||||
if ($this->fix) {
|
||||
$subscription->update([
|
||||
'stripe_invoice_paid' => false,
|
||||
'stripe_past_due' => false,
|
||||
]);
|
||||
if ($fix) {
|
||||
$team = $subscription->team;
|
||||
|
||||
if ($stripeStatus === 'canceled') {
|
||||
$subscription->team?->subscriptionEnded();
|
||||
if ($resolution === 'manual_review') {
|
||||
$manualReviewCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($resolution === 'delete_stale') {
|
||||
if (! $validReplacement && $inactiveSubscription && $team) {
|
||||
$team->subscriptionEnded($inactiveSubscription);
|
||||
}
|
||||
|
||||
$subscription->delete();
|
||||
$fixedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($team) {
|
||||
$team->subscriptionEnded($subscription);
|
||||
} else {
|
||||
$subscription->update([
|
||||
'stripe_invoice_paid' => false,
|
||||
'stripe_past_due' => false,
|
||||
]);
|
||||
}
|
||||
$fixedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->fix && count($discrepancies) > 0) {
|
||||
if ($fix && $fixedCount > 0) {
|
||||
send_internal_notification(
|
||||
'SyncStripeSubscriptionsJob: Fixed '.count($discrepancies)." discrepancies:\n".
|
||||
"SyncStripeSubscriptions: Fixed {$fixedCount} discrepancies:\n".
|
||||
json_encode($discrepancies, JSON_PRETTY_PRINT)
|
||||
);
|
||||
}
|
||||
@@ -114,7 +157,9 @@ class SyncStripeSubscriptionsJob implements ShouldBeEncrypted, ShouldQueue
|
||||
'discrepancies' => $discrepancies,
|
||||
'resubscribed' => $resubscribed,
|
||||
'errors' => $errors,
|
||||
'fixed' => $this->fix,
|
||||
'fixed' => $fix,
|
||||
'fixed_count' => $fixedCount,
|
||||
'manual_review_count' => $manualReviewCount,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -183,13 +228,13 @@ class SyncStripeSubscriptionsJob implements ShouldBeEncrypted, ShouldQueue
|
||||
$validIds = [];
|
||||
$fetched = 0;
|
||||
|
||||
foreach (['active', 'past_due'] as $status) {
|
||||
foreach (self::VALID_STRIPE_STATUSES as $status) {
|
||||
foreach ($stripe->subscriptions->all(['status' => $status, 'limit' => 100])->autoPagingIterator() as $sub) {
|
||||
$validIds[] = $sub->id;
|
||||
$fetched++;
|
||||
|
||||
if ($onProgress) {
|
||||
$onProgress($fetched);
|
||||
$onProgress('fetching', $fetched, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,7 @@ class DeleteUserResources
|
||||
|
||||
return [
|
||||
'applications' => $applications->unique('id'),
|
||||
'databases' => $databases->unique('id'),
|
||||
'databases' => $databases->unique(fn ($database) => $database::class.':'.$database->id),
|
||||
'services' => $services->unique('id'),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace App\Auth\Oidc\Exceptions;
|
||||
|
||||
class OidcDiscoveryException extends OidcException {}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace App\Auth\Oidc\Exceptions;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class OidcException extends RuntimeException {}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace App\Auth\Oidc\Exceptions;
|
||||
|
||||
class OidcJwksException extends OidcException {}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace App\Auth\Oidc\Exceptions;
|
||||
|
||||
class OidcSigningKeyNotFoundException extends OidcTokenException {}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace App\Auth\Oidc\Exceptions;
|
||||
|
||||
class OidcTokenException extends OidcException {}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Auth\Oidc;
|
||||
|
||||
use App\Models\OauthSetting;
|
||||
|
||||
final readonly class OidcConfig
|
||||
{
|
||||
/**
|
||||
* @param array<int, string> $scopes
|
||||
*/
|
||||
public function __construct(
|
||||
public string $issuerUrl,
|
||||
public string $clientId,
|
||||
public string $clientSecret,
|
||||
public string $redirectUri,
|
||||
public array $scopes = ['openid', 'email', 'profile'],
|
||||
public bool $usePkce = true,
|
||||
public int $clockSkewSeconds = 60,
|
||||
) {}
|
||||
|
||||
public static function fromOauthSetting(OauthSetting $setting): self
|
||||
{
|
||||
return new self(
|
||||
issuerUrl: rtrim((string) $setting->base_url, '/'),
|
||||
clientId: (string) $setting->client_id,
|
||||
clientSecret: (string) $setting->client_secret,
|
||||
redirectUri: filled($setting->redirect_uri) ? $setting->redirect_uri : route('auth.callback', 'oidc'),
|
||||
scopes: $setting->scopeList(),
|
||||
usePkce: $setting->use_pkce ?? true,
|
||||
clockSkewSeconds: $setting->clock_skew_seconds ?? 60,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Auth\Oidc;
|
||||
|
||||
use App\Auth\Oidc\Exceptions\OidcDiscoveryException;
|
||||
|
||||
final readonly class OidcDiscoveryDocument
|
||||
{
|
||||
/**
|
||||
* @param array<int, string> $supportedScopes
|
||||
* @param array<int, string> $supportedClaims
|
||||
* @param array<int, string> $idTokenSigningAlgValuesSupported
|
||||
*/
|
||||
public function __construct(
|
||||
public string $issuer,
|
||||
public string $authorizationEndpoint,
|
||||
public string $tokenEndpoint,
|
||||
public string $userinfoEndpoint,
|
||||
public string $jwksUri,
|
||||
public ?string $endSessionEndpoint = null,
|
||||
public array $supportedScopes = [],
|
||||
public array $supportedClaims = [],
|
||||
public array $idTokenSigningAlgValuesSupported = [],
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public static function fromArray(array $payload): self
|
||||
{
|
||||
foreach (['issuer', 'authorization_endpoint', 'token_endpoint', 'userinfo_endpoint', 'jwks_uri'] as $field) {
|
||||
if (! is_string($payload[$field] ?? null) || trim($payload[$field]) === '') {
|
||||
throw new OidcDiscoveryException("Discovery document is missing required field: {$field}");
|
||||
}
|
||||
}
|
||||
|
||||
return new self(
|
||||
issuer: $payload['issuer'],
|
||||
authorizationEndpoint: $payload['authorization_endpoint'],
|
||||
tokenEndpoint: $payload['token_endpoint'],
|
||||
userinfoEndpoint: $payload['userinfo_endpoint'],
|
||||
jwksUri: $payload['jwks_uri'],
|
||||
endSessionEndpoint: is_string($payload['end_session_endpoint'] ?? null) ? $payload['end_session_endpoint'] : null,
|
||||
supportedScopes: self::stringList($payload['scopes_supported'] ?? []),
|
||||
supportedClaims: self::stringList($payload['claims_supported'] ?? []),
|
||||
idTokenSigningAlgValuesSupported: self::stringList($payload['id_token_signing_alg_values_supported'] ?? []),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private static function stringList(mixed $value): array
|
||||
{
|
||||
if (! is_array($value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(array_map('strval', $value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Auth\Oidc;
|
||||
|
||||
use App\Auth\Oidc\Exceptions\OidcDiscoveryException;
|
||||
use App\Auth\Oidc\Exceptions\OidcJwksException;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Throwable;
|
||||
|
||||
class OidcDiscoveryService
|
||||
{
|
||||
public function discover(string $issuerUrl): OidcDiscoveryDocument
|
||||
{
|
||||
$this->assertHttpsUrl($issuerUrl, new OidcDiscoveryException('Issuer URL must be an absolute HTTPS URL.'));
|
||||
|
||||
$issuerUrl = rtrim($issuerUrl, '/');
|
||||
$cacheKey = 'oidc:discovery:'.hash('sha256', $issuerUrl);
|
||||
|
||||
return Cache::remember($cacheKey, 3600, function () use ($issuerUrl): OidcDiscoveryDocument {
|
||||
$url = $issuerUrl.'/.well-known/openid-configuration';
|
||||
|
||||
try {
|
||||
$response = Http::timeout(5)->connectTimeout(3)->acceptJson()->get($url);
|
||||
} catch (Throwable $e) {
|
||||
throw new OidcDiscoveryException("Failed to fetch discovery document: {$e->getMessage()}", previous: $e);
|
||||
}
|
||||
|
||||
if ($response->failed()) {
|
||||
throw new OidcDiscoveryException("Discovery endpoint returned HTTP {$response->status()}");
|
||||
}
|
||||
|
||||
$json = $response->json();
|
||||
if (! is_array($json) || $json === []) {
|
||||
throw new OidcDiscoveryException('Discovery endpoint returned invalid JSON.');
|
||||
}
|
||||
|
||||
$discovery = OidcDiscoveryDocument::fromArray($json);
|
||||
if (rtrim($discovery->issuer, '/') !== $issuerUrl) {
|
||||
throw new OidcDiscoveryException('Discovery issuer does not match the configured issuer URL.');
|
||||
}
|
||||
|
||||
return $discovery;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the JWKS for the given URI.
|
||||
*
|
||||
* When $forceRefresh is true the cached document is bypassed so freshly
|
||||
* rotated signing keys become visible immediately. A short cooldown still
|
||||
* prevents a flood of upstream requests if many logins miss the same kid.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function jwks(string $jwksUri, bool $forceRefresh = false): array
|
||||
{
|
||||
$this->assertHttpsUrl($jwksUri, new OidcJwksException('JWKS URI must be an absolute HTTPS URL.'));
|
||||
|
||||
$cacheKey = 'oidc:jwks:'.hash('sha256', $jwksUri);
|
||||
|
||||
if ($forceRefresh) {
|
||||
$cooldownKey = $cacheKey.':refresh';
|
||||
if (Cache::add($cooldownKey, true, 60)) {
|
||||
Cache::forget($cacheKey);
|
||||
}
|
||||
}
|
||||
|
||||
return Cache::remember($cacheKey, 21600, function () use ($jwksUri): array {
|
||||
try {
|
||||
$response = Http::timeout(5)->connectTimeout(3)->acceptJson()->get($jwksUri);
|
||||
} catch (Throwable $e) {
|
||||
throw new OidcJwksException("Failed to fetch JWKS: {$e->getMessage()}", previous: $e);
|
||||
}
|
||||
|
||||
if ($response->failed()) {
|
||||
throw new OidcJwksException("JWKS endpoint returned HTTP {$response->status()}");
|
||||
}
|
||||
|
||||
$json = $response->json();
|
||||
if (! is_array($json) || ! is_array($json['keys'] ?? null)) {
|
||||
throw new OidcJwksException("JWKS endpoint returned an invalid payload without 'keys'.");
|
||||
}
|
||||
|
||||
return $json;
|
||||
});
|
||||
}
|
||||
|
||||
private function assertHttpsUrl(string $url, Throwable $exception): void
|
||||
{
|
||||
$parts = parse_url($url);
|
||||
|
||||
if (($parts['scheme'] ?? null) !== 'https' || ! is_string($parts['host'] ?? null) || $parts['host'] === '') {
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
namespace App\Auth\Oidc;
|
||||
|
||||
use App\Auth\Oidc\Exceptions\OidcSigningKeyNotFoundException;
|
||||
use App\Auth\Oidc\Exceptions\OidcTokenException;
|
||||
use Firebase\JWT\JWK;
|
||||
use Firebase\JWT\JWT;
|
||||
use Throwable;
|
||||
|
||||
class OidcTokenValidator
|
||||
{
|
||||
/**
|
||||
* Algorithms we accept for id_token signatures. RS256 only — this is the
|
||||
* OIDC baseline and a strict allowlist prevents algorithm-confusion and
|
||||
* "none" attacks.
|
||||
*/
|
||||
private const ALLOWED_ALGORITHM = 'RS256';
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $jwks
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function validate(
|
||||
string $idToken,
|
||||
OidcDiscoveryDocument $discovery,
|
||||
array $jwks,
|
||||
string $clientId,
|
||||
?string $expectedNonce = null,
|
||||
int $clockSkewSeconds = 60,
|
||||
): array {
|
||||
$kid = $this->extractKid($idToken);
|
||||
|
||||
try {
|
||||
$keys = JWK::parseKeySet($this->signingKeysOnly($jwks), self::ALLOWED_ALGORITHM);
|
||||
} catch (Throwable $e) {
|
||||
throw new OidcTokenException("Unable to parse JWKS: {$e->getMessage()}", previous: $e);
|
||||
}
|
||||
|
||||
// Surface an unknown signing key distinctly so the caller can refresh
|
||||
// the JWKS once (key rotation) before giving up.
|
||||
if (! array_key_exists($kid, $keys)) {
|
||||
throw new OidcSigningKeyNotFoundException('No matching JWKS key found for id_token kid.');
|
||||
}
|
||||
|
||||
$previousLeeway = JWT::$leeway;
|
||||
JWT::$leeway = $clockSkewSeconds;
|
||||
|
||||
try {
|
||||
// Validates signature, header alg against the key alg (RS256),
|
||||
// exp, nbf and iat. Throws on any failure.
|
||||
$claims = (array) JWT::decode($idToken, $keys);
|
||||
} catch (OidcTokenException $e) {
|
||||
throw $e;
|
||||
} catch (Throwable $e) {
|
||||
throw new OidcTokenException("id_token validation failed: {$e->getMessage()}", previous: $e);
|
||||
} finally {
|
||||
JWT::$leeway = $previousLeeway;
|
||||
}
|
||||
|
||||
$this->assertExpiry($claims);
|
||||
$this->assertIssuer($claims, $discovery->issuer);
|
||||
$this->assertAudience($claims, $clientId);
|
||||
$this->assertNonce($claims, $expectedNonce);
|
||||
$this->assertSubject($claims);
|
||||
|
||||
return $claims;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop JWKS entries explicitly marked for anything other than signing
|
||||
* (e.g. "use":"enc") so they can never verify an id_token signature.
|
||||
* firebase/php-jwt does not honour the "use" parameter on its own.
|
||||
*
|
||||
* @param array<string, mixed> $jwks
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function signingKeysOnly(array $jwks): array
|
||||
{
|
||||
$keys = array_values(array_filter(
|
||||
$jwks['keys'] ?? [],
|
||||
fn ($jwk): bool => is_array($jwk) && (! isset($jwk['use']) || $jwk['use'] === 'sig'),
|
||||
));
|
||||
|
||||
return ['keys' => $keys];
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode just the JWT header to read the kid before signature
|
||||
* verification, so an unknown key can be reported as a rotation miss.
|
||||
*/
|
||||
private function extractKid(string $idToken): string
|
||||
{
|
||||
$segments = explode('.', $idToken);
|
||||
if (count($segments) !== 3) {
|
||||
throw new OidcTokenException('Malformed id_token.');
|
||||
}
|
||||
|
||||
$header = json_decode($this->base64UrlDecode($segments[0]), true);
|
||||
if (! is_array($header)) {
|
||||
throw new OidcTokenException('id_token header contains invalid JSON.');
|
||||
}
|
||||
|
||||
if (($header['alg'] ?? null) !== self::ALLOWED_ALGORITHM) {
|
||||
throw new OidcTokenException('id_token uses a disallowed algorithm.');
|
||||
}
|
||||
|
||||
$kid = $header['kid'] ?? null;
|
||||
if (! is_string($kid) || $kid === '') {
|
||||
throw new OidcTokenException('id_token header is missing kid.');
|
||||
}
|
||||
|
||||
return $kid;
|
||||
}
|
||||
|
||||
private function base64UrlDecode(string $value): string
|
||||
{
|
||||
$remainder = strlen($value) % 4;
|
||||
if ($remainder !== 0) {
|
||||
$value .= str_repeat('=', 4 - $remainder);
|
||||
}
|
||||
|
||||
$decoded = base64_decode(strtr($value, '-_', '+/'), true);
|
||||
if ($decoded === false) {
|
||||
throw new OidcTokenException('Invalid base64url value in id_token header.');
|
||||
}
|
||||
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $claims
|
||||
*/
|
||||
private function assertExpiry(array $claims): void
|
||||
{
|
||||
// Firebase enforces the exp window when present; OIDC requires it to exist.
|
||||
if (! is_numeric($claims['exp'] ?? null)) {
|
||||
throw new OidcTokenException('id_token is missing the exp claim.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $claims
|
||||
*/
|
||||
private function assertSubject(array $claims): void
|
||||
{
|
||||
$subject = $claims['sub'] ?? null;
|
||||
if (! is_string($subject) || $subject === '') {
|
||||
throw new OidcTokenException('id_token subject is missing or invalid.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $claims
|
||||
*/
|
||||
private function assertIssuer(array $claims, string $expectedIssuer): void
|
||||
{
|
||||
if (($claims['iss'] ?? null) !== $expectedIssuer) {
|
||||
throw new OidcTokenException('id_token issuer does not match discovery issuer.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $claims
|
||||
*/
|
||||
private function assertAudience(array $claims, string $clientId): void
|
||||
{
|
||||
$audience = $claims['aud'] ?? null;
|
||||
if (is_string($audience)) {
|
||||
$audience = [$audience];
|
||||
}
|
||||
|
||||
if (! is_array($audience) || ! in_array($clientId, $audience, true)) {
|
||||
throw new OidcTokenException('id_token audience does not include configured client id.');
|
||||
}
|
||||
|
||||
if (count($audience) > 1 && (! isset($claims['azp']) || $claims['azp'] !== $clientId)) {
|
||||
throw new OidcTokenException('id_token azp is required when aud contains multiple values and must match configured client id.');
|
||||
}
|
||||
|
||||
if (isset($claims['azp']) && $claims['azp'] !== $clientId) {
|
||||
throw new OidcTokenException('id_token azp does not match configured client id.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $claims
|
||||
*/
|
||||
private function assertNonce(array $claims, ?string $expectedNonce): void
|
||||
{
|
||||
if ($expectedNonce === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (($claims['nonce'] ?? null) !== $expectedNonce) {
|
||||
throw new OidcTokenException('id_token nonce does not match.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Auth\Oidc;
|
||||
|
||||
use Laravel\Socialite\Two\User as SocialiteUser;
|
||||
|
||||
class OidcUser extends SocialiteUser
|
||||
{
|
||||
public ?string $issuer = null;
|
||||
|
||||
public ?string $subject = null;
|
||||
|
||||
public bool $emailVerified = false;
|
||||
|
||||
/**
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
public array $idTokenClaims = [];
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $claims
|
||||
*/
|
||||
public function setIdTokenClaims(array $claims): self
|
||||
{
|
||||
$this->idTokenClaims = $claims;
|
||||
$this->issuer = is_string($claims['iss'] ?? null) ? $claims['iss'] : null;
|
||||
$this->subject = is_string($claims['sub'] ?? null) ? $claims['sub'] : null;
|
||||
$this->emailVerified = ($claims['email_verified'] ?? false) === true;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
<?php
|
||||
|
||||
namespace App\Auth\Oidc\Socialite;
|
||||
|
||||
use App\Auth\Oidc\Exceptions\OidcException;
|
||||
use App\Auth\Oidc\Exceptions\OidcSigningKeyNotFoundException;
|
||||
use App\Auth\Oidc\OidcConfig;
|
||||
use App\Auth\Oidc\OidcDiscoveryDocument;
|
||||
use App\Auth\Oidc\OidcDiscoveryService;
|
||||
use App\Auth\Oidc\OidcTokenValidator;
|
||||
use App\Auth\Oidc\OidcUser;
|
||||
use GuzzleHttp\RequestOptions;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Str;
|
||||
use Laravel\Socialite\Two\AbstractProvider;
|
||||
use Laravel\Socialite\Two\InvalidStateException;
|
||||
use Laravel\Socialite\Two\ProviderInterface;
|
||||
|
||||
class OidcProvider extends AbstractProvider implements ProviderInterface
|
||||
{
|
||||
private const int OIDC_FLOW_TTL_MINUTES = 10;
|
||||
|
||||
/**
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $scopes = ['openid', 'email', 'profile'];
|
||||
|
||||
protected $scopeSeparator = ' ';
|
||||
|
||||
protected ?OidcConfig $oidcConfig = null;
|
||||
|
||||
protected ?OidcDiscoveryDocument $discovery = null;
|
||||
|
||||
public function __construct(
|
||||
Request $request,
|
||||
protected OidcDiscoveryService $discoveryService,
|
||||
protected OidcTokenValidator $tokenValidator,
|
||||
string $clientId,
|
||||
string $clientSecret,
|
||||
string $redirectUrl,
|
||||
) {
|
||||
parent::__construct($request, $clientId, $clientSecret, $redirectUrl);
|
||||
}
|
||||
|
||||
public function setConfig(OidcConfig $config): self
|
||||
{
|
||||
$this->oidcConfig = $config;
|
||||
$this->clientId = $config->clientId;
|
||||
$this->clientSecret = $config->clientSecret;
|
||||
$this->redirectUrl = $config->redirectUri;
|
||||
$this->scopes = $config->scopes;
|
||||
$this->discovery = null;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getConfig(): OidcConfig
|
||||
{
|
||||
if ($this->oidcConfig === null) {
|
||||
throw new OidcException('OIDC provider config is not set.');
|
||||
}
|
||||
|
||||
return $this->oidcConfig;
|
||||
}
|
||||
|
||||
protected function getAuthUrl($state): string
|
||||
{
|
||||
$config = $this->getConfig();
|
||||
$nonce = Str::random(40);
|
||||
$this->putOidcFlowValue($this->nonceSessionKey($state), $nonce);
|
||||
|
||||
$extra = ['nonce' => $nonce];
|
||||
if ($config->usePkce) {
|
||||
$verifier = $this->generateCodeVerifier();
|
||||
$this->putOidcFlowValue($this->verifierSessionKey($state), $verifier);
|
||||
$extra['code_challenge'] = $this->codeChallenge($verifier);
|
||||
$extra['code_challenge_method'] = 'S256';
|
||||
}
|
||||
|
||||
return $this->buildAuthUrlFromBase($this->resolveDiscovery()->authorizationEndpoint, $state)
|
||||
.'&'.http_build_query($extra, '', '&', $this->encodingType);
|
||||
}
|
||||
|
||||
protected function getTokenUrl(): string
|
||||
{
|
||||
return $this->resolveDiscovery()->tokenEndpoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function getUserByToken($token): array
|
||||
{
|
||||
$response = $this->getHttpClient()->get($this->resolveDiscovery()->userinfoEndpoint, [
|
||||
RequestOptions::HEADERS => [
|
||||
'Accept' => 'application/json',
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
],
|
||||
RequestOptions::CONNECT_TIMEOUT => 5,
|
||||
RequestOptions::TIMEOUT => 10,
|
||||
]);
|
||||
|
||||
$decoded = json_decode((string) $response->getBody(), true);
|
||||
|
||||
return is_array($decoded) ? $decoded : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $user
|
||||
*/
|
||||
protected function mapUserToObject(array $user)
|
||||
{
|
||||
return (new OidcUser)->setRaw($user)->map([
|
||||
'id' => $user['sub'] ?? null,
|
||||
'nickname' => $user['preferred_username'] ?? null,
|
||||
'name' => $this->resolveName($user),
|
||||
'email' => $user['email'] ?? null,
|
||||
'avatar' => $user['picture'] ?? null,
|
||||
]);
|
||||
}
|
||||
|
||||
public function user()
|
||||
{
|
||||
if ($this->user) {
|
||||
return $this->user;
|
||||
}
|
||||
|
||||
if ($this->hasInvalidState()) {
|
||||
throw new InvalidStateException;
|
||||
}
|
||||
|
||||
$tokenResponse = $this->getAccessTokenResponse($this->getCode());
|
||||
$accessToken = Arr::get($tokenResponse, 'access_token');
|
||||
$idToken = Arr::get($tokenResponse, 'id_token');
|
||||
|
||||
if (! is_string($accessToken) || $accessToken === '' || ! is_string($idToken) || $idToken === '') {
|
||||
throw new OidcException('OIDC token endpoint did not return required tokens.');
|
||||
}
|
||||
|
||||
$discovery = $this->resolveDiscovery();
|
||||
$config = $this->getConfig();
|
||||
$expectedNonce = $this->pullOidcFlowValue($this->nonceSessionKey((string) $this->request->input('state')));
|
||||
if ($expectedNonce === null) {
|
||||
throw new OidcException('OIDC login session expired. Please try again.');
|
||||
}
|
||||
|
||||
$claims = $this->validateIdToken($idToken, $discovery, $config, $expectedNonce);
|
||||
|
||||
$userinfo = $this->getUserByToken($accessToken);
|
||||
|
||||
// OIDC core §5.3.2: the userinfo sub MUST match the id_token sub.
|
||||
// Reject the response rather than trust unsigned userinfo claims.
|
||||
$userinfoSub = $userinfo['sub'] ?? null;
|
||||
if (is_string($userinfoSub) && $userinfoSub !== '' && $userinfoSub !== ($claims['sub'] ?? null)) {
|
||||
throw new OidcException('OIDC userinfo subject does not match the id_token subject.');
|
||||
}
|
||||
|
||||
$merged = array_merge($userinfo, $claims);
|
||||
|
||||
/** @var OidcUser $user */
|
||||
$user = $this->mapUserToObject($merged);
|
||||
$user->setIdTokenClaims($claims)
|
||||
->setToken($accessToken)
|
||||
->setRefreshToken(Arr::get($tokenResponse, 'refresh_token'))
|
||||
->setExpiresIn(Arr::get($tokenResponse, 'expires_in'));
|
||||
|
||||
return $this->user = $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the id_token, retrying once against a freshly fetched JWKS when
|
||||
* the signing key is unknown. This keeps logins working immediately after
|
||||
* the IdP rotates keys instead of failing until the JWKS cache expires.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function validateIdToken(
|
||||
string $idToken,
|
||||
OidcDiscoveryDocument $discovery,
|
||||
OidcConfig $config,
|
||||
?string $expectedNonce,
|
||||
): array {
|
||||
foreach ([false, true] as $forceRefresh) {
|
||||
try {
|
||||
return $this->tokenValidator->validate(
|
||||
idToken: $idToken,
|
||||
discovery: $discovery,
|
||||
jwks: $this->discoveryService->jwks($discovery->jwksUri, $forceRefresh),
|
||||
clientId: $config->clientId,
|
||||
expectedNonce: $expectedNonce,
|
||||
clockSkewSeconds: $config->clockSkewSeconds,
|
||||
);
|
||||
} catch (OidcSigningKeyNotFoundException $e) {
|
||||
if ($forceRefresh) {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new OidcSigningKeyNotFoundException('No matching JWKS key found for id_token kid.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function getAccessTokenResponse($code)
|
||||
{
|
||||
$fields = $this->getTokenFields($code);
|
||||
if ($this->getConfig()->usePkce) {
|
||||
$verifier = $this->pullOidcFlowValue($this->verifierSessionKey((string) $this->request->input('state')));
|
||||
if ($verifier === null) {
|
||||
throw new OidcException('OIDC login session expired. Please try again.');
|
||||
}
|
||||
|
||||
$fields['code_verifier'] = $verifier;
|
||||
}
|
||||
|
||||
$response = $this->getHttpClient()->post($this->getTokenUrl(), [
|
||||
RequestOptions::HEADERS => ['Accept' => 'application/json'],
|
||||
RequestOptions::FORM_PARAMS => $fields,
|
||||
RequestOptions::CONNECT_TIMEOUT => 5,
|
||||
RequestOptions::TIMEOUT => 10,
|
||||
]);
|
||||
|
||||
$decoded = json_decode((string) $response->getBody(), true);
|
||||
|
||||
return is_array($decoded) ? $decoded : [];
|
||||
}
|
||||
|
||||
protected function resolveDiscovery(): OidcDiscoveryDocument
|
||||
{
|
||||
return $this->discovery ??= $this->discoveryService->discover($this->getConfig()->issuerUrl);
|
||||
}
|
||||
|
||||
protected function generateCodeVerifier(): string
|
||||
{
|
||||
return rtrim(strtr(base64_encode(random_bytes(64)), '+/', '-_'), '=');
|
||||
}
|
||||
|
||||
protected function codeChallenge(string $verifier): string
|
||||
{
|
||||
return rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $user
|
||||
*/
|
||||
protected function resolveName(array $user): ?string
|
||||
{
|
||||
if (is_string($user['name'] ?? null) && $user['name'] !== '') {
|
||||
return $user['name'];
|
||||
}
|
||||
|
||||
$name = trim(((string) ($user['given_name'] ?? '')).' '.((string) ($user['family_name'] ?? '')));
|
||||
|
||||
return $name === '' ? null : $name;
|
||||
}
|
||||
|
||||
protected function putOidcFlowValue(string $key, string $value): void
|
||||
{
|
||||
$this->request->session()->put($key, [
|
||||
'value' => $value,
|
||||
'expires_at' => now()->addMinutes(self::OIDC_FLOW_TTL_MINUTES)->timestamp,
|
||||
]);
|
||||
}
|
||||
|
||||
protected function pullOidcFlowValue(string $key): ?string
|
||||
{
|
||||
$entry = $this->request->session()->pull($key);
|
||||
|
||||
if (! is_array($entry)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$value = $entry['value'] ?? null;
|
||||
$expiresAt = $entry['expires_at'] ?? null;
|
||||
|
||||
if (! is_string($value) || $value === '' || ! is_int($expiresAt)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($expiresAt < now()->timestamp) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
protected function nonceSessionKey(string $state): string
|
||||
{
|
||||
return "oidc.nonce.{$state}";
|
||||
}
|
||||
|
||||
protected function verifierSessionKey(string $state): string
|
||||
{
|
||||
return "oidc.code_verifier.{$state}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Cloud;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class CleanupUnverifiedUsers extends Command
|
||||
{
|
||||
protected $signature = 'cloud:cleanup-unverified-users
|
||||
{--yes : Delete eligible users instead of running a dry run}';
|
||||
|
||||
protected $description = 'Delete unverified users without Stripe subscriptions or defined resources';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
if (! isCloud()) {
|
||||
$this->error('This command can only be run on Coolify Cloud.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$eligibleUsers = $this->eligibleUsers();
|
||||
$eligibleCount = $eligibleUsers->count();
|
||||
|
||||
$this->info("Found {$eligibleCount} ".Str::plural('unverified user', $eligibleCount).' eligible for deletion.');
|
||||
$shouldDelete = (bool) $this->option('yes');
|
||||
|
||||
if (! $shouldDelete) {
|
||||
$this->warn('Dry run only. Use --yes to delete eligible users.');
|
||||
}
|
||||
|
||||
$deletedCount = 0;
|
||||
|
||||
if ($eligibleCount > 0) {
|
||||
$progressAction = $shouldDelete ? 'Deleting' : 'Checking';
|
||||
$progressBar = $this->output->createProgressBar($eligibleCount);
|
||||
$progressBar->setFormat("{$progressAction} eligible users: %current%/%max% [%bar%] %percent:3s%%");
|
||||
$progressBar->start();
|
||||
|
||||
foreach ($eligibleUsers->lazyById(100) as $user) {
|
||||
if ($shouldDelete && $user->delete()) {
|
||||
$deletedCount++;
|
||||
}
|
||||
|
||||
$progressBar->advance();
|
||||
}
|
||||
|
||||
$progressBar->finish();
|
||||
$this->newLine(2);
|
||||
}
|
||||
|
||||
if ($shouldDelete) {
|
||||
$this->info("Deleted {$deletedCount} ".Str::plural('unverified user', $deletedCount).'.');
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function eligibleUsers(): Builder
|
||||
{
|
||||
return User::query()
|
||||
->where('id', '!=', 0)
|
||||
->whereNull('email_verified_at')
|
||||
->whereDoesntHave('teams', fn (Builder $query) => $query->whereKey(0))
|
||||
->whereDoesntHave('teams.subscription')
|
||||
->whereDoesntHave('teams.servers')
|
||||
->whereDoesntHave('teams', function (Builder $query) {
|
||||
$query->whereHas('projects.applications')
|
||||
->orWhereHas('projects.postgresqls')
|
||||
->orWhereHas('projects.redis')
|
||||
->orWhereHas('projects.mongodbs')
|
||||
->orWhereHas('projects.mysqls')
|
||||
->orWhereHas('projects.mariadbs')
|
||||
->orWhereHas('projects.keydbs')
|
||||
->orWhereHas('projects.dragonflies')
|
||||
->orWhereHas('projects.clickhouses')
|
||||
->orWhereHas('projects.services');
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Cloud;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class ExportUsers extends Command
|
||||
{
|
||||
protected $signature = 'cloud:export-users';
|
||||
|
||||
protected $description = 'Export subscribed and unsubscribed verified Coolify Cloud users to separate CSV files';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
if (! isCloud()) {
|
||||
$this->error('This command can only be run on Coolify Cloud.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$backups = Storage::disk('backups');
|
||||
$backups->delete('cloud-users.csv');
|
||||
|
||||
$subscribedPath = $backups->path('cloud-users-subscribed.csv');
|
||||
$unsubscribedPath = $backups->path('cloud-users-unsubscribed.csv');
|
||||
$subscribedOutput = fopen($subscribedPath, 'wb');
|
||||
|
||||
if ($subscribedOutput === false) {
|
||||
$this->error("Unable to open {$subscribedPath} for writing.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$unsubscribedOutput = fopen($unsubscribedPath, 'wb');
|
||||
|
||||
if ($unsubscribedOutput === false) {
|
||||
fclose($subscribedOutput);
|
||||
$this->error("Unable to open {$unsubscribedPath} for writing.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$subscribedCount = 0;
|
||||
$unsubscribedCount = 0;
|
||||
|
||||
try {
|
||||
$header = [
|
||||
'email',
|
||||
'first_name',
|
||||
'last_name',
|
||||
'lifetime_value_currency',
|
||||
'lifetime_value_amount',
|
||||
'utm_campaign',
|
||||
'utm_source',
|
||||
'utm_medium',
|
||||
'utm_content',
|
||||
'utm_term',
|
||||
'phone',
|
||||
];
|
||||
|
||||
$this->writeCsvRow($subscribedOutput, $header);
|
||||
$this->writeCsvRow($unsubscribedOutput, $header);
|
||||
|
||||
foreach (User::query()
|
||||
->select(['id', 'email', 'name'])
|
||||
->where('id', '!=', 0)
|
||||
->whereNotNull('email_verified_at')
|
||||
->withExists([
|
||||
'teams as is_subscribed' => fn ($query) => $query
|
||||
->whereRelation('subscription', 'stripe_invoice_paid', true),
|
||||
])
|
||||
->lazyById(500) as $user) {
|
||||
$nameParts = preg_split('/\s+/u', trim((string) $user->name), 2) ?: [];
|
||||
[$firstName, $lastName] = array_pad($nameParts, 2, '');
|
||||
|
||||
$row = [
|
||||
$user->email,
|
||||
$firstName,
|
||||
$lastName,
|
||||
'',
|
||||
'',
|
||||
'',
|
||||
'',
|
||||
'',
|
||||
'',
|
||||
'',
|
||||
'',
|
||||
];
|
||||
|
||||
if ($user->is_subscribed) {
|
||||
$this->writeCsvRow($subscribedOutput, $row);
|
||||
$subscribedCount++;
|
||||
} else {
|
||||
$this->writeCsvRow($unsubscribedOutput, $row);
|
||||
$unsubscribedCount++;
|
||||
}
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
$this->error("Unable to export users: {$exception->getMessage()}");
|
||||
|
||||
return self::FAILURE;
|
||||
} finally {
|
||||
fclose($subscribedOutput);
|
||||
fclose($unsubscribedOutput);
|
||||
}
|
||||
|
||||
$this->info("Exported {$subscribedCount} subscribed verified users to {$subscribedPath}");
|
||||
$this->info("Exported {$unsubscribedCount} unsubscribed verified users to {$unsubscribedPath}");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param resource $output
|
||||
* @param array<int, mixed> $fields
|
||||
*/
|
||||
private function writeCsvRow($output, array $fields): void
|
||||
{
|
||||
if (fputcsv($output, $fields, ',', '"', '') === false) {
|
||||
throw new RuntimeException('Unable to write the CSV file.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace App\Console\Commands\Cloud;
|
||||
|
||||
use App\Jobs\SyncStripeSubscriptionsJob;
|
||||
use App\Actions\Stripe\SyncStripeSubscriptions as SyncStripeSubscriptionsAction;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class SyncStripeSubscriptions extends Command
|
||||
@@ -35,14 +35,18 @@ class SyncStripeSubscriptions extends Command
|
||||
|
||||
$this->newLine();
|
||||
|
||||
$job = new SyncStripeSubscriptionsJob($fix);
|
||||
$fetched = 0;
|
||||
$result = $job->handle(function (int $count) use (&$fetched): void {
|
||||
$fetched = $count;
|
||||
$this->output->write("\r Fetching subscriptions from Stripe... {$fetched}");
|
||||
$progressShown = false;
|
||||
$result = SyncStripeSubscriptionsAction::run($fix, function (string $stage, int $current, ?int $total) use (&$progressShown): void {
|
||||
$progressShown = true;
|
||||
$message = match ($stage) {
|
||||
'checking' => " Checking stale subscriptions against Stripe... {$current}/{$total}",
|
||||
default => " Fetching valid subscriptions from Stripe... {$current}",
|
||||
};
|
||||
|
||||
$this->output->write("\r".str_pad($message, 80));
|
||||
});
|
||||
if ($fetched > 0) {
|
||||
$this->output->write("\r".str_repeat(' ', 60)."\r");
|
||||
if ($progressShown) {
|
||||
$this->output->write("\r".str_repeat(' ', 80)."\r");
|
||||
}
|
||||
|
||||
if (isset($result['error'])) {
|
||||
@@ -63,13 +67,22 @@ class SyncStripeSubscriptions extends Command
|
||||
$this->line(" Team ID: {$discrepancy['team_id']}");
|
||||
$this->line(" Stripe ID: {$discrepancy['stripe_subscription_id']}");
|
||||
$this->line(" Stripe Status: {$discrepancy['stripe_status']}");
|
||||
$resolution = match ($discrepancy['resolution']) {
|
||||
'delete_stale' => 'Delete stale local row',
|
||||
'manual_review' => 'Manual review required',
|
||||
default => 'End local subscription',
|
||||
};
|
||||
$this->line(" Resolution: {$resolution}");
|
||||
$this->newLine();
|
||||
}
|
||||
|
||||
if ($fix) {
|
||||
$this->info('All discrepancies have been fixed.');
|
||||
$this->info("Automatic corrections applied: {$result['fixed_count']}");
|
||||
if ($result['manual_review_count'] > 0) {
|
||||
$this->warn("Skipped for manual review: {$result['manual_review_count']}");
|
||||
}
|
||||
} else {
|
||||
$this->comment('Run with --fix to correct these discrepancies.');
|
||||
$this->comment('Run with --fix to apply automatic corrections.');
|
||||
}
|
||||
} else {
|
||||
$this->info('No discrepancies found. All subscriptions are in sync.');
|
||||
@@ -84,6 +97,7 @@ class SyncStripeSubscriptions extends Command
|
||||
$this->line(" - Team ID: {$resub['team_id']} | Email: {$resub['email']}");
|
||||
$this->line(" Old: {$resub['old_stripe_subscription_id']} (cus: {$resub['old_stripe_customer_id']})");
|
||||
$this->line(" New: {$resub['new_stripe_subscription_id']} (cus: {$resub['new_stripe_customer_id']}) [{$resub['new_status']}]");
|
||||
$this->line(' Linked to this team: '.($resub['linked_to_team'] ? 'Yes' : 'No'));
|
||||
$this->newLine();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ use App\Models\User;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
class Init extends Command
|
||||
@@ -161,10 +160,12 @@ class Init extends Command
|
||||
|
||||
private function pullTemplatesFromCDN()
|
||||
{
|
||||
$response = Http::retry(3, 1000)->get(config('constants.services.official'));
|
||||
$response = Http::retry(3, 1000, throw: false)
|
||||
->timeout(60)
|
||||
->connectTimeout(10)
|
||||
->get(config('constants.services.official'));
|
||||
if ($response->successful()) {
|
||||
$services = $response->json();
|
||||
File::put(base_path('templates/'.config('constants.services.file_name')), json_encode($services));
|
||||
store_service_templates_bundle($response->body());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -69,8 +69,9 @@ class Handler extends ExceptionHandler
|
||||
*/
|
||||
public function render($request, Throwable $e)
|
||||
{
|
||||
// Handle authorization exceptions for API routes
|
||||
if ($e instanceof AuthorizationException) {
|
||||
// Handle authorization exceptions for API routes. Exceptions carrying
|
||||
// an explicit status (e.g. denyAsNotFound) keep it via parent::render.
|
||||
if ($e instanceof AuthorizationException && ! $e->hasStatus()) {
|
||||
if ($request->is('api/*') || $request->expectsJson()) {
|
||||
if ($request->is('api/*')) {
|
||||
auditLog('api.auth.policy_denied', [
|
||||
|
||||
@@ -127,6 +127,7 @@ class SshMultiplexingHelper
|
||||
|
||||
$scpCommand .= self::getCommonSshOptions($server, $sshKeyLocation, self::getConnectionTimeout($server), config('constants.ssh.server_interval'), isScp: true);
|
||||
|
||||
// Upload: local source -> remote dest
|
||||
if ($server->isIpv6()) {
|
||||
return $scpCommand.escapeshellarg($source).' '.escapeshellarg($server->user).'@['.escapeshellarg($server->ip).']:'.escapeshellarg($dest);
|
||||
}
|
||||
@@ -134,6 +135,46 @@ class SshMultiplexingHelper
|
||||
return $scpCommand.escapeshellarg($source).' '.self::escapedUserAtHost($server).':'.escapeshellarg($dest);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an SCP command that downloads a remote file onto the Coolify host.
|
||||
*/
|
||||
public static function generateScpDownloadCommand(Server $server, string $remoteSource, string $localDest): string
|
||||
{
|
||||
$sshConfig = self::serverSshConfiguration($server);
|
||||
$sshKeyLocation = $sshConfig['sshKeyLocation'];
|
||||
$scpCommand = 'timeout '.config('constants.ssh.command_timeout').' scp ';
|
||||
|
||||
if ($server->isIpv6()) {
|
||||
$scpCommand .= '-6 ';
|
||||
}
|
||||
|
||||
if (self::isMultiplexingEnabled()) {
|
||||
try {
|
||||
if (self::ensureMultiplexedConnection($server)) {
|
||||
$scpCommand .= self::multiplexingOptions($server);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('SSH multiplexing failed for SCP download, falling back to non-multiplexed connection', [
|
||||
'server' => $server->name ?? $server->ip,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if (data_get($server, 'settings.is_cloudflare_tunnel')) {
|
||||
$scpCommand .= '-o ProxyCommand="cloudflared access ssh --hostname %h" ';
|
||||
}
|
||||
|
||||
$scpCommand .= self::getCommonSshOptions($server, $sshKeyLocation, self::getConnectionTimeout($server), config('constants.ssh.server_interval'), isScp: true);
|
||||
|
||||
// Download: remote source -> local dest
|
||||
if ($server->isIpv6()) {
|
||||
return $scpCommand.escapeshellarg($server->user).'@['.escapeshellarg($server->ip).']:'.escapeshellarg($remoteSource).' '.escapeshellarg($localDest);
|
||||
}
|
||||
|
||||
return $scpCommand.self::escapedUserAtHost($server).':'.escapeshellarg($remoteSource).' '.escapeshellarg($localDest);
|
||||
}
|
||||
|
||||
public static function generateSshCommand(Server $server, string $command, bool $disableMultiplexing = false, ?int $commandTimeout = null): string
|
||||
{
|
||||
if ($server->settings->force_disabled) {
|
||||
@@ -169,12 +210,18 @@ class SshMultiplexingHelper
|
||||
|
||||
$delimiter = base64_encode(Hash::make($command));
|
||||
$command = str_replace($delimiter, '', $command);
|
||||
$remoteShellCommand = self::remoteShellCommand();
|
||||
|
||||
return $sshCommand.self::escapedUserAtHost($server)." 'bash -se' << \\$delimiter".PHP_EOL
|
||||
return $sshCommand.self::escapedUserAtHost($server)." '{$remoteShellCommand}' << \\$delimiter".PHP_EOL
|
||||
.$command.PHP_EOL
|
||||
.$delimiter;
|
||||
}
|
||||
|
||||
private static function remoteShellCommand(): string
|
||||
{
|
||||
return 'if command -v bash >/dev/null 2>&1; then exec bash -se; else exec sh -se; fi';
|
||||
}
|
||||
|
||||
public static function getConnectionTimeout(Server $server): int
|
||||
{
|
||||
$timeout = data_get($server, 'settings.connection_timeout');
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,281 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\CloudInitScript;
|
||||
use App\Rules\ValidCloudInitYaml;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use OpenApi\Attributes as OA;
|
||||
|
||||
class CloudInitScriptsController extends Controller
|
||||
{
|
||||
private function removeSensitiveData(CloudInitScript $script): array
|
||||
{
|
||||
$script->makeHidden(['id', 'team_id']);
|
||||
|
||||
if (request()->attributes->get('can_read_sensitive', false) === true) {
|
||||
$script->makeVisible(['script']);
|
||||
}
|
||||
|
||||
return serializeApiResponse($script)->all();
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'List Cloud-init Scripts',
|
||||
description: 'List all cloud-init scripts for the authenticated team.',
|
||||
path: '/cloud-init-scripts',
|
||||
operationId: 'list-cloud-init-scripts',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Cloud-init Scripts'],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Cloud-init scripts for the team.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 403, description: 'Forbidden.'),
|
||||
]
|
||||
)]
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$this->authorize('viewAny', CloudInitScript::class);
|
||||
|
||||
$scripts = CloudInitScript::where('team_id', $teamId)
|
||||
->orderByDesc('created_at')
|
||||
->get()
|
||||
->map(fn (CloudInitScript $script) => $this->removeSensitiveData($script));
|
||||
|
||||
return response()->json($scripts);
|
||||
}
|
||||
|
||||
#[OA\Post(
|
||||
summary: 'Create Cloud-init Script',
|
||||
description: 'Create a new cloud-init script for the authenticated team.',
|
||||
path: '/cloud-init-scripts',
|
||||
operationId: 'create-cloud-init-script',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Cloud-init Scripts'],
|
||||
requestBody: new OA\RequestBody(
|
||||
required: true,
|
||||
content: new OA\JsonContent(
|
||||
required: ['name', 'script'],
|
||||
properties: [
|
||||
new OA\Property(property: 'name', type: 'string'),
|
||||
new OA\Property(property: 'script', type: 'string', description: 'Bash script (#!) or cloud-config YAML.'),
|
||||
]
|
||||
)
|
||||
),
|
||||
responses: [
|
||||
new OA\Response(response: 201, description: 'Cloud-init script created.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 403, description: 'Forbidden.'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
]
|
||||
)]
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$this->authorize('create', CloudInitScript::class);
|
||||
|
||||
$return = validateIncomingRequest($request);
|
||||
if ($return instanceof JsonResponse) {
|
||||
return $return;
|
||||
}
|
||||
|
||||
$validator = customApiValidator($request->all(), [
|
||||
'name' => 'required|string|max:255',
|
||||
'script' => ['required', 'string', new ValidCloudInitYaml],
|
||||
]);
|
||||
$extraFields = array_diff(array_keys($request->all()), ['name', 'script']);
|
||||
if ($validator->fails() || ! empty($extraFields)) {
|
||||
$errors = $validator->errors();
|
||||
foreach ($extraFields as $field) {
|
||||
$errors->add($field, 'This field is not allowed.');
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Validation failed.',
|
||||
'errors' => $errors,
|
||||
], 422);
|
||||
}
|
||||
|
||||
$script = CloudInitScript::create([
|
||||
'team_id' => $teamId,
|
||||
'name' => $request->string('name')->toString(),
|
||||
'script' => $request->string('script')->toString(),
|
||||
]);
|
||||
|
||||
auditLog('api.cloud_init_script.created', [
|
||||
'team_id' => $teamId,
|
||||
'cloud_init_script_uuid' => $script->uuid,
|
||||
'cloud_init_script_name' => $script->name,
|
||||
]);
|
||||
|
||||
return response()->json($this->removeSensitiveData($script), 201);
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'Get Cloud-init Script',
|
||||
description: 'Get a cloud-init script by UUID.',
|
||||
path: '/cloud-init-scripts/{uuid}',
|
||||
operationId: 'get-cloud-init-script-by-uuid',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Cloud-init Scripts'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Cloud-init script.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 403, description: 'Forbidden.'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
]
|
||||
)]
|
||||
public function show(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$script = CloudInitScript::where('team_id', $teamId)->where('uuid', $request->route('uuid'))->first();
|
||||
if (! $script) {
|
||||
return response()->json(['message' => 'Cloud-init script not found.'], 404);
|
||||
}
|
||||
|
||||
$this->authorize('view', $script);
|
||||
|
||||
return response()->json($this->removeSensitiveData($script));
|
||||
}
|
||||
|
||||
#[OA\Patch(
|
||||
summary: 'Update Cloud-init Script',
|
||||
description: 'Update a cloud-init script by UUID.',
|
||||
path: '/cloud-init-scripts/{uuid}',
|
||||
operationId: 'update-cloud-init-script-by-uuid',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Cloud-init Scripts'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
requestBody: new OA\RequestBody(
|
||||
required: true,
|
||||
content: new OA\JsonContent(
|
||||
properties: [
|
||||
new OA\Property(property: 'name', type: 'string'),
|
||||
new OA\Property(property: 'script', type: 'string'),
|
||||
]
|
||||
)
|
||||
),
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Cloud-init script updated.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 403, description: 'Forbidden.'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
]
|
||||
)]
|
||||
public function update(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$return = validateIncomingRequest($request);
|
||||
if ($return instanceof JsonResponse) {
|
||||
return $return;
|
||||
}
|
||||
|
||||
if ($request->all() === []) {
|
||||
return response()->json(['message' => 'At least one field must be provided.'], 422);
|
||||
}
|
||||
|
||||
$script = CloudInitScript::where('team_id', $teamId)->where('uuid', $request->route('uuid'))->first();
|
||||
if (! $script) {
|
||||
return response()->json(['message' => 'Cloud-init script not found.'], 404);
|
||||
}
|
||||
|
||||
$this->authorize('update', $script);
|
||||
|
||||
$validator = customApiValidator($request->all(), [
|
||||
'name' => 'string|max:255',
|
||||
'script' => ['string', new ValidCloudInitYaml],
|
||||
]);
|
||||
$extraFields = array_diff(array_keys($request->all()), ['name', 'script']);
|
||||
if ($validator->fails() || ! empty($extraFields)) {
|
||||
$errors = $validator->errors();
|
||||
foreach ($extraFields as $field) {
|
||||
$errors->add($field, 'This field is not allowed.');
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Validation failed.',
|
||||
'errors' => $errors,
|
||||
], 422);
|
||||
}
|
||||
|
||||
$script->update($request->only(['name', 'script']));
|
||||
|
||||
auditLog('api.cloud_init_script.updated', [
|
||||
'team_id' => $teamId,
|
||||
'cloud_init_script_uuid' => $script->uuid,
|
||||
'cloud_init_script_name' => $script->name,
|
||||
'changed_fields' => array_values(array_intersect(['name', 'script'], array_keys($request->all()))),
|
||||
]);
|
||||
|
||||
return response()->json($this->removeSensitiveData($script->fresh()));
|
||||
}
|
||||
|
||||
#[OA\Delete(
|
||||
summary: 'Delete Cloud-init Script',
|
||||
description: 'Delete a cloud-init script by UUID.',
|
||||
path: '/cloud-init-scripts/{uuid}',
|
||||
operationId: 'delete-cloud-init-script-by-uuid',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Cloud-init Scripts'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Cloud-init script deleted.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 403, description: 'Forbidden.'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
]
|
||||
)]
|
||||
public function destroy(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$script = CloudInitScript::where('team_id', $teamId)->where('uuid', $request->route('uuid'))->first();
|
||||
if (! $script) {
|
||||
return response()->json(['message' => 'Cloud-init script not found.'], 404);
|
||||
}
|
||||
|
||||
$this->authorize('delete', $script);
|
||||
|
||||
$uuid = $script->uuid;
|
||||
$name = $script->name;
|
||||
$script->delete();
|
||||
|
||||
auditLog('api.cloud_init_script.deleted', [
|
||||
'team_id' => $teamId,
|
||||
'cloud_init_script_uuid' => $uuid,
|
||||
'cloud_init_script_name' => $name,
|
||||
]);
|
||||
|
||||
return response()->json(['message' => 'Cloud-init script deleted.']);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use App\Enums\NewDatabaseTypes;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Jobs\DatabaseBackupJob;
|
||||
use App\Jobs\DeleteResourceJob;
|
||||
use App\Jobs\VolumeCloneJob;
|
||||
use App\Models\EnvironmentVariable;
|
||||
use App\Models\LocalFileVolume;
|
||||
use App\Models\LocalPersistentVolume;
|
||||
@@ -18,11 +19,14 @@ use App\Models\Project;
|
||||
use App\Models\S3Storage;
|
||||
use App\Models\ScheduledDatabaseBackup;
|
||||
use App\Models\Server;
|
||||
use App\Models\StandaloneDocker;
|
||||
use App\Models\StandalonePostgresql;
|
||||
use App\Models\SwarmDocker;
|
||||
use App\Support\ValidationPatterns;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Bus;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use OpenApi\Attributes as OA;
|
||||
|
||||
@@ -850,6 +854,12 @@ class DatabasesController extends Controller
|
||||
|
||||
$this->authorize('manageBackups', $database);
|
||||
|
||||
if (! $database->isBackupSolutionAvailable()) {
|
||||
return response()->json([
|
||||
'message' => 'Scheduled backups are not supported for this database type.',
|
||||
], 422);
|
||||
}
|
||||
|
||||
// Validate frequency is a valid cron expression
|
||||
$isValid = validate_cron_expression($request->frequency);
|
||||
if (! $isValid) {
|
||||
@@ -915,6 +925,8 @@ class DatabasesController extends Controller
|
||||
$backupData['databases_to_backup'] = $database->mysql_database;
|
||||
} elseif ($database->type() === 'standalone-mariadb') {
|
||||
$backupData['databases_to_backup'] = $database->mariadb_database;
|
||||
} elseif ($database->type() === 'standalone-clickhouse') {
|
||||
$backupData['databases_to_backup'] = $database->clickhouse_db;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1805,6 +1817,12 @@ class DatabasesController extends Controller
|
||||
if (! $server) {
|
||||
return response()->json(['message' => 'Server not found.'], 404);
|
||||
}
|
||||
if (! $server->canHostResources()) {
|
||||
return response()->json([
|
||||
'message' => 'Validation failed.',
|
||||
'errors' => ['server_uuid' => ['The specified server is configured as a build server and cannot host resources.']],
|
||||
], 422);
|
||||
}
|
||||
$destinations = $server->destinations();
|
||||
if ($destinations->count() == 0) {
|
||||
return response()->json(['message' => 'Server has no destinations.'], 400);
|
||||
@@ -3036,9 +3054,57 @@ class DatabasesController extends Controller
|
||||
return moveResourceToEnvironment($request, $database, 'Database', $teamId);
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
#[OA\Post(
|
||||
summary: 'Migrate to Server',
|
||||
description: 'Migrate a database to another destination/server owned by the authenticated team. Stops the database, optionally transfers persistent volume data when both servers are managed by Coolify, and updates database records. Redeploy after migration completes.',
|
||||
path: '/databases/{uuid}/migrate',
|
||||
operationId: 'migrate-database-by-uuid',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Databases'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the database.', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
requestBody: new OA\RequestBody(
|
||||
required: true,
|
||||
content: new OA\JsonContent(
|
||||
required: ['destination_uuid'],
|
||||
properties: [
|
||||
new OA\Property(property: 'destination_uuid', type: 'string', description: 'UUID of the target destination.'),
|
||||
new OA\Property(property: 'migrate_volumes', type: 'boolean', default: true, description: 'Whether to transfer persistent volume data when migrating across servers.'),
|
||||
]
|
||||
)
|
||||
),
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Database migration started or completed.'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
]
|
||||
)]
|
||||
public function migrate_by_uuid(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
$uuid = $request->route('uuid');
|
||||
if (! $uuid) {
|
||||
return response()->json(['message' => 'UUID is required.'], 400);
|
||||
}
|
||||
$database = queryDatabaseByUuidWithinTeam($request->uuid, $teamId);
|
||||
if (! $database) {
|
||||
return response()->json(['message' => 'Database not found.'], 404);
|
||||
}
|
||||
|
||||
$this->authorize('update', $database);
|
||||
|
||||
return migrateResourceToDestination($request, $database, 'Database', $teamId);
|
||||
}
|
||||
|
||||
#[OA\Post(
|
||||
summary: 'Start',
|
||||
description: 'Start database. `Post` request is also accepted.',
|
||||
description: 'Start database.',
|
||||
path: '/databases/{uuid}/start',
|
||||
operationId: 'start-database-by-uuid',
|
||||
security: [
|
||||
@@ -3123,9 +3189,9 @@ class DatabasesController extends Controller
|
||||
);
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
#[OA\Post(
|
||||
summary: 'Stop',
|
||||
description: 'Stop database. `Post` request is also accepted.',
|
||||
description: 'Stop database.',
|
||||
path: '/databases/{uuid}/stop',
|
||||
operationId: 'stop-database-by-uuid',
|
||||
security: [
|
||||
@@ -3222,9 +3288,9 @@ class DatabasesController extends Controller
|
||||
);
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
#[OA\Post(
|
||||
summary: 'Restart',
|
||||
description: 'Restart database. `Post` request is also accepted.',
|
||||
description: 'Restart database.',
|
||||
path: '/databases/{uuid}/restart',
|
||||
operationId: 'restart-database-by-uuid',
|
||||
security: [
|
||||
@@ -4470,6 +4536,8 @@ class DatabasesController extends Controller
|
||||
], 422);
|
||||
}
|
||||
|
||||
$storage->abortIfScheduledBackupsExist();
|
||||
|
||||
if ($storage instanceof LocalFileVolume) {
|
||||
$storage->deleteStorageOnServer();
|
||||
}
|
||||
@@ -4632,4 +4700,220 @@ class DatabasesController extends Controller
|
||||
{
|
||||
return $this->deleteTag($request);
|
||||
}
|
||||
|
||||
#[OA\Post(
|
||||
summary: 'Clone',
|
||||
description: 'Clone a database to a destination owned by the authenticated team.',
|
||||
path: '/databases/{uuid}/clone',
|
||||
operationId: 'clone-database-by-uuid',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Databases'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the database.', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
requestBody: new OA\RequestBody(
|
||||
required: true,
|
||||
content: new OA\JsonContent(
|
||||
required: ['destination_uuid'],
|
||||
properties: [
|
||||
new OA\Property(property: 'destination_uuid', type: 'string'),
|
||||
new OA\Property(property: 'name', type: 'string', nullable: true),
|
||||
new OA\Property(property: 'clone_volumes', type: 'boolean', default: false),
|
||||
]
|
||||
)
|
||||
),
|
||||
responses: [
|
||||
new OA\Response(response: 201, description: 'Database cloned.'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
]
|
||||
)]
|
||||
public function clone_by_uuid(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$return = validateIncomingRequest($request);
|
||||
if ($return instanceof JsonResponse) {
|
||||
return $return;
|
||||
}
|
||||
|
||||
$validator = customApiValidator($request->all(), [
|
||||
'destination_uuid' => 'required|string',
|
||||
'name' => 'string|max:255|nullable',
|
||||
'clone_volumes' => 'boolean',
|
||||
]);
|
||||
$allowedFields = ['destination_uuid', 'name', 'clone_volumes'];
|
||||
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
|
||||
if ($validator->fails() || ! empty($extraFields)) {
|
||||
$errors = $validator->errors();
|
||||
foreach ($extraFields as $field) {
|
||||
$errors->add($field, 'This field is not allowed.');
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Validation failed.',
|
||||
'errors' => $errors,
|
||||
], 422);
|
||||
}
|
||||
|
||||
$database = queryDatabaseByUuidWithinTeam($request->route('uuid'), $teamId);
|
||||
if (! $database) {
|
||||
return response()->json(['message' => 'Database not found.'], 404);
|
||||
}
|
||||
|
||||
$this->authorize('update', $database);
|
||||
|
||||
$destination = StandaloneDocker::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->destination_uuid)->first()
|
||||
?? SwarmDocker::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->destination_uuid)->first();
|
||||
|
||||
if (! $destination || ! $destination->server?->canHostResources()) {
|
||||
return response()->json(['message' => 'Destination not found.'], 404);
|
||||
}
|
||||
|
||||
$uuid = new_public_id();
|
||||
$name = $request->filled('name')
|
||||
? $request->string('name')->toString()
|
||||
: $database->name.'-clone-'.$uuid;
|
||||
$cloneVolumeData = $request->boolean('clone_volumes', false);
|
||||
|
||||
$newDatabase = $database->replicate([
|
||||
'id',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
])->fill([
|
||||
'uuid' => $uuid,
|
||||
'name' => $name,
|
||||
'status' => 'exited',
|
||||
'started_at' => null,
|
||||
'destination_id' => $destination->id,
|
||||
'destination_type' => $destination->getMorphClass(),
|
||||
]);
|
||||
$newDatabase->save();
|
||||
|
||||
foreach ($database->tags as $tag) {
|
||||
$newDatabase->tags()->attach($tag->id);
|
||||
}
|
||||
|
||||
$newDatabase->persistentStorages()->delete();
|
||||
$pendingVolumeClones = [];
|
||||
$sourceServer = $database->destination?->server;
|
||||
$targetServer = $newDatabase->destination?->server;
|
||||
|
||||
foreach ($database->persistentStorages()->get() as $volume) {
|
||||
$originalName = $volume->name;
|
||||
$newName = match (true) {
|
||||
str_starts_with($originalName, 'postgres-data-') => 'postgres-data-'.$newDatabase->uuid,
|
||||
str_starts_with($originalName, 'mysql-data-') => 'mysql-data-'.$newDatabase->uuid,
|
||||
str_starts_with($originalName, 'redis-data-') => 'redis-data-'.$newDatabase->uuid,
|
||||
str_starts_with($originalName, 'clickhouse-data-') => 'clickhouse-data-'.$newDatabase->uuid,
|
||||
str_starts_with($originalName, 'mariadb-data-') => 'mariadb-data-'.$newDatabase->uuid,
|
||||
str_starts_with($originalName, 'mongodb-data-') => 'mongodb-data-'.$newDatabase->uuid,
|
||||
str_starts_with($originalName, 'keydb-data-') => 'keydb-data-'.$newDatabase->uuid,
|
||||
str_starts_with($originalName, 'dragonfly-data-') => 'dragonfly-data-'.$newDatabase->uuid,
|
||||
str_starts_with($volume->name, $database->uuid) => str($volume->name)->replace($database->uuid, $newDatabase->uuid)->toString(),
|
||||
default => $newDatabase->uuid.'-'.$volume->name,
|
||||
};
|
||||
|
||||
$newPersistentVolume = $volume->replicate([
|
||||
'id',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'uuid',
|
||||
])->fill([
|
||||
'name' => $newName,
|
||||
'resource_id' => $newDatabase->id,
|
||||
]);
|
||||
$newPersistentVolume->save();
|
||||
|
||||
if ($cloneVolumeData) {
|
||||
$pendingVolumeClones[] = [
|
||||
'source' => $volume->name,
|
||||
'target' => $newPersistentVolume->name,
|
||||
'model' => $newPersistentVolume,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// Stop once, clone all volumes, then start once — avoids per-volume stop/start races.
|
||||
if ($pendingVolumeClones !== [] && $sourceServer && $targetServer) {
|
||||
try {
|
||||
$chain = [
|
||||
function () use ($database) {
|
||||
StopDatabase::run($database);
|
||||
},
|
||||
];
|
||||
|
||||
foreach ($pendingVolumeClones as $clone) {
|
||||
$chain[] = new VolumeCloneJob(
|
||||
$clone['source'],
|
||||
$clone['target'],
|
||||
$sourceServer,
|
||||
$targetServer,
|
||||
$clone['model'],
|
||||
);
|
||||
}
|
||||
|
||||
$chain[] = function () use ($database) {
|
||||
StartDatabase::run($database);
|
||||
};
|
||||
|
||||
Bus::chain($chain)->onQueue('high')->dispatch();
|
||||
} catch (\Exception $e) {
|
||||
\Log::error('Failed to queue database volume clone for '.$database->uuid.': '.$e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($database->fileStorages()->get() as $storage) {
|
||||
$storage->replicate([
|
||||
'id',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
])->fill([
|
||||
'resource_id' => $newDatabase->id,
|
||||
])->save();
|
||||
}
|
||||
|
||||
foreach ($database->scheduledBackups()->get() as $backup) {
|
||||
$backup->replicate([
|
||||
'id',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
])->fill([
|
||||
'uuid' => new_public_id(),
|
||||
'database_id' => $newDatabase->id,
|
||||
'database_type' => $newDatabase->getMorphClass(),
|
||||
'team_id' => $teamId,
|
||||
])->save();
|
||||
}
|
||||
|
||||
foreach ($database->environment_variables()->get() as $environmentVariable) {
|
||||
$environmentVariable->replicate([
|
||||
'id',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
])->fill([
|
||||
'resourceable_id' => $newDatabase->id,
|
||||
'resourceable_type' => $newDatabase->getMorphClass(),
|
||||
])->save();
|
||||
}
|
||||
|
||||
auditLog('api.database.cloned', [
|
||||
'team_id' => $teamId,
|
||||
'source_uuid' => $database->uuid,
|
||||
'database_uuid' => $newDatabase->uuid,
|
||||
'database_name' => $newDatabase->name,
|
||||
'destination_uuid' => $destination->uuid,
|
||||
'clone_volumes' => $cloneVolumeData,
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'uuid' => $newDatabase->uuid,
|
||||
'message' => 'Database cloned.',
|
||||
], 201);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,57 +238,71 @@ class DeployController extends Controller
|
||||
ApplicationDeploymentStatus::IN_PROGRESS->value,
|
||||
];
|
||||
|
||||
if (! in_array($deployment->status, $cancellableStatuses)) {
|
||||
if (! in_array($deployment->status, $cancellableStatuses, true)) {
|
||||
return response()->json([
|
||||
'message' => "Deployment cannot be cancelled. Current status: {$deployment->status}",
|
||||
], 400);
|
||||
}
|
||||
|
||||
// Perform the cancellation
|
||||
$cancelled = false;
|
||||
$deploymentServer = Server::whereTeamId($teamId)->find($deployment->server_id);
|
||||
|
||||
try {
|
||||
$deployment_uuid = $deployment->deployment_uuid;
|
||||
$kill_command = "docker rm -f {$deployment_uuid}";
|
||||
$build_server_id = $deployment->build_server_id ?? $deployment->server_id;
|
||||
|
||||
// Mark deployment as cancelled
|
||||
$deployment->update([
|
||||
'status' => ApplicationDeploymentStatus::CANCELLED_BY_USER->value,
|
||||
]);
|
||||
$updated = ApplicationDeploymentQueue::whereKey($deployment->getKey())
|
||||
->whereIn('status', $cancellableStatuses)
|
||||
->update(['status' => ApplicationDeploymentStatus::CANCELLED_BY_USER->value]);
|
||||
|
||||
if ($updated !== 1) {
|
||||
$deployment->refresh();
|
||||
|
||||
return response()->json([
|
||||
'message' => "Deployment cannot be cancelled. Current status: {$deployment->status}",
|
||||
], 400);
|
||||
}
|
||||
|
||||
$deployment->status = ApplicationDeploymentStatus::CANCELLED_BY_USER->value;
|
||||
$cancelled = true;
|
||||
|
||||
// Get the server
|
||||
$server = Server::whereTeamId($teamId)->find($build_server_id);
|
||||
|
||||
if ($server) {
|
||||
// Add cancellation log entry
|
||||
$deployment->addLogEntry('Deployment cancelled by user via API.', 'stderr');
|
||||
try {
|
||||
if ($server) {
|
||||
// Add cancellation log entry
|
||||
$deployment->addLogEntry('Deployment cancelled by user via API.', 'stderr');
|
||||
|
||||
// Check if container exists and kill it
|
||||
$checkCommand = "docker ps -a --filter name={$deployment_uuid} --format '{{.Names}}'";
|
||||
$containerExists = instant_remote_process([$checkCommand], $server);
|
||||
// Check if container exists and kill it
|
||||
$checkCommand = "docker ps -a --filter name={$deployment_uuid} --format '{{.Names}}'";
|
||||
$containerExists = instant_remote_process([$checkCommand], $server);
|
||||
|
||||
if ($containerExists && str($containerExists)->trim()->isNotEmpty()) {
|
||||
instant_remote_process([$kill_command], $server);
|
||||
$deployment->addLogEntry('Deployment container stopped.');
|
||||
} else {
|
||||
$deployment->addLogEntry('Deployment container not yet started. Will be cancelled when job checks status.');
|
||||
}
|
||||
if ($containerExists && str($containerExists)->trim()->isNotEmpty()) {
|
||||
instant_remote_process([$kill_command], $server);
|
||||
$deployment->addLogEntry('Deployment container stopped.');
|
||||
} else {
|
||||
$deployment->addLogEntry('Deployment container not yet started. Will be cancelled when job checks status.');
|
||||
}
|
||||
|
||||
// Kill running process if process ID exists
|
||||
if ($deployment->current_process_id) {
|
||||
try {
|
||||
// Kill running process if process ID exists
|
||||
if ($deployment->current_process_id) {
|
||||
$processKillCommand = "kill -9 {$deployment->current_process_id}";
|
||||
instant_remote_process([$processKillCommand], $server);
|
||||
} catch (\Throwable $e) {
|
||||
// Process might already be gone
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
\Log::warning("Failed to clean up cancelled deployment {$deployment->id}: {$e->getMessage()}");
|
||||
}
|
||||
|
||||
auditLog('api.deployment.cancelled', [
|
||||
'team_id' => $teamId,
|
||||
'deployment_uuid' => $deployment->deployment_uuid,
|
||||
'application_id' => $application?->id,
|
||||
'application_uuid' => $application?->uuid,
|
||||
'application_id' => $deployment->application_id,
|
||||
'application_uuid' => $deployment->application?->uuid,
|
||||
'server_id' => $deployment->server_id,
|
||||
]);
|
||||
|
||||
@@ -301,12 +315,20 @@ class DeployController extends Controller
|
||||
return response()->json([
|
||||
'message' => 'Failed to cancel deployment: '.$e->getMessage(),
|
||||
], 500);
|
||||
} finally {
|
||||
if ($cancelled) {
|
||||
try {
|
||||
next_after_cancel($deploymentServer);
|
||||
} catch (\Throwable $e) {
|
||||
\Log::warning("Failed to advance deployment queue after cancelling deployment {$deployment->id}: {$e->getMessage()}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
#[OA\Post(
|
||||
summary: 'Deploy',
|
||||
description: 'Deploy by tag or uuid. `Post` request also accepted with `uuid` and `tag` json body.',
|
||||
description: 'Deploy by tag or UUID using query parameters or a JSON body.',
|
||||
path: '/deploy',
|
||||
operationId: 'deploy-by-tag-or-uuid',
|
||||
security: [
|
||||
|
||||
@@ -274,6 +274,84 @@ class DestinationsController extends Controller
|
||||
|| in_array($driverCode, ['19', '1062', '2067'], true);
|
||||
}
|
||||
|
||||
#[OA\Patch(
|
||||
summary: 'Update destination',
|
||||
description: 'Update a Docker network destination name. Network cannot be changed via the API.',
|
||||
path: '/destinations/{uuid}',
|
||||
operationId: 'update-destination-by-uuid',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Destinations'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Destination UUID', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
requestBody: new OA\RequestBody(
|
||||
required: true,
|
||||
content: new OA\JsonContent(
|
||||
properties: [
|
||||
new OA\Property(property: 'name', type: 'string', maxLength: 255),
|
||||
],
|
||||
type: 'object',
|
||||
),
|
||||
),
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 200,
|
||||
description: 'Destination updated.',
|
||||
content: new OA\JsonContent(ref: '#/components/schemas/Destination'),
|
||||
),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
],
|
||||
)]
|
||||
public function update(Request $request, string $uuid): JsonResponse
|
||||
{
|
||||
$teamId = $this->teamIdOrAbort();
|
||||
if (! is_int($teamId)) {
|
||||
return $teamId;
|
||||
}
|
||||
|
||||
$return = validateIncomingRequest($request);
|
||||
if ($return instanceof JsonResponse) {
|
||||
return $return;
|
||||
}
|
||||
|
||||
$allowed = ['name'];
|
||||
|
||||
$validator = customApiValidator($request->all(), [
|
||||
'name' => 'required|string|max:255',
|
||||
]);
|
||||
$extra = array_diff(array_keys($request->all()), $allowed);
|
||||
if ($validator->fails() || ! empty($extra)) {
|
||||
$errors = $validator->errors();
|
||||
if (! empty($extra)) {
|
||||
foreach ($extra as $field) {
|
||||
$errors->add($field, 'This field is not allowed.');
|
||||
}
|
||||
}
|
||||
|
||||
return response()->json(['message' => 'Validation failed.', 'errors' => $errors], 422);
|
||||
}
|
||||
|
||||
$destination = $this->findDestinationForTeam($teamId, $uuid);
|
||||
|
||||
$this->authorize('update', $destination);
|
||||
|
||||
$destination->update(['name' => $request->input('name')]);
|
||||
$destination->load('server:id,uuid');
|
||||
|
||||
auditLog('api.destination.updated', [
|
||||
'team_id' => $teamId,
|
||||
'destination_uuid' => $destination->uuid,
|
||||
'destination_name' => $destination->name,
|
||||
'destination_type' => $destination instanceof SwarmDocker ? 'swarm' : 'standalone',
|
||||
'server_uuid' => $destination->server?->uuid,
|
||||
'changed_fields' => ['name'],
|
||||
]);
|
||||
|
||||
return response()->json($this->transform($destination));
|
||||
}
|
||||
|
||||
#[OA\Delete(
|
||||
summary: 'Delete destination',
|
||||
description: 'Delete an unused Docker network destination.',
|
||||
|
||||
@@ -0,0 +1,540 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\GitlabApp;
|
||||
use App\Rules\SafeExternalUrl;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
use OpenApi\Attributes as OA;
|
||||
|
||||
class GitlabController extends Controller
|
||||
{
|
||||
private function removeSensitiveData(GitlabApp $gitlabApp)
|
||||
{
|
||||
if (request()->attributes->get('can_read_sensitive', false) === true) {
|
||||
$gitlabApp->makeVisible([
|
||||
'client_secret',
|
||||
'webhook_token',
|
||||
'access_token',
|
||||
'refresh_token',
|
||||
]);
|
||||
} else {
|
||||
$gitlabApp->makeHidden([
|
||||
'client_secret',
|
||||
'webhook_token',
|
||||
'access_token',
|
||||
'refresh_token',
|
||||
]);
|
||||
}
|
||||
|
||||
return serializeApiResponse($gitlabApp);
|
||||
}
|
||||
|
||||
private function findTeamGitlabApp(int|string $gitlabAppId, int $teamId): GitlabApp
|
||||
{
|
||||
return GitlabApp::where('id', $gitlabAppId)
|
||||
->where('team_id', $teamId)
|
||||
->firstOrFail();
|
||||
}
|
||||
|
||||
private function gitlabApiUrlFromHtmlUrl(string $htmlUrl): string
|
||||
{
|
||||
return rtrim($htmlUrl, '/').'/api/v4';
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'List',
|
||||
description: 'List all GitLab apps for the current team (and system-wide sources).',
|
||||
path: '/gitlab-apps',
|
||||
operationId: 'list-gitlab-apps',
|
||||
security: [
|
||||
['bearerAuth' => []],
|
||||
],
|
||||
tags: ['GitLab Apps'],
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 200,
|
||||
description: 'List of GitLab apps.',
|
||||
content: [
|
||||
new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'array',
|
||||
items: new OA\Items(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'id' => ['type' => 'integer'],
|
||||
'uuid' => ['type' => 'string'],
|
||||
'name' => ['type' => 'string'],
|
||||
'api_url' => ['type' => 'string'],
|
||||
'html_url' => ['type' => 'string'],
|
||||
'custom_user' => ['type' => 'string'],
|
||||
'custom_port' => ['type' => 'integer'],
|
||||
'client_id' => ['type' => 'string', 'nullable' => true],
|
||||
'group_name' => ['type' => 'string', 'nullable' => true],
|
||||
'redirect_uri' => ['type' => 'string', 'nullable' => true],
|
||||
'is_system_wide' => ['type' => 'boolean'],
|
||||
'is_public' => ['type' => 'boolean'],
|
||||
'team_id' => ['type' => 'integer'],
|
||||
]
|
||||
)
|
||||
)
|
||||
),
|
||||
]
|
||||
),
|
||||
new OA\Response(
|
||||
response: 401,
|
||||
ref: '#/components/responses/401',
|
||||
),
|
||||
new OA\Response(
|
||||
response: 400,
|
||||
ref: '#/components/responses/400',
|
||||
),
|
||||
]
|
||||
)]
|
||||
public function list_gitlab_apps(Request $request)
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$gitlabApps = GitlabApp::where(function ($query) use ($teamId) {
|
||||
$query->where('team_id', $teamId)
|
||||
->orWhere('is_system_wide', true);
|
||||
})->get();
|
||||
|
||||
$gitlabApps = $gitlabApps->map(function ($app) {
|
||||
return $this->removeSensitiveData($app);
|
||||
});
|
||||
|
||||
return response()->json($gitlabApps);
|
||||
}
|
||||
|
||||
#[OA\Post(
|
||||
summary: 'Create GitLab App',
|
||||
description: 'Create a new GitLab app (OAuth source). Credentials may be supplied later via the UI or update endpoint.',
|
||||
path: '/gitlab-apps',
|
||||
operationId: 'create-gitlab-app',
|
||||
security: [
|
||||
['bearerAuth' => []],
|
||||
],
|
||||
tags: ['GitLab Apps'],
|
||||
requestBody: new OA\RequestBody(
|
||||
description: 'GitLab app creation payload.',
|
||||
required: true,
|
||||
content: [
|
||||
new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'name' => ['type' => 'string', 'description' => 'Name of the GitLab app.'],
|
||||
'html_url' => ['type' => 'string', 'description' => 'GitLab instance URL (e.g., https://gitlab.com).'],
|
||||
'api_url' => ['type' => 'string', 'description' => 'GitLab API URL (defaults to {html_url}/api/v4).'],
|
||||
'custom_user' => ['type' => 'string', 'description' => 'Custom user for SSH access (default: git).'],
|
||||
'custom_port' => ['type' => 'integer', 'description' => 'Custom port for SSH access (default: 22).'],
|
||||
'group_name' => ['type' => 'string', 'nullable' => true, 'description' => 'Optional comma-separated group names to filter repositories.'],
|
||||
'client_id' => ['type' => 'string', 'nullable' => true, 'description' => 'GitLab OAuth Application ID.'],
|
||||
'client_secret' => ['type' => 'string', 'nullable' => true, 'description' => 'GitLab OAuth Application Secret.'],
|
||||
'webhook_token' => ['type' => 'string', 'nullable' => true, 'description' => 'Webhook secret token (auto-generated when omitted).'],
|
||||
'redirect_uri' => ['type' => 'string', 'nullable' => true, 'description' => 'OAuth redirect URI registered in GitLab.'],
|
||||
'is_system_wide' => ['type' => 'boolean', 'description' => 'Is this app system-wide (non-cloud instances only).'],
|
||||
],
|
||||
required: ['name', 'html_url'],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 201,
|
||||
description: 'GitLab app created successfully.',
|
||||
content: [
|
||||
new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'id' => ['type' => 'integer'],
|
||||
'uuid' => ['type' => 'string'],
|
||||
'name' => ['type' => 'string'],
|
||||
'api_url' => ['type' => 'string'],
|
||||
'html_url' => ['type' => 'string'],
|
||||
'custom_user' => ['type' => 'string'],
|
||||
'custom_port' => ['type' => 'integer'],
|
||||
'client_id' => ['type' => 'string', 'nullable' => true],
|
||||
'group_name' => ['type' => 'string', 'nullable' => true],
|
||||
'redirect_uri' => ['type' => 'string', 'nullable' => true],
|
||||
'is_system_wide' => ['type' => 'boolean'],
|
||||
'team_id' => ['type' => 'integer'],
|
||||
]
|
||||
)
|
||||
),
|
||||
]
|
||||
),
|
||||
new OA\Response(
|
||||
response: 400,
|
||||
ref: '#/components/responses/400',
|
||||
),
|
||||
new OA\Response(
|
||||
response: 401,
|
||||
ref: '#/components/responses/401',
|
||||
),
|
||||
new OA\Response(
|
||||
response: 422,
|
||||
ref: '#/components/responses/422',
|
||||
),
|
||||
]
|
||||
)]
|
||||
public function create_gitlab_app(Request $request)
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
$this->authorize('create', [GitlabApp::class]);
|
||||
$return = validateIncomingRequest($request);
|
||||
if ($return instanceof JsonResponse) {
|
||||
return $return;
|
||||
}
|
||||
|
||||
$allowedFields = [
|
||||
'name',
|
||||
'html_url',
|
||||
'api_url',
|
||||
'custom_user',
|
||||
'custom_port',
|
||||
'group_name',
|
||||
'client_id',
|
||||
'client_secret',
|
||||
'webhook_token',
|
||||
'redirect_uri',
|
||||
'is_system_wide',
|
||||
];
|
||||
|
||||
$validator = customApiValidator($request->all(), [
|
||||
'name' => 'required|string|max:255',
|
||||
'html_url' => ['required', 'string', 'url', new SafeExternalUrl],
|
||||
'api_url' => ['nullable', 'string', 'url', new SafeExternalUrl],
|
||||
'custom_user' => 'nullable|string|max:255',
|
||||
'custom_port' => 'nullable|integer|min:1|max:65535',
|
||||
'group_name' => 'nullable|string|max:255',
|
||||
'client_id' => 'nullable|string|max:255',
|
||||
'client_secret' => 'nullable|string',
|
||||
'webhook_token' => 'nullable|string',
|
||||
// Callback to this Coolify instance — may be a private/LAN URL; do not use SafeExternalUrl.
|
||||
'redirect_uri' => ['nullable', 'string', 'url'],
|
||||
'is_system_wide' => 'boolean',
|
||||
]);
|
||||
|
||||
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
|
||||
if ($validator->fails() || ! empty($extraFields)) {
|
||||
$errors = $validator->errors();
|
||||
if (! empty($extraFields)) {
|
||||
foreach ($extraFields as $field) {
|
||||
$errors->add($field, 'This field is not allowed.');
|
||||
}
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Validation failed.',
|
||||
'errors' => $errors,
|
||||
], 422);
|
||||
}
|
||||
|
||||
try {
|
||||
$htmlUrl = rtrim((string) $request->input('html_url'), '/');
|
||||
$apiUrl = filled($request->input('api_url'))
|
||||
? rtrim((string) $request->input('api_url'), '/')
|
||||
: $this->gitlabApiUrlFromHtmlUrl($htmlUrl);
|
||||
|
||||
$payload = [
|
||||
'name' => $request->input('name'),
|
||||
'html_url' => $htmlUrl,
|
||||
'api_url' => $apiUrl,
|
||||
'custom_user' => $request->input('custom_user', 'git'),
|
||||
'custom_port' => $request->input('custom_port', 22),
|
||||
'group_name' => $request->input('group_name'),
|
||||
'client_id' => $request->input('client_id'),
|
||||
'client_secret' => $request->input('client_secret'),
|
||||
'webhook_token' => $request->input('webhook_token') ?: Str::random(32),
|
||||
'redirect_uri' => $request->input('redirect_uri'),
|
||||
'is_public' => false,
|
||||
'team_id' => $teamId,
|
||||
];
|
||||
|
||||
if (! isCloud()) {
|
||||
$payload['is_system_wide'] = $request->boolean('is_system_wide', false);
|
||||
}
|
||||
|
||||
$gitlabApp = GitlabApp::create($payload);
|
||||
|
||||
auditLog('api.gitlab_app.created', [
|
||||
'team_id' => $teamId,
|
||||
'gitlab_app_uuid' => $gitlabApp->uuid,
|
||||
'gitlab_app_name' => $gitlabApp->name,
|
||||
]);
|
||||
|
||||
return response()->json($this->removeSensitiveData($gitlabApp->fresh()), 201);
|
||||
} catch (\Throwable $e) {
|
||||
return handleError($e);
|
||||
}
|
||||
}
|
||||
|
||||
#[OA\Patch(
|
||||
path: '/gitlab-apps/{gitlab_app_id}',
|
||||
operationId: 'updateGitlabApp',
|
||||
security: [
|
||||
['bearerAuth' => []],
|
||||
],
|
||||
tags: ['GitLab Apps'],
|
||||
summary: 'Update GitLab App',
|
||||
description: 'Update an existing GitLab app.',
|
||||
parameters: [
|
||||
new OA\Parameter(
|
||||
name: 'gitlab_app_id',
|
||||
in: 'path',
|
||||
required: true,
|
||||
schema: new OA\Schema(type: 'integer'),
|
||||
description: 'GitLab App ID'
|
||||
),
|
||||
],
|
||||
requestBody: new OA\RequestBody(
|
||||
required: true,
|
||||
content: new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'name' => ['type' => 'string', 'description' => 'GitLab App name'],
|
||||
'html_url' => ['type' => 'string', 'description' => 'GitLab HTML URL'],
|
||||
'api_url' => ['type' => 'string', 'description' => 'GitLab API URL'],
|
||||
'custom_user' => ['type' => 'string', 'description' => 'Custom user for SSH'],
|
||||
'custom_port' => ['type' => 'integer', 'description' => 'Custom port for SSH'],
|
||||
'group_name' => ['type' => 'string', 'nullable' => true, 'description' => 'Optional group filter'],
|
||||
'client_id' => ['type' => 'string', 'nullable' => true, 'description' => 'OAuth Application ID'],
|
||||
'client_secret' => ['type' => 'string', 'nullable' => true, 'description' => 'OAuth Application Secret'],
|
||||
'webhook_token' => ['type' => 'string', 'nullable' => true, 'description' => 'Webhook secret token'],
|
||||
'redirect_uri' => ['type' => 'string', 'nullable' => true, 'description' => 'OAuth redirect URI'],
|
||||
'is_system_wide' => ['type' => 'boolean', 'description' => 'Is system wide (non-cloud instances only)'],
|
||||
]
|
||||
)
|
||||
)
|
||||
),
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 200,
|
||||
description: 'GitLab app updated successfully',
|
||||
content: new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'message' => ['type' => 'string', 'example' => 'GitLab app updated successfully'],
|
||||
'data' => ['type' => 'object', 'description' => 'Updated GitLab app data'],
|
||||
]
|
||||
)
|
||||
)
|
||||
),
|
||||
new OA\Response(response: 401, description: 'Unauthorized'),
|
||||
new OA\Response(response: 404, description: 'GitLab app not found'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
]
|
||||
)]
|
||||
public function update_gitlab_app(Request $request, $gitlab_app_id)
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
try {
|
||||
$gitlabApp = $this->findTeamGitlabApp($gitlab_app_id, $teamId);
|
||||
$this->authorize('update', $gitlabApp);
|
||||
|
||||
$allowedFields = [
|
||||
'name',
|
||||
'html_url',
|
||||
'api_url',
|
||||
'custom_user',
|
||||
'custom_port',
|
||||
'group_name',
|
||||
'client_id',
|
||||
'client_secret',
|
||||
'webhook_token',
|
||||
'redirect_uri',
|
||||
];
|
||||
|
||||
if (! isCloud()) {
|
||||
$allowedFields[] = 'is_system_wide';
|
||||
}
|
||||
|
||||
$payload = $request->only($allowedFields);
|
||||
|
||||
$rules = [];
|
||||
if (isset($payload['name'])) {
|
||||
$rules['name'] = 'string|max:255';
|
||||
}
|
||||
if (isset($payload['html_url'])) {
|
||||
$rules['html_url'] = ['url', new SafeExternalUrl];
|
||||
}
|
||||
if (isset($payload['api_url'])) {
|
||||
$rules['api_url'] = ['url', new SafeExternalUrl];
|
||||
}
|
||||
if (isset($payload['custom_user'])) {
|
||||
$rules['custom_user'] = 'string|max:255';
|
||||
}
|
||||
if (isset($payload['custom_port'])) {
|
||||
$rules['custom_port'] = 'integer|min:1|max:65535';
|
||||
}
|
||||
if (array_key_exists('group_name', $payload)) {
|
||||
$rules['group_name'] = 'nullable|string|max:255';
|
||||
}
|
||||
if (array_key_exists('client_id', $payload)) {
|
||||
$rules['client_id'] = 'nullable|string|max:255';
|
||||
}
|
||||
if (array_key_exists('client_secret', $payload)) {
|
||||
$rules['client_secret'] = 'nullable|string';
|
||||
}
|
||||
if (array_key_exists('webhook_token', $payload)) {
|
||||
$rules['webhook_token'] = 'nullable|string';
|
||||
}
|
||||
if (array_key_exists('redirect_uri', $payload)) {
|
||||
// Callback to this Coolify instance — may be a private/LAN URL.
|
||||
$rules['redirect_uri'] = 'nullable|url';
|
||||
}
|
||||
if (! isCloud() && isset($payload['is_system_wide'])) {
|
||||
$rules['is_system_wide'] = 'boolean';
|
||||
}
|
||||
|
||||
$validator = customApiValidator($payload, $rules);
|
||||
if ($validator->fails()) {
|
||||
return response()->json([
|
||||
'message' => 'Validation error',
|
||||
'errors' => $validator->errors(),
|
||||
], 422);
|
||||
}
|
||||
|
||||
if (isset($payload['html_url'])) {
|
||||
$payload['html_url'] = rtrim((string) $payload['html_url'], '/');
|
||||
if (! filled($payload['api_url'] ?? null)) {
|
||||
$payload['api_url'] = $this->gitlabApiUrlFromHtmlUrl($payload['html_url']);
|
||||
}
|
||||
}
|
||||
if (isset($payload['api_url'])) {
|
||||
$payload['api_url'] = rtrim((string) $payload['api_url'], '/');
|
||||
}
|
||||
|
||||
$gitlabApp->update($payload);
|
||||
|
||||
auditLog('api.gitlab_app.updated', [
|
||||
'team_id' => $teamId,
|
||||
'gitlab_app_uuid' => $gitlabApp->uuid,
|
||||
'gitlab_app_name' => $gitlabApp->name,
|
||||
'changed_fields' => array_values(array_diff(array_keys($payload), ['client_secret', 'webhook_token'])),
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'message' => 'GitLab app updated successfully',
|
||||
'data' => $this->removeSensitiveData($gitlabApp->fresh()),
|
||||
]);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
return response()->json([
|
||||
'message' => 'GitLab app not found',
|
||||
], 404);
|
||||
}
|
||||
}
|
||||
|
||||
#[OA\Delete(
|
||||
path: '/gitlab-apps/{gitlab_app_id}',
|
||||
operationId: 'deleteGitlabApp',
|
||||
security: [
|
||||
['bearerAuth' => []],
|
||||
],
|
||||
tags: ['GitLab Apps'],
|
||||
summary: 'Delete GitLab App',
|
||||
description: 'Delete a GitLab app if it is not being used by any applications.',
|
||||
parameters: [
|
||||
new OA\Parameter(
|
||||
name: 'gitlab_app_id',
|
||||
in: 'path',
|
||||
required: true,
|
||||
schema: new OA\Schema(type: 'integer'),
|
||||
description: 'GitLab App ID'
|
||||
),
|
||||
],
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 200,
|
||||
description: 'GitLab app deleted successfully',
|
||||
content: new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'message' => ['type' => 'string', 'example' => 'GitLab app deleted successfully'],
|
||||
]
|
||||
)
|
||||
)
|
||||
),
|
||||
new OA\Response(response: 401, description: 'Unauthorized'),
|
||||
new OA\Response(response: 404, description: 'GitLab app not found'),
|
||||
new OA\Response(
|
||||
response: 409,
|
||||
description: 'Conflict - GitLab app is in use',
|
||||
content: new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'message' => ['type' => 'string', 'example' => 'This GitLab app is being used by 5 application(s). Please delete all applications first.'],
|
||||
]
|
||||
)
|
||||
)
|
||||
),
|
||||
]
|
||||
)]
|
||||
public function delete_gitlab_app($gitlab_app_id)
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
try {
|
||||
$gitlabApp = $this->findTeamGitlabApp($gitlab_app_id, $teamId);
|
||||
$this->authorize('delete', $gitlabApp);
|
||||
|
||||
if ($gitlabApp->applications->isNotEmpty()) {
|
||||
$count = $gitlabApp->applications->count();
|
||||
|
||||
return response()->json([
|
||||
'message' => "This GitLab app is being used by {$count} application(s). Please delete all applications first.",
|
||||
], 409);
|
||||
}
|
||||
|
||||
$deletedUuid = $gitlabApp->uuid;
|
||||
$deletedName = $gitlabApp->name;
|
||||
$gitlabApp->delete();
|
||||
|
||||
auditLog('api.gitlab_app.deleted', [
|
||||
'team_id' => $teamId,
|
||||
'gitlab_app_uuid' => $deletedUuid,
|
||||
'gitlab_app_name' => $deletedName,
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'message' => 'GitLab app deleted successfully',
|
||||
]);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
return response()->json([
|
||||
'message' => 'GitLab app not found',
|
||||
], 404);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,511 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\DiscordNotificationSettings;
|
||||
use App\Models\EmailNotificationSettings;
|
||||
use App\Models\PushoverNotificationSettings;
|
||||
use App\Models\SlackNotificationSettings;
|
||||
use App\Models\Team;
|
||||
use App\Models\TelegramNotificationSettings;
|
||||
use App\Models\WebhookNotificationSettings;
|
||||
use App\Rules\SafeWebhookUrl;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use OpenApi\Attributes as OA;
|
||||
|
||||
class NotificationsController extends Controller
|
||||
{
|
||||
/**
|
||||
* @return array{model: class-string<Model>, rules: array<string, mixed>}
|
||||
*/
|
||||
private function channelConfig(string $channel): array
|
||||
{
|
||||
return match ($channel) {
|
||||
'email' => [
|
||||
'model' => EmailNotificationSettings::class,
|
||||
'rules' => [
|
||||
'smtp_enabled' => 'sometimes|boolean',
|
||||
'smtp_from_address' => 'sometimes|nullable|email',
|
||||
'smtp_from_name' => 'sometimes|nullable|string|max:255',
|
||||
'smtp_recipients' => 'sometimes|nullable|string|max:1000',
|
||||
'smtp_host' => 'sometimes|nullable|string|max:255',
|
||||
'smtp_port' => 'sometimes|nullable|integer|min:1|max:65535',
|
||||
'smtp_encryption' => 'sometimes|nullable|string|in:starttls,tls,none',
|
||||
'smtp_username' => 'sometimes|nullable|string|max:255',
|
||||
'smtp_password' => 'sometimes|nullable|string|max:255',
|
||||
'smtp_timeout' => 'sometimes|nullable|integer|min:0',
|
||||
'resend_enabled' => 'sometimes|boolean',
|
||||
'resend_api_key' => 'sometimes|nullable|string|max:255',
|
||||
'use_instance_email_settings' => 'sometimes|boolean',
|
||||
'deployment_success_email_notifications' => 'sometimes|boolean',
|
||||
'deployment_failure_email_notifications' => 'sometimes|boolean',
|
||||
'status_change_email_notifications' => 'sometimes|boolean',
|
||||
'backup_success_email_notifications' => 'sometimes|boolean',
|
||||
'backup_failure_email_notifications' => 'sometimes|boolean',
|
||||
'scheduled_task_success_email_notifications' => 'sometimes|boolean',
|
||||
'scheduled_task_failure_email_notifications' => 'sometimes|boolean',
|
||||
'docker_cleanup_success_email_notifications' => 'sometimes|boolean',
|
||||
'docker_cleanup_failure_email_notifications' => 'sometimes|boolean',
|
||||
'server_disk_usage_email_notifications' => 'sometimes|boolean',
|
||||
'server_reachable_email_notifications' => 'sometimes|boolean',
|
||||
'server_unreachable_email_notifications' => 'sometimes|boolean',
|
||||
'server_patch_email_notifications' => 'sometimes|boolean',
|
||||
'traefik_outdated_email_notifications' => 'sometimes|boolean',
|
||||
],
|
||||
],
|
||||
'discord' => [
|
||||
'model' => DiscordNotificationSettings::class,
|
||||
'rules' => [
|
||||
'discord_enabled' => 'sometimes|boolean',
|
||||
'discord_webhook_url' => ['sometimes', 'nullable', 'string', new SafeWebhookUrl],
|
||||
'deployment_success_discord_notifications' => 'sometimes|boolean',
|
||||
'deployment_failure_discord_notifications' => 'sometimes|boolean',
|
||||
'status_change_discord_notifications' => 'sometimes|boolean',
|
||||
'backup_success_discord_notifications' => 'sometimes|boolean',
|
||||
'backup_failure_discord_notifications' => 'sometimes|boolean',
|
||||
'scheduled_task_success_discord_notifications' => 'sometimes|boolean',
|
||||
'scheduled_task_failure_discord_notifications' => 'sometimes|boolean',
|
||||
'docker_cleanup_success_discord_notifications' => 'sometimes|boolean',
|
||||
'docker_cleanup_failure_discord_notifications' => 'sometimes|boolean',
|
||||
'server_disk_usage_discord_notifications' => 'sometimes|boolean',
|
||||
'server_reachable_discord_notifications' => 'sometimes|boolean',
|
||||
'server_unreachable_discord_notifications' => 'sometimes|boolean',
|
||||
'server_patch_discord_notifications' => 'sometimes|boolean',
|
||||
'traefik_outdated_discord_notifications' => 'sometimes|boolean',
|
||||
'discord_ping_enabled' => 'sometimes|boolean',
|
||||
],
|
||||
],
|
||||
'slack' => [
|
||||
'model' => SlackNotificationSettings::class,
|
||||
'rules' => [
|
||||
'slack_enabled' => 'sometimes|boolean',
|
||||
'slack_webhook_url' => ['sometimes', 'nullable', 'string', new SafeWebhookUrl],
|
||||
'deployment_success_slack_notifications' => 'sometimes|boolean',
|
||||
'deployment_failure_slack_notifications' => 'sometimes|boolean',
|
||||
'status_change_slack_notifications' => 'sometimes|boolean',
|
||||
'backup_success_slack_notifications' => 'sometimes|boolean',
|
||||
'backup_failure_slack_notifications' => 'sometimes|boolean',
|
||||
'scheduled_task_success_slack_notifications' => 'sometimes|boolean',
|
||||
'scheduled_task_failure_slack_notifications' => 'sometimes|boolean',
|
||||
'docker_cleanup_success_slack_notifications' => 'sometimes|boolean',
|
||||
'docker_cleanup_failure_slack_notifications' => 'sometimes|boolean',
|
||||
'server_disk_usage_slack_notifications' => 'sometimes|boolean',
|
||||
'server_reachable_slack_notifications' => 'sometimes|boolean',
|
||||
'server_unreachable_slack_notifications' => 'sometimes|boolean',
|
||||
'server_patch_slack_notifications' => 'sometimes|boolean',
|
||||
'traefik_outdated_slack_notifications' => 'sometimes|boolean',
|
||||
],
|
||||
],
|
||||
'telegram' => [
|
||||
'model' => TelegramNotificationSettings::class,
|
||||
'rules' => [
|
||||
'telegram_enabled' => 'sometimes|boolean',
|
||||
'telegram_token' => 'sometimes|nullable|string|max:255',
|
||||
'telegram_chat_id' => 'sometimes|nullable|string|max:255',
|
||||
'deployment_success_telegram_notifications' => 'sometimes|boolean',
|
||||
'deployment_failure_telegram_notifications' => 'sometimes|boolean',
|
||||
'status_change_telegram_notifications' => 'sometimes|boolean',
|
||||
'backup_success_telegram_notifications' => 'sometimes|boolean',
|
||||
'backup_failure_telegram_notifications' => 'sometimes|boolean',
|
||||
'scheduled_task_success_telegram_notifications' => 'sometimes|boolean',
|
||||
'scheduled_task_failure_telegram_notifications' => 'sometimes|boolean',
|
||||
'docker_cleanup_success_telegram_notifications' => 'sometimes|boolean',
|
||||
'docker_cleanup_failure_telegram_notifications' => 'sometimes|boolean',
|
||||
'server_disk_usage_telegram_notifications' => 'sometimes|boolean',
|
||||
'server_reachable_telegram_notifications' => 'sometimes|boolean',
|
||||
'server_unreachable_telegram_notifications' => 'sometimes|boolean',
|
||||
'server_patch_telegram_notifications' => 'sometimes|boolean',
|
||||
'traefik_outdated_telegram_notifications' => 'sometimes|boolean',
|
||||
'telegram_notifications_deployment_success_thread_id' => 'sometimes|nullable|string|max:255',
|
||||
'telegram_notifications_deployment_failure_thread_id' => 'sometimes|nullable|string|max:255',
|
||||
'telegram_notifications_status_change_thread_id' => 'sometimes|nullable|string|max:255',
|
||||
'telegram_notifications_backup_success_thread_id' => 'sometimes|nullable|string|max:255',
|
||||
'telegram_notifications_backup_failure_thread_id' => 'sometimes|nullable|string|max:255',
|
||||
'telegram_notifications_scheduled_task_success_thread_id' => 'sometimes|nullable|string|max:255',
|
||||
'telegram_notifications_scheduled_task_failure_thread_id' => 'sometimes|nullable|string|max:255',
|
||||
'telegram_notifications_docker_cleanup_success_thread_id' => 'sometimes|nullable|string|max:255',
|
||||
'telegram_notifications_docker_cleanup_failure_thread_id' => 'sometimes|nullable|string|max:255',
|
||||
'telegram_notifications_server_disk_usage_thread_id' => 'sometimes|nullable|string|max:255',
|
||||
'telegram_notifications_server_reachable_thread_id' => 'sometimes|nullable|string|max:255',
|
||||
'telegram_notifications_server_unreachable_thread_id' => 'sometimes|nullable|string|max:255',
|
||||
'telegram_notifications_server_patch_thread_id' => 'sometimes|nullable|string|max:255',
|
||||
'telegram_notifications_traefik_outdated_thread_id' => 'sometimes|nullable|string|max:255',
|
||||
],
|
||||
],
|
||||
'pushover' => [
|
||||
'model' => PushoverNotificationSettings::class,
|
||||
'rules' => [
|
||||
'pushover_enabled' => 'sometimes|boolean',
|
||||
'pushover_user_key' => 'sometimes|nullable|string|max:255',
|
||||
'pushover_api_token' => 'sometimes|nullable|string|max:255',
|
||||
'deployment_success_pushover_notifications' => 'sometimes|boolean',
|
||||
'deployment_failure_pushover_notifications' => 'sometimes|boolean',
|
||||
'status_change_pushover_notifications' => 'sometimes|boolean',
|
||||
'backup_success_pushover_notifications' => 'sometimes|boolean',
|
||||
'backup_failure_pushover_notifications' => 'sometimes|boolean',
|
||||
'scheduled_task_success_pushover_notifications' => 'sometimes|boolean',
|
||||
'scheduled_task_failure_pushover_notifications' => 'sometimes|boolean',
|
||||
'docker_cleanup_success_pushover_notifications' => 'sometimes|boolean',
|
||||
'docker_cleanup_failure_pushover_notifications' => 'sometimes|boolean',
|
||||
'server_disk_usage_pushover_notifications' => 'sometimes|boolean',
|
||||
'server_reachable_pushover_notifications' => 'sometimes|boolean',
|
||||
'server_unreachable_pushover_notifications' => 'sometimes|boolean',
|
||||
'server_patch_pushover_notifications' => 'sometimes|boolean',
|
||||
'traefik_outdated_pushover_notifications' => 'sometimes|boolean',
|
||||
],
|
||||
],
|
||||
'webhook' => [
|
||||
'model' => WebhookNotificationSettings::class,
|
||||
'rules' => [
|
||||
'webhook_enabled' => 'sometimes|boolean',
|
||||
'webhook_url' => ['sometimes', 'nullable', 'string', new SafeWebhookUrl],
|
||||
'deployment_success_webhook_notifications' => 'sometimes|boolean',
|
||||
'deployment_failure_webhook_notifications' => 'sometimes|boolean',
|
||||
'status_change_webhook_notifications' => 'sometimes|boolean',
|
||||
'backup_success_webhook_notifications' => 'sometimes|boolean',
|
||||
'backup_failure_webhook_notifications' => 'sometimes|boolean',
|
||||
'scheduled_task_success_webhook_notifications' => 'sometimes|boolean',
|
||||
'scheduled_task_failure_webhook_notifications' => 'sometimes|boolean',
|
||||
'docker_cleanup_success_webhook_notifications' => 'sometimes|boolean',
|
||||
'docker_cleanup_failure_webhook_notifications' => 'sometimes|boolean',
|
||||
'server_disk_usage_webhook_notifications' => 'sometimes|boolean',
|
||||
'server_reachable_webhook_notifications' => 'sometimes|boolean',
|
||||
'server_unreachable_webhook_notifications' => 'sometimes|boolean',
|
||||
'server_patch_webhook_notifications' => 'sometimes|boolean',
|
||||
'traefik_outdated_webhook_notifications' => 'sometimes|boolean',
|
||||
],
|
||||
],
|
||||
default => throw new \InvalidArgumentException("Unknown notification channel [{$channel}]."),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
private function allowedFields(string $channel): array
|
||||
{
|
||||
$config = $this->channelConfig($channel);
|
||||
/** @var Model $model */
|
||||
$model = new $config['model'];
|
||||
|
||||
return array_values(array_filter(
|
||||
$model->getFillable(),
|
||||
fn (string $field): bool => $field !== 'team_id'
|
||||
));
|
||||
}
|
||||
|
||||
private function serializeSettings(Model $settings): array
|
||||
{
|
||||
exposeSensitiveFields($settings);
|
||||
|
||||
$settings->makeHidden(['team']);
|
||||
|
||||
return serializeApiResponse($settings)->toArray();
|
||||
}
|
||||
|
||||
private function resolveSettings(string $channel, int $teamId): Model
|
||||
{
|
||||
$config = $this->channelConfig($channel);
|
||||
$modelClass = $config['model'];
|
||||
|
||||
/** @var Model $settings */
|
||||
$settings = $modelClass::query()->firstOrCreate(['team_id' => $teamId]);
|
||||
$settings->setRelation('team', Team::query()->findOrFail($teamId));
|
||||
|
||||
return $settings;
|
||||
}
|
||||
|
||||
private function showChannel(string $channel): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$settings = $this->resolveSettings($channel, $teamId);
|
||||
$this->authorize('view', $settings);
|
||||
|
||||
return response()->json($this->serializeSettings($settings));
|
||||
}
|
||||
|
||||
private function updateChannel(Request $request, string $channel): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$return = validateIncomingRequest($request);
|
||||
if ($return instanceof JsonResponse) {
|
||||
return $return;
|
||||
}
|
||||
|
||||
$allowedFields = $this->allowedFields($channel);
|
||||
$body = $request->json()->all();
|
||||
$config = $this->channelConfig($channel);
|
||||
|
||||
$validator = customApiValidator($body, $config['rules']);
|
||||
|
||||
$extraFields = array_diff(array_keys($body), $allowedFields);
|
||||
if ($validator->fails() || ! empty($extraFields)) {
|
||||
$errors = $validator->errors();
|
||||
if (! empty($extraFields)) {
|
||||
foreach ($extraFields as $field) {
|
||||
$errors->add($field, 'This field is not allowed.');
|
||||
}
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Validation failed.',
|
||||
'errors' => $errors,
|
||||
], 422);
|
||||
}
|
||||
|
||||
$settings = $this->resolveSettings($channel, $teamId);
|
||||
$this->authorize('update', $settings);
|
||||
|
||||
$settings->fill(array_intersect_key($body, array_flip($allowedFields)));
|
||||
$settings->save();
|
||||
|
||||
auditLog("api.notifications.{$channel}.updated", [
|
||||
'team_id' => $teamId,
|
||||
'changed_fields' => array_values(array_intersect($allowedFields, array_keys($body))),
|
||||
]);
|
||||
|
||||
$settings->refresh();
|
||||
$settings->setRelation('team', Team::query()->findOrFail($teamId));
|
||||
|
||||
return response()->json($this->serializeSettings($settings));
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'Get email notification settings',
|
||||
description: 'Get the current team email notification settings. Encrypted secrets are only returned when the token has `read:sensitive` (or `root`) and the user is a team admin/owner.',
|
||||
path: '/notifications/email',
|
||||
operationId: 'get-current-team-email-notifications',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Notifications'],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Email notification settings.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
]
|
||||
)]
|
||||
public function email(Request $request): JsonResponse
|
||||
{
|
||||
return $this->showChannel('email');
|
||||
}
|
||||
|
||||
#[OA\Patch(
|
||||
summary: 'Update email notification settings',
|
||||
description: 'Update the current team email notification settings.',
|
||||
path: '/notifications/email',
|
||||
operationId: 'update-current-team-email-notifications',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Notifications'],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Updated email notification settings.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 403, description: 'Forbidden.'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
]
|
||||
)]
|
||||
public function update_email(Request $request): JsonResponse
|
||||
{
|
||||
return $this->updateChannel($request, 'email');
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'Get Discord notification settings',
|
||||
description: 'Get the current team Discord notification settings. Encrypted secrets are only returned when the token has `read:sensitive` (or `root`) and the user is a team admin/owner.',
|
||||
path: '/notifications/discord',
|
||||
operationId: 'get-current-team-discord-notifications',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Notifications'],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Discord notification settings.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
]
|
||||
)]
|
||||
public function discord(Request $request): JsonResponse
|
||||
{
|
||||
return $this->showChannel('discord');
|
||||
}
|
||||
|
||||
#[OA\Patch(
|
||||
summary: 'Update Discord notification settings',
|
||||
description: 'Update the current team Discord notification settings.',
|
||||
path: '/notifications/discord',
|
||||
operationId: 'update-current-team-discord-notifications',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Notifications'],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Updated Discord notification settings.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 403, description: 'Forbidden.'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
]
|
||||
)]
|
||||
public function update_discord(Request $request): JsonResponse
|
||||
{
|
||||
return $this->updateChannel($request, 'discord');
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'Get Slack notification settings',
|
||||
description: 'Get the current team Slack notification settings. Encrypted secrets are only returned when the token has `read:sensitive` (or `root`) and the user is a team admin/owner.',
|
||||
path: '/notifications/slack',
|
||||
operationId: 'get-current-team-slack-notifications',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Notifications'],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Slack notification settings.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
]
|
||||
)]
|
||||
public function slack(Request $request): JsonResponse
|
||||
{
|
||||
return $this->showChannel('slack');
|
||||
}
|
||||
|
||||
#[OA\Patch(
|
||||
summary: 'Update Slack notification settings',
|
||||
description: 'Update the current team Slack notification settings.',
|
||||
path: '/notifications/slack',
|
||||
operationId: 'update-current-team-slack-notifications',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Notifications'],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Updated Slack notification settings.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 403, description: 'Forbidden.'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
]
|
||||
)]
|
||||
public function update_slack(Request $request): JsonResponse
|
||||
{
|
||||
return $this->updateChannel($request, 'slack');
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'Get Telegram notification settings',
|
||||
description: 'Get the current team Telegram notification settings. Encrypted secrets are only returned when the token has `read:sensitive` (or `root`) and the user is a team admin/owner.',
|
||||
path: '/notifications/telegram',
|
||||
operationId: 'get-current-team-telegram-notifications',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Notifications'],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Telegram notification settings.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
]
|
||||
)]
|
||||
public function telegram(Request $request): JsonResponse
|
||||
{
|
||||
return $this->showChannel('telegram');
|
||||
}
|
||||
|
||||
#[OA\Patch(
|
||||
summary: 'Update Telegram notification settings',
|
||||
description: 'Update the current team Telegram notification settings.',
|
||||
path: '/notifications/telegram',
|
||||
operationId: 'update-current-team-telegram-notifications',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Notifications'],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Updated Telegram notification settings.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 403, description: 'Forbidden.'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
]
|
||||
)]
|
||||
public function update_telegram(Request $request): JsonResponse
|
||||
{
|
||||
return $this->updateChannel($request, 'telegram');
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'Get Pushover notification settings',
|
||||
description: 'Get the current team Pushover notification settings. Encrypted secrets are only returned when the token has `read:sensitive` (or `root`) and the user is a team admin/owner.',
|
||||
path: '/notifications/pushover',
|
||||
operationId: 'get-current-team-pushover-notifications',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Notifications'],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Pushover notification settings.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
]
|
||||
)]
|
||||
public function pushover(Request $request): JsonResponse
|
||||
{
|
||||
return $this->showChannel('pushover');
|
||||
}
|
||||
|
||||
#[OA\Patch(
|
||||
summary: 'Update Pushover notification settings',
|
||||
description: 'Update the current team Pushover notification settings.',
|
||||
path: '/notifications/pushover',
|
||||
operationId: 'update-current-team-pushover-notifications',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Notifications'],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Updated Pushover notification settings.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 403, description: 'Forbidden.'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
]
|
||||
)]
|
||||
public function update_pushover(Request $request): JsonResponse
|
||||
{
|
||||
return $this->updateChannel($request, 'pushover');
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'Get webhook notification settings',
|
||||
description: 'Get the current team webhook notification settings. Encrypted secrets are only returned when the token has `read:sensitive` (or `root`) and the user is a team admin/owner.',
|
||||
path: '/notifications/webhook',
|
||||
operationId: 'get-current-team-webhook-notifications',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Notifications'],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Webhook notification settings.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
]
|
||||
)]
|
||||
public function webhook(Request $request): JsonResponse
|
||||
{
|
||||
return $this->showChannel('webhook');
|
||||
}
|
||||
|
||||
#[OA\Patch(
|
||||
summary: 'Update webhook notification settings',
|
||||
description: 'Update the current team webhook notification settings.',
|
||||
path: '/notifications/webhook',
|
||||
operationId: 'update-current-team-webhook-notifications',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Notifications'],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Updated webhook notification settings.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 403, description: 'Forbidden.'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
]
|
||||
)]
|
||||
public function update_webhook(Request $request): JsonResponse
|
||||
{
|
||||
return $this->updateChannel($request, 'webhook');
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,20 @@
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use OpenApi\Attributes as OA;
|
||||
|
||||
class OtherController extends Controller
|
||||
{
|
||||
public function post_required(): JsonResponse
|
||||
{
|
||||
return response()
|
||||
->json(['message' => 'This endpoint has changed to a POST request.'], 405)
|
||||
->header('Allow', 'POST');
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'Version',
|
||||
description: 'Get Coolify version.',
|
||||
@@ -41,7 +49,7 @@ class OtherController extends Controller
|
||||
return response(config('constants.coolify.version'));
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
#[OA\Post(
|
||||
summary: 'Enable API',
|
||||
description: 'Enable API (only with root permissions).',
|
||||
path: '/enable',
|
||||
@@ -97,7 +105,7 @@ class OtherController extends Controller
|
||||
return response()->json(['message' => 'API enabled.'], 200);
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
#[OA\Post(
|
||||
summary: 'Disable API',
|
||||
description: 'Disable API (only with root permissions).',
|
||||
path: '/disable',
|
||||
@@ -308,6 +316,6 @@ class OtherController extends Controller
|
||||
)]
|
||||
public function healthcheck(Request $request)
|
||||
{
|
||||
return 'OK';
|
||||
return response('OK');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -682,6 +682,155 @@ class ProjectController extends Controller
|
||||
])->setStatusCode(201);
|
||||
}
|
||||
|
||||
#[OA\Patch(
|
||||
summary: 'Update Environment',
|
||||
description: 'Update environment by name or UUID within a project.',
|
||||
path: '/projects/{uuid}/environments/{environment_name_or_uuid}',
|
||||
operationId: 'update-environment',
|
||||
security: [
|
||||
['bearerAuth' => []],
|
||||
],
|
||||
tags: ['Projects'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Project UUID', schema: new OA\Schema(type: 'string')),
|
||||
new OA\Parameter(name: 'environment_name_or_uuid', in: 'path', required: true, description: 'Environment name or UUID', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
requestBody: new OA\RequestBody(
|
||||
required: true,
|
||||
description: 'Environment fields to update.',
|
||||
content: new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'name' => ['type' => 'string', 'description' => 'The name of the environment.'],
|
||||
'description' => ['type' => 'string', 'description' => 'The description of the environment.'],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 200,
|
||||
description: 'Environment updated.',
|
||||
content: [
|
||||
new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'uuid' => ['type' => 'string', 'example' => 'env123'],
|
||||
'name' => ['type' => 'string', 'example' => 'staging'],
|
||||
'description' => ['type' => 'string', 'example' => 'Staging environment'],
|
||||
]
|
||||
)
|
||||
),
|
||||
]),
|
||||
new OA\Response(
|
||||
response: 401,
|
||||
ref: '#/components/responses/401',
|
||||
),
|
||||
new OA\Response(
|
||||
response: 400,
|
||||
ref: '#/components/responses/400',
|
||||
),
|
||||
new OA\Response(
|
||||
response: 404,
|
||||
description: 'Project or environment not found.',
|
||||
),
|
||||
new OA\Response(
|
||||
response: 409,
|
||||
description: 'Environment with this name already exists.',
|
||||
),
|
||||
new OA\Response(
|
||||
response: 422,
|
||||
ref: '#/components/responses/422',
|
||||
),
|
||||
]
|
||||
)]
|
||||
public function update_environment(Request $request)
|
||||
{
|
||||
$allowedFields = ['name', 'description'];
|
||||
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$return = validateIncomingRequest($request);
|
||||
if ($return instanceof JsonResponse) {
|
||||
return $return;
|
||||
}
|
||||
|
||||
$validator = Validator::make($request->all(), [
|
||||
'name' => ValidationPatterns::nameRules(required: false),
|
||||
'description' => ValidationPatterns::descriptionRules(),
|
||||
], ValidationPatterns::combinedMessages());
|
||||
|
||||
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
|
||||
if ($validator->fails() || ! empty($extraFields)) {
|
||||
$errors = $validator->errors();
|
||||
if (! empty($extraFields)) {
|
||||
foreach ($extraFields as $field) {
|
||||
$errors->add($field, 'This field is not allowed.');
|
||||
}
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Validation failed.',
|
||||
'errors' => $errors,
|
||||
], 422);
|
||||
}
|
||||
|
||||
if (! $request->uuid) {
|
||||
return response()->json(['message' => 'Project UUID is required.'], 422);
|
||||
}
|
||||
if (! $request->environment_name_or_uuid) {
|
||||
return response()->json(['message' => 'Environment name or UUID is required.'], 422);
|
||||
}
|
||||
|
||||
$project = Project::whereTeamId($teamId)->whereUuid($request->uuid)->first();
|
||||
if (! $project) {
|
||||
return response()->json(['message' => 'Project not found.'], 404);
|
||||
}
|
||||
|
||||
$environment = $project->environments()->whereName($request->environment_name_or_uuid)->first();
|
||||
if (! $environment) {
|
||||
$environment = $project->environments()->whereUuid($request->environment_name_or_uuid)->first();
|
||||
}
|
||||
if (! $environment) {
|
||||
return response()->json(['message' => 'Environment not found.'], 404);
|
||||
}
|
||||
|
||||
$this->authorize('update', $environment);
|
||||
|
||||
if ($request->filled('name') && $request->name !== $environment->name) {
|
||||
$existingEnvironment = $project->environments()
|
||||
->where('name', $request->name)
|
||||
->where('id', '!=', $environment->id)
|
||||
->first();
|
||||
if ($existingEnvironment) {
|
||||
return response()->json(['message' => 'Environment with this name already exists.'], 409);
|
||||
}
|
||||
}
|
||||
|
||||
$environment->update($request->only($allowedFields));
|
||||
|
||||
auditLog('api.project.environment_updated', [
|
||||
'team_id' => $teamId,
|
||||
'project_uuid' => $project->uuid,
|
||||
'environment_uuid' => $environment->uuid,
|
||||
'environment_name' => $environment->name,
|
||||
'changed_fields' => array_values(array_intersect($allowedFields, array_keys($request->all()))),
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'uuid' => $environment->uuid,
|
||||
'name' => $environment->name,
|
||||
'description' => $environment->description,
|
||||
]);
|
||||
}
|
||||
|
||||
#[OA\Delete(
|
||||
summary: 'Delete Environment',
|
||||
description: 'Delete environment by name or UUID. Environment must be empty.',
|
||||
|
||||
@@ -0,0 +1,566 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\S3Storage;
|
||||
use App\Rules\SafeWebhookUrl;
|
||||
use App\Rules\ValidS3BucketName;
|
||||
use App\Support\ValidationPatterns;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use OpenApi\Attributes as OA;
|
||||
|
||||
class S3StoragesController extends Controller
|
||||
{
|
||||
private function removeSensitiveData(S3Storage $storage)
|
||||
{
|
||||
$storage->makeHidden([
|
||||
'id',
|
||||
]);
|
||||
|
||||
if (request()->attributes->get('can_read_sensitive', false) === true) {
|
||||
$storage->makeVisible([
|
||||
'key',
|
||||
'secret',
|
||||
]);
|
||||
}
|
||||
|
||||
return serializeApiResponse($storage);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{valid: bool, error: string|null}
|
||||
*/
|
||||
private function validateStorageConnection(S3Storage $storage): array
|
||||
{
|
||||
try {
|
||||
$storage->testConnection(shouldSave: true);
|
||||
|
||||
return ['valid' => true, 'error' => null];
|
||||
} catch (\Throwable $e) {
|
||||
return ['valid' => false, 'error' => $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $body
|
||||
* @param array<int, string> $allowedFields
|
||||
* @param array<string, mixed> $rules
|
||||
*/
|
||||
private function validateBody(array $body, array $allowedFields, array $rules): ?JsonResponse
|
||||
{
|
||||
$validator = customApiValidator($body, $rules);
|
||||
|
||||
$extraFields = array_diff(array_keys($body), $allowedFields);
|
||||
if ($validator->fails() || ! empty($extraFields)) {
|
||||
$errors = $validator->errors();
|
||||
if (! empty($extraFields)) {
|
||||
foreach ($extraFields as $field) {
|
||||
$errors->add($field, 'This field is not allowed.');
|
||||
}
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Validation failed.',
|
||||
'errors' => $errors,
|
||||
], 422);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'List S3 Storages',
|
||||
description: 'List all S3 storages for the authenticated team.',
|
||||
path: '/s3-storages',
|
||||
operationId: 'list-s3-storages',
|
||||
security: [
|
||||
['bearerAuth' => []],
|
||||
],
|
||||
tags: ['S3 Storages'],
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 200,
|
||||
description: 'Get all S3 storages.',
|
||||
content: [
|
||||
new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'array',
|
||||
items: new OA\Items(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'uuid' => ['type' => 'string'],
|
||||
'name' => ['type' => 'string'],
|
||||
'description' => ['type' => 'string', 'nullable' => true],
|
||||
'endpoint' => ['type' => 'string'],
|
||||
'bucket' => ['type' => 'string'],
|
||||
'region' => ['type' => 'string'],
|
||||
'is_usable' => ['type' => 'boolean'],
|
||||
'team_id' => ['type' => 'integer'],
|
||||
'created_at' => ['type' => 'string'],
|
||||
'updated_at' => ['type' => 'string'],
|
||||
]
|
||||
)
|
||||
)
|
||||
),
|
||||
]),
|
||||
new OA\Response(
|
||||
response: 401,
|
||||
ref: '#/components/responses/401',
|
||||
),
|
||||
new OA\Response(
|
||||
response: 400,
|
||||
ref: '#/components/responses/400',
|
||||
),
|
||||
]
|
||||
)]
|
||||
public function index(Request $request)
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$storages = S3Storage::ownedByCurrentTeamAPI($teamId)
|
||||
->get()
|
||||
->map(function ($storage) {
|
||||
return $this->removeSensitiveData($storage);
|
||||
});
|
||||
|
||||
return response()->json($storages);
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'Get S3 Storage',
|
||||
description: 'Get S3 storage by UUID.',
|
||||
path: '/s3-storages/{uuid}',
|
||||
operationId: 'get-s3-storage-by-uuid',
|
||||
security: [
|
||||
['bearerAuth' => []],
|
||||
],
|
||||
tags: ['S3 Storages'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'S3 Storage UUID', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 200,
|
||||
description: 'Get S3 storage by UUID',
|
||||
content: [
|
||||
new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'uuid' => ['type' => 'string'],
|
||||
'name' => ['type' => 'string'],
|
||||
'description' => ['type' => 'string', 'nullable' => true],
|
||||
'endpoint' => ['type' => 'string'],
|
||||
'bucket' => ['type' => 'string'],
|
||||
'region' => ['type' => 'string'],
|
||||
'is_usable' => ['type' => 'boolean'],
|
||||
'team_id' => ['type' => 'integer'],
|
||||
'created_at' => ['type' => 'string'],
|
||||
'updated_at' => ['type' => 'string'],
|
||||
]
|
||||
)
|
||||
),
|
||||
]),
|
||||
new OA\Response(
|
||||
response: 401,
|
||||
ref: '#/components/responses/401',
|
||||
),
|
||||
new OA\Response(
|
||||
response: 404,
|
||||
ref: '#/components/responses/404',
|
||||
),
|
||||
]
|
||||
)]
|
||||
public function show(Request $request)
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$storage = S3Storage::ownedByCurrentTeamAPI($teamId)
|
||||
->whereUuid($request->uuid)
|
||||
->first();
|
||||
|
||||
if (is_null($storage)) {
|
||||
return response()->json(['message' => 'S3 storage not found.'], 404);
|
||||
}
|
||||
$this->authorize('view', $storage);
|
||||
|
||||
return response()->json($this->removeSensitiveData($storage));
|
||||
}
|
||||
|
||||
#[OA\Post(
|
||||
summary: 'Create S3 Storage',
|
||||
description: 'Create a new S3 storage configuration for the authenticated team.',
|
||||
path: '/s3-storages',
|
||||
operationId: 'create-s3-storage',
|
||||
security: [
|
||||
['bearerAuth' => []],
|
||||
],
|
||||
tags: ['S3 Storages'],
|
||||
requestBody: new OA\RequestBody(
|
||||
required: true,
|
||||
description: 'S3 storage details',
|
||||
content: new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'object',
|
||||
required: ['name', 'endpoint', 'bucket', 'region', 'key', 'secret'],
|
||||
properties: [
|
||||
'name' => ['type' => 'string', 'example' => 'My S3 Storage', 'description' => 'A friendly name for the storage.'],
|
||||
'description' => ['type' => 'string', 'nullable' => true, 'description' => 'Optional description.'],
|
||||
'endpoint' => ['type' => 'string', 'example' => 'https://s3.us-east-1.amazonaws.com', 'description' => 'S3-compatible endpoint URL.'],
|
||||
'bucket' => ['type' => 'string', 'example' => 'my-bucket', 'description' => 'S3 bucket name.'],
|
||||
'region' => ['type' => 'string', 'example' => 'us-east-1', 'description' => 'S3 region.'],
|
||||
'key' => ['type' => 'string', 'description' => 'Access key.'],
|
||||
'secret' => ['type' => 'string', 'description' => 'Secret key.'],
|
||||
'is_usable' => ['type' => 'boolean', 'description' => 'Whether the storage is marked usable.'],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 201,
|
||||
description: 'S3 storage created.',
|
||||
content: [
|
||||
new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'uuid' => ['type' => 'string', 'example' => 'og888os', 'description' => 'The UUID of the S3 storage.'],
|
||||
]
|
||||
)
|
||||
),
|
||||
]),
|
||||
new OA\Response(
|
||||
response: 401,
|
||||
ref: '#/components/responses/401',
|
||||
),
|
||||
new OA\Response(
|
||||
response: 400,
|
||||
ref: '#/components/responses/400',
|
||||
),
|
||||
new OA\Response(
|
||||
response: 422,
|
||||
ref: '#/components/responses/422',
|
||||
),
|
||||
]
|
||||
)]
|
||||
public function store(Request $request)
|
||||
{
|
||||
$allowedFields = ['name', 'description', 'endpoint', 'bucket', 'region', 'key', 'secret', 'is_usable'];
|
||||
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
$this->authorize('create', [S3Storage::class]);
|
||||
|
||||
$return = validateIncomingRequest($request);
|
||||
if ($return instanceof JsonResponse) {
|
||||
return $return;
|
||||
}
|
||||
|
||||
$body = $request->json()->all();
|
||||
|
||||
$validationError = $this->validateBody($body, $allowedFields, [
|
||||
'name' => ValidationPatterns::nameRules(),
|
||||
'description' => ValidationPatterns::descriptionRules(),
|
||||
'endpoint' => ['required', 'string', 'max:255', new SafeWebhookUrl],
|
||||
'bucket' => ['required', new ValidS3BucketName],
|
||||
'region' => 'required|string|max:255',
|
||||
'key' => 'required|string|max:255',
|
||||
'secret' => 'required|string|max:255',
|
||||
'is_usable' => 'sometimes|boolean',
|
||||
]);
|
||||
if ($validationError instanceof JsonResponse) {
|
||||
return $validationError;
|
||||
}
|
||||
|
||||
$storage = S3Storage::create([
|
||||
'team_id' => $teamId,
|
||||
'name' => $body['name'],
|
||||
'description' => $body['description'] ?? null,
|
||||
'endpoint' => $body['endpoint'],
|
||||
'bucket' => $body['bucket'],
|
||||
'region' => $body['region'],
|
||||
'key' => $body['key'],
|
||||
'secret' => $body['secret'],
|
||||
'is_usable' => $body['is_usable'] ?? false,
|
||||
]);
|
||||
|
||||
auditLog('api.s3_storage.created', [
|
||||
'team_id' => $teamId,
|
||||
's3_storage_uuid' => $storage->uuid,
|
||||
's3_storage_name' => $storage->name,
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'uuid' => $storage->uuid,
|
||||
])->setStatusCode(201);
|
||||
}
|
||||
|
||||
#[OA\Patch(
|
||||
summary: 'Update S3 Storage',
|
||||
description: 'Update S3 storage by UUID.',
|
||||
path: '/s3-storages/{uuid}',
|
||||
operationId: 'update-s3-storage-by-uuid',
|
||||
security: [
|
||||
['bearerAuth' => []],
|
||||
],
|
||||
tags: ['S3 Storages'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'S3 Storage UUID', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
requestBody: new OA\RequestBody(
|
||||
required: true,
|
||||
description: 'S3 storage fields to update.',
|
||||
content: new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'name' => ['type' => 'string', 'description' => 'A friendly name for the storage.'],
|
||||
'description' => ['type' => 'string', 'nullable' => true, 'description' => 'Optional description.'],
|
||||
'endpoint' => ['type' => 'string', 'description' => 'S3-compatible endpoint URL.'],
|
||||
'bucket' => ['type' => 'string', 'description' => 'S3 bucket name.'],
|
||||
'region' => ['type' => 'string', 'description' => 'S3 region.'],
|
||||
'key' => ['type' => 'string', 'description' => 'Access key.'],
|
||||
'secret' => ['type' => 'string', 'description' => 'Secret key.'],
|
||||
'is_usable' => ['type' => 'boolean', 'description' => 'Whether the storage is marked usable.'],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 200,
|
||||
description: 'S3 storage updated.',
|
||||
content: [
|
||||
new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'uuid' => ['type' => 'string'],
|
||||
]
|
||||
)
|
||||
),
|
||||
]),
|
||||
new OA\Response(
|
||||
response: 401,
|
||||
ref: '#/components/responses/401',
|
||||
),
|
||||
new OA\Response(
|
||||
response: 404,
|
||||
ref: '#/components/responses/404',
|
||||
),
|
||||
new OA\Response(
|
||||
response: 422,
|
||||
ref: '#/components/responses/422',
|
||||
),
|
||||
]
|
||||
)]
|
||||
public function update(Request $request)
|
||||
{
|
||||
$allowedFields = ['name', 'description', 'endpoint', 'bucket', 'region', 'key', 'secret', 'is_usable'];
|
||||
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$return = validateIncomingRequest($request);
|
||||
if ($return instanceof JsonResponse) {
|
||||
return $return;
|
||||
}
|
||||
|
||||
$body = $request->json()->all();
|
||||
|
||||
$validationError = $this->validateBody($body, $allowedFields, [
|
||||
'name' => ValidationPatterns::nameRules(required: false),
|
||||
'description' => ValidationPatterns::descriptionRules(),
|
||||
'endpoint' => ['sometimes', 'string', 'max:255', new SafeWebhookUrl],
|
||||
'bucket' => ['sometimes', new ValidS3BucketName],
|
||||
'region' => 'sometimes|string|max:255',
|
||||
'key' => 'sometimes|string|max:255',
|
||||
'secret' => 'sometimes|string|max:255',
|
||||
'is_usable' => 'sometimes|boolean',
|
||||
]);
|
||||
if ($validationError instanceof JsonResponse) {
|
||||
return $validationError;
|
||||
}
|
||||
|
||||
$storage = S3Storage::ownedByCurrentTeamAPI($teamId)->whereUuid($request->route('uuid'))->first();
|
||||
if (! $storage) {
|
||||
return response()->json(['message' => 'S3 storage not found.'], 404);
|
||||
}
|
||||
$this->authorize('update', $storage);
|
||||
|
||||
$storage->update(array_intersect_key($body, array_flip($allowedFields)));
|
||||
|
||||
auditLog('api.s3_storage.updated', [
|
||||
'team_id' => $teamId,
|
||||
's3_storage_uuid' => $storage->uuid,
|
||||
's3_storage_name' => $storage->name,
|
||||
'changed_fields' => array_values(array_intersect($allowedFields, array_keys($body))),
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'uuid' => $storage->uuid,
|
||||
]);
|
||||
}
|
||||
|
||||
#[OA\Delete(
|
||||
summary: 'Delete S3 Storage',
|
||||
description: 'Delete S3 storage by UUID.',
|
||||
path: '/s3-storages/{uuid}',
|
||||
operationId: 'delete-s3-storage-by-uuid',
|
||||
security: [
|
||||
['bearerAuth' => []],
|
||||
],
|
||||
tags: ['S3 Storages'],
|
||||
parameters: [
|
||||
new OA\Parameter(
|
||||
name: 'uuid',
|
||||
in: 'path',
|
||||
description: 'UUID of the S3 storage.',
|
||||
required: true,
|
||||
schema: new OA\Schema(
|
||||
type: 'string',
|
||||
)
|
||||
),
|
||||
],
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 200,
|
||||
description: 'S3 storage deleted.',
|
||||
content: [
|
||||
new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'message' => ['type' => 'string', 'example' => 'S3 storage deleted.'],
|
||||
]
|
||||
)
|
||||
),
|
||||
]),
|
||||
new OA\Response(
|
||||
response: 401,
|
||||
ref: '#/components/responses/401',
|
||||
),
|
||||
new OA\Response(
|
||||
response: 404,
|
||||
ref: '#/components/responses/404',
|
||||
),
|
||||
]
|
||||
)]
|
||||
public function destroy(Request $request)
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
if (! $request->uuid) {
|
||||
return response()->json(['message' => 'UUID is required.'], 422);
|
||||
}
|
||||
|
||||
$storage = S3Storage::ownedByCurrentTeamAPI($teamId)->whereUuid($request->uuid)->first();
|
||||
|
||||
if (! $storage) {
|
||||
return response()->json(['message' => 'S3 storage not found.'], 404);
|
||||
}
|
||||
$this->authorize('delete', $storage);
|
||||
|
||||
$storageUuid = $storage->uuid;
|
||||
$storageName = $storage->name;
|
||||
$storage->delete();
|
||||
|
||||
auditLog('api.s3_storage.deleted', [
|
||||
'team_id' => $teamId,
|
||||
's3_storage_uuid' => $storageUuid,
|
||||
's3_storage_name' => $storageName,
|
||||
]);
|
||||
|
||||
return response()->json(['message' => 'S3 storage deleted.']);
|
||||
}
|
||||
|
||||
#[OA\Post(
|
||||
summary: 'Validate S3 Storage',
|
||||
description: 'Validate an S3 storage connection using ListObjectsV2.',
|
||||
path: '/s3-storages/{uuid}/validate',
|
||||
operationId: 'validate-s3-storage-by-uuid',
|
||||
security: [
|
||||
['bearerAuth' => []],
|
||||
],
|
||||
tags: ['S3 Storages'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'S3 Storage UUID', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 200,
|
||||
description: 'S3 storage validation result.',
|
||||
content: [
|
||||
new OA\MediaType(
|
||||
mediaType: 'application/json',
|
||||
schema: new OA\Schema(
|
||||
type: 'object',
|
||||
properties: [
|
||||
'valid' => ['type' => 'boolean', 'example' => true],
|
||||
'message' => ['type' => 'string', 'example' => 'S3 storage connection is valid.'],
|
||||
]
|
||||
)
|
||||
),
|
||||
]),
|
||||
new OA\Response(
|
||||
response: 401,
|
||||
ref: '#/components/responses/401',
|
||||
),
|
||||
new OA\Response(
|
||||
response: 404,
|
||||
ref: '#/components/responses/404',
|
||||
),
|
||||
]
|
||||
)]
|
||||
public function validateStorage(Request $request)
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$storage = S3Storage::ownedByCurrentTeamAPI($teamId)->whereUuid($request->uuid)->first();
|
||||
|
||||
if (! $storage) {
|
||||
return response()->json(['message' => 'S3 storage not found.'], 404);
|
||||
}
|
||||
$this->authorize('validateConnection', $storage);
|
||||
|
||||
$validation = $this->validateStorageConnection($storage);
|
||||
|
||||
auditLog('api.s3_storage.validated', [
|
||||
'team_id' => $teamId,
|
||||
's3_storage_uuid' => $storage->uuid,
|
||||
's3_storage_name' => $storage->name,
|
||||
'valid' => $validation['valid'],
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'valid' => $validation['valid'],
|
||||
'message' => $validation['valid'] ? 'S3 storage connection is valid.' : $validation['error'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Jobs\ScheduledTaskJob;
|
||||
use App\Models\Application;
|
||||
use App\Models\ScheduledTask;
|
||||
use App\Models\Service;
|
||||
@@ -224,6 +225,28 @@ class ScheduledTasksController extends Controller
|
||||
return response()->json($executions);
|
||||
}
|
||||
|
||||
private function executeTask(Request $request, Application|Service $resource): JsonResponse
|
||||
{
|
||||
$this->authorize('update', $resource);
|
||||
|
||||
$task = $resource->scheduled_tasks()->where('uuid', $request->task_uuid)->first();
|
||||
if (! $task) {
|
||||
return response()->json(['message' => 'Scheduled task not found.'], 404);
|
||||
}
|
||||
|
||||
ScheduledTaskJob::dispatch($task);
|
||||
|
||||
auditLog('api.scheduled_task.executed', [
|
||||
'team_id' => getTeamIdFromToken(),
|
||||
'task_uuid' => $task->uuid,
|
||||
'task_name' => $task->name,
|
||||
'resource_type' => $resource instanceof Application ? 'application' : 'service',
|
||||
'resource_uuid' => $resource->uuid,
|
||||
]);
|
||||
|
||||
return response()->json(['message' => 'Scheduled task execution queued.']);
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'List Tasks',
|
||||
description: 'List all scheduled tasks for an application.',
|
||||
@@ -949,4 +972,68 @@ class ScheduledTasksController extends Controller
|
||||
|
||||
return $this->getExecutions($request, $service);
|
||||
}
|
||||
|
||||
#[OA\Post(
|
||||
summary: 'Execute Task',
|
||||
description: 'Queue immediate execution of a scheduled task for an application.',
|
||||
path: '/applications/{uuid}/scheduled-tasks/{task_uuid}/execute',
|
||||
operationId: 'execute-scheduled-task-by-application-uuid',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Scheduled Tasks'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the application.', schema: new OA\Schema(type: 'string')),
|
||||
new OA\Parameter(name: 'task_uuid', in: 'path', required: true, description: 'UUID of the scheduled task.', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Scheduled task execution queued.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
]
|
||||
)]
|
||||
public function execute_scheduled_task_by_application_uuid(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$application = $this->resolveApplication($request, $teamId);
|
||||
if (! $application) {
|
||||
return response()->json(['message' => 'Application not found.'], 404);
|
||||
}
|
||||
|
||||
return $this->executeTask($request, $application);
|
||||
}
|
||||
|
||||
#[OA\Post(
|
||||
summary: 'Execute Task',
|
||||
description: 'Queue immediate execution of a scheduled task for a service.',
|
||||
path: '/services/{uuid}/scheduled-tasks/{task_uuid}/execute',
|
||||
operationId: 'execute-scheduled-task-by-service-uuid',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Scheduled Tasks'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the service.', schema: new OA\Schema(type: 'string')),
|
||||
new OA\Parameter(name: 'task_uuid', in: 'path', required: true, description: 'UUID of the scheduled task.', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Scheduled task execution queued.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
]
|
||||
)]
|
||||
public function execute_scheduled_task_by_service_uuid(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$service = $this->resolveService($request, $teamId);
|
||||
if (! $service) {
|
||||
return response()->json(['message' => 'Service not found.'], 404);
|
||||
}
|
||||
|
||||
return $this->executeTask($request, $service);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Server;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use OpenApi\Attributes as OA;
|
||||
|
||||
class ServerCloudflareTunnelController extends Controller
|
||||
{
|
||||
private const ALLOWED_FIELDS = [
|
||||
'is_cloudflare_tunnel',
|
||||
];
|
||||
|
||||
private function findServerForTeam(int $teamId, string $uuid): ?Server
|
||||
{
|
||||
return Server::whereTeamId($teamId)->whereUuid($uuid)->first();
|
||||
}
|
||||
|
||||
private function transform(Server $server): array
|
||||
{
|
||||
return [
|
||||
'is_cloudflare_tunnel' => (bool) $server->settings->is_cloudflare_tunnel,
|
||||
'ip' => $server->ip,
|
||||
'ip_previous' => $server->ip_previous,
|
||||
];
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'Get Cloudflare Tunnel settings',
|
||||
description: 'Get Cloudflare Tunnel settings for a server owned by the authenticated team.',
|
||||
path: '/servers/{uuid}/cloudflare-tunnel',
|
||||
operationId: 'get-server-cloudflare-tunnel',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Servers'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 200,
|
||||
description: 'Cloudflare Tunnel settings.',
|
||||
content: new OA\JsonContent(
|
||||
properties: [
|
||||
new OA\Property(property: 'is_cloudflare_tunnel', type: 'boolean'),
|
||||
new OA\Property(property: 'ip', type: 'string'),
|
||||
new OA\Property(property: 'ip_previous', type: 'string', nullable: true),
|
||||
],
|
||||
type: 'object',
|
||||
),
|
||||
),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
],
|
||||
)]
|
||||
public function show(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$server = $this->findServerForTeam($teamId, $request->uuid);
|
||||
if (! $server) {
|
||||
return response()->json(['message' => 'Server not found.'], 404);
|
||||
}
|
||||
|
||||
$this->authorize('view', $server);
|
||||
|
||||
return response()->json($this->transform($server));
|
||||
}
|
||||
|
||||
#[OA\Patch(
|
||||
summary: 'Update Cloudflare Tunnel settings',
|
||||
description: 'Update stored Cloudflare Tunnel settings for a server. Does not run remote cloudflared configuration; use enable/disable for the manual UI actions.',
|
||||
path: '/servers/{uuid}/cloudflare-tunnel',
|
||||
operationId: 'update-server-cloudflare-tunnel',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Servers'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
requestBody: new OA\RequestBody(
|
||||
required: true,
|
||||
content: new OA\JsonContent(
|
||||
properties: [
|
||||
new OA\Property(property: 'is_cloudflare_tunnel', type: 'boolean'),
|
||||
],
|
||||
type: 'object',
|
||||
),
|
||||
),
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Updated Cloudflare Tunnel settings.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
],
|
||||
)]
|
||||
public function update(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$return = validateIncomingRequest($request);
|
||||
if ($return instanceof JsonResponse) {
|
||||
return $return;
|
||||
}
|
||||
|
||||
$server = $this->findServerForTeam($teamId, $request->uuid);
|
||||
if (! $server) {
|
||||
return response()->json(['message' => 'Server not found.'], 404);
|
||||
}
|
||||
|
||||
$this->authorize('update', $server);
|
||||
|
||||
if ($server->isLocalhost()) {
|
||||
return response()->json(['message' => 'Cloudflare Tunnel cannot be configured on the localhost server.'], 422);
|
||||
}
|
||||
|
||||
$validator = customApiValidator($request->all(), [
|
||||
'is_cloudflare_tunnel' => 'required|boolean',
|
||||
]);
|
||||
$extraFields = array_diff(array_keys($request->all()), self::ALLOWED_FIELDS);
|
||||
if ($validator->fails() || ! empty($extraFields)) {
|
||||
$errors = $validator->errors();
|
||||
foreach ($extraFields as $field) {
|
||||
$errors->add($field, 'This field is not allowed.');
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Validation failed.',
|
||||
'errors' => $errors,
|
||||
], 422);
|
||||
}
|
||||
|
||||
$enabled = $request->boolean('is_cloudflare_tunnel');
|
||||
$server->settings->is_cloudflare_tunnel = $enabled;
|
||||
$server->settings->save();
|
||||
|
||||
if (! $enabled && $server->ip_previous) {
|
||||
$server->update(['ip' => $server->ip_previous]);
|
||||
}
|
||||
|
||||
auditLog('api.server.cloudflare_tunnel.updated', [
|
||||
'team_id' => $teamId,
|
||||
'server_uuid' => $server->uuid,
|
||||
'server_name' => $server->name,
|
||||
'is_cloudflare_tunnel' => $enabled,
|
||||
]);
|
||||
|
||||
return response()->json($this->transform($server->refresh()));
|
||||
}
|
||||
|
||||
#[OA\Post(
|
||||
summary: 'Enable Cloudflare Tunnel (manual)',
|
||||
description: 'Manually mark Cloudflare Tunnel as enabled for a server (matches UI manual enable). Does not deploy cloudflared remotely.',
|
||||
path: '/servers/{uuid}/cloudflare-tunnel/enable',
|
||||
operationId: 'enable-server-cloudflare-tunnel',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Servers'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Cloudflare Tunnel enabled.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
],
|
||||
)]
|
||||
public function enable(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$server = $this->findServerForTeam($teamId, $request->uuid);
|
||||
if (! $server) {
|
||||
return response()->json(['message' => 'Server not found.'], 404);
|
||||
}
|
||||
|
||||
$this->authorize('update', $server);
|
||||
|
||||
if ($server->isLocalhost()) {
|
||||
return response()->json(['message' => 'Cloudflare Tunnel cannot be configured on the localhost server.'], 422);
|
||||
}
|
||||
|
||||
$server->settings->is_cloudflare_tunnel = true;
|
||||
$server->settings->save();
|
||||
|
||||
auditLog('api.server.cloudflare_tunnel.enabled', [
|
||||
'team_id' => $teamId,
|
||||
'server_uuid' => $server->uuid,
|
||||
'server_name' => $server->name,
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Cloudflare Tunnel enabled.',
|
||||
...$this->transform($server->refresh()),
|
||||
]);
|
||||
}
|
||||
|
||||
#[OA\Post(
|
||||
summary: 'Disable Cloudflare Tunnel',
|
||||
description: 'Mark Cloudflare Tunnel as disabled and restore ip_previous when available. Does not remove the remote cloudflared container.',
|
||||
path: '/servers/{uuid}/cloudflare-tunnel/disable',
|
||||
operationId: 'disable-server-cloudflare-tunnel',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Servers'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Cloudflare Tunnel disabled.'),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
],
|
||||
)]
|
||||
public function disable(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$server = $this->findServerForTeam($teamId, $request->uuid);
|
||||
if (! $server) {
|
||||
return response()->json(['message' => 'Server not found.'], 404);
|
||||
}
|
||||
|
||||
$this->authorize('update', $server);
|
||||
|
||||
if ($server->isLocalhost()) {
|
||||
return response()->json(['message' => 'Cloudflare Tunnel cannot be configured on the localhost server.'], 422);
|
||||
}
|
||||
|
||||
$server->settings->is_cloudflare_tunnel = false;
|
||||
$server->settings->save();
|
||||
|
||||
$message = 'Cloudflare Tunnel disabled.';
|
||||
if ($server->ip_previous) {
|
||||
$server->update(['ip' => $server->ip_previous]);
|
||||
$message .= ' Server IP restored to its previous IP address.';
|
||||
} else {
|
||||
$message .= ' Action required: Update the server IP address to its real IP address if needed.';
|
||||
}
|
||||
|
||||
auditLog('api.server.cloudflare_tunnel.disabled', [
|
||||
'team_id' => $teamId,
|
||||
'server_uuid' => $server->uuid,
|
||||
'server_name' => $server->name,
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'message' => $message,
|
||||
...$this->transform($server->refresh()),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Jobs\DockerCleanupJob;
|
||||
use App\Models\Server;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use OpenApi\Attributes as OA;
|
||||
|
||||
class ServerDockerCleanupController extends Controller
|
||||
{
|
||||
private const ALLOWED_FIELDS = [
|
||||
'docker_cleanup_frequency',
|
||||
'docker_cleanup_threshold',
|
||||
'force_docker_cleanup',
|
||||
'delete_unused_volumes',
|
||||
'delete_unused_networks',
|
||||
'disable_application_image_retention',
|
||||
];
|
||||
|
||||
private function findServerForTeam(int $teamId, string $uuid): ?Server
|
||||
{
|
||||
return Server::whereTeamId($teamId)->whereUuid($uuid)->first();
|
||||
}
|
||||
|
||||
private function transform(Server $server): array
|
||||
{
|
||||
$settings = $server->settings;
|
||||
|
||||
return [
|
||||
'docker_cleanup_frequency' => $settings->docker_cleanup_frequency,
|
||||
'docker_cleanup_threshold' => (int) $settings->docker_cleanup_threshold,
|
||||
'force_docker_cleanup' => (bool) $settings->force_docker_cleanup,
|
||||
'delete_unused_volumes' => (bool) $settings->delete_unused_volumes,
|
||||
'delete_unused_networks' => (bool) $settings->delete_unused_networks,
|
||||
'disable_application_image_retention' => (bool) $settings->disable_application_image_retention,
|
||||
];
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'Get Docker cleanup settings',
|
||||
description: 'Get Docker cleanup settings for a server owned by the authenticated team.',
|
||||
path: '/servers/{uuid}/docker-cleanup',
|
||||
operationId: 'get-server-docker-cleanup',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Servers'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 200,
|
||||
description: 'Docker cleanup settings.',
|
||||
content: new OA\JsonContent(
|
||||
properties: [
|
||||
new OA\Property(property: 'docker_cleanup_frequency', type: 'string'),
|
||||
new OA\Property(property: 'docker_cleanup_threshold', type: 'integer'),
|
||||
new OA\Property(property: 'force_docker_cleanup', type: 'boolean'),
|
||||
new OA\Property(property: 'delete_unused_volumes', type: 'boolean'),
|
||||
new OA\Property(property: 'delete_unused_networks', type: 'boolean'),
|
||||
new OA\Property(property: 'disable_application_image_retention', type: 'boolean'),
|
||||
],
|
||||
type: 'object',
|
||||
),
|
||||
),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
],
|
||||
)]
|
||||
public function show(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$server = $this->findServerForTeam($teamId, $request->uuid);
|
||||
if (! $server) {
|
||||
return response()->json(['message' => 'Server not found.'], 404);
|
||||
}
|
||||
|
||||
$this->authorize('view', $server);
|
||||
|
||||
return response()->json($this->transform($server));
|
||||
}
|
||||
|
||||
#[OA\Patch(
|
||||
summary: 'Update Docker cleanup settings',
|
||||
description: 'Update Docker cleanup settings for a server owned by the authenticated team.',
|
||||
path: '/servers/{uuid}/docker-cleanup',
|
||||
operationId: 'update-server-docker-cleanup',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Servers'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
requestBody: new OA\RequestBody(
|
||||
required: true,
|
||||
content: new OA\JsonContent(
|
||||
properties: [
|
||||
new OA\Property(property: 'docker_cleanup_frequency', type: 'string', description: 'Cron / human frequency expression.'),
|
||||
new OA\Property(property: 'docker_cleanup_threshold', type: 'integer', minimum: 1, maximum: 99),
|
||||
new OA\Property(property: 'force_docker_cleanup', type: 'boolean'),
|
||||
new OA\Property(property: 'delete_unused_volumes', type: 'boolean'),
|
||||
new OA\Property(property: 'delete_unused_networks', type: 'boolean'),
|
||||
new OA\Property(property: 'disable_application_image_retention', type: 'boolean'),
|
||||
],
|
||||
type: 'object',
|
||||
),
|
||||
),
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 200,
|
||||
description: 'Updated Docker cleanup settings.',
|
||||
content: new OA\JsonContent(
|
||||
properties: [
|
||||
new OA\Property(property: 'docker_cleanup_frequency', type: 'string'),
|
||||
new OA\Property(property: 'docker_cleanup_threshold', type: 'integer'),
|
||||
new OA\Property(property: 'force_docker_cleanup', type: 'boolean'),
|
||||
new OA\Property(property: 'delete_unused_volumes', type: 'boolean'),
|
||||
new OA\Property(property: 'delete_unused_networks', type: 'boolean'),
|
||||
new OA\Property(property: 'disable_application_image_retention', type: 'boolean'),
|
||||
],
|
||||
type: 'object',
|
||||
),
|
||||
),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
],
|
||||
)]
|
||||
public function update(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$return = validateIncomingRequest($request);
|
||||
if ($return instanceof JsonResponse) {
|
||||
return $return;
|
||||
}
|
||||
|
||||
$server = $this->findServerForTeam($teamId, $request->uuid);
|
||||
if (! $server) {
|
||||
return response()->json(['message' => 'Server not found.'], 404);
|
||||
}
|
||||
|
||||
$this->authorize('update', $server);
|
||||
|
||||
$validator = customApiValidator($request->all(), [
|
||||
'docker_cleanup_frequency' => 'string',
|
||||
'docker_cleanup_threshold' => 'integer|min:1|max:99',
|
||||
'force_docker_cleanup' => 'boolean',
|
||||
'delete_unused_volumes' => 'boolean',
|
||||
'delete_unused_networks' => 'boolean',
|
||||
'disable_application_image_retention' => 'boolean',
|
||||
]);
|
||||
|
||||
$extraFields = array_diff(array_keys($request->all()), self::ALLOWED_FIELDS);
|
||||
if ($validator->fails() || ! empty($extraFields)) {
|
||||
$errors = $validator->errors();
|
||||
foreach ($extraFields as $field) {
|
||||
$errors->add($field, 'This field is not allowed.');
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Validation failed.',
|
||||
'errors' => $errors,
|
||||
], 422);
|
||||
}
|
||||
|
||||
if ($request->has('docker_cleanup_frequency') && ! validate_cron_expression($request->docker_cleanup_frequency)) {
|
||||
return response()->json([
|
||||
'message' => 'Validation failed.',
|
||||
'errors' => ['docker_cleanup_frequency' => ['Invalid Cron / Human expression for Docker Cleanup Frequency.']],
|
||||
], 422);
|
||||
}
|
||||
|
||||
$settings = $server->settings;
|
||||
foreach (self::ALLOWED_FIELDS as $field) {
|
||||
if ($request->has($field)) {
|
||||
$settings->{$field} = $request->input($field);
|
||||
}
|
||||
}
|
||||
$settings->save();
|
||||
|
||||
auditLog('api.server.docker_cleanup.updated', [
|
||||
'team_id' => $teamId,
|
||||
'server_uuid' => $server->uuid,
|
||||
'server_name' => $server->name,
|
||||
'changed_fields' => array_values(array_intersect(self::ALLOWED_FIELDS, array_keys($request->all()))),
|
||||
]);
|
||||
|
||||
return response()->json($this->transform($server->refresh()));
|
||||
}
|
||||
|
||||
#[OA\Post(
|
||||
summary: 'Run Docker cleanup',
|
||||
description: 'Dispatch a manual Docker cleanup job for a server owned by the authenticated team.',
|
||||
path: '/servers/{uuid}/docker-cleanup/run',
|
||||
operationId: 'run-server-docker-cleanup',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Servers'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
requestBody: new OA\RequestBody(
|
||||
required: false,
|
||||
content: new OA\JsonContent(
|
||||
properties: [
|
||||
new OA\Property(property: 'delete_unused_volumes', type: 'boolean'),
|
||||
new OA\Property(property: 'delete_unused_networks', type: 'boolean'),
|
||||
],
|
||||
type: 'object',
|
||||
),
|
||||
),
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 200,
|
||||
description: 'Docker cleanup job dispatched.',
|
||||
content: new OA\JsonContent(
|
||||
properties: [
|
||||
new OA\Property(property: 'message', type: 'string', example: 'Manual cleanup job started.'),
|
||||
],
|
||||
type: 'object',
|
||||
),
|
||||
),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
new OA\Response(response: 422, ref: '#/components/responses/422'),
|
||||
],
|
||||
)]
|
||||
public function run(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$server = $this->findServerForTeam($teamId, $request->uuid);
|
||||
if (! $server) {
|
||||
return response()->json(['message' => 'Server not found.'], 404);
|
||||
}
|
||||
|
||||
$this->authorize('update', $server);
|
||||
|
||||
$validator = customApiValidator($request->all(), [
|
||||
'delete_unused_volumes' => 'boolean',
|
||||
'delete_unused_networks' => 'boolean',
|
||||
]);
|
||||
$extraFields = array_diff(array_keys($request->all()), ['delete_unused_volumes', 'delete_unused_networks']);
|
||||
if ($validator->fails() || ! empty($extraFields)) {
|
||||
$errors = $validator->errors();
|
||||
foreach ($extraFields as $field) {
|
||||
$errors->add($field, 'This field is not allowed.');
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Validation failed.',
|
||||
'errors' => $errors,
|
||||
], 422);
|
||||
}
|
||||
|
||||
$deleteUnusedVolumes = $request->has('delete_unused_volumes')
|
||||
? $request->boolean('delete_unused_volumes')
|
||||
: (bool) $server->settings->delete_unused_volumes;
|
||||
$deleteUnusedNetworks = $request->has('delete_unused_networks')
|
||||
? $request->boolean('delete_unused_networks')
|
||||
: (bool) $server->settings->delete_unused_networks;
|
||||
|
||||
DockerCleanupJob::dispatch($server, true, $deleteUnusedVolumes, $deleteUnusedNetworks);
|
||||
|
||||
auditLog('api.server.docker_cleanup.run', [
|
||||
'team_id' => $teamId,
|
||||
'server_uuid' => $server->uuid,
|
||||
'server_name' => $server->name,
|
||||
'delete_unused_volumes' => $deleteUnusedVolumes,
|
||||
'delete_unused_networks' => $deleteUnusedNetworks,
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Manual cleanup job started. Depending on the amount of data, this might take a while.',
|
||||
]);
|
||||
}
|
||||
|
||||
#[OA\Get(
|
||||
summary: 'List Docker cleanup executions',
|
||||
description: 'List recent Docker cleanup execution logs for a server owned by the authenticated team.',
|
||||
path: '/servers/{uuid}/docker-cleanup/executions',
|
||||
operationId: 'list-server-docker-cleanup-executions',
|
||||
security: [['bearerAuth' => []]],
|
||||
tags: ['Servers'],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
|
||||
],
|
||||
responses: [
|
||||
new OA\Response(
|
||||
response: 200,
|
||||
description: 'Recent Docker cleanup executions.',
|
||||
content: new OA\JsonContent(
|
||||
type: 'array',
|
||||
items: new OA\Items(
|
||||
properties: [
|
||||
new OA\Property(property: 'uuid', type: 'string'),
|
||||
new OA\Property(property: 'status', type: 'string'),
|
||||
new OA\Property(property: 'message', type: 'string', nullable: true),
|
||||
new OA\Property(property: 'finished_at', type: 'string', nullable: true),
|
||||
new OA\Property(property: 'created_at', type: 'string'),
|
||||
new OA\Property(property: 'updated_at', type: 'string'),
|
||||
],
|
||||
type: 'object',
|
||||
),
|
||||
),
|
||||
),
|
||||
new OA\Response(response: 401, ref: '#/components/responses/401'),
|
||||
new OA\Response(response: 400, ref: '#/components/responses/400'),
|
||||
new OA\Response(response: 404, ref: '#/components/responses/404'),
|
||||
],
|
||||
)]
|
||||
public function executions(Request $request): JsonResponse
|
||||
{
|
||||
$teamId = getTeamIdFromToken();
|
||||
if (is_null($teamId)) {
|
||||
return invalidTokenResponse();
|
||||
}
|
||||
|
||||
$server = $this->findServerForTeam($teamId, $request->uuid);
|
||||
if (! $server) {
|
||||
return response()->json(['message' => 'Server not found.'], 404);
|
||||
}
|
||||
|
||||
$this->authorize('view', $server);
|
||||
|
||||
$executions = $server->dockerCleanupExecutions()
|
||||
->orderBy('created_at', 'desc')
|
||||
->take(20)
|
||||
->get()
|
||||
->map(fn ($execution) => [
|
||||
'uuid' => $execution->uuid,
|
||||
'status' => $execution->status,
|
||||
'message' => $execution->message,
|
||||
'finished_at' => $execution->finished_at,
|
||||
'created_at' => $execution->created_at,
|
||||
'updated_at' => $execution->updated_at,
|
||||
])
|
||||
->values();
|
||||
|
||||
return response()->json($executions);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user