Compare commits
49
Commits
62be7af0c3
...
v1.3.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab4ccbd7a1 | ||
|
|
b2dbb4ad98 | ||
|
|
3f6f402872 | ||
|
|
9c00b268dc | ||
|
|
a185b3a2cb | ||
|
|
ed4d6f8a46 | ||
|
|
597017b625 | ||
|
|
7cd86fcda1 | ||
|
|
ce8393e0c3 | ||
|
|
3fb8480f8a | ||
|
|
721332e767 | ||
|
|
ec70104085 | ||
|
|
c01c75116a | ||
|
|
19620c0803 | ||
|
|
60da2b9032 | ||
|
|
3e4cacab42 | ||
|
|
859ad23006 | ||
|
|
30447d8380 | ||
|
|
c9eee6fdcb | ||
|
|
2b3c48cdde | ||
|
|
32248d88a4 | ||
|
|
278a6b64b4 | ||
|
|
56f2ed78e5 | ||
|
|
1d497d01c2 | ||
|
|
9783974949 | ||
|
|
a58d91ff5e | ||
|
|
9d8c2aff86 | ||
|
|
f1767b8a1f | ||
|
|
0a4293b735 | ||
|
|
e748c875bc | ||
|
|
6a6cb34eeb | ||
|
|
60e15ca40a | ||
|
|
1893778e3a | ||
|
|
76a58beb7e | ||
|
|
13c079c969 | ||
|
|
cd616c7a03 | ||
|
|
733c041482 | ||
|
|
d8340e8a0b | ||
|
|
704624cbe7 | ||
|
|
6c379f339b | ||
|
|
c6fa3428e6 | ||
|
|
a4fd955c1b | ||
|
|
52edc3ba73 | ||
|
|
57ee231417 | ||
|
|
c3ad676e75 | ||
|
|
a15b52df95 | ||
|
|
1e8236298d | ||
|
|
af191dcd5b | ||
|
|
b4daa76696 |
No files matched your search
@@ -1,17 +1,17 @@
|
||||
---
|
||||
name: reui
|
||||
description: Use the ReUI registry from your AI agent - find, install, and correctly use ReUI components (the 17 free building blocks like data-grid, kanban, filters), their free examples, premium blocks, and Motion Icons. Applies in any project using ReUI, the @reui registry, REUI_LICENSE_KEY, or any shadcn project where the user asks for premium blocks, data grids, kanban boards, dashboards, or full pages. Pairs with the free ReUI MCP server for live, scored registry search and inline component APIs.
|
||||
description: Use the ReUI registry from your AI agent - find, install, and correctly use ReUI components (the 20 free building blocks like data-grid, kanban, filters), their free examples, premium blocks, and Motion Icons. Applies in any project using ReUI, the @reui registry, REUI_LICENSE_KEY, or any shadcn project where the user asks for premium blocks, data grids, kanban boards, dashboards, or full pages. Pairs with the free ReUI MCP server for live, scored registry search and inline component APIs.
|
||||
user-invocable: false
|
||||
allowed-tools: Bash(npx shadcn@latest *), Bash(pnpm dlx shadcn@latest *), Bash(bunx --bun shadcn@latest *)
|
||||
---
|
||||
|
||||
> **ReUI skill version `0e224b0281`.** If the ReUI MCP's `get_agent_skill` reports a newer `version`, re-run the ReUI installer (see `get_agent_skill` -> `install.recommended`) to update this skill. Cloud/tools-only agents have no local file and always read the latest - they can ignore this.
|
||||
> **ReUI skill version `668fb463eb`.** If the ReUI MCP's `get_agent_skill` reports a newer `version`, re-run the ReUI installer (see `get_agent_skill` -> `install.recommended`) to update this skill. Cloud/tools-only agents have no local file and always read the latest - they can ignore this.
|
||||
|
||||
# ReUI for Agents
|
||||
|
||||
ReUI is a shadcn-compatible registry. It ships four things you **reuse** - never redesign:
|
||||
|
||||
- **components** - the 17 ReUI building blocks with real APIs: `data-grid`, `kanban`, `filters`, `date-selector`, `tree`, `stepper`, ... (free)
|
||||
- **components** - the 20 ReUI building blocks with real APIs: `data-grid`, `kanban`, `filters`, `date-selector`, `tree`, `stepper`, ... (free)
|
||||
- **examples** - free `c-*` single-pattern use-cases of a component (`c-kanban-1`); install one and read it to see exact composition
|
||||
- **blocks** - premium full-page sections that compose components (`data-grid-2`, `pricing-page-1`); Pro or Ultimate license at install
|
||||
- **icons** - Motion Icons in 4 styles, static + hover-animated variants; Ultimate license at install
|
||||
@@ -58,7 +58,7 @@ Invocation differs slightly per agent (`/mcp__reui__build` in Claude Code/Cursor
|
||||
|
||||
- [rules/registry.md](./rules/registry.md) - the four types, the @reui registry, base/radix, free vs premium + license
|
||||
- [rules/workflow.md](./rules/workflow.md) - the find -> install -> read-API -> adapt loop (most important)
|
||||
- [rules/components.md](./rules/components.md) - the 17 components, the data-grid contract, base vs radix
|
||||
- [rules/components.md](./rules/components.md) - the 20 components, the data-grid contract, base vs radix
|
||||
- [rules/adapting.md](./rules/adapting.md) - reuse-first: preserve the design (no over-customizing), reuse examples + a block's own elements, real data, don't invent APIs
|
||||
- [rules/craft.md](./rules/craft.md) - make it exceptional: point of view, hierarchy, density, states, responsive, motion, the bar
|
||||
- [rules/quality.md](./rules/quality.md) - security, accessibility, and scroll gates (the done gate)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Registry setup (one-time, per project)
|
||||
|
||||
Free items (the 17 components and all `c-*` examples) need only the plain string registry in `components.json`:
|
||||
Free items (the 20 components and all `c-*` examples) need only the plain string registry in `components.json`:
|
||||
|
||||
```json
|
||||
{ "registries": { "@reui": "https://reui.io/r/{style}/{name}.json" } }
|
||||
@@ -29,6 +29,8 @@ REUI_LICENSE_KEY=your-license-key
|
||||
}
|
||||
```
|
||||
|
||||
The shadcn CLI expands `${REUI_LICENSE_KEY}` from `.env.local` inside `components.json`, but an MCP client config never expands variables, so a ReUI MCP server config must carry the raw token instead (for example `reui_pat_your_token_here`).
|
||||
|
||||
The MCP `get_project_context` tool returns the right config. Full guide: https://reui.io/docs/registry
|
||||
|
||||
## Installing
|
||||
@@ -52,7 +54,7 @@ bunx --bun shadcn@latest add @reui/<name> --yes # bun
|
||||
|
||||
## Free vs premium boundary
|
||||
|
||||
- Public, no key: `c-*` examples and the 17 components (`@reui/data-grid`, `@reui/badge`, ...) that those examples depend on.
|
||||
- Public, no key: `c-*` examples and the 20 components (`@reui/data-grid`, `@reui/badge`, ...) that those examples depend on.
|
||||
- Key required at install: blocks (`@reui/<category>-N`) need a Pro or Ultimate license; Motion Icons (`@reui/icons/...`) and templates need Ultimate.
|
||||
|
||||
If an install 401/403s, the license key is missing, invalid, or the plan does not cover that resource (blocks: Pro or higher; icons and templates: Ultimate). Point the user to https://reui.io/account (their key) or https://reui.io/pricing (upgrade).
|
||||
@@ -1,24 +1,23 @@
|
||||
# ReUI components
|
||||
|
||||
The 17 ReUI building blocks: `alert`, `autocomplete`, `badge`, `data-grid`, `date-selector`, `filters`, `frame`, `icon-stack`, `kanban`, `number-field`, `phone-input`, `rating`, `scrollspy`, `sortable`, `stepper`, `timeline`, `tree`. Examples and blocks are composed from these.
|
||||
The 20 ReUI building blocks: `alert`, `autocomplete`, `badge`, `data-grid`, `date-selector`, `event-calendar`, `filters`, `frame`, `gantt`, `icon-stack`, `icon-tile`, `kanban`, `number-field`, `phone-input`, `rating`, `scrollspy`, `sortable`, `stepper`, `timeline`, `tree`. Examples and blocks are composed from these.
|
||||
|
||||
**Rule one: never guess a component's API. Read it first.** Call **`get_component(name)`** for its inline `api` (props + usage, no web fetch), and **share the result's `docsUrl`** (the component's API documentation page) with the user whenever you work with that component's API, so they have the full reference (the `/llms.txt` index is a further fallback). Then call **`get_examples(name)`** to install a worked example and copy real composition. The contracts below are first-try orientation (required props, composition shape, the one gotcha); the inline `api` is the full reference. No single block fits? Compose: search the components you need, read each `get_component`, install a `get_examples` example per component, and adapt.
|
||||
|
||||
## data-grid (the flagship - read its API every time)
|
||||
|
||||
`data-grid` wraps TanStack Table v8. It is NOT a styled `<table>` and does NOT take `data`/`columns` props directly. The contract:
|
||||
`data-grid` wraps TanStack Table v9. It is NOT a styled `<table>` and does NOT take `data`/`columns` props directly. The contract:
|
||||
|
||||
- Build a TanStack table instance with `useReactTable(...)` (columns, data, the feature models you need: sorting, pagination, row selection).
|
||||
- Build a TanStack table instance with `useTable({ features: dataGridFeatures, ... })` (columns, data). `dataGridFeatures` is exported by the primitive and already bundles sorting, filtering, pagination, row selection, expanding, pinning, resizing and faceting, so there are no per-table row models to wire.
|
||||
- Pass that instance to `<DataGrid table={table} recordCount={total}>`.
|
||||
- Compose the body with `DataGridTable` inside `DataGrid`, and enable features through `tableLayout` (e.g. `{ headerSticky: true, columnsResizable: true }`), not ad-hoc classes.
|
||||
- Server-side data uses the documented fetch shape (`recordCount` is the total for pagination).
|
||||
|
||||
```tsx
|
||||
const table = useReactTable({
|
||||
const table = useTable({
|
||||
features: dataGridFeatures,
|
||||
data,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
// add sorting/pagination/selection models per the API
|
||||
})
|
||||
|
||||
<DataGrid table={table} recordCount={data.length}>
|
||||
@@ -28,9 +27,37 @@ const table = useReactTable({
|
||||
|
||||
Common mistakes:
|
||||
|
||||
- **Incorrect:** `<DataGrid data={rows} columns={cols} />` - these props do not exist. **Correct:** build a `useReactTable` instance and pass `table={table}` + `recordCount`.
|
||||
- **Incorrect:** `<DataGrid data={rows} columns={cols} />` - these props do not exist. **Correct:** build a `useTable({ features: dataGridFeatures, ... })` instance and pass `table={table}` + `recordCount`.
|
||||
- **Incorrect:** a raw `<table>` / hand-rolled pagination. **Correct:** use `data-grid`; read its API for sticky header, pagination, virtualization, row selection.
|
||||
- **Incorrect:** styling rows/cells with arbitrary classes. **Correct:** drive layout via `tableLayout` and the documented `ColumnMeta` (e.g. `cellClassName`, `headerTitle`).
|
||||
- **Incorrect:** styling rows/cells with arbitrary classes. **Correct:** drive layout via `tableLayout` and the primitive's `DataGridColumnMeta` (e.g. `cellClassName`, `headerTitle`), set through the bundle's `columnMeta` slot.
|
||||
|
||||
## event-calendar
|
||||
|
||||
**Required:** events via `events`/`onEventsChange` (controlled) or `defaultEvents` (uncontrolled), plus a height on the root.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<EventCalendar defaultEvents={events} defaultView="month" className="h-[560px]">
|
||||
<EventCalendarNav />
|
||||
<EventCalendarContent />
|
||||
</EventCalendar>
|
||||
```
|
||||
|
||||
**Gotcha:** headless-first: `EventCalendarContent` renders the active view (month/week/day/days/agenda; a resource view activates when `resources` is passed) - there is no per-view JSX to compose. Events are `{ id, title, start, end (exclusive), allDay?, color?, recurrence?, resourceId? }`. Mutations flow through `onEventUpdate`/`canDropEvent` (return `false` to reject); the root needs an explicit height because it is a min-h-0 flex column.
|
||||
|
||||
## gantt
|
||||
|
||||
**Required:** `resources` (the left tree) plus bars via `events`/`defaultEvents` attached by `resourceId`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Gantt defaultEvents={bars} resources={tasks} defaultScale="month" className="h-[480px]">
|
||||
<GanttNav />
|
||||
<GanttView />
|
||||
</Gantt>
|
||||
```
|
||||
|
||||
**Gotcha:** bars move along the time axis only (never across rows) and are all-day spans with exclusive `end`; `progress` is 0-100. Scales are `day | week | month | quarter | year`. Zoom control, infinite scroll, summary rollups, and row checkboxes are ON by default - turn off what you do not need. Same `onEventUpdate`/`canDropEvent` commit pipeline as `event-calendar`; the root needs an explicit height.
|
||||
|
||||
## kanban
|
||||
|
||||
@@ -284,6 +311,19 @@ const [value, setValue] = useState<DateSelectorValue | undefined>()
|
||||
|
||||
**Gotcha:** isometric layered artwork for empty states and illustrations; style the inner icon via its own `className`. Mark purely decorative stacks `aria-hidden="true"` and keep the real label in surrounding copy.
|
||||
|
||||
## icon-tile
|
||||
|
||||
**Required:** one child icon
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<IconTile variant="elevated" size="lg">
|
||||
<PackageIcon />
|
||||
</IconTile>
|
||||
```
|
||||
|
||||
**Gotcha:** the square container an icon sits in, so every list row, feature card and empty state shares one affordance. `variant`: `outline` (default) | `elevated` (muted fill, raised ring) | `soft` (tinted nested, tone from currentColor) | `solid` (filled tone, contrasting glyph) | `frame` (double container). `soft` and `solid` retint from one text color class (they default to `text-primary`). `size`: `xs | sm | default | lg | xl` (24/32/40/48/64px tile, glyph scales 12/14/16/20/24px). `radius`: `default | full`. Do not set a `size-*` class on the child icon unless you mean to override the tile's glyph size; recolor with `className` on the tile, not the icon.
|
||||
|
||||
## alert
|
||||
|
||||
**Required:** `Alert` > `AlertTitle`
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
ReUI is a shadcn-compatible registry with four entity types. **Examples and blocks are built FROM components** - reuse them, don't rebuild.
|
||||
|
||||
- **component** - one of the 17 ReUI building blocks with a real API (`data-grid`, `kanban`, `filters`, `date-selector`, `tree`, ...). Install directly (`@reui/data-grid`) or let it come in as a dependency of an example/block. Free. Read its API with `get_component(name)`.
|
||||
- **component** - one of the 20 ReUI building blocks with a real API (`data-grid`, `kanban`, `filters`, `date-selector`, `tree`, ...). Install directly (`@reui/data-grid`) or let it come in as a dependency of an example/block. Free. Read its API with `get_component(name)`.
|
||||
- **example** - a free `c-*` single-pattern use-case of a component (`c-kanban-1`, `c-data-grid-3`). Install one and read it to copy real composition. Find a component's examples with `get_examples(name)`.
|
||||
- **block** - a premium, full-page section that composes several components (`data-grid-2`, `pricing-page-1`). Pro or Ultimate license at install. Adapts to your active theme via semantic tokens.
|
||||
- **icon** - Motion Icons in 4 styles (outline, solid, duotone, filled), static (`@reui/icons/default/<style>/<name>`) and hover-animated (`@reui/icons/animated/<style>/<name>`). Ultimate license at install. See [icons.md](./icons.md).
|
||||
@@ -27,7 +27,7 @@ Blocks adapt to your active theme through semantic tokens and CSS variables - ch
|
||||
|
||||
## Free vs premium
|
||||
|
||||
- **Free, no key:** the 17 components, all `c-*` examples, the ReUI MCP, and this skill.
|
||||
- **Free, no key:** the 20 components, all `c-*` examples, the ReUI MCP, and this skill.
|
||||
- **Premium, license required at install:** blocks (Pro or Ultimate), Motion Icons and templates (Ultimate). Set `REUI_LICENSE_KEY` (see [cli.md](./cli.md)).
|
||||
|
||||
## Component API index
|
||||
|
||||
@@ -8,7 +8,7 @@ The core ReUI loop. The MCP tells you what to install and gives you the API; the
|
||||
|
||||
For everything else, call `search` with the user's intent. Pass structured hints whenever you can infer them - you are an LLM, so do the parsing the server cannot:
|
||||
|
||||
- `type`: `"component"` (one of the 17 building blocks), `"example"` (a c-\* use-case), `"block"` (a full page/section), `"icon"`.
|
||||
- `type`: `"component"` (one of the 20 building blocks), `"example"` (a c-\* use-case), `"block"` (a full page/section), `"icon"`.
|
||||
- `component`: the ReUI component the request implies (`"data-grid"`, `"kanban"`, ...).
|
||||
- `category`, `features` (e.g. `["sortable","pagination"]`), `free`.
|
||||
|
||||
@@ -40,7 +40,7 @@ Before writing code against any component an item uses:
|
||||
|
||||
Installing files is not the end, and redesigning them defeats the point. First note the project's **base** so you write the right API - read `components.json` -> `style` and take the segment before the first `-` (`base-nova` -> Base UI, `radix-nova` -> Radix UI), see [components.md](./components.md). After `add`:
|
||||
|
||||
1. **Read the added files**; keep the composition intact. For a block, verify the components are wired correctly (for `data-grid`: a `useReactTable` instance passed as `table`, `recordCount` set - see [components.md](./components.md)).
|
||||
1. **Read the added files**; keep the composition intact. For a block, verify the components are wired correctly (for `data-grid`: a `useTable({ features: dataGridFeatures, ... })` instance passed as `table`, `recordCount` set - see [components.md](./components.md)).
|
||||
2. **Replace demo data with the user's real data** via typed structures (see [adapting.md](./adapting.md)).
|
||||
3. **Fix icon imports** to the project's icon library (see [icons.md](./icons.md)).
|
||||
4. **Align styling** to semantic tokens and the active theme - no raw colors (see [styling.md](./styling.md)).
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
---
|
||||
name: reui
|
||||
description: Use the ReUI registry from your AI agent - find, install, and correctly use ReUI components (the 17 free building blocks like data-grid, kanban, filters), their free examples, premium blocks, and Motion Icons. Applies in any project using ReUI, the @reui registry, REUI_LICENSE_KEY, or any shadcn project where the user asks for premium blocks, data grids, kanban boards, dashboards, or full pages. Pairs with the free ReUI MCP server for live, scored registry search and inline component APIs.
|
||||
description: Use the ReUI registry from your AI agent - find, install, and correctly use ReUI components (the 20 free building blocks like data-grid, kanban, filters), their free examples, premium blocks, and Motion Icons. Applies in any project using ReUI, the @reui registry, REUI_LICENSE_KEY, or any shadcn project where the user asks for premium blocks, data grids, kanban boards, dashboards, or full pages. Pairs with the free ReUI MCP server for live, scored registry search and inline component APIs.
|
||||
user-invocable: false
|
||||
allowed-tools: Bash(npx shadcn@latest *), Bash(pnpm dlx shadcn@latest *), Bash(bunx --bun shadcn@latest *)
|
||||
---
|
||||
|
||||
> **ReUI skill version `0e224b0281`.** If the ReUI MCP's `get_agent_skill` reports a newer `version`, re-run the ReUI installer (see `get_agent_skill` -> `install.recommended`) to update this skill. Cloud/tools-only agents have no local file and always read the latest - they can ignore this.
|
||||
> **ReUI skill version `668fb463eb`.** If the ReUI MCP's `get_agent_skill` reports a newer `version`, re-run the ReUI installer (see `get_agent_skill` -> `install.recommended`) to update this skill. Cloud/tools-only agents have no local file and always read the latest - they can ignore this.
|
||||
|
||||
# ReUI for Agents
|
||||
|
||||
ReUI is a shadcn-compatible registry. It ships four things you **reuse** - never redesign:
|
||||
|
||||
- **components** - the 17 ReUI building blocks with real APIs: `data-grid`, `kanban`, `filters`, `date-selector`, `tree`, `stepper`, ... (free)
|
||||
- **components** - the 20 ReUI building blocks with real APIs: `data-grid`, `kanban`, `filters`, `date-selector`, `tree`, `stepper`, ... (free)
|
||||
- **examples** - free `c-*` single-pattern use-cases of a component (`c-kanban-1`); install one and read it to see exact composition
|
||||
- **blocks** - premium full-page sections that compose components (`data-grid-2`, `pricing-page-1`); Pro or Ultimate license at install
|
||||
- **icons** - Motion Icons in 4 styles, static + hover-animated variants; Ultimate license at install
|
||||
@@ -58,7 +58,7 @@ Invocation differs slightly per agent (`/mcp__reui__build` in Claude Code/Cursor
|
||||
|
||||
- [rules/registry.md](./rules/registry.md) - the four types, the @reui registry, base/radix, free vs premium + license
|
||||
- [rules/workflow.md](./rules/workflow.md) - the find -> install -> read-API -> adapt loop (most important)
|
||||
- [rules/components.md](./rules/components.md) - the 17 components, the data-grid contract, base vs radix
|
||||
- [rules/components.md](./rules/components.md) - the 20 components, the data-grid contract, base vs radix
|
||||
- [rules/adapting.md](./rules/adapting.md) - reuse-first: preserve the design (no over-customizing), reuse examples + a block's own elements, real data, don't invent APIs
|
||||
- [rules/craft.md](./rules/craft.md) - make it exceptional: point of view, hierarchy, density, states, responsive, motion, the bar
|
||||
- [rules/quality.md](./rules/quality.md) - security, accessibility, and scroll gates (the done gate)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Registry setup (one-time, per project)
|
||||
|
||||
Free items (the 17 components and all `c-*` examples) need only the plain string registry in `components.json`:
|
||||
Free items (the 20 components and all `c-*` examples) need only the plain string registry in `components.json`:
|
||||
|
||||
```json
|
||||
{ "registries": { "@reui": "https://reui.io/r/{style}/{name}.json" } }
|
||||
@@ -29,6 +29,8 @@ REUI_LICENSE_KEY=your-license-key
|
||||
}
|
||||
```
|
||||
|
||||
The shadcn CLI expands `${REUI_LICENSE_KEY}` from `.env.local` inside `components.json`, but an MCP client config never expands variables, so a ReUI MCP server config must carry the raw token instead (for example `reui_pat_your_token_here`).
|
||||
|
||||
The MCP `get_project_context` tool returns the right config. Full guide: https://reui.io/docs/registry
|
||||
|
||||
## Installing
|
||||
@@ -52,7 +54,7 @@ bunx --bun shadcn@latest add @reui/<name> --yes # bun
|
||||
|
||||
## Free vs premium boundary
|
||||
|
||||
- Public, no key: `c-*` examples and the 17 components (`@reui/data-grid`, `@reui/badge`, ...) that those examples depend on.
|
||||
- Public, no key: `c-*` examples and the 20 components (`@reui/data-grid`, `@reui/badge`, ...) that those examples depend on.
|
||||
- Key required at install: blocks (`@reui/<category>-N`) need a Pro or Ultimate license; Motion Icons (`@reui/icons/...`) and templates need Ultimate.
|
||||
|
||||
If an install 401/403s, the license key is missing, invalid, or the plan does not cover that resource (blocks: Pro or higher; icons and templates: Ultimate). Point the user to https://reui.io/account (their key) or https://reui.io/pricing (upgrade).
|
||||
@@ -1,24 +1,23 @@
|
||||
# ReUI components
|
||||
|
||||
The 17 ReUI building blocks: `alert`, `autocomplete`, `badge`, `data-grid`, `date-selector`, `filters`, `frame`, `icon-stack`, `kanban`, `number-field`, `phone-input`, `rating`, `scrollspy`, `sortable`, `stepper`, `timeline`, `tree`. Examples and blocks are composed from these.
|
||||
The 20 ReUI building blocks: `alert`, `autocomplete`, `badge`, `data-grid`, `date-selector`, `event-calendar`, `filters`, `frame`, `gantt`, `icon-stack`, `icon-tile`, `kanban`, `number-field`, `phone-input`, `rating`, `scrollspy`, `sortable`, `stepper`, `timeline`, `tree`. Examples and blocks are composed from these.
|
||||
|
||||
**Rule one: never guess a component's API. Read it first.** Call **`get_component(name)`** for its inline `api` (props + usage, no web fetch), and **share the result's `docsUrl`** (the component's API documentation page) with the user whenever you work with that component's API, so they have the full reference (the `/llms.txt` index is a further fallback). Then call **`get_examples(name)`** to install a worked example and copy real composition. The contracts below are first-try orientation (required props, composition shape, the one gotcha); the inline `api` is the full reference. No single block fits? Compose: search the components you need, read each `get_component`, install a `get_examples` example per component, and adapt.
|
||||
|
||||
## data-grid (the flagship - read its API every time)
|
||||
|
||||
`data-grid` wraps TanStack Table v8. It is NOT a styled `<table>` and does NOT take `data`/`columns` props directly. The contract:
|
||||
`data-grid` wraps TanStack Table v9. It is NOT a styled `<table>` and does NOT take `data`/`columns` props directly. The contract:
|
||||
|
||||
- Build a TanStack table instance with `useReactTable(...)` (columns, data, the feature models you need: sorting, pagination, row selection).
|
||||
- Build a TanStack table instance with `useTable({ features: dataGridFeatures, ... })` (columns, data). `dataGridFeatures` is exported by the primitive and already bundles sorting, filtering, pagination, row selection, expanding, pinning, resizing and faceting, so there are no per-table row models to wire.
|
||||
- Pass that instance to `<DataGrid table={table} recordCount={total}>`.
|
||||
- Compose the body with `DataGridTable` inside `DataGrid`, and enable features through `tableLayout` (e.g. `{ headerSticky: true, columnsResizable: true }`), not ad-hoc classes.
|
||||
- Server-side data uses the documented fetch shape (`recordCount` is the total for pagination).
|
||||
|
||||
```tsx
|
||||
const table = useReactTable({
|
||||
const table = useTable({
|
||||
features: dataGridFeatures,
|
||||
data,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
// add sorting/pagination/selection models per the API
|
||||
})
|
||||
|
||||
<DataGrid table={table} recordCount={data.length}>
|
||||
@@ -28,9 +27,37 @@ const table = useReactTable({
|
||||
|
||||
Common mistakes:
|
||||
|
||||
- **Incorrect:** `<DataGrid data={rows} columns={cols} />` - these props do not exist. **Correct:** build a `useReactTable` instance and pass `table={table}` + `recordCount`.
|
||||
- **Incorrect:** `<DataGrid data={rows} columns={cols} />` - these props do not exist. **Correct:** build a `useTable({ features: dataGridFeatures, ... })` instance and pass `table={table}` + `recordCount`.
|
||||
- **Incorrect:** a raw `<table>` / hand-rolled pagination. **Correct:** use `data-grid`; read its API for sticky header, pagination, virtualization, row selection.
|
||||
- **Incorrect:** styling rows/cells with arbitrary classes. **Correct:** drive layout via `tableLayout` and the documented `ColumnMeta` (e.g. `cellClassName`, `headerTitle`).
|
||||
- **Incorrect:** styling rows/cells with arbitrary classes. **Correct:** drive layout via `tableLayout` and the primitive's `DataGridColumnMeta` (e.g. `cellClassName`, `headerTitle`), set through the bundle's `columnMeta` slot.
|
||||
|
||||
## event-calendar
|
||||
|
||||
**Required:** events via `events`/`onEventsChange` (controlled) or `defaultEvents` (uncontrolled), plus a height on the root.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<EventCalendar defaultEvents={events} defaultView="month" className="h-[560px]">
|
||||
<EventCalendarNav />
|
||||
<EventCalendarContent />
|
||||
</EventCalendar>
|
||||
```
|
||||
|
||||
**Gotcha:** headless-first: `EventCalendarContent` renders the active view (month/week/day/days/agenda; a resource view activates when `resources` is passed) - there is no per-view JSX to compose. Events are `{ id, title, start, end (exclusive), allDay?, color?, recurrence?, resourceId? }`. Mutations flow through `onEventUpdate`/`canDropEvent` (return `false` to reject); the root needs an explicit height because it is a min-h-0 flex column.
|
||||
|
||||
## gantt
|
||||
|
||||
**Required:** `resources` (the left tree) plus bars via `events`/`defaultEvents` attached by `resourceId`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Gantt defaultEvents={bars} resources={tasks} defaultScale="month" className="h-[480px]">
|
||||
<GanttNav />
|
||||
<GanttView />
|
||||
</Gantt>
|
||||
```
|
||||
|
||||
**Gotcha:** bars move along the time axis only (never across rows) and are all-day spans with exclusive `end`; `progress` is 0-100. Scales are `day | week | month | quarter | year`. Zoom control, infinite scroll, summary rollups, and row checkboxes are ON by default - turn off what you do not need. Same `onEventUpdate`/`canDropEvent` commit pipeline as `event-calendar`; the root needs an explicit height.
|
||||
|
||||
## kanban
|
||||
|
||||
@@ -284,6 +311,19 @@ const [value, setValue] = useState<DateSelectorValue | undefined>()
|
||||
|
||||
**Gotcha:** isometric layered artwork for empty states and illustrations; style the inner icon via its own `className`. Mark purely decorative stacks `aria-hidden="true"` and keep the real label in surrounding copy.
|
||||
|
||||
## icon-tile
|
||||
|
||||
**Required:** one child icon
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<IconTile variant="elevated" size="lg">
|
||||
<PackageIcon />
|
||||
</IconTile>
|
||||
```
|
||||
|
||||
**Gotcha:** the square container an icon sits in, so every list row, feature card and empty state shares one affordance. `variant`: `outline` (default) | `elevated` (muted fill, raised ring) | `soft` (tinted nested, tone from currentColor) | `solid` (filled tone, contrasting glyph) | `frame` (double container). `soft` and `solid` retint from one text color class (they default to `text-primary`). `size`: `xs | sm | default | lg | xl` (24/32/40/48/64px tile, glyph scales 12/14/16/20/24px). `radius`: `default | full`. Do not set a `size-*` class on the child icon unless you mean to override the tile's glyph size; recolor with `className` on the tile, not the icon.
|
||||
|
||||
## alert
|
||||
|
||||
**Required:** `Alert` > `AlertTitle`
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
ReUI is a shadcn-compatible registry with four entity types. **Examples and blocks are built FROM components** - reuse them, don't rebuild.
|
||||
|
||||
- **component** - one of the 17 ReUI building blocks with a real API (`data-grid`, `kanban`, `filters`, `date-selector`, `tree`, ...). Install directly (`@reui/data-grid`) or let it come in as a dependency of an example/block. Free. Read its API with `get_component(name)`.
|
||||
- **component** - one of the 20 ReUI building blocks with a real API (`data-grid`, `kanban`, `filters`, `date-selector`, `tree`, ...). Install directly (`@reui/data-grid`) or let it come in as a dependency of an example/block. Free. Read its API with `get_component(name)`.
|
||||
- **example** - a free `c-*` single-pattern use-case of a component (`c-kanban-1`, `c-data-grid-3`). Install one and read it to copy real composition. Find a component's examples with `get_examples(name)`.
|
||||
- **block** - a premium, full-page section that composes several components (`data-grid-2`, `pricing-page-1`). Pro or Ultimate license at install. Adapts to your active theme via semantic tokens.
|
||||
- **icon** - Motion Icons in 4 styles (outline, solid, duotone, filled), static (`@reui/icons/default/<style>/<name>`) and hover-animated (`@reui/icons/animated/<style>/<name>`). Ultimate license at install. See [icons.md](./icons.md).
|
||||
@@ -27,7 +27,7 @@ Blocks adapt to your active theme through semantic tokens and CSS variables - ch
|
||||
|
||||
## Free vs premium
|
||||
|
||||
- **Free, no key:** the 17 components, all `c-*` examples, the ReUI MCP, and this skill.
|
||||
- **Free, no key:** the 20 components, all `c-*` examples, the ReUI MCP, and this skill.
|
||||
- **Premium, license required at install:** blocks (Pro or Ultimate), Motion Icons and templates (Ultimate). Set `REUI_LICENSE_KEY` (see [cli.md](./cli.md)).
|
||||
|
||||
## Component API index
|
||||
|
||||
@@ -8,7 +8,7 @@ The core ReUI loop. The MCP tells you what to install and gives you the API; the
|
||||
|
||||
For everything else, call `search` with the user's intent. Pass structured hints whenever you can infer them - you are an LLM, so do the parsing the server cannot:
|
||||
|
||||
- `type`: `"component"` (one of the 17 building blocks), `"example"` (a c-\* use-case), `"block"` (a full page/section), `"icon"`.
|
||||
- `type`: `"component"` (one of the 20 building blocks), `"example"` (a c-\* use-case), `"block"` (a full page/section), `"icon"`.
|
||||
- `component`: the ReUI component the request implies (`"data-grid"`, `"kanban"`, ...).
|
||||
- `category`, `features` (e.g. `["sortable","pagination"]`), `free`.
|
||||
|
||||
@@ -40,7 +40,7 @@ Before writing code against any component an item uses:
|
||||
|
||||
Installing files is not the end, and redesigning them defeats the point. First note the project's **base** so you write the right API - read `components.json` -> `style` and take the segment before the first `-` (`base-nova` -> Base UI, `radix-nova` -> Radix UI), see [components.md](./components.md). After `add`:
|
||||
|
||||
1. **Read the added files**; keep the composition intact. For a block, verify the components are wired correctly (for `data-grid`: a `useReactTable` instance passed as `table`, `recordCount` set - see [components.md](./components.md)).
|
||||
1. **Read the added files**; keep the composition intact. For a block, verify the components are wired correctly (for `data-grid`: a `useTable({ features: dataGridFeatures, ... })` instance passed as `table`, `recordCount` set - see [components.md](./components.md)).
|
||||
2. **Replace demo data with the user's real data** via typed structures (see [adapting.md](./adapting.md)).
|
||||
3. **Fix icon imports** to the project's icon library (see [icons.md](./icons.md)).
|
||||
4. **Align styling** to semantic tokens and the active theme - no raw colors (see [styling.md](./styling.md)).
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"pid": 47044,
|
||||
"version": "0.9.9",
|
||||
"socketPath": "\\\\.\\pipe\\codegraph-7bcc7a2b16d00925",
|
||||
"startedAt": 1784215894915
|
||||
}
|
||||
File renamed without changes.
@@ -20,13 +20,14 @@ Fastify backend: `apps/api/`. Контракты — `@cfdm/shared` (Zod). Front
|
||||
- Дублирование Zod schemas в `apps/web` — только re-export из `@cfdm/shared`
|
||||
- Самописные формы без `Field` + RHF + Zod
|
||||
|
||||
## shadcn-паттерны
|
||||
## UI-паттерны (ReUI Frame)
|
||||
|
||||
| API-данные | UI |
|
||||
|------------|-----|
|
||||
| Список | `Table` / `DataTableCard` |
|
||||
| Создание | `Card` + `FieldGroup` + RHF |
|
||||
| Статус | `Badge` variants |
|
||||
| Список | `ResourcePage` (Frame + DataGrid + Filters) |
|
||||
| Создание / редактирование | `FormSheet` + `FieldGroup` + RHF |
|
||||
| Settings | `SettingsShell` + Frame + `SettingRow` |
|
||||
| Статус | ReUI `Badge` / `StatusBadge` |
|
||||
| Ошибка | `sonner` `toast.error` |
|
||||
|
||||
## Согласованность
|
||||
|
||||
@@ -1,183 +1,102 @@
|
||||
---
|
||||
description: Frontend — ТОЛЬКО shadcn/ui docs (Components, Blocks, Installation); best practices, CLI-first
|
||||
description: Frontend — shadcn primitives + ReUI PRO blocks; CLI-first; kit patterns
|
||||
globs: apps/web/**/*,packages/ui/**/*
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Frontend — shadcn/ui (обязательно)
|
||||
# Frontend — shadcn/ui + ReUI PRO
|
||||
|
||||
**Источник истины — MCP shadcn + официальная документация.** Не выдумывать UI, не писать кастомный CSS, не обходить MCP и CLI.
|
||||
**Источник истины:** MCP **`user-reui`** (pages/blocks/KPI/settings) + MCP `plugin-shadcn-shadcn` (primitives) + docs. Не выдумывать UI.
|
||||
|
||||
Monorepo layout — [`frontend-monorepo.mdc`](frontend-monorepo.mdc). MCP workflow — [`shadcn-mcp.mdc`](shadcn-mcp.mdc). UI patterns — [`frontend-ui-patterns.mdc`](frontend-ui-patterns.mdc).
|
||||
Monorepo — [`frontend-monorepo.mdc`](frontend-monorepo.mdc). ReUI — [`reui-mcp.mdc`](reui-mcp.mdc). Patterns — [`frontend-ui-patterns.mdc`](frontend-ui-patterns.mdc).
|
||||
|
||||
| Документ | URL |
|
||||
|----------|-----|
|
||||
| **Components (primary catalog)** | https://ui.shadcn.com/docs/components |
|
||||
| **Blocks** | https://ui.shadcn.com/blocks |
|
||||
| **shadcn Components** | https://ui.shadcn.com/docs/components |
|
||||
| **ReUI Blocks** | https://reui.io/blocks |
|
||||
| **ReUI llms.txt** | https://reui.io/llms.txt |
|
||||
| **ReUI Settings** | https://reui.io/blocks/application/settings |
|
||||
| **Installation** | https://ui.shadcn.com/docs/installation |
|
||||
| **Monorepo** | https://ui.shadcn.com/docs/monorepo |
|
||||
| **Theming** | https://ui.shadcn.com/docs/theming |
|
||||
| **Dark Mode** | https://ui.shadcn.com/docs/dark-mode |
|
||||
| **Forms (RHF)** | https://ui.shadcn.com/docs/forms/react-hook-form |
|
||||
|
||||
## Шаг 0 — перед любым UI-кодом
|
||||
|
||||
0. **Codegraph** `codegraph_explore` — найти существующие реализации
|
||||
1. **MCP `plugin-shadcn-shadcn`:** `search_items_in_registries` → `get_item_examples_from_registries` → `get_add_command_for_items` ([`shadcn-mcp.mdc`](shadcn-mcp.mdc))
|
||||
2. Открыть **Components** или **Blocks** — найти готовое решение
|
||||
3. `cd apps/web && pnpm dlx shadcn@latest docs <component>` — сверить API с [Components](https://ui.shadcn.com/docs/components)
|
||||
4. Сверить MCP examples ↔ docs API — только потом писать код
|
||||
5. `cd apps/web && pnpm dlx shadcn@latest search "@shadcn/<query>"` — если MCP не дал результат
|
||||
0. Найти существующие `reui-kit/*` / shared
|
||||
1. **Pages / KPI / settings / enterprise** → MCP `user-reui` (`search` → `get_block` / `compose_page`) + cite `previewUrl`
|
||||
2. **Primitives** → MCP `plugin-shadcn-shadcn` + `pnpm dlx shadcn@latest docs <component>`
|
||||
3. CLI add из `apps/web` → adapt
|
||||
|
||||
**Новая страница** → сначала [Blocks](https://ui.shadcn.com/blocks), потом `pnpm dlx shadcn@latest add <block-id>`.
|
||||
**Новая страница** → сначала ReUI PRO `compose_page` / blocks ([reui.io/blocks](https://reui.io/blocks)), не ui.shadcn.com/blocks как primary.
|
||||
|
||||
## Docs workflow
|
||||
|
||||
1. MCP `plugin-shadcn-shadcn` — search → examples → add command
|
||||
2. `pnpm dlx shadcn@latest docs <component>` — fetch URLs, сверить API
|
||||
3. Skill `.agents/skills/shadcn/SKILL.md` — critical rules
|
||||
4. Context7 — только TanStack / Recharts
|
||||
|
||||
## Shared components (обязательно)
|
||||
## Shared / kit (обязательно)
|
||||
|
||||
| Component | Файл |
|
||||
|-----------|------|
|
||||
| `PageShell` | `page-shell.tsx` |
|
||||
| `PageHeader` | `page-header.tsx` |
|
||||
| `ResourcePage` | `reui-kit/resource-page.tsx` |
|
||||
| `OpsDashboard` / `KpiStatGrid` / `QuickActionGrid` | `reui-kit/ops-dashboard.tsx`, `kpi-stat-grid.tsx`, `quick-action-grid.tsx` |
|
||||
| `KanbanBoard` | `reui-kit/kanban-board.tsx` |
|
||||
| `DetailPanel` | `reui-kit/detail-panel.tsx` |
|
||||
| `SettingsShell` | `reui-kit/settings-shell.tsx` |
|
||||
| `EmptyState` | `empty-state.tsx` |
|
||||
| `QueryState` | `query-state.tsx` |
|
||||
| `ConfirmDialog` | `confirm-dialog.tsx` |
|
||||
| `DataGridCard` | `data-grid-card.tsx` |
|
||||
| `SectionCards` | `section-cards.tsx` |
|
||||
| `StatusBadge` | `status-badge.tsx` |
|
||||
| `FormSheet` | `form-sheet.tsx` |
|
||||
| `FormField` | `form-field.tsx` |
|
||||
| `TableCard` | `table-card.tsx` |
|
||||
| `LoadingButton` | `loading-button.tsx` |
|
||||
| `SectionCardsSkeleton` / `TableSkeleton` | `skeletons.tsx` |
|
||||
| `SettingRow` | `setting-row.tsx` |
|
||||
|
||||
**Не использовать как эталон:** устаревшие `PageHeader` / `SectionCards` / `DataGridCard` / `TableCard` (если удалены или мёртвы).
|
||||
|
||||
**Overlay:** Sheet — forms; AlertDialog — destructive confirm.
|
||||
|
||||
## Шаг 1 — CLI (обязательно)
|
||||
## Шаг 1 — CLI
|
||||
|
||||
```bash
|
||||
cd apps/web
|
||||
pnpm dlx shadcn@latest add table select badge card field input button ...
|
||||
pnpm dlx shadcn@latest add sidebar-07 # layout
|
||||
pnpm dlx shadcn@latest add dashboard-01 # dashboard
|
||||
pnpm dlx shadcn@latest add login-03 # auth
|
||||
pnpm dlx shadcn@latest apply b2fA --only theme -y # тема — ТОЛЬКО так
|
||||
pnpm dlx shadcn@latest add button field input ...
|
||||
pnpm dlx shadcn@latest add @reui/frame @reui/data-grid @reui/filters
|
||||
pnpm dlx shadcn@latest add @reui/stats-12 @reui/card-35 @reui/settings-16 @reui/auth-13
|
||||
pnpm dlx shadcn@latest apply b2fA --only theme -y
|
||||
```
|
||||
|
||||
- Копипаст с сайта **без** CLI — запрещено
|
||||
- `packages/ui/src/components/*` — только registry; domain-логика → `apps/web/src/components/<name>.tsx`
|
||||
## Приоритет композиции
|
||||
|
||||
## Шаг 2 — композиция (best practices)
|
||||
1. `@cfdm/ui/components/*` (primitives)
|
||||
2. ReUI PRO block → adapt (`blocks/` reference + kit)
|
||||
3. `reui-kit/*` + shared
|
||||
4. Domain-обёртка
|
||||
|
||||
### Приоритет
|
||||
## Запрещено
|
||||
|
||||
1. Установленный `@cfdm/ui/components/*`
|
||||
2. Block из registry (адаптация под TanStack Router)
|
||||
3. Shared проекта: `PageShell`, `PageHeader`, `EmptyState`, `QueryState`, `ConfirmDialog`, `DataTableCard`, `SectionCards`, `StatusBadge`
|
||||
4. Domain-обёртка — последний уровень кастомизации
|
||||
|
||||
### Запрещено
|
||||
|
||||
| ❌ | ✅ из [Components](https://ui.shadcn.com/docs/components) |
|
||||
|----|-----------------------------------------------------------|
|
||||
| `<table>`, `<select>`, `<hr>` | `Table`, `Select`, `Separator` |
|
||||
| `bg-emerald-*`, `text-blue-500`, hex в className | `bg-primary`, `text-muted-foreground`, `Badge variant` |
|
||||
| Ручной `globals.css`, `.css` модули | CLI `apply b2fA --only theme` |
|
||||
| `space-y-*` / `space-x-*` | `flex` + `gap-*` |
|
||||
| `w-10 h-10` | `size-10` |
|
||||
| `className` для цветов Button/Badge | `variant`, `size` |
|
||||
| `useState` для полей формы | `FieldGroup` + RHF + Zod |
|
||||
| Styled `<Link>` | `Button variant="link"` + `render={<Link />}` |
|
||||
| `inline style={{}}` в routes | layout Tailwind |
|
||||
| `animate-pulse` div | `Skeleton` |
|
||||
| кастомный toast | `sonner` → `toast()` |
|
||||
| ❌ | ✅ |
|
||||
|----|-----|
|
||||
| `<table>`, raw select | DataGrid / `Select` |
|
||||
| `bg-emerald-*` | semantic / ReUI `variant` |
|
||||
| Card как ops-shell | ReUI `Frame` |
|
||||
| Hand-roll KPI | `KpiStatGrid` / [stats-12](https://reui.io/preview/base/stats-12) |
|
||||
| `space-y-*` | `flex` + `gap-*` |
|
||||
| `@/components/ui/*` | `@cfdm/ui/components/*` |
|
||||
|
||||
### Формы
|
||||
|
||||
По https://ui.shadcn.com/docs/forms/react-hook-form:
|
||||
|
||||
```tsx
|
||||
<FieldGroup>
|
||||
<Field data-invalid={!!errors.name}>
|
||||
<FieldLabel htmlFor="name">Имя</FieldLabel>
|
||||
<Input id="name" aria-invalid={!!errors.name} {...register('name')} />
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
```
|
||||
|
||||
### Card
|
||||
|
||||
`CardHeader` / `CardTitle` / `CardDescription` / `CardContent` / `CardFooter` — полная композиция из docs.
|
||||
|
||||
### Таблицы
|
||||
|
||||
`Table`, `TableHeader`, `TableBody`, `TableRow`, `TableHead`, `TableCell` — из docs.
|
||||
Сложная таблица → [Data Table](https://ui.shadcn.com/docs/components/data-table) + block `dashboard-01`.
|
||||
|
||||
### Графики
|
||||
|
||||
`Chart` + `ChartContainer` + `chartConfig` с `var(--chart-1)` — не raw recharts без обёртки.
|
||||
|
||||
### Иконки в Button
|
||||
|
||||
```tsx
|
||||
<Button>
|
||||
<PlusIcon data-icon="inline-start" />
|
||||
Создать
|
||||
</Button>
|
||||
```
|
||||
|
||||
Без `size-4` на иконке внутри shadcn-компонента.
|
||||
|
||||
## Стек (не shadcn, но обязателен)
|
||||
|
||||
TanStack Router + Query — [`vite-tanstack-frontend.mdc`](vite-tanstack-frontend.mdc).
|
||||
|
||||
- Preset: **base-nova** + **neutral** — [`apps/web/components.json`](apps/web/components.json), [`packages/ui/components.json`](packages/ui/components.json)
|
||||
- `@base-ui/react` → `render` prop (не Radix `asChild`)
|
||||
- **Не Next.js** — нет Server Components, `'use client'`
|
||||
|
||||
## Эталоны проекта
|
||||
|
||||
| Зона | Файл | Block |
|
||||
|------|------|-------|
|
||||
| Shell | `apps/web/src/components/layout/app-shell.tsx` | [sidebar-07](https://ui.shadcn.com/blocks) |
|
||||
| Login | `apps/web/src/routes/login.tsx` | [login-03](https://ui.shadcn.com/blocks) |
|
||||
| Dashboard | `apps/web/src/routes/_auth/index.tsx` | [dashboard-01](https://ui.shadcn.com/blocks) |
|
||||
| CRUD | `routes/_auth/services.tsx`, `domains/index.tsx` | Card + Field + Table |
|
||||
| Зона | Файл | Preview |
|
||||
|------|------|---------|
|
||||
| Shell | `layout/app-shell.tsx` | [app-shell-12](https://reui.io/preview/base/app-shell-12) |
|
||||
| Login | `routes/login.tsx` | [auth-13](https://reui.io/preview/base/auth-13) |
|
||||
| Dashboard | `routes/_auth/index.tsx` | [stats-12](https://reui.io/preview/base/stats-12) / dashboard-1 |
|
||||
| Lists | `ResourcePage` | [data-grid-filtering-2](https://reui.io/preview/base/data-grid-filtering-2) |
|
||||
| Settings | `settings/integrations.tsx` | [settings-16](https://reui.io/preview/base/settings-16) |
|
||||
|
||||
## Структура файлов
|
||||
## Чеклист
|
||||
|
||||
```
|
||||
apps/web/src/
|
||||
components/ ← domain + layout + shared (blocks)
|
||||
routes/ ← страницы (композиция @cfdm/ui, без raw HTML)
|
||||
queries/ ← queryOptions (не inline в routes)
|
||||
lib/schemas.ts ← Zod для форм
|
||||
|
||||
packages/ui/src/
|
||||
components/ ← только CLI (не трогать под кейс)
|
||||
hooks/ ← registry hooks (use-mobile)
|
||||
lib/utils.ts ← cn()
|
||||
styles/globals.css ← только output shadcn CLI
|
||||
```
|
||||
|
||||
## Чеклист перед завершением задачи
|
||||
|
||||
- [ ] MCP shadcn: search + examples (+ add command при новых примитивах)
|
||||
- [ ] Решение есть в https://ui.shadcn.com/docs/components или /blocks
|
||||
- [ ] Компоненты добавлены через `pnpm dlx shadcn@latest add` из `apps/web`
|
||||
- [ ] Нет кастомного CSS и raw HTML-примитивов
|
||||
- [ ] Semantic tokens, `variant`/`size` вместо переопределения className
|
||||
- [ ] UI-импорты через `@cfdm/ui/components/*`
|
||||
- [ ] `pnpm --filter web build` без ошибок
|
||||
- [ ] `user-reui` + preview/docs для зоны
|
||||
- [ ] Frame surface
|
||||
- [ ] CLI add при новых items
|
||||
- [ ] `pnpm --filter web build`
|
||||
|
||||
## Язык
|
||||
|
||||
Ответы пользователю — русский. Commits — [`commit-messages-ru.mdc`](commit-messages-ru.mdc).
|
||||
Ответы — русский. Commits — [`commit-messages-ru.mdc`](commit-messages-ru.mdc).
|
||||
@@ -10,19 +10,35 @@ alwaysApply: false
|
||||
|
||||
## Docs workflow (обязательно)
|
||||
|
||||
0. Codegraph `codegraph_explore` — найти существующие shared/domain-компоненты
|
||||
1. Skill [`.agents/skills/shadcn/SKILL.md`](../.agents/skills/shadcn/SKILL.md) + ReUI skill — component selection
|
||||
2. MCP `plugin-shadcn-shadcn` / `user-reui` — search → examples → add command (`surface: "frame"`)
|
||||
3. CLI: `cd apps/web && pnpm dlx shadcn@latest docs <component>` / `add @reui/...` → сверить API
|
||||
4. Код по examples + docs API (только после совпадения MCP ↔ docs)
|
||||
5. Context7 — **только** TanStack Router/Query, Recharts (не shadcn/ReUI primitives)
|
||||
6. MCP `get_audit_checklist` — перед merge
|
||||
7. Codegraph `codegraph_status` — Pending sync пустой
|
||||
0. Codegraph / поиск существующих shared/domain / `reui-kit`
|
||||
1. Skill ReUI + shadcn — component selection
|
||||
2. **Primary:** MCP `user-reui` — search → `get_block` / `compose_page` (`surface: "frame"`) — **всегда cite `previewUrl` + `docsUrl`**
|
||||
3. Primitives: MCP `plugin-shadcn-shadcn` + `pnpm dlx shadcn@latest docs <component>`
|
||||
4. CLI: `cd apps/web && pnpm dlx shadcn@latest add @reui/...` → сверить API
|
||||
5. Код по examples + docs (только после MCP ↔ docs)
|
||||
6. Context7 — **только** TanStack Router/Query, Recharts
|
||||
7. MCP `validate_usage` / `get_audit_checklist` — перед merge
|
||||
|
||||
## Surface
|
||||
|
||||
Проект использует **ReUI Frame** (`surface: frame`), не shadcn Card как оболочку list/ops-экранов. Эталон списка: [data-grid-filtering-2](https://reui.io/preview/base/data-grid-filtering-2).
|
||||
|
||||
## Обязательные референсы по зонам
|
||||
|
||||
| Зона | Preview |
|
||||
|------|---------|
|
||||
| KPI | [stats-12](https://reui.io/preview/base/stats-12) — EvoBGP hybrid SoT |
|
||||
| Quick Actions | [stats-12](https://reui.io/preview/base/stats-12) · [card-12](https://reui.io/preview/base/card-12) → `QuickActionGrid` |
|
||||
| List | [data-grid-filtering-2](https://reui.io/preview/base/data-grid-filtering-2) |
|
||||
| Settings | [settings-16](https://reui.io/preview/base/settings-16), [Application Settings](https://reui.io/blocks/application/settings) |
|
||||
| Settings rows / Health-check | [settings-2](https://reui.io/preview/base/settings-2), [settings-3](https://reui.io/preview/base/settings-3) |
|
||||
| Auth | [auth-13](https://reui.io/preview/base/auth-13) |
|
||||
| Empty | [empty-state-12](https://reui.io/preview/base/empty-state-12) |
|
||||
| Forms | [form-7](https://reui.io/preview/base/form-7) |
|
||||
| Shell | [app-shell-12](https://reui.io/preview/base/app-shell-12) |
|
||||
|
||||
**SettingRow:** `FieldSeparator` opt-in (`separated`); не между toggle-row и nested fields (Health-check). Settings-секции — отдельные Frame + `gap`, без hairline под PageHeader.
|
||||
|
||||
## Иерархия компонентов
|
||||
|
||||
```
|
||||
@@ -35,7 +51,7 @@ apps/web/src/components/ ← shared + domain + layout
|
||||
kanban-board.tsx ← kanban + KanbanBoardSkeleton
|
||||
detail-panel.tsx ← detail: Frame header/metrics
|
||||
settings-shell.tsx
|
||||
ops-dashboard.tsx ← KPI card-35 + charts
|
||||
ops-dashboard.tsx ← KPI stats-12 + charts
|
||||
catalog-board-toggle.tsx
|
||||
empty-state.tsx
|
||||
query-state.tsx
|
||||
@@ -58,7 +74,8 @@ apps/web/src/components/ ← shared + domain + layout
|
||||
| Kanban | `KanbanBoard` / `KanbanBoardSkeleton` | ReUI `kanban` + `Frame` |
|
||||
| Detail | `DetailPanel` | ReUI `Frame` |
|
||||
| Settings | `SettingsShell` | — |
|
||||
| Dashboard KPI | `OpsDashboard` / `KpiStatGrid` | ReUI Frame [card-35](https://reui.io/preview/base/card-35) |
|
||||
| Dashboard KPI | `OpsDashboard` / `KpiStatGrid` | ReUI Frame [stats-12](https://reui.io/preview/base/stats-12) hybrid |
|
||||
| Quick Actions | `QuickActionGrid` | Frame tiles + Badge «Перейти» |
|
||||
| Empty | `EmptyState` | `Empty` |
|
||||
| Loading / Error | `QueryState` / kit skeletons | `Skeleton`, `Alert` |
|
||||
| Status | `StatusBadge` | ReUI `Badge` (`success`/`info`/`warning`) |
|
||||
@@ -112,7 +129,7 @@ Toggle «Доска» / «К каталогу» — всегда `outline` в `p
|
||||
|
||||
## Dashboard KPI
|
||||
|
||||
Эталон: [card-35](https://reui.io/preview/base/card-35) — muted **label** + крупный **value** + optional **hint**; клик по карточке через `to` (`Link`), без отдельных hint-links.
|
||||
Эталон: [stats-12](https://reui.io/preview/base/stats-12) — icon tile + value + label + optional badge/footer; клик через `to` (`Link`) / `onSelect`. Compact strip: [card-35](https://reui.io/preview/base/card-35).
|
||||
|
||||
## Sidebar
|
||||
|
||||
@@ -134,13 +151,16 @@ Toggle «Доска» / «К каталогу» — всегда `outline` в `p
|
||||
| Shell | [app-shell-12](https://reui.io/preview/base/app-shell-12) |
|
||||
| List + tabs + filters | [data-grid-filtering-2](https://reui.io/preview/base/data-grid-filtering-2) |
|
||||
| Line tabs | [c-tabs-2](https://reui.io/preview/base/components/c-tabs-2) |
|
||||
| KPI | [card-35](https://reui.io/preview/base/card-35) |
|
||||
| Login | auth-13 / login-03 |
|
||||
| KPI | [stats-12](https://reui.io/preview/base/stats-12) — на dashboard, certificates, domains, groups, services |
|
||||
| Login | [auth-13](https://reui.io/preview/base/auth-13) |
|
||||
| Settings | [settings-16](https://reui.io/preview/base/settings-16) / [settings-6](https://reui.io/preview/base/settings-6) |
|
||||
| Empty | [empty-state-12](https://reui.io/preview/base/empty-state-12) |
|
||||
|
||||
## Spacing
|
||||
|
||||
```
|
||||
AppShell main: gap-4 md:gap-6, px-4 md:px-6, py-4 md:py-5
|
||||
(--sidebar-width: 240px; header h-12; AppSwitcher + AppsMenu — Shared App Shell chrome)
|
||||
PageShell: gap-4 md:gap-6
|
||||
Title/desc: gap-px
|
||||
Card/Frame grid: gap-4 (dashboard denser: gap-2 md:gap-3)
|
||||
@@ -150,6 +170,8 @@ Toolbar / header actions: gap-2
|
||||
Tabs list (line): gap-5
|
||||
```
|
||||
|
||||
Shared chrome (vps-tracker / CFDM / EvoBGP): см. [`docs/ui-design-contract.md`](../../docs/ui-design-contract.md) — секция **Shared App Shell chrome**. Preview: [app-shell-12](https://reui.io/preview/base/app-shell-12).
|
||||
|
||||
**Запрещено:** `space-y-*`, raw colors (`bg-emerald-*`), custom empty divs, page-level Spinner / plain «Загрузка…» без Skeleton.
|
||||
|
||||
## UX/UI (состояния данных)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
description: Только hybrid KPI — KpiStatGrid / row tile DNA (stats-12 + IconTile). Запрет SectionCards и hand-roll.
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# KPI hybrid — только kit (stats-12 + IconTile)
|
||||
|
||||
Preview: [stats-12](https://reui.io/preview/base/stats-12). Primitive: [icon-tile](https://reui.io/docs/components/base/icon-tile). SoT DNA = EvoBGP. Markup: `apps/web/src/components/reui-kit/kpi-stat-grid.tsx`.
|
||||
|
||||
Связанные: [`reui-mcp.mdc`](reui-mcp.mdc), [`frontend-ui-patterns.mdc`](frontend-ui-patterns.mdc).
|
||||
|
||||
## MUST
|
||||
|
||||
| Зона | Компонент / DNA |
|
||||
|------|-----------------|
|
||||
| KPI-полосы / dashboard metrics | только `reui-kit/KpiStatGrid` (через `OpsDashboard` / `DetailPanel.Metrics` при наличии) |
|
||||
| Markup | horizontal compact hybrid: icon left `IconTile` `variant="elevated"` `className="size-10.5"` + label/Badge + value ± `variant` |
|
||||
| Row icon tiles (data-grid) | та же DNA — semantic `text-*` на IconTile elevated |
|
||||
| Quick Actions | только `reui-kit/QuickActionGrid` (sibling hybrid DNA, IconTile elevated) |
|
||||
|
||||
Импорты UI: `@cfdm/ui/components/*`. IconTile: `@/components/reui/icon-tile`.
|
||||
|
||||
## NEVER
|
||||
|
||||
- SectionCards / vertical-only KPI / hand-roll Frame/Card KPI
|
||||
- `Item` `size-10.5` `bg-muted` hybrid вместо IconTile
|
||||
- Другой size / radius / solid brand fill вместо `elevated`
|
||||
- `card-35` как замена stats-12 hybrid KPI
|
||||
- Копипаст ReUI block в route — adapt через `reui-kit/`
|
||||
- Голый lucide `size-4` в name-cell без IconTile
|
||||
+86
-75
@@ -1,109 +1,120 @@
|
||||
---
|
||||
description: ReUI registry (@reui) — enterprise-компоненты, MCP workflow, зависимости, матрица выбора shadcn vs ReUI
|
||||
description: ReUI PRO (@reui) — MCP user-reui, Frame surface, kit, license, матрица выбора
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# ReUI MCP — обязательно для enterprise-компонентов
|
||||
# ReUI MCP — обязательно (PRO + free)
|
||||
|
||||
ReUI — first-class shadcn registry с enterprise-компонентами (Data Grid, Filters, Stepper и др.). Проект использует **Base UI** (`style: base-nova`), не Radix.
|
||||
Проект: **Base UI** (`style: base-nova`), surface lock **`frame`**.
|
||||
|
||||
Связанные правила: [`shadcn-mcp.mdc`](shadcn-mcp.mdc), [`frontend-monorepo.mdc`](frontend-monorepo.mdc), [`frontend-shadcn.mdc`](frontend-shadcn.mdc).
|
||||
Связанные: [`shadcn-mcp.mdc`](shadcn-mcp.mdc), [`frontend-monorepo.mdc`](frontend-monorepo.mdc), [`frontend-shadcn.mdc`](frontend-shadcn.mdc), [`frontend-ui-patterns.mdc`](frontend-ui-patterns.mdc).
|
||||
|
||||
| Документ | URL |
|
||||
|----------|-----|
|
||||
| **llms.txt (карта для ИИ)** | https://reui.io/llms.txt |
|
||||
| **Introduction** | https://reui.io/docs |
|
||||
| **llms.txt** | https://reui.io/llms.txt |
|
||||
| **Get Started** | https://reui.io/docs/get-started |
|
||||
| **Styling (semantic tokens)** | https://reui.io/docs/styling |
|
||||
| **Styling** | https://reui.io/docs/styling |
|
||||
| **Registry** | https://reui.io/docs/registry |
|
||||
| **MCP** | https://reui.io/docs/mcp |
|
||||
| **Agent Skills** | https://reui.io/docs/agent-skills |
|
||||
| **Cursor MCP** | https://reui.io/docs/cursor |
|
||||
| **Blocks** | https://reui.io/blocks |
|
||||
| **Settings blocks** | https://reui.io/blocks/application/settings |
|
||||
| **License** | https://reui.io/docs/license-setup |
|
||||
| **Base UI components** | https://reui.io/docs/components/base/<name> |
|
||||
|
||||
## Когда использовать ReUI vs shadcn
|
||||
## Primary MCP
|
||||
|
||||
1. **`user-reui`** — `search` / `compose_page` / `get_block` / `get_component` / `get_install_command` / `validate_usage` / `get_audit_checklist`
|
||||
2. **`plugin-shadcn-shadcn`** — primitives `@shadcn`; для `@reui` — вторично
|
||||
|
||||
**Обязательно** цитировать `previewUrl` + `docsUrl` для каждой UI-зоны.
|
||||
|
||||
**Registry (актуально):** 20 free components — `alert`, `autocomplete`, `badge`, `data-grid`, `date-selector`, `event-calendar`, `filters`, `frame`, `gantt`, `icon-stack`, `icon-tile`, `kanban`, `number-field`, `phone-input`, `rating`, `scrollspy`, `sortable`, `stepper`, `timeline`, `tree` ([docs](https://reui.io/docs), [MCP](https://reui.io/docs/mcp)). Skill: `.claude/skills/reui` (v `668fb463eb`); обновление: `curl.exe -fsSL https://mcp.reui.io/install | node -` из корня проекта.
|
||||
|
||||
**Важно:** skill описывает текущий registry (в т.ч. data-grid на TanStack Table v9). Установленный в проекте `@reui/data-grid` может оставаться на v8 до явного CLI upgrade — не ломать kit без миграции.
|
||||
|
||||
## Когда ReUI vs shadcn
|
||||
|
||||
| Задача | Registry | Импорт |
|
||||
|--------|----------|--------|
|
||||
| Button, Card, Sheet, Field, Sidebar | `@shadcn` | `@cfdm/ui/components/*` |
|
||||
| Blocks (sidebar-07, dashboard-01) | `@shadcn` | blocks → `apps/web/src/components/` |
|
||||
| Data Grid (sort, pagination, virtual, columns) | `@reui` | `@/components/reui/data-grid/*` → обёртка `DataGridCard` |
|
||||
| Мультифильтры | `@reui` | `@/components/reui/filters` → `DomainsFiltersToolbar` |
|
||||
| Number field со stepper | `@reui` | `@/components/reui/number-field` |
|
||||
| Autocomplete | `@reui` | `@/components/reui/autocomplete` → `AutoCompleteInput` |
|
||||
| Date selector / range | `@reui` | `@/components/reui/date-selector` |
|
||||
| Color picker (формы) | `@reui` | `@/components/reui/color-picker` — hex только в swatch data |
|
||||
| Semantic badge (success/info/warning) | `@reui` | `@/components/reui/badge` или `StatusBadge` |
|
||||
| Button, Sheet, Field, Sidebar, Tabs | `@shadcn` | `@cfdm/ui/components/*` |
|
||||
| PRO pages/sections (settings, stats, auth, dashboard) | `@reui` blocks | adapt → `apps/web/src/components/` / `reui-kit/` |
|
||||
| Data Grid | `@reui` | `@/components/reui/data-grid/*` → `ResourcePage` |
|
||||
| Filters | `@reui` | `@/components/reui/filters` |
|
||||
| Frame surface | `@reui` | `@/components/reui/frame` |
|
||||
| KPI | block [stats-12](https://reui.io/preview/base/stats-12) | `reui-kit/KpiStatGrid` — см. [`kpi-hybrid.mdc`](kpi-hybrid.mdc) |
|
||||
| Quick Actions | Frame tiles sibling KPI | `reui-kit/QuickActionGrid` |
|
||||
| Semantic badge / alert | `@reui` | `@/components/reui/badge`, `@/components/reui/alert` |
|
||||
| Number / date / autocomplete / color / kanban / timeline / stepper / tree | `@reui` | `@/components/reui/*` |
|
||||
| Event Calendar / Gantt / Icon Tile (registry, 20 free) | `@reui` | CLI `@reui/<name>` → `@/components/reui/*` при установке |
|
||||
|
||||
**Простые списки** — shadcn `Table`. **Сложные data-списки** — `DataGridCard` (ReUI data-grid), не shadcn Data Table.
|
||||
**Сложные списки** — `ResourcePage` (Frame + data-grid + filters), не raw `<table>`, не DataGridCard.
|
||||
**Quick Actions** — только `QuickActionGrid` (не Card / Button grid).
|
||||
|
||||
## Источники для ИИ (порядок)
|
||||
## MCP workflow
|
||||
|
||||
1. [ReUI llms.txt](https://reui.io/llms.txt) — полный каталог компонентов
|
||||
2. MCP `plugin-shadcn-shadcn` с `registries: ["@reui"]`
|
||||
3. Docs с **Copy Markdown**: `https://reui.io/docs/components/base/<name>`
|
||||
4. CLI dry-run: `cd apps/web && pnpm dlx shadcn@latest add @reui/<name> --dry-run`
|
||||
0. Codegraph / поиск существующих `reui-kit/*`, `@/components/reui/*`
|
||||
1. `user-reui` `search` (`surface: "frame"`, `category` при известном)
|
||||
2. Страница целиком → `compose_page`; секция → `get_block`
|
||||
3. `get_component` для API primitives из `componentsUsed`
|
||||
4. CLI из `apps/web`: `pnpm dlx shadcn@latest add @reui/<name> --yes`
|
||||
5. Post-add: shadcn imports → `@cfdm/ui/components/*`
|
||||
6. Adapt by reuse → kit / route
|
||||
7. `validate_usage` + `get_audit_checklist`
|
||||
|
||||
## MCP workflow (ветка ReUI)
|
||||
|
||||
0. **Codegraph** `codegraph_explore` — найти `DataGridCard`, `DomainsFiltersToolbar` и существующие `@/components/reui/*`
|
||||
1. **`get_project_registries`** — должен содержать `@reui`
|
||||
2. **`search_items_in_registries`** с `registries: ["@reui"]`, `query`: `"data grid"`, `"filters"`, `"stepper"` и т.д.
|
||||
3. **`get_item_examples_from_registries`** — полный код перед JSX
|
||||
4. **`get_add_command_for_items`** — точная CLI-команда
|
||||
5. Выполнить add из `apps/web` (см. [`frontend-monorepo.mdc`](frontend-monorepo.mdc))
|
||||
6. **Docs:** ReUI `https://reui.io/docs/components/base/<name>` + llms.txt — **не** ui.shadcn.com для `@reui/*`
|
||||
7. Post-add: импорты shadcn-примитивов → `@cfdm/ui/components/*`
|
||||
8. `pnpm install` + `pnpm --filter web build`
|
||||
|
||||
## Размещение и импорты
|
||||
## Размещение
|
||||
|
||||
| Слой | Путь | Импорт |
|
||||
|------|------|--------|
|
||||
| shadcn primitives | `packages/ui/src/components/` | `@cfdm/ui/components/*` |
|
||||
| ReUI enterprise | `apps/web/src/components/reui/` | `@/components/reui/*` |
|
||||
| Проектные обёртки | `apps/web/src/components/` | `@/components/data-grid-card` и т.д. |
|
||||
| shadcn | `packages/ui/src/components/` | `@cfdm/ui/components/*` |
|
||||
| ReUI CLI | `apps/web/src/components/reui/` | `@/components/reui/*` |
|
||||
| PRO blocks (reference) | `apps/web/src/components/blocks/` | adapt into kit, не копипаст в routes |
|
||||
| Kit | `apps/web/src/components/reui-kit/` | `@/components/reui-kit/*` |
|
||||
|
||||
```bash
|
||||
cd apps/web
|
||||
pnpm dlx shadcn@latest add @reui/data-grid
|
||||
pnpm dlx shadcn@latest add @reui/filters
|
||||
## Установленные ReUI (apps/web)
|
||||
|
||||
**Components:** `frame`, `data-grid/*`, `filters`, `kanban`, `badge`, `alert`, `autocomplete`, `number-field`, `date-selector`, `color-picker`, `timeline`, `rating`, `phone-input`, `icon-stack`, `icon-tile`
|
||||
|
||||
**Kit:** `ResourcePage`, `KpiStatGrid`, `QuickActionGrid`, `OpsDashboard`, `KanbanBoard`, `DetailPanel`, `SettingsShell`
|
||||
|
||||
**Blocks (reference):** `stats-12`, `card-35`, `auth-13`, `app-shell-12`, `settings-16`, `settings-8`, `empty-state-12`, `form-7`, `data-grid-filtering-2`, `dashboard-1`, …
|
||||
|
||||
## License
|
||||
|
||||
```env
|
||||
# .env.local (gitignored)
|
||||
REUI_LICENSE_KEY=
|
||||
```
|
||||
|
||||
## Уже установленные ReUI-компоненты
|
||||
`apps/web/components.json` → `@reui` с `Authorization: Bearer ${REUI_LICENSE_KEY}`.
|
||||
|
||||
`badge`, `data-grid/*`, `filters` — в [`apps/web/src/components/reui/`](apps/web/src/components/reui/).
|
||||
## Эталоны preview
|
||||
|
||||
Перед добавлением дубликата — проверить Codegraph и существующие обёртки.
|
||||
|
||||
## Зависимости (только `apps/web`, не `packages/ui`)
|
||||
|
||||
| npm-пакет | ReUI-компоненты |
|
||||
|-----------|-----------------|
|
||||
| `@tanstack/react-table` | data-grid |
|
||||
| `@tanstack/react-virtual` | data-grid (virtual) |
|
||||
| `@dnd-kit/core`, `@dnd-kit/sortable`, `@dnd-kit/modifiers`, `@dnd-kit/utilities` | data-grid dnd, sortable, kanban |
|
||||
| `date-fns`, `react-day-picker` | date-selector |
|
||||
|
||||
После `shadcn add @reui/...` — проверить, что CLI добавил недостающие deps в [`apps/web/package.json`](apps/web/package.json).
|
||||
|
||||
## Semantic tokens (Styling)
|
||||
|
||||
ReUI расширяет тему shadcn токенами `--success`, `--info`, `--warning`, `--destructive-foreground`, `--invert` — уже в [`packages/ui/src/styles/globals.css`](packages/ui/src/styles/globals.css).
|
||||
|
||||
- Badge/Alert: `variant="success"` / `"info"` / `"warning"` — не `bg-emerald-*`
|
||||
- Базовая тема: `pnpm dlx shadcn@latest apply b2fA --only theme`
|
||||
- ReUI-токены: по [Styling guide](https://reui.io/docs/styling); не править `globals.css` вручную без сверки с docs
|
||||
| Зона | Preview |
|
||||
|------|---------|
|
||||
| KPI / Quick Actions | https://reui.io/preview/base/stats-12 · https://reui.io/preview/base/card-12 |
|
||||
| List | https://reui.io/preview/base/data-grid-filtering-2 |
|
||||
| Settings | https://reui.io/preview/base/settings-16 |
|
||||
| Auth | https://reui.io/preview/base/auth-13 |
|
||||
| Shell | https://reui.io/preview/base/app-shell-12 |
|
||||
| Empty | https://reui.io/preview/base/empty-state-12 |
|
||||
|
||||
## Запрещено
|
||||
|
||||
- Копипаст с reui.io без CLI `add @reui/...`
|
||||
- Класть ReUI в `packages/ui` или импортировать как `@cfdm/ui`
|
||||
- Radix-варианты (`/docs/components/radix/...`) — только Base UI
|
||||
- Raw Tailwind-цвета вместо ReUI semantic `variant`
|
||||
- Писать data-grid/filters с нуля, если есть `@reui/*` и shared-обёртки
|
||||
- Копипаст с reui.io без CLI
|
||||
- ReUI в `packages/ui` / импорт как `@cfdm/ui`
|
||||
- Radix-варианты docs — только Base UI
|
||||
- Raw `bg-emerald-*` вместо ReUI `variant`
|
||||
- Hand-roll data-grid/filters/KPI/Quick Actions/settings rows при наличии `@reui` / kit
|
||||
- Смешивать Card и Frame на ops-экране
|
||||
- Ставить shadcn/ui blocks выше ReUI PRO
|
||||
|
||||
## Чеклист
|
||||
|
||||
- [ ] Задача требует ReUI? (см. матрицу выше)
|
||||
- [ ] MCP search с `registries: ["@reui"]` + examples
|
||||
- [ ] `shadcn add @reui/<name>` из `apps/web`
|
||||
- [ ] Импорты: `@cfdm/ui` для примитивов, `@/components/reui` для ReUI
|
||||
- [ ] Зависимости в `apps/web/package.json`
|
||||
- [ ] `pnpm --filter web build` без ошибок
|
||||
- [ ] `user-reui` search/get_block + previewUrl
|
||||
- [ ] `surface: frame`
|
||||
- [ ] CLI add из `apps/web` при новом item
|
||||
- [ ] Kit / `@/components/reui` / `@cfdm/ui` — правильный слой
|
||||
- [ ] `pnpm --filter web build`
|
||||
@@ -11,7 +11,7 @@ user-invocable: false
|
||||
allowed-tools: Bash(npx shadcn@latest *), Bash(pnpm dlx shadcn@latest *), Bash(bunx --bun shadcn@latest *)
|
||||
---
|
||||
|
||||
> **ReUI skill version `0e224b0281`.** If the ReUI MCP's `get_agent_skill` reports a newer `version`, re-run the ReUI installer (see `get_agent_skill` -> `install.recommended`) to update this skill. Cloud/tools-only agents have no local file and always read the latest - they can ignore this.
|
||||
> **ReUI skill version `42d70dcc3d`.** If the ReUI MCP's `get_agent_skill` reports a newer `version`, re-run the ReUI installer (see `get_agent_skill` -> `install.recommended`) to update this skill. Cloud/tools-only agents have no local file and always read the latest - they can ignore this.
|
||||
|
||||
# ReUI for Agents
|
||||
|
||||
|
||||
@@ -1,49 +1,44 @@
|
||||
---
|
||||
description: ВСЕГДА использовать MCP-плагин shadcn UI перед любым UI-кодом
|
||||
description: shadcn MCP — primitives secondary; pages/blocks → user-reui first
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# shadcn MCP — обязательно
|
||||
# shadcn MCP — primitives (secondary)
|
||||
|
||||
Перед **любой** задачей с UI (новый экран, компонент, стили, рефакторинг внешнего вида) — **сначала MCP** `plugin-shadcn-shadcn`, не память и не веб-поиск.
|
||||
Перед UI-задачей: **сначала** MCP `user-reui` для pages / KPI / lists / settings / Frame ([`reui-mcp.mdc`](reui-mcp.mdc)).
|
||||
MCP `plugin-shadcn-shadcn` — для **primitives** `@shadcn` и registry sync, не вместо PRO blocks.
|
||||
|
||||
CLI и docs — **после** MCP, по команде из `get_add_command_for_items`.
|
||||
|
||||
## Порядок (строго)
|
||||
## Порядок (primitives)
|
||||
|
||||
0. **Codegraph** `codegraph_explore` — найти существующие реализации и shared-обёртки (один вызов перед правками)
|
||||
1. **`get_project_registries`** — какие registry доступны в проекте
|
||||
2. **`search_items_in_registries`** — компонент, block, example (`query`: `"card"`, `"tabs demo"`, `"dashboard"`, `"scroll-area"`)
|
||||
3. **`get_item_examples_from_registries`** — полный код примера перед написанием JSX
|
||||
4. **`get_add_command_for_items`** — точная CLI-команда `pnpm dlx shadcn@latest add ...`
|
||||
5. Выполнить add из `apps/web` (см. [`frontend-monorepo.mdc`](frontend-monorepo.mdc))
|
||||
6. **CLI docs (обязательно):** `cd apps/web && pnpm dlx shadcn@latest docs <component>` — сверить API/props с [ui.shadcn.com/docs/components](https://ui.shadcn.com/docs/components)
|
||||
7. Сверить examples из MCP с API из docs CLI — реализовать только после совпадения
|
||||
8. Адаптировать пример под TanStack Router / Query → `apps/web/src/`
|
||||
9. **Context7** — только TanStack / Recharts / не-shadcn (не заменяет шаги 1–8 для примитивов)
|
||||
10. **`get_audit_checklist`** — перед merge PR
|
||||
11. **Codegraph** `codegraph_status` — Pending sync пустой после правок
|
||||
0. Поиск существующих shared / `reui-kit`
|
||||
1. **`get_project_registries`**
|
||||
2. **`search_items_in_registries`** — primitive / example
|
||||
3. **`get_item_examples_from_registries`**
|
||||
4. **`get_add_command_for_items`** → CLI из `apps/web`
|
||||
5. `pnpm dlx shadcn@latest docs <component>` — сверить API
|
||||
6. Адаптировать под TanStack → `apps/web/src/`
|
||||
7. Context7 — только TanStack / Recharts / не-shadcn
|
||||
8. **`get_audit_checklist`** — перед merge
|
||||
|
||||
## Когда вызывать MCP
|
||||
## Когда
|
||||
|
||||
| Задача | MCP |
|
||||
|--------|-----|
|
||||
| Новая страница / layout | `search` → `types: ["block"]` → examples → add block |
|
||||
| Нет примитива в `@cfdm/ui` | `search` → `get_add_command_for_items` → add |
|
||||
| Сомнение в API/props | `get_item_examples_from_registries` |
|
||||
| Ревью UI перед сдачей | `get_audit_checklist` |
|
||||
| Новая страница / KPI / list / settings | **`user-reui`** ([`reui-mcp.mdc`](reui-mcp.mdc)) |
|
||||
| Нет примитива в `@cfdm/ui` | `plugin-shadcn-shadcn` → add |
|
||||
| Сомнение в props примитива | examples + docs CLI |
|
||||
|
||||
## Запрещено
|
||||
|
||||
- Писать UI по памяти, не проверив MCP
|
||||
- Копипаст с ui.shadcn.com без examples/add из MCP
|
||||
- Самописные примитивы, если есть item в registry
|
||||
- Пропускать MCP «потому что компонент простой»
|
||||
- Писать UI по памяти
|
||||
- Ставить ui.shadcn.com/blocks выше ReUI PRO
|
||||
- Самописные примитивы при наличии registry item
|
||||
|
||||
## Сервер и инструменты
|
||||
## Сервер
|
||||
|
||||
- **MCP server:** `plugin-shadcn-shadcn`
|
||||
- **Инструменты:** `get_project_registries`, `search_items_in_registries`, `get_item_examples_from_registries`, `get_add_command_for_items`, `view_items_in_registries`, `list_items_in_registries`, `get_audit_checklist`
|
||||
- Перед вызовом — прочитать schema в `mcps/plugin-shadcn-shadcn/tools/`
|
||||
- **MCP:** `plugin-shadcn-shadcn` (+ `user-reui` primary)
|
||||
- Schema: `mcps/plugin-shadcn-shadcn/tools/`
|
||||
|
||||
Связанные правила: [`shadcn-ui-production.mdc`](shadcn-ui-production.mdc), [`frontend-shadcn.mdc`](frontend-shadcn.mdc).
|
||||
Связанные: [`shadcn-ui-production.mdc`](shadcn-ui-production.mdc), [`reui-mcp.mdc`](reui-mcp.mdc), [`frontend-shadcn.mdc`](frontend-shadcn.mdc).
|
||||
@@ -1,26 +1,33 @@
|
||||
---
|
||||
description: shadcn/ui — глобальные UI-принципы проекта; frontend см. frontend-shadcn.mdc
|
||||
description: shadcn/ui + ReUI PRO — глобальные UI-принципы; ReUI PRO выше shadcn
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# shadcn/ui — правила проекта
|
||||
# shadcn/ui + ReUI PRO — правила проекта
|
||||
|
||||
UI строится **исключительно** по [shadcn/ui](https://ui.shadcn.com/docs/installation): [Components](https://ui.shadcn.com/docs/components), [Blocks](https://ui.shadcn.com/blocks), [Monorepo](https://ui.shadcn.com/docs/monorepo).
|
||||
UI строится по [shadcn/ui](https://ui.shadcn.com/docs/installation) + **ReUI PRO** (`@reui`): [Components](https://ui.shadcn.com/docs/components), [Blocks](https://ui.shadcn.com/blocks), [ReUI Get Started](https://reui.io/docs/get-started), [llms.txt](https://reui.io/llms.txt).
|
||||
|
||||
**Первый шаг любой UI-задачи — MCP `plugin-shadcn-shadcn`** (см. [`shadcn-mcp.mdc`](shadcn-mcp.mdc)): search → examples → add command → CLI.
|
||||
**Иерархия:** ReUI PRO (`user-reui`) **выше** базового shadcn. Pages / KPI / lists / settings / shell → ReUI; shadcn — primitives.
|
||||
|
||||
## Разработка frontend
|
||||
**Первый шаг UI-задачи:**
|
||||
1. MCP **`user-reui`** для pages / KPI / data-grid / settings / Frame / Quick Actions (`surface: frame`)
|
||||
2. MCP **`plugin-shadcn-shadcn`** для primitives `@shadcn`
|
||||
|
||||
**Все правила frontend** — в [`frontend-shadcn.mdc`](frontend-shadcn.mdc), [`frontend-ui-patterns.mdc`](frontend-ui-patterns.mdc) и [`frontend-monorepo.mdc`](frontend-monorepo.mdc) (globs: `apps/web/**`, `packages/ui/**`).
|
||||
См. [`shadcn-mcp.mdc`](shadcn-mcp.mdc), [`reui-mcp.mdc`](reui-mcp.mdc). Contract: [`docs/ui-design-contract.md`](../../docs/ui-design-contract.md).
|
||||
|
||||
Кратко: docs → CLI из `apps/web` → Block → композиция → `pnpm --filter web build`. Кастомный CSS и самописные примитивы **запрещены**.
|
||||
## Frontend
|
||||
|
||||
Детали: [`frontend-shadcn.mdc`](frontend-shadcn.mdc), [`frontend-ui-patterns.mdc`](frontend-ui-patterns.mdc), [`frontend-monorepo.mdc`](frontend-monorepo.mdc).
|
||||
|
||||
Кратко: MCP → CLI из `apps/web` → Block → kit → `pnpm --filter web build`. Кастомный CSS и самописные примитивы **запрещены**.
|
||||
|
||||
## Стек
|
||||
|
||||
- Monorepo: `apps/web` + `packages/ui` (`@cfdm/ui`), pnpm workspaces
|
||||
- Vite + TanStack Router/Query + shadcn **base-nova**
|
||||
- Vite + TanStack Router/Query + shadcn **base-nova** + ReUI **@reui**
|
||||
- Конфиг: [`apps/web/components.json`](apps/web/components.json), [`packages/ui/components.json`](packages/ui/components.json)
|
||||
- Тема: `pnpm dlx shadcn@latest apply b2fA --only theme -y` — единственный способ менять базовую тему `globals.css`; ReUI semantic tokens — [Styling](https://reui.io/docs/styling)
|
||||
- Тема: `pnpm dlx shadcn@latest apply b2fA --only theme -y`; ReUI tokens — [Styling](https://reui.io/docs/styling)
|
||||
- License: `REUI_LICENSE_KEY` в `apps/web/.env.local`
|
||||
|
||||
## Backend → UI
|
||||
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
---
|
||||
name: reui
|
||||
description: Use the ReUI registry from your AI agent - find, install, and correctly use ReUI components (the 17 free building blocks like data-grid, kanban, filters), their free examples, premium blocks, and Motion Icons. Applies in any project using ReUI, the @reui registry, REUI_LICENSE_KEY, or any shadcn project where the user asks for premium blocks, data grids, kanban boards, dashboards, or full pages. Pairs with the free ReUI MCP server for live, scored registry search and inline component APIs.
|
||||
description: Use the ReUI registry from your AI agent - find, install, and correctly use ReUI components (the 20 free building blocks like data-grid, kanban, filters), their free examples, premium blocks, and Motion Icons. Applies in any project using ReUI, the @reui registry, REUI_LICENSE_KEY, or any shadcn project where the user asks for premium blocks, data grids, kanban boards, dashboards, or full pages. Pairs with the free ReUI MCP server for live, scored registry search and inline component APIs.
|
||||
user-invocable: false
|
||||
allowed-tools: Bash(npx shadcn@latest *), Bash(pnpm dlx shadcn@latest *), Bash(bunx --bun shadcn@latest *)
|
||||
---
|
||||
|
||||
> **ReUI skill version `0e224b0281`.** If the ReUI MCP's `get_agent_skill` reports a newer `version`, re-run the ReUI installer (see `get_agent_skill` -> `install.recommended`) to update this skill. Cloud/tools-only agents have no local file and always read the latest - they can ignore this.
|
||||
> **ReUI skill version `668fb463eb`.** If the ReUI MCP's `get_agent_skill` reports a newer `version`, re-run the ReUI installer (see `get_agent_skill` -> `install.recommended`) to update this skill. Cloud/tools-only agents have no local file and always read the latest - they can ignore this.
|
||||
|
||||
# ReUI for Agents
|
||||
|
||||
ReUI is a shadcn-compatible registry. It ships four things you **reuse** - never redesign:
|
||||
|
||||
- **components** - the 17 ReUI building blocks with real APIs: `data-grid`, `kanban`, `filters`, `date-selector`, `tree`, `stepper`, ... (free)
|
||||
- **components** - the 20 ReUI building blocks with real APIs: `data-grid`, `kanban`, `filters`, `date-selector`, `tree`, `stepper`, ... (free)
|
||||
- **examples** - free `c-*` single-pattern use-cases of a component (`c-kanban-1`); install one and read it to see exact composition
|
||||
- **blocks** - premium full-page sections that compose components (`data-grid-2`, `pricing-page-1`); Pro or Ultimate license at install
|
||||
- **icons** - Motion Icons in 4 styles, static + hover-animated variants; Ultimate license at install
|
||||
@@ -58,7 +58,7 @@ Invocation differs slightly per agent (`/mcp__reui__build` in Claude Code/Cursor
|
||||
|
||||
- [rules/registry.md](./rules/registry.md) - the four types, the @reui registry, base/radix, free vs premium + license
|
||||
- [rules/workflow.md](./rules/workflow.md) - the find -> install -> read-API -> adapt loop (most important)
|
||||
- [rules/components.md](./rules/components.md) - the 17 components, the data-grid contract, base vs radix
|
||||
- [rules/components.md](./rules/components.md) - the 20 components, the data-grid contract, base vs radix
|
||||
- [rules/adapting.md](./rules/adapting.md) - reuse-first: preserve the design (no over-customizing), reuse examples + a block's own elements, real data, don't invent APIs
|
||||
- [rules/craft.md](./rules/craft.md) - make it exceptional: point of view, hierarchy, density, states, responsive, motion, the bar
|
||||
- [rules/quality.md](./rules/quality.md) - security, accessibility, and scroll gates (the done gate)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Registry setup (one-time, per project)
|
||||
|
||||
Free items (the 17 components and all `c-*` examples) need only the plain string registry in `components.json`:
|
||||
Free items (the 20 components and all `c-*` examples) need only the plain string registry in `components.json`:
|
||||
|
||||
```json
|
||||
{ "registries": { "@reui": "https://reui.io/r/{style}/{name}.json" } }
|
||||
@@ -29,6 +29,8 @@ REUI_LICENSE_KEY=your-license-key
|
||||
}
|
||||
```
|
||||
|
||||
The shadcn CLI expands `${REUI_LICENSE_KEY}` from `.env.local` inside `components.json`, but an MCP client config never expands variables, so a ReUI MCP server config must carry the raw token instead (for example `reui_pat_your_token_here`).
|
||||
|
||||
The MCP `get_project_context` tool returns the right config. Full guide: https://reui.io/docs/registry
|
||||
|
||||
## Installing
|
||||
@@ -52,7 +54,7 @@ bunx --bun shadcn@latest add @reui/<name> --yes # bun
|
||||
|
||||
## Free vs premium boundary
|
||||
|
||||
- Public, no key: `c-*` examples and the 17 components (`@reui/data-grid`, `@reui/badge`, ...) that those examples depend on.
|
||||
- Public, no key: `c-*` examples and the 20 components (`@reui/data-grid`, `@reui/badge`, ...) that those examples depend on.
|
||||
- Key required at install: blocks (`@reui/<category>-N`) need a Pro or Ultimate license; Motion Icons (`@reui/icons/...`) and templates need Ultimate.
|
||||
|
||||
If an install 401/403s, the license key is missing, invalid, or the plan does not cover that resource (blocks: Pro or higher; icons and templates: Ultimate). Point the user to https://reui.io/account (their key) or https://reui.io/pricing (upgrade).
|
||||
@@ -1,24 +1,23 @@
|
||||
# ReUI components
|
||||
|
||||
The 17 ReUI building blocks: `alert`, `autocomplete`, `badge`, `data-grid`, `date-selector`, `filters`, `frame`, `icon-stack`, `kanban`, `number-field`, `phone-input`, `rating`, `scrollspy`, `sortable`, `stepper`, `timeline`, `tree`. Examples and blocks are composed from these.
|
||||
The 20 ReUI building blocks: `alert`, `autocomplete`, `badge`, `data-grid`, `date-selector`, `event-calendar`, `filters`, `frame`, `gantt`, `icon-stack`, `icon-tile`, `kanban`, `number-field`, `phone-input`, `rating`, `scrollspy`, `sortable`, `stepper`, `timeline`, `tree`. Examples and blocks are composed from these.
|
||||
|
||||
**Rule one: never guess a component's API. Read it first.** Call **`get_component(name)`** for its inline `api` (props + usage, no web fetch), and **share the result's `docsUrl`** (the component's API documentation page) with the user whenever you work with that component's API, so they have the full reference (the `/llms.txt` index is a further fallback). Then call **`get_examples(name)`** to install a worked example and copy real composition. The contracts below are first-try orientation (required props, composition shape, the one gotcha); the inline `api` is the full reference. No single block fits? Compose: search the components you need, read each `get_component`, install a `get_examples` example per component, and adapt.
|
||||
|
||||
## data-grid (the flagship - read its API every time)
|
||||
|
||||
`data-grid` wraps TanStack Table v8. It is NOT a styled `<table>` and does NOT take `data`/`columns` props directly. The contract:
|
||||
`data-grid` wraps TanStack Table v9. It is NOT a styled `<table>` and does NOT take `data`/`columns` props directly. The contract:
|
||||
|
||||
- Build a TanStack table instance with `useReactTable(...)` (columns, data, the feature models you need: sorting, pagination, row selection).
|
||||
- Build a TanStack table instance with `useTable({ features: dataGridFeatures, ... })` (columns, data). `dataGridFeatures` is exported by the primitive and already bundles sorting, filtering, pagination, row selection, expanding, pinning, resizing and faceting, so there are no per-table row models to wire.
|
||||
- Pass that instance to `<DataGrid table={table} recordCount={total}>`.
|
||||
- Compose the body with `DataGridTable` inside `DataGrid`, and enable features through `tableLayout` (e.g. `{ headerSticky: true, columnsResizable: true }`), not ad-hoc classes.
|
||||
- Server-side data uses the documented fetch shape (`recordCount` is the total for pagination).
|
||||
|
||||
```tsx
|
||||
const table = useReactTable({
|
||||
const table = useTable({
|
||||
features: dataGridFeatures,
|
||||
data,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
// add sorting/pagination/selection models per the API
|
||||
})
|
||||
|
||||
<DataGrid table={table} recordCount={data.length}>
|
||||
@@ -28,9 +27,37 @@ const table = useReactTable({
|
||||
|
||||
Common mistakes:
|
||||
|
||||
- **Incorrect:** `<DataGrid data={rows} columns={cols} />` - these props do not exist. **Correct:** build a `useReactTable` instance and pass `table={table}` + `recordCount`.
|
||||
- **Incorrect:** `<DataGrid data={rows} columns={cols} />` - these props do not exist. **Correct:** build a `useTable({ features: dataGridFeatures, ... })` instance and pass `table={table}` + `recordCount`.
|
||||
- **Incorrect:** a raw `<table>` / hand-rolled pagination. **Correct:** use `data-grid`; read its API for sticky header, pagination, virtualization, row selection.
|
||||
- **Incorrect:** styling rows/cells with arbitrary classes. **Correct:** drive layout via `tableLayout` and the documented `ColumnMeta` (e.g. `cellClassName`, `headerTitle`).
|
||||
- **Incorrect:** styling rows/cells with arbitrary classes. **Correct:** drive layout via `tableLayout` and the primitive's `DataGridColumnMeta` (e.g. `cellClassName`, `headerTitle`), set through the bundle's `columnMeta` slot.
|
||||
|
||||
## event-calendar
|
||||
|
||||
**Required:** events via `events`/`onEventsChange` (controlled) or `defaultEvents` (uncontrolled), plus a height on the root.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<EventCalendar defaultEvents={events} defaultView="month" className="h-[560px]">
|
||||
<EventCalendarNav />
|
||||
<EventCalendarContent />
|
||||
</EventCalendar>
|
||||
```
|
||||
|
||||
**Gotcha:** headless-first: `EventCalendarContent` renders the active view (month/week/day/days/agenda; a resource view activates when `resources` is passed) - there is no per-view JSX to compose. Events are `{ id, title, start, end (exclusive), allDay?, color?, recurrence?, resourceId? }`. Mutations flow through `onEventUpdate`/`canDropEvent` (return `false` to reject); the root needs an explicit height because it is a min-h-0 flex column.
|
||||
|
||||
## gantt
|
||||
|
||||
**Required:** `resources` (the left tree) plus bars via `events`/`defaultEvents` attached by `resourceId`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Gantt defaultEvents={bars} resources={tasks} defaultScale="month" className="h-[480px]">
|
||||
<GanttNav />
|
||||
<GanttView />
|
||||
</Gantt>
|
||||
```
|
||||
|
||||
**Gotcha:** bars move along the time axis only (never across rows) and are all-day spans with exclusive `end`; `progress` is 0-100. Scales are `day | week | month | quarter | year`. Zoom control, infinite scroll, summary rollups, and row checkboxes are ON by default - turn off what you do not need. Same `onEventUpdate`/`canDropEvent` commit pipeline as `event-calendar`; the root needs an explicit height.
|
||||
|
||||
## kanban
|
||||
|
||||
@@ -284,6 +311,19 @@ const [value, setValue] = useState<DateSelectorValue | undefined>()
|
||||
|
||||
**Gotcha:** isometric layered artwork for empty states and illustrations; style the inner icon via its own `className`. Mark purely decorative stacks `aria-hidden="true"` and keep the real label in surrounding copy.
|
||||
|
||||
## icon-tile
|
||||
|
||||
**Required:** one child icon
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<IconTile variant="elevated" size="lg">
|
||||
<PackageIcon />
|
||||
</IconTile>
|
||||
```
|
||||
|
||||
**Gotcha:** the square container an icon sits in, so every list row, feature card and empty state shares one affordance. `variant`: `outline` (default) | `elevated` (muted fill, raised ring) | `soft` (tinted nested, tone from currentColor) | `solid` (filled tone, contrasting glyph) | `frame` (double container). `soft` and `solid` retint from one text color class (they default to `text-primary`). `size`: `xs | sm | default | lg | xl` (24/32/40/48/64px tile, glyph scales 12/14/16/20/24px). `radius`: `default | full`. Do not set a `size-*` class on the child icon unless you mean to override the tile's glyph size; recolor with `className` on the tile, not the icon.
|
||||
|
||||
## alert
|
||||
|
||||
**Required:** `Alert` > `AlertTitle`
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
ReUI is a shadcn-compatible registry with four entity types. **Examples and blocks are built FROM components** - reuse them, don't rebuild.
|
||||
|
||||
- **component** - one of the 17 ReUI building blocks with a real API (`data-grid`, `kanban`, `filters`, `date-selector`, `tree`, ...). Install directly (`@reui/data-grid`) or let it come in as a dependency of an example/block. Free. Read its API with `get_component(name)`.
|
||||
- **component** - one of the 20 ReUI building blocks with a real API (`data-grid`, `kanban`, `filters`, `date-selector`, `tree`, ...). Install directly (`@reui/data-grid`) or let it come in as a dependency of an example/block. Free. Read its API with `get_component(name)`.
|
||||
- **example** - a free `c-*` single-pattern use-case of a component (`c-kanban-1`, `c-data-grid-3`). Install one and read it to copy real composition. Find a component's examples with `get_examples(name)`.
|
||||
- **block** - a premium, full-page section that composes several components (`data-grid-2`, `pricing-page-1`). Pro or Ultimate license at install. Adapts to your active theme via semantic tokens.
|
||||
- **icon** - Motion Icons in 4 styles (outline, solid, duotone, filled), static (`@reui/icons/default/<style>/<name>`) and hover-animated (`@reui/icons/animated/<style>/<name>`). Ultimate license at install. See [icons.md](./icons.md).
|
||||
@@ -27,7 +27,7 @@ Blocks adapt to your active theme through semantic tokens and CSS variables - ch
|
||||
|
||||
## Free vs premium
|
||||
|
||||
- **Free, no key:** the 17 components, all `c-*` examples, the ReUI MCP, and this skill.
|
||||
- **Free, no key:** the 20 components, all `c-*` examples, the ReUI MCP, and this skill.
|
||||
- **Premium, license required at install:** blocks (Pro or Ultimate), Motion Icons and templates (Ultimate). Set `REUI_LICENSE_KEY` (see [cli.md](./cli.md)).
|
||||
|
||||
## Component API index
|
||||
|
||||
@@ -8,7 +8,7 @@ The core ReUI loop. The MCP tells you what to install and gives you the API; the
|
||||
|
||||
For everything else, call `search` with the user's intent. Pass structured hints whenever you can infer them - you are an LLM, so do the parsing the server cannot:
|
||||
|
||||
- `type`: `"component"` (one of the 17 building blocks), `"example"` (a c-\* use-case), `"block"` (a full page/section), `"icon"`.
|
||||
- `type`: `"component"` (one of the 20 building blocks), `"example"` (a c-\* use-case), `"block"` (a full page/section), `"icon"`.
|
||||
- `component`: the ReUI component the request implies (`"data-grid"`, `"kanban"`, ...).
|
||||
- `category`, `features` (e.g. `["sortable","pagination"]`), `free`.
|
||||
|
||||
@@ -40,7 +40,7 @@ Before writing code against any component an item uses:
|
||||
|
||||
Installing files is not the end, and redesigning them defeats the point. First note the project's **base** so you write the right API - read `components.json` -> `style` and take the segment before the first `-` (`base-nova` -> Base UI, `radix-nova` -> Radix UI), see [components.md](./components.md). After `add`:
|
||||
|
||||
1. **Read the added files**; keep the composition intact. For a block, verify the components are wired correctly (for `data-grid`: a `useReactTable` instance passed as `table`, `recordCount` set - see [components.md](./components.md)).
|
||||
1. **Read the added files**; keep the composition intact. For a block, verify the components are wired correctly (for `data-grid`: a `useTable({ features: dataGridFeatures, ... })` instance passed as `table`, `recordCount` set - see [components.md](./components.md)).
|
||||
2. **Replace demo data with the user's real data** via typed structures (see [adapting.md](./adapting.md)).
|
||||
3. **Fix icon imports** to the project's icon library (see [icons.md](./icons.md)).
|
||||
4. **Align styling** to semantic tokens and the active theme - no raw colors (see [styling.md](./styling.md)).
|
||||
|
||||
+48
-11
@@ -1,15 +1,52 @@
|
||||
# Build context = repository root (deploy/docker/docker-bake.hcl).
|
||||
.git
|
||||
.gitea
|
||||
.github
|
||||
.cursor
|
||||
data
|
||||
**/target
|
||||
.claude
|
||||
.codegraph
|
||||
.agents
|
||||
.opencode
|
||||
memory-bank
|
||||
.vscode
|
||||
.idea
|
||||
|
||||
**/.DS_Store
|
||||
**/Thumbs.db
|
||||
**/.env
|
||||
**/.env.*
|
||||
!**/.env.example
|
||||
!**/.env.*.example
|
||||
|
||||
node_modules
|
||||
**/node_modules
|
||||
**/.turbo
|
||||
**/dist
|
||||
**/*.md
|
||||
**/.git*
|
||||
frontend
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
.env
|
||||
.env.*
|
||||
**/.turbo
|
||||
# Генерируется `tsr generate` в `web` build (tsc идёт до Vite-плагина).
|
||||
apps/web/src/routeTree.gen.ts
|
||||
apps/web/playwright-report
|
||||
apps/web/test-results
|
||||
|
||||
*.md
|
||||
AGENTS.md
|
||||
CONTRIBUTING.md
|
||||
LICENSE
|
||||
docs
|
||||
|
||||
.pre-commit-config.yaml
|
||||
.releaserc.json
|
||||
.commitlintrc.*
|
||||
commitlint.config.cjs
|
||||
package-lock.json
|
||||
|
||||
data
|
||||
*.exe
|
||||
**/*.test.ts
|
||||
**/*.spec.ts
|
||||
coverage
|
||||
.coverage
|
||||
*.out
|
||||
.release-version
|
||||
CHANGELOG.md
|
||||
deploy/docker/docker-bake.override.hcl
|
||||
deploy/compose/runtime-logs
|
||||
+19
-4
@@ -4,15 +4,30 @@ CLOUDFLARE_API_TOKEN=
|
||||
# Database
|
||||
DATABASE_URL=sqlite:data/app.db
|
||||
|
||||
# Auth
|
||||
JWT_SECRET=dev-secret-change-me
|
||||
# Auth — portal SSO (prod) или локальный admin (dev)
|
||||
# AUTH_REQUIRED=true → JWT от auth-portal, apps включает cfdm
|
||||
AUTH_REQUIRED=false
|
||||
AUTH_JWT_SECRET=dev-secret-change-me
|
||||
# alias: JWT_SECRET=
|
||||
AUTH_ISSUER=https://auth.shnt.top
|
||||
AUTH_PORTAL_URL=http://localhost:5175
|
||||
# Shared with auth-portal AUDIT_INGEST_SECRET — dual-write audit to portal
|
||||
AUTH_AUDIT_INGEST_SECRET=dev-audit-ingest-secret
|
||||
JWT_TTL_HOURS=24
|
||||
|
||||
# Legacy local login (только при AUTH_REQUIRED=false)
|
||||
ADMIN_USERNAME=admin
|
||||
# Leave empty for dev default password "admin"
|
||||
ADMIN_PASSWORD_HASH=
|
||||
|
||||
# Frontend (Vite)
|
||||
# Публичные URL приложений и integration token настраиваются в UI: Настройки → Интеграции
|
||||
# Frontend (Vite) — apps/web/.env.local
|
||||
# VITE_AUTH_ENABLED=true
|
||||
# VITE_AUTH_PORTAL_URL=http://localhost:5175
|
||||
# Публичные URL приложений и integration token: Настройки → Интеграции
|
||||
|
||||
# ReUI PRO (apps/web/components.json → @reui Authorization)
|
||||
# Ключ: https://reui.io/docs/license-setup — класть в .env.local (gitignored)
|
||||
REUI_LICENSE_KEY=
|
||||
|
||||
# Server
|
||||
SERVER_PORT=8080
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# Gitea Actions
|
||||
|
||||
| Workflow | Когда | Что |
|
||||
|----------|--------|-----|
|
||||
| [workflows/ci.yaml](workflows/ci.yaml) | pull request в main/master | quality gates + commitlint |
|
||||
| [workflows/cd.yaml](workflows/cd.yaml) | push в main/master | quality gates + semantic-release + docker push; wiki параллельно |
|
||||
| [workflows/quality.yaml](workflows/quality.yaml) | reusable (`workflow_call`) | changes, web, api, commitlint, docker-check |
|
||||
|
||||
Подробнее: [docs/releasing.md](../docs/releasing.md).
|
||||
|
||||
## CI (quality gates)
|
||||
|
||||
Job **changes** вычисляет флаги по путям в diff. Полный прогон: `.gitea/workflows/*`, `scripts/*`, корневой `package.json` / `pnpm-lock.yaml` / `.releaserc.json`. Правки `.cursor/`, `.claude/`, `*.md` quality jobs не запускают (wiki — отдельный job в CD).
|
||||
|
||||
На **pull request** — **commitlint**. При изменении `deploy/docker/**` / `.dockerignore` — job **docker-check** (`bake --print`, bake без `--push` если есть доступ к registry).
|
||||
|
||||
Кэш зависимостей — нативный `actions/cache` (cache server act_runner), ключ `sha256sum` lockfile (не `hashFiles`). Пути **абсолютные** (`$HOME/.pnpm-store`): тильда `~` на Gitea часто не раскрывается и даёт вечный miss.
|
||||
|
||||
Кэшируется целиком: pnpm store + `node_modules` + corepack. При hit: `pnpm install --offline`. `HUSKY=0` в `scripts/ci/pnpm-ci.sh` (у корня есть `prepare: husky`).
|
||||
|
||||
Если restore пишет `connect ECONNREFUSED` / `cache server not configured` — на runner включите cache server (см. ниже). Иначе каждый job снова качает пакеты (~минуты).
|
||||
|
||||
Runner: `ubuntu-latest`, Docker для **docker-check** (PR) и **publish** (CD).
|
||||
|
||||
## CD (job publish)
|
||||
|
||||
После успешных quality gates на **push в main** job **publish**:
|
||||
|
||||
1. `pnpm exec semantic-release` — тег `vX.Y.Z` на **текущий commit** (без дополнительного commit в main).
|
||||
2. Gitea Release + `CHANGELOG.md` как attachment (не в git).
|
||||
3. Зеркало base-образов в `cfdm-buildcache:base-*` (`deploy/docker/mirror-base-images.sh`; skip существующих тегов, `linux/amd64`, retry при 429).
|
||||
4. `docker buildx bake default --push` с `VERSION=X.Y.Z`, `pull=false`, named builder `cfdm` (`cleanup: false`).
|
||||
|
||||
Если releasable-коммитов нет — semantic-release no-op, образы не публикуются.
|
||||
|
||||
Повтор упавшего **publish** (тег уже есть, bake нет): detect берёт `v*` на `HEAD` и всё равно пушит образы. Подробнее: [docs/releasing.md](../docs/releasing.md#перезапуск-упавшего-job-publish).
|
||||
|
||||
Job **update-wiki** идёт **параллельно** publish (не блокирует образы): при diff `docs/Home.md` копирует файл в wiki-репозиторий. Clone/push идут на публичный **`https://git.shx.one`** (не внутренний `gitea.server_url` / `192.168.x.x:3000`): Gitea `ROOT_URL` совпадает с Host, иначе `git-receive-pack` wiki отвечает `Repository not found`. Токен в URL `https://oauth2:<PAT>@…/*.wiki.git` — Gitea на неаутентифицированный wiki push даёт **404, не 401**, поэтому `http.extraHeader` / ASKPASS не срабатывают. Секрет: **`ACTIONS_PAT`**, fallback **`GITEA_TOKEN`**.
|
||||
|
||||
### Секреты
|
||||
|
||||
**`ACTIONS_PAT`**: push tags, releases, Container Registry. Для git tag fallback: `gitea.token`. Push OCI — **только PAT** (у job token Gitea нет права packages).
|
||||
|
||||
**`GITEA_TOKEN`**: опциональный wiki-only PAT (fallback, если нет `ACTIONS_PAT`).
|
||||
|
||||
### Теги образов
|
||||
|
||||
```text
|
||||
git.shx.one/<owner>/cfdm:latest
|
||||
git.shx.one/<owner>/cfdm:v1.2.3
|
||||
git.shx.one/<owner>/cfdm:1.2.3
|
||||
git.shx.one/<owner>/cfdm:<short-sha>
|
||||
git.shx.one/<owner>/cfdm:sha-<full-sha>
|
||||
```
|
||||
|
||||
Тот же манифест публикуется как `cloudflare-domain-manager` (drop-in для текущего `docker pull`).
|
||||
|
||||
Кэш сборки: `cfdm-buildcache:node-buildcache` и `cfdm-buildcache:base-*`.
|
||||
|
||||
Пример:
|
||||
|
||||
```bash
|
||||
docker pull git.shx.one/denozord/cfdm:latest
|
||||
docker pull git.shx.one/denozord/cloudflare-domain-manager:latest
|
||||
```
|
||||
|
||||
См. [deploy/docker/README.md](../deploy/docker/README.md).
|
||||
|
||||
## act_runner: cache server
|
||||
|
||||
`actions/cache` ходит в **встроенный cache server** runner (не GitHub `type=gha`). Кэш локален для этого runner.
|
||||
|
||||
В `config.yaml` runner:
|
||||
|
||||
```yaml
|
||||
cache:
|
||||
enabled: true
|
||||
dir: "" # по умолчанию $HOME/.cache/actcache
|
||||
host: "" # IP, доступный из job-контейнера (не 0.0.0.0)
|
||||
port: 8088
|
||||
```
|
||||
|
||||
Если runner в Docker, а jobs — отдельные контейнеры: пробросьте порт и задайте `host` (LAN IP хоста) или `external_server: "http://<host>:8088/"`. Иначе restore — timeout/ECONNREFUSED и пакеты качаются снова.
|
||||
|
||||
Не делайте `docker system prune -a` по cron: сотрётся и Docker-кэш FROM, и пользы от `cleanup: false` у buildx не будет.
|
||||
@@ -0,0 +1,203 @@
|
||||
name: CD
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, master]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
uses: ./.gitea/workflows/quality.yaml
|
||||
with:
|
||||
is_pull_request: false
|
||||
before_sha: ${{ github.event.before }}
|
||||
head_sha: ${{ github.sha }}
|
||||
allow_registry_login: false
|
||||
secrets:
|
||||
ACTIONS_PAT: ${{ secrets.ACTIONS_PAT }}
|
||||
|
||||
update-wiki:
|
||||
if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout main repository
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
fetch-depth: 2
|
||||
- name: Check for changes in documentation
|
||||
id: check_changes
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if ! git rev-parse --verify HEAD~1 >/dev/null 2>&1; then
|
||||
echo "changed=true" >> "$GITHUB_OUTPUT"
|
||||
elif git diff HEAD~1 HEAD --quiet -- docs/Home.md; then
|
||||
echo "changed=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "changed=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- name: Update and push Wiki content
|
||||
if: steps.check_changes.outputs.changed == 'true'
|
||||
env:
|
||||
# ACTIONS_PAT уже пишет git (tags/releases). GITEA_TOKEN — опциональный
|
||||
# wiki-only PAT; если он задан без write, Gitea отвечает 404, не 403.
|
||||
WIKI_TOKEN: ${{ secrets.ACTIONS_PAT || secrets.GITEA_TOKEN }}
|
||||
# Не gitea.server_url: на runner это внутренний http://192.168.x.x:3000,
|
||||
# а ROOT_URL = git.shx.one — git-receive-pack wiki тогда даёт 404.
|
||||
GITEA_PUBLIC_URL: https://git.shx.one
|
||||
REPO: ${{ gitea.repository }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -z "${WIKI_TOKEN:-}" ]; then
|
||||
echo "ACTIONS_PAT / GITEA_TOKEN is empty — cannot push wiki"
|
||||
exit 1
|
||||
fi
|
||||
PUBLIC_URL="${GITEA_PUBLIC_URL%/}"
|
||||
TOKEN_ENC="$(python3 -c 'import urllib.parse,os; print(urllib.parse.quote(os.environ["WIKI_TOKEN"], safe=""))')"
|
||||
WIKI_URL="${PUBLIC_URL}/${REPO}.wiki.git"
|
||||
# Gitea на неаутентифицированный wiki push отвечает 404, не 401 —
|
||||
# extraHeader/ASKPASS не помогают: токен должен быть в URL с первого запроса.
|
||||
AUTH_INSTEAD="url.https://oauth2:${TOKEN_ENC}@${PUBLIC_URL#https://}/.insteadOf=${PUBLIC_URL}/"
|
||||
GIT_TERMINAL_PROMPT=0 git -c "${AUTH_INSTEAD}" clone "${WIKI_URL}" cfdm.wiki
|
||||
cp docs/Home.md cfdm.wiki/Home.md
|
||||
cd cfdm.wiki
|
||||
git config user.name "Gitea Actions"
|
||||
git config user.email "actions@gitea"
|
||||
git add Home.md
|
||||
if git diff --staged --quiet; then
|
||||
echo "Wiki Home.md already up to date"
|
||||
exit 0
|
||||
fi
|
||||
git commit -m "docs: Update Wiki from main repository"
|
||||
GIT_TERMINAL_PROMPT=0 git -c "${AUTH_INSTEAD}" push origin HEAD
|
||||
|
||||
publish:
|
||||
needs: [quality]
|
||||
if: >-
|
||||
always() &&
|
||||
(github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master') &&
|
||||
needs.quality.result == 'success'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
releases: write
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
token: ${{ secrets.ACTIONS_PAT || gitea.token }}
|
||||
persist-credentials: true
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: "22"
|
||||
- name: Export cache paths
|
||||
run: sh scripts/ci/export-cache-env.sh
|
||||
- id: pnpm-hash
|
||||
run: echo "key=$(sha256sum pnpm-lock.yaml | awk '{print $1}')" >> "$GITHUB_OUTPUT"
|
||||
- id: pnpm-cache
|
||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
||||
with:
|
||||
path: |
|
||||
${{ env.PNPM_STORE_DIR }}
|
||||
${{ env.COREPACK_HOME }}
|
||||
node_modules
|
||||
apps/web/node_modules
|
||||
apps/api/node_modules
|
||||
packages/ui/node_modules
|
||||
packages/shared/node_modules
|
||||
packages/db/node_modules
|
||||
key: pnpm-${{ runner.os }}-${{ steps.pnpm-hash.outputs.key }}
|
||||
restore-keys: |
|
||||
pnpm-${{ runner.os }}-
|
||||
- name: Install release tooling
|
||||
env:
|
||||
PNPM_CACHE_HIT: ${{ steps.pnpm-cache.outputs.cache-hit }}
|
||||
run: sh scripts/ci/pnpm-ci.sh
|
||||
- name: Verify releasable commit messages
|
||||
run: pnpm exec node scripts/commit/verify-release-commits.mjs
|
||||
- name: Semantic release
|
||||
run: pnpm exec semantic-release
|
||||
env:
|
||||
GITEA_URL: https://git.shx.one
|
||||
GITEA_TOKEN: ${{ secrets.ACTIONS_PAT || gitea.token }}
|
||||
- name: Detect new release
|
||||
id: rel
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version=""
|
||||
if [ -f .release-version ]; then
|
||||
version="$(tr -d '[:space:]' < .release-version)"
|
||||
echo "New release from semantic-release: $version"
|
||||
else
|
||||
git fetch --tags --force origin || true
|
||||
tag="$(git tag --points-at HEAD --list 'v*.*.*' | sort -V | tail -n1 || true)"
|
||||
if [ -n "${tag:-}" ]; then
|
||||
version="${tag#v}"
|
||||
echo "Reuse existing tag $tag on HEAD (release retry)"
|
||||
fi
|
||||
fi
|
||||
if [ -n "${version:-}" ]; then
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "released=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "released=false" >> "$GITHUB_OUTPUT"
|
||||
echo "No releasable commits — skipping image publish"
|
||||
fi
|
||||
- name: Set up Docker Buildx
|
||||
if: steps.rel.outputs.released == 'true'
|
||||
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
|
||||
with:
|
||||
name: cfdm
|
||||
driver: docker-container
|
||||
cleanup: false
|
||||
- name: Prepare image metadata
|
||||
if: steps.rel.outputs.released == 'true'
|
||||
id: meta
|
||||
run: |
|
||||
set -euo pipefail
|
||||
echo "version=${{ steps.rel.outputs.version }}" >> "$GITHUB_OUTPUT"
|
||||
owner_lc="$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')"
|
||||
echo "owner_lc=$owner_lc" >> "$GITHUB_OUTPUT"
|
||||
short_sha="$(echo '${{ github.sha }}' | cut -c1-7)"
|
||||
echo "short_sha=$short_sha" >> "$GITHUB_OUTPUT"
|
||||
echo "build_time=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$GITHUB_OUTPUT"
|
||||
- name: Log in to Gitea Registry
|
||||
if: steps.rel.outputs.released == 'true'
|
||||
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
|
||||
with:
|
||||
registry: git.shx.one
|
||||
username: ${{ gitea.actor }}
|
||||
password: ${{ secrets.ACTIONS_PAT }}
|
||||
- name: Mirror base images into buildcache
|
||||
if: steps.rel.outputs.released == 'true'
|
||||
env:
|
||||
REGISTRY: git.shx.one/${{ steps.meta.outputs.owner_lc }}
|
||||
MIRROR_ENV_FILE: ${{ runner.temp }}/mirror-base.env
|
||||
run: sh deploy/docker/mirror-base-images.sh
|
||||
- name: Build and push images (bake)
|
||||
if: steps.rel.outputs.released == 'true'
|
||||
env:
|
||||
REGISTRY: git.shx.one/${{ steps.meta.outputs.owner_lc }}
|
||||
IMAGE_TAG: latest
|
||||
VERSION: ${{ steps.meta.outputs.version }}
|
||||
SHORT_SHA: ${{ steps.meta.outputs.short_sha }}
|
||||
SHA_FULL: ${{ github.sha }}
|
||||
BUILD_TIME: ${{ steps.meta.outputs.build_time }}
|
||||
CACHE_REF_NODE: git.shx.one/${{ steps.meta.outputs.owner_lc }}/cfdm-buildcache:node-buildcache
|
||||
BUILDX_BAKE_ENTITLEMENTS_FS: "0"
|
||||
BUILDX_BAKE_FILE_RELATIVE_PATHS: "1"
|
||||
MIRROR_ENV_FILE: ${{ runner.temp }}/mirror-base.env
|
||||
working-directory: deploy/docker
|
||||
run: |
|
||||
set -euxo pipefail
|
||||
if [ -f "${MIRROR_ENV_FILE}" ]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1090
|
||||
. "${MIRROR_ENV_FILE}"
|
||||
set +a
|
||||
fi
|
||||
docker buildx bake --allow=fs.read="${{ github.workspace }}" \
|
||||
-f docker-bake.hcl default --push
|
||||
@@ -0,0 +1,23 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main, master]
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
uses: ./.gitea/workflows/quality.yaml
|
||||
with:
|
||||
is_pull_request: true
|
||||
base_sha: ${{ github.event.pull_request.base.sha }}
|
||||
head_sha: ${{ github.event.pull_request.head.sha }}
|
||||
allow_registry_login: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
|
||||
secrets:
|
||||
ACTIONS_PAT: ${{ secrets.ACTIONS_PAT }}
|
||||
@@ -1,189 +0,0 @@
|
||||
name: Build, Test, and Push CFDM Docker Image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, develop, 'feature/**', 'release/**', 'hotfix/**']
|
||||
tags: ['v*']
|
||||
paths: ['**']
|
||||
pull_request:
|
||||
branches: [main, develop]
|
||||
paths: ['**']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10.12.1
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Lint web
|
||||
run: pnpm --filter web lint
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build test stage
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.test
|
||||
load: true
|
||||
tags: cfdm:test
|
||||
provenance: false
|
||||
|
||||
- name: Run tests
|
||||
run: docker run --rm cfdm:test
|
||||
|
||||
build-and-push:
|
||||
needs: test
|
||||
if: startsWith(gitea.ref, 'refs/tags/v') || (gitea.ref_name == 'main' && gitea.event_name == 'push')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Gitea Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: git.shts.su
|
||||
username: ${{ gitea.actor }}
|
||||
password: ${{ secrets.ACTIONS_PAT }}
|
||||
|
||||
- name: Create version file
|
||||
run: |
|
||||
VERSION=$(cat VERSION)
|
||||
BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')
|
||||
BRANCH="${{ gitea.ref_name }}"
|
||||
echo "APP_VERSION=${VERSION}" > ./version.txt
|
||||
echo "BUILD_DATE=${BUILD_DATE}" >> ./version.txt
|
||||
echo "GIT_BRANCH=${BRANCH}" >> ./version.txt
|
||||
echo "GIT_COMMIT=${{ gitea.sha }}" >> ./version.txt
|
||||
echo "GIT_COMMIT_SHORT=$(echo ${{ gitea.sha }} | cut -c1-7)" >> ./version.txt
|
||||
echo "BUILD_TIMESTAMP=$(date -u +%s)" >> ./version.txt
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: git.shts.su/${{ gitea.repository }}
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=raw,value=latest,enable=${{ gitea.ref_name == 'main' }}
|
||||
type=sha,prefix={{date 'YYYYMMDD'}}-,enable=${{ gitea.ref_name == 'main' }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
build-args: |
|
||||
NODE_VERSION=22.23.0-bookworm-slim
|
||||
cache-from: type=registry,ref=git.shts.su/${{ gitea.repository }}:buildcache
|
||||
cache-to: type=registry,ref=git.shts.su/${{ gitea.repository }}:buildcache,mode=max
|
||||
provenance: true
|
||||
|
||||
create-release:
|
||||
needs: build-and-push
|
||||
if: startsWith(gitea.ref, 'refs/tags/v')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Generate changelog
|
||||
id: changelog
|
||||
run: |
|
||||
LAST_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
|
||||
if [[ -n "$LAST_TAG" ]]; then
|
||||
CHANGELOG=$(git log --pretty=format:"- **%h** %s (%an, %ar)" --no-merges ${LAST_TAG}..HEAD 2>/dev/null || echo "")
|
||||
else
|
||||
CHANGELOG=$(git log --pretty=format:"- **%h** %s (%an, %ar)" --no-merges -10 2>/dev/null || echo "")
|
||||
fi
|
||||
if [[ -z "$CHANGELOG" ]]; then CHANGELOG="- No changes detected"; fi
|
||||
echo "CHANGELOG<<EOF" >> $GITEA_OUTPUT
|
||||
echo "$CHANGELOG" >> $GITEA_OUTPUT
|
||||
echo "EOF" >> $GITEA_OUTPUT
|
||||
|
||||
- name: Create Release
|
||||
run: |
|
||||
VERSION="${{ gitea.ref_name }}"
|
||||
RELEASE_DATA=$(cat <<EOF
|
||||
{
|
||||
"tag_name": "${VERSION}",
|
||||
"target_commitish": "${{ gitea.sha }}",
|
||||
"name": "Cloudflare Domain Manager ${VERSION}",
|
||||
"body": "## Cloudflare Domain Manager ${VERSION}\n\n### Docker\n\n\`\`\`bash\ndocker pull git.shts.su/${{ gitea.repository }}:${VERSION}\ndocker run -d -p 8080:8080 -v ./data:/data --name cfdm git.shts.su/${{ gitea.repository }}:${VERSION}\n\`\`\`\n\n### Changelog\n\n${{ steps.changelog.outputs.CHANGELOG }}",
|
||||
"draft": false,
|
||||
"prerelease": false
|
||||
}
|
||||
EOF
|
||||
)
|
||||
HTTP_CODE=$(curl -s -w "%{http_code}" -o /tmp/release.json -X POST \
|
||||
-H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$RELEASE_DATA" \
|
||||
"${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}/releases")
|
||||
if [ "$HTTP_CODE" -eq 201 ] || [ "$HTTP_CODE" -eq 409 ]; then
|
||||
echo "Release OK (HTTP $HTTP_CODE)"
|
||||
else
|
||||
cat /tmp/release.json
|
||||
exit 1
|
||||
fi
|
||||
|
||||
update-wiki:
|
||||
needs: test
|
||||
if: gitea.ref_name == 'main' && gitea.event_name == 'push'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout main repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 2
|
||||
|
||||
- name: Check for changes in documentation
|
||||
id: check_changes
|
||||
run: |
|
||||
if git diff HEAD~1 HEAD --quiet -- docs/Home.md; then
|
||||
echo "changed=false" >> $GITEA_OUTPUT
|
||||
else
|
||||
echo "changed=true" >> $GITEA_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Clone Wiki repository
|
||||
if: steps.check_changes.outputs.changed == 'true'
|
||||
run: |
|
||||
WIKI_URL=$(echo "${{ gitea.server_url }}/${{ gitea.repository }}.wiki.git" | sed -e "s|://|://gitea-actions:${{ secrets.GITEA_TOKEN }}@|")
|
||||
git clone "${WIKI_URL}" cfdm.wiki
|
||||
|
||||
- name: Update and push Wiki content
|
||||
if: steps.check_changes.outputs.changed == 'true'
|
||||
run: |
|
||||
cp docs/Home.md cfdm.wiki/Home.md
|
||||
cd cfdm.wiki
|
||||
git config user.name "Gitea Actions"
|
||||
git config user.email "actions@gitea"
|
||||
git add Home.md
|
||||
git diff --staged --quiet || git commit -m "docs: Update Wiki from main repository"
|
||||
git push
|
||||
@@ -0,0 +1,295 @@
|
||||
# Quality gates (reusable). Callers: ci.yaml (PR), cd.yaml (push main).
|
||||
name: quality
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
is_pull_request:
|
||||
type: boolean
|
||||
required: true
|
||||
base_sha:
|
||||
type: string
|
||||
required: false
|
||||
default: ""
|
||||
head_sha:
|
||||
type: string
|
||||
required: false
|
||||
default: ""
|
||||
before_sha:
|
||||
type: string
|
||||
required: false
|
||||
default: ""
|
||||
allow_registry_login:
|
||||
type: boolean
|
||||
required: false
|
||||
default: false
|
||||
secrets:
|
||||
ACTIONS_PAT:
|
||||
required: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
changes:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
web: ${{ steps.detect.outputs.web }}
|
||||
api: ${{ steps.detect.outputs.api }}
|
||||
docker: ${{ steps.detect.outputs.docker }}
|
||||
steps:
|
||||
- if: ${{ inputs.is_pull_request }}
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- if: ${{ inputs.is_pull_request == false }}
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
fetch-depth: 2
|
||||
- id: detect
|
||||
name: Detect changed paths per module
|
||||
env:
|
||||
IS_PR: ${{ inputs.is_pull_request }}
|
||||
BASE_SHA: ${{ inputs.base_sha }}
|
||||
HEAD_SHA: ${{ inputs.head_sha }}
|
||||
BEFORE_SHA: ${{ inputs.before_sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
web=false
|
||||
api=false
|
||||
docker=false
|
||||
|
||||
set_all_flags_true() {
|
||||
web=true
|
||||
api=true
|
||||
docker=true
|
||||
}
|
||||
|
||||
write_outputs() {
|
||||
for v in web api docker; do
|
||||
eval "echo \"\$v=\$$v\"" >> "$GITHUB_OUTPUT"
|
||||
done
|
||||
}
|
||||
|
||||
if [ "$IS_PR" = "true" ]; then
|
||||
FILES="$(git diff --name-only "$BASE_SHA" "$HEAD_SHA")"
|
||||
else
|
||||
after="${HEAD_SHA:-$(git rev-parse HEAD)}"
|
||||
before="$BEFORE_SHA"
|
||||
if [ -n "$before" ] && [ "$before" != "0000000000000000000000000000000000000000" ]; then
|
||||
FILES="$(git diff --name-only "$before" "$after")"
|
||||
elif git rev-parse --verify HEAD~1 >/dev/null 2>&1; then
|
||||
FILES="$(git diff --name-only HEAD~1 HEAD)"
|
||||
else
|
||||
set_all_flags_true
|
||||
write_outputs
|
||||
echo "No parent commit — full pipeline (all modules)"
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$(printf '%s' "$FILES" | tr -d '[:space:]')" ]; then
|
||||
set_all_flags_true
|
||||
write_outputs
|
||||
echo "Empty diff — full pipeline fallback"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
full_pipeline=false
|
||||
|
||||
while IFS= read -r f || [ -n "${f:-}" ]; do
|
||||
[ -z "${f:-}" ] && continue
|
||||
case "$f" in
|
||||
.gitea/workflows/*|scripts/*)
|
||||
full_pipeline=true
|
||||
;;
|
||||
.cursor/*|.claude/*|.codegraph/*|.agents/*)
|
||||
;;
|
||||
*.md|AGENTS.md)
|
||||
;;
|
||||
apps/web/README.md|apps/web/components.json|packages/ui/components.json)
|
||||
;;
|
||||
apps/web/*|packages/ui/*)
|
||||
web=true
|
||||
;;
|
||||
apps/api/*|packages/db/*)
|
||||
api=true
|
||||
;;
|
||||
packages/shared/*)
|
||||
web=true
|
||||
api=true
|
||||
;;
|
||||
deploy/compose/*|deploy/docker/*|.dockerignore|docker-compose.yml)
|
||||
docker=true
|
||||
;;
|
||||
docs/*)
|
||||
;;
|
||||
package.json|pnpm-lock.yaml|pnpm-workspace.yaml|turbo.json|.releaserc.json|commitlint.config.cjs)
|
||||
full_pipeline=true
|
||||
;;
|
||||
*)
|
||||
;;
|
||||
esac
|
||||
done <<< "$FILES"
|
||||
|
||||
if $full_pipeline; then
|
||||
set_all_flags_true
|
||||
fi
|
||||
|
||||
write_outputs
|
||||
|
||||
echo "Changed files (first 30):"
|
||||
printf '%s\n' "$FILES" | head -n 30
|
||||
echo "--- flags ---"
|
||||
echo "web=$web api=$api docker=$docker full_pipeline=$full_pipeline"
|
||||
|
||||
web:
|
||||
needs: [changes]
|
||||
if: needs.changes.outputs.web == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: "22"
|
||||
- name: Export cache paths
|
||||
run: sh scripts/ci/export-cache-env.sh
|
||||
- id: pnpm-hash
|
||||
run: echo "key=$(sha256sum pnpm-lock.yaml | awk '{print $1}')" >> "$GITHUB_OUTPUT"
|
||||
- id: pnpm-cache
|
||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
||||
with:
|
||||
path: |
|
||||
${{ env.PNPM_STORE_DIR }}
|
||||
${{ env.COREPACK_HOME }}
|
||||
node_modules
|
||||
apps/web/node_modules
|
||||
apps/api/node_modules
|
||||
packages/ui/node_modules
|
||||
packages/shared/node_modules
|
||||
packages/db/node_modules
|
||||
key: pnpm-${{ runner.os }}-${{ steps.pnpm-hash.outputs.key }}
|
||||
restore-keys: |
|
||||
pnpm-${{ runner.os }}-
|
||||
- name: pnpm install, lint, test, build
|
||||
env:
|
||||
PNPM_CACHE_HIT: ${{ steps.pnpm-cache.outputs.cache-hit }}
|
||||
run: |
|
||||
set -euxo pipefail
|
||||
sh scripts/ci/pnpm-ci.sh
|
||||
pnpm --filter web lint
|
||||
pnpm exec turbo run test --filter=web
|
||||
pnpm exec turbo run build --filter=web
|
||||
|
||||
api:
|
||||
needs: [changes]
|
||||
if: needs.changes.outputs.api == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: "22"
|
||||
- name: Export cache paths
|
||||
run: sh scripts/ci/export-cache-env.sh
|
||||
- id: pnpm-hash
|
||||
run: echo "key=$(sha256sum pnpm-lock.yaml | awk '{print $1}')" >> "$GITHUB_OUTPUT"
|
||||
- id: pnpm-cache
|
||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
||||
with:
|
||||
path: |
|
||||
${{ env.PNPM_STORE_DIR }}
|
||||
${{ env.COREPACK_HOME }}
|
||||
node_modules
|
||||
apps/web/node_modules
|
||||
apps/api/node_modules
|
||||
packages/ui/node_modules
|
||||
packages/shared/node_modules
|
||||
packages/db/node_modules
|
||||
key: pnpm-${{ runner.os }}-${{ steps.pnpm-hash.outputs.key }}
|
||||
restore-keys: |
|
||||
pnpm-${{ runner.os }}-
|
||||
- name: pnpm install, test, build
|
||||
env:
|
||||
PNPM_CACHE_HIT: ${{ steps.pnpm-cache.outputs.cache-hit }}
|
||||
run: |
|
||||
set -euxo pipefail
|
||||
sh scripts/ci/pnpm-ci.sh
|
||||
pnpm exec turbo run test --filter=@cfdm/api
|
||||
pnpm exec turbo run build --filter=@cfdm/api
|
||||
|
||||
commitlint:
|
||||
if: inputs.is_pull_request
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: "22"
|
||||
- name: Export cache paths
|
||||
run: sh scripts/ci/export-cache-env.sh
|
||||
- id: pnpm-hash
|
||||
run: echo "key=$(sha256sum pnpm-lock.yaml | awk '{print $1}')" >> "$GITHUB_OUTPUT"
|
||||
- id: pnpm-cache
|
||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
||||
with:
|
||||
path: |
|
||||
${{ env.PNPM_STORE_DIR }}
|
||||
${{ env.COREPACK_HOME }}
|
||||
node_modules
|
||||
apps/web/node_modules
|
||||
apps/api/node_modules
|
||||
packages/ui/node_modules
|
||||
packages/shared/node_modules
|
||||
packages/db/node_modules
|
||||
key: pnpm-${{ runner.os }}-${{ steps.pnpm-hash.outputs.key }}
|
||||
restore-keys: |
|
||||
pnpm-${{ runner.os }}-
|
||||
- name: Lint commit messages
|
||||
env:
|
||||
BASE_SHA: ${{ inputs.base_sha }}
|
||||
HEAD_SHA: ${{ inputs.head_sha }}
|
||||
PNPM_CACHE_HIT: ${{ steps.pnpm-cache.outputs.cache-hit }}
|
||||
run: |
|
||||
set -euxo pipefail
|
||||
sh scripts/ci/pnpm-ci.sh
|
||||
pnpm exec commitlint --from "$BASE_SHA" --to "$HEAD_SHA"
|
||||
|
||||
docker-check:
|
||||
needs: [changes]
|
||||
if: inputs.is_pull_request && needs.changes.outputs.docker == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
|
||||
with:
|
||||
name: cfdm
|
||||
driver: docker-container
|
||||
cleanup: false
|
||||
- name: Log in to Gitea Registry
|
||||
if: inputs.allow_registry_login
|
||||
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
|
||||
with:
|
||||
registry: git.shx.one
|
||||
username: ${{ gitea.actor }}
|
||||
password: ${{ secrets.ACTIONS_PAT }}
|
||||
- name: bake --print
|
||||
working-directory: deploy/docker
|
||||
env:
|
||||
BUILDX_BAKE_ENTITLEMENTS_FS: "0"
|
||||
BUILDX_BAKE_FILE_RELATIVE_PATHS: "1"
|
||||
run: docker buildx bake --allow=fs.read="${{ github.workspace }}" -f docker-bake.hcl --print default
|
||||
- name: bake (no push)
|
||||
if: inputs.allow_registry_login
|
||||
working-directory: deploy/docker
|
||||
env:
|
||||
BUILDX_BAKE_ENTITLEMENTS_FS: "0"
|
||||
BUILDX_BAKE_FILE_RELATIVE_PATHS: "1"
|
||||
run: |
|
||||
set -euxo pipefail
|
||||
owner_lc="$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')"
|
||||
export CACHE_REF_NODE="git.shx.one/${owner_lc}/cfdm-buildcache:node-buildcache"
|
||||
docker buildx bake --allow=fs.read="${{ github.workspace }}" -f docker-bake.hcl default
|
||||
@@ -32,3 +32,10 @@ Thumbs.db
|
||||
|
||||
# Build
|
||||
version.txt
|
||||
.release-version
|
||||
CHANGELOG.md
|
||||
.codegraph/daemon.pid
|
||||
|
||||
# Local MCP configs (may contain REUI license Bearer)
|
||||
.cursor/mcp.json
|
||||
.mcp.json
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"codegraph": {
|
||||
"type": "stdio",
|
||||
"command": "codegraph",
|
||||
"args": [
|
||||
"serve",
|
||||
"--mcp"
|
||||
]
|
||||
},
|
||||
"reui": {
|
||||
"type": "http",
|
||||
"url": "https://mcp.reui.io/api/mcp"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
---
|
||||
name: reui
|
||||
description: Use the ReUI registry from your AI agent - find, install, and correctly use ReUI components (the 17 free building blocks like data-grid, kanban, filters), their free examples, premium blocks, and Motion Icons. Applies in any project using ReUI, the @reui registry, REUI_LICENSE_KEY, or any shadcn project where the user asks for premium blocks, data grids, kanban boards, dashboards, or full pages. Pairs with the free ReUI MCP server for live, scored registry search and inline component APIs.
|
||||
description: Use the ReUI registry from your AI agent - find, install, and correctly use ReUI components (the 20 free building blocks like data-grid, kanban, filters), their free examples, premium blocks, and Motion Icons. Applies in any project using ReUI, the @reui registry, REUI_LICENSE_KEY, or any shadcn project where the user asks for premium blocks, data grids, kanban boards, dashboards, or full pages. Pairs with the free ReUI MCP server for live, scored registry search and inline component APIs.
|
||||
user-invocable: false
|
||||
allowed-tools: Bash(npx shadcn@latest *), Bash(pnpm dlx shadcn@latest *), Bash(bunx --bun shadcn@latest *)
|
||||
---
|
||||
|
||||
> **ReUI skill version `0e224b0281`.** If the ReUI MCP's `get_agent_skill` reports a newer `version`, re-run the ReUI installer (see `get_agent_skill` -> `install.recommended`) to update this skill. Cloud/tools-only agents have no local file and always read the latest - they can ignore this.
|
||||
> **ReUI skill version `668fb463eb`.** If the ReUI MCP's `get_agent_skill` reports a newer `version`, re-run the ReUI installer (see `get_agent_skill` -> `install.recommended`) to update this skill. Cloud/tools-only agents have no local file and always read the latest - they can ignore this.
|
||||
|
||||
# ReUI for Agents
|
||||
|
||||
ReUI is a shadcn-compatible registry. It ships four things you **reuse** - never redesign:
|
||||
|
||||
- **components** - the 17 ReUI building blocks with real APIs: `data-grid`, `kanban`, `filters`, `date-selector`, `tree`, `stepper`, ... (free)
|
||||
- **components** - the 20 ReUI building blocks with real APIs: `data-grid`, `kanban`, `filters`, `date-selector`, `tree`, `stepper`, ... (free)
|
||||
- **examples** - free `c-*` single-pattern use-cases of a component (`c-kanban-1`); install one and read it to see exact composition
|
||||
- **blocks** - premium full-page sections that compose components (`data-grid-2`, `pricing-page-1`); Pro or Ultimate license at install
|
||||
- **icons** - Motion Icons in 4 styles, static + hover-animated variants; Ultimate license at install
|
||||
@@ -58,7 +58,7 @@ Invocation differs slightly per agent (`/mcp__reui__build` in Claude Code/Cursor
|
||||
|
||||
- [rules/registry.md](./rules/registry.md) - the four types, the @reui registry, base/radix, free vs premium + license
|
||||
- [rules/workflow.md](./rules/workflow.md) - the find -> install -> read-API -> adapt loop (most important)
|
||||
- [rules/components.md](./rules/components.md) - the 17 components, the data-grid contract, base vs radix
|
||||
- [rules/components.md](./rules/components.md) - the 20 components, the data-grid contract, base vs radix
|
||||
- [rules/adapting.md](./rules/adapting.md) - reuse-first: preserve the design (no over-customizing), reuse examples + a block's own elements, real data, don't invent APIs
|
||||
- [rules/craft.md](./rules/craft.md) - make it exceptional: point of view, hierarchy, density, states, responsive, motion, the bar
|
||||
- [rules/quality.md](./rules/quality.md) - security, accessibility, and scroll gates (the done gate)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Registry setup (one-time, per project)
|
||||
|
||||
Free items (the 17 components and all `c-*` examples) need only the plain string registry in `components.json`:
|
||||
Free items (the 20 components and all `c-*` examples) need only the plain string registry in `components.json`:
|
||||
|
||||
```json
|
||||
{ "registries": { "@reui": "https://reui.io/r/{style}/{name}.json" } }
|
||||
@@ -29,6 +29,8 @@ REUI_LICENSE_KEY=your-license-key
|
||||
}
|
||||
```
|
||||
|
||||
The shadcn CLI expands `${REUI_LICENSE_KEY}` from `.env.local` inside `components.json`, but an MCP client config never expands variables, so a ReUI MCP server config must carry the raw token instead (for example `reui_pat_your_token_here`).
|
||||
|
||||
The MCP `get_project_context` tool returns the right config. Full guide: https://reui.io/docs/registry
|
||||
|
||||
## Installing
|
||||
@@ -52,7 +54,7 @@ bunx --bun shadcn@latest add @reui/<name> --yes # bun
|
||||
|
||||
## Free vs premium boundary
|
||||
|
||||
- Public, no key: `c-*` examples and the 17 components (`@reui/data-grid`, `@reui/badge`, ...) that those examples depend on.
|
||||
- Public, no key: `c-*` examples and the 20 components (`@reui/data-grid`, `@reui/badge`, ...) that those examples depend on.
|
||||
- Key required at install: blocks (`@reui/<category>-N`) need a Pro or Ultimate license; Motion Icons (`@reui/icons/...`) and templates need Ultimate.
|
||||
|
||||
If an install 401/403s, the license key is missing, invalid, or the plan does not cover that resource (blocks: Pro or higher; icons and templates: Ultimate). Point the user to https://reui.io/account (their key) or https://reui.io/pricing (upgrade).
|
||||
@@ -1,24 +1,23 @@
|
||||
# ReUI components
|
||||
|
||||
The 17 ReUI building blocks: `alert`, `autocomplete`, `badge`, `data-grid`, `date-selector`, `filters`, `frame`, `icon-stack`, `kanban`, `number-field`, `phone-input`, `rating`, `scrollspy`, `sortable`, `stepper`, `timeline`, `tree`. Examples and blocks are composed from these.
|
||||
The 20 ReUI building blocks: `alert`, `autocomplete`, `badge`, `data-grid`, `date-selector`, `event-calendar`, `filters`, `frame`, `gantt`, `icon-stack`, `icon-tile`, `kanban`, `number-field`, `phone-input`, `rating`, `scrollspy`, `sortable`, `stepper`, `timeline`, `tree`. Examples and blocks are composed from these.
|
||||
|
||||
**Rule one: never guess a component's API. Read it first.** Call **`get_component(name)`** for its inline `api` (props + usage, no web fetch), and **share the result's `docsUrl`** (the component's API documentation page) with the user whenever you work with that component's API, so they have the full reference (the `/llms.txt` index is a further fallback). Then call **`get_examples(name)`** to install a worked example and copy real composition. The contracts below are first-try orientation (required props, composition shape, the one gotcha); the inline `api` is the full reference. No single block fits? Compose: search the components you need, read each `get_component`, install a `get_examples` example per component, and adapt.
|
||||
|
||||
## data-grid (the flagship - read its API every time)
|
||||
|
||||
`data-grid` wraps TanStack Table v8. It is NOT a styled `<table>` and does NOT take `data`/`columns` props directly. The contract:
|
||||
`data-grid` wraps TanStack Table v9. It is NOT a styled `<table>` and does NOT take `data`/`columns` props directly. The contract:
|
||||
|
||||
- Build a TanStack table instance with `useReactTable(...)` (columns, data, the feature models you need: sorting, pagination, row selection).
|
||||
- Build a TanStack table instance with `useTable({ features: dataGridFeatures, ... })` (columns, data). `dataGridFeatures` is exported by the primitive and already bundles sorting, filtering, pagination, row selection, expanding, pinning, resizing and faceting, so there are no per-table row models to wire.
|
||||
- Pass that instance to `<DataGrid table={table} recordCount={total}>`.
|
||||
- Compose the body with `DataGridTable` inside `DataGrid`, and enable features through `tableLayout` (e.g. `{ headerSticky: true, columnsResizable: true }`), not ad-hoc classes.
|
||||
- Server-side data uses the documented fetch shape (`recordCount` is the total for pagination).
|
||||
|
||||
```tsx
|
||||
const table = useReactTable({
|
||||
const table = useTable({
|
||||
features: dataGridFeatures,
|
||||
data,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
// add sorting/pagination/selection models per the API
|
||||
})
|
||||
|
||||
<DataGrid table={table} recordCount={data.length}>
|
||||
@@ -28,9 +27,37 @@ const table = useReactTable({
|
||||
|
||||
Common mistakes:
|
||||
|
||||
- **Incorrect:** `<DataGrid data={rows} columns={cols} />` - these props do not exist. **Correct:** build a `useReactTable` instance and pass `table={table}` + `recordCount`.
|
||||
- **Incorrect:** `<DataGrid data={rows} columns={cols} />` - these props do not exist. **Correct:** build a `useTable({ features: dataGridFeatures, ... })` instance and pass `table={table}` + `recordCount`.
|
||||
- **Incorrect:** a raw `<table>` / hand-rolled pagination. **Correct:** use `data-grid`; read its API for sticky header, pagination, virtualization, row selection.
|
||||
- **Incorrect:** styling rows/cells with arbitrary classes. **Correct:** drive layout via `tableLayout` and the documented `ColumnMeta` (e.g. `cellClassName`, `headerTitle`).
|
||||
- **Incorrect:** styling rows/cells with arbitrary classes. **Correct:** drive layout via `tableLayout` and the primitive's `DataGridColumnMeta` (e.g. `cellClassName`, `headerTitle`), set through the bundle's `columnMeta` slot.
|
||||
|
||||
## event-calendar
|
||||
|
||||
**Required:** events via `events`/`onEventsChange` (controlled) or `defaultEvents` (uncontrolled), plus a height on the root.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<EventCalendar defaultEvents={events} defaultView="month" className="h-[560px]">
|
||||
<EventCalendarNav />
|
||||
<EventCalendarContent />
|
||||
</EventCalendar>
|
||||
```
|
||||
|
||||
**Gotcha:** headless-first: `EventCalendarContent` renders the active view (month/week/day/days/agenda; a resource view activates when `resources` is passed) - there is no per-view JSX to compose. Events are `{ id, title, start, end (exclusive), allDay?, color?, recurrence?, resourceId? }`. Mutations flow through `onEventUpdate`/`canDropEvent` (return `false` to reject); the root needs an explicit height because it is a min-h-0 flex column.
|
||||
|
||||
## gantt
|
||||
|
||||
**Required:** `resources` (the left tree) plus bars via `events`/`defaultEvents` attached by `resourceId`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Gantt defaultEvents={bars} resources={tasks} defaultScale="month" className="h-[480px]">
|
||||
<GanttNav />
|
||||
<GanttView />
|
||||
</Gantt>
|
||||
```
|
||||
|
||||
**Gotcha:** bars move along the time axis only (never across rows) and are all-day spans with exclusive `end`; `progress` is 0-100. Scales are `day | week | month | quarter | year`. Zoom control, infinite scroll, summary rollups, and row checkboxes are ON by default - turn off what you do not need. Same `onEventUpdate`/`canDropEvent` commit pipeline as `event-calendar`; the root needs an explicit height.
|
||||
|
||||
## kanban
|
||||
|
||||
@@ -284,6 +311,19 @@ const [value, setValue] = useState<DateSelectorValue | undefined>()
|
||||
|
||||
**Gotcha:** isometric layered artwork for empty states and illustrations; style the inner icon via its own `className`. Mark purely decorative stacks `aria-hidden="true"` and keep the real label in surrounding copy.
|
||||
|
||||
## icon-tile
|
||||
|
||||
**Required:** one child icon
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<IconTile variant="elevated" size="lg">
|
||||
<PackageIcon />
|
||||
</IconTile>
|
||||
```
|
||||
|
||||
**Gotcha:** the square container an icon sits in, so every list row, feature card and empty state shares one affordance. `variant`: `outline` (default) | `elevated` (muted fill, raised ring) | `soft` (tinted nested, tone from currentColor) | `solid` (filled tone, contrasting glyph) | `frame` (double container). `soft` and `solid` retint from one text color class (they default to `text-primary`). `size`: `xs | sm | default | lg | xl` (24/32/40/48/64px tile, glyph scales 12/14/16/20/24px). `radius`: `default | full`. Do not set a `size-*` class on the child icon unless you mean to override the tile's glyph size; recolor with `className` on the tile, not the icon.
|
||||
|
||||
## alert
|
||||
|
||||
**Required:** `Alert` > `AlertTitle`
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
ReUI is a shadcn-compatible registry with four entity types. **Examples and blocks are built FROM components** - reuse them, don't rebuild.
|
||||
|
||||
- **component** - one of the 17 ReUI building blocks with a real API (`data-grid`, `kanban`, `filters`, `date-selector`, `tree`, ...). Install directly (`@reui/data-grid`) or let it come in as a dependency of an example/block. Free. Read its API with `get_component(name)`.
|
||||
- **component** - one of the 20 ReUI building blocks with a real API (`data-grid`, `kanban`, `filters`, `date-selector`, `tree`, ...). Install directly (`@reui/data-grid`) or let it come in as a dependency of an example/block. Free. Read its API with `get_component(name)`.
|
||||
- **example** - a free `c-*` single-pattern use-case of a component (`c-kanban-1`, `c-data-grid-3`). Install one and read it to copy real composition. Find a component's examples with `get_examples(name)`.
|
||||
- **block** - a premium, full-page section that composes several components (`data-grid-2`, `pricing-page-1`). Pro or Ultimate license at install. Adapts to your active theme via semantic tokens.
|
||||
- **icon** - Motion Icons in 4 styles (outline, solid, duotone, filled), static (`@reui/icons/default/<style>/<name>`) and hover-animated (`@reui/icons/animated/<style>/<name>`). Ultimate license at install. See [icons.md](./icons.md).
|
||||
@@ -27,7 +27,7 @@ Blocks adapt to your active theme through semantic tokens and CSS variables - ch
|
||||
|
||||
## Free vs premium
|
||||
|
||||
- **Free, no key:** the 17 components, all `c-*` examples, the ReUI MCP, and this skill.
|
||||
- **Free, no key:** the 20 components, all `c-*` examples, the ReUI MCP, and this skill.
|
||||
- **Premium, license required at install:** blocks (Pro or Ultimate), Motion Icons and templates (Ultimate). Set `REUI_LICENSE_KEY` (see [cli.md](./cli.md)).
|
||||
|
||||
## Component API index
|
||||
|
||||
@@ -8,7 +8,7 @@ The core ReUI loop. The MCP tells you what to install and gives you the API; the
|
||||
|
||||
For everything else, call `search` with the user's intent. Pass structured hints whenever you can infer them - you are an LLM, so do the parsing the server cannot:
|
||||
|
||||
- `type`: `"component"` (one of the 17 building blocks), `"example"` (a c-\* use-case), `"block"` (a full page/section), `"icon"`.
|
||||
- `type`: `"component"` (one of the 20 building blocks), `"example"` (a c-\* use-case), `"block"` (a full page/section), `"icon"`.
|
||||
- `component`: the ReUI component the request implies (`"data-grid"`, `"kanban"`, ...).
|
||||
- `category`, `features` (e.g. `["sortable","pagination"]`), `free`.
|
||||
|
||||
@@ -40,7 +40,7 @@ Before writing code against any component an item uses:
|
||||
|
||||
Installing files is not the end, and redesigning them defeats the point. First note the project's **base** so you write the right API - read `components.json` -> `style` and take the segment before the first `-` (`base-nova` -> Base UI, `radix-nova` -> Radix UI), see [components.md](./components.md). After `add`:
|
||||
|
||||
1. **Read the added files**; keep the composition intact. For a block, verify the components are wired correctly (for `data-grid`: a `useReactTable` instance passed as `table`, `recordCount` set - see [components.md](./components.md)).
|
||||
1. **Read the added files**; keep the composition intact. For a block, verify the components are wired correctly (for `data-grid`: a `useTable({ features: dataGridFeatures, ... })` instance passed as `table`, `recordCount` set - see [components.md](./components.md)).
|
||||
2. **Replace demo data with the user's real data** via typed structures (see [adapting.md](./adapting.md)).
|
||||
3. **Fix icon imports** to the project's icon library (see [icons.md](./icons.md)).
|
||||
4. **Align styling** to semantic tokens and the active theme - no raw colors (see [styling.md](./styling.md)).
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"branches": ["main", "master"],
|
||||
"tagFormat": "v${version}",
|
||||
"plugins": [
|
||||
[
|
||||
"@semantic-release/commit-analyzer",
|
||||
{
|
||||
"preset": "conventionalcommits",
|
||||
"releaseRules": [
|
||||
{ "type": "feat", "release": "minor" },
|
||||
{ "type": "fix", "release": "patch" },
|
||||
{ "type": "perf", "release": "patch" },
|
||||
{ "type": "ci", "release": "patch" },
|
||||
{ "type": "refactor", "release": "patch" },
|
||||
{ "breaking": true, "release": "major" }
|
||||
]
|
||||
}
|
||||
],
|
||||
[
|
||||
"@semantic-release/release-notes-generator",
|
||||
{
|
||||
"preset": "conventionalcommits"
|
||||
}
|
||||
],
|
||||
[
|
||||
"@semantic-release/changelog",
|
||||
{
|
||||
"changelogFile": "CHANGELOG.md"
|
||||
}
|
||||
],
|
||||
[
|
||||
"@semantic-release/exec",
|
||||
{
|
||||
"successCmd": "echo ${nextRelease.version} > .release-version"
|
||||
}
|
||||
],
|
||||
[
|
||||
"@markwylde/semantic-release-gitea",
|
||||
{
|
||||
"giteaUrl": "https://git.shx.one",
|
||||
"assets": [
|
||||
{
|
||||
"path": "CHANGELOG.md",
|
||||
"label": "Changelog"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
# Cloudflare Domain Manager — Руководство для ИИ
|
||||
|
||||
## Описание
|
||||
|
||||
CFDM — self-hosted управление доменами, DNS и SSL через Cloudflare API. Группы доменов, сервисы, health-check, балансировка.
|
||||
|
||||
## Стек
|
||||
|
||||
- Monorepo: pnpm + turbo (`apps/*`, `packages/*`)
|
||||
- `apps/web` — Vite + React + TanStack + shadcn **base-nova** + ReUI Frame
|
||||
- `apps/api` — Fastify + Drizzle + SQLite
|
||||
- Packages: `@cfdm/ui`, `@cfdm/shared`, `@cfdm/db`
|
||||
|
||||
## Команды
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm --filter @cfdm/shared build
|
||||
pnpm --filter @cfdm/db build
|
||||
pnpm --filter @cfdm/api dev
|
||||
pnpm --filter web dev
|
||||
pnpm --filter web build
|
||||
```
|
||||
|
||||
## ReUI PRO
|
||||
|
||||
Surface: **frame** (`apps/web/src/lib/ui-surface.ts` → `UI_SURFACE = 'frame'`).
|
||||
Hierarchy: **ReUI PRO > shadcn**. Contract: [`docs/ui-design-contract.md`](docs/ui-design-contract.md).
|
||||
MCP `user-reui` primary + `plugin-shadcn-shadcn` primitives. CLI из `apps/web`.
|
||||
KPI/QuickActions: EvoBGP hybrid SoT (`KpiStatGrid`, `QuickActionGrid`) + `IconTile` `elevated` `size-10.5`.
|
||||
Docs: [Introduction](https://reui.io/docs) · [llms.txt](https://reui.io/llms.txt) · [MCP](https://reui.io/docs/mcp) · [Agent Skills](https://reui.io/docs/agent-skills).
|
||||
Skill: `.claude/skills/reui` (`668fb463eb`).
|
||||
|
||||
## Docs
|
||||
|
||||
[`docs/Home.md`](docs/Home.md), [`CONTRIBUTING.md`](CONTRIBUTING.md), [`docs/ui-design-contract.md`](docs/ui-design-contract.md), [`docs/releasing.md`](docs/releasing.md).
|
||||
|
||||
## CI/CD
|
||||
|
||||
Gitea Actions: [`.gitea/workflows`](.gitea/workflows) (`ci.yaml` / `cd.yaml` / `quality.yaml`). Образы — `docker buildx bake` из `deploy/docker` (runtime `node:22-alpine`, теги `cfdm` + `cloudflare-domain-manager`). Подробнее: [`.gitea/README.md`](.gitea/README.md).
|
||||
+6
-9
@@ -17,23 +17,23 @@ Types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`
|
||||
## Pull requests
|
||||
|
||||
- Target `develop` for features; `main` for release/hotfix
|
||||
- CI `test` job must pass
|
||||
- CI quality jobs (`web`, `api`) must pass
|
||||
- At least one approval
|
||||
- Rebase/merge when up to date with target branch
|
||||
- Delete branch after merge
|
||||
|
||||
## Versioning
|
||||
|
||||
- SemVer in [`VERSION`](VERSION)
|
||||
- Bump version in `release/*` or `hotfix/*` branches
|
||||
- Tag `vX.Y.Z` on `main` after release merge
|
||||
- SemVer через [semantic-release](https://semantic-release.gitbook.io/) на push в `main`
|
||||
- Не править версию вручную; тег `vX.Y.Z` ставит CI
|
||||
- Подробнее: [`docs/releasing.md`](docs/releasing.md)
|
||||
|
||||
## Branch protection (Gitea)
|
||||
|
||||
Configure for **main** and **develop**:
|
||||
|
||||
- Require pull request reviews
|
||||
- Require status checks (`test`)
|
||||
- Require status checks (`CI` / quality jobs `web`, `api`)
|
||||
- Require branches to be up to date
|
||||
- No force push, no deletion
|
||||
|
||||
@@ -54,7 +54,4 @@ pnpm --filter web dev
|
||||
|
||||
## Release process
|
||||
|
||||
1. `git checkout -b release/v0.2.0 develop`
|
||||
2. Bump `VERSION`, fix release issues
|
||||
3. PR to `main` → merge → tag `v0.2.0`
|
||||
4. Merge release branch back to `develop`
|
||||
Релизы делает workflow **CD** на push в `main` (semantic-release + bake). Не создавать ветки `release/*` и не bump'ать файлы версии вручную. См. [`docs/releasing.md`](docs/releasing.md).
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
ARG NODE_VERSION=22.23.0-bookworm-slim
|
||||
|
||||
FROM node:${NODE_VERSION} AS build
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends python3 make g++ \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& corepack enable
|
||||
|
||||
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml turbo.json ./
|
||||
COPY apps/web/package.json apps/web/
|
||||
COPY apps/api/package.json apps/api/
|
||||
COPY packages/ui/package.json packages/ui/
|
||||
COPY packages/shared/package.json packages/shared/
|
||||
COPY packages/db/package.json packages/db/
|
||||
RUN --mount=type=cache,id=pnpm-store,target=/root/.local/share/pnpm/store \
|
||||
pnpm install --frozen-lockfile
|
||||
|
||||
COPY apps/web apps/web
|
||||
COPY apps/api apps/api
|
||||
COPY packages/ui packages/ui
|
||||
COPY packages/shared packages/shared
|
||||
COPY packages/db packages/db
|
||||
|
||||
RUN pnpm turbo build --filter=web --filter=@cfdm/api \
|
||||
&& pnpm --filter @cfdm/api deploy --prod /out \
|
||||
&& cp -r apps/web/dist /out/static \
|
||||
&& rm -rf /out/src /out/test /out/.turbo \
|
||||
&& rm -rf /out/node_modules/@cfdm/db/src /out/node_modules/@cfdm/db/scripts /out/node_modules/@cfdm/db/.turbo \
|
||||
&& rm -rf /out/node_modules/@cfdm/shared/src /out/node_modules/@cfdm/shared/.turbo \
|
||||
&& find /out/dist /out/node_modules/@cfdm -type f \( -name '*.d.ts' -o -name '*.map' -o -name 'tsconfig*.json' -o -name 'vitest.config.ts' -o -name 'drizzle.config.ts' \) -delete
|
||||
|
||||
FROM node:${NODE_VERSION}
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production \
|
||||
STATIC_DIR=/app/static \
|
||||
DATABASE_URL=sqlite:/data/app.db \
|
||||
SERVER_PORT=8080
|
||||
|
||||
COPY --from=build /out ./
|
||||
|
||||
EXPOSE 8080
|
||||
VOLUME ["/data"]
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD ["node", "-e", "fetch('http://127.0.0.1:8080/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
|
||||
CMD ["node", "dist/server.js"]
|
||||
@@ -1,28 +0,0 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
ARG NODE_VERSION=22.23.0-bookworm-slim
|
||||
|
||||
FROM node:${NODE_VERSION} AS test
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends python3 make g++ \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& corepack enable
|
||||
|
||||
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml turbo.json ./
|
||||
COPY apps/web/package.json apps/web/
|
||||
COPY apps/api/package.json apps/api/
|
||||
COPY packages/ui/package.json packages/ui/
|
||||
COPY packages/shared/package.json packages/shared/
|
||||
COPY packages/db/package.json packages/db/
|
||||
RUN --mount=type=cache,id=pnpm-store,target=/root/.local/share/pnpm/store \
|
||||
pnpm install --frozen-lockfile
|
||||
|
||||
COPY apps/web apps/web
|
||||
COPY apps/api apps/api
|
||||
COPY packages/ui packages/ui
|
||||
COPY packages/shared packages/shared
|
||||
COPY packages/db packages/db
|
||||
|
||||
RUN pnpm turbo build --filter=@cfdm/shared --filter=@cfdm/db --filter=@cfdm/api
|
||||
CMD ["sh", "-c", "pnpm --filter @cfdm/api test && pnpm --filter web test"]
|
||||
@@ -28,7 +28,7 @@ Open http://localhost:8080 — default login `admin` / `admin` (dev only).
|
||||
- **Backend:** Node.js 22, Fastify 5, Drizzle ORM, SQLite (`apps/api`)
|
||||
- **Shared:** Zod schemas (`packages/shared`), DB layer (`packages/db`)
|
||||
- **Frontend:** pnpm monorepo (`apps/web` + `packages/ui`), React, Vite, TanStack Router/Query/Table, shadcn/ui (base-nova), Recharts
|
||||
- **CI:** Gitea Actions (Gitflow)
|
||||
- **CI:** Gitea Actions ([docs/releasing.md](docs/releasing.md)) — quality gates + semantic-release + bake (`cfdm` / `cloudflare-domain-manager`)
|
||||
|
||||
## Development
|
||||
|
||||
@@ -53,7 +53,7 @@ shadcn CLI: `cd apps/web && pnpm dlx shadcn@latest add <component>`
|
||||
|
||||
## Documentation
|
||||
|
||||
See [docs/Home.md](docs/Home.md) and [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
See [docs/Home.md](docs/Home.md), [docs/releasing.md](docs/releasing.md) and [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
## Load balancing & health checks
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ import { dnsRoutes } from "./routes/dns.js";
|
||||
import { subdomainRoutes } from "./routes/subdomains.js";
|
||||
import { certificateRoutes } from "./routes/certificates.js";
|
||||
import { syncRoutes } from "./routes/sync.js";
|
||||
import { originHealthCheckRoutes } from "./routes/origin-health-checks.js";
|
||||
import { healthCheckRoutes } from "./routes/health-check.js";
|
||||
import {
|
||||
domainMonitorRoutes,
|
||||
@@ -31,6 +32,7 @@ import {
|
||||
} from "./routes/domain-monitors.js";
|
||||
import { settingsRoutes } from "./routes/settings.js";
|
||||
import { integrationsVpsTrackerRoutes } from "./routes/integrations-vps-tracker.js";
|
||||
import { auditRoutes } from "./routes/audit.js";
|
||||
import * as certificateService from "./services/certificate-service.js";
|
||||
import * as healthCheckService from "./services/health-check-service.js";
|
||||
import * as serviceConfigService from "./services/service-config-service.js";
|
||||
@@ -80,9 +82,11 @@ export async function buildApp(opts: BuildAppOptions = {}) {
|
||||
await protectedApi.register(certificateRoutes);
|
||||
await protectedApi.register(syncRoutes);
|
||||
await protectedApi.register(healthCheckRoutes);
|
||||
await protectedApi.register(originHealthCheckRoutes);
|
||||
await protectedApi.register(domainMonitorRoutes);
|
||||
await protectedApi.register(notificationRoutes);
|
||||
await protectedApi.register(settingsRoutes);
|
||||
await protectedApi.register(auditRoutes);
|
||||
},
|
||||
{ prefix: "/api/v1" },
|
||||
);
|
||||
@@ -128,9 +132,11 @@ export async function buildApp(opts: BuildAppOptions = {}) {
|
||||
degradedFailures: config.healthDegradedFailures,
|
||||
downFailures: config.healthDownFailures,
|
||||
latencyWarnMs: config.healthLatencyWarnMs,
|
||||
successRecoveries: config.healthSuccessRecoveries,
|
||||
};
|
||||
const n = await healthCheckService.runAllChecks(app.db, {
|
||||
thresholds,
|
||||
probeGapMs: config.healthProbeGapMs,
|
||||
onStatusChange: async (target, prev, next) => {
|
||||
try {
|
||||
const label =
|
||||
|
||||
+37
-2
@@ -13,15 +13,35 @@ export interface AppConfig {
|
||||
healthCheckCron: string;
|
||||
healthDegradedFailures: number;
|
||||
healthDownFailures: number;
|
||||
healthSuccessRecoveries: number;
|
||||
healthLatencyWarnMs: number;
|
||||
/** Min pause between probes to different physical targets (same IP is probed once). */
|
||||
healthProbeGapMs: number;
|
||||
logLevel: string;
|
||||
/** Portal SSO — when true, require portal JWT with apps includes cfdm */
|
||||
authRequired: boolean;
|
||||
authIssuer: string;
|
||||
authPortalUrl: string;
|
||||
/** Bearer secret for POST {authPortalUrl}/api/v1/ingest/audit */
|
||||
authAuditIngestSecret: string | null;
|
||||
}
|
||||
|
||||
function boolEnv(v: string | undefined, fallback: boolean): boolean {
|
||||
if (v === undefined || v === "") return fallback;
|
||||
return v === "1" || v.toLowerCase() === "true";
|
||||
}
|
||||
|
||||
export function loadConfig(): AppConfig {
|
||||
const isProd = process.env.NODE_ENV === "production";
|
||||
const jwtSecret =
|
||||
process.env.AUTH_JWT_SECRET ??
|
||||
process.env.JWT_SECRET ??
|
||||
(isProd ? "" : "dev-secret-change-me");
|
||||
|
||||
return {
|
||||
databaseUrl: process.env.DATABASE_URL ?? "sqlite:data/app.db",
|
||||
cloudflareApiToken: (process.env.CLOUDFLARE_API_TOKEN ?? "").trim(),
|
||||
jwtSecret: process.env.JWT_SECRET ?? "dev-secret-change-me",
|
||||
jwtSecret: jwtSecret || "dev-secret-change-me",
|
||||
jwtTtlHours: Number(process.env.JWT_TTL_HOURS ?? "24") || 24,
|
||||
adminUsername: process.env.ADMIN_USERNAME ?? "admin",
|
||||
adminPasswordHash:
|
||||
@@ -31,12 +51,27 @@ export function loadConfig(): AppConfig {
|
||||
? resolve(process.env.STATIC_DIR)
|
||||
: null,
|
||||
certCheckCron: process.env.CERT_CHECK_CRON ?? "0 0 */6 * * *",
|
||||
healthCheckCron: process.env.HEALTH_CHECK_CRON ?? "*/30 * * * * *",
|
||||
// Default: every 2 minutes (was every 30s — hammered origins / anti-bot).
|
||||
healthCheckCron: process.env.HEALTH_CHECK_CRON ?? "0 */2 * * * *",
|
||||
healthDegradedFailures:
|
||||
Number(process.env.HEALTH_DEGRADED_FAILURES ?? "1") || 1,
|
||||
healthDownFailures: Number(process.env.HEALTH_DOWN_FAILURES ?? "2") || 2,
|
||||
healthSuccessRecoveries:
|
||||
Number(process.env.HEALTH_SUCCESS_RECOVERIES ?? "2") || 2,
|
||||
healthLatencyWarnMs:
|
||||
Number(process.env.HEALTH_LATENCY_WARN_MS ?? "1000") || 1000,
|
||||
healthProbeGapMs: Number(process.env.HEALTH_PROBE_GAP_MS ?? "2000") || 2000,
|
||||
logLevel: process.env.LOG_LEVEL ?? "info",
|
||||
authRequired: boolEnv(process.env.AUTH_REQUIRED, false),
|
||||
authIssuer:
|
||||
process.env.AUTH_ISSUER ?? process.env.ISSUER ?? "https://auth.shnt.top",
|
||||
authPortalUrl: (
|
||||
process.env.AUTH_PORTAL_URL ??
|
||||
process.env.VITE_AUTH_PORTAL_URL ??
|
||||
"http://localhost:5175"
|
||||
).replace(/\/$/, ""),
|
||||
authAuditIngestSecret:
|
||||
process.env.AUTH_AUDIT_INGEST_SECRET?.trim() ||
|
||||
(!isProd ? "dev-audit-ingest-secret" : null),
|
||||
};
|
||||
}
|
||||
+46
-2
@@ -8,6 +8,14 @@ export type ErrorCode =
|
||||
| "FORBIDDEN"
|
||||
| "CONFLICT"
|
||||
| "CLOUDFLARE_ERROR"
|
||||
| "DNS_UPDATE_FAILED"
|
||||
| "HEALTHCHECK_CREATE_FAILED"
|
||||
| "ZONE_NOT_FOUND"
|
||||
| "INVALID_IP"
|
||||
| "INVALID_HOSTNAME"
|
||||
| "RATE_LIMITED"
|
||||
| "CLOUDFLARE_AUTH_FAILED"
|
||||
| "SYNC_FAILED"
|
||||
| "INTERNAL_ERROR";
|
||||
|
||||
export class AppError extends Error {
|
||||
@@ -32,8 +40,8 @@ export class AppError extends Error {
|
||||
return new AppError("UNAUTHORIZED", "unauthorized", 401);
|
||||
}
|
||||
|
||||
static forbidden() {
|
||||
return new AppError("FORBIDDEN", "forbidden", 403);
|
||||
static forbidden(message = "forbidden") {
|
||||
return new AppError("FORBIDDEN", message, 403);
|
||||
}
|
||||
|
||||
static conflict(message: string) {
|
||||
@@ -44,6 +52,42 @@ export class AppError extends Error {
|
||||
return new AppError("CLOUDFLARE_ERROR", message, 502);
|
||||
}
|
||||
|
||||
static dnsUpdateFailed(message: string) {
|
||||
return new AppError(
|
||||
"DNS_UPDATE_FAILED",
|
||||
message,
|
||||
502,
|
||||
);
|
||||
}
|
||||
|
||||
static healthcheckCreateFailed(message: string) {
|
||||
return new AppError("HEALTHCHECK_CREATE_FAILED", message, 502);
|
||||
}
|
||||
|
||||
static zoneNotFound(message = "зона Cloudflare не найдена") {
|
||||
return new AppError("ZONE_NOT_FOUND", message, 404);
|
||||
}
|
||||
|
||||
static invalidIp(message = "Некорректный IP-адрес") {
|
||||
return new AppError("INVALID_IP", message, 400);
|
||||
}
|
||||
|
||||
static invalidHostname(message = "Некорректное имя хоста") {
|
||||
return new AppError("INVALID_HOSTNAME", message, 400);
|
||||
}
|
||||
|
||||
static rateLimited(message = "Cloudflare временно ограничил запросы. Повторите попытку.") {
|
||||
return new AppError("RATE_LIMITED", message, 429);
|
||||
}
|
||||
|
||||
static cloudflareAuthFailed(message = "Cloudflare отклонил токен доступа") {
|
||||
return new AppError("CLOUDFLARE_AUTH_FAILED", message, 401);
|
||||
}
|
||||
|
||||
static syncFailed(message: string) {
|
||||
return new AppError("SYNC_FAILED", message, 502);
|
||||
}
|
||||
|
||||
static internal(message: string) {
|
||||
return new AppError("INTERNAL_ERROR", message, 500);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { FastifyInstance, FastifyRequest } from "fastify";
|
||||
import { appendAudit, type AppendAuditInput } from "@cfdm/db";
|
||||
import { pushAuditEvents } from "../services/audit-portal-push.js";
|
||||
|
||||
export function clientIp(request: FastifyRequest): string | null {
|
||||
const forwarded = request.headers["x-forwarded-for"];
|
||||
if (typeof forwarded === "string" && forwarded.trim()) {
|
||||
return forwarded.split(",")[0]?.trim() ?? null;
|
||||
}
|
||||
return request.ip ?? null;
|
||||
}
|
||||
|
||||
export function actorFromRequest(
|
||||
request: FastifyRequest,
|
||||
): Pick<AppendAuditInput, "actorUserId" | "actorEmail" | "actorName"> {
|
||||
const u = request.authUser;
|
||||
if (u) {
|
||||
return {
|
||||
actorUserId: u.id,
|
||||
actorEmail: u.email || null,
|
||||
actorName: u.name || null,
|
||||
};
|
||||
}
|
||||
|
||||
const payload = request.user;
|
||||
if (payload?.sub) {
|
||||
return {
|
||||
actorUserId: String(payload.sub),
|
||||
actorEmail: payload.email ? String(payload.email) : null,
|
||||
actorName: payload.name ? String(payload.name) : null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
actorUserId: null,
|
||||
actorEmail: null,
|
||||
actorName: null,
|
||||
};
|
||||
}
|
||||
|
||||
type RecordAuditInput = Omit<
|
||||
AppendAuditInput,
|
||||
| "sourceApp"
|
||||
| "eventId"
|
||||
| "ip"
|
||||
| "actorUserId"
|
||||
| "actorEmail"
|
||||
| "actorName"
|
||||
>;
|
||||
|
||||
/** Local append + optional async push to auth-portal ingest. */
|
||||
export function recordAudit(
|
||||
app: FastifyInstance,
|
||||
request: FastifyRequest,
|
||||
input: RecordAuditInput,
|
||||
): void {
|
||||
const eventId = randomUUID();
|
||||
const actor = actorFromRequest(request);
|
||||
const ip = clientIp(request);
|
||||
const createdAt = input.createdAt ?? new Date().toISOString();
|
||||
|
||||
const full: AppendAuditInput = {
|
||||
...input,
|
||||
...actor,
|
||||
eventId,
|
||||
sourceApp: "cfdm",
|
||||
ip,
|
||||
createdAt,
|
||||
};
|
||||
|
||||
try {
|
||||
appendAudit(app.db, full);
|
||||
} catch (err) {
|
||||
app.log.warn({ err }, "audit_log append failed");
|
||||
}
|
||||
|
||||
const secret = app.config.authAuditIngestSecret;
|
||||
const portalUrl = app.config.authPortalUrl;
|
||||
if (!secret || !portalUrl) return;
|
||||
|
||||
void pushAuditEvents(portalUrl, secret, [
|
||||
{
|
||||
event_id: eventId,
|
||||
source_app: "cfdm",
|
||||
action: input.action,
|
||||
severity: input.severity,
|
||||
actor_user_id: actor.actorUserId,
|
||||
actor_email: actor.actorEmail,
|
||||
actor_name: actor.actorName,
|
||||
target_type: input.targetType,
|
||||
target_id: input.targetId,
|
||||
summary: input.summary,
|
||||
details: input.details,
|
||||
ip,
|
||||
created_at: createdAt,
|
||||
},
|
||||
]).catch((err) => {
|
||||
app.log.warn({ err, eventId }, "audit portal push failed");
|
||||
});
|
||||
}
|
||||
+57
-125
@@ -1,152 +1,84 @@
|
||||
import type {
|
||||
CfDnsRecord,
|
||||
CfHealthCheck,
|
||||
CfZone,
|
||||
CreateDnsRecordPayload,
|
||||
PatchDnsRecordPayload,
|
||||
} from "@cfdm/shared";
|
||||
import { AppError } from "../errors.js";
|
||||
import { withRetry, parseRetryAfter } from "./cf-retry.js";
|
||||
import { createDnsAdapter } from "./cloudflare/dns-service.js";
|
||||
import { createHealthCheckAdapter, type CfHealthCheckPayload } from "./cloudflare/healthcheck-service.js";
|
||||
import { createZoneAdapter } from "./cloudflare/zone-service.js";
|
||||
|
||||
const BASE_URL = "https://api.cloudflare.com/client/v4";
|
||||
|
||||
interface CfResponse<T> {
|
||||
success: boolean;
|
||||
result?: T;
|
||||
errors?: Array<{ code: number; message: string }>;
|
||||
}
|
||||
export type { CfHealthCheckPayload };
|
||||
|
||||
export class CloudflareClient {
|
||||
constructor(private readonly token: string) {}
|
||||
private readonly zones;
|
||||
private readonly dns;
|
||||
private readonly healthchecks;
|
||||
|
||||
private async handleResponse<T>(
|
||||
response: Response,
|
||||
operation: string,
|
||||
): Promise<T> {
|
||||
if (response.status === 429) {
|
||||
const wait = parseRetryAfter(response.headers) ?? 5000;
|
||||
throw AppError.cloudflare(`rate limited, retry after ${wait}ms`);
|
||||
}
|
||||
|
||||
const body = (await response.json()) as CfResponse<T>;
|
||||
if (!body.success) {
|
||||
const msg =
|
||||
body.errors?.map((e) => e.message).join("; ") ??
|
||||
"unknown cloudflare error";
|
||||
throw AppError.cloudflare(`${operation}: ${msg}`);
|
||||
}
|
||||
if (body.result === undefined) {
|
||||
throw AppError.cloudflare(`${operation}: empty result`);
|
||||
}
|
||||
return body.result;
|
||||
constructor(token: string) {
|
||||
this.zones = createZoneAdapter(token);
|
||||
this.dns = createDnsAdapter(token);
|
||||
this.healthchecks = createHealthCheckAdapter(token);
|
||||
}
|
||||
|
||||
async listZones(): Promise<CfZone[]> {
|
||||
return withRetry(async () => {
|
||||
const all: CfZone[] = [];
|
||||
let page = 1;
|
||||
while (true) {
|
||||
const url = new URL(`${BASE_URL}/zones`);
|
||||
url.searchParams.set("per_page", "50");
|
||||
url.searchParams.set("page", String(page));
|
||||
const response = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${this.token}` },
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
});
|
||||
if (response.status >= 500 || response.status === 429) {
|
||||
throw AppError.cloudflare(String(response.status));
|
||||
}
|
||||
const batch = await this.handleResponse<CfZone[]>(
|
||||
response,
|
||||
"list_zones",
|
||||
);
|
||||
if (batch.length === 0) break;
|
||||
all.push(...batch);
|
||||
if (batch.length < 50) break;
|
||||
page += 1;
|
||||
}
|
||||
return all;
|
||||
});
|
||||
listZones(): Promise<CfZone[]> {
|
||||
return this.zones.listZones();
|
||||
}
|
||||
|
||||
async getZone(zoneId: string): Promise<CfZone> {
|
||||
const response = await fetch(`${BASE_URL}/zones/${zoneId}`, {
|
||||
headers: { Authorization: `Bearer ${this.token}` },
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
});
|
||||
return this.handleResponse(response, "get_zone");
|
||||
getZone(zoneId: string): Promise<CfZone> {
|
||||
return this.zones.getZone(zoneId);
|
||||
}
|
||||
|
||||
async listDnsRecords(zoneId: string): Promise<CfDnsRecord[]> {
|
||||
return withRetry(async () => {
|
||||
const all: CfDnsRecord[] = [];
|
||||
let page = 1;
|
||||
while (page <= 50) {
|
||||
const url = new URL(`${BASE_URL}/zones/${zoneId}/dns_records`);
|
||||
url.searchParams.set("per_page", "100");
|
||||
url.searchParams.set("page", String(page));
|
||||
const response = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${this.token}` },
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
});
|
||||
if (response.status >= 500 || response.status === 429) {
|
||||
throw AppError.cloudflare(String(response.status));
|
||||
}
|
||||
const batch = await this.handleResponse<CfDnsRecord[]>(
|
||||
response,
|
||||
"list_dns_records",
|
||||
);
|
||||
if (batch.length === 0) break;
|
||||
all.push(...batch);
|
||||
page += 1;
|
||||
}
|
||||
return all;
|
||||
});
|
||||
listDnsRecords(zoneId: string): Promise<CfDnsRecord[]> {
|
||||
return this.dns.listDnsRecords(zoneId);
|
||||
}
|
||||
|
||||
async createDnsRecord(
|
||||
zoneId: string,
|
||||
payload: CreateDnsRecordPayload,
|
||||
): Promise<CfDnsRecord> {
|
||||
const response = await fetch(`${BASE_URL}/zones/${zoneId}/dns_records`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
});
|
||||
return this.handleResponse(response, "create_dns_record");
|
||||
createDnsRecord(zoneId: string, payload: CreateDnsRecordPayload): Promise<CfDnsRecord> {
|
||||
return this.dns.createDnsRecord(zoneId, payload);
|
||||
}
|
||||
|
||||
async updateDnsRecord(
|
||||
updateDnsRecord(
|
||||
zoneId: string,
|
||||
recordId: string,
|
||||
payload: CreateDnsRecordPayload,
|
||||
): Promise<CfDnsRecord> {
|
||||
const response = await fetch(
|
||||
`${BASE_URL}/zones/${zoneId}/dns_records/${recordId}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
},
|
||||
);
|
||||
return this.handleResponse(response, "update_dns_record");
|
||||
return this.dns.updateDnsRecord(zoneId, recordId, payload);
|
||||
}
|
||||
|
||||
async deleteDnsRecord(zoneId: string, recordId: string): Promise<void> {
|
||||
const response = await fetch(
|
||||
`${BASE_URL}/zones/${zoneId}/dns_records/${recordId}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: { Authorization: `Bearer ${this.token}` },
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
},
|
||||
);
|
||||
await this.handleResponse(response, "delete_dns_record");
|
||||
patchDnsRecord(
|
||||
zoneId: string,
|
||||
recordId: string,
|
||||
payload: PatchDnsRecordPayload,
|
||||
): Promise<CfDnsRecord> {
|
||||
return this.dns.patchDnsRecord(zoneId, recordId, payload);
|
||||
}
|
||||
|
||||
deleteDnsRecord(zoneId: string, recordId: string): Promise<void> {
|
||||
return this.dns.deleteDnsRecord(zoneId, recordId);
|
||||
}
|
||||
|
||||
listHealthChecks(zoneId: string): Promise<CfHealthCheck[]> {
|
||||
return this.healthchecks.listHealthChecks(zoneId);
|
||||
}
|
||||
|
||||
getHealthCheck(zoneId: string, id: string): Promise<CfHealthCheck> {
|
||||
return this.healthchecks.getHealthCheck(zoneId, id);
|
||||
}
|
||||
|
||||
createHealthCheck(zoneId: string, payload: CfHealthCheckPayload): Promise<CfHealthCheck> {
|
||||
return this.healthchecks.createHealthCheck(zoneId, payload);
|
||||
}
|
||||
|
||||
updateHealthCheck(
|
||||
zoneId: string,
|
||||
id: string,
|
||||
payload: CfHealthCheckPayload,
|
||||
): Promise<CfHealthCheck> {
|
||||
return this.healthchecks.updateHealthCheck(zoneId, id, payload);
|
||||
}
|
||||
|
||||
deleteHealthCheck(zoneId: string, id: string): Promise<void> {
|
||||
return this.healthchecks.deleteHealthCheck(zoneId, id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import type { CfDnsRecord, CreateDnsRecordPayload, PatchDnsRecordPayload } from "@cfdm/shared";
|
||||
import { withRetry } from "../cf-retry.js";
|
||||
import { CF_API_BASE, handleCfResponse, mapCloudflareFailure } from "./http.js";
|
||||
|
||||
export function createDnsAdapter(token: string) {
|
||||
return {
|
||||
async listDnsRecords(zoneId: string): Promise<CfDnsRecord[]> {
|
||||
return withRetry(async () => {
|
||||
const all: CfDnsRecord[] = [];
|
||||
let page = 1;
|
||||
while (page <= 50) {
|
||||
const url = new URL(`${CF_API_BASE}/zones/${zoneId}/dns_records`);
|
||||
url.searchParams.set("per_page", "100");
|
||||
url.searchParams.set("page", String(page));
|
||||
const response = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
});
|
||||
if (response.status >= 500 || response.status === 429) {
|
||||
throw mapCloudflareFailure(
|
||||
"list_dns_records",
|
||||
response.status,
|
||||
String(response.status),
|
||||
);
|
||||
}
|
||||
const batch = await handleCfResponse<CfDnsRecord[]>(
|
||||
response,
|
||||
"list_dns_records",
|
||||
);
|
||||
if (batch.length === 0) break;
|
||||
all.push(...batch);
|
||||
page += 1;
|
||||
}
|
||||
return all;
|
||||
});
|
||||
},
|
||||
|
||||
async createDnsRecord(
|
||||
zoneId: string,
|
||||
payload: CreateDnsRecordPayload,
|
||||
): Promise<CfDnsRecord> {
|
||||
const response = await fetch(`${CF_API_BASE}/zones/${zoneId}/dns_records`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
});
|
||||
return handleCfResponse(response, "create_dns_record");
|
||||
},
|
||||
|
||||
async updateDnsRecord(
|
||||
zoneId: string,
|
||||
recordId: string,
|
||||
payload: CreateDnsRecordPayload,
|
||||
): Promise<CfDnsRecord> {
|
||||
const response = await fetch(
|
||||
`${CF_API_BASE}/zones/${zoneId}/dns_records/${recordId}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
},
|
||||
);
|
||||
return handleCfResponse(response, "update_dns_record");
|
||||
},
|
||||
|
||||
async patchDnsRecord(
|
||||
zoneId: string,
|
||||
recordId: string,
|
||||
payload: PatchDnsRecordPayload,
|
||||
): Promise<CfDnsRecord> {
|
||||
const response = await fetch(
|
||||
`${CF_API_BASE}/zones/${zoneId}/dns_records/${recordId}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
},
|
||||
);
|
||||
return handleCfResponse(response, "patch_dns_record");
|
||||
},
|
||||
|
||||
async deleteDnsRecord(zoneId: string, recordId: string): Promise<void> {
|
||||
const response = await fetch(
|
||||
`${CF_API_BASE}/zones/${zoneId}/dns_records/${recordId}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
},
|
||||
);
|
||||
await handleCfResponse(response, "delete_dns_record");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import type { CfHealthCheck } from "@cfdm/shared";
|
||||
import { CF_API_BASE, handleCfResponse } from "./http.js";
|
||||
|
||||
export interface CfHealthCheckHttpConfig {
|
||||
method?: string;
|
||||
path?: string;
|
||||
expected_codes?: string[];
|
||||
header?: Record<string, string[]>;
|
||||
port?: number;
|
||||
follow_redirects?: boolean;
|
||||
allow_insecure?: boolean;
|
||||
}
|
||||
|
||||
export interface CfHealthCheckTcpConfig {
|
||||
method?: "connection_established";
|
||||
port?: number;
|
||||
}
|
||||
|
||||
export interface CfHealthCheckPayload {
|
||||
address: string;
|
||||
name: string;
|
||||
type?: "HTTP" | "HTTPS" | "TCP";
|
||||
description?: string;
|
||||
interval?: number;
|
||||
timeout?: number;
|
||||
retries?: number;
|
||||
consecutive_fails?: number;
|
||||
consecutive_successes?: number;
|
||||
suspended?: boolean;
|
||||
check_regions?: string[];
|
||||
http_config?: CfHealthCheckHttpConfig;
|
||||
tcp_config?: CfHealthCheckTcpConfig;
|
||||
}
|
||||
|
||||
export function createHealthCheckAdapter(token: string) {
|
||||
return {
|
||||
async listHealthChecks(zoneId: string): Promise<CfHealthCheck[]> {
|
||||
const response = await fetch(
|
||||
`${CF_API_BASE}/zones/${zoneId}/healthchecks`,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
},
|
||||
);
|
||||
return handleCfResponse(response, "list_healthchecks");
|
||||
},
|
||||
|
||||
async getHealthCheck(zoneId: string, id: string): Promise<CfHealthCheck> {
|
||||
const response = await fetch(
|
||||
`${CF_API_BASE}/zones/${zoneId}/healthchecks/${id}`,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
},
|
||||
);
|
||||
return handleCfResponse(response, "get_healthcheck");
|
||||
},
|
||||
|
||||
async createHealthCheck(
|
||||
zoneId: string,
|
||||
payload: CfHealthCheckPayload,
|
||||
): Promise<CfHealthCheck> {
|
||||
const response = await fetch(
|
||||
`${CF_API_BASE}/zones/${zoneId}/healthchecks`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
},
|
||||
);
|
||||
return handleCfResponse(response, "create_healthcheck");
|
||||
},
|
||||
|
||||
async updateHealthCheck(
|
||||
zoneId: string,
|
||||
id: string,
|
||||
payload: CfHealthCheckPayload,
|
||||
): Promise<CfHealthCheck> {
|
||||
const response = await fetch(
|
||||
`${CF_API_BASE}/zones/${zoneId}/healthchecks/${id}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
},
|
||||
);
|
||||
return handleCfResponse(response, "update_healthcheck");
|
||||
},
|
||||
|
||||
async deleteHealthCheck(zoneId: string, id: string): Promise<void> {
|
||||
const response = await fetch(
|
||||
`${CF_API_BASE}/zones/${zoneId}/healthchecks/${id}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
},
|
||||
);
|
||||
await handleCfResponse(response, "delete_healthcheck");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { CfDnsRecord } from "@cfdm/shared";
|
||||
import { AppError } from "../../errors.js";
|
||||
import { parseRetryAfter } from "../cf-retry.js";
|
||||
|
||||
export const CF_API_BASE = "https://api.cloudflare.com/client/v4";
|
||||
|
||||
export interface CfResponse<T> {
|
||||
success: boolean;
|
||||
result?: T;
|
||||
errors?: Array<{ code: number; message: string }>;
|
||||
}
|
||||
|
||||
export function mapCloudflareFailure(
|
||||
operation: string,
|
||||
status: number,
|
||||
message: string,
|
||||
): AppError {
|
||||
const lower = message.toLowerCase();
|
||||
if (status === 401 || status === 403 || lower.includes("authentication")) {
|
||||
return AppError.cloudflareAuthFailed(
|
||||
"Cloudflare отклонил токен. Проверьте CLOUDFLARE_API_TOKEN.",
|
||||
);
|
||||
}
|
||||
if (status === 429 || lower.includes("rate limit")) {
|
||||
return AppError.rateLimited();
|
||||
}
|
||||
if (lower.includes("zone") && (lower.includes("not found") || status === 404)) {
|
||||
return AppError.zoneNotFound();
|
||||
}
|
||||
if (
|
||||
operation.includes("healthcheck") &&
|
||||
(lower.includes("plan") ||
|
||||
lower.includes("not entitled") ||
|
||||
lower.includes("not allowed") ||
|
||||
lower.includes("permission"))
|
||||
) {
|
||||
return AppError.healthcheckCreateFailed(
|
||||
"Cloudflare Health Checks недоступны для этой зоны. Используйте локальные проверки.",
|
||||
);
|
||||
}
|
||||
if (operation.includes("dns") || operation.includes("dns_record")) {
|
||||
return AppError.dnsUpdateFailed(`Не удалось обновить DNS в Cloudflare: ${message}`);
|
||||
}
|
||||
return AppError.cloudflare(`${operation}: ${message}`);
|
||||
}
|
||||
|
||||
export async function handleCfResponse<T>(
|
||||
response: Response,
|
||||
operation: string,
|
||||
): Promise<T> {
|
||||
if (response.status === 429) {
|
||||
const wait = parseRetryAfter(response.headers) ?? 5000;
|
||||
throw AppError.rateLimited(
|
||||
`Cloudflare временно ограничил запросы. Повторите через ${Math.ceil(wait / 1000)} с.`,
|
||||
);
|
||||
}
|
||||
|
||||
const body = (await response.json()) as CfResponse<T>;
|
||||
if (!body.success) {
|
||||
const msg =
|
||||
body.errors?.map((e) => e.message).join("; ") ?? "unknown cloudflare error";
|
||||
throw mapCloudflareFailure(operation, response.status, msg);
|
||||
}
|
||||
if (body.result === undefined) {
|
||||
throw mapCloudflareFailure(operation, response.status, "empty result");
|
||||
}
|
||||
return body.result;
|
||||
}
|
||||
|
||||
export async function cfRequest<T>(
|
||||
token: string,
|
||||
path: string,
|
||||
operation: string,
|
||||
init: RequestInit = {},
|
||||
): Promise<T> {
|
||||
const response = await fetch(`${CF_API_BASE}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
...(init.body ? { "Content-Type": "application/json" } : {}),
|
||||
...init.headers,
|
||||
},
|
||||
signal: init.signal ?? AbortSignal.timeout(30_000),
|
||||
});
|
||||
if (response.status >= 500 || response.status === 429) {
|
||||
throw mapCloudflareFailure(operation, response.status, String(response.status));
|
||||
}
|
||||
return handleCfResponse<T>(response, operation);
|
||||
}
|
||||
|
||||
export type DnsRecordResult = CfDnsRecord;
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { CfZone } from "@cfdm/shared";
|
||||
import { withRetry } from "../cf-retry.js";
|
||||
import { CF_API_BASE, handleCfResponse, mapCloudflareFailure } from "./http.js";
|
||||
|
||||
export function createZoneAdapter(token: string) {
|
||||
return {
|
||||
async listZones(): Promise<CfZone[]> {
|
||||
return withRetry(async () => {
|
||||
const all: CfZone[] = [];
|
||||
let page = 1;
|
||||
while (true) {
|
||||
const url = new URL(`${CF_API_BASE}/zones`);
|
||||
url.searchParams.set("per_page", "50");
|
||||
url.searchParams.set("page", String(page));
|
||||
const response = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
});
|
||||
if (response.status >= 500 || response.status === 429) {
|
||||
throw mapCloudflareFailure("list_zones", response.status, String(response.status));
|
||||
}
|
||||
const batch = await handleCfResponse<CfZone[]>(response, "list_zones");
|
||||
if (batch.length === 0) break;
|
||||
all.push(...batch);
|
||||
if (batch.length < 50) break;
|
||||
page += 1;
|
||||
}
|
||||
return all;
|
||||
});
|
||||
},
|
||||
|
||||
async getZone(zoneId: string): Promise<CfZone> {
|
||||
const response = await fetch(`${CF_API_BASE}/zones/${zoneId}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
});
|
||||
return handleCfResponse(response, "get_zone");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* Portal JWT RBAC helpers (mirrors @authportal/shared hasPermission).
|
||||
* Format: cfdm:<section>:<read|write|admin>
|
||||
*/
|
||||
|
||||
export type AuthUser = {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
apps: string[];
|
||||
permissions: string[];
|
||||
isAdmin?: boolean;
|
||||
};
|
||||
|
||||
export function hasPermission(
|
||||
granted: readonly string[],
|
||||
required: string,
|
||||
): boolean {
|
||||
if (granted.includes(required)) return true;
|
||||
const parts = required.split(":");
|
||||
if (parts.length !== 3) return false;
|
||||
const [app, section, action] = parts;
|
||||
if (action === "read") {
|
||||
return (
|
||||
granted.includes(`${app}:${section}:write`) ||
|
||||
granted.includes(`${app}:${section}:admin`)
|
||||
);
|
||||
}
|
||||
if (action === "write") {
|
||||
return granted.includes(`${app}:${section}:admin`);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
type Rule = {
|
||||
methods: string[];
|
||||
match: (path: string) => boolean;
|
||||
permission: string;
|
||||
};
|
||||
|
||||
const RULES: Rule[] = [
|
||||
{
|
||||
methods: ["GET"],
|
||||
match: (p) =>
|
||||
p.startsWith("/api/v1/domains") ||
|
||||
p.startsWith("/api/v1/domain-monitors") ||
|
||||
p === "/api/v1/domain-monitors",
|
||||
permission: "cfdm:domains:read",
|
||||
},
|
||||
{
|
||||
methods: ["POST", "PUT", "PATCH", "DELETE"],
|
||||
match: (p) =>
|
||||
p.startsWith("/api/v1/domains") ||
|
||||
p.startsWith("/api/v1/domain-monitors"),
|
||||
permission: "cfdm:domains:write",
|
||||
},
|
||||
{
|
||||
methods: ["GET"],
|
||||
match: (p) =>
|
||||
p.startsWith("/api/v1/dns") || p.startsWith("/api/v1/subdomains"),
|
||||
permission: "cfdm:dns:read",
|
||||
},
|
||||
{
|
||||
methods: ["POST", "PUT", "PATCH", "DELETE"],
|
||||
match: (p) =>
|
||||
p.startsWith("/api/v1/dns") || p.startsWith("/api/v1/subdomains"),
|
||||
permission: "cfdm:dns:write",
|
||||
},
|
||||
{
|
||||
methods: ["GET"],
|
||||
match: (p) => p.startsWith("/api/v1/certificates"),
|
||||
permission: "cfdm:certificates:read",
|
||||
},
|
||||
{
|
||||
methods: ["POST", "PUT", "PATCH", "DELETE"],
|
||||
match: (p) => p.startsWith("/api/v1/certificates"),
|
||||
permission: "cfdm:certificates:write",
|
||||
},
|
||||
{
|
||||
methods: ["GET"],
|
||||
match: (p) =>
|
||||
p.startsWith("/api/v1/groups") ||
|
||||
p.startsWith("/api/v1/service-groups"),
|
||||
permission: "cfdm:groups:read",
|
||||
},
|
||||
{
|
||||
methods: ["POST", "PUT", "PATCH", "DELETE"],
|
||||
match: (p) =>
|
||||
p.startsWith("/api/v1/groups") ||
|
||||
p.startsWith("/api/v1/service-groups"),
|
||||
permission: "cfdm:groups:write",
|
||||
},
|
||||
{
|
||||
methods: ["GET"],
|
||||
match: (p) =>
|
||||
p.startsWith("/api/v1/services") ||
|
||||
p.startsWith("/api/v1/service-bindings") ||
|
||||
p.startsWith("/api/v1/health-checks") ||
|
||||
p === "/api/v1/ops-summary",
|
||||
permission: "cfdm:services:read",
|
||||
},
|
||||
{
|
||||
methods: ["POST", "PUT", "PATCH", "DELETE"],
|
||||
match: (p) =>
|
||||
p.startsWith("/api/v1/services") ||
|
||||
p.startsWith("/api/v1/service-bindings") ||
|
||||
p.startsWith("/api/v1/health-checks"),
|
||||
permission: "cfdm:services:write",
|
||||
},
|
||||
{
|
||||
methods: ["GET", "POST"],
|
||||
match: (p) => p.startsWith("/api/v1/sync"),
|
||||
permission: "cfdm:domains:write",
|
||||
},
|
||||
{
|
||||
methods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
|
||||
match: (p) =>
|
||||
p.startsWith("/api/v1/settings") ||
|
||||
p.startsWith("/api/v1/notifications") ||
|
||||
p.startsWith("/api/v1/health-check"),
|
||||
permission: "cfdm:settings:admin",
|
||||
},
|
||||
{
|
||||
methods: ["GET"],
|
||||
match: (p) => p.startsWith("/api/v1/audit"),
|
||||
permission: "cfdm:settings:admin",
|
||||
},
|
||||
];
|
||||
|
||||
/** Resolve required permission for method+path, or null if public / unknown. */
|
||||
export function permissionForRequest(
|
||||
method: string,
|
||||
path: string,
|
||||
): string | null {
|
||||
const m = method.toUpperCase();
|
||||
const pathname = path.split("?")[0] ?? path;
|
||||
for (const rule of RULES) {
|
||||
if (!rule.methods.includes(m)) continue;
|
||||
if (rule.match(pathname)) return rule.permission;
|
||||
}
|
||||
// Default: any authenticated cfdm user for unmatched /api/v1/*
|
||||
if (pathname.startsWith("/api/v1/")) return "cfdm:domains:read";
|
||||
return null;
|
||||
}
|
||||
@@ -1,28 +1,126 @@
|
||||
import type { FastifyInstance, FastifyRequest } from "fastify";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import fp from "fastify-plugin";
|
||||
import type { AppConfig } from "../config.js";
|
||||
import { AppError } from "../errors.js";
|
||||
import {
|
||||
hasPermission,
|
||||
permissionForRequest,
|
||||
type AuthUser,
|
||||
} from "../lib/permissions.js";
|
||||
|
||||
declare module "fastify" {
|
||||
interface FastifyRequest {
|
||||
authUser?: AuthUser;
|
||||
}
|
||||
}
|
||||
|
||||
declare module "@fastify/jwt" {
|
||||
interface FastifyJWT {
|
||||
payload: {
|
||||
sub: string;
|
||||
email?: string;
|
||||
name?: string;
|
||||
apps?: string[];
|
||||
permissions?: string[];
|
||||
is_admin?: boolean;
|
||||
iss?: string;
|
||||
exp?: number;
|
||||
};
|
||||
user: {
|
||||
sub: string;
|
||||
email?: string;
|
||||
name?: string;
|
||||
apps?: string[];
|
||||
permissions?: string[];
|
||||
is_admin?: boolean;
|
||||
iss?: string;
|
||||
exp?: number;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function authPlugin(
|
||||
app: FastifyInstance,
|
||||
opts: { config: AppConfig },
|
||||
) {
|
||||
const { config } = opts;
|
||||
|
||||
if (config.authRequired && (!config.jwtSecret || config.jwtSecret.length < 8)) {
|
||||
throw new Error(
|
||||
"AUTH_JWT_SECRET / JWT_SECRET required when AUTH_REQUIRED=true",
|
||||
);
|
||||
}
|
||||
|
||||
await app.register(import("@fastify/jwt"), {
|
||||
secret: opts.config.jwtSecret,
|
||||
secret: config.jwtSecret,
|
||||
...(config.authRequired
|
||||
? {
|
||||
verify: {
|
||||
allowedIss: [config.authIssuer],
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
|
||||
if (config.authRequired) {
|
||||
app.log.info(
|
||||
{ issuer: config.authIssuer, portal: config.authPortalUrl },
|
||||
"AUTH_REQUIRED=true — portal JWT middleware enabled",
|
||||
);
|
||||
} else {
|
||||
app.log.info("AUTH_REQUIRED=false — local JWT / open protected routes with requireAuth");
|
||||
}
|
||||
}
|
||||
|
||||
export async function requireAuth(request: FastifyRequest): Promise<void> {
|
||||
/**
|
||||
* Protect /api/v1 routes.
|
||||
* - AUTH_REQUIRED=false: Bearer JWT from local login (legacy admin).
|
||||
* - AUTH_REQUIRED=true: portal JWT with apps.includes('cfdm') + permissions.
|
||||
*/
|
||||
export async function requireAuth(
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
): Promise<void> {
|
||||
const config = request.server.config;
|
||||
const authHeader = request.headers.authorization ?? "";
|
||||
const token = authHeader.startsWith("Bearer ")
|
||||
? authHeader.slice(7)
|
||||
: "";
|
||||
if (!token) throw AppError.unauthorized();
|
||||
|
||||
try {
|
||||
await request.jwtVerify();
|
||||
} catch {
|
||||
throw AppError.unauthorized();
|
||||
}
|
||||
|
||||
if (!config.authRequired) {
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = request.user;
|
||||
const apps = Array.isArray(payload.apps) ? payload.apps.map(String) : [];
|
||||
const permissions = Array.isArray(payload.permissions)
|
||||
? payload.permissions.map(String)
|
||||
: [];
|
||||
|
||||
if (!apps.includes("cfdm")) {
|
||||
throw AppError.forbidden("Нет доступа к приложению Cloudflare Domain Manager");
|
||||
}
|
||||
|
||||
request.authUser = {
|
||||
id: String(payload.sub),
|
||||
email: String(payload.email ?? ""),
|
||||
name: String(payload.name ?? ""),
|
||||
apps,
|
||||
permissions,
|
||||
isAdmin: Boolean(payload.is_admin),
|
||||
};
|
||||
|
||||
const required = permissionForRequest(request.method, request.url);
|
||||
if (required && !hasPermission(permissions, required)) {
|
||||
throw AppError.forbidden(`Недостаточно прав: ${required}`);
|
||||
}
|
||||
}
|
||||
|
||||
export default fp(authPlugin, { name: "auth" });
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { listAudit } from "@cfdm/db";
|
||||
import { auditListQuerySchema } from "@cfdm/shared";
|
||||
import { AppError } from "../errors.js";
|
||||
|
||||
export async function auditRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.get("/audit", async (request) => {
|
||||
const parsed = auditListQuerySchema.safeParse(request.query);
|
||||
if (!parsed.success) {
|
||||
throw AppError.validation("Некорректные параметры запроса");
|
||||
}
|
||||
|
||||
const q = parsed.data;
|
||||
return listAudit(app.db, {
|
||||
action: q.action,
|
||||
severity: q.severity,
|
||||
userId: q.user_id,
|
||||
sourceApp: q.source_app,
|
||||
limit: q.limit,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { z } from "zod";
|
||||
import * as dnsService from "../services/dns-service.js";
|
||||
import { recordAudit } from "../lib/audit.js";
|
||||
|
||||
export async function dnsRoutes(app: FastifyInstance) {
|
||||
const createSchema = z.object({
|
||||
@@ -31,12 +32,25 @@ export async function dnsRoutes(app: FastifyInstance) {
|
||||
app.post("/domains/:id/dns", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = createSchema.parse(request.body);
|
||||
return dnsService.create(
|
||||
const record = await dnsService.create(
|
||||
request.server.db,
|
||||
request.server.cf,
|
||||
Number(id),
|
||||
body,
|
||||
);
|
||||
recordAudit(request.server, request, {
|
||||
action: "dns.create",
|
||||
targetType: "app_resource",
|
||||
targetId: String(record.id),
|
||||
summary: `Создана DNS-запись ${record.name} (${record.record_type})`,
|
||||
details: {
|
||||
domain_id: Number(id),
|
||||
record_type: record.record_type,
|
||||
name: record.name,
|
||||
content: record.content,
|
||||
},
|
||||
});
|
||||
return record;
|
||||
});
|
||||
|
||||
app.post("/domains/:id/dns/bulk", async (request) => {
|
||||
@@ -69,13 +83,21 @@ export async function dnsRoutes(app: FastifyInstance) {
|
||||
id: string;
|
||||
recordId: string;
|
||||
};
|
||||
return dnsService.update(
|
||||
const record = await dnsService.update(
|
||||
request.server.db,
|
||||
request.server.cf,
|
||||
Number(id),
|
||||
Number(recordId),
|
||||
request.body as dnsService.UpdateDnsRequest,
|
||||
);
|
||||
recordAudit(request.server, request, {
|
||||
action: "dns.update",
|
||||
targetType: "app_resource",
|
||||
targetId: String(recordId),
|
||||
summary: `Обновлена DNS-запись ${record.name}`,
|
||||
details: { domain_id: Number(id), record_id: Number(recordId) },
|
||||
});
|
||||
return record;
|
||||
});
|
||||
|
||||
app.delete("/domains/:id/dns/:recordId", async (request) => {
|
||||
@@ -83,12 +105,25 @@ export async function dnsRoutes(app: FastifyInstance) {
|
||||
id: string;
|
||||
recordId: string;
|
||||
};
|
||||
const record = dnsService.get(
|
||||
request.server.db,
|
||||
Number(id),
|
||||
Number(recordId),
|
||||
);
|
||||
await dnsService.deleteRecord(
|
||||
request.server.db,
|
||||
request.server.cf,
|
||||
Number(id),
|
||||
Number(recordId),
|
||||
);
|
||||
recordAudit(request.server, request, {
|
||||
action: "dns.delete",
|
||||
severity: "warning",
|
||||
targetType: "app_resource",
|
||||
targetId: String(recordId),
|
||||
summary: `Удалена DNS-запись ${record.name}`,
|
||||
details: { domain_id: Number(id), name: record.name },
|
||||
});
|
||||
return { deleted: true };
|
||||
});
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { FastifyInstance } from "fastify";
|
||||
import { bulkUpdateDomainsSchema, updateDomainSchema } from "@cfdm/shared";
|
||||
import { z } from "zod";
|
||||
import * as domainService from "../services/domain-service.js";
|
||||
import { recordAudit } from "../lib/audit.js";
|
||||
|
||||
export async function domainRoutes(app: FastifyInstance) {
|
||||
const createSchema = z.object({
|
||||
@@ -17,12 +18,20 @@ export async function domainRoutes(app: FastifyInstance) {
|
||||
|
||||
app.post("/domains", async (request) => {
|
||||
const body = createSchema.parse(request.body);
|
||||
return domainService.createDomain(
|
||||
const domain = await domainService.createDomain(
|
||||
request.server.db,
|
||||
request.server.cf,
|
||||
body.group_id ?? null,
|
||||
body.zone_name,
|
||||
);
|
||||
recordAudit(request.server, request, {
|
||||
action: "domain.create",
|
||||
targetType: "app_resource",
|
||||
targetId: String(domain.id),
|
||||
summary: `Добавлен домен ${domain.zone_name}`,
|
||||
details: { zone_name: domain.zone_name, group_id: domain.group_id },
|
||||
});
|
||||
return domain;
|
||||
});
|
||||
|
||||
app.post("/domains/bulk", async (request) => {
|
||||
@@ -47,12 +56,29 @@ export async function domainRoutes(app: FastifyInstance) {
|
||||
app.patch("/domains/:id", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = updateDomainSchema.parse(request.body);
|
||||
return domainService.updateDomain(request.server.db, Number(id), body);
|
||||
const domain = domainService.updateDomain(request.server.db, Number(id), body);
|
||||
recordAudit(request.server, request, {
|
||||
action: "domain.update",
|
||||
targetType: "app_resource",
|
||||
targetId: String(domain.id),
|
||||
summary: `Обновлён домен ${domain.zone_name}`,
|
||||
details: body,
|
||||
});
|
||||
return domain;
|
||||
});
|
||||
|
||||
app.delete("/domains/:id", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const domain = domainService.getDomain(request.server.db, Number(id));
|
||||
domainService.deleteDomain(request.server.db, Number(id));
|
||||
recordAudit(request.server, request, {
|
||||
action: "domain.delete",
|
||||
severity: "warning",
|
||||
targetType: "app_resource",
|
||||
targetId: String(id),
|
||||
summary: `Удалён домен ${domain.zone_name}`,
|
||||
details: { zone_name: domain.zone_name },
|
||||
});
|
||||
return { deleted: true };
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { repos } from "@cfdm/db";
|
||||
import * as groupService from "../services/group-service.js";
|
||||
import { recordAudit } from "../lib/audit.js";
|
||||
|
||||
export async function groupRoutes(app: FastifyInstance) {
|
||||
const bodySchema = z.object({
|
||||
@@ -14,7 +16,15 @@ export async function groupRoutes(app: FastifyInstance) {
|
||||
|
||||
app.post("/groups", async (request) => {
|
||||
const body = bodySchema.parse(request.body);
|
||||
return groupService.createGroup(request.server.db, body.name, body.slug);
|
||||
const group = groupService.createGroup(request.server.db, body.name, body.slug);
|
||||
recordAudit(request.server, request, {
|
||||
action: "group.create",
|
||||
targetType: "app_resource",
|
||||
targetId: String(group.id),
|
||||
summary: `Создана группа «${group.name}»`,
|
||||
details: { name: group.name, slug: group.slug },
|
||||
});
|
||||
return group;
|
||||
});
|
||||
|
||||
app.get("/groups/:id", async (request) => {
|
||||
@@ -25,17 +35,34 @@ export async function groupRoutes(app: FastifyInstance) {
|
||||
app.patch("/groups/:id", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = bodySchema.parse(request.body);
|
||||
return groupService.updateGroup(
|
||||
const group = groupService.updateGroup(
|
||||
request.server.db,
|
||||
Number(id),
|
||||
body.name,
|
||||
body.slug,
|
||||
);
|
||||
recordAudit(request.server, request, {
|
||||
action: "group.update",
|
||||
targetType: "app_resource",
|
||||
targetId: String(group.id),
|
||||
summary: `Обновлена группа «${group.name}»`,
|
||||
details: { name: group.name, slug: group.slug },
|
||||
});
|
||||
return group;
|
||||
});
|
||||
|
||||
app.delete("/groups/:id", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const group = repos.getGroup(request.server.db, Number(id));
|
||||
groupService.deleteGroup(request.server.db, Number(id));
|
||||
recordAudit(request.server, request, {
|
||||
action: "group.delete",
|
||||
severity: "warning",
|
||||
targetType: "app_resource",
|
||||
targetId: String(id),
|
||||
summary: `Удалена группа «${group.name}»`,
|
||||
details: { name: group.name, slug: group.slug },
|
||||
});
|
||||
return { deleted: true };
|
||||
});
|
||||
}
|
||||
@@ -20,9 +20,11 @@ export async function healthCheckRoutes(app: FastifyInstance) {
|
||||
degradedFailures: config.healthDegradedFailures,
|
||||
downFailures: config.healthDownFailures,
|
||||
latencyWarnMs: config.healthLatencyWarnMs,
|
||||
successRecoveries: config.healthSuccessRecoveries,
|
||||
};
|
||||
const checked = await healthCheckService.runAllChecks(request.server.db, {
|
||||
thresholds,
|
||||
probeGapMs: config.healthProbeGapMs,
|
||||
onStatusChange: async (target, prev, next) => {
|
||||
try {
|
||||
const label =
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { healthCheck } from "../plugins/db.js";
|
||||
import { getAppSwitcher } from "@cfdm/db";
|
||||
import * as authService from "../services/auth.js";
|
||||
|
||||
export async function healthRoutes(app: FastifyInstance) {
|
||||
@@ -32,8 +31,12 @@ export async function healthRoutes(app: FastifyInstance) {
|
||||
}
|
||||
|
||||
export async function authRoutes(app: FastifyInstance) {
|
||||
app.get("/settings/app-switcher", async (request) => {
|
||||
return getAppSwitcher(request.server.db);
|
||||
app.get("/auth/config", async (request) => {
|
||||
const { config } = request.server;
|
||||
return {
|
||||
required: config.authRequired,
|
||||
portal_url: config.authPortalUrl,
|
||||
};
|
||||
});
|
||||
|
||||
const loginSchema = z.object({
|
||||
@@ -42,6 +45,14 @@ export async function authRoutes(app: FastifyInstance) {
|
||||
});
|
||||
|
||||
app.post("/auth/login", async (request, reply) => {
|
||||
if (request.server.config.authRequired) {
|
||||
return reply.code(403).send({
|
||||
error: {
|
||||
code: "FORBIDDEN",
|
||||
message: "Локальный вход отключён — используйте auth-portal",
|
||||
},
|
||||
});
|
||||
}
|
||||
const body = loginSchema.parse(request.body);
|
||||
const result = await authService.login(
|
||||
request.server.config,
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { FastifyInstance } from "fastify";
|
||||
import { vpsTrackerEventSchema } from "@cfdm/shared";
|
||||
import { getAppSettingsSecrets } from "@cfdm/db";
|
||||
import * as vpsTrackerEvents from "../services/vps-tracker-events.js";
|
||||
import { buildAllSyncBindings } from "../services/vps-tracker-sync.js";
|
||||
|
||||
function verifyBearer(authHeader: string | undefined, expected: string): boolean {
|
||||
if (!authHeader?.startsWith("Bearer ")) return false;
|
||||
@@ -41,4 +42,31 @@ export async function integrationsVpsTrackerRoutes(app: FastifyInstance) {
|
||||
);
|
||||
return { ok: true, reconciled };
|
||||
});
|
||||
|
||||
/**
|
||||
* Полная синхронизация по запросу VPS Tracker (pull).
|
||||
* Bindings возвращаются в ответе — клиент применяет их локально.
|
||||
* Не требует доступности VPS Tracker URL из CFDM.
|
||||
*/
|
||||
app.post("/integrations/vps-tracker/sync", async (req, reply) => {
|
||||
const secrets = getAppSettingsSecrets(app.db);
|
||||
const token = secrets.vpsTrackerIntegrationToken;
|
||||
if (!token) {
|
||||
return reply.status(503).send({
|
||||
ok: false,
|
||||
error: "Integration not configured",
|
||||
});
|
||||
}
|
||||
if (!verifyBearer(req.headers.authorization, token)) {
|
||||
return reply.status(401).send({ ok: false, error: "Unauthorized" });
|
||||
}
|
||||
|
||||
const bindings = await buildAllSyncBindings(app.db);
|
||||
return {
|
||||
ok: true,
|
||||
count: bindings.length,
|
||||
bindings,
|
||||
fullSync: true,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import {
|
||||
createOriginHealthCheckSchema,
|
||||
} from "@cfdm/shared";
|
||||
import * as originHealth from "../services/origin-health-check-service.js";
|
||||
import { recordAudit } from "../lib/audit.js";
|
||||
|
||||
export async function originHealthCheckRoutes(app: FastifyInstance) {
|
||||
app.get("/health-checks", async (request) => {
|
||||
return originHealth.listOriginHealthChecks(request.server.db);
|
||||
});
|
||||
|
||||
app.post("/health-checks", async (request) => {
|
||||
const body = createOriginHealthCheckSchema.parse(request.body);
|
||||
const check = await originHealth.createOriginHealthCheck(
|
||||
request.server.db,
|
||||
request.server.cf,
|
||||
body,
|
||||
);
|
||||
recordAudit(request.server, request, {
|
||||
action: "healthcheck.create",
|
||||
targetType: "app_resource",
|
||||
targetId: String(check.id),
|
||||
summary: `Создан health check «${check.name}» (${check.provider})`,
|
||||
});
|
||||
return check;
|
||||
});
|
||||
|
||||
app.get("/health-checks/:id", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
return originHealth.getOriginHealthCheck(request.server.db, Number(id));
|
||||
});
|
||||
|
||||
app.patch("/health-checks/:id", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = createOriginHealthCheckSchema.partial().parse(request.body);
|
||||
const check = await originHealth.updateOriginHealthCheck(
|
||||
request.server.db,
|
||||
request.server.cf,
|
||||
Number(id),
|
||||
body,
|
||||
);
|
||||
recordAudit(request.server, request, {
|
||||
action: "healthcheck.update",
|
||||
targetType: "app_resource",
|
||||
targetId: id,
|
||||
summary: `Обновлён health check «${check.name}»`,
|
||||
});
|
||||
return check;
|
||||
});
|
||||
|
||||
app.delete("/health-checks/:id", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
await originHealth.deleteOriginHealthCheck(
|
||||
request.server.db,
|
||||
request.server.cf,
|
||||
Number(id),
|
||||
);
|
||||
recordAudit(request.server, request, {
|
||||
action: "healthcheck.delete",
|
||||
severity: "warning",
|
||||
targetType: "app_resource",
|
||||
targetId: id,
|
||||
summary: `Удалён health check ${id}`,
|
||||
});
|
||||
return { deleted: true };
|
||||
});
|
||||
|
||||
app.post("/health-checks/:id/sync", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
return originHealth.syncOriginHealthCheck(
|
||||
request.server.db,
|
||||
request.server.cf,
|
||||
Number(id),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { changeIpSchema } from "@cfdm/shared";
|
||||
import * as bindingService from "../services/binding-service.js";
|
||||
import * as changeIp from "../services/change-ip-service.js";
|
||||
import { recordAudit } from "../lib/audit.js";
|
||||
|
||||
export async function serviceBindingRoutes(app: FastifyInstance) {
|
||||
const createSchema = z.object({
|
||||
@@ -52,6 +55,27 @@ export async function serviceBindingRoutes(app: FastifyInstance) {
|
||||
return { deleted: true };
|
||||
});
|
||||
|
||||
app.post("/service-bindings/:id/change-ip", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = changeIpSchema.parse(request.body);
|
||||
const result = await changeIp.changeBindingIp(
|
||||
request.server.db,
|
||||
request.server.cf,
|
||||
Number(id),
|
||||
body,
|
||||
);
|
||||
if (result.applied) {
|
||||
recordAudit(request.server, request, {
|
||||
action: "binding.change_ip",
|
||||
targetType: "app_resource",
|
||||
targetId: id,
|
||||
summary: `Сменён IP: ${result.message}`,
|
||||
details: result,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
app.get("/domains/:id/service-bindings", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
return bindingService.listByDomain(request.server.db, Number(id));
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { reorderServicesSchema, updateServiceConfigSchema } from "@cfdm/shared";
|
||||
import {
|
||||
changeDomainSchema,
|
||||
createServiceNodeSchema,
|
||||
reorderServicesSchema,
|
||||
updateServiceConfigSchema,
|
||||
updateServiceNodeSchema,
|
||||
} from "@cfdm/shared";
|
||||
import { repos } from "@cfdm/db";
|
||||
import * as serviceConfig from "../services/service-config-service.js";
|
||||
import * as nodeService from "../services/node-service.js";
|
||||
import * as changeDomain from "../services/change-domain-service.js";
|
||||
import { recordAudit } from "../lib/audit.js";
|
||||
|
||||
export async function serviceRoutes(app: FastifyInstance) {
|
||||
const createSchema = z.object({
|
||||
@@ -39,7 +48,15 @@ export async function serviceRoutes(app: FastifyInstance) {
|
||||
body.service_group_id,
|
||||
);
|
||||
}
|
||||
return serviceConfig.getView(request.server.db, service.id);
|
||||
const view = await serviceConfig.getView(request.server.db, service.id);
|
||||
recordAudit(request.server, request, {
|
||||
action: "service.create",
|
||||
targetType: "app_resource",
|
||||
targetId: String(service.id),
|
||||
summary: `Создан сервис «${service.name}»`,
|
||||
details: { name: service.name, slug: service.slug },
|
||||
});
|
||||
return view;
|
||||
});
|
||||
|
||||
app.get("/services/:id", async (request) => {
|
||||
@@ -47,20 +64,120 @@ export async function serviceRoutes(app: FastifyInstance) {
|
||||
return serviceConfig.getView(request.server.db, Number(id));
|
||||
});
|
||||
|
||||
app.patch("/services/:id", async (request) => {
|
||||
app.get("/services/:id/overview", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = updateServiceConfigSchema.parse(request.body);
|
||||
return serviceConfig.updateConfig(
|
||||
return nodeService.getOverview(request.server.db, Number(id));
|
||||
});
|
||||
|
||||
app.get("/services/:id/nodes", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
return nodeService.listNodes(request.server.db, Number(id));
|
||||
});
|
||||
|
||||
app.post("/services/:id/nodes", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = createServiceNodeSchema.parse(request.body);
|
||||
const node = nodeService.createNode(request.server.db, Number(id), body);
|
||||
recordAudit(request.server, request, {
|
||||
action: "node.create",
|
||||
targetType: "app_resource",
|
||||
targetId: String(node.id),
|
||||
summary: `Добавлена нода ${node.address}`,
|
||||
details: { service_id: Number(id), address: node.address },
|
||||
});
|
||||
return node;
|
||||
});
|
||||
|
||||
app.patch("/services/:id/nodes/:nodeId", async (request) => {
|
||||
const { id, nodeId } = request.params as { id: string; nodeId: string };
|
||||
const body = updateServiceNodeSchema.parse(request.body);
|
||||
const node = nodeService.updateNode(
|
||||
request.server.db,
|
||||
Number(id),
|
||||
Number(nodeId),
|
||||
body,
|
||||
);
|
||||
recordAudit(request.server, request, {
|
||||
action: "node.update",
|
||||
targetType: "app_resource",
|
||||
targetId: String(node.id),
|
||||
summary: `Обновлена нода ${node.address}`,
|
||||
details: body,
|
||||
});
|
||||
return node;
|
||||
});
|
||||
|
||||
app.delete("/services/:id/nodes/:nodeId", async (request) => {
|
||||
const { id, nodeId } = request.params as { id: string; nodeId: string };
|
||||
const node = repos.getNode(request.server.db, Number(nodeId));
|
||||
nodeService.deleteNode(request.server.db, Number(id), Number(nodeId));
|
||||
recordAudit(request.server, request, {
|
||||
action: "node.delete",
|
||||
severity: "warning",
|
||||
targetType: "app_resource",
|
||||
targetId: nodeId,
|
||||
summary: `Удалена нода ${node.address}`,
|
||||
});
|
||||
return { deleted: true };
|
||||
});
|
||||
|
||||
app.post("/services/:id/change-domain", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = changeDomainSchema.parse(request.body);
|
||||
const result = await changeDomain.changeServiceDomain(
|
||||
request.server.db,
|
||||
request.server.cf,
|
||||
Number(id),
|
||||
body,
|
||||
);
|
||||
if (result.applied) {
|
||||
recordAudit(request.server, request, {
|
||||
action: "service.change_domain",
|
||||
targetType: "app_resource",
|
||||
targetId: id,
|
||||
summary: result.message,
|
||||
details: result,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
app.get("/ops-summary", async (request) => {
|
||||
return nodeService.opsSummary(request.server.db);
|
||||
});
|
||||
|
||||
|
||||
app.patch("/services/:id", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = updateServiceConfigSchema.parse(request.body);
|
||||
const view = await serviceConfig.updateConfig(
|
||||
request.server.db,
|
||||
request.server.cf,
|
||||
Number(id),
|
||||
body,
|
||||
);
|
||||
recordAudit(request.server, request, {
|
||||
action: "service.update",
|
||||
targetType: "app_resource",
|
||||
targetId: String(id),
|
||||
summary: `Обновлён сервис «${view.name}»`,
|
||||
details: body,
|
||||
});
|
||||
return view;
|
||||
});
|
||||
|
||||
app.delete("/services/:id", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const view = await serviceConfig.getView(request.server.db, Number(id));
|
||||
repos.deleteService(request.server.db, Number(id));
|
||||
recordAudit(request.server, request, {
|
||||
action: "service.delete",
|
||||
severity: "warning",
|
||||
targetType: "app_resource",
|
||||
targetId: String(id),
|
||||
summary: `Удалён сервис «${view.name}»`,
|
||||
details: { name: view.name, slug: view.slug },
|
||||
});
|
||||
return { deleted: true };
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { request } from "undici";
|
||||
import type { IngestAuditEvent } from "@cfdm/shared";
|
||||
|
||||
export async function pushAuditEvents(
|
||||
portalUrl: string,
|
||||
secret: string,
|
||||
events: IngestAuditEvent[],
|
||||
): Promise<void> {
|
||||
const base = portalUrl.replace(/\/$/, "");
|
||||
const res = await request(`${base}/api/v1/ingest/audit`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
authorization: `Bearer ${secret}`,
|
||||
},
|
||||
body: JSON.stringify({ events }),
|
||||
});
|
||||
|
||||
if (res.statusCode >= 400) {
|
||||
const body = await res.body.text();
|
||||
throw new Error(`portal audit ingest ${res.statusCode}: ${body}`);
|
||||
}
|
||||
}
|
||||
@@ -21,10 +21,19 @@ export interface CertificateTarget {
|
||||
hostname: string;
|
||||
}
|
||||
|
||||
function pruneStaleCertificates(db: Db): void {
|
||||
const targets = resolveCertificateTargets(db);
|
||||
repos.deleteCertificatesNotIn(
|
||||
db,
|
||||
targets.map((t) => t.hostname),
|
||||
);
|
||||
}
|
||||
|
||||
export function listCertificates(
|
||||
db: Db,
|
||||
status?: string,
|
||||
): Certificate[] {
|
||||
pruneStaleCertificates(db);
|
||||
return repos.listCertificates(db, status);
|
||||
}
|
||||
|
||||
@@ -133,6 +142,29 @@ function bindingSubdomain(
|
||||
return repos.findSubdomainByDomainAndName(db, domainId, hostname);
|
||||
}
|
||||
|
||||
type HealthTlsFlags = {
|
||||
health_check_enabled: boolean;
|
||||
health_check_verify_tls: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Auto SSL monitoring follows effective health-check with TLS verify.
|
||||
* No health → no SSL. Health without verify_tls (self-signed) → no SSL.
|
||||
* Binding inherits group health when its own health is off.
|
||||
*/
|
||||
function hasSslHealthGate(
|
||||
own: HealthTlsFlags,
|
||||
group: (HealthTlsFlags & { enabled: boolean }) | null,
|
||||
): boolean {
|
||||
if (own.health_check_enabled) {
|
||||
return own.health_check_verify_tls;
|
||||
}
|
||||
if (group?.enabled && group.health_check_enabled) {
|
||||
return group.health_check_verify_tls;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function buildServiceCertificateFqdns(
|
||||
db: Db,
|
||||
): Map<string, CertificateTarget> {
|
||||
@@ -144,6 +176,17 @@ export function buildServiceCertificateFqdns(
|
||||
? repos.getServiceGroup(db, service.service_group_id)
|
||||
: null;
|
||||
if (!shouldMonitorService(service, group)) continue;
|
||||
if (
|
||||
!hasSslHealthGate(
|
||||
{
|
||||
health_check_enabled: binding.health_check_enabled,
|
||||
health_check_verify_tls: binding.health_check_verify_tls,
|
||||
},
|
||||
group,
|
||||
)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const subdomain = bindingSubdomain(db, binding.domain_id, binding.hostname);
|
||||
if (subdomain && !subdomain.enabled) continue;
|
||||
@@ -159,6 +202,7 @@ export function buildServiceCertificateFqdns(
|
||||
const knownZones = repos.listAllDomains(db).map((d) => d.zone_name);
|
||||
for (const group of repos.listServiceGroups(db)) {
|
||||
if (!group.enabled || !group.domain?.trim()) continue;
|
||||
if (!group.health_check_enabled || !group.health_check_verify_tls) continue;
|
||||
|
||||
const parsed = parseFqdn(group.domain, knownZones);
|
||||
if (!parsed) continue;
|
||||
@@ -244,5 +288,6 @@ export async function runAllChecks(db: Db): Promise<number> {
|
||||
}
|
||||
|
||||
export function statusSummary(db: Db): Array<[string, number]> {
|
||||
pruneStaleCertificates(db);
|
||||
return repos.countCertificatesByStatus(db);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import type { Db } from "@cfdm/db";
|
||||
import { repos } from "@cfdm/db";
|
||||
import type { ChangeDomainInput } from "@cfdm/shared";
|
||||
import type { CloudflareClient } from "../lib/cf-client.js";
|
||||
import { AppError } from "../errors.js";
|
||||
import * as dnsService from "./dns-service.js";
|
||||
import { withBindingLock } from "./routing/index.js";
|
||||
import { applyBindingDesiredDns, fqdnToDisplay } from "./service-config-service.js";
|
||||
|
||||
export interface ChangeDomainItem {
|
||||
binding_id: number;
|
||||
hostname: string;
|
||||
from_fqdn: string;
|
||||
to_fqdn: string;
|
||||
}
|
||||
|
||||
export interface ChangeDomainPreview {
|
||||
from_domain_id: number;
|
||||
to_domain_id: number;
|
||||
from_zone: string;
|
||||
to_zone: string;
|
||||
items: ChangeDomainItem[];
|
||||
dry_run: boolean;
|
||||
applied: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export async function changeServiceDomain(
|
||||
db: Db,
|
||||
cf: CloudflareClient,
|
||||
serviceId: number,
|
||||
input: ChangeDomainInput,
|
||||
): Promise<ChangeDomainPreview> {
|
||||
repos.getService(db, serviceId);
|
||||
if (input.from_domain_id === input.to_domain_id) {
|
||||
throw AppError.validation("укажите другой целевой домен");
|
||||
}
|
||||
const fromDomain = repos.getDomain(db, input.from_domain_id);
|
||||
const toDomain = repos.getDomain(db, input.to_domain_id);
|
||||
const bindings = repos
|
||||
.listBindingsByService(db, serviceId)
|
||||
.filter((b) => b.domain_id === input.from_domain_id);
|
||||
const selected = input.hostnames?.length
|
||||
? bindings.filter((b) => input.hostnames!.includes(b.hostname))
|
||||
: bindings;
|
||||
if (selected.length === 0) {
|
||||
throw AppError.validation("нет привязок для переноса");
|
||||
}
|
||||
|
||||
const items: ChangeDomainItem[] = selected.map((binding) => ({
|
||||
binding_id: binding.id,
|
||||
hostname: binding.hostname,
|
||||
from_fqdn: fqdnToDisplay(binding.hostname, fromDomain.zone_name),
|
||||
to_fqdn: fqdnToDisplay(binding.hostname, toDomain.zone_name),
|
||||
}));
|
||||
|
||||
const preview: ChangeDomainPreview = {
|
||||
from_domain_id: fromDomain.id,
|
||||
to_domain_id: toDomain.id,
|
||||
from_zone: fromDomain.zone_name,
|
||||
to_zone: toDomain.zone_name,
|
||||
items,
|
||||
dry_run: Boolean(input.dry_run),
|
||||
applied: false,
|
||||
message: `Перенос ${items.length} привязок ${fromDomain.zone_name} → ${toDomain.zone_name}`,
|
||||
};
|
||||
|
||||
if (input.dry_run) return preview;
|
||||
|
||||
const createdRecordIds: number[] = [];
|
||||
try {
|
||||
for (const binding of selected) {
|
||||
const existing = repos.findBinding(
|
||||
db,
|
||||
serviceId,
|
||||
toDomain.id,
|
||||
binding.hostname,
|
||||
);
|
||||
if (existing) {
|
||||
throw AppError.conflict(
|
||||
`привязка ${fqdnToDisplay(binding.hostname, toDomain.zone_name)} уже существует`,
|
||||
);
|
||||
}
|
||||
await withBindingLock(binding.id, async () => {
|
||||
repos.bumpBindingVersion(db, binding.id);
|
||||
const ips = repos.listBindingIps(db, binding.id);
|
||||
repos.updateBindingDomain(db, binding.id, toDomain.id, binding.hostname);
|
||||
await applyBindingDesiredDns(db, cf, binding.id, ips);
|
||||
const newRecords = repos.listRecordsForBinding(db, binding.id);
|
||||
createdRecordIds.push(...newRecords.map((r) => r.id));
|
||||
|
||||
const oldRecords = newRecords.filter((r) => r.domain_id === fromDomain.id);
|
||||
for (const record of oldRecords) {
|
||||
repos.unlinkBindingRecord(db, binding.id, record.id);
|
||||
try {
|
||||
await dnsService.deleteRecord(db, cf, fromDomain.id, record.id);
|
||||
} catch {
|
||||
// best-effort cleanup of old zone
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
throw err instanceof AppError
|
||||
? err
|
||||
: AppError.syncFailed(
|
||||
err instanceof Error ? err.message : "не удалось перенести привязки",
|
||||
);
|
||||
}
|
||||
|
||||
void createdRecordIds;
|
||||
return {
|
||||
...preview,
|
||||
dry_run: false,
|
||||
applied: true,
|
||||
message: `Привязки перенесены в ${toDomain.zone_name}. Старые записи зоны удалены.`,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import type { Db } from "@cfdm/db";
|
||||
import { repos } from "@cfdm/db";
|
||||
import type { ChangeIpInput } from "@cfdm/shared";
|
||||
import type { CloudflareClient } from "../lib/cf-client.js";
|
||||
import { AppError } from "../errors.js";
|
||||
import { isValidIpv4 } from "../lib/validators.js";
|
||||
import { withBindingLock } from "./routing/index.js";
|
||||
import { applyBindingDesiredDns } from "./service-config-service.js";
|
||||
|
||||
export interface ChangeIpPreview {
|
||||
binding_id: number;
|
||||
hostname: string;
|
||||
zone_name: string;
|
||||
from_ip: string;
|
||||
to_ip: string;
|
||||
dry_run: boolean;
|
||||
applied: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
async function patchRecordContent(
|
||||
db: Db,
|
||||
cf: CloudflareClient,
|
||||
domainId: number,
|
||||
recordId: number,
|
||||
content: string,
|
||||
): Promise<void> {
|
||||
const domain = repos.getDomain(db, domainId);
|
||||
const record = repos.getDnsRecord(db, domainId, recordId);
|
||||
if (!record.cf_record_id) {
|
||||
throw AppError.dnsUpdateFailed("у DNS-записи нет идентификатора Cloudflare");
|
||||
}
|
||||
try {
|
||||
const patched = await cf.patchDnsRecord(domain.cf_zone_id, record.cf_record_id, {
|
||||
content,
|
||||
});
|
||||
repos.updateDnsFields(
|
||||
db,
|
||||
record.id,
|
||||
patched.type ?? record.record_type,
|
||||
patched.name ?? record.name,
|
||||
patched.content ?? content,
|
||||
patched.ttl ?? record.ttl,
|
||||
patched.proxied ?? record.proxied,
|
||||
patched.priority ?? record.priority,
|
||||
"synced",
|
||||
patched.id ?? record.cf_record_id,
|
||||
null,
|
||||
);
|
||||
} catch (err) {
|
||||
if (err instanceof AppError) throw err;
|
||||
throw AppError.dnsUpdateFailed(
|
||||
err instanceof Error ? err.message : "не удалось обновить запись в Cloudflare",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function changeBindingIp(
|
||||
db: Db,
|
||||
cf: CloudflareClient,
|
||||
bindingId: number,
|
||||
input: ChangeIpInput,
|
||||
): Promise<ChangeIpPreview> {
|
||||
const binding = repos.getBinding(db, bindingId);
|
||||
const domain = repos.getDomain(db, binding.domain_id);
|
||||
const current = repos.listBindingIpsWithMeta(db, bindingId);
|
||||
if (current.length === 0) {
|
||||
throw AppError.validation("у привязки нет IP для замены");
|
||||
}
|
||||
|
||||
let fromIp = input.from_ip?.trim();
|
||||
let toIp = input.to_ip?.trim();
|
||||
|
||||
if (input.node_id) {
|
||||
const node = repos.getNode(db, input.node_id);
|
||||
if (node.service_id !== binding.service_id) {
|
||||
throw AppError.validation("нода не принадлежит сервису этой привязки");
|
||||
}
|
||||
toIp = node.address;
|
||||
}
|
||||
|
||||
if (!fromIp) {
|
||||
fromIp = current[0]!.ip;
|
||||
}
|
||||
if (!toIp) {
|
||||
throw AppError.invalidIp("укажите новый IP или ноду");
|
||||
}
|
||||
if (!isValidIpv4(toIp)) {
|
||||
throw AppError.invalidIp(`Некорректный IP-адрес: ${toIp}`);
|
||||
}
|
||||
if (!current.some((row) => row.ip === fromIp)) {
|
||||
throw AppError.validation(`IP ${fromIp} нет в привязке`);
|
||||
}
|
||||
|
||||
const preview: ChangeIpPreview = {
|
||||
binding_id: bindingId,
|
||||
hostname: binding.hostname,
|
||||
zone_name: domain.zone_name,
|
||||
from_ip: fromIp,
|
||||
to_ip: toIp,
|
||||
dry_run: Boolean(input.dry_run),
|
||||
applied: false,
|
||||
message: `${fromIp} → ${toIp}`,
|
||||
};
|
||||
|
||||
if (input.dry_run || fromIp === toIp) {
|
||||
return preview;
|
||||
}
|
||||
|
||||
return withBindingLock(bindingId, async () => {
|
||||
repos.bumpBindingVersion(db, bindingId);
|
||||
const next = current.map((row) =>
|
||||
row.ip === fromIp ? { ...row, ip: toIp } : row,
|
||||
);
|
||||
repos.replaceBindingIpsWithMeta(db, bindingId, next);
|
||||
|
||||
const records = repos.listRecordsForBinding(db, bindingId);
|
||||
const match = records.find(
|
||||
(record) =>
|
||||
record.content === fromIp &&
|
||||
(record.record_type.toUpperCase() === "A" ||
|
||||
record.record_type.toUpperCase() === "AAAA"),
|
||||
);
|
||||
if (match) {
|
||||
await patchRecordContent(db, cf, binding.domain_id, match.id, toIp);
|
||||
} else {
|
||||
await applyBindingDesiredDns(
|
||||
db,
|
||||
cf,
|
||||
bindingId,
|
||||
next.map((row) => row.ip),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
...preview,
|
||||
dry_run: false,
|
||||
applied: true,
|
||||
message: `Запись обновлена в Cloudflare (${fromIp} → ${toIp}). Распространение зависит от TTL.`,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Db } from "@cfdm/db";
|
||||
import { repos, type DnsListFilter } from "@cfdm/db";
|
||||
import type { CreateDnsRecordPayload, DnsRecord } from "@cfdm/shared";
|
||||
import type { CreateDnsRecordPayload, DnsRecord, PatchDnsRecordPayload } from "@cfdm/shared";
|
||||
import {
|
||||
SYNC_CONFLICT,
|
||||
SYNC_ERROR,
|
||||
@@ -179,6 +179,52 @@ export async function update(
|
||||
return pushRecord(db, cf, domainId, domain.cf_zone_id, updated);
|
||||
}
|
||||
|
||||
export async function patchContent(
|
||||
db: Db,
|
||||
cf: CloudflareClient,
|
||||
domainId: number,
|
||||
recordId: number,
|
||||
payload: PatchDnsRecordPayload,
|
||||
): Promise<DnsRecord> {
|
||||
const domain = repos.getDomain(db, domainId);
|
||||
const existing = repos.getDnsRecord(db, domainId, recordId);
|
||||
if (!existing.cf_record_id) {
|
||||
throw AppError.dnsUpdateFailed("у DNS-записи нет идентификатора Cloudflare");
|
||||
}
|
||||
try {
|
||||
const cfRec = await cf.patchDnsRecord(
|
||||
domain.cf_zone_id,
|
||||
existing.cf_record_id,
|
||||
payload,
|
||||
);
|
||||
repos.updateDnsFields(
|
||||
db,
|
||||
existing.id,
|
||||
cfRec.type ?? existing.record_type,
|
||||
cfRec.name ?? existing.name,
|
||||
cfRec.content ?? existing.content,
|
||||
cfRec.ttl ?? existing.ttl,
|
||||
cfRec.proxied ?? existing.proxied,
|
||||
cfRec.priority ?? existing.priority,
|
||||
SYNC_SYNCED,
|
||||
cfRec.id ?? existing.cf_record_id,
|
||||
null,
|
||||
);
|
||||
return repos.getDnsRecord(db, domainId, existing.id);
|
||||
} catch (e) {
|
||||
repos.setDnsSyncStatus(
|
||||
db,
|
||||
existing.id,
|
||||
SYNC_ERROR,
|
||||
existing.cf_record_id,
|
||||
e instanceof Error ? e.message : String(e),
|
||||
);
|
||||
throw e instanceof AppError
|
||||
? e
|
||||
: AppError.dnsUpdateFailed(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteRecord(
|
||||
db: Db,
|
||||
cf: CloudflareClient,
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import { connect } from "node:net";
|
||||
import { connect, isIP } from "node:net";
|
||||
import { resolve4, resolve6 } from "node:dns/promises";
|
||||
import { Agent, fetch as undiciFetch } from "undici";
|
||||
import { Agent, buildConnector, fetch as undiciFetch } from "undici";
|
||||
import type { Db } from "@cfdm/db";
|
||||
import { repos } from "@cfdm/db";
|
||||
import type { HealthCheckTarget, IpHealthState } from "@cfdm/shared";
|
||||
import { AppError } from "../errors.js";
|
||||
import { nextHealthState } from "./health/state-machine.js";
|
||||
|
||||
export interface HealthCheckThresholds {
|
||||
degradedFailures: number;
|
||||
downFailures: number;
|
||||
latencyWarnMs: number;
|
||||
successRecoveries?: number;
|
||||
}
|
||||
|
||||
export interface ProbeResult {
|
||||
@@ -18,6 +20,26 @@ export interface ProbeResult {
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/** Bracket IPv6 for URL authority; leave IPv4/hostname as-is. */
|
||||
export function hostForUrl(ipOrHost: string): string {
|
||||
return isIP(ipOrHost) === 6 ? `[${ipOrHost}]` : ipOrHost;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build http(s) URL authority for the probe.
|
||||
* Prefer FQDN in the URL (correct Host/SNI); TCP dial goes to configured IP via custom connector.
|
||||
*/
|
||||
export function buildHttpProbeUrl(
|
||||
urlHost: string,
|
||||
port: number,
|
||||
pathWithSlash: string,
|
||||
useTls: boolean,
|
||||
): string {
|
||||
const defaultPort = useTls ? 443 : 80;
|
||||
const portPart = port === defaultPort ? "" : `:${port}`;
|
||||
return `${useTls ? "https" : "http"}://${hostForUrl(urlHost)}${portPart}${pathWithSlash}`;
|
||||
}
|
||||
|
||||
function tcpProbe(
|
||||
ip: string,
|
||||
port: number,
|
||||
@@ -59,6 +81,41 @@ function tcpProbe(
|
||||
});
|
||||
}
|
||||
|
||||
/** Dial `connectAddr` for TCP/TLS while URL Host/SNI stay on the FQDN. */
|
||||
function createIpPinnedAgent(
|
||||
connectAddr: string,
|
||||
sniHost: string,
|
||||
useTls: boolean,
|
||||
timeoutMs: number,
|
||||
verifyTls: boolean,
|
||||
): Agent {
|
||||
const connector = buildConnector({
|
||||
rejectUnauthorized: verifyTls,
|
||||
timeout: timeoutMs,
|
||||
});
|
||||
return new Agent({
|
||||
connect(opts, callback) {
|
||||
connector(
|
||||
{
|
||||
...opts,
|
||||
// Force socket to configured IP (or CNAME target), not public DNS of FQDN.
|
||||
hostname: connectAddr,
|
||||
host: connectAddr,
|
||||
servername:
|
||||
useTls && isIP(sniHost) === 0
|
||||
? sniHost
|
||||
: (opts.servername as string | undefined),
|
||||
},
|
||||
callback,
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP(S) probe: URL/Host/SNI use hostname (vhost), TCP connects to configured IP when numeric.
|
||||
* Avoids re-resolving FQDN via public DNS (which skewed group vs binding latency for the same IP).
|
||||
*/
|
||||
async function httpProbe(
|
||||
ip: string,
|
||||
target: HealthCheckTarget,
|
||||
@@ -69,21 +126,23 @@ async function httpProbe(
|
||||
const pathWithSlash = path.startsWith("/") ? path : `/${path}`;
|
||||
const port = target.port ?? 80;
|
||||
const useTls = port === 443;
|
||||
const urlHost = useTls ? target.hostname || ip : ip;
|
||||
const url = `${useTls ? "https" : "http"}://${urlHost}${pathWithSlash}`;
|
||||
const dispatcher =
|
||||
useTls && target.hostname
|
||||
? new Agent({
|
||||
connect: {
|
||||
servername: target.hostname,
|
||||
rejectUnauthorized: false,
|
||||
},
|
||||
})
|
||||
const connectAddr = String(ip || "").trim();
|
||||
const headerHost = (target.hostname || "").trim() || connectAddr;
|
||||
const url = buildHttpProbeUrl(headerHost, port, pathWithSlash, useTls);
|
||||
const verifyTls = target.verify_tls === true;
|
||||
|
||||
const family = isIP(connectAddr);
|
||||
const pinToIp = family === 4 || family === 6;
|
||||
|
||||
const dispatcher = pinToIp
|
||||
? createIpPinnedAgent(connectAddr, headerHost, useTls, timeoutMs, verifyTls)
|
||||
: useTls
|
||||
? createIpPinnedAgent(connectAddr, headerHost, useTls, timeoutMs, verifyTls)
|
||||
: undefined;
|
||||
|
||||
try {
|
||||
const response = await undiciFetch(url, {
|
||||
method: "GET",
|
||||
headers: { Host: target.hostname || ip },
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
redirect: "manual",
|
||||
dispatcher,
|
||||
@@ -177,27 +236,31 @@ export async function probeTarget(
|
||||
function deriveState(
|
||||
ok: boolean,
|
||||
latencyMs: number,
|
||||
prev: { consecutive_failures: number; status: string } | null,
|
||||
prev: {
|
||||
consecutive_failures: number;
|
||||
consecutive_successes?: number;
|
||||
status: string;
|
||||
} | null,
|
||||
thresholds: HealthCheckThresholds,
|
||||
): { state: IpHealthState; failures: number } {
|
||||
if (!ok) {
|
||||
const failures = (prev?.consecutive_failures ?? 0) + 1;
|
||||
if (failures >= thresholds.downFailures) {
|
||||
return { state: "down", failures };
|
||||
}
|
||||
if (failures >= thresholds.degradedFailures) {
|
||||
return { state: "degraded", failures };
|
||||
}
|
||||
return { state: "degraded", failures };
|
||||
}
|
||||
if (latencyMs > thresholds.latencyWarnMs) {
|
||||
return { state: "degraded", failures: 0 };
|
||||
}
|
||||
return { state: "up", failures: 0 };
|
||||
): { state: IpHealthState; failures: number; successes: number; node: string } {
|
||||
const next = nextHealthState(ok, latencyMs, prev, {
|
||||
degradedFailures: thresholds.degradedFailures,
|
||||
downFailures: thresholds.downFailures,
|
||||
latencyWarnMs: thresholds.latencyWarnMs,
|
||||
successRecoveries: thresholds.successRecoveries ?? 2,
|
||||
});
|
||||
return {
|
||||
state: next.legacy,
|
||||
failures: next.failures,
|
||||
successes: next.successes,
|
||||
node: next.node,
|
||||
};
|
||||
}
|
||||
|
||||
export interface RunAllChecksOptions {
|
||||
thresholds: HealthCheckThresholds;
|
||||
/** Pause between unique physical probes (default 2000). Same IP is only probed once. */
|
||||
probeGapMs?: number;
|
||||
onStatusChange?: (
|
||||
target: HealthCheckTarget,
|
||||
prevState: IpHealthState | null,
|
||||
@@ -205,47 +268,109 @@ export interface RunAllChecksOptions {
|
||||
) => void;
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
/**
|
||||
* One network hit per key. Group+binding on the same IP share a single TCP/HTTP probe
|
||||
* so anti-bot / rate-limit on the origin is not tripped by back-to-back checks.
|
||||
*/
|
||||
export function physicalProbeKey(target: HealthCheckTarget): string {
|
||||
const port = target.port ?? (target.type === "http" ? 80 : 80);
|
||||
const ip = String(target.ip || "").trim().toLowerCase();
|
||||
if (target.type === "http") {
|
||||
const path = (target.path?.trim() || "/") || "/";
|
||||
const expected = target.expected_status ?? "";
|
||||
return `http|${ip}|${port}|${path}|${expected}`;
|
||||
}
|
||||
if (target.type === "tcp") return `tcp|${ip}|${port}`;
|
||||
if (target.type === "ping") {
|
||||
return `ping|${String(target.hostname || target.ip || "").trim().toLowerCase()}`;
|
||||
}
|
||||
if (target.type === "dns") {
|
||||
return `dns|${String(target.hostname || target.ip || "").trim().toLowerCase()}`;
|
||||
}
|
||||
return `${target.type}|${ip}|${port}`;
|
||||
}
|
||||
|
||||
export async function runAllChecks(
|
||||
db: Db,
|
||||
options: RunAllChecksOptions,
|
||||
): Promise<number> {
|
||||
const targets = repos.listHealthCheckTargets(db);
|
||||
const gapMs = Math.max(0, options.probeGapMs ?? 2000);
|
||||
|
||||
const byPhysical = new Map<string, HealthCheckTarget[]>();
|
||||
for (const target of targets) {
|
||||
const prev = repos.getIpHealthStatusRow(
|
||||
db,
|
||||
target.scope,
|
||||
target.ref_id,
|
||||
target.ip,
|
||||
);
|
||||
const result = await probeTarget(target);
|
||||
const { state, failures } = deriveState(
|
||||
result.ok,
|
||||
result.latencyMs,
|
||||
prev
|
||||
? {
|
||||
consecutive_failures: prev.consecutive_failures,
|
||||
status: prev.status,
|
||||
}
|
||||
: null,
|
||||
options.thresholds,
|
||||
);
|
||||
const prevState: IpHealthState | null = prev
|
||||
? (prev.status as IpHealthState)
|
||||
: null;
|
||||
repos.upsertIpHealthStatus(
|
||||
db,
|
||||
target.scope,
|
||||
target.ref_id,
|
||||
target.ip,
|
||||
state,
|
||||
result.latencyMs,
|
||||
failures,
|
||||
result.error,
|
||||
);
|
||||
if (prevState !== state) {
|
||||
options.onStatusChange?.(target, prevState, state);
|
||||
const key = physicalProbeKey(target);
|
||||
const list = byPhysical.get(key);
|
||||
if (list) list.push(target);
|
||||
else byPhysical.set(key, [target]);
|
||||
}
|
||||
|
||||
let probeIndex = 0;
|
||||
for (const group of byPhysical.values()) {
|
||||
if (probeIndex > 0 && gapMs > 0) {
|
||||
await sleep(gapMs);
|
||||
}
|
||||
probeIndex += 1;
|
||||
|
||||
// Prefer binding hostname for SNI when several scopes share one IP.
|
||||
const representative =
|
||||
group.find((t) => t.scope === "binding") ?? group[0]!;
|
||||
const result = await probeTarget(representative);
|
||||
|
||||
for (const target of group) {
|
||||
const prev = repos.getIpHealthStatusRow(
|
||||
db,
|
||||
target.scope,
|
||||
target.ref_id,
|
||||
target.ip,
|
||||
);
|
||||
const { state, failures, successes, node } = deriveState(
|
||||
result.ok,
|
||||
result.latencyMs,
|
||||
prev
|
||||
? {
|
||||
consecutive_failures: prev.consecutive_failures,
|
||||
consecutive_successes: prev.consecutive_successes,
|
||||
status: prev.status,
|
||||
}
|
||||
: null,
|
||||
options.thresholds,
|
||||
);
|
||||
const prevState: IpHealthState | null = prev
|
||||
? (prev.status as IpHealthState)
|
||||
: null;
|
||||
repos.upsertIpHealthStatus(
|
||||
db,
|
||||
target.scope,
|
||||
target.ref_id,
|
||||
target.ip,
|
||||
state,
|
||||
result.latencyMs,
|
||||
failures,
|
||||
result.error,
|
||||
successes,
|
||||
);
|
||||
const matchedNode = repos.findNodeByIp(db, target.ip);
|
||||
if (matchedNode && matchedNode.enabled) {
|
||||
repos.updateNode(db, matchedNode.id, {
|
||||
health_status: node,
|
||||
consecutive_failures: failures,
|
||||
consecutive_successes: successes,
|
||||
last_check_at: new Date().toISOString().replace("T", " ").slice(0, 19),
|
||||
last_failure_reason: result.error,
|
||||
});
|
||||
}
|
||||
if (prevState !== state) {
|
||||
options.onStatusChange?.(target, prevState, state);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Orphan rows (old IPs / hostname keys) still feed MAX latency on group badge.
|
||||
repos.pruneStaleIpHealthStatus(db, targets);
|
||||
return targets.length;
|
||||
}
|
||||
|
||||
@@ -266,6 +391,7 @@ export async function runDomainMonitors(
|
||||
path: monitor.path,
|
||||
expected_status: monitor.expected_status,
|
||||
timeout_ms: monitor.timeout_ms,
|
||||
verify_tls: false,
|
||||
};
|
||||
let result: ProbeResult;
|
||||
if (monitor.type === "http") {
|
||||
@@ -292,6 +418,7 @@ export async function runDomainMonitors(
|
||||
result.latencyMs,
|
||||
{
|
||||
consecutive_failures: result.ok ? 0 : 1,
|
||||
consecutive_successes: result.ok ? 1 : 0,
|
||||
status: prevStatus,
|
||||
},
|
||||
thresholds,
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { Db } from "@cfdm/db";
|
||||
import { repos } from "@cfdm/db";
|
||||
import type { CfHealthCheck, HealthCheckTarget, OriginHealthCheck } from "@cfdm/shared";
|
||||
import type { CloudflareClient } from "../../lib/cf-client.js";
|
||||
import type { CfHealthCheckPayload } from "../../lib/cloudflare/healthcheck-service.js";
|
||||
import { AppError } from "../../errors.js";
|
||||
import type { ProbeResult } from "../health-check-service.js";
|
||||
import type { HealthCheckProvider } from "./provider.js";
|
||||
|
||||
function toPayload(
|
||||
check: OriginHealthCheck,
|
||||
address: string,
|
||||
): CfHealthCheckPayload {
|
||||
const type = (check.protocol || "TCP").toUpperCase() as "HTTP" | "HTTPS" | "TCP";
|
||||
const payload: CfHealthCheckPayload = {
|
||||
address,
|
||||
name: check.name,
|
||||
type,
|
||||
interval: check.interval_sec,
|
||||
timeout: check.timeout,
|
||||
retries: check.retries,
|
||||
consecutive_fails: check.consecutive_fails,
|
||||
consecutive_successes: check.consecutive_successes,
|
||||
suspended: check.suspended,
|
||||
};
|
||||
if (type === "HTTP" || type === "HTTPS") {
|
||||
payload.http_config = {
|
||||
method: check.method ?? "GET",
|
||||
path: check.path ?? "/",
|
||||
expected_codes: check.expected_status != null ? [String(check.expected_status)] : ["200"],
|
||||
};
|
||||
} else {
|
||||
payload.tcp_config = { method: "connection_established" };
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
export class CloudflareHealthCheckProvider implements HealthCheckProvider {
|
||||
readonly kind = "cloudflare" as const;
|
||||
|
||||
constructor(
|
||||
private readonly db: Db,
|
||||
private readonly cf: CloudflareClient,
|
||||
) {}
|
||||
|
||||
async probe(target: HealthCheckTarget): Promise<ProbeResult> {
|
||||
const node = repos.findNodeByIp(this.db, target.ip);
|
||||
if (!node?.health_check_id) {
|
||||
return { ok: false, latencyMs: 0, error: "нет Cloudflare Health Check" };
|
||||
}
|
||||
const check = repos.getHealthCheck(this.db, node.health_check_id);
|
||||
if (!check.cf_zone_id || !check.cf_healthcheck_id) {
|
||||
return { ok: false, latencyMs: 0, error: "Cloudflare Health Check не синхронизирован" };
|
||||
}
|
||||
try {
|
||||
const remote = await this.cf.getHealthCheck(check.cf_zone_id, check.cf_healthcheck_id);
|
||||
const status = (remote.status ?? "").toLowerCase();
|
||||
const ok = status === "healthy" || status === "ok";
|
||||
return {
|
||||
ok,
|
||||
latencyMs: 0,
|
||||
error: ok ? null : remote.status ?? "unhealthy",
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
ok: false,
|
||||
latencyMs: 0,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async syncCreate(
|
||||
check: OriginHealthCheck,
|
||||
zoneId: string,
|
||||
address: string,
|
||||
): Promise<CfHealthCheck> {
|
||||
try {
|
||||
const remote = await this.cf.createHealthCheck(zoneId, toPayload(check, address));
|
||||
repos.updateHealthCheck(this.db, check.id, {
|
||||
cf_healthcheck_id: remote.id,
|
||||
cf_zone_id: zoneId,
|
||||
provider: "cloudflare",
|
||||
});
|
||||
return remote;
|
||||
} catch (err) {
|
||||
if (err instanceof AppError) throw err;
|
||||
throw AppError.healthcheckCreateFailed(
|
||||
err instanceof Error ? err.message : "не удалось создать Cloudflare Health Check",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async syncUpdate(
|
||||
check: OriginHealthCheck,
|
||||
address: string,
|
||||
): Promise<CfHealthCheck> {
|
||||
if (!check.cf_zone_id || !check.cf_healthcheck_id) {
|
||||
throw AppError.healthcheckCreateFailed("Cloudflare Health Check не привязан к зоне");
|
||||
}
|
||||
return this.cf.updateHealthCheck(
|
||||
check.cf_zone_id,
|
||||
check.cf_healthcheck_id,
|
||||
toPayload(check, address),
|
||||
);
|
||||
}
|
||||
|
||||
async syncDelete(check: OriginHealthCheck): Promise<void> {
|
||||
if (!check.cf_zone_id || !check.cf_healthcheck_id) return;
|
||||
await this.cf.deleteHealthCheck(check.cf_zone_id, check.cf_healthcheck_id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { HealthCheckTarget } from "@cfdm/shared";
|
||||
import { probeTarget, type ProbeResult } from "../health-check-service.js";
|
||||
import type { HealthCheckProvider } from "./provider.js";
|
||||
|
||||
export class LocalHealthCheckProvider implements HealthCheckProvider {
|
||||
readonly kind = "local" as const;
|
||||
|
||||
probe(target: HealthCheckTarget): Promise<ProbeResult> {
|
||||
return probeTarget(target);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { HealthCheckTarget } from "@cfdm/shared";
|
||||
import type { ProbeResult } from "../health-check-service.js";
|
||||
|
||||
export interface HealthCheckProvider {
|
||||
readonly kind: "local" | "cloudflare";
|
||||
probe(target: HealthCheckTarget): Promise<ProbeResult>;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { IpHealthState, NodeHealthState } from "@cfdm/shared";
|
||||
|
||||
export interface HealthThresholds {
|
||||
degradedFailures: number;
|
||||
downFailures: number;
|
||||
successRecoveries: number;
|
||||
latencyWarnMs: number;
|
||||
}
|
||||
|
||||
export interface HealthCounters {
|
||||
status: string;
|
||||
consecutive_failures: number;
|
||||
consecutive_successes?: number;
|
||||
}
|
||||
|
||||
export interface NextHealth {
|
||||
legacy: IpHealthState;
|
||||
node: NodeHealthState;
|
||||
failures: number;
|
||||
successes: number;
|
||||
}
|
||||
|
||||
function wasHealthy(status: string | undefined): boolean {
|
||||
return status === "up" || status === "healthy";
|
||||
}
|
||||
|
||||
function wasUnhealthy(status: string | undefined): boolean {
|
||||
return (
|
||||
status === "down" ||
|
||||
status === "unhealthy" ||
|
||||
status === "checking" ||
|
||||
status === "degraded"
|
||||
);
|
||||
}
|
||||
|
||||
export function nextHealthState(
|
||||
ok: boolean,
|
||||
latencyMs: number,
|
||||
prev: HealthCounters | null,
|
||||
thresholds: HealthThresholds,
|
||||
): NextHealth {
|
||||
if (!ok) {
|
||||
const failures = (prev?.consecutive_failures ?? 0) + 1;
|
||||
if (failures >= thresholds.downFailures) {
|
||||
return { legacy: "down", node: "unhealthy", failures, successes: 0 };
|
||||
}
|
||||
return { legacy: "degraded", node: "degraded", failures, successes: 0 };
|
||||
}
|
||||
|
||||
if (latencyMs > thresholds.latencyWarnMs) {
|
||||
return { legacy: "degraded", node: "degraded", failures: 0, successes: 0 };
|
||||
}
|
||||
|
||||
if (!prev || wasHealthy(prev.status) || !wasUnhealthy(prev.status)) {
|
||||
return {
|
||||
legacy: "up",
|
||||
node: "healthy",
|
||||
failures: 0,
|
||||
successes: (prev?.consecutive_successes ?? 0) + 1,
|
||||
};
|
||||
}
|
||||
|
||||
const successes = (prev.consecutive_successes ?? 0) + 1;
|
||||
if (successes >= thresholds.successRecoveries) {
|
||||
return { legacy: "up", node: "healthy", failures: 0, successes };
|
||||
}
|
||||
return { legacy: "unknown", node: "checking", failures: 0, successes };
|
||||
}
|
||||
|
||||
export function toLegacyHealth(status: NodeHealthState | IpHealthState): IpHealthState {
|
||||
if (status === "healthy" || status === "up") return "up";
|
||||
if (status === "unhealthy" || status === "down") return "down";
|
||||
if (status === "degraded") return "degraded";
|
||||
return "unknown";
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import type { Db } from "@cfdm/db";
|
||||
import { repos } from "@cfdm/db";
|
||||
import type {
|
||||
CreateServiceNodeInput,
|
||||
ServiceNode,
|
||||
ServiceOverview,
|
||||
UpdateServiceNodeInput,
|
||||
} from "@cfdm/shared";
|
||||
import { AppError } from "../errors.js";
|
||||
import { isValidIpv4 } from "../lib/validators.js";
|
||||
import { getView } from "./service-config-service.js";
|
||||
import { selectActiveIpsByMode } from "./routing/index.js";
|
||||
|
||||
function assertAddress(address: string): void {
|
||||
if (!isValidIpv4(address)) {
|
||||
throw AppError.invalidIp(`Некорректный IP-адрес: ${address}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function listNodes(db: Db, serviceId: number): ServiceNode[] {
|
||||
repos.getService(db, serviceId);
|
||||
return repos.listNodes(db, serviceId);
|
||||
}
|
||||
|
||||
export function createNode(
|
||||
db: Db,
|
||||
serviceId: number,
|
||||
input: CreateServiceNodeInput,
|
||||
): ServiceNode {
|
||||
repos.getService(db, serviceId);
|
||||
assertAddress(input.address);
|
||||
try {
|
||||
return repos.createNode(db, serviceId, {
|
||||
address: input.address,
|
||||
protocol: input.protocol,
|
||||
port: input.port,
|
||||
enabled: input.enabled,
|
||||
priority: input.priority,
|
||||
weight: input.weight,
|
||||
health_check_id: input.health_check_id,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.name === "ConflictError") {
|
||||
throw AppError.conflict(err.message);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export function updateNode(
|
||||
db: Db,
|
||||
serviceId: number,
|
||||
nodeId: number,
|
||||
patch: UpdateServiceNodeInput,
|
||||
): ServiceNode {
|
||||
const node = repos.getNode(db, nodeId);
|
||||
if (node.service_id !== serviceId) {
|
||||
throw AppError.notFound(`node ${nodeId}`);
|
||||
}
|
||||
if (patch.address) assertAddress(patch.address);
|
||||
return repos.updateNode(db, nodeId, patch);
|
||||
}
|
||||
|
||||
export function deleteNode(db: Db, serviceId: number, nodeId: number): void {
|
||||
const node = repos.getNode(db, nodeId);
|
||||
if (node.service_id !== serviceId) {
|
||||
throw AppError.notFound(`node ${nodeId}`);
|
||||
}
|
||||
repos.deleteNode(db, nodeId);
|
||||
}
|
||||
|
||||
export async function getOverview(
|
||||
db: Db,
|
||||
serviceId: number,
|
||||
): Promise<ServiceOverview> {
|
||||
const service = await getView(db, serviceId);
|
||||
const nodes = repos.listNodes(db, serviceId);
|
||||
const bindings = repos.listBindingsByService(db, serviceId);
|
||||
const first = bindings[0];
|
||||
const routing = first?.routing_strategy ?? first?.lb_mode ?? "round_robin";
|
||||
const healthCheck =
|
||||
nodes
|
||||
.map((n) => n.health_check_id)
|
||||
.find((id): id is number => id != null) != null
|
||||
? repos.getHealthCheck(
|
||||
db,
|
||||
nodes.find((n) => n.health_check_id != null)!.health_check_id!,
|
||||
)
|
||||
: null;
|
||||
|
||||
const active = new Set<string>();
|
||||
for (const binding of bindings) {
|
||||
const metas = repos.listBindingIpsWithMeta(db, binding.id);
|
||||
const rows = metas.map((entry) => {
|
||||
const status = repos.getIpHealthStatusRow(db, "binding", binding.id, entry.ip);
|
||||
return {
|
||||
ip: entry.ip,
|
||||
weight: entry.weight,
|
||||
priority: entry.priority,
|
||||
health: status ? status.status : ("unknown" as const),
|
||||
};
|
||||
});
|
||||
for (const ip of selectActiveIpsByMode(
|
||||
{
|
||||
lb_mode: binding.lb_mode,
|
||||
health_check_enabled: binding.health_check_enabled,
|
||||
},
|
||||
rows,
|
||||
)) {
|
||||
active.add(ip);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
service,
|
||||
nodes,
|
||||
health_check: healthCheck,
|
||||
routing_strategy: routing,
|
||||
active_addresses: [...active],
|
||||
};
|
||||
}
|
||||
|
||||
export function opsSummary(db: Db) {
|
||||
const allNodes = repos.listAllNodes(db);
|
||||
const services = repos.listServices(db);
|
||||
const domains = repos.listDomains(db);
|
||||
const healthy = allNodes.filter(
|
||||
(n) => n.health_status === "healthy" || n.health_status === "up",
|
||||
).length;
|
||||
const unhealthy = allNodes.filter(
|
||||
(n) => n.health_status === "unhealthy" || n.health_status === "down",
|
||||
).length;
|
||||
const failoverActive = repos.listAllBindings(db).filter((binding) => {
|
||||
if (binding.lb_mode !== "failover" || !binding.health_check_enabled) {
|
||||
return false;
|
||||
}
|
||||
return binding.target_ips.some((ip) => {
|
||||
const row = repos.getIpHealthStatusRow(db, "binding", binding.id, ip);
|
||||
return row?.status === "down";
|
||||
});
|
||||
}).length;
|
||||
return {
|
||||
domains: domains.length,
|
||||
services: services.length,
|
||||
nodes: allNodes.length,
|
||||
healthy,
|
||||
unhealthy,
|
||||
active_failovers: failoverActive,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import type { Db } from "@cfdm/db";
|
||||
import { repos } from "@cfdm/db";
|
||||
import type {
|
||||
CreateOriginHealthCheckInput,
|
||||
OriginHealthCheck,
|
||||
} from "@cfdm/shared";
|
||||
import type { CloudflareClient } from "../lib/cf-client.js";
|
||||
import { AppError } from "../errors.js";
|
||||
import { CloudflareHealthCheckProvider } from "./health/cloudflare.js";
|
||||
|
||||
export function listOriginHealthChecks(db: Db): OriginHealthCheck[] {
|
||||
return repos.listHealthChecks(db);
|
||||
}
|
||||
|
||||
export function getOriginHealthCheck(db: Db, id: number): OriginHealthCheck {
|
||||
return repos.getHealthCheck(db, id);
|
||||
}
|
||||
|
||||
export async function createOriginHealthCheck(
|
||||
db: Db,
|
||||
cf: CloudflareClient,
|
||||
input: CreateOriginHealthCheckInput,
|
||||
): Promise<OriginHealthCheck> {
|
||||
const protocol = (input.protocol ?? "tcp").toLowerCase();
|
||||
const check = repos.createHealthCheck(db, {
|
||||
provider: input.provider,
|
||||
name: input.name,
|
||||
cf_zone_id: input.cf_zone_id ?? null,
|
||||
protocol,
|
||||
path: input.path,
|
||||
method: input.method,
|
||||
timeout: input.timeout,
|
||||
interval_sec: input.interval_sec,
|
||||
retries: input.retries,
|
||||
expected_status: input.expected_status,
|
||||
consecutive_fails: input.consecutive_fails,
|
||||
consecutive_successes: input.consecutive_successes,
|
||||
suspended: input.suspended,
|
||||
});
|
||||
|
||||
if (input.node_id) {
|
||||
const node = repos.getNode(db, input.node_id);
|
||||
repos.updateNode(db, node.id, { health_check_id: check.id });
|
||||
}
|
||||
|
||||
if (input.provider === "cloudflare") {
|
||||
const zoneId = input.cf_zone_id;
|
||||
if (!zoneId) {
|
||||
throw AppError.zoneNotFound("укажите зону Cloudflare для Health Check");
|
||||
}
|
||||
const address = input.node_id
|
||||
? repos.getNode(db, input.node_id).address
|
||||
: check.name;
|
||||
const provider = new CloudflareHealthCheckProvider(db, cf);
|
||||
await provider.syncCreate(check, zoneId, address);
|
||||
return repos.getHealthCheck(db, check.id);
|
||||
}
|
||||
|
||||
return check;
|
||||
}
|
||||
|
||||
export async function updateOriginHealthCheck(
|
||||
db: Db,
|
||||
cf: CloudflareClient,
|
||||
id: number,
|
||||
patch: Partial<CreateOriginHealthCheckInput>,
|
||||
): Promise<OriginHealthCheck> {
|
||||
const current = repos.getHealthCheck(db, id);
|
||||
const updated = repos.updateHealthCheck(db, id, {
|
||||
provider: patch.provider,
|
||||
name: patch.name,
|
||||
cf_zone_id: patch.cf_zone_id,
|
||||
protocol: patch.protocol?.toLowerCase(),
|
||||
path: patch.path,
|
||||
method: patch.method,
|
||||
timeout: patch.timeout,
|
||||
interval_sec: patch.interval_sec,
|
||||
retries: patch.retries,
|
||||
expected_status: patch.expected_status,
|
||||
consecutive_fails: patch.consecutive_fails,
|
||||
consecutive_successes: patch.consecutive_successes,
|
||||
suspended: patch.suspended,
|
||||
});
|
||||
if (updated.provider === "cloudflare" && updated.cf_healthcheck_id) {
|
||||
const address = repos.findNodeByIp(db, updated.name)?.address ?? updated.name;
|
||||
const provider = new CloudflareHealthCheckProvider(db, cf);
|
||||
await provider.syncUpdate(updated, address);
|
||||
}
|
||||
void current;
|
||||
return repos.getHealthCheck(db, id);
|
||||
}
|
||||
|
||||
export async function deleteOriginHealthCheck(
|
||||
db: Db,
|
||||
cf: CloudflareClient,
|
||||
id: number,
|
||||
): Promise<void> {
|
||||
const check = repos.getHealthCheck(db, id);
|
||||
if (check.provider === "cloudflare") {
|
||||
const provider = new CloudflareHealthCheckProvider(db, cf);
|
||||
await provider.syncDelete(check);
|
||||
}
|
||||
repos.deleteHealthCheck(db, id);
|
||||
}
|
||||
|
||||
export async function syncOriginHealthCheck(
|
||||
db: Db,
|
||||
cf: CloudflareClient,
|
||||
id: number,
|
||||
): Promise<OriginHealthCheck> {
|
||||
const check = repos.getHealthCheck(db, id);
|
||||
if (check.provider !== "cloudflare") {
|
||||
throw AppError.validation("синхронизация доступна только для Cloudflare Health Checks");
|
||||
}
|
||||
if (!check.cf_zone_id) {
|
||||
throw AppError.zoneNotFound();
|
||||
}
|
||||
const provider = new CloudflareHealthCheckProvider(db, cf);
|
||||
const address = repos.findNodeByIp(db, check.name)?.address ?? check.name;
|
||||
if (check.cf_healthcheck_id) {
|
||||
await provider.syncUpdate(check, address);
|
||||
} else {
|
||||
await provider.syncCreate(check, check.cf_zone_id, address);
|
||||
}
|
||||
return repos.getHealthCheck(db, id);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
const locks = new Map<number, Promise<void>>();
|
||||
|
||||
export async function withBindingLock<T>(
|
||||
bindingId: number,
|
||||
fn: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
const previous = locks.get(bindingId) ?? Promise.resolve();
|
||||
let release!: () => void;
|
||||
const current = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
locks.set(
|
||||
bindingId,
|
||||
previous.then(() => current).catch(() => current),
|
||||
);
|
||||
await previous.catch(() => undefined);
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
release();
|
||||
if (locks.get(bindingId) === current) {
|
||||
locks.delete(bindingId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { LbIpRow } from "./types.js";
|
||||
import { isHealthy } from "./health.js";
|
||||
|
||||
export function failoverDesired(rows: LbIpRow[]): string[] {
|
||||
if (rows.length === 0) return [];
|
||||
const healthy = rows.filter((r) => isHealthy(r.health));
|
||||
const pool = healthy.length > 0 ? healthy : rows;
|
||||
const sorted = [...pool].sort(
|
||||
(a, b) => a.priority - b.priority || a.weight - b.weight,
|
||||
);
|
||||
const minPriority = sorted[0]!.priority;
|
||||
const primaries = sorted.filter((r) => r.priority === minPriority);
|
||||
if (healthy.length > 0) {
|
||||
return primaries.map((r) => r.ip);
|
||||
}
|
||||
return [sorted[0]!.ip];
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import type { IpHealthState, NodeHealthState } from "@cfdm/shared";
|
||||
|
||||
export function isHealthy(state: IpHealthState | NodeHealthState | string): boolean {
|
||||
return state === "up" || state === "healthy";
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { LbMode } from "@cfdm/shared";
|
||||
import { failoverDesired } from "./failover.js";
|
||||
import { roundRobinDesired } from "./round-robin.js";
|
||||
import type { LbIpRow, LbTargetConfig } from "./types.js";
|
||||
|
||||
export type { LbIpRow, LbTargetConfig } from "./types.js";
|
||||
export { isHealthy } from "./health.js";
|
||||
export { withBindingLock } from "./binding-lock.js";
|
||||
|
||||
export function selectActiveIpsByMode(
|
||||
config: LbTargetConfig,
|
||||
rows: LbIpRow[],
|
||||
): string[] {
|
||||
if (rows.length === 0) return [];
|
||||
if (config.lb_mode === "failover") {
|
||||
return failoverDesired(rows);
|
||||
}
|
||||
// weighted = round_robin on DNS (one A per IP)
|
||||
return roundRobinDesired(rows);
|
||||
}
|
||||
|
||||
export function strategyLabel(mode: LbMode): string {
|
||||
if (mode === "failover") return "Failover";
|
||||
if (mode === "weighted") return "Round Robin (weighted alias)";
|
||||
return "Round Robin";
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { LbIpRow } from "./types.js";
|
||||
import { isHealthy } from "./health.js";
|
||||
|
||||
export function roundRobinDesired(rows: LbIpRow[]): string[] {
|
||||
const healthy = rows.filter((r) => isHealthy(r.health));
|
||||
const pool = healthy.length > 0 ? healthy : rows;
|
||||
return pool.map((r) => r.ip);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { IpHealthState, LbMode } from "@cfdm/shared";
|
||||
|
||||
export interface LbTargetConfig {
|
||||
lb_mode: LbMode;
|
||||
health_check_enabled: boolean;
|
||||
}
|
||||
|
||||
export interface LbIpRow {
|
||||
ip: string;
|
||||
weight: number;
|
||||
priority: number;
|
||||
health: IpHealthState;
|
||||
}
|
||||
@@ -24,6 +24,15 @@ import { isValidIpv4 } from "../lib/validators.js";
|
||||
import * as dnsService from "./dns-service.js";
|
||||
import * as domainService from "./domain-service.js";
|
||||
import { syncServiceToVpsTracker } from "./vps-tracker-sync.js";
|
||||
import {
|
||||
selectActiveIpsByMode,
|
||||
withBindingLock,
|
||||
type LbIpRow,
|
||||
type LbTargetConfig,
|
||||
} from "./routing/index.js";
|
||||
|
||||
export type { LbIpRow, LbTargetConfig };
|
||||
export { selectActiveIpsByMode };
|
||||
|
||||
export interface ServiceDomainInput {
|
||||
fqdn: string;
|
||||
@@ -40,6 +49,7 @@ export interface ServiceDomainInput {
|
||||
health_check_expected_status?: number | null;
|
||||
health_check_interval_sec?: number;
|
||||
health_check_timeout_ms?: number;
|
||||
health_check_verify_tls?: boolean;
|
||||
}
|
||||
|
||||
export interface ToggleRequest {
|
||||
@@ -59,6 +69,7 @@ export interface ServiceGroupBody {
|
||||
health_check_expected_status?: number | null;
|
||||
health_check_interval_sec?: number;
|
||||
health_check_timeout_ms?: number;
|
||||
health_check_verify_tls?: boolean;
|
||||
}
|
||||
|
||||
export interface UpdateServiceGroupBody {
|
||||
@@ -74,6 +85,7 @@ export interface UpdateServiceGroupBody {
|
||||
health_check_expected_status?: number | null;
|
||||
health_check_interval_sec?: number;
|
||||
health_check_timeout_ms?: number;
|
||||
health_check_verify_tls?: boolean;
|
||||
}
|
||||
|
||||
export interface UpdateServiceConfigRequest {
|
||||
@@ -134,54 +146,6 @@ function aggregateSyncStatus(statuses: string[]): string | null {
|
||||
return statuses[0] ?? null;
|
||||
}
|
||||
|
||||
function isHealthy(state: IpHealthState): boolean {
|
||||
return state === "up" || state === "unknown";
|
||||
}
|
||||
|
||||
export interface LbTargetConfig {
|
||||
lb_mode: LbMode;
|
||||
health_check_enabled: boolean;
|
||||
}
|
||||
|
||||
export interface LbIpRow {
|
||||
ip: string;
|
||||
weight: number;
|
||||
priority: number;
|
||||
health: IpHealthState;
|
||||
}
|
||||
|
||||
export function selectActiveIpsByMode(
|
||||
config: LbTargetConfig,
|
||||
rows: LbIpRow[],
|
||||
): string[] {
|
||||
if (rows.length === 0) return [];
|
||||
|
||||
const healthy = rows.filter((r) => isHealthy(r.health));
|
||||
const pool = healthy.length > 0 ? healthy : rows;
|
||||
|
||||
if (config.lb_mode === "failover") {
|
||||
const sorted = [...pool].sort(
|
||||
(a, b) => a.priority - b.priority || a.weight - b.weight,
|
||||
);
|
||||
const minPriority = sorted[0]!.priority;
|
||||
const primaries = sorted.filter((r) => r.priority === minPriority);
|
||||
if (healthy.length > 0) {
|
||||
return primaries.map((r) => r.ip);
|
||||
}
|
||||
return [sorted[0]!.ip];
|
||||
}
|
||||
|
||||
if (config.lb_mode === "weighted") {
|
||||
// Cloudflare не допускает дублирования A-записей с одинаковым name+content,
|
||||
// поэтому weighted на уровне DNS реализован как RR по одному A на IP.
|
||||
// Веса сохраняются в БД и используются для приоритизации/отображения;
|
||||
// точное weighted-распределение требует CF Load Balancer (см. README).
|
||||
return pool.map((r) => r.ip);
|
||||
}
|
||||
|
||||
return pool.map((r) => r.ip);
|
||||
}
|
||||
|
||||
function getBindingLbState(
|
||||
db: Db,
|
||||
bindingId: number,
|
||||
@@ -322,6 +286,7 @@ async function buildView(db: Db, serviceId: number): Promise<ServiceView> {
|
||||
health_check_expected_status: binding.health_check_expected_status,
|
||||
health_check_interval_sec: binding.health_check_interval_sec,
|
||||
health_check_timeout_ms: binding.health_check_timeout_ms,
|
||||
health_check_verify_tls: binding.health_check_verify_tls,
|
||||
sync_status: aggregateSyncStatus(statuses),
|
||||
};
|
||||
});
|
||||
@@ -400,9 +365,8 @@ export async function listGroupViews(db: Db): Promise<ServiceGroupsResponse> {
|
||||
const withHealth = attachServiceHealth(db, allServiceViews);
|
||||
const healthById = new Map(withHealth.map((v) => [v.id, v]));
|
||||
|
||||
const groupHealthById = repos.aggregateIpHealthByRefs(
|
||||
const groupHealthById = repos.aggregateGroupScopeHealthByIds(
|
||||
db,
|
||||
"group",
|
||||
groups.map((g) => g.id),
|
||||
);
|
||||
|
||||
@@ -411,12 +375,17 @@ export async function listGroupViews(db: Db): Promise<ServiceGroupsResponse> {
|
||||
(s) => healthById.get(s.id) ?? { ...s, health_status: "unknown" as const, health_latency_ms: null },
|
||||
);
|
||||
const groupScopeHealth = groupHealthById.get(group.id);
|
||||
const merged = repos.mergeHealthAggregates([
|
||||
groupScopeHealth,
|
||||
...services.map((s) => ({
|
||||
// Only enabled services feed the group badge — a disabled service with a
|
||||
// stale `down` must not keep the group red while live members are OK.
|
||||
const enabledServiceHealth = services
|
||||
.filter((s) => s.enabled)
|
||||
.map((s) => ({
|
||||
health_status: s.health_status,
|
||||
health_latency_ms: s.health_latency_ms,
|
||||
})),
|
||||
}));
|
||||
const merged = repos.mergeHealthAggregates([
|
||||
groupScopeHealth,
|
||||
...enabledServiceHealth,
|
||||
]);
|
||||
return {
|
||||
...group,
|
||||
@@ -815,49 +784,6 @@ async function findOrImportDnsARecord(
|
||||
);
|
||||
}
|
||||
|
||||
async function serviceBindingsExistInDns(
|
||||
db: Db,
|
||||
cf: CloudflareClient,
|
||||
serviceId: number,
|
||||
): Promise<boolean> {
|
||||
const bindings = repos.listBindingsByService(db, serviceId);
|
||||
if (bindings.length === 0) return false;
|
||||
|
||||
for (const binding of bindings) {
|
||||
const cnameTarget = binding.cname_target?.trim() || null;
|
||||
if (cnameTarget) {
|
||||
const record = await findOrImportDnsRecord(
|
||||
db,
|
||||
cf,
|
||||
binding.domain_id,
|
||||
binding.zone_name,
|
||||
binding.hostname,
|
||||
"CNAME",
|
||||
cnameTarget,
|
||||
);
|
||||
if (!record) return false;
|
||||
continue;
|
||||
}
|
||||
|
||||
const targetIps = repos.listBindingIps(db, binding.id);
|
||||
if (targetIps.length === 0) return false;
|
||||
|
||||
for (const ip of targetIps) {
|
||||
const record = await findOrImportDnsARecord(
|
||||
db,
|
||||
cf,
|
||||
binding.domain_id,
|
||||
binding.zone_name,
|
||||
binding.hostname,
|
||||
ip,
|
||||
);
|
||||
if (!record) return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async function syncServiceBindingsToDns(
|
||||
db: Db,
|
||||
cf: CloudflareClient,
|
||||
@@ -1168,95 +1094,95 @@ export async function updateConfig(
|
||||
let removedBindingIds: number[] = [];
|
||||
|
||||
if (req.domains) {
|
||||
if (req.domains.length > 0) {
|
||||
for (const input of req.domains) {
|
||||
const fqdn = input.fqdn.trim();
|
||||
if (!fqdn) continue;
|
||||
const targetCname = bindingTargetCname(input);
|
||||
const targetIps = bindingTargetIps(input);
|
||||
if (!targetCname) {
|
||||
validateTargetIpsInPool(targetIps, ips);
|
||||
} else if (targetIps.length > 0) {
|
||||
throw AppError.validation(
|
||||
`укажите либо IP, либо CNAME для ${fqdn}`,
|
||||
);
|
||||
}
|
||||
|
||||
const { zoneName, hostname } = parseFqdn(fqdn, knownZones);
|
||||
const domainId = await resolveDomainId(db, cf, zoneName);
|
||||
|
||||
const binding =
|
||||
repos.findBinding(db, id, domainId, hostname) ??
|
||||
repos.insertBinding(db, domainId, id, hostname, null);
|
||||
|
||||
keptBindingIds.push(binding.id);
|
||||
|
||||
const targetIpWeights = input.target_ip_weights ?? {};
|
||||
const targetIpPriorities = input.target_ip_priorities ?? {};
|
||||
const bindingIpEntries = (targetCname ? [] : targetIps).map((ip) => ({
|
||||
ip,
|
||||
weight: targetIpWeights[ip] ?? 1,
|
||||
priority: targetIpPriorities[ip] ?? 1,
|
||||
}));
|
||||
repos.replaceBindingIpsWithMeta(db, binding.id, bindingIpEntries);
|
||||
repos.setBindingCnameTarget(db, binding.id, targetCname);
|
||||
|
||||
if (
|
||||
input.lb_mode !== undefined ||
|
||||
input.health_check_enabled !== undefined ||
|
||||
input.health_check_type !== undefined ||
|
||||
input.health_check_port !== undefined ||
|
||||
input.health_check_path !== undefined ||
|
||||
input.health_check_expected_status !== undefined ||
|
||||
input.health_check_interval_sec !== undefined ||
|
||||
input.health_check_timeout_ms !== undefined
|
||||
) {
|
||||
repos.updateBindingLbConfig(db, binding.id, {
|
||||
lb_mode: input.lb_mode,
|
||||
health_check_enabled: input.health_check_enabled,
|
||||
health_check_type: input.health_check_type,
|
||||
health_check_port: input.health_check_port,
|
||||
health_check_path: input.health_check_path,
|
||||
health_check_expected_status: input.health_check_expected_status,
|
||||
health_check_interval_sec: input.health_check_interval_sec,
|
||||
health_check_timeout_ms: input.health_check_timeout_ms,
|
||||
});
|
||||
}
|
||||
|
||||
if (pushDns) {
|
||||
let effectiveIps = targetIps;
|
||||
const refreshedBinding = repos.getBinding(db, binding.id);
|
||||
if (refreshedBinding.health_check_enabled) {
|
||||
const activeIps = computeActiveIps(db, "binding", binding.id);
|
||||
if (activeIps.length > 0) {
|
||||
effectiveIps = activeIps;
|
||||
}
|
||||
}
|
||||
await syncBindingDns(
|
||||
db,
|
||||
cf,
|
||||
binding.id,
|
||||
domainId,
|
||||
hostname,
|
||||
effectiveIps,
|
||||
targetCname,
|
||||
);
|
||||
}
|
||||
for (const input of req.domains) {
|
||||
const fqdn = input.fqdn.trim();
|
||||
if (!fqdn) continue;
|
||||
const targetCname = bindingTargetCname(input);
|
||||
const targetIps = bindingTargetIps(input);
|
||||
if (!targetCname) {
|
||||
validateTargetIpsInPool(targetIps, ips);
|
||||
} else if (targetIps.length > 0) {
|
||||
throw AppError.validation(
|
||||
`укажите либо IP, либо CNAME для ${fqdn}`,
|
||||
);
|
||||
}
|
||||
|
||||
const removed = repos.bindingsToRemove(db, id, keptBindingIds);
|
||||
removedBindingIds = removed.map((binding) => binding.id);
|
||||
for (const binding of removed) {
|
||||
await cleanupBindingDns(
|
||||
const { zoneName, hostname } = parseFqdn(fqdn, knownZones);
|
||||
const domainId = await resolveDomainId(db, cf, zoneName);
|
||||
|
||||
const binding =
|
||||
repos.findBinding(db, id, domainId, hostname) ??
|
||||
repos.insertBinding(db, domainId, id, hostname, null);
|
||||
|
||||
keptBindingIds.push(binding.id);
|
||||
|
||||
const targetIpWeights = input.target_ip_weights ?? {};
|
||||
const targetIpPriorities = input.target_ip_priorities ?? {};
|
||||
const bindingIpEntries = (targetCname ? [] : targetIps).map((ip) => ({
|
||||
ip,
|
||||
weight: targetIpWeights[ip] ?? 1,
|
||||
priority: targetIpPriorities[ip] ?? 1,
|
||||
}));
|
||||
repos.replaceBindingIpsWithMeta(db, binding.id, bindingIpEntries);
|
||||
repos.setBindingCnameTarget(db, binding.id, targetCname);
|
||||
|
||||
if (
|
||||
input.lb_mode !== undefined ||
|
||||
input.health_check_enabled !== undefined ||
|
||||
input.health_check_type !== undefined ||
|
||||
input.health_check_port !== undefined ||
|
||||
input.health_check_path !== undefined ||
|
||||
input.health_check_expected_status !== undefined ||
|
||||
input.health_check_interval_sec !== undefined ||
|
||||
input.health_check_timeout_ms !== undefined ||
|
||||
input.health_check_verify_tls !== undefined
|
||||
) {
|
||||
repos.updateBindingLbConfig(db, binding.id, {
|
||||
lb_mode: input.lb_mode,
|
||||
health_check_enabled: input.health_check_enabled,
|
||||
health_check_type: input.health_check_type,
|
||||
health_check_port: input.health_check_port,
|
||||
health_check_path: input.health_check_path,
|
||||
health_check_expected_status: input.health_check_expected_status,
|
||||
health_check_interval_sec: input.health_check_interval_sec,
|
||||
health_check_timeout_ms: input.health_check_timeout_ms,
|
||||
health_check_verify_tls: input.health_check_verify_tls,
|
||||
});
|
||||
}
|
||||
|
||||
if (pushDns) {
|
||||
let effectiveIps = targetIps;
|
||||
const refreshedBinding = repos.getBinding(db, binding.id);
|
||||
if (refreshedBinding.health_check_enabled) {
|
||||
const activeIps = computeActiveIps(db, "binding", binding.id);
|
||||
if (activeIps.length > 0) {
|
||||
effectiveIps = activeIps;
|
||||
}
|
||||
}
|
||||
await syncBindingDns(
|
||||
db,
|
||||
cf,
|
||||
binding.id,
|
||||
binding.domain_id,
|
||||
binding.hostname,
|
||||
domainId,
|
||||
hostname,
|
||||
effectiveIps,
|
||||
targetCname,
|
||||
);
|
||||
}
|
||||
repos.deleteBindingsExcept(db, id, keptBindingIds);
|
||||
}
|
||||
|
||||
const removed = repos.bindingsToRemove(db, id, keptBindingIds);
|
||||
removedBindingIds = removed.map((binding) => binding.id);
|
||||
for (const binding of removed) {
|
||||
await cleanupBindingDns(
|
||||
db,
|
||||
cf,
|
||||
binding.id,
|
||||
binding.domain_id,
|
||||
binding.hostname,
|
||||
);
|
||||
}
|
||||
repos.deleteBindingsExcept(db, id, keptBindingIds);
|
||||
} else if (ipsUpdated) {
|
||||
const bindings = repos.listBindingsByService(db, id);
|
||||
for (const binding of bindings) {
|
||||
@@ -1272,17 +1198,24 @@ export async function updateConfig(
|
||||
}
|
||||
|
||||
service = repos.getService(db, id);
|
||||
if (shouldPushDns(db, service)) {
|
||||
await syncServiceBindingsToDns(db, cf, id);
|
||||
await syncGroupDomainForService(db, cf, id);
|
||||
} else if (
|
||||
const remainingBindings = repos.listBindingsByService(db, id);
|
||||
|
||||
// Creating/editing with FQDN bindings should publish DNS. Previously a
|
||||
// disabled service stayed off unless records already existed in Cloudflare
|
||||
// (chicken-and-egg for brand-new services).
|
||||
if (
|
||||
req.domains &&
|
||||
req.domains.length > 0 &&
|
||||
!service.enabled &&
|
||||
(await serviceBindingsExistInDns(db, cf, id))
|
||||
!service.enabled
|
||||
) {
|
||||
repos.setServiceEnabled(db, id, true);
|
||||
await syncServiceBindingsToDns(db, cf, id);
|
||||
service = repos.getService(db, id);
|
||||
}
|
||||
|
||||
if (shouldPushDns(db, service)) {
|
||||
if (remainingBindings.length > 0) {
|
||||
await syncServiceBindingsToDns(db, cf, id);
|
||||
}
|
||||
await syncGroupDomainForService(db, cf, id);
|
||||
}
|
||||
|
||||
@@ -1314,6 +1247,7 @@ export async function createGroup(
|
||||
health_check_expected_status: body.health_check_expected_status,
|
||||
health_check_interval_sec: body.health_check_interval_sec,
|
||||
health_check_timeout_ms: body.health_check_timeout_ms,
|
||||
health_check_verify_tls: body.health_check_verify_tls,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1349,6 +1283,7 @@ export async function updateGroup(
|
||||
health_check_expected_status: body.health_check_expected_status,
|
||||
health_check_interval_sec: body.health_check_interval_sec,
|
||||
health_check_timeout_ms: body.health_check_timeout_ms,
|
||||
health_check_verify_tls: body.health_check_verify_tls,
|
||||
},
|
||||
);
|
||||
if (!domain && group.enabled) {
|
||||
@@ -1437,6 +1372,25 @@ export function reorderServices(
|
||||
repos.reorderServices(db, groupId, serviceIds);
|
||||
}
|
||||
|
||||
export async function applyBindingDesiredDns(
|
||||
db: Db,
|
||||
cf: CloudflareClient,
|
||||
bindingId: number,
|
||||
desiredIps: string[],
|
||||
): Promise<void> {
|
||||
const binding = repos.getBinding(db, bindingId);
|
||||
const cnameTarget = binding.cname_target?.trim() || null;
|
||||
await syncBindingDns(
|
||||
db,
|
||||
cf,
|
||||
binding.id,
|
||||
binding.domain_id,
|
||||
binding.hostname,
|
||||
desiredIps,
|
||||
cnameTarget,
|
||||
);
|
||||
}
|
||||
|
||||
export async function reconcileDnsForTarget(
|
||||
db: Db,
|
||||
cf: CloudflareClient,
|
||||
@@ -1444,26 +1398,28 @@ export async function reconcileDnsForTarget(
|
||||
refId: number,
|
||||
): Promise<void> {
|
||||
if (scope === "binding") {
|
||||
const binding = repos.getBinding(db, refId);
|
||||
if (!binding.health_check_enabled) return;
|
||||
const service = repos.getService(db, binding.service_id);
|
||||
if (!shouldPushDns(db, service)) return;
|
||||
const cnameTarget = binding.cname_target?.trim() || null;
|
||||
if (cnameTarget) return;
|
||||
const ips = repos.listServiceIps(db, service.id);
|
||||
const targetIps = repos.listBindingIps(db, binding.id);
|
||||
validateTargetIpsInPool(targetIps, ips);
|
||||
const activeIps = computeActiveIps(db, "binding", refId);
|
||||
const desiredIps = activeIps.length > 0 ? activeIps : targetIps;
|
||||
await syncBindingDns(
|
||||
db,
|
||||
cf,
|
||||
binding.id,
|
||||
binding.domain_id,
|
||||
binding.hostname,
|
||||
desiredIps,
|
||||
null,
|
||||
);
|
||||
await withBindingLock(refId, async () => {
|
||||
const binding = repos.getBinding(db, refId);
|
||||
if (!binding.health_check_enabled) return;
|
||||
const service = repos.getService(db, binding.service_id);
|
||||
if (!shouldPushDns(db, service)) return;
|
||||
const cnameTarget = binding.cname_target?.trim() || null;
|
||||
if (cnameTarget) return;
|
||||
const ips = repos.listServiceIps(db, service.id);
|
||||
const targetIps = repos.listBindingIps(db, binding.id);
|
||||
validateTargetIpsInPool(targetIps, ips);
|
||||
const activeIps = computeActiveIps(db, "binding", refId);
|
||||
const desiredIps = activeIps.length > 0 ? activeIps : targetIps;
|
||||
await syncBindingDns(
|
||||
db,
|
||||
cf,
|
||||
binding.id,
|
||||
binding.domain_id,
|
||||
binding.hostname,
|
||||
desiredIps,
|
||||
null,
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { CfdmBindingSyncItem } from "@cfdm/shared";
|
||||
import { resolve4 } from "node:dns/promises";
|
||||
import type { CfdmBindingSyncItem, ServiceBindingView } from "@cfdm/shared";
|
||||
import { isIpLiteral } from "@cfdm/shared";
|
||||
import type { Db } from "@cfdm/db";
|
||||
import { repos, getAppSettingsSecrets, touchVpsTrackerSync } from "@cfdm/db";
|
||||
|
||||
@@ -7,23 +9,127 @@ function fqdnToDisplay(hostname: string, zoneName: string): string {
|
||||
return `${hostname}.${zoneName}`;
|
||||
}
|
||||
|
||||
export function buildServiceSyncBindings(
|
||||
function normalizeCnameHost(target: string, zoneName: string): string {
|
||||
const trimmed = target.trim().toLowerCase().replace(/\.$/, "");
|
||||
if (!trimmed) return "";
|
||||
if (trimmed.includes(".")) return trimmed;
|
||||
return `${trimmed}.${zoneName.toLowerCase()}`;
|
||||
}
|
||||
|
||||
type BindingIpIndex = {
|
||||
byFqdn: Map<string, ServiceBindingView>;
|
||||
};
|
||||
|
||||
function buildBindingIndex(bindings: ServiceBindingView[]): BindingIpIndex {
|
||||
const byFqdn = new Map<string, ServiceBindingView>();
|
||||
for (const b of bindings) {
|
||||
const fqdn = fqdnToDisplay(b.hostname, b.zone_name).toLowerCase();
|
||||
byFqdn.set(fqdn, b);
|
||||
}
|
||||
return { byFqdn };
|
||||
}
|
||||
|
||||
/** Локальная цепочка CNAME → A (по bindings в CFDM), без внешнего DNS. */
|
||||
function resolveIpsLocally(
|
||||
index: BindingIpIndex,
|
||||
startFqdn: string,
|
||||
depth = 0,
|
||||
seen = new Set<string>(),
|
||||
): string[] {
|
||||
const key = startFqdn.toLowerCase().replace(/\.$/, "");
|
||||
if (!key || depth > 8 || seen.has(key)) return [];
|
||||
seen.add(key);
|
||||
|
||||
const binding = index.byFqdn.get(key);
|
||||
if (!binding) return [];
|
||||
|
||||
if (binding.target_ips.some(isIpLiteral)) {
|
||||
return binding.target_ips.filter(isIpLiteral);
|
||||
}
|
||||
|
||||
const cname = binding.cname_target?.trim();
|
||||
if (!cname) return [];
|
||||
|
||||
const next = normalizeCnameHost(cname, binding.zone_name);
|
||||
return resolveIpsLocally(index, next, depth + 1, seen);
|
||||
}
|
||||
|
||||
async function resolveIpsViaDns(hostname: string): Promise<string[]> {
|
||||
const host = hostname.trim().toLowerCase().replace(/\.$/, "");
|
||||
if (!host) return [];
|
||||
try {
|
||||
// resolve4 следует по CNAME до A-записей
|
||||
return await resolve4(host);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* IP для матчинга в VPS Tracker:
|
||||
* 1) A/AAAA binding (только литералы IP — не CNAME hostname из dns_record.content)
|
||||
* 2) локальная CNAME-цепочка по другим bindings
|
||||
* 3) origin A/AAAA из dns_records CFDM
|
||||
* 4) IP сервиса
|
||||
* 5) публичный DNS — последний и обычно вреден (CF anycast при proxied)
|
||||
*/
|
||||
export async function resolveBindingIpsForSync(
|
||||
binding: ServiceBindingView,
|
||||
serviceIps: string[],
|
||||
index: BindingIpIndex,
|
||||
db?: Db,
|
||||
): Promise<string[]> {
|
||||
const directIps = binding.target_ips.filter(isIpLiteral);
|
||||
if (directIps.length > 0) {
|
||||
return [...directIps];
|
||||
}
|
||||
|
||||
const cname = binding.cname_target?.trim();
|
||||
if (cname) {
|
||||
const targetFqdn = normalizeCnameHost(cname, binding.zone_name);
|
||||
const local = resolveIpsLocally(index, targetFqdn).filter(isIpLiteral);
|
||||
if (local.length > 0) return local;
|
||||
|
||||
if (db) {
|
||||
const fromTable = repos.listOriginIpsForFqdn(db, targetFqdn).filter(isIpLiteral);
|
||||
if (fromTable.length > 0) return fromTable;
|
||||
}
|
||||
}
|
||||
|
||||
const fromService = serviceIps.filter(isIpLiteral);
|
||||
if (fromService.length > 0) return [...fromService];
|
||||
|
||||
if (cname) {
|
||||
const targetFqdn = normalizeCnameHost(cname, binding.zone_name);
|
||||
const viaDns = (await resolveIpsViaDns(targetFqdn)).filter(isIpLiteral);
|
||||
if (viaDns.length > 0) return viaDns;
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
function cnameTargetForSync(binding: ServiceBindingView): string | undefined {
|
||||
const raw = binding.cname_target?.trim();
|
||||
if (!raw) return undefined;
|
||||
const normalized = normalizeCnameHost(raw, binding.zone_name);
|
||||
return normalized || undefined;
|
||||
}
|
||||
|
||||
export async function buildServiceSyncBindingsAsync(
|
||||
db: Db,
|
||||
serviceId: number,
|
||||
deletedBindingIds: number[] = [],
|
||||
): CfdmBindingSyncItem[] {
|
||||
): Promise<CfdmBindingSyncItem[]> {
|
||||
const service = repos.getService(db, serviceId);
|
||||
const serviceIps = repos.listServiceIps(db, serviceId);
|
||||
const allBindings = repos.listAllBindings(db);
|
||||
const index = buildBindingIndex(allBindings);
|
||||
const bindings = repos.listBindingsByService(db, serviceId);
|
||||
const items: CfdmBindingSyncItem[] = bindings.map((binding) => {
|
||||
const targetIps = repos.listBindingIps(db, binding.id);
|
||||
const ips =
|
||||
targetIps.length > 0
|
||||
? targetIps
|
||||
: serviceIps.length > 0
|
||||
? serviceIps
|
||||
: [];
|
||||
return {
|
||||
|
||||
const items: CfdmBindingSyncItem[] = [];
|
||||
for (const binding of bindings) {
|
||||
const ips = await resolveBindingIpsForSync(binding, serviceIps, index, db);
|
||||
items.push({
|
||||
bindingId: binding.id,
|
||||
serviceId: service.id,
|
||||
serviceName: service.name,
|
||||
@@ -32,8 +138,9 @@ export function buildServiceSyncBindings(
|
||||
zoneName: binding.zone_name,
|
||||
hostname: binding.hostname,
|
||||
ips,
|
||||
};
|
||||
});
|
||||
cnameTarget: cnameTargetForSync(binding),
|
||||
});
|
||||
}
|
||||
|
||||
for (const bindingId of deletedBindingIds) {
|
||||
items.push({
|
||||
@@ -52,6 +159,36 @@ export function buildServiceSyncBindings(
|
||||
return items;
|
||||
}
|
||||
|
||||
export async function buildAllSyncBindings(
|
||||
db: Db,
|
||||
): Promise<CfdmBindingSyncItem[]> {
|
||||
const bindings = repos.listAllBindings(db);
|
||||
const index = buildBindingIndex(bindings);
|
||||
const serviceIpCache = new Map<number, string[]>();
|
||||
|
||||
const items: CfdmBindingSyncItem[] = [];
|
||||
for (const binding of bindings) {
|
||||
let serviceIps = serviceIpCache.get(binding.service_id);
|
||||
if (!serviceIps) {
|
||||
serviceIps = repos.listServiceIps(db, binding.service_id);
|
||||
serviceIpCache.set(binding.service_id, serviceIps);
|
||||
}
|
||||
const ips = await resolveBindingIpsForSync(binding, serviceIps, index, db);
|
||||
items.push({
|
||||
bindingId: binding.id,
|
||||
serviceId: binding.service_id,
|
||||
serviceName: binding.service_name,
|
||||
serviceSlug: binding.service_slug,
|
||||
fqdn: fqdnToDisplay(binding.hostname, binding.zone_name),
|
||||
zoneName: binding.zone_name,
|
||||
hostname: binding.hostname,
|
||||
ips,
|
||||
cnameTarget: cnameTargetForSync(binding),
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
export async function syncServiceToVpsTracker(
|
||||
db: Db,
|
||||
serviceId: number,
|
||||
@@ -64,7 +201,11 @@ export async function syncServiceToVpsTracker(
|
||||
const token = config.vpsTrackerIntegrationToken;
|
||||
if (!baseUrl || !token) return;
|
||||
|
||||
const bindings = buildServiceSyncBindings(db, serviceId, deletedBindingIds);
|
||||
const bindings = await buildServiceSyncBindingsAsync(
|
||||
db,
|
||||
serviceId,
|
||||
deletedBindingIds,
|
||||
);
|
||||
if (bindings.length === 0) return;
|
||||
|
||||
try {
|
||||
@@ -91,6 +232,56 @@ export async function syncServiceToVpsTracker(
|
||||
}
|
||||
}
|
||||
|
||||
export async function syncAllToVpsTracker(db: Db): Promise<{
|
||||
ok: boolean;
|
||||
count: number;
|
||||
error?: string;
|
||||
}> {
|
||||
const config = getAppSettingsSecrets(db);
|
||||
if (!config.vpsTrackerSyncEnabled) {
|
||||
return { ok: false, count: 0, error: "Синхронизация выключена в CFDM" };
|
||||
}
|
||||
|
||||
const baseUrl = config.vpsTrackerUrl.replace(/\/$/, "");
|
||||
const token = config.vpsTrackerIntegrationToken;
|
||||
if (!baseUrl) {
|
||||
return { ok: false, count: 0, error: "Укажите URL VPS Tracker" };
|
||||
}
|
||||
if (!token) {
|
||||
return { ok: false, count: 0, error: "Укажите integration token" };
|
||||
}
|
||||
|
||||
const bindings = await buildAllSyncBindings(db);
|
||||
|
||||
try {
|
||||
const res = await fetch(`${baseUrl}/api/integrations/cfdm/sync-bindings`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({ bindings, fullSync: true }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const detail = await res.text();
|
||||
return {
|
||||
ok: false,
|
||||
count: 0,
|
||||
error: `VPS Tracker ${baseUrl} ответил HTTP ${res.status}: ${detail}`,
|
||||
};
|
||||
}
|
||||
touchVpsTrackerSync(db);
|
||||
return { ok: true, count: bindings.length };
|
||||
} catch (err) {
|
||||
const raw = err instanceof Error ? err.message : "Ошибка сети";
|
||||
return {
|
||||
ok: false,
|
||||
count: 0,
|
||||
error: `Не удалось отправить данные в VPS Tracker (${baseUrl}): ${raw}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function pingVpsTracker(db: Db): Promise<{
|
||||
ok: boolean;
|
||||
error?: string;
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, expect, it, vi, afterEach } from "vitest";
|
||||
import { buildApp } from "../src/app.js";
|
||||
import { loadConfig } from "../src/config.js";
|
||||
import * as auditPortalPush from "../src/services/audit-portal-push.js";
|
||||
|
||||
describe("audit log", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("GET /api/v1/audit returns local entries", async () => {
|
||||
const pushSpy = vi
|
||||
.spyOn(auditPortalPush, "pushAuditEvents")
|
||||
.mockResolvedValue(undefined);
|
||||
|
||||
const app = await buildApp({
|
||||
config: {
|
||||
...loadConfig(),
|
||||
staticDir: null,
|
||||
authAuditIngestSecret: null,
|
||||
},
|
||||
memory: true,
|
||||
});
|
||||
|
||||
const login = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/auth/login",
|
||||
payload: { username: "admin", password: "admin" },
|
||||
});
|
||||
expect(login.statusCode).toBe(200);
|
||||
const token = (login.json() as { token: string }).token;
|
||||
|
||||
const create = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/groups",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { name: "Audit Test", slug: "audit-test" },
|
||||
});
|
||||
expect(create.statusCode).toBe(200);
|
||||
|
||||
const list = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/audit?action=group.create",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
expect(list.statusCode).toBe(200);
|
||||
const entries = list.json() as { action: string; source_app: string }[];
|
||||
expect(entries.length).toBeGreaterThanOrEqual(1);
|
||||
expect(entries[0]?.action).toBe("group.create");
|
||||
expect(entries[0]?.source_app).toBe("cfdm");
|
||||
|
||||
expect(pushSpy).not.toHaveBeenCalled();
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("recordAudit pushes to portal when secret configured", async () => {
|
||||
const pushSpy = vi
|
||||
.spyOn(auditPortalPush, "pushAuditEvents")
|
||||
.mockResolvedValue(undefined);
|
||||
|
||||
const app = await buildApp({
|
||||
config: {
|
||||
...loadConfig(),
|
||||
staticDir: null,
|
||||
authPortalUrl: "http://portal.test",
|
||||
authAuditIngestSecret: "test-ingest-secret",
|
||||
},
|
||||
memory: true,
|
||||
});
|
||||
|
||||
const login = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/auth/login",
|
||||
payload: { username: "admin", password: "admin" },
|
||||
});
|
||||
const token = (login.json() as { token: string }).token;
|
||||
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/groups",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { name: "Portal Push", slug: "portal-push" },
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(pushSpy).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
const [portalUrl, secret, events] = pushSpy.mock.calls[0]!;
|
||||
expect(portalUrl).toBe("http://portal.test");
|
||||
expect(secret).toBe("test-ingest-secret");
|
||||
expect(events[0]?.source_app).toBe("cfdm");
|
||||
expect(events[0]?.action).toBe("group.create");
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import { describe, expect, it, beforeAll, afterAll } from "vitest";
|
||||
import { buildApp } from "../src/app.js";
|
||||
import { loadConfig } from "../src/config.js";
|
||||
import { hasPermission, permissionForRequest } from "../src/lib/permissions.js";
|
||||
|
||||
describe("permissions helpers", () => {
|
||||
it("hasPermission respects admin ⊃ write ⊃ read", () => {
|
||||
expect(hasPermission(["cfdm:domains:write"], "cfdm:domains:read")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(hasPermission(["cfdm:domains:admin"], "cfdm:domains:write")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(hasPermission(["cfdm:domains:read"], "cfdm:domains:write")).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("permissionForRequest maps domains and settings", () => {
|
||||
expect(permissionForRequest("GET", "/api/v1/domains")).toBe(
|
||||
"cfdm:domains:read",
|
||||
);
|
||||
expect(permissionForRequest("POST", "/api/v1/domains")).toBe(
|
||||
"cfdm:domains:write",
|
||||
);
|
||||
expect(permissionForRequest("GET", "/api/v1/settings")).toBe(
|
||||
"cfdm:settings:admin",
|
||||
);
|
||||
expect(permissionForRequest("POST", "/api/v1/sync/foo")).toBe(
|
||||
"cfdm:domains:write",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("auth plugin (AUTH_REQUIRED)", () => {
|
||||
const secret = "test-secret-at-least-8";
|
||||
const issuer = "https://auth.shnt.top";
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.AUTH_REQUIRED = "true";
|
||||
process.env.AUTH_JWT_SECRET = secret;
|
||||
process.env.AUTH_ISSUER = issuer;
|
||||
process.env.AUTH_PORTAL_URL = "http://localhost:5175";
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
delete process.env.AUTH_REQUIRED;
|
||||
delete process.env.AUTH_JWT_SECRET;
|
||||
delete process.env.AUTH_ISSUER;
|
||||
delete process.env.AUTH_PORTAL_URL;
|
||||
});
|
||||
|
||||
it("GET /api/v1/auth/config exposes portal settings", async () => {
|
||||
const app = await buildApp({
|
||||
config: {
|
||||
...loadConfig(),
|
||||
authRequired: true,
|
||||
jwtSecret: secret,
|
||||
authIssuer: issuer,
|
||||
authPortalUrl: "http://localhost:5175",
|
||||
staticDir: null,
|
||||
},
|
||||
memory: true,
|
||||
});
|
||||
|
||||
const res = await app.inject({ method: "GET", url: "/api/v1/auth/config" });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toMatchObject({
|
||||
required: true,
|
||||
portal_url: "http://localhost:5175",
|
||||
});
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("401 without token; 403 without cfdm app; 200 with rights", async () => {
|
||||
const app = await buildApp({
|
||||
config: {
|
||||
...loadConfig(),
|
||||
authRequired: true,
|
||||
jwtSecret: secret,
|
||||
authIssuer: issuer,
|
||||
authPortalUrl: "http://localhost:5175",
|
||||
staticDir: null,
|
||||
},
|
||||
memory: true,
|
||||
});
|
||||
|
||||
const noAuth = await app.inject({ method: "GET", url: "/api/v1/domains" });
|
||||
expect(noAuth.statusCode).toBe(401);
|
||||
|
||||
const tokenNoApp = app.jwt.sign(
|
||||
{
|
||||
sub: "u1",
|
||||
email: "a@b.c",
|
||||
name: "A",
|
||||
apps: ["vps"],
|
||||
permissions: ["cfdm:domains:read"],
|
||||
iss: issuer,
|
||||
},
|
||||
{ expiresIn: "1h" },
|
||||
);
|
||||
const forbiddenApp = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/domains",
|
||||
headers: { authorization: `Bearer ${tokenNoApp}` },
|
||||
});
|
||||
expect(forbiddenApp.statusCode).toBe(403);
|
||||
|
||||
const okToken = app.jwt.sign(
|
||||
{
|
||||
sub: "u2",
|
||||
email: "r@b.c",
|
||||
name: "R",
|
||||
apps: ["cfdm"],
|
||||
permissions: ["cfdm:domains:read"],
|
||||
iss: issuer,
|
||||
},
|
||||
{ expiresIn: "1h" },
|
||||
);
|
||||
const okRead = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/domains",
|
||||
headers: { authorization: `Bearer ${okToken}` },
|
||||
});
|
||||
expect(okRead.statusCode).toBe(200);
|
||||
|
||||
const denyWrite = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/domains",
|
||||
headers: { authorization: `Bearer ${okToken}` },
|
||||
payload: { name: "x" },
|
||||
});
|
||||
expect(denyWrite.statusCode).toBe(403);
|
||||
|
||||
const loginBlocked = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/auth/login",
|
||||
payload: { username: "admin", password: "admin" },
|
||||
});
|
||||
expect(loginBlocked.statusCode).toBe(403);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -73,7 +73,17 @@ describe("certificates", () => {
|
||||
);
|
||||
const service = repos.createService(testApp.db, "Web", "web");
|
||||
repos.setServiceEnabled(testApp.db, service.id, true);
|
||||
repos.insertBinding(testApp.db, domain.id, service.id, "api", null);
|
||||
const binding = repos.insertBinding(
|
||||
testApp.db,
|
||||
domain.id,
|
||||
service.id,
|
||||
"api",
|
||||
null,
|
||||
);
|
||||
repos.updateBindingLbConfig(testApp.db, binding.id, {
|
||||
health_check_enabled: true,
|
||||
health_check_verify_tls: true,
|
||||
});
|
||||
|
||||
const expiresAt = new Date(Date.now() + 90 * 24 * 60 * 60 * 1000);
|
||||
vi.spyOn(certificateService, "checkHostname").mockResolvedValue({
|
||||
@@ -94,6 +104,76 @@ describe("certificates", () => {
|
||||
await testApp.close();
|
||||
});
|
||||
|
||||
it("does not monitor binding when health-check is off", async () => {
|
||||
const testApp = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
memory: true,
|
||||
});
|
||||
const headers = await authHeaders(testApp);
|
||||
|
||||
const domain = repos.createDomain(
|
||||
testApp.db,
|
||||
null,
|
||||
"rkns.example.com",
|
||||
"cf-zone-imsk",
|
||||
);
|
||||
const service = repos.createService(testApp.db, "Cname", "cname");
|
||||
repos.setServiceEnabled(testApp.db, service.id, true);
|
||||
const binding = repos.insertBinding(
|
||||
testApp.db,
|
||||
domain.id,
|
||||
service.id,
|
||||
"imsk",
|
||||
null,
|
||||
);
|
||||
repos.setBindingCnameTarget(testApp.db, binding.id, "ihome.rkns.example.com");
|
||||
repos.updateBindingLbConfig(testApp.db, binding.id, {
|
||||
health_check_enabled: false,
|
||||
});
|
||||
|
||||
repos.upsertCertificateCheck(
|
||||
testApp.db,
|
||||
domain.id,
|
||||
null,
|
||||
"imsk.rkns.example.com",
|
||||
null,
|
||||
CERT_ERROR,
|
||||
"stale",
|
||||
);
|
||||
|
||||
vi.spyOn(certificateService, "checkHostname").mockResolvedValue({
|
||||
expiresAt: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000),
|
||||
error: null,
|
||||
});
|
||||
|
||||
await testApp.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/certificates/check",
|
||||
headers,
|
||||
});
|
||||
|
||||
expect(
|
||||
repos.listCertificates(testApp.db).some(
|
||||
(c) => c.hostname === "imsk.rkns.example.com",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(certificateService.checkHostname).not.toHaveBeenCalled();
|
||||
|
||||
const listRes = await testApp.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/certificates",
|
||||
headers,
|
||||
});
|
||||
expect(listRes.statusCode).toBe(200);
|
||||
expect(
|
||||
(listRes.json() as { hostname: string }[]).some(
|
||||
(c) => c.hostname === "imsk.rkns.example.com",
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
await testApp.close();
|
||||
});
|
||||
|
||||
it("does not monitor host when service is disabled", async () => {
|
||||
const testApp = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
@@ -248,4 +328,216 @@ describe("certificates", () => {
|
||||
|
||||
await testApp.close();
|
||||
});
|
||||
|
||||
it("skips SSL monitoring when group health is on without TLS verify", async () => {
|
||||
const testApp = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
memory: true,
|
||||
});
|
||||
const headers = await authHeaders(testApp);
|
||||
|
||||
const domain = repos.createDomain(
|
||||
testApp.db,
|
||||
null,
|
||||
"rkns.example.com",
|
||||
"cf-zone-rkns",
|
||||
);
|
||||
const group = repos.createServiceGroup(
|
||||
testApp.db,
|
||||
"TG Proxy",
|
||||
"vpn",
|
||||
null,
|
||||
"gt.rkns.example.com",
|
||||
{
|
||||
health_check_enabled: true,
|
||||
health_check_type: "http",
|
||||
health_check_port: 443,
|
||||
health_check_verify_tls: false,
|
||||
},
|
||||
);
|
||||
const service = repos.createService(testApp.db, "Node", "node");
|
||||
repos.setServiceEnabled(testApp.db, service.id, true);
|
||||
repos.setServiceGroup(testApp.db, service.id, group.id);
|
||||
repos.insertBinding(testApp.db, domain.id, service.id, "rutg", null);
|
||||
|
||||
vi.spyOn(certificateService, "checkHostname").mockResolvedValue({
|
||||
expiresAt: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000),
|
||||
error: null,
|
||||
});
|
||||
|
||||
await testApp.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/certificates/check",
|
||||
headers,
|
||||
});
|
||||
|
||||
const certs = repos.listCertificates(testApp.db);
|
||||
expect(certs.some((c) => c.hostname === "gt.rkns.example.com")).toBe(false);
|
||||
expect(certs.some((c) => c.hostname === "rutg.rkns.example.com")).toBe(
|
||||
false,
|
||||
);
|
||||
expect(certificateService.checkHostname).not.toHaveBeenCalled();
|
||||
|
||||
await testApp.close();
|
||||
});
|
||||
|
||||
it("monitors group hosts when health TLS verify is on", async () => {
|
||||
const testApp = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
memory: true,
|
||||
});
|
||||
const headers = await authHeaders(testApp);
|
||||
|
||||
const domain = repos.createDomain(
|
||||
testApp.db,
|
||||
null,
|
||||
"ok.example.com",
|
||||
"cf-zone-ok",
|
||||
);
|
||||
const group = repos.createServiceGroup(
|
||||
testApp.db,
|
||||
"LB",
|
||||
"vpn",
|
||||
null,
|
||||
"lb.ok.example.com",
|
||||
{
|
||||
health_check_enabled: true,
|
||||
health_check_type: "http",
|
||||
health_check_port: 443,
|
||||
health_check_verify_tls: true,
|
||||
},
|
||||
);
|
||||
const service = repos.createService(testApp.db, "Edge", "edge");
|
||||
repos.setServiceEnabled(testApp.db, service.id, true);
|
||||
repos.setServiceGroup(testApp.db, service.id, group.id);
|
||||
repos.insertBinding(testApp.db, domain.id, service.id, "edge", null);
|
||||
|
||||
vi.spyOn(certificateService, "checkHostname").mockResolvedValue({
|
||||
expiresAt: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000),
|
||||
error: null,
|
||||
});
|
||||
|
||||
await testApp.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/certificates/check",
|
||||
headers,
|
||||
});
|
||||
|
||||
const certs = repos.listCertificates(testApp.db);
|
||||
expect(certs.some((c) => c.hostname === "lb.ok.example.com")).toBe(true);
|
||||
expect(certs.some((c) => c.hostname === "edge.ok.example.com")).toBe(true);
|
||||
|
||||
await testApp.close();
|
||||
});
|
||||
|
||||
it("required mode still monitors when group skips TLS verify", async () => {
|
||||
const testApp = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
memory: true,
|
||||
});
|
||||
const headers = await authHeaders(testApp);
|
||||
|
||||
const domain = repos.createDomain(
|
||||
testApp.db,
|
||||
null,
|
||||
"force.example.com",
|
||||
"cf-zone-force",
|
||||
);
|
||||
repos.updateDomain(testApp.db, domain.id, {
|
||||
group_id: null,
|
||||
status: "active",
|
||||
cert_monitoring: CERT_MONITOR_REQUIRED,
|
||||
});
|
||||
repos.createServiceGroup(
|
||||
testApp.db,
|
||||
"Proxy",
|
||||
"vpn",
|
||||
null,
|
||||
"force.example.com",
|
||||
{
|
||||
health_check_enabled: true,
|
||||
health_check_verify_tls: false,
|
||||
},
|
||||
);
|
||||
|
||||
vi.spyOn(certificateService, "checkHostname").mockResolvedValue({
|
||||
expiresAt: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000),
|
||||
error: null,
|
||||
});
|
||||
|
||||
await testApp.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/certificates/check",
|
||||
headers,
|
||||
});
|
||||
|
||||
expect(
|
||||
repos.listCertificates(testApp.db).some(
|
||||
(c) => c.hostname === domain.zone_name,
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
await testApp.close();
|
||||
});
|
||||
|
||||
it("GET /certificates prunes stale rows without running check", async () => {
|
||||
const testApp = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
memory: true,
|
||||
});
|
||||
const headers = await authHeaders(testApp);
|
||||
|
||||
const domain = repos.createDomain(
|
||||
testApp.db,
|
||||
null,
|
||||
"stale-list.example.com",
|
||||
"cf-zone-stale-list",
|
||||
);
|
||||
const group = repos.createServiceGroup(
|
||||
testApp.db,
|
||||
"Stale",
|
||||
"vpn",
|
||||
null,
|
||||
"gt.stale-list.example.com",
|
||||
{
|
||||
health_check_enabled: true,
|
||||
health_check_verify_tls: false,
|
||||
},
|
||||
);
|
||||
const service = repos.createService(testApp.db, "S", "s");
|
||||
repos.setServiceEnabled(testApp.db, service.id, true);
|
||||
repos.setServiceGroup(testApp.db, service.id, group.id);
|
||||
repos.insertBinding(testApp.db, domain.id, service.id, "rutg", null);
|
||||
|
||||
repos.upsertCertificateCheck(
|
||||
testApp.db,
|
||||
domain.id,
|
||||
null,
|
||||
"gt.stale-list.example.com",
|
||||
null,
|
||||
CERT_ERROR,
|
||||
"stale group domain",
|
||||
);
|
||||
repos.upsertCertificateCheck(
|
||||
testApp.db,
|
||||
domain.id,
|
||||
null,
|
||||
"rutg.stale-list.example.com",
|
||||
null,
|
||||
CERT_ERROR,
|
||||
"stale binding",
|
||||
);
|
||||
|
||||
expect(repos.listCertificates(testApp.db)).toHaveLength(2);
|
||||
|
||||
const listRes = await testApp.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/certificates",
|
||||
headers,
|
||||
});
|
||||
expect(listRes.statusCode).toBe(200);
|
||||
expect(listRes.json()).toEqual([]);
|
||||
|
||||
await testApp.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { repos } from "@cfdm/db";
|
||||
import { buildApp } from "../src/app.js";
|
||||
import { loadConfig } from "../src/config.js";
|
||||
|
||||
async function authHeaders(app: Awaited<ReturnType<typeof buildApp>>) {
|
||||
const config = loadConfig();
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/auth/login",
|
||||
payload: { username: config.adminUsername, password: "admin" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const { token } = res.json() as { token: string };
|
||||
return { authorization: `Bearer ${token}` };
|
||||
}
|
||||
|
||||
describe("origin health checks", () => {
|
||||
it("creates a local health check", async () => {
|
||||
const app = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
memory: true,
|
||||
});
|
||||
const headers = await authHeaders(app);
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/health-checks",
|
||||
headers,
|
||||
payload: { provider: "local", name: "origin-1", protocol: "tcp" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { provider: string; name: string };
|
||||
expect(body.provider).toBe("local");
|
||||
expect(body.name).toBe("origin-1");
|
||||
expect(repos.listHealthChecks(app.db)).toHaveLength(1);
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { repos } from "@cfdm/db";
|
||||
import type { CloudflareClient } from "../src/lib/cf-client.js";
|
||||
import { buildApp } from "../src/app.js";
|
||||
import { loadConfig } from "../src/config.js";
|
||||
import { changeServiceDomain } from "../src/services/change-domain-service.js";
|
||||
import { updateConfig } from "../src/services/service-config-service.js";
|
||||
|
||||
function mockCf(): CloudflareClient {
|
||||
return {
|
||||
listDnsRecords: async () => [],
|
||||
createDnsRecord: async (_zoneId: string, payload: { type: string; name: string; content: string }) => ({
|
||||
id: `cf-${payload.name}-${payload.content}`,
|
||||
type: payload.type,
|
||||
name: payload.name,
|
||||
content: payload.content,
|
||||
ttl: 1,
|
||||
proxied: false,
|
||||
}),
|
||||
updateDnsRecord: async (
|
||||
_zoneId: string,
|
||||
id: string,
|
||||
payload: { type: string; name: string; content: string },
|
||||
) => ({
|
||||
id,
|
||||
type: payload.type,
|
||||
name: payload.name,
|
||||
content: payload.content,
|
||||
ttl: 1,
|
||||
proxied: false,
|
||||
}),
|
||||
patchDnsRecord: async (
|
||||
_zoneId: string,
|
||||
id: string,
|
||||
payload: { content?: string },
|
||||
) => ({
|
||||
id,
|
||||
type: "A",
|
||||
name: "app.example.com",
|
||||
content: payload.content ?? "1.1.1.1",
|
||||
ttl: 1,
|
||||
proxied: false,
|
||||
}),
|
||||
deleteDnsRecord: async () => undefined,
|
||||
listZones: async () => [
|
||||
{ id: "zone-1", name: "example.com", status: "active" },
|
||||
{ id: "zone-2", name: "other.com", status: "active" },
|
||||
],
|
||||
} as unknown as CloudflareClient;
|
||||
}
|
||||
|
||||
describe("change-domain", () => {
|
||||
it("dry-run lists FQDN from → to", async () => {
|
||||
const app = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
memory: true,
|
||||
});
|
||||
const cf = mockCf();
|
||||
const from = repos.createDomain(app.db, null, "example.com", "zone-1");
|
||||
const to = repos.createDomain(app.db, null, "other.com", "zone-2");
|
||||
const service = repos.createService(app.db, "App", "app");
|
||||
await updateConfig(app.db, cf, service.id, {
|
||||
ips: ["1.1.1.1"],
|
||||
domains: [{ fqdn: "app.example.com", target_ips: ["1.1.1.1"] }],
|
||||
});
|
||||
const preview = await changeServiceDomain(app.db, cf, service.id, {
|
||||
from_domain_id: from.id,
|
||||
to_domain_id: to.id,
|
||||
dry_run: true,
|
||||
});
|
||||
expect(preview.applied).toBe(false);
|
||||
expect(preview.items[0]?.from_fqdn).toBe("app.example.com");
|
||||
expect(preview.items[0]?.to_fqdn).toBe("app.other.com");
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { repos } from "@cfdm/db";
|
||||
import type { CloudflareClient } from "../src/lib/cf-client.js";
|
||||
import { buildApp } from "../src/app.js";
|
||||
import { loadConfig } from "../src/config.js";
|
||||
import { changeBindingIp } from "../src/services/change-ip-service.js";
|
||||
import { withBindingLock } from "../src/services/routing/index.js";
|
||||
import { updateConfig } from "../src/services/service-config-service.js";
|
||||
|
||||
function mockCf(): CloudflareClient {
|
||||
return {
|
||||
listDnsRecords: async () => [],
|
||||
createDnsRecord: async (_zoneId: string, payload: { type: string; name: string; content: string }) => ({
|
||||
id: `cf-${payload.name}-${payload.content}`,
|
||||
type: payload.type,
|
||||
name: payload.name,
|
||||
content: payload.content,
|
||||
ttl: 1,
|
||||
proxied: false,
|
||||
}),
|
||||
updateDnsRecord: async (
|
||||
_zoneId: string,
|
||||
id: string,
|
||||
payload: { type: string; name: string; content: string },
|
||||
) => ({
|
||||
id,
|
||||
type: payload.type,
|
||||
name: payload.name,
|
||||
content: payload.content,
|
||||
ttl: 1,
|
||||
proxied: false,
|
||||
}),
|
||||
patchDnsRecord: async (
|
||||
_zoneId: string,
|
||||
id: string,
|
||||
payload: { content?: string },
|
||||
) => ({
|
||||
id,
|
||||
type: "A",
|
||||
name: "panel.example.com",
|
||||
content: payload.content ?? "0.0.0.0",
|
||||
ttl: 1,
|
||||
proxied: false,
|
||||
}),
|
||||
deleteDnsRecord: async () => undefined,
|
||||
listZones: async () => [{ id: "zone-1", name: "example.com", status: "active" }],
|
||||
} as unknown as CloudflareClient;
|
||||
}
|
||||
|
||||
describe("change-ip", () => {
|
||||
it("dry-run previews from → to without writing", async () => {
|
||||
const app = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
memory: true,
|
||||
});
|
||||
const cf = mockCf();
|
||||
repos.createDomain(app.db, null, "example.com", "zone-1");
|
||||
const service = repos.createService(app.db, "Panel", "panel");
|
||||
await updateConfig(app.db, cf, service.id, {
|
||||
ips: ["10.0.0.10"],
|
||||
domains: [{ fqdn: "panel.example.com", target_ips: ["10.0.0.10"] }],
|
||||
});
|
||||
const bindings = repos.listBindingsByService(app.db, service.id);
|
||||
const preview = await changeBindingIp(app.db, cf, bindings[0]!.id, {
|
||||
from_ip: "10.0.0.10",
|
||||
to_ip: "10.0.0.20",
|
||||
dry_run: true,
|
||||
});
|
||||
expect(preview.applied).toBe(false);
|
||||
expect(preview.message).toBe("10.0.0.10 → 10.0.0.20");
|
||||
expect(repos.listBindingIps(app.db, bindings[0]!.id)).toEqual(["10.0.0.10"]);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("apply patches binding IP", async () => {
|
||||
const app = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
memory: true,
|
||||
});
|
||||
const cf = mockCf();
|
||||
repos.createDomain(app.db, null, "example.com", "zone-1");
|
||||
const service = repos.createService(app.db, "Panel", "panel");
|
||||
await updateConfig(app.db, cf, service.id, {
|
||||
ips: ["10.0.0.10"],
|
||||
domains: [{ fqdn: "panel.example.com", target_ips: ["10.0.0.10"] }],
|
||||
});
|
||||
const binding = repos.listBindingsByService(app.db, service.id)[0]!;
|
||||
const result = await changeBindingIp(app.db, cf, binding.id, {
|
||||
from_ip: "10.0.0.10",
|
||||
to_ip: "10.0.0.20",
|
||||
});
|
||||
expect(result.applied).toBe(true);
|
||||
expect(repos.listBindingIps(app.db, binding.id)).toEqual(["10.0.0.20"]);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("serializes concurrent binding locks", async () => {
|
||||
const order: number[] = [];
|
||||
await Promise.all([
|
||||
withBindingLock(1, async () => {
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
order.push(1);
|
||||
}),
|
||||
withBindingLock(1, async () => {
|
||||
order.push(2);
|
||||
}),
|
||||
]);
|
||||
expect(order).toEqual([1, 2]);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it, beforeAll, afterAll } from "vitest";
|
||||
import { createServer, type Server } from "node:net";
|
||||
import { createServer as createHttpServer, type Server as HttpServer } from "node:http";
|
||||
import * as healthCheckService from "../src/services/health-check-service.js";
|
||||
import type { HealthCheckTarget } from "@cfdm/shared";
|
||||
|
||||
@@ -15,6 +16,20 @@ function startTcpServer(): Promise<{ server: Server; port: number }> {
|
||||
});
|
||||
}
|
||||
|
||||
describe("health-check URL helpers", () => {
|
||||
it("buildHttpProbeUrl uses FQDN in URL (IP pinned via connector)", () => {
|
||||
expect(
|
||||
healthCheckService.buildHttpProbeUrl("gt.rkns.top", 443, "/", true),
|
||||
).toBe("https://gt.rkns.top/");
|
||||
expect(
|
||||
healthCheckService.buildHttpProbeUrl("gt.rkns.top", 8080, "/health", false),
|
||||
).toBe("http://gt.rkns.top:8080/health");
|
||||
expect(
|
||||
healthCheckService.buildHttpProbeUrl("2001:db8::1", 443, "/", true),
|
||||
).toBe("https://[2001:db8::1]/");
|
||||
});
|
||||
});
|
||||
|
||||
describe("health-check probeTarget", () => {
|
||||
let server: Server;
|
||||
let port: number;
|
||||
@@ -40,6 +55,7 @@ describe("health-check probeTarget", () => {
|
||||
path: null,
|
||||
expected_status: null,
|
||||
timeout_ms: 1000,
|
||||
verify_tls: false,
|
||||
};
|
||||
const result = await healthCheckService.probeTarget(target);
|
||||
expect(result.ok).toBe(true);
|
||||
@@ -58,11 +74,83 @@ describe("health-check probeTarget", () => {
|
||||
path: null,
|
||||
expected_status: null,
|
||||
timeout_ms: 500,
|
||||
verify_tls: false,
|
||||
};
|
||||
const result = await healthCheckService.probeTarget(target);
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.error).not.toBeNull();
|
||||
});
|
||||
|
||||
it("http probe hits IP with Host=hostname (same IP, different FQDN)", async () => {
|
||||
let seenHost: string | undefined;
|
||||
const httpServer: HttpServer = createHttpServer((req, res) => {
|
||||
seenHost = req.headers.host;
|
||||
res.writeHead(200);
|
||||
res.end("ok");
|
||||
});
|
||||
const httpPort = await new Promise<number>((resolve) => {
|
||||
httpServer.listen(0, "127.0.0.1", () => {
|
||||
const address = httpServer.address();
|
||||
resolve(typeof address === "object" && address ? address.port : 0);
|
||||
});
|
||||
});
|
||||
|
||||
try {
|
||||
const groupTarget: HealthCheckTarget = {
|
||||
scope: "group",
|
||||
ref_id: 1,
|
||||
ip: "127.0.0.1",
|
||||
hostname: "gt.rkns.top",
|
||||
type: "http",
|
||||
port: httpPort,
|
||||
path: "/",
|
||||
expected_status: 200,
|
||||
timeout_ms: 1000,
|
||||
verify_tls: false,
|
||||
};
|
||||
const bindingTarget: HealthCheckTarget = {
|
||||
...groupTarget,
|
||||
scope: "binding",
|
||||
hostname: "rutg.rkns.top",
|
||||
};
|
||||
|
||||
const groupResult = await healthCheckService.probeTarget(groupTarget);
|
||||
expect(groupResult.ok).toBe(true);
|
||||
expect(seenHost?.startsWith("gt.rkns.top")).toBe(true);
|
||||
|
||||
const bindingResult = await healthCheckService.probeTarget(bindingTarget);
|
||||
expect(bindingResult.ok).toBe(true);
|
||||
expect(seenHost?.startsWith("rutg.rkns.top")).toBe(true);
|
||||
|
||||
// Same loopback IP → latencies in the same ballpark (not ~1s DNS skew)
|
||||
expect(Math.abs(groupResult.latencyMs - bindingResult.latencyMs)).toBeLessThan(200);
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => httpServer.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
|
||||
it("physicalProbeKey collapses group+binding on same IP for tcp", async () => {
|
||||
const { physicalProbeKey } = await import("../src/services/health-check-service.js");
|
||||
const group: HealthCheckTarget = {
|
||||
scope: "group",
|
||||
ref_id: 1,
|
||||
ip: "93.115.203.183",
|
||||
hostname: "gt.rkns.top",
|
||||
type: "tcp",
|
||||
port: 443,
|
||||
path: null,
|
||||
expected_status: null,
|
||||
timeout_ms: 3000,
|
||||
verify_tls: false,
|
||||
};
|
||||
const binding: HealthCheckTarget = {
|
||||
...group,
|
||||
scope: "binding",
|
||||
ref_id: 2,
|
||||
hostname: "rutg.rkns.top",
|
||||
};
|
||||
expect(physicalProbeKey(group)).toBe(physicalProbeKey(binding));
|
||||
});
|
||||
});
|
||||
|
||||
describe("health-check state derivation via runAllChecks", () => {
|
||||
@@ -90,7 +178,6 @@ describe("health-check state derivation via runAllChecks", () => {
|
||||
{ ip: "127.0.0.1", weight: 1, priority: 1 },
|
||||
]);
|
||||
|
||||
// Запуск с closed port (port 1) — должен зафиксировать down после 2 проверок
|
||||
await healthCheckService.runAllChecks(db, {
|
||||
thresholds: {
|
||||
degradedFailures: 1,
|
||||
@@ -121,4 +208,27 @@ describe("health-check state derivation via runAllChecks", () => {
|
||||
);
|
||||
expect(status?.status).toBe("down");
|
||||
});
|
||||
|
||||
it("listHealthCheckTargets includes verify_tls from binding config", async () => {
|
||||
const { createMemoryDb, repos, runMigrations } = await import("@cfdm/db");
|
||||
const { db, sqlite } = createMemoryDb();
|
||||
runMigrations(sqlite);
|
||||
|
||||
const domain = repos.createDomain(db, null, "example.com", "zone-id");
|
||||
const service = repos.createService(db, "Svc", "svc");
|
||||
const binding = repos.insertBinding(db, domain.id, service.id, "@", null);
|
||||
repos.updateBindingLbConfig(db, binding.id, {
|
||||
health_check_enabled: true,
|
||||
health_check_type: "http",
|
||||
health_check_port: 443,
|
||||
health_check_verify_tls: true,
|
||||
});
|
||||
repos.replaceBindingIpsWithMeta(db, binding.id, [
|
||||
{ ip: "10.0.0.1", weight: 1, priority: 1 },
|
||||
]);
|
||||
|
||||
const targets = repos.listHealthCheckTargets(db);
|
||||
expect(targets).toHaveLength(1);
|
||||
expect(targets[0]?.verify_tls).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { nextHealthState } from "../src/services/health/state-machine.js";
|
||||
|
||||
const thresholds = {
|
||||
degradedFailures: 1,
|
||||
downFailures: 2,
|
||||
successRecoveries: 2,
|
||||
latencyWarnMs: 1000,
|
||||
};
|
||||
|
||||
describe("health state machine", () => {
|
||||
it("first success from unknown is healthy immediately", () => {
|
||||
const next = nextHealthState(true, 20, null, thresholds);
|
||||
expect(next.legacy).toBe("up");
|
||||
expect(next.node).toBe("healthy");
|
||||
});
|
||||
|
||||
it("recovery from down goes checking until consecutive successes", () => {
|
||||
const first = nextHealthState(
|
||||
true,
|
||||
10,
|
||||
{ status: "down", consecutive_failures: 3, consecutive_successes: 0 },
|
||||
thresholds,
|
||||
);
|
||||
expect(first.node).toBe("checking");
|
||||
expect(first.legacy).toBe("unknown");
|
||||
const second = nextHealthState(
|
||||
true,
|
||||
10,
|
||||
{
|
||||
status: "checking",
|
||||
consecutive_failures: 0,
|
||||
consecutive_successes: first.successes,
|
||||
},
|
||||
thresholds,
|
||||
);
|
||||
expect(second.node).toBe("healthy");
|
||||
expect(second.legacy).toBe("up");
|
||||
});
|
||||
|
||||
it("two failures mark unhealthy", () => {
|
||||
const first = nextHealthState(
|
||||
false,
|
||||
5,
|
||||
{ status: "up", consecutive_failures: 0, consecutive_successes: 1 },
|
||||
thresholds,
|
||||
);
|
||||
expect(first.node).toBe("degraded");
|
||||
const second = nextHealthState(
|
||||
false,
|
||||
5,
|
||||
{
|
||||
status: "degraded",
|
||||
consecutive_failures: first.failures,
|
||||
consecutive_successes: 0,
|
||||
},
|
||||
thresholds,
|
||||
);
|
||||
expect(second.node).toBe("unhealthy");
|
||||
expect(second.legacy).toBe("down");
|
||||
});
|
||||
});
|
||||
@@ -39,7 +39,10 @@ describe("selectActiveIpsByMode", () => {
|
||||
lb_mode: "round_robin",
|
||||
health_check_enabled: true,
|
||||
};
|
||||
const rows = [row("1.1.1.1", { health: "unknown" }), row("2.2.2.2")];
|
||||
const rows = [
|
||||
row("1.1.1.1", { health: "unknown" }),
|
||||
row("2.2.2.2", { health: "unknown" }),
|
||||
];
|
||||
expect(selectActiveIpsByMode(config, rows).sort()).toEqual([
|
||||
"1.1.1.1",
|
||||
"2.2.2.2",
|
||||
@@ -88,6 +91,18 @@ describe("selectActiveIpsByMode", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("round_robin excludes unknown when another ip is up", () => {
|
||||
const config: LbTargetConfig = {
|
||||
lb_mode: "round_robin",
|
||||
health_check_enabled: true,
|
||||
};
|
||||
const rows = [
|
||||
row("1.1.1.1", { health: "up" }),
|
||||
row("2.2.2.2", { health: "unknown" }),
|
||||
];
|
||||
expect(selectActiveIpsByMode(config, rows)).toEqual(["1.1.1.1"]);
|
||||
});
|
||||
|
||||
it("returns empty array for no rows", () => {
|
||||
const config: LbTargetConfig = {
|
||||
lb_mode: "round_robin",
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { repos } from "@cfdm/db";
|
||||
import { buildApp } from "../src/app.js";
|
||||
import { loadConfig } from "../src/config.js";
|
||||
|
||||
async function authHeaders(app: Awaited<ReturnType<typeof buildApp>>) {
|
||||
const config = loadConfig();
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/auth/login",
|
||||
payload: { username: config.adminUsername, password: "admin" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const { token } = res.json() as { token: string };
|
||||
return { authorization: `Bearer ${token}` };
|
||||
}
|
||||
|
||||
describe("service nodes API", () => {
|
||||
it("creates and lists nodes without changing empty DNS pool until bound", async () => {
|
||||
const app = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
memory: true,
|
||||
});
|
||||
const headers = await authHeaders(app);
|
||||
const service = repos.createService(app.db, "Panel", "panel");
|
||||
|
||||
const created = await app.inject({
|
||||
method: "POST",
|
||||
url: `/api/v1/services/${service.id}/nodes`,
|
||||
headers,
|
||||
payload: { address: "10.0.0.8", protocol: "tcp" },
|
||||
});
|
||||
expect(created.statusCode).toBe(200);
|
||||
const node = created.json() as { address: string };
|
||||
expect(node.address).toBe("10.0.0.8");
|
||||
expect(repos.listServiceIps(app.db, service.id)).toContain("10.0.0.8");
|
||||
|
||||
const listed = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/v1/services/${service.id}/nodes`,
|
||||
headers,
|
||||
});
|
||||
expect(listed.statusCode).toBe(200);
|
||||
expect(listed.json()).toHaveLength(1);
|
||||
|
||||
const overview = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/v1/services/${service.id}/overview`,
|
||||
headers,
|
||||
});
|
||||
expect(overview.statusCode).toBe(200);
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createMemoryDb, repos, runMigrations } from "@cfdm/db";
|
||||
import type { CloudflareClient } from "../src/lib/cf-client.js";
|
||||
import { updateConfig } from "../src/services/service-config-service.js";
|
||||
|
||||
function mockCf(): CloudflareClient {
|
||||
return {
|
||||
listDnsRecords: async () => [],
|
||||
createDnsRecord: async () => ({
|
||||
id: "cf-new",
|
||||
type: "A",
|
||||
name: "api.example.com",
|
||||
content: "10.0.0.1",
|
||||
ttl: 1,
|
||||
proxied: false,
|
||||
}),
|
||||
updateDnsRecord: async () => ({
|
||||
id: "cf-upd",
|
||||
type: "A",
|
||||
name: "api.example.com",
|
||||
content: "10.0.0.1",
|
||||
ttl: 1,
|
||||
proxied: false,
|
||||
}),
|
||||
deleteDnsRecord: async () => undefined,
|
||||
verifyToken: async () => true,
|
||||
listZones: async () => [],
|
||||
} as unknown as CloudflareClient;
|
||||
}
|
||||
|
||||
function setupDb() {
|
||||
const { db, sqlite } = createMemoryDb();
|
||||
runMigrations(sqlite);
|
||||
return db;
|
||||
}
|
||||
|
||||
describe("service bindings prune", () => {
|
||||
it("updateConfig with domains: [] removes all bindings", async () => {
|
||||
const db = setupDb();
|
||||
const cf = mockCf();
|
||||
|
||||
const domain = repos.createDomain(db, null, "example.com", "cf-zone-example");
|
||||
const service = repos.createService(db, "Web", "web");
|
||||
repos.replaceServiceIps(db, service.id, ["10.0.0.1"]);
|
||||
const binding = repos.insertBinding(db, domain.id, service.id, "api", null);
|
||||
repos.replaceBindingIps(db, binding.id, ["10.0.0.1"]);
|
||||
|
||||
expect(repos.listBindingsByService(db, service.id)).toHaveLength(1);
|
||||
|
||||
const view = await updateConfig(db, cf, service.id, {
|
||||
ips: ["10.0.0.1"],
|
||||
domains: [],
|
||||
});
|
||||
|
||||
expect(repos.listBindingsByService(db, service.id)).toHaveLength(0);
|
||||
expect(view.domains).toEqual([]);
|
||||
});
|
||||
|
||||
it("updateConfig keeps multiple FQDN bindings", async () => {
|
||||
const db = setupDb();
|
||||
const cf = mockCf();
|
||||
|
||||
repos.createDomain(db, null, "a.example", "cf-zone-a");
|
||||
repos.createDomain(db, null, "b.example", "cf-zone-b");
|
||||
const service = repos.createService(db, "Edge", "edge");
|
||||
repos.replaceServiceIps(db, service.id, ["10.0.0.2"]);
|
||||
|
||||
const view = await updateConfig(db, cf, service.id, {
|
||||
ips: ["10.0.0.2"],
|
||||
domains: [
|
||||
{ fqdn: "api.a.example", target_ips: ["10.0.0.2"] },
|
||||
{ fqdn: "www.b.example", target_ips: ["10.0.0.2"] },
|
||||
],
|
||||
});
|
||||
|
||||
expect(view.domains).toHaveLength(2);
|
||||
const bindings = repos.listBindingsByService(db, service.id);
|
||||
expect(bindings).toHaveLength(2);
|
||||
expect(bindings.map((b) => b.hostname).sort()).toEqual(["api", "www"]);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildApp } from "../src/app.js";
|
||||
import { loadConfig } from "../src/config.js";
|
||||
import { repos } from "@cfdm/db";
|
||||
import { createMemoryDb, repos, runMigrations } from "@cfdm/db";
|
||||
|
||||
async function authHeaders(app: Awaited<ReturnType<typeof buildApp>>) {
|
||||
const config = loadConfig();
|
||||
@@ -31,8 +31,14 @@ describe("service groups health enrichment", () => {
|
||||
null,
|
||||
"vpn.example.com",
|
||||
);
|
||||
repos.updateServiceGroup(app.db, group.id, "VPN", "vpn", null, "vpn.example.com", {
|
||||
health_check_enabled: true,
|
||||
health_check_type: "tcp",
|
||||
health_check_port: 443,
|
||||
});
|
||||
const service = repos.createService(app.db, "Panel", "panel");
|
||||
repos.setServiceGroup(app.db, service.id, group.id);
|
||||
repos.setServiceEnabled(app.db, service.id, true);
|
||||
const binding = repos.insertBinding(
|
||||
app.db,
|
||||
domain.id,
|
||||
@@ -57,7 +63,7 @@ describe("service groups health enrichment", () => {
|
||||
app.db,
|
||||
"group",
|
||||
group.id,
|
||||
"5.6.7.8",
|
||||
"1.2.3.4",
|
||||
"up",
|
||||
40,
|
||||
0,
|
||||
@@ -91,4 +97,124 @@ describe("service groups health enrichment", () => {
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("group badge ignores disabled service health and pool-only dead IPs", async () => {
|
||||
const app = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
memory: true,
|
||||
});
|
||||
const headers = await authHeaders(app);
|
||||
|
||||
const domain = repos.createDomain(app.db, null, "rkns.top", "zone-tg");
|
||||
const group = repos.createServiceGroup(
|
||||
app.db,
|
||||
"TG Proxy",
|
||||
"custom",
|
||||
null,
|
||||
"gt.rkns.top",
|
||||
);
|
||||
repos.updateServiceGroup(app.db, group.id, "TG Proxy", "custom", null, "gt.rkns.top", {
|
||||
health_check_enabled: true,
|
||||
health_check_type: "tcp",
|
||||
health_check_port: 443,
|
||||
});
|
||||
|
||||
const live = repos.createService(app.db, "Live", "live");
|
||||
repos.setServiceGroup(app.db, live.id, group.id);
|
||||
repos.setServiceEnabled(app.db, live.id, true);
|
||||
repos.replaceServiceIps(app.db, live.id, ["10.0.0.1", "10.0.0.99"]);
|
||||
const liveBinding = repos.insertBinding(app.db, domain.id, live.id, "gt", null);
|
||||
repos.replaceBindingIpsWithMeta(app.db, liveBinding.id, [
|
||||
{ ip: "10.0.0.1", weight: 1, priority: 1 },
|
||||
]);
|
||||
|
||||
const dead = repos.createService(app.db, "Dead", "dead");
|
||||
repos.setServiceGroup(app.db, dead.id, group.id);
|
||||
repos.setServiceEnabled(app.db, dead.id, false);
|
||||
const deadBinding = repos.insertBinding(app.db, domain.id, dead.id, "old", null);
|
||||
repos.replaceBindingIpsWithMeta(app.db, deadBinding.id, [
|
||||
{ ip: "10.0.0.2", weight: 1, priority: 1 },
|
||||
]);
|
||||
|
||||
// Live binding + group FQDN are up; pool-only IP and disabled service are down.
|
||||
repos.upsertIpHealthStatus(app.db, "binding", liveBinding.id, "10.0.0.1", "up", 20, 0, null);
|
||||
repos.upsertIpHealthStatus(app.db, "group", group.id, "10.0.0.1", "up", 20, 0, null);
|
||||
repos.upsertIpHealthStatus(app.db, "group", group.id, "10.0.0.99", "down", null, 5, "timeout");
|
||||
repos.upsertIpHealthStatus(app.db, "binding", deadBinding.id, "10.0.0.2", "down", null, 5, "timeout");
|
||||
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/service-groups",
|
||||
headers,
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as {
|
||||
groups: Array<{ id: number; health_status: string }>;
|
||||
};
|
||||
const groupView = body.groups.find((g) => g.id === group.id);
|
||||
expect(groupView?.health_status).toBe("up");
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("group health check targets", () => {
|
||||
it("probes binding IPs for group scope, not unused pool IPs", () => {
|
||||
const { db, sqlite } = createMemoryDb();
|
||||
runMigrations(sqlite);
|
||||
|
||||
const domain = repos.createDomain(db, null, "rkns.top", "zone-1");
|
||||
const group = repos.createServiceGroup(db, "TG Proxy", "custom", null, "gt.rkns.top");
|
||||
repos.updateServiceGroup(db, group.id, "TG Proxy", "custom", null, "gt.rkns.top", {
|
||||
health_check_enabled: true,
|
||||
health_check_type: "tcp",
|
||||
health_check_port: 443,
|
||||
});
|
||||
const service = repos.createService(db, "Svc", "svc");
|
||||
repos.setServiceGroup(db, service.id, group.id);
|
||||
repos.setServiceEnabled(db, service.id, true);
|
||||
repos.replaceServiceIps(db, service.id, ["10.0.0.1", "10.0.0.99"]);
|
||||
const binding = repos.insertBinding(db, domain.id, service.id, "gt", null);
|
||||
repos.replaceBindingIpsWithMeta(db, binding.id, [
|
||||
{ ip: "10.0.0.1", weight: 1, priority: 1 },
|
||||
]);
|
||||
|
||||
const targets = repos.listHealthCheckTargets(db);
|
||||
const groupScope = targets.filter((t) => t.scope === "group" && t.ref_id === group.id);
|
||||
expect(groupScope.map((t) => t.ip).sort()).toEqual(["10.0.0.1"]);
|
||||
expect(groupScope.every((t) => t.hostname === "gt.rkns.top")).toBe(true);
|
||||
});
|
||||
|
||||
it("pruneStaleIpHealthStatus drops pool-only and orphan group rows", () => {
|
||||
const { db, sqlite } = createMemoryDb();
|
||||
runMigrations(sqlite);
|
||||
|
||||
const domain = repos.createDomain(db, null, "rkns.top", "zone-1");
|
||||
const group = repos.createServiceGroup(db, "TG Proxy", "custom", null, "gt.rkns.top");
|
||||
repos.updateServiceGroup(db, group.id, "TG Proxy", "custom", null, "gt.rkns.top", {
|
||||
health_check_enabled: true,
|
||||
health_check_type: "tcp",
|
||||
health_check_port: 443,
|
||||
});
|
||||
const service = repos.createService(db, "Svc", "svc");
|
||||
repos.setServiceGroup(db, service.id, group.id);
|
||||
repos.setServiceEnabled(db, service.id, true);
|
||||
repos.replaceServiceIps(db, service.id, ["10.0.0.1", "10.0.0.99"]);
|
||||
const binding = repos.insertBinding(db, domain.id, service.id, "gt", null);
|
||||
repos.replaceBindingIpsWithMeta(db, binding.id, [
|
||||
{ ip: "10.0.0.1", weight: 1, priority: 1 },
|
||||
]);
|
||||
|
||||
repos.upsertIpHealthStatus(db, "group", group.id, "10.0.0.1", "up", 10, 0, null);
|
||||
repos.upsertIpHealthStatus(db, "group", group.id, "10.0.0.99", "down", null, 3, "dead pool");
|
||||
repos.upsertIpHealthStatus(db, "group", 999, "1.1.1.1", "down", null, 3, "orphan ref");
|
||||
|
||||
const targets = repos.listHealthCheckTargets(db);
|
||||
const deleted = repos.pruneStaleIpHealthStatus(db, targets);
|
||||
expect(deleted).toBeGreaterThanOrEqual(2);
|
||||
|
||||
const rows = repos.listIpHealthStatus(db, "group", group.id);
|
||||
expect(rows.map((r) => r.ip)).toEqual(["10.0.0.1"]);
|
||||
expect(repos.listIpHealthStatus(db, "group", 999)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { serviceGroupsResponseSchema } from "@cfdm/shared";
|
||||
import { repos } from "@cfdm/db";
|
||||
import type { CloudflareClient } from "../src/lib/cf-client.js";
|
||||
import { buildApp } from "../src/app.js";
|
||||
import { loadConfig } from "../src/config.js";
|
||||
import {
|
||||
listGroupViews,
|
||||
updateConfig,
|
||||
} from "../src/services/service-config-service.js";
|
||||
|
||||
function mockCf(): CloudflareClient {
|
||||
return {
|
||||
listDnsRecords: async () => [],
|
||||
createDnsRecord: async (_zoneId: string, payload: { type: string; name: string; content: string }) => ({
|
||||
id: `cf-${payload.name}`,
|
||||
type: payload.type,
|
||||
name: payload.name,
|
||||
content: payload.content,
|
||||
ttl: 1,
|
||||
proxied: false,
|
||||
}),
|
||||
updateDnsRecord: async (
|
||||
_zoneId: string,
|
||||
id: string,
|
||||
payload: { type: string; name: string; content: string },
|
||||
) => ({
|
||||
id,
|
||||
type: payload.type,
|
||||
name: payload.name,
|
||||
content: payload.content,
|
||||
ttl: 1,
|
||||
proxied: false,
|
||||
}),
|
||||
deleteDnsRecord: async () => undefined,
|
||||
verifyToken: async () => true,
|
||||
listZones: async () => [{ id: "zone-1", name: "example.com", status: "active" }],
|
||||
} as unknown as CloudflareClient;
|
||||
}
|
||||
|
||||
async function authHeaders(app: Awaited<ReturnType<typeof buildApp>>) {
|
||||
const config = loadConfig();
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/auth/login",
|
||||
payload: { username: config.adminUsername, password: "admin" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const { token } = res.json() as { token: string };
|
||||
return { authorization: `Bearer ${token}` };
|
||||
}
|
||||
|
||||
describe("create service then list groups", () => {
|
||||
it("create + updateConfig then listGroupViews parses with shared Zod schema", async () => {
|
||||
const app = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
memory: true,
|
||||
});
|
||||
const headers = await authHeaders(app);
|
||||
const cf = mockCf();
|
||||
|
||||
repos.createDomain(app.db, null, "example.com", "zone-1");
|
||||
const group = repos.createServiceGroup(
|
||||
app.db,
|
||||
"VPN",
|
||||
"vpn",
|
||||
null,
|
||||
"vpn.example.com",
|
||||
);
|
||||
|
||||
const createRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/services",
|
||||
headers,
|
||||
payload: {
|
||||
name: "Panel",
|
||||
slug: "panel",
|
||||
service_group_id: group.id,
|
||||
},
|
||||
});
|
||||
expect(createRes.statusCode).toBe(200);
|
||||
const created = createRes.json() as {
|
||||
id: number;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
};
|
||||
expect(created.id).toBeTypeOf("number");
|
||||
expect(created.enabled).toBe(true);
|
||||
|
||||
await updateConfig(app.db, cf, created.id, {
|
||||
ips: ["1.2.3.4"],
|
||||
service_group_id: group.id,
|
||||
domains: [
|
||||
{
|
||||
fqdn: "panel.example.com",
|
||||
target_ips: ["1.2.3.4"],
|
||||
target_ip_weights: { "1.2.3.4": 1 },
|
||||
target_ip_priorities: { "1.2.3.4": 1 },
|
||||
lb_mode: "round_robin",
|
||||
health_check_enabled: true,
|
||||
health_check_type: "tcp",
|
||||
health_check_port: 443,
|
||||
health_check_path: null,
|
||||
health_check_expected_status: null,
|
||||
health_check_interval_sec: 30,
|
||||
health_check_timeout_ms: 3000,
|
||||
health_check_verify_tls: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const body = await listGroupViews(app.db);
|
||||
const parsed = serviceGroupsResponseSchema.safeParse(body);
|
||||
expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true);
|
||||
|
||||
const listRes = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/service-groups",
|
||||
headers,
|
||||
});
|
||||
expect(listRes.statusCode).toBe(200);
|
||||
const httpParsed = serviceGroupsResponseSchema.safeParse(listRes.json());
|
||||
expect(httpParsed.success, JSON.stringify(httpParsed.error?.issues)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
httpParsed.data!.groups
|
||||
.find((g) => g.id === group.id)
|
||||
?.services.some((s) => s.id === created.id),
|
||||
).toBe(true);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("POST /services returns resolved ServiceView with numeric id", async () => {
|
||||
const app = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
memory: true,
|
||||
});
|
||||
const headers = await authHeaders(app);
|
||||
|
||||
const createRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/services",
|
||||
headers,
|
||||
payload: { name: "Bare", slug: "bare" },
|
||||
});
|
||||
expect(createRes.statusCode).toBe(200);
|
||||
const created = createRes.json() as Record<string, unknown>;
|
||||
expect(typeof created.id).toBe("number");
|
||||
expect(created.name).toBe("Bare");
|
||||
expect(created.enabled).toBe(true);
|
||||
expect(Array.isArray(created.ips)).toBe(true);
|
||||
expect(Array.isArray(created.domains)).toBe(true);
|
||||
|
||||
const listRes = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/service-groups",
|
||||
headers,
|
||||
});
|
||||
expect(listRes.statusCode).toBe(200);
|
||||
const parsed = serviceGroupsResponseSchema.safeParse(listRes.json());
|
||||
expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true);
|
||||
expect(parsed.data!.ungrouped.some((s) => s.slug === "bare")).toBe(true);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
Loaded 100 of 348 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user