Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
54f3d19afb | ||
|
|
cc190a381c | ||
|
|
2ac36a6ca5 | ||
|
|
cffcfada88 | ||
|
|
9240e8be11 | ||
|
|
d79fb3815a | ||
|
|
765b9a1658 | ||
|
|
5d181e7cb0 | ||
|
|
cf211f7418 | ||
|
|
04225886e0 | ||
|
|
1f0704add0 | ||
|
|
6569dbfc60 | ||
|
|
78b268cc39 | ||
|
|
3d5b7f0ea6 | ||
|
|
b4d2d4bc20 | ||
|
|
c90a6ca3b8 | ||
|
|
bf4b9b5443 | ||
|
|
5ce56b5168 | ||
|
|
f1af1a85e5 | ||
|
|
414a419f18 | ||
|
|
6a286a1f66 | ||
|
|
bf3d50e1ff |
No files matched your search
@@ -1,67 +0,0 @@
|
||||
---
|
||||
name: reui
|
||||
description: Use the ReUI registry from your AI agent - find, install, and correctly use ReUI components (the 22 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 `fe6742e29c`.** 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 22 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
|
||||
|
||||
The skill is free and this MCP is free to use; it just needs a ReUI account. On first use your agent opens a browser "Sign in with ReUI" prompt (a free account is created if you don't have one). Free covers components and examples with a daily request allowance; a Pro or Ultimate license unlocks premium blocks and Motion Icons and removes the limit (see [rules/registry.md](./rules/registry.md)). The same account and skill work in every agent and service the MCP connects to - this skill is agent-agnostic.
|
||||
|
||||
Skill + MCP are a team: this skill is the workflow (how to find, install, read the API, and adapt by reuse); the MCP is the live data and the hands (search, get_component, install commands). Your job: find the right item, install it with the shadcn CLI, read its real API, and **adapt by reuse** - wire real data and theme it; do not hand-roll or restyle what ReUI already provides. This skill **layers on the shadcn skill**: follow that for generic rules (spacing, `cn()`, semantic colors, forms); follow this for everything ReUI-specific.
|
||||
|
||||
## The core loop (MCP-native)
|
||||
|
||||
1. **Find** - call the ReUI MCP `search` tool with the user's intent. It returns a ranked, scored list across components/examples/blocks/icons, each with an `install` command, `previewUrl`, `docsUrl`, and `componentsUsed`. Pass hints (`type`, `component`, `category`, `features`, `free`) when you can infer them.
|
||||
2. **Install** - run the returned command non-interactively (`npx shadcn@latest add @reui/<name> --yes`). The CLI resolves deps, aliases, and the base/style from `components.json`. See [cli.md](./rules/cli.md).
|
||||
3. **Read the API (on your base)** - first note your base from `components.json` -> `style` (`base-nova` -> Base UI, `radix-nova` -> Radix UI). For each component an item uses, call `get_component(name)` and read its **inline `api`** (no web fetch); then `get_examples(name)` to install a worked example and copy its composition - the installed files are already in your base. Whenever you work with a component's API, also **share its `docsUrl`** (the primitive's API documentation page) with the user so they have the full reference. See [components.md](./rules/components.md).
|
||||
4. **Adapt (reuse-first)** - swap demo data for real data, fix icon imports, align tokens. Do not redesign. See [adapting.md](./rules/adapting.md).
|
||||
|
||||
**Always show the preview.** Every item a tool returns carries a `previewUrl` (a live preview page). Whenever you list, recommend, or present ReUI items to the user - blocks, components, examples, or icons, whether from `search`, `search_icons`, `list_components`, `compose_page`, or any getter - include each item's `previewUrl` so they can SEE it before installing. Blocks and examples open an individual live preview; icons and components link to their live category/component page. Never present an item without its preview link.
|
||||
|
||||
If the ReUI MCP is not configured, fall back to `npx shadcn@latest search @reui -q "..."` then `add` - but the MCP gives scored matches + inline APIs; prefer it.
|
||||
|
||||
## Commands
|
||||
|
||||
Run ReUI as explicit slash commands (via the ReUI MCP) **or** just ask in plain language - both run the same workflow.
|
||||
|
||||
| Command | Invoke | Does |
|
||||
| ----------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
|
||||
| **build** | `/mcp__reui__build <what>` | Compose a page/section/feature from ReUI: plan → install → read API → adapt → craft → audit. |
|
||||
| **add** | `/mcp__reui__add <item>` | Find & install one component/example/block/icon and wire it in. |
|
||||
| **fix** | `/mcp__reui__fix [target]` | Diagnose & fix ReUI usage: wrong/undocumented props, base/radix mismatch, missing states, a11y/scroll. |
|
||||
| **improve** | `/mcp__reui__improve [target]` | Refine + extend existing ReUI UI to a production-exceptional bar (hierarchy, density, states, responsive, motion). |
|
||||
|
||||
Invocation differs slightly per agent (`/mcp__reui__build` in Claude Code/Cursor/Windsurf, `/mcp.reui.build` in VS Code). No command surface? Just describe what you want - this skill drives the identical loop.
|
||||
|
||||
## When to reach for ReUI vs plain shadcn
|
||||
|
||||
| Need | Reach for |
|
||||
| -------------------------------------------------------------------- | ------------------------------------------------------------------------- |
|
||||
| A full page or section (dashboard, billing, auth, pricing, settings) | `compose_page` first (plans sections + best blocks), then ReUI **blocks** |
|
||||
| A data table with sorting/filtering/pagination/virtualization | the **data-grid** component (never hand-roll a `<table>`) |
|
||||
| A drag-and-drop board | the **kanban** component |
|
||||
| Advanced column filtering, date range, tree, stepper, ... | the matching ReUI **component** |
|
||||
| A single generic control already in shadcn (Button, Dialog, Select) | plain **shadcn** |
|
||||
|
||||
## Detailed references
|
||||
|
||||
- [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 22 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)
|
||||
- [rules/styling.md](./rules/styling.md) - ReUI extended tokens, theme adaptation, density
|
||||
- [rules/icons.md](./rules/icons.md) - portable icons, swapping imports, Motion Icons (static + animated)
|
||||
- [tools.md](./tools.md) - the ReUI MCP: golden path, the 19 tools, token rules, result shapes, errors
|
||||
@@ -1,43 +0,0 @@
|
||||
# Adapting installed ReUI code (reuse-first, no AI slop)
|
||||
|
||||
ReUI items ship production-quality. Your job is to **adapt by reuse** - wire real data and fit the app - not to redesign or hand-roll. The output should look like ReUI built it for this product.
|
||||
|
||||
## Preserve the design - don't over-customize
|
||||
|
||||
The design IS the product. A ReUI block/component encodes senior-designer decisions: spacing, hierarchy, density, color treatment, and component choices. The fastest way to turn a premium block back into generic AI slop is to "improve" its look - so don't.
|
||||
|
||||
- Change **data, copy, and props**; keep the **structure and styling** it ships with. Make the **smallest** change that wires the real data. If your diff touches `className` / JSX structure more than data / props, you are over-customizing - stop and reuse.
|
||||
- Don't swap ReUI components for hand-rolled ones, restructure the layout, re-skin spacing / radius / colors, or add decorative chrome. Let the installed components carry the default spacing, radius, sizing, icon rhythm, density, and state styling; add custom Tailwind only when a component genuinely lacks a contract you need.
|
||||
- Want a different look? `search` for a block whose design already fits and reuse that - don't restyle this one into a new design.
|
||||
|
||||
## Reuse the parts: examples and the block's own elements
|
||||
|
||||
- **Examples are building parts.** A free `c-*` example is a correct, single-pattern composition you can reuse. Before composing from scratch, `get_examples(component)`, install the closest one, and reuse its wiring - assemble UI from examples instead of hand-rolling what an example already shows.
|
||||
- **Reuse a block's own elements.** Need more rows, cards, items, or sections than ship by default? Repeat the block's **existing** element by mapping real data through the same markup - never invent parallel markup that drifts from its design. Need a variant (empty / loading / expanded)? Derive it from an element the block already has.
|
||||
|
||||
## Don't invent (read, don't guess)
|
||||
|
||||
- Never write a prop, variant value, import path, or `@reui/...` name you didn't read in a component's inline `api`, an installed example, or a `search` result. If you didn't see it, treat it as nonexistent - call `get_component` / `get_examples` / `search` first, or run the MCP `validate_usage` tool to check planned names + props against the docs before writing code.
|
||||
- If a getter returns `found: false` or `search` returns nothing, say so and fall back (plain shadcn, or ask) - never fabricate an install command or an API.
|
||||
|
||||
## What to change vs leave alone
|
||||
|
||||
- **Change:** the item's own data, copy, props, and layout to fit the app.
|
||||
- **Leave alone:** installed component files, hooks, and the shared theme - do not edit vendored ReUI internals; change behavior through props and the documented API.
|
||||
- Blocks are **portable React** - no `next/link`, `next/image`, or other framework-runtime imports inside them. Keep them portable.
|
||||
|
||||
## Demo data -> real data
|
||||
|
||||
- Replace every placeholder with the user's real data. Model it as **typed data structures** and **map over arrays** - never duplicate JSX per row/card. Keep small block-specific formatters next to the data.
|
||||
- Wire the real source (columns, fields, fetch). For `data-grid`, implement the server fetch contract if the user needs server-side data.
|
||||
- **Type from the component API, derive during render.** Type domain state through the component's own types - e.g. map status to `BadgeProps["variant"]` via a typed `Record<Status, …>` - instead of stringly-typed values. Compute view state during render; don't mirror derived data into `useState`/`useEffect`.
|
||||
- **Adapt on the right base.** Use the API for the project's base (Base UI vs Radix - see [components.md](./components.md)); the installed files are already base-correct, so reuse their shape rather than translating from memory.
|
||||
|
||||
## Believable content (no AI tells)
|
||||
|
||||
- Use realistic labels, counts, timestamps, and statuses that map to a real workflow.
|
||||
- No decorative buttons, fake tabs, meaningless toggles, equal-weight card walls, empty gradients, ornamental icons, or generic SaaS filler. Every element should do something.
|
||||
|
||||
## Operational surfaces (settings / profile / admin)
|
||||
|
||||
Pick ONE archetype and keep the family consistent: a vertical rail (3-6 sections), horizontal tabs (5-8), or a frame/stack. Prefer `frame` for tool-like surfaces, a card for profile-like ones. Don't mix archetypes in one surface.
|
||||
@@ -1,60 +0,0 @@
|
||||
# CLI: registry setup, license, non-interactive install
|
||||
|
||||
## Registry setup (one-time, per project)
|
||||
|
||||
Free items (the 22 components and all `c-*` examples) need only the plain string registry in `components.json`:
|
||||
|
||||
```json
|
||||
{ "registries": { "@reui": "https://reui.io/r/{style}/{name}.json" } }
|
||||
```
|
||||
|
||||
Premium items (blocks; Motion Icons and templates) require a ReUI license at install:
|
||||
|
||||
1. Add the key to `.env.local`:
|
||||
|
||||
```bash
|
||||
REUI_LICENSE_KEY=your-license-key
|
||||
```
|
||||
|
||||
2. Switch `components.json` to the authenticated object form:
|
||||
|
||||
```json
|
||||
{
|
||||
"registries": {
|
||||
"@reui": {
|
||||
"url": "https://reui.io/r/{style}/{name}.json",
|
||||
"headers": { "Authorization": "Bearer ${REUI_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?ref=skill
|
||||
|
||||
## Installing
|
||||
|
||||
Use the project's package runner (check `packageManager`):
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add @reui/<name> --yes # npm
|
||||
pnpm dlx shadcn@latest add @reui/<name> --yes # pnpm
|
||||
bunx --bun shadcn@latest add @reui/<name> --yes # bun
|
||||
```
|
||||
|
||||
`--yes` skips confirmation prompts. The CLI auto-detects the package manager from the lockfile (there is no `--package-manager` flag). It also resolves the correct base+style variant from `components.json`, so do not pass a style.
|
||||
|
||||
## Handling prompts and conflicts
|
||||
|
||||
- **Always pass `--yes`** so the CLI does not block on confirmation prompts.
|
||||
- **Do NOT pass `--overwrite` by default.** If the CLI reports an existing file, read the output and resolve deliberately: install under a different name, adjust the path, or ask the user. Only use `--overwrite` when the user explicitly wants to replace a file.
|
||||
- **Preview first when touching an existing project**: `npx shadcn@latest add @reui/<name> --dry-run` shows what would change; `--diff <file>` shows a specific file's diff. Use these before overwriting.
|
||||
- Run from the **project root** so `components.json` and `.env.local` are found.
|
||||
|
||||
## Free vs premium boundary
|
||||
|
||||
- Public, no key: `c-*` examples and the 22 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?ref=skill (their key) or https://reui.io/pricing?ref=skill (upgrade).
|
||||
@@ -1,428 +0,0 @@
|
||||
# ReUI components
|
||||
|
||||
The 22 ReUI building blocks: `alert`, `autocomplete`, `badge`, `cascader`, `code-block`, `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 v9. It is NOT a styled `<table>` and does NOT take `data`/`columns` props directly. The contract:
|
||||
|
||||
- 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 = useTable({
|
||||
features: dataGridFeatures,
|
||||
data,
|
||||
columns,
|
||||
})
|
||||
|
||||
<DataGrid table={table} recordCount={data.length}>
|
||||
<DataGridTable />
|
||||
</DataGrid>
|
||||
```
|
||||
|
||||
Common mistakes:
|
||||
|
||||
- **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 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
|
||||
|
||||
**Required:** `value` (`Record<string, T[]>`), `onValueChange`, `getItemValue`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Kanban value={cols} onValueChange={setCols} getItemValue={(i) => i.id}>
|
||||
<KanbanBoard>
|
||||
{Object.entries(cols).map(([id, items]) => (
|
||||
<KanbanColumn key={id} value={id}>
|
||||
<KanbanColumnHandle><h3>{id}</h3></KanbanColumnHandle>
|
||||
<KanbanColumnContent value={id}>
|
||||
{items.map((i) => (
|
||||
<KanbanItem key={i.id} value={i.id}>
|
||||
<KanbanItemHandle>{i.title}</KanbanItemHandle>
|
||||
</KanbanItem>
|
||||
))}
|
||||
</KanbanColumnContent>
|
||||
</KanbanColumn>
|
||||
))}
|
||||
</KanbanBoard>
|
||||
<KanbanOverlay><div className="bg-muted size-full rounded-md" /></KanbanOverlay>
|
||||
</Kanban>
|
||||
```
|
||||
|
||||
**Gotcha:** state is `Record<columnId, T[]>`. Each `KanbanColumnContent value` must match its parent `KanbanColumn value`. Omit `KanbanOverlay` and the drag preview silently breaks.
|
||||
|
||||
## sortable
|
||||
|
||||
**Required:** `value` (`T[]`), `onValueChange`, `getItemValue`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Sortable value={items} onValueChange={setItems} getItemValue={(i) => i.id}>
|
||||
{items.map((i) => (
|
||||
<SortableItem key={i.id} value={i.id}>
|
||||
<SortableItemHandle><GripVertical /></SortableItemHandle>
|
||||
{i.label}
|
||||
</SortableItem>
|
||||
))}
|
||||
</Sortable>
|
||||
```
|
||||
|
||||
**Gotcha:** a flat 1D reorder list (not columns - that is `kanban`). `getItemValue` must return a stable, unique string. Pass `layout="grid"` or `layout="nested"` for non-list layouts.
|
||||
|
||||
## filters
|
||||
|
||||
**Required:** `fields` (`FilterField[]`). The value is ONE `FilterQuery` tree - `query` + `onQueryChange`, or uncontrolled `defaultQuery`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
const fields: FilterField[] = [
|
||||
{ id: "title", label: "Title", type: "text" },
|
||||
{
|
||||
id: "status",
|
||||
label: "Status",
|
||||
type: "select",
|
||||
options: [
|
||||
{ value: "active", label: "Active" },
|
||||
{ value: "archived", label: "Archived" },
|
||||
],
|
||||
},
|
||||
]
|
||||
const [query, setQuery] = useState<FilterQuery>(() => createFilterQuery())
|
||||
|
||||
<Filters fields={fields} query={query} onQueryChange={setQuery} />
|
||||
```
|
||||
|
||||
**Gotcha:** the state is a TREE, not a list of chips. `FilterQuery` is a group of rules joined by `and`/`or` and a group may hold another group, so `(A and B) or C` is expressible; a rule is `{ id, type: "rule", path: ["status"], operator, value }` and `path` is the whole nested attribute path, root first. The pre-rewrite API is GONE: there is no `filters`/`onChange` prop, no `FilterFieldConfig` (fields are `FilterField`, nested through their own `fields`, keyed `id` not `key`), and no `createFilter()` - it minted ids inside a pure function and broke hydration, so ids now come from `createFilterIdFactory(seed)` seeded off `useId`, and `createFilterQuery()` / `createFilterRule()` take one. Read the query back with `flattenFilterConditions` (`{ path, field, operator, values, negated }` per rule, incomplete rules skipped) and walk the tree yourself when the parentheses carry meaning - the primitive compiles nothing, no SQL, no query string.
|
||||
|
||||
`variant` picks the chrome over that one query: `"basic"`, the default, is the flat chip row for a toolbar over a table; `"advanced"` is the condition builder, hung off a trigger or rendered in place with `advancedMode="inline"`. Both read and write the same tree, so a saved view built in one opens in the other. Other props worth knowing before you hand-roll them: `size` is two rungs, `"sm" | "default"`, resolved per style (there is no `lg`); `reorderable` turns on drag and Alt+Arrow row moves in the builder; `onBeforeQueryChange` is the ONE veto point for every write (return `false` to refuse, it cannot rewrite); `editors` registers custom value editors a field selects by `editor` name; `labels` / `operatorLabels` own every rendered string; `pathCollapse` + `maxPathSegments` shorten deep attribute paths; `renderChip` / `renderValue` / `renderEmpty` replace rendered parts. On a field, `loadOptions` supplies async options with paging and `resolveValues` renders a chip restored from a saved view whose option was never loaded. Pairs naturally with `data-grid`.
|
||||
|
||||
## cascader
|
||||
|
||||
**Required:** `items` (a tree of `{ value, label, children? }`), plus the panel parts inside `CascaderContent`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Cascader items={items} value={value} onValueChange={setValue}>
|
||||
<CascaderTrigger render={<Button variant="outline" />}>
|
||||
<CascaderValue placeholder="Select an attribute" />
|
||||
</CascaderTrigger>
|
||||
<CascaderContent className="w-80">
|
||||
<CascaderPanel>
|
||||
<CascaderNav>
|
||||
<CascaderBreadcrumb />
|
||||
<CascaderInput />
|
||||
</CascaderNav>
|
||||
<CascaderEmpty />
|
||||
<CascaderList maxHeight={288}>
|
||||
<CascaderItems />
|
||||
</CascaderList>
|
||||
<CascaderStatus />
|
||||
</CascaderPanel>
|
||||
</CascaderContent>
|
||||
</Cascader>
|
||||
```
|
||||
|
||||
**Gotcha:** pressing a branch NAVIGATES, it does not select - only leaves are selectable until you pass `selectable="any"` or a predicate, and once a branch is selectable its chevron becomes the only way to open it. `CascaderInput` must stay inside `CascaderContent` (Base UI refills the query from the selection when the input sits outside the popup). Always include `CascaderStatus`: it is the live region announcing level changes, which the visual breadcrumb does not provide to screen readers. Accepts a flat adjacency list via `getParent` as well as nested `children`. `searchScope="deep"` searches every level and annotates results with their path; `multiple` gives checkbox rows; `inline` + a bare `CascaderPanel` embeds it with no popover.
|
||||
|
||||
The shape above is `mode="drill"`, the default. `mode="tree"` keeps the same parts (drop `CascaderBreadcrumb`, pass `showBack={false}`, drive expansion with `expanded`/`onExpandedChange`); `mode="columns"` REPLACES `CascaderList` + `CascaderItems` with a single `CascaderColumns`, and has no breadcrumb. Other props worth knowing before you hand-roll them: `cascade` (multi-select only, parent/child selection with indeterminate branches - pair it with `selectable="any"`, since a leaf-only tree can never cascade), `indicator={false}` to drop the single-select check and its gutter (visual only, no-op with `multiple`), `virtualize`/`virtualizeThreshold` plus `CascaderVirtualItems` for long levels, and `getChildren` for async levels with cursor paging, retry on failure and optional `prefetch`. `CascaderFooter` pins commands below the list (`actions` is the quick path) and `CascaderSubmenu` opens one as a side-anchored flyout with the full menu keyboard model. To head a run of rows use `CascaderGroup` wrapping a `CascaderLabel` - a bare label inside a listbox names nothing and is dropped from the accessibility tree - and `CascaderSeparator` for the rule between runs. Every rendered string comes from `labels`, and the panel is RTL-correct under a `DirectionProvider` or `dir="rtl"`.
|
||||
|
||||
## date-selector
|
||||
|
||||
**Required:** none, but wire `onChange` to capture the value.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
const [value, setValue] = useState<DateSelectorValue | undefined>()
|
||||
|
||||
<DateSelector value={value} onChange={setValue} label="Due date" />
|
||||
```
|
||||
|
||||
**Gotcha:** the value is a structured `DateSelectorValue` (period / operator / start+end dates), NOT a `Date` - never pass a raw `Date`. Use `allowRange={false}` to lock single-date picking. Read `get_component("date-selector")` for the value shape.
|
||||
|
||||
## tree
|
||||
|
||||
**Required:** `tree` (a `@headless-tree/core` instance you construct)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Tree tree={tree}>
|
||||
{tree.getItems().map((item) => (
|
||||
<TreeItem key={item.getId()} item={item}>
|
||||
<TreeItemLabel />
|
||||
</TreeItem>
|
||||
))}
|
||||
</Tree>
|
||||
```
|
||||
|
||||
**Gotcha:** `Tree` is a styled shell - it takes a headless-tree instance via `tree`, NOT `data`/`items` props. Build the instance with `@headless-tree/react`. External API: https://headless-tree.lukasbach.com/
|
||||
|
||||
## stepper
|
||||
|
||||
**Required:** `StepperItem step` (number), `StepperContent value` (number)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Stepper defaultValue={1}>
|
||||
<StepperNav>
|
||||
<StepperItem step={1}>
|
||||
<StepperTrigger><StepperIndicator>1</StepperIndicator></StepperTrigger>
|
||||
<StepperSeparator />
|
||||
</StepperItem>
|
||||
<StepperItem step={2}>
|
||||
<StepperTrigger><StepperIndicator>2</StepperIndicator></StepperTrigger>
|
||||
</StepperItem>
|
||||
</StepperNav>
|
||||
<StepperPanel>
|
||||
<StepperContent value={1}>Step 1 content</StepperContent>
|
||||
<StepperContent value={2}>Step 2 content</StepperContent>
|
||||
</StepperPanel>
|
||||
</Stepper>
|
||||
```
|
||||
|
||||
**Gotcha:** steps are 1-indexed. Without `StepperPanel` + `StepperContent` you render the nav trail but no body. Put `StepperSeparator` in every `StepperItem` except the last.
|
||||
|
||||
## timeline
|
||||
|
||||
**Required:** `TimelineItem step` (number)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Timeline>
|
||||
<TimelineItem step={1}>
|
||||
<TimelineHeader>
|
||||
<TimelineDate>March 2024</TimelineDate>
|
||||
<TimelineTitle>Project initialized</TimelineTitle>
|
||||
</TimelineHeader>
|
||||
<TimelineIndicator />
|
||||
<TimelineSeparator />
|
||||
<TimelineContent>Repo and architecture set up.</TimelineContent>
|
||||
</TimelineItem>
|
||||
</Timeline>
|
||||
```
|
||||
|
||||
**Gotcha:** each item needs a unique `step`. `orientation` is `"vertical"` (default) or `"horizontal"`. This is a static event display, not interactive like `stepper`.
|
||||
|
||||
## autocomplete
|
||||
|
||||
**Required:** `items` (array; each item has at least `value`)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Autocomplete items={items}>
|
||||
<AutocompleteInput placeholder="Search..." />
|
||||
<AutocompleteContent>
|
||||
<AutocompleteEmpty>No results found.</AutocompleteEmpty>
|
||||
<AutocompleteList>
|
||||
{(item) => (
|
||||
<AutocompleteItem key={item.value} value={item}>{item.label}</AutocompleteItem>
|
||||
)}
|
||||
</AutocompleteList>
|
||||
</AutocompleteContent>
|
||||
</Autocomplete>
|
||||
```
|
||||
|
||||
**Gotcha:** `AutocompleteList` takes a render-prop `(item) => ReactNode`, NOT a mapped array of children. External API: https://base-ui.com/react/components/autocomplete
|
||||
|
||||
## phone-input
|
||||
|
||||
**Required:** none, but wire `onChange`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<PhoneInput placeholder="Enter phone number" defaultCountry="US" value={value} onChange={setValue} />
|
||||
```
|
||||
|
||||
**Gotcha:** `value`/`onChange` use an E.164 string (e.g. `"+14155551234"`), not a display-formatted string; `onChange` can fire `undefined`. `defaultCountry` is a 2-letter ISO code. Wraps `react-phone-number-input`.
|
||||
|
||||
## number-field
|
||||
|
||||
**Required:** wrap the controls in `NumberFieldGroup`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<NumberField defaultValue={0}>
|
||||
<NumberFieldScrubArea label="Quantity" />
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
```
|
||||
|
||||
**Gotcha:** import from `@/components/ui/number-field`. The accessible label goes on `NumberFieldScrubArea`, not `NumberField`. External API: https://base-ui.com/react/components/number-field
|
||||
|
||||
## rating
|
||||
|
||||
**Required:** `rating` (number)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Rating rating={4.5} showValue editable onRatingChange={setRating} />
|
||||
```
|
||||
|
||||
**Gotcha:** supports decimals (partial stars). Pass `editable` + `onRatingChange` for interactive input; omit both for a read-only display.
|
||||
|
||||
## scrollspy
|
||||
|
||||
**Required:** `targetRef` (the scroll container ref)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Scrollspy targetRef={containerRef}>
|
||||
<a href="#s1" data-scrollspy-anchor="s1">Section 1</a>
|
||||
<a href="#s2" data-scrollspy-anchor="s2">Section 2</a>
|
||||
</Scrollspy>
|
||||
<div ref={containerRef}>
|
||||
<div id="s1">...</div>
|
||||
<div id="s2">...</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
**Gotcha:** each link's `data-scrollspy-anchor` must match a section `id`. `targetRef` is the scrollable container (defaults to the window).
|
||||
|
||||
## frame
|
||||
|
||||
**Required:** `Frame` > `FramePanel`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Frame>
|
||||
<FramePanel>
|
||||
<FrameHeader>
|
||||
<FrameTitle>Title</FrameTitle>
|
||||
<FrameDescription>Description</FrameDescription>
|
||||
</FrameHeader>
|
||||
<div className="p-5">Content</div>
|
||||
<FrameFooter>Footer</FrameFooter>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
```
|
||||
|
||||
**Gotcha:** a structured card shell for tool-like surfaces. `stacked` connects multiple panels with shared borders; `dense` removes panel padding; radius via the `--frame-radius` CSS variable.
|
||||
|
||||
## icon-stack
|
||||
|
||||
**Required:** one child icon
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<IconStack aria-hidden="true">
|
||||
<InboxIcon className="size-4" />
|
||||
</IconStack>
|
||||
```
|
||||
|
||||
**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.
|
||||
|
||||
## code-block
|
||||
|
||||
**Required:** `code` + `language`, or pre-highlighted `lines`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<CodeBlock code={code} language="tsx" />
|
||||
|
||||
<CodeBlock code={code} language="tsx" showLineNumbers maxLines={20}>
|
||||
<CodeBlockHeader>
|
||||
<CodeBlockTitle>use-totals.ts</CodeBlockTitle>
|
||||
<CodeBlockLanguage />
|
||||
<CodeBlockCopyButton className="ml-auto" />
|
||||
</CodeBlockHeader>
|
||||
<CodeBlockExpandButton />
|
||||
</CodeBlock>
|
||||
```
|
||||
|
||||
**Gotcha:** the one-liner is already a complete block; every child (header, title, language label, copy button, wrap toggle, expand button, line actions) is optional chrome, at any depth. Shiki is the only npm dependency and loads lazily, one chunk per language, on first highlight; `lines` (from `highlightCode` in `code-block-highlight`, which is server-safe and has no `"use client"`) or `highlight={false}` loads nothing at all. `maxLines` caps the height AND marks the block collapsible, which is what makes `CodeBlockExpandButton` appear. Use `variant="ghost"` when the block sits inside a surface that already has a border.
|
||||
|
||||
## alert
|
||||
|
||||
**Required:** `Alert` > `AlertTitle`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Alert variant="success">
|
||||
<ShieldCheckIcon />
|
||||
<AlertTitle>Security update</AlertTitle>
|
||||
<AlertDescription>Enable two-factor authentication.</AlertDescription>
|
||||
<AlertAction><Button size="xs">Update</Button></AlertAction>
|
||||
</Alert>
|
||||
```
|
||||
|
||||
**Gotcha:** shadcn-compatible API. `variant`: `default | destructive | info | success | warning | invert`. The non-default variants use ReUI extended color tokens (`--success`/`--info`/`--warning`/`--invert`), which the install adds. Defer generic alert rules to the shadcn skill.
|
||||
|
||||
## badge
|
||||
|
||||
**Required:** none (text child).
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Badge variant="success-light" size="sm">Success</Badge>
|
||||
<Badge variant="outline" radius="full">Pill</Badge>
|
||||
```
|
||||
|
||||
**Gotcha:** shadcn-compatible. Rich `variant` set (solid, `-outline`, `-light` per color), `size` `xs..xl`, `radius` `default | full`. Like `alert`, the color variants rely on ReUI extended tokens. Prefer `Badge` variants over raw color classes for statuses.
|
||||
|
||||
## base vs radix - write for the project's base
|
||||
|
||||
ReUI ships every component in two builds: `base` (Base UI) and `radix` (Radix UI). The install command and name are identical, and the CLI installs the build matching the project. But you must write/adapt code against the **right base**, because their APIs differ.
|
||||
|
||||
**Detect the base first.** Read `components.json` -> `style` and take the segment before the first `-`:
|
||||
|
||||
- `"style": "base-nova"` -> **Base UI**
|
||||
- `"style": "radix-nova"` -> **Radix UI**
|
||||
|
||||
**Then use that base's API.** The deltas mirror shadcn's base-vs-radix split:
|
||||
|
||||
- Slot/composition: Base UI `render={<… />}` vs Radix `asChild`.
|
||||
- `Select`: Base UI takes `items`; Radix uses `<SelectItem>` children.
|
||||
- `ToggleGroup`: Base UI `multiple` boolean vs Radix `type="single" | "multiple"`.
|
||||
|
||||
The safest path is to **read the installed files and `c-*` examples** - they're already in your base, so reuse their wiring instead of guessing. When `get_component`'s inline `api` or an example shows the other base's shape, translate it to your base (or `validate_usage` to confirm). Defer the generic base/radix mechanics to the shadcn skill.
|
||||
@@ -1,45 +0,0 @@
|
||||
# Craft: make ReUI UI exceptional, not generic
|
||||
|
||||
ReUI items ship senior-designer quality. Your adaptation has to hold that bar, so the result reads like a real product surface a team would keep - not a wireframe an AI generated. Use these alongside the reuse rules in [adapting.md](./adapting.md).
|
||||
|
||||
## Have a point of view
|
||||
|
||||
Pick an emotional register before you compose - calm, operational, premium, editorial, dense, energetic - and let layout, spacing, surface treatment, and icon behavior all reinforce it. One or two memorable decisions and restraint everywhere else beats ten generic ones. UI with no point of view reads as generated.
|
||||
|
||||
## Brutally clear hierarchy
|
||||
|
||||
One focal point per card or panel: the dominant metric or task first, its label second, supporting detail third. The first thing the eye lands on should be the right thing; secondary text must read as secondary. Borders, separators, and surfaces do real work to create 2-3 information bands - don't flatten everything to equal weight.
|
||||
|
||||
## Spacing rhythm and deliberate density
|
||||
|
||||
Gaps are a signal, not a default. Keep them intentional and consistent within a family (`gap-1`/`gap-2` for tight operational rows, larger gaps for section breaks), and smaller within a group than between groups. Match the surrounding ReUI density; don't pad an operational surface like a marketing page, and don't drift density mid-section. The composition should still feel authored in grayscale.
|
||||
|
||||
## Cover the real states (the usual miss)
|
||||
|
||||
A surface isn't done at the happy path. Compose, and wire:
|
||||
|
||||
- **Empty** - a purposeful empty state (short message + the primary action), never a blank panel.
|
||||
- **Loading** - a **skeleton** that matches the real layout, not a centered spinner.
|
||||
- **Error** - an inline, recoverable error with a retry, announced via `role="status"`/`aria-live`.
|
||||
|
||||
Derive these from an element the block already has (don't invent parallel markup), or `get_examples` for a state-specific example.
|
||||
|
||||
## Responsive by default
|
||||
|
||||
Mobile-first, not mobile-afterthought. In constrained rows/cards/sidebars, put `min-w-0` on the shrinking container and `truncate` long single-line labels; protect the primary label's width and let secondary content compress. Reflow layouts (multi-column -> single column) rather than just shrinking them. Desktop and mobile should both look designed.
|
||||
|
||||
## Motion, subtly
|
||||
|
||||
Motion should clarify, not decorate. Use ReUI Motion Icons on primary actions for a subtle hover cue; keep transitions short (~200-300ms) with calm easing; prefer a skeleton pulse over a spinner. No bouncing, no gratuitous entrance animations on every element.
|
||||
|
||||
## Real, activated content
|
||||
|
||||
Use believable, typed data (realistic labels, counts, timestamps, statuses that map to a real workflow) - never lorem or abstract filler. Every visible control does something: no decorative buttons, fake tabs, meaningless toggles, or stats with no job. It must still hold with long names, empty values, and crowded data.
|
||||
|
||||
## Avoid the AI tells
|
||||
|
||||
These instantly read as generated - don't ship them: equal-weight card walls, empty gradients, repetitive padding everywhere, generic enterprise copy, ornamental icons, and number tiles that don't earn their place.
|
||||
|
||||
## The bar
|
||||
|
||||
Before you finish, ask: **would a product team keep this instead of replacing it? Does it still feel strong after swapping in real content?** If not, reuse the shipped ReUI design harder - don't restyle it into something new - then run the [quality.md](./quality.md) gates.
|
||||
@@ -1,39 +0,0 @@
|
||||
# Icons (ReUI delta over shadcn)
|
||||
|
||||
Follow the shadcn icon rules (use the project's configured `iconLibrary`, `data-icon` on icons inside `Button`, no sizing classes on icons inside components, pass icons as component objects not string keys). ReUI adds the following.
|
||||
|
||||
## Portable icons (library-agnostic)
|
||||
|
||||
ReUI components, examples, and blocks are authored to be icon-library-agnostic. When `iconLibrary` is set in `components.json`, the shadcn CLI installs each item's icons in **your** library automatically - you swap nothing. If an installed item's icons don't match your project (for example `iconLibrary` isn't set, so they came in from the item's demo library), change the **import source and component name** to your library, keeping the same icon-name semantics:
|
||||
|
||||
- `lucide` -> `lucide-react`
|
||||
- `tabler` -> `@tabler/icons-react`
|
||||
- `phosphor` -> `@phosphor-icons/react`
|
||||
- `remix` -> `@remixicon/react`
|
||||
- `hugeicons` -> `@hugeicons/react`
|
||||
|
||||
Don't assume `lucide-react`; read `iconLibrary` from `components.json`.
|
||||
|
||||
## Keep icons purposeful
|
||||
|
||||
Icons support the hierarchy, they don't replace it: keep them small, matched to the surrounding density, and decorative ones `aria-hidden="true"` (an icon-only control still needs an accessible label on the control). Don't add ornamental icons that do no job.
|
||||
|
||||
## Motion Icons (the `@reui/icons/...` set)
|
||||
|
||||
ReUI ships its own icon set in 4 styles (outline, solid, duotone, filled), each icon in two variants:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add @reui/icons/default/<style>/<name> --yes # static
|
||||
npx shadcn@latest add @reui/icons/animated/<style>/<name> --yes # hover-animated (motion/react)
|
||||
```
|
||||
|
||||
Finding them via the MCP is free; installing requires an Ultimate license (`REUI_LICENSE_KEY`, see [cli.md](./cli.md)). Reach for a Motion Icon on a primary action when a subtle hover cue helps; keep motion restrained.
|
||||
|
||||
Finding icons:
|
||||
|
||||
- Several icons (the common case): **`search_icons(concepts[])`** - up to 24 concepts in one call, the best icons per concept with install commands. Pass `animated: true` to get only icons with a hover-animated Motion variant.
|
||||
- One icon: `search` with `type: "icon"`.
|
||||
- Icon results and `get_icon` carry `animated: true` and `installAnimated` when an animated variant exists - use those install strings, do not construct paths by hand.
|
||||
- Every icon result carries a `previewUrl` (its live icon-category page) - **share it with the user** so they can SEE the icon before installing.
|
||||
|
||||
The `icon-stack` component composes multiple icons into a stacked display.
|
||||
@@ -1,22 +0,0 @@
|
||||
# Quality gates (security, accessibility, scroll)
|
||||
|
||||
These are the **done gate**, not a nice-to-have: before you call any ReUI work finished, call the MCP `get_audit_checklist` tool and pass every item below (plus the craft bar in [craft.md](./craft.md)). Then typecheck and lint.
|
||||
|
||||
## Security
|
||||
|
||||
- Never `dangerouslySetInnerHTML`. Render data as text/components.
|
||||
- External links (`target="_blank"`) must always pair `rel="noopener noreferrer"`.
|
||||
- No real PII, secrets, or tokens in demo or committed code. Remote media only from sources the project already allows.
|
||||
|
||||
## Accessibility
|
||||
|
||||
- Implicit list/card items that navigate get real anchors with a standard hover affordance.
|
||||
- Icon-only or numeric buttons need an `aria-label`; decorative icons get `aria-hidden`.
|
||||
- Every non-submit button is `type="button"`.
|
||||
- Keyboard + focus: everything interactive is reachable in a sensible Tab order with a visible focus ring; layers (dialogs/sheets/menus) trap focus and close on `Escape`. ReUI components ship standard keyboard behavior - read each component's inline `api` rather than re-implementing it.
|
||||
- Announce async UI: loading and error messages use `role="status"` / `aria-live` so they're not silent to screen readers.
|
||||
|
||||
## Scroll mechanics
|
||||
|
||||
- Make scroll regions with a parent-owned height: a `min-h-0` + flex chain down to the scroll container. Never guess a `max-h`.
|
||||
- The scroll container owns `overflow-auto`; ancestors stay `min-h-0` so the height resolves.
|
||||
@@ -1,35 +0,0 @@
|
||||
# ReUI registry structure
|
||||
|
||||
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 22 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).
|
||||
|
||||
## The @reui registry
|
||||
|
||||
Install everything through the shadcn CLI: `npx shadcn@latest add @reui/<name> --yes`. The CLI reads the `@reui` registry from the project's `components.json`. Free items need only the plain string form:
|
||||
|
||||
```json
|
||||
{ "registries": { "@reui": "https://reui.io/r/{style}/{name}.json" } }
|
||||
```
|
||||
|
||||
Premium installs need the authenticated form + `REUI_LICENSE_KEY` in `.env.local` - see [cli.md](./cli.md). The MCP `get_project_context` tool returns the right config.
|
||||
|
||||
## Know your base: base or radix
|
||||
|
||||
ReUI ships every item in two builds - `base` (Base UI) and `radix` (Radix UI) - with mirrored names. The CLI installs the build matching your project automatically, but **you must write code against the right base's API**. Detect it from `components.json` -> `style`: the segment before the first `-` is the base (`base-nova` -> Base UI, `radix-nova` -> Radix UI). The installed files and `c-*` examples are already in your base - read them and adapt on that base. See [components.md](./components.md) for the API deltas.
|
||||
|
||||
**So the MCP's own `docsUrl` and `previewUrl` match your base**, send your `style` to the MCP: add `?style=<your components.json style>` to the ReUI MCP server URL (or set an `X-Reui-Style` header) in your MCP client config - set once, applies to every call. The MCP then resolves docs/preview links to YOUR library (`/docs/components/radix/...`, `/preview/radix/...` for a radix project) instead of the default base; `get_project_context` echoes back the style it currently sees so you can confirm it. Install commands are unaffected (the CLI already installs the right variant). If you notice the MCP returning `base` links for a `radix` project, tell the user to add `?style=` to the server URL.
|
||||
|
||||
Blocks adapt to your active theme through semantic tokens and CSS variables - change the theme and every block follows.
|
||||
|
||||
## Free vs premium
|
||||
|
||||
- **Free, no key:** the 22 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
|
||||
|
||||
The canonical index of every component's API docs is **https://reui.io/llms.txt** (returned as `componentsApiUrl` in MCP results). Prefer the inline `api` from `get_component`; use the index/docs as the fallback.
|
||||
@@ -1,26 +0,0 @@
|
||||
# Styling (ReUI delta over shadcn)
|
||||
|
||||
Follow the shadcn skill for the generic rules (semantic colors not raw values, `gap-*` not `space-y-*`, `size-*`, `cn()`, no manual `dark:` overrides, no overlay `z-index`). This file is only the ReUI-specific additions.
|
||||
|
||||
## ReUI extended semantic tokens
|
||||
|
||||
ReUI adds semantic tokens beyond shadcn's base set. Use these instead of raw colors for status and emphasis:
|
||||
|
||||
- `--success` / `--success-foreground`
|
||||
- `--info` / `--info-foreground`
|
||||
- `--warning` / `--warning-foreground`
|
||||
- `--destructive-foreground` (paired with shadcn's `--destructive`)
|
||||
- `--invert` / `--invert-foreground` (inverted surfaces)
|
||||
|
||||
Use them as Tailwind utilities (`bg-success text-success-foreground`, `text-warning`, ...). They are defined in the project's global CSS and registered with Tailwind (`@theme inline` on v4). If a token is missing in the project, add it to the global CSS file (never a new file) following the same `name` / `name-foreground` convention, exactly as the shadcn customization rules describe.
|
||||
|
||||
**Incorrect:** `<span className="text-green-600">Active</span>`
|
||||
**Correct:** `<Badge variant="success">Active</Badge>` or `<span className="text-success">Active</span>`
|
||||
|
||||
## Blocks follow your theme
|
||||
|
||||
When you install a block it adapts to your active theme through the semantic tokens above and the project's CSS variables. Don't hardcode style-specific values into installed block code and don't fork it to "restyle" - change the theme via the CSS variables / a preset and every block follows. Want a different look? `search` for a block whose design already fits instead of re-skinning one.
|
||||
|
||||
## Density and typography rhythm
|
||||
|
||||
ReUI operational UI usually feels dense, not airy. Keep the gap between a title and its supporting description tight by default (`gap-0.5`, `space-y-1`, or `space-y-px`), and smaller than the gap between sections. Match the surrounding ReUI density when you add rows or fields; do not pad operational surfaces like a marketing page.
|
||||
@@ -1,54 +0,0 @@
|
||||
# Workflow: find -> install -> read API -> adapt
|
||||
|
||||
The core ReUI loop. The MCP tells you what to install and gives you the API; the shadcn CLI installs it; you turn the installed files into correct, themed, data-wired code by **reuse**, not redesign.
|
||||
|
||||
## 1. Find (ReUI MCP `search` / `compose_page`)
|
||||
|
||||
**Full multi-section page ask?** Call `compose_page(intent, sections?)` FIRST, before searching block-by-block. It returns ordered sections, each with the best block for the intent (top pick + alternates); sections listed in `unavailableSections` have no real inventory - compose those from components, do not force a bad block.
|
||||
|
||||
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 22 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`.
|
||||
|
||||
Example: "build a users management page with filters" -> `search({ query: "users management page with filters", type: "block", component: "data-grid", features: ["filters"] })`.
|
||||
|
||||
Each result has `install`, `previewUrl`, `docsUrl`, `componentsUsed`, `score`, `termCoverage`, and `whyMatch`. `score` is relative to the top hit (the top is ~100 by construction), not an absolute quality - compare results to each other, and show the user the top options if several score closely; do not silently guess. A low `termCoverage` means a weak match even with a high score - rephrase or widen.
|
||||
|
||||
**Always show the preview link.** Whenever you list or recommend items - from `search`, `search_icons`, `list_components`, `compose_page`, or a getter - include each item's `previewUrl` (a live preview page) so the user can SEE it before you install. Blocks and examples link to an individual live preview; icons and components to their live category/component page. This applies to every listing, not only a single pick.
|
||||
|
||||
## 2. Install (shadcn CLI)
|
||||
|
||||
Run the result's `install` command from the project root, non-interactively:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add @reui/<name> --yes
|
||||
```
|
||||
|
||||
The CLI reads `components.json`, installs the correct base+style variant, resolves `registryDependencies` (a block pulls in its components), installs npm deps, and rewrites aliases. Do not pass the base/style. See [cli.md](./cli.md).
|
||||
|
||||
## 3. Read the API (do not guess props)
|
||||
|
||||
Before writing code against any component an item uses:
|
||||
|
||||
1. The item's `componentDigests` already give a 1-line contract per component - often enough to wire it. For the full API, call **`get_component(names)`** with ALL of `componentsUsed` in ONE call (it accepts an array) and read each inline `api` - no web fetch. **Share the component's `docsUrl`** (its 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.
|
||||
2. Call **`get_examples(name)`** for the free `c-*` examples of that component; install one and **read the added files** to copy the exact composition. This is the fastest correct path - the example shows real wiring you adapt, not invent.
|
||||
3. About to write a prop you did not see in an `api` or installed file? Run **`validate_usage`** BEFORE writing the code - per-prop documented / notDocumented verdicts plus did-you-mean suggestions. notDocumented means read the API, not push on.
|
||||
|
||||
## 4. Adapt (reuse-first) - do not skip
|
||||
|
||||
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 `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)).
|
||||
5. **Validate before finalizing**: if your adaptation introduced components or props you did not read in an `api` or example, run `validate_usage` on them.
|
||||
6. **Hit the craft bar** - clear hierarchy, deliberate density, the empty / loading / error states, subtle motion, and mobile-first responsiveness (see [craft.md](./craft.md)). Generic-looking output means you under-reused the design, not that it needs restyling.
|
||||
7. **Pass the quality gates** (security, a11y, scroll) - call the MCP `get_audit_checklist` tool and clear every item (see [quality.md](./quality.md)).
|
||||
8. **Typecheck / lint**.
|
||||
|
||||
## If no single block fits
|
||||
|
||||
Compose from components (`compose_page` tells you which sections have no block inventory via `unavailableSections`). `search` the components you need, read each `get_component` API, install a worked `get_examples` example for each, and assemble by adapting those examples. A block in the same category is a useful reference - install it and read its files to see how ReUI composes those components, then adapt.
|
||||
@@ -1,58 +0,0 @@
|
||||
# ReUI MCP: full reference
|
||||
|
||||
The ReUI MCP (`https://mcp.reui.io`, Streamable HTTP) is free to use but needs a ReUI account: on first use the agent signs in with ReUI (a free account is created if the user has none), so every request is tied to an account. Free covers components and examples; a Pro or Ultimate license unlocks premium blocks and Motion Icons and removes the daily request limit. It does **discovery + guidance** (search, inline APIs, page planning, validation) and never serves source; the shadcn CLI does **installation**, and the license key lives there (the `@reui` entry in `components.json`, backed by `.env.local`). Goal: from the user's intent to correct, themed, data-wired ReUI code in the **fewest tokens and calls**, with **no guessing**.
|
||||
|
||||
## Golden path (token-optimal - follow this order)
|
||||
|
||||
Most tasks need 2-4 MCP calls and ZERO web fetches:
|
||||
|
||||
1. **`search(query, ...hints)`** -> pick the top 1-3 results. Each result already carries `install`, `previewUrl`, `docsUrl`, `componentsUsed`, `score`, `whyMatch`. The payload is complete - do not call another tool just to "confirm" a result.
|
||||
2. **`get_component([...componentsUsed])`** in ONE batched call (one name or an array of up to 20) -> read each inline `api`. This **replaces** fetching docs pages. Often skippable: search responses carry `componentDigests`, a compact API contract per referenced component.
|
||||
3. **`get_examples(component)`** -> install ONE returned `c-*` example, read the added files, copy the composition.
|
||||
4. **`get_install_command(item)`** only to validate a name you are unsure of (results already include `install`). Run the install with the shadcn CLI (`--yes`).
|
||||
5. **`get_audit_checklist()`** before declaring done.
|
||||
|
||||
If you already know the exact item name, skip `search`. Everything else is situational.
|
||||
|
||||
## The 5 task-specific tools (when to reach for each)
|
||||
|
||||
- **`compose_page`** - BEFORE building any full page (dashboard, settings, billing, landing). Pass the intent (and optionally the sections you want); it returns ordered sections, each with the best premium block for the intent (top pick + alternates). Sections with no real inventory are listed honestly in `unavailableSections` - compose those from components instead of forcing a bad block.
|
||||
- **`search_icons`** - whenever you need icons, especially several. Batch up to 24 concepts in one call; each concept returns its best icons with install commands. Pass `animated: true` to get only icons that have a hover-animated Motion variant.
|
||||
- **`validate_usage`** - BEFORE writing code with component names or props you have not read in an inline `api` or an installed example. It checks planned names + props against the indexed API docs and registry item names; returns did-you-mean suggestions and per-prop documented / notDocumented verdicts. Deterministic, no inference - a notDocumented prop means stop and read the API, not push on.
|
||||
- **`whats_new`** - when your registry knowledge might be stale (a name 404s, the user mentions an item you don't know). Returns items added/removed per build, newest first.
|
||||
- **`report_issue`** - when an installed item is actually broken (bad source, wrong dependency, broken preview). Goes straight to the ReUI team; rate-limited 5/hour. Not for usage questions.
|
||||
|
||||
## All 19 tools
|
||||
|
||||
`search`, `get_block`, `get_example`, `get_icon`, `list_block_groups`, `list_block_categories`, `list_example_categories`, `list_icon_categories`, `list_components`, `get_component`, `get_examples`, `search_icons`, `compose_page`, `validate_usage`, `whats_new`, `report_issue`, `get_install_command`, `get_project_context`, `get_audit_checklist`. The MCP serves the full parameter schemas; do not guess parameters beyond them.
|
||||
|
||||
## Token + speed rules
|
||||
|
||||
- **Batch `get_component`** - ONE call with the whole `componentsUsed` array, never N calls. Skip it entirely when `componentDigests` already answers the question.
|
||||
- **Read source by installing** - the MCP serves no source. To read or analyze an item's real code, install it with the shadcn CLI and open the local files. Learn an API from the inline `api` / `componentDigests`, never by reading raw source.
|
||||
- **Infer `search` hints yourself** (`type`, `component`, `category`, `features`, `free`) - hints shrink the result set and the tokens. Keep `limit` low; one right result beats ten.
|
||||
- Run independent calls (and the shadcn install) concurrently in one turn - serial tool calls are the main source of slowness.
|
||||
- Don't repeat a search for the same intent; don't call `list_*` to "see everything" - `search` is the entry point, `list_*` is only for browsing a taxonomy the user explicitly wants to explore.
|
||||
- Prefer `get_component`'s inline `api` over `docsUrl` / `/llms.txt`. Fetch a web page only as a last resort.
|
||||
|
||||
## Result shapes (so you don't re-fetch)
|
||||
|
||||
- `score` is 0-100 RELATIVE to the top hit (the top is ~100 by construction), not absolute - compare results to each other.
|
||||
- `termCoverage` (0-1) is the share of the query the item matched - low means a weak match even if the score looks high; rephrase or widen the search.
|
||||
- Each result carries `whyMatch`, `install`, docs/preview URLs, and a `free` flag; premium items carry `requiredPlan` (`"pro"` for blocks, `"ultimate"` for icons).
|
||||
- `componentDigests` is a top-level map: a compact API contract per referenced component - often enough to wire an item without a `get_component` call.
|
||||
- Icon results and `get_icon` include `animated: true` and `installAnimated` when a hover-animated Motion variant exists (animated: `@reui/icons/animated/<style>/<name>`; static: `@reui/icons/default/<style>/<name>`).
|
||||
|
||||
## Error playbook
|
||||
|
||||
- **401** - the MCP requires a signed-in ReUI account. The client prompts "Sign in with ReUI" (OAuth) on first use; a free account is created if needed. For headless/CI, pass a personal token (`reui_pat_...`, created at https://reui.io/account/mcp?ref=skill) as `Authorization: Bearer`.
|
||||
- **403 / locked result** - a valid account but the plan does not cover the item: premium blocks need Pro, Motion Icons need Ultimate. Point to https://reui.io/pricing?ref=skill (upgrade). Free accounts still get all components + examples.
|
||||
- **429** - rate limited (120 requests/min per IP); back off, honor `Retry-After`.
|
||||
- **not found** (`found: false`) - use the returned `suggestions`, or `search`; check `whats_new` if you suspect a stale name. Never run a fabricated install command.
|
||||
|
||||
## Fallbacks
|
||||
|
||||
- No ReUI MCP: `npx shadcn@latest search @reui -q "..."` then `add` (generic, no scoring / inline API).
|
||||
- The shadcn project's own MCP also works over the `@reui` registry: https://ui.shadcn.com/docs/mcp.
|
||||
|
||||
Per-agent MCP setup: https://reui.io/docs/mcp?ref=skill
|
||||
@@ -1 +0,0 @@
|
||||
{"version":"0.0.1","configurations":[{"name":"MikrotikManager","runtimeExecutable":"npm","runtimeArgs":["run","dev"],"port":3000,"autoPort":true}]}
|
||||
@@ -1,70 +0,0 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(npm install *)",
|
||||
"mcp__Claude_Preview__preview_start",
|
||||
"Bash(npx tsc *)",
|
||||
"Bash(npm run *)",
|
||||
"Bash(curl -s -o /dev/null -w \"%{http_code}\" http://localhost:3000/dashboard)",
|
||||
"Bash(curl -s -o /dev/null -w '%{http_code}' http://localhost:3000__TRACKED_VAR__)",
|
||||
"Bash(curl -s -o /dev/null -w '%{http_code}' http://localhost:3001__TRACKED_VAR__)",
|
||||
"PowerShell(netstat -ano | Select-String \":300\" | Where-Object { $_ -match \"LISTENING\" })",
|
||||
"Bash(curl -s -o /dev/null -w '%{http_code}' http://localhost:__TRACKED_VAR__/dashboard)",
|
||||
"Bash(curl -s -o /dev/null -w '%{http_code}' http://localhost:3333__TRACKED_VAR__)",
|
||||
"Bash(curl -s -o /dev/null -w '%{http_code}' http://localhost:59959__TRACKED_VAR__)",
|
||||
"WebFetch(domain:git.shx.one)",
|
||||
"Bash(curl -s \"https://git.shx.one/denozord/router-lists-ui/raw/branch/v5/frontend/src/RouteOptimizerPage.jsx\")",
|
||||
"Bash(curl -s \"https://git.shx.one/denozord/router-lists-ui/raw/branch/v5/frontend/src/OspfToolsPage.jsx\")",
|
||||
"Bash(node -e ' *)",
|
||||
"Bash(powershell -Command \"Get-Item 'C:\\\\Users\\\\shats\\\\.claude\\\\projects\\\\C--Users-shats-Dev-MikrotikManager-3\\\\b1dbd554-4665-40c0-bb5b-19d63bb494a0.jsonl'\")",
|
||||
"Bash(node -e \"const { createRequire } = require\\('module'\\); const r = createRequire\\(__filename\\); const lucide = r\\('lucide-react'\\); ['SlackIcon','WebhookIcon'].forEach\\(n => console.log\\(n, !!lucide[n]\\)\\)\")",
|
||||
"mcp__Claude_in_Chrome__tabs_context_mcp",
|
||||
"Bash(npx eslint *)",
|
||||
"Bash(grep -E \"^C:\\\\\\\\\\\\\\\\| [0-9]+:[0-9]+ error\")",
|
||||
"Bash(grep -E \"\\(\\\\\\\\\\\\\\\\.*\\\\.tsx$\\)|\\(error\\)\")",
|
||||
"Bash(python -c \"import sys,json; data=json.load\\(sys.stdin\\); [print\\(m['ruleId'], m['line'], m['message'][:60]\\) for f in data for m in f['messages'] if m['severity']==2]\")",
|
||||
"Bash(python -c \"import sys,json; data=json.load\\(sys.stdin\\); [print\\(m['ruleId'], m['line'], m['message'][:80]\\) for f in data for m in f['messages'] if m['severity']==2]\")",
|
||||
"Bash(npx next *)",
|
||||
"Bash(dir \"C:\\\\Users\\\\shats\\\\Dev\\\\MikrotikManager-3\\\\app\\\\\\(main\\)\")",
|
||||
"Bash(Get-ChildItem \"C:\\\\Users\\\\shats\\\\Dev\\\\MikrotikManager-3\\\\app\\\\\\(main\\)\" -Directory)",
|
||||
"Bash(Select-Object Name)",
|
||||
"Bash(Sort-Object Name)",
|
||||
"Bash(awk 'NR>=508 && NR<=730' \"app/\\(main\\)/servers/page.tsx\")",
|
||||
"Bash(grep -n \"Fragment\\\\|<>\\\\s*$\" \"app/\\(main\\)/filters/page.tsx\")",
|
||||
"Bash(grep -n \"\\\\.map\\\\|Fragment\\\\|<>\\\\s*$\" \"app/\\(main\\)/ospf/page.tsx\")",
|
||||
"Bash(grep -v \"//.*console\\\\|ErrorRecord\\\\|console\\\\.error.*err\\\\|any>\\\\|: any\\\\|as any\\\\|any\\\\[\\\\]\\\\|Record<.*any\\\\|Promise<any\")",
|
||||
"Bash(curl -s http://localhost:8000/api/servers)",
|
||||
"Bash(curl -s -X POST http://localhost:8000/api/servers/1/poll)",
|
||||
"Bash(curl -s http://localhost:8000/api/servers/1)",
|
||||
"Bash(curl -s http://localhost:8000/api/servers/1/snapshots)",
|
||||
"Bash(curl -s -X DELETE http://localhost:8000/api/servers/1 -w \"\\\\nHTTP %{http_code}\")",
|
||||
"Bash(curl -s http://localhost:8000/api/servers/999)",
|
||||
"Bash(curl -s -X POST http://localhost:8000/api/servers -H \"Content-Type: application/json\" -d \"{}\")",
|
||||
"Bash(curl -s -X POST http://localhost:8000/api/servers/test-connection -H 'Content-Type: application/json' -d '{\"host\":\"192.168.0.254\",\"port\":80,\"useSsl\":false,\"verifySsl\":false,\"apiPath\":\"/rest\",\"username\":\"admin\",\"password\":\"\"}')",
|
||||
"Bash(curl -s -X POST http://localhost:8000/api/servers -H 'Content-Type: application/json' -d '{\"host\":\"192.168.0.254\",\"port\":80,\"useSsl\":false,\"verifySsl\":false,\"username\":\"admin\",\"password\":\"test123\",\"name\":\"RB5009 Home\",\"type\":\"home-router\",\"site\":\"MSK\",\"country\":\"RU\",\"asn\":\"\",\"comment\":\"Тестовый роутер\",\"enabled\":true}')",
|
||||
"Bash(python3 -m json.tool)",
|
||||
"Bash(curl -s -X POST http://localhost:8000/api/servers -H 'Content-Type: application/json' -d '{\"host\":\"192.168.0.254\",\"port\":80,\"useSsl\":false,\"verifySsl\":false,\"username\":\"admin\",\"password\":\"test123\",\"name\":\"RB5009 Home\",\"type\":\"home-router\",\"site\":\"MSK\",\"country\":\"RU\"}')",
|
||||
"Bash(node -e \"const d=require\\('fs'\\).readFileSync\\('/dev/stdin','utf8'\\); const a=JSON.parse\\(d\\); a.forEach\\(s=>console.log\\(s.id, s.host, s.name\\)\\)\")",
|
||||
"Bash(curl -s http://localhost:8000/api/bgp/sessions)",
|
||||
"Bash(curl -s \"http://localhost:8000/api/bgp/sessions/raw/3\")",
|
||||
"Bash(node -e \"0\")",
|
||||
"Bash(curl -su \"admin:Ifwrbqifwrbq1995\" \"http://vpsville.msk.rt.shx.su/rest/routing/ospf/neighbor\")",
|
||||
"Bash(curl -su \"admin:Ifwrbqifwrbq1995\" \"http://vpsville.msk.rt.shx.su/rest/routing/ospf/instance\")",
|
||||
"Bash(curl -su \"admin:Ifwrbqifwrbq1995\" \"http://vpsville.msk.rt.shx.su/rest/routing/ospf/area\")",
|
||||
"Bash(curl -su \"admin:Ifwrbqifwrbq1995\" \"http://vpsville.msk.rt.shx.su/rest/routing/ospf/interface-template\")",
|
||||
"Bash(curl -su \"admin:Ifwrbqifwrbq1995\" \"http://vpsville.msk.rt.shx.su/rest/ip/route?.type=ospf\")",
|
||||
"Bash(curl -su \"admin:Ifwrbqifwrbq1995\" \"http://vpsville.msk.rt.shx.su/rest/ip/route\")",
|
||||
"Bash(curl -su \"admin:Ifwrbqifwrbq1995\" \"http://192.168.0.254/rest/routing/ospf/neighbor\")",
|
||||
"Bash(curl -su \"admin:Ifwrbqifwrbq1995\" \"http://192.168.0.254/rest/routing/ospf/instance\")",
|
||||
"Bash(curl -s http://localhost:8000/api/ospf/all)",
|
||||
"Bash(curl -su \"admin:Ifwrbqifwrbq1995\" \"http://192.168.0.254/rest/routing/bfd/session\")",
|
||||
"Bash(curl -su \"admin:Ifwrbqifwrbq1995\" \"http://vpsville.msk.rt.shx.su/rest/routing/bfd/session\")",
|
||||
"Bash(node -e \"const j=JSON.parse\\(require\\('fs'\\).readFileSync\\(0,'utf8'\\)\\); console.log\\('bfd:', JSON.stringify\\(j.bfdSessions, null, 2\\)\\)\")",
|
||||
"Bash(xargs grep *)",
|
||||
"Bash(npx shadcn@latest add popover --yes)"
|
||||
]
|
||||
},
|
||||
"env": {
|
||||
"REUI_LICENSE_KEY": "REUI-EAF4-EA40-6C5C-5D86"
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
---
|
||||
name: reui
|
||||
description: Use the ReUI registry from your AI agent - find, install, and correctly use ReUI components (the 22 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 `fe6742e29c`.** 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 22 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
|
||||
|
||||
The skill is free and this MCP is free to use; it just needs a ReUI account. On first use your agent opens a browser "Sign in with ReUI" prompt (a free account is created if you don't have one). Free covers components and examples with a daily request allowance; a Pro or Ultimate license unlocks premium blocks and Motion Icons and removes the limit (see [rules/registry.md](./rules/registry.md)). The same account and skill work in every agent and service the MCP connects to - this skill is agent-agnostic.
|
||||
|
||||
Skill + MCP are a team: this skill is the workflow (how to find, install, read the API, and adapt by reuse); the MCP is the live data and the hands (search, get_component, install commands). Your job: find the right item, install it with the shadcn CLI, read its real API, and **adapt by reuse** - wire real data and theme it; do not hand-roll or restyle what ReUI already provides. This skill **layers on the shadcn skill**: follow that for generic rules (spacing, `cn()`, semantic colors, forms); follow this for everything ReUI-specific.
|
||||
|
||||
## The core loop (MCP-native)
|
||||
|
||||
1. **Find** - call the ReUI MCP `search` tool with the user's intent. It returns a ranked, scored list across components/examples/blocks/icons, each with an `install` command, `previewUrl`, `docsUrl`, and `componentsUsed`. Pass hints (`type`, `component`, `category`, `features`, `free`) when you can infer them.
|
||||
2. **Install** - run the returned command non-interactively (`npx shadcn@latest add @reui/<name> --yes`). The CLI resolves deps, aliases, and the base/style from `components.json`. See [cli.md](./rules/cli.md).
|
||||
3. **Read the API (on your base)** - first note your base from `components.json` -> `style` (`base-nova` -> Base UI, `radix-nova` -> Radix UI). For each component an item uses, call `get_component(name)` and read its **inline `api`** (no web fetch); then `get_examples(name)` to install a worked example and copy its composition - the installed files are already in your base. Whenever you work with a component's API, also **share its `docsUrl`** (the primitive's API documentation page) with the user so they have the full reference. See [components.md](./rules/components.md).
|
||||
4. **Adapt (reuse-first)** - swap demo data for real data, fix icon imports, align tokens. Do not redesign. See [adapting.md](./rules/adapting.md).
|
||||
|
||||
**Always show the preview.** Every item a tool returns carries a `previewUrl` (a live preview page). Whenever you list, recommend, or present ReUI items to the user - blocks, components, examples, or icons, whether from `search`, `search_icons`, `list_components`, `compose_page`, or any getter - include each item's `previewUrl` so they can SEE it before installing. Blocks and examples open an individual live preview; icons and components link to their live category/component page. Never present an item without its preview link.
|
||||
|
||||
If the ReUI MCP is not configured, fall back to `npx shadcn@latest search @reui -q "..."` then `add` - but the MCP gives scored matches + inline APIs; prefer it.
|
||||
|
||||
## Commands
|
||||
|
||||
Run ReUI as explicit slash commands (via the ReUI MCP) **or** just ask in plain language - both run the same workflow.
|
||||
|
||||
| Command | Invoke | Does |
|
||||
| ----------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
|
||||
| **build** | `/mcp__reui__build <what>` | Compose a page/section/feature from ReUI: plan → install → read API → adapt → craft → audit. |
|
||||
| **add** | `/mcp__reui__add <item>` | Find & install one component/example/block/icon and wire it in. |
|
||||
| **fix** | `/mcp__reui__fix [target]` | Diagnose & fix ReUI usage: wrong/undocumented props, base/radix mismatch, missing states, a11y/scroll. |
|
||||
| **improve** | `/mcp__reui__improve [target]` | Refine + extend existing ReUI UI to a production-exceptional bar (hierarchy, density, states, responsive, motion). |
|
||||
|
||||
Invocation differs slightly per agent (`/mcp__reui__build` in Claude Code/Cursor/Windsurf, `/mcp.reui.build` in VS Code). No command surface? Just describe what you want - this skill drives the identical loop.
|
||||
|
||||
## When to reach for ReUI vs plain shadcn
|
||||
|
||||
| Need | Reach for |
|
||||
| -------------------------------------------------------------------- | ------------------------------------------------------------------------- |
|
||||
| A full page or section (dashboard, billing, auth, pricing, settings) | `compose_page` first (plans sections + best blocks), then ReUI **blocks** |
|
||||
| A data table with sorting/filtering/pagination/virtualization | the **data-grid** component (never hand-roll a `<table>`) |
|
||||
| A drag-and-drop board | the **kanban** component |
|
||||
| Advanced column filtering, date range, tree, stepper, ... | the matching ReUI **component** |
|
||||
| A single generic control already in shadcn (Button, Dialog, Select) | plain **shadcn** |
|
||||
|
||||
## Detailed references
|
||||
|
||||
- [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 22 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)
|
||||
- [rules/styling.md](./rules/styling.md) - ReUI extended tokens, theme adaptation, density
|
||||
- [rules/icons.md](./rules/icons.md) - portable icons, swapping imports, Motion Icons (static + animated)
|
||||
- [tools.md](./tools.md) - the ReUI MCP: golden path, the 19 tools, token rules, result shapes, errors
|
||||
@@ -1,43 +0,0 @@
|
||||
# Adapting installed ReUI code (reuse-first, no AI slop)
|
||||
|
||||
ReUI items ship production-quality. Your job is to **adapt by reuse** - wire real data and fit the app - not to redesign or hand-roll. The output should look like ReUI built it for this product.
|
||||
|
||||
## Preserve the design - don't over-customize
|
||||
|
||||
The design IS the product. A ReUI block/component encodes senior-designer decisions: spacing, hierarchy, density, color treatment, and component choices. The fastest way to turn a premium block back into generic AI slop is to "improve" its look - so don't.
|
||||
|
||||
- Change **data, copy, and props**; keep the **structure and styling** it ships with. Make the **smallest** change that wires the real data. If your diff touches `className` / JSX structure more than data / props, you are over-customizing - stop and reuse.
|
||||
- Don't swap ReUI components for hand-rolled ones, restructure the layout, re-skin spacing / radius / colors, or add decorative chrome. Let the installed components carry the default spacing, radius, sizing, icon rhythm, density, and state styling; add custom Tailwind only when a component genuinely lacks a contract you need.
|
||||
- Want a different look? `search` for a block whose design already fits and reuse that - don't restyle this one into a new design.
|
||||
|
||||
## Reuse the parts: examples and the block's own elements
|
||||
|
||||
- **Examples are building parts.** A free `c-*` example is a correct, single-pattern composition you can reuse. Before composing from scratch, `get_examples(component)`, install the closest one, and reuse its wiring - assemble UI from examples instead of hand-rolling what an example already shows.
|
||||
- **Reuse a block's own elements.** Need more rows, cards, items, or sections than ship by default? Repeat the block's **existing** element by mapping real data through the same markup - never invent parallel markup that drifts from its design. Need a variant (empty / loading / expanded)? Derive it from an element the block already has.
|
||||
|
||||
## Don't invent (read, don't guess)
|
||||
|
||||
- Never write a prop, variant value, import path, or `@reui/...` name you didn't read in a component's inline `api`, an installed example, or a `search` result. If you didn't see it, treat it as nonexistent - call `get_component` / `get_examples` / `search` first, or run the MCP `validate_usage` tool to check planned names + props against the docs before writing code.
|
||||
- If a getter returns `found: false` or `search` returns nothing, say so and fall back (plain shadcn, or ask) - never fabricate an install command or an API.
|
||||
|
||||
## What to change vs leave alone
|
||||
|
||||
- **Change:** the item's own data, copy, props, and layout to fit the app.
|
||||
- **Leave alone:** installed component files, hooks, and the shared theme - do not edit vendored ReUI internals; change behavior through props and the documented API.
|
||||
- Blocks are **portable React** - no `next/link`, `next/image`, or other framework-runtime imports inside them. Keep them portable.
|
||||
|
||||
## Demo data -> real data
|
||||
|
||||
- Replace every placeholder with the user's real data. Model it as **typed data structures** and **map over arrays** - never duplicate JSX per row/card. Keep small block-specific formatters next to the data.
|
||||
- Wire the real source (columns, fields, fetch). For `data-grid`, implement the server fetch contract if the user needs server-side data.
|
||||
- **Type from the component API, derive during render.** Type domain state through the component's own types - e.g. map status to `BadgeProps["variant"]` via a typed `Record<Status, …>` - instead of stringly-typed values. Compute view state during render; don't mirror derived data into `useState`/`useEffect`.
|
||||
- **Adapt on the right base.** Use the API for the project's base (Base UI vs Radix - see [components.md](./components.md)); the installed files are already base-correct, so reuse their shape rather than translating from memory.
|
||||
|
||||
## Believable content (no AI tells)
|
||||
|
||||
- Use realistic labels, counts, timestamps, and statuses that map to a real workflow.
|
||||
- No decorative buttons, fake tabs, meaningless toggles, equal-weight card walls, empty gradients, ornamental icons, or generic SaaS filler. Every element should do something.
|
||||
|
||||
## Operational surfaces (settings / profile / admin)
|
||||
|
||||
Pick ONE archetype and keep the family consistent: a vertical rail (3-6 sections), horizontal tabs (5-8), or a frame/stack. Prefer `frame` for tool-like surfaces, a card for profile-like ones. Don't mix archetypes in one surface.
|
||||
@@ -1,60 +0,0 @@
|
||||
# CLI: registry setup, license, non-interactive install
|
||||
|
||||
## Registry setup (one-time, per project)
|
||||
|
||||
Free items (the 22 components and all `c-*` examples) need only the plain string registry in `components.json`:
|
||||
|
||||
```json
|
||||
{ "registries": { "@reui": "https://reui.io/r/{style}/{name}.json" } }
|
||||
```
|
||||
|
||||
Premium items (blocks; Motion Icons and templates) require a ReUI license at install:
|
||||
|
||||
1. Add the key to `.env.local`:
|
||||
|
||||
```bash
|
||||
REUI_LICENSE_KEY=your-license-key
|
||||
```
|
||||
|
||||
2. Switch `components.json` to the authenticated object form:
|
||||
|
||||
```json
|
||||
{
|
||||
"registries": {
|
||||
"@reui": {
|
||||
"url": "https://reui.io/r/{style}/{name}.json",
|
||||
"headers": { "Authorization": "Bearer ${REUI_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?ref=skill
|
||||
|
||||
## Installing
|
||||
|
||||
Use the project's package runner (check `packageManager`):
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add @reui/<name> --yes # npm
|
||||
pnpm dlx shadcn@latest add @reui/<name> --yes # pnpm
|
||||
bunx --bun shadcn@latest add @reui/<name> --yes # bun
|
||||
```
|
||||
|
||||
`--yes` skips confirmation prompts. The CLI auto-detects the package manager from the lockfile (there is no `--package-manager` flag). It also resolves the correct base+style variant from `components.json`, so do not pass a style.
|
||||
|
||||
## Handling prompts and conflicts
|
||||
|
||||
- **Always pass `--yes`** so the CLI does not block on confirmation prompts.
|
||||
- **Do NOT pass `--overwrite` by default.** If the CLI reports an existing file, read the output and resolve deliberately: install under a different name, adjust the path, or ask the user. Only use `--overwrite` when the user explicitly wants to replace a file.
|
||||
- **Preview first when touching an existing project**: `npx shadcn@latest add @reui/<name> --dry-run` shows what would change; `--diff <file>` shows a specific file's diff. Use these before overwriting.
|
||||
- Run from the **project root** so `components.json` and `.env.local` are found.
|
||||
|
||||
## Free vs premium boundary
|
||||
|
||||
- Public, no key: `c-*` examples and the 22 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?ref=skill (their key) or https://reui.io/pricing?ref=skill (upgrade).
|
||||
@@ -1,428 +0,0 @@
|
||||
# ReUI components
|
||||
|
||||
The 22 ReUI building blocks: `alert`, `autocomplete`, `badge`, `cascader`, `code-block`, `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 v9. It is NOT a styled `<table>` and does NOT take `data`/`columns` props directly. The contract:
|
||||
|
||||
- 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 = useTable({
|
||||
features: dataGridFeatures,
|
||||
data,
|
||||
columns,
|
||||
})
|
||||
|
||||
<DataGrid table={table} recordCount={data.length}>
|
||||
<DataGridTable />
|
||||
</DataGrid>
|
||||
```
|
||||
|
||||
Common mistakes:
|
||||
|
||||
- **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 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
|
||||
|
||||
**Required:** `value` (`Record<string, T[]>`), `onValueChange`, `getItemValue`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Kanban value={cols} onValueChange={setCols} getItemValue={(i) => i.id}>
|
||||
<KanbanBoard>
|
||||
{Object.entries(cols).map(([id, items]) => (
|
||||
<KanbanColumn key={id} value={id}>
|
||||
<KanbanColumnHandle><h3>{id}</h3></KanbanColumnHandle>
|
||||
<KanbanColumnContent value={id}>
|
||||
{items.map((i) => (
|
||||
<KanbanItem key={i.id} value={i.id}>
|
||||
<KanbanItemHandle>{i.title}</KanbanItemHandle>
|
||||
</KanbanItem>
|
||||
))}
|
||||
</KanbanColumnContent>
|
||||
</KanbanColumn>
|
||||
))}
|
||||
</KanbanBoard>
|
||||
<KanbanOverlay><div className="bg-muted size-full rounded-md" /></KanbanOverlay>
|
||||
</Kanban>
|
||||
```
|
||||
|
||||
**Gotcha:** state is `Record<columnId, T[]>`. Each `KanbanColumnContent value` must match its parent `KanbanColumn value`. Omit `KanbanOverlay` and the drag preview silently breaks.
|
||||
|
||||
## sortable
|
||||
|
||||
**Required:** `value` (`T[]`), `onValueChange`, `getItemValue`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Sortable value={items} onValueChange={setItems} getItemValue={(i) => i.id}>
|
||||
{items.map((i) => (
|
||||
<SortableItem key={i.id} value={i.id}>
|
||||
<SortableItemHandle><GripVertical /></SortableItemHandle>
|
||||
{i.label}
|
||||
</SortableItem>
|
||||
))}
|
||||
</Sortable>
|
||||
```
|
||||
|
||||
**Gotcha:** a flat 1D reorder list (not columns - that is `kanban`). `getItemValue` must return a stable, unique string. Pass `layout="grid"` or `layout="nested"` for non-list layouts.
|
||||
|
||||
## filters
|
||||
|
||||
**Required:** `fields` (`FilterField[]`). The value is ONE `FilterQuery` tree - `query` + `onQueryChange`, or uncontrolled `defaultQuery`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
const fields: FilterField[] = [
|
||||
{ id: "title", label: "Title", type: "text" },
|
||||
{
|
||||
id: "status",
|
||||
label: "Status",
|
||||
type: "select",
|
||||
options: [
|
||||
{ value: "active", label: "Active" },
|
||||
{ value: "archived", label: "Archived" },
|
||||
],
|
||||
},
|
||||
]
|
||||
const [query, setQuery] = useState<FilterQuery>(() => createFilterQuery())
|
||||
|
||||
<Filters fields={fields} query={query} onQueryChange={setQuery} />
|
||||
```
|
||||
|
||||
**Gotcha:** the state is a TREE, not a list of chips. `FilterQuery` is a group of rules joined by `and`/`or` and a group may hold another group, so `(A and B) or C` is expressible; a rule is `{ id, type: "rule", path: ["status"], operator, value }` and `path` is the whole nested attribute path, root first. The pre-rewrite API is GONE: there is no `filters`/`onChange` prop, no `FilterFieldConfig` (fields are `FilterField`, nested through their own `fields`, keyed `id` not `key`), and no `createFilter()` - it minted ids inside a pure function and broke hydration, so ids now come from `createFilterIdFactory(seed)` seeded off `useId`, and `createFilterQuery()` / `createFilterRule()` take one. Read the query back with `flattenFilterConditions` (`{ path, field, operator, values, negated }` per rule, incomplete rules skipped) and walk the tree yourself when the parentheses carry meaning - the primitive compiles nothing, no SQL, no query string.
|
||||
|
||||
`variant` picks the chrome over that one query: `"basic"`, the default, is the flat chip row for a toolbar over a table; `"advanced"` is the condition builder, hung off a trigger or rendered in place with `advancedMode="inline"`. Both read and write the same tree, so a saved view built in one opens in the other. Other props worth knowing before you hand-roll them: `size` is two rungs, `"sm" | "default"`, resolved per style (there is no `lg`); `reorderable` turns on drag and Alt+Arrow row moves in the builder; `onBeforeQueryChange` is the ONE veto point for every write (return `false` to refuse, it cannot rewrite); `editors` registers custom value editors a field selects by `editor` name; `labels` / `operatorLabels` own every rendered string; `pathCollapse` + `maxPathSegments` shorten deep attribute paths; `renderChip` / `renderValue` / `renderEmpty` replace rendered parts. On a field, `loadOptions` supplies async options with paging and `resolveValues` renders a chip restored from a saved view whose option was never loaded. Pairs naturally with `data-grid`.
|
||||
|
||||
## cascader
|
||||
|
||||
**Required:** `items` (a tree of `{ value, label, children? }`), plus the panel parts inside `CascaderContent`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Cascader items={items} value={value} onValueChange={setValue}>
|
||||
<CascaderTrigger render={<Button variant="outline" />}>
|
||||
<CascaderValue placeholder="Select an attribute" />
|
||||
</CascaderTrigger>
|
||||
<CascaderContent className="w-80">
|
||||
<CascaderPanel>
|
||||
<CascaderNav>
|
||||
<CascaderBreadcrumb />
|
||||
<CascaderInput />
|
||||
</CascaderNav>
|
||||
<CascaderEmpty />
|
||||
<CascaderList maxHeight={288}>
|
||||
<CascaderItems />
|
||||
</CascaderList>
|
||||
<CascaderStatus />
|
||||
</CascaderPanel>
|
||||
</CascaderContent>
|
||||
</Cascader>
|
||||
```
|
||||
|
||||
**Gotcha:** pressing a branch NAVIGATES, it does not select - only leaves are selectable until you pass `selectable="any"` or a predicate, and once a branch is selectable its chevron becomes the only way to open it. `CascaderInput` must stay inside `CascaderContent` (Base UI refills the query from the selection when the input sits outside the popup). Always include `CascaderStatus`: it is the live region announcing level changes, which the visual breadcrumb does not provide to screen readers. Accepts a flat adjacency list via `getParent` as well as nested `children`. `searchScope="deep"` searches every level and annotates results with their path; `multiple` gives checkbox rows; `inline` + a bare `CascaderPanel` embeds it with no popover.
|
||||
|
||||
The shape above is `mode="drill"`, the default. `mode="tree"` keeps the same parts (drop `CascaderBreadcrumb`, pass `showBack={false}`, drive expansion with `expanded`/`onExpandedChange`); `mode="columns"` REPLACES `CascaderList` + `CascaderItems` with a single `CascaderColumns`, and has no breadcrumb. Other props worth knowing before you hand-roll them: `cascade` (multi-select only, parent/child selection with indeterminate branches - pair it with `selectable="any"`, since a leaf-only tree can never cascade), `indicator={false}` to drop the single-select check and its gutter (visual only, no-op with `multiple`), `virtualize`/`virtualizeThreshold` plus `CascaderVirtualItems` for long levels, and `getChildren` for async levels with cursor paging, retry on failure and optional `prefetch`. `CascaderFooter` pins commands below the list (`actions` is the quick path) and `CascaderSubmenu` opens one as a side-anchored flyout with the full menu keyboard model. To head a run of rows use `CascaderGroup` wrapping a `CascaderLabel` - a bare label inside a listbox names nothing and is dropped from the accessibility tree - and `CascaderSeparator` for the rule between runs. Every rendered string comes from `labels`, and the panel is RTL-correct under a `DirectionProvider` or `dir="rtl"`.
|
||||
|
||||
## date-selector
|
||||
|
||||
**Required:** none, but wire `onChange` to capture the value.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
const [value, setValue] = useState<DateSelectorValue | undefined>()
|
||||
|
||||
<DateSelector value={value} onChange={setValue} label="Due date" />
|
||||
```
|
||||
|
||||
**Gotcha:** the value is a structured `DateSelectorValue` (period / operator / start+end dates), NOT a `Date` - never pass a raw `Date`. Use `allowRange={false}` to lock single-date picking. Read `get_component("date-selector")` for the value shape.
|
||||
|
||||
## tree
|
||||
|
||||
**Required:** `tree` (a `@headless-tree/core` instance you construct)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Tree tree={tree}>
|
||||
{tree.getItems().map((item) => (
|
||||
<TreeItem key={item.getId()} item={item}>
|
||||
<TreeItemLabel />
|
||||
</TreeItem>
|
||||
))}
|
||||
</Tree>
|
||||
```
|
||||
|
||||
**Gotcha:** `Tree` is a styled shell - it takes a headless-tree instance via `tree`, NOT `data`/`items` props. Build the instance with `@headless-tree/react`. External API: https://headless-tree.lukasbach.com/
|
||||
|
||||
## stepper
|
||||
|
||||
**Required:** `StepperItem step` (number), `StepperContent value` (number)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Stepper defaultValue={1}>
|
||||
<StepperNav>
|
||||
<StepperItem step={1}>
|
||||
<StepperTrigger><StepperIndicator>1</StepperIndicator></StepperTrigger>
|
||||
<StepperSeparator />
|
||||
</StepperItem>
|
||||
<StepperItem step={2}>
|
||||
<StepperTrigger><StepperIndicator>2</StepperIndicator></StepperTrigger>
|
||||
</StepperItem>
|
||||
</StepperNav>
|
||||
<StepperPanel>
|
||||
<StepperContent value={1}>Step 1 content</StepperContent>
|
||||
<StepperContent value={2}>Step 2 content</StepperContent>
|
||||
</StepperPanel>
|
||||
</Stepper>
|
||||
```
|
||||
|
||||
**Gotcha:** steps are 1-indexed. Without `StepperPanel` + `StepperContent` you render the nav trail but no body. Put `StepperSeparator` in every `StepperItem` except the last.
|
||||
|
||||
## timeline
|
||||
|
||||
**Required:** `TimelineItem step` (number)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Timeline>
|
||||
<TimelineItem step={1}>
|
||||
<TimelineHeader>
|
||||
<TimelineDate>March 2024</TimelineDate>
|
||||
<TimelineTitle>Project initialized</TimelineTitle>
|
||||
</TimelineHeader>
|
||||
<TimelineIndicator />
|
||||
<TimelineSeparator />
|
||||
<TimelineContent>Repo and architecture set up.</TimelineContent>
|
||||
</TimelineItem>
|
||||
</Timeline>
|
||||
```
|
||||
|
||||
**Gotcha:** each item needs a unique `step`. `orientation` is `"vertical"` (default) or `"horizontal"`. This is a static event display, not interactive like `stepper`.
|
||||
|
||||
## autocomplete
|
||||
|
||||
**Required:** `items` (array; each item has at least `value`)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Autocomplete items={items}>
|
||||
<AutocompleteInput placeholder="Search..." />
|
||||
<AutocompleteContent>
|
||||
<AutocompleteEmpty>No results found.</AutocompleteEmpty>
|
||||
<AutocompleteList>
|
||||
{(item) => (
|
||||
<AutocompleteItem key={item.value} value={item}>{item.label}</AutocompleteItem>
|
||||
)}
|
||||
</AutocompleteList>
|
||||
</AutocompleteContent>
|
||||
</Autocomplete>
|
||||
```
|
||||
|
||||
**Gotcha:** `AutocompleteList` takes a render-prop `(item) => ReactNode`, NOT a mapped array of children. External API: https://base-ui.com/react/components/autocomplete
|
||||
|
||||
## phone-input
|
||||
|
||||
**Required:** none, but wire `onChange`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<PhoneInput placeholder="Enter phone number" defaultCountry="US" value={value} onChange={setValue} />
|
||||
```
|
||||
|
||||
**Gotcha:** `value`/`onChange` use an E.164 string (e.g. `"+14155551234"`), not a display-formatted string; `onChange` can fire `undefined`. `defaultCountry` is a 2-letter ISO code. Wraps `react-phone-number-input`.
|
||||
|
||||
## number-field
|
||||
|
||||
**Required:** wrap the controls in `NumberFieldGroup`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<NumberField defaultValue={0}>
|
||||
<NumberFieldScrubArea label="Quantity" />
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
```
|
||||
|
||||
**Gotcha:** import from `@/components/ui/number-field`. The accessible label goes on `NumberFieldScrubArea`, not `NumberField`. External API: https://base-ui.com/react/components/number-field
|
||||
|
||||
## rating
|
||||
|
||||
**Required:** `rating` (number)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Rating rating={4.5} showValue editable onRatingChange={setRating} />
|
||||
```
|
||||
|
||||
**Gotcha:** supports decimals (partial stars). Pass `editable` + `onRatingChange` for interactive input; omit both for a read-only display.
|
||||
|
||||
## scrollspy
|
||||
|
||||
**Required:** `targetRef` (the scroll container ref)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Scrollspy targetRef={containerRef}>
|
||||
<a href="#s1" data-scrollspy-anchor="s1">Section 1</a>
|
||||
<a href="#s2" data-scrollspy-anchor="s2">Section 2</a>
|
||||
</Scrollspy>
|
||||
<div ref={containerRef}>
|
||||
<div id="s1">...</div>
|
||||
<div id="s2">...</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
**Gotcha:** each link's `data-scrollspy-anchor` must match a section `id`. `targetRef` is the scrollable container (defaults to the window).
|
||||
|
||||
## frame
|
||||
|
||||
**Required:** `Frame` > `FramePanel`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Frame>
|
||||
<FramePanel>
|
||||
<FrameHeader>
|
||||
<FrameTitle>Title</FrameTitle>
|
||||
<FrameDescription>Description</FrameDescription>
|
||||
</FrameHeader>
|
||||
<div className="p-5">Content</div>
|
||||
<FrameFooter>Footer</FrameFooter>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
```
|
||||
|
||||
**Gotcha:** a structured card shell for tool-like surfaces. `stacked` connects multiple panels with shared borders; `dense` removes panel padding; radius via the `--frame-radius` CSS variable.
|
||||
|
||||
## icon-stack
|
||||
|
||||
**Required:** one child icon
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<IconStack aria-hidden="true">
|
||||
<InboxIcon className="size-4" />
|
||||
</IconStack>
|
||||
```
|
||||
|
||||
**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.
|
||||
|
||||
## code-block
|
||||
|
||||
**Required:** `code` + `language`, or pre-highlighted `lines`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<CodeBlock code={code} language="tsx" />
|
||||
|
||||
<CodeBlock code={code} language="tsx" showLineNumbers maxLines={20}>
|
||||
<CodeBlockHeader>
|
||||
<CodeBlockTitle>use-totals.ts</CodeBlockTitle>
|
||||
<CodeBlockLanguage />
|
||||
<CodeBlockCopyButton className="ml-auto" />
|
||||
</CodeBlockHeader>
|
||||
<CodeBlockExpandButton />
|
||||
</CodeBlock>
|
||||
```
|
||||
|
||||
**Gotcha:** the one-liner is already a complete block; every child (header, title, language label, copy button, wrap toggle, expand button, line actions) is optional chrome, at any depth. Shiki is the only npm dependency and loads lazily, one chunk per language, on first highlight; `lines` (from `highlightCode` in `code-block-highlight`, which is server-safe and has no `"use client"`) or `highlight={false}` loads nothing at all. `maxLines` caps the height AND marks the block collapsible, which is what makes `CodeBlockExpandButton` appear. Use `variant="ghost"` when the block sits inside a surface that already has a border.
|
||||
|
||||
## alert
|
||||
|
||||
**Required:** `Alert` > `AlertTitle`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Alert variant="success">
|
||||
<ShieldCheckIcon />
|
||||
<AlertTitle>Security update</AlertTitle>
|
||||
<AlertDescription>Enable two-factor authentication.</AlertDescription>
|
||||
<AlertAction><Button size="xs">Update</Button></AlertAction>
|
||||
</Alert>
|
||||
```
|
||||
|
||||
**Gotcha:** shadcn-compatible API. `variant`: `default | destructive | info | success | warning | invert`. The non-default variants use ReUI extended color tokens (`--success`/`--info`/`--warning`/`--invert`), which the install adds. Defer generic alert rules to the shadcn skill.
|
||||
|
||||
## badge
|
||||
|
||||
**Required:** none (text child).
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Badge variant="success-light" size="sm">Success</Badge>
|
||||
<Badge variant="outline" radius="full">Pill</Badge>
|
||||
```
|
||||
|
||||
**Gotcha:** shadcn-compatible. Rich `variant` set (solid, `-outline`, `-light` per color), `size` `xs..xl`, `radius` `default | full`. Like `alert`, the color variants rely on ReUI extended tokens. Prefer `Badge` variants over raw color classes for statuses.
|
||||
|
||||
## base vs radix - write for the project's base
|
||||
|
||||
ReUI ships every component in two builds: `base` (Base UI) and `radix` (Radix UI). The install command and name are identical, and the CLI installs the build matching the project. But you must write/adapt code against the **right base**, because their APIs differ.
|
||||
|
||||
**Detect the base first.** Read `components.json` -> `style` and take the segment before the first `-`:
|
||||
|
||||
- `"style": "base-nova"` -> **Base UI**
|
||||
- `"style": "radix-nova"` -> **Radix UI**
|
||||
|
||||
**Then use that base's API.** The deltas mirror shadcn's base-vs-radix split:
|
||||
|
||||
- Slot/composition: Base UI `render={<… />}` vs Radix `asChild`.
|
||||
- `Select`: Base UI takes `items`; Radix uses `<SelectItem>` children.
|
||||
- `ToggleGroup`: Base UI `multiple` boolean vs Radix `type="single" | "multiple"`.
|
||||
|
||||
The safest path is to **read the installed files and `c-*` examples** - they're already in your base, so reuse their wiring instead of guessing. When `get_component`'s inline `api` or an example shows the other base's shape, translate it to your base (or `validate_usage` to confirm). Defer the generic base/radix mechanics to the shadcn skill.
|
||||
@@ -1,45 +0,0 @@
|
||||
# Craft: make ReUI UI exceptional, not generic
|
||||
|
||||
ReUI items ship senior-designer quality. Your adaptation has to hold that bar, so the result reads like a real product surface a team would keep - not a wireframe an AI generated. Use these alongside the reuse rules in [adapting.md](./adapting.md).
|
||||
|
||||
## Have a point of view
|
||||
|
||||
Pick an emotional register before you compose - calm, operational, premium, editorial, dense, energetic - and let layout, spacing, surface treatment, and icon behavior all reinforce it. One or two memorable decisions and restraint everywhere else beats ten generic ones. UI with no point of view reads as generated.
|
||||
|
||||
## Brutally clear hierarchy
|
||||
|
||||
One focal point per card or panel: the dominant metric or task first, its label second, supporting detail third. The first thing the eye lands on should be the right thing; secondary text must read as secondary. Borders, separators, and surfaces do real work to create 2-3 information bands - don't flatten everything to equal weight.
|
||||
|
||||
## Spacing rhythm and deliberate density
|
||||
|
||||
Gaps are a signal, not a default. Keep them intentional and consistent within a family (`gap-1`/`gap-2` for tight operational rows, larger gaps for section breaks), and smaller within a group than between groups. Match the surrounding ReUI density; don't pad an operational surface like a marketing page, and don't drift density mid-section. The composition should still feel authored in grayscale.
|
||||
|
||||
## Cover the real states (the usual miss)
|
||||
|
||||
A surface isn't done at the happy path. Compose, and wire:
|
||||
|
||||
- **Empty** - a purposeful empty state (short message + the primary action), never a blank panel.
|
||||
- **Loading** - a **skeleton** that matches the real layout, not a centered spinner.
|
||||
- **Error** - an inline, recoverable error with a retry, announced via `role="status"`/`aria-live`.
|
||||
|
||||
Derive these from an element the block already has (don't invent parallel markup), or `get_examples` for a state-specific example.
|
||||
|
||||
## Responsive by default
|
||||
|
||||
Mobile-first, not mobile-afterthought. In constrained rows/cards/sidebars, put `min-w-0` on the shrinking container and `truncate` long single-line labels; protect the primary label's width and let secondary content compress. Reflow layouts (multi-column -> single column) rather than just shrinking them. Desktop and mobile should both look designed.
|
||||
|
||||
## Motion, subtly
|
||||
|
||||
Motion should clarify, not decorate. Use ReUI Motion Icons on primary actions for a subtle hover cue; keep transitions short (~200-300ms) with calm easing; prefer a skeleton pulse over a spinner. No bouncing, no gratuitous entrance animations on every element.
|
||||
|
||||
## Real, activated content
|
||||
|
||||
Use believable, typed data (realistic labels, counts, timestamps, statuses that map to a real workflow) - never lorem or abstract filler. Every visible control does something: no decorative buttons, fake tabs, meaningless toggles, or stats with no job. It must still hold with long names, empty values, and crowded data.
|
||||
|
||||
## Avoid the AI tells
|
||||
|
||||
These instantly read as generated - don't ship them: equal-weight card walls, empty gradients, repetitive padding everywhere, generic enterprise copy, ornamental icons, and number tiles that don't earn their place.
|
||||
|
||||
## The bar
|
||||
|
||||
Before you finish, ask: **would a product team keep this instead of replacing it? Does it still feel strong after swapping in real content?** If not, reuse the shipped ReUI design harder - don't restyle it into something new - then run the [quality.md](./quality.md) gates.
|
||||
@@ -1,39 +0,0 @@
|
||||
# Icons (ReUI delta over shadcn)
|
||||
|
||||
Follow the shadcn icon rules (use the project's configured `iconLibrary`, `data-icon` on icons inside `Button`, no sizing classes on icons inside components, pass icons as component objects not string keys). ReUI adds the following.
|
||||
|
||||
## Portable icons (library-agnostic)
|
||||
|
||||
ReUI components, examples, and blocks are authored to be icon-library-agnostic. When `iconLibrary` is set in `components.json`, the shadcn CLI installs each item's icons in **your** library automatically - you swap nothing. If an installed item's icons don't match your project (for example `iconLibrary` isn't set, so they came in from the item's demo library), change the **import source and component name** to your library, keeping the same icon-name semantics:
|
||||
|
||||
- `lucide` -> `lucide-react`
|
||||
- `tabler` -> `@tabler/icons-react`
|
||||
- `phosphor` -> `@phosphor-icons/react`
|
||||
- `remix` -> `@remixicon/react`
|
||||
- `hugeicons` -> `@hugeicons/react`
|
||||
|
||||
Don't assume `lucide-react`; read `iconLibrary` from `components.json`.
|
||||
|
||||
## Keep icons purposeful
|
||||
|
||||
Icons support the hierarchy, they don't replace it: keep them small, matched to the surrounding density, and decorative ones `aria-hidden="true"` (an icon-only control still needs an accessible label on the control). Don't add ornamental icons that do no job.
|
||||
|
||||
## Motion Icons (the `@reui/icons/...` set)
|
||||
|
||||
ReUI ships its own icon set in 4 styles (outline, solid, duotone, filled), each icon in two variants:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add @reui/icons/default/<style>/<name> --yes # static
|
||||
npx shadcn@latest add @reui/icons/animated/<style>/<name> --yes # hover-animated (motion/react)
|
||||
```
|
||||
|
||||
Finding them via the MCP is free; installing requires an Ultimate license (`REUI_LICENSE_KEY`, see [cli.md](./cli.md)). Reach for a Motion Icon on a primary action when a subtle hover cue helps; keep motion restrained.
|
||||
|
||||
Finding icons:
|
||||
|
||||
- Several icons (the common case): **`search_icons(concepts[])`** - up to 24 concepts in one call, the best icons per concept with install commands. Pass `animated: true` to get only icons with a hover-animated Motion variant.
|
||||
- One icon: `search` with `type: "icon"`.
|
||||
- Icon results and `get_icon` carry `animated: true` and `installAnimated` when an animated variant exists - use those install strings, do not construct paths by hand.
|
||||
- Every icon result carries a `previewUrl` (its live icon-category page) - **share it with the user** so they can SEE the icon before installing.
|
||||
|
||||
The `icon-stack` component composes multiple icons into a stacked display.
|
||||
@@ -1,22 +0,0 @@
|
||||
# Quality gates (security, accessibility, scroll)
|
||||
|
||||
These are the **done gate**, not a nice-to-have: before you call any ReUI work finished, call the MCP `get_audit_checklist` tool and pass every item below (plus the craft bar in [craft.md](./craft.md)). Then typecheck and lint.
|
||||
|
||||
## Security
|
||||
|
||||
- Never `dangerouslySetInnerHTML`. Render data as text/components.
|
||||
- External links (`target="_blank"`) must always pair `rel="noopener noreferrer"`.
|
||||
- No real PII, secrets, or tokens in demo or committed code. Remote media only from sources the project already allows.
|
||||
|
||||
## Accessibility
|
||||
|
||||
- Implicit list/card items that navigate get real anchors with a standard hover affordance.
|
||||
- Icon-only or numeric buttons need an `aria-label`; decorative icons get `aria-hidden`.
|
||||
- Every non-submit button is `type="button"`.
|
||||
- Keyboard + focus: everything interactive is reachable in a sensible Tab order with a visible focus ring; layers (dialogs/sheets/menus) trap focus and close on `Escape`. ReUI components ship standard keyboard behavior - read each component's inline `api` rather than re-implementing it.
|
||||
- Announce async UI: loading and error messages use `role="status"` / `aria-live` so they're not silent to screen readers.
|
||||
|
||||
## Scroll mechanics
|
||||
|
||||
- Make scroll regions with a parent-owned height: a `min-h-0` + flex chain down to the scroll container. Never guess a `max-h`.
|
||||
- The scroll container owns `overflow-auto`; ancestors stay `min-h-0` so the height resolves.
|
||||
@@ -1,35 +0,0 @@
|
||||
# ReUI registry structure
|
||||
|
||||
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 22 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).
|
||||
|
||||
## The @reui registry
|
||||
|
||||
Install everything through the shadcn CLI: `npx shadcn@latest add @reui/<name> --yes`. The CLI reads the `@reui` registry from the project's `components.json`. Free items need only the plain string form:
|
||||
|
||||
```json
|
||||
{ "registries": { "@reui": "https://reui.io/r/{style}/{name}.json" } }
|
||||
```
|
||||
|
||||
Premium installs need the authenticated form + `REUI_LICENSE_KEY` in `.env.local` - see [cli.md](./cli.md). The MCP `get_project_context` tool returns the right config.
|
||||
|
||||
## Know your base: base or radix
|
||||
|
||||
ReUI ships every item in two builds - `base` (Base UI) and `radix` (Radix UI) - with mirrored names. The CLI installs the build matching your project automatically, but **you must write code against the right base's API**. Detect it from `components.json` -> `style`: the segment before the first `-` is the base (`base-nova` -> Base UI, `radix-nova` -> Radix UI). The installed files and `c-*` examples are already in your base - read them and adapt on that base. See [components.md](./components.md) for the API deltas.
|
||||
|
||||
**So the MCP's own `docsUrl` and `previewUrl` match your base**, send your `style` to the MCP: add `?style=<your components.json style>` to the ReUI MCP server URL (or set an `X-Reui-Style` header) in your MCP client config - set once, applies to every call. The MCP then resolves docs/preview links to YOUR library (`/docs/components/radix/...`, `/preview/radix/...` for a radix project) instead of the default base; `get_project_context` echoes back the style it currently sees so you can confirm it. Install commands are unaffected (the CLI already installs the right variant). If you notice the MCP returning `base` links for a `radix` project, tell the user to add `?style=` to the server URL.
|
||||
|
||||
Blocks adapt to your active theme through semantic tokens and CSS variables - change the theme and every block follows.
|
||||
|
||||
## Free vs premium
|
||||
|
||||
- **Free, no key:** the 22 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
|
||||
|
||||
The canonical index of every component's API docs is **https://reui.io/llms.txt** (returned as `componentsApiUrl` in MCP results). Prefer the inline `api` from `get_component`; use the index/docs as the fallback.
|
||||
@@ -1,26 +0,0 @@
|
||||
# Styling (ReUI delta over shadcn)
|
||||
|
||||
Follow the shadcn skill for the generic rules (semantic colors not raw values, `gap-*` not `space-y-*`, `size-*`, `cn()`, no manual `dark:` overrides, no overlay `z-index`). This file is only the ReUI-specific additions.
|
||||
|
||||
## ReUI extended semantic tokens
|
||||
|
||||
ReUI adds semantic tokens beyond shadcn's base set. Use these instead of raw colors for status and emphasis:
|
||||
|
||||
- `--success` / `--success-foreground`
|
||||
- `--info` / `--info-foreground`
|
||||
- `--warning` / `--warning-foreground`
|
||||
- `--destructive-foreground` (paired with shadcn's `--destructive`)
|
||||
- `--invert` / `--invert-foreground` (inverted surfaces)
|
||||
|
||||
Use them as Tailwind utilities (`bg-success text-success-foreground`, `text-warning`, ...). They are defined in the project's global CSS and registered with Tailwind (`@theme inline` on v4). If a token is missing in the project, add it to the global CSS file (never a new file) following the same `name` / `name-foreground` convention, exactly as the shadcn customization rules describe.
|
||||
|
||||
**Incorrect:** `<span className="text-green-600">Active</span>`
|
||||
**Correct:** `<Badge variant="success">Active</Badge>` or `<span className="text-success">Active</span>`
|
||||
|
||||
## Blocks follow your theme
|
||||
|
||||
When you install a block it adapts to your active theme through the semantic tokens above and the project's CSS variables. Don't hardcode style-specific values into installed block code and don't fork it to "restyle" - change the theme via the CSS variables / a preset and every block follows. Want a different look? `search` for a block whose design already fits instead of re-skinning one.
|
||||
|
||||
## Density and typography rhythm
|
||||
|
||||
ReUI operational UI usually feels dense, not airy. Keep the gap between a title and its supporting description tight by default (`gap-0.5`, `space-y-1`, or `space-y-px`), and smaller than the gap between sections. Match the surrounding ReUI density when you add rows or fields; do not pad operational surfaces like a marketing page.
|
||||
@@ -1,54 +0,0 @@
|
||||
# Workflow: find -> install -> read API -> adapt
|
||||
|
||||
The core ReUI loop. The MCP tells you what to install and gives you the API; the shadcn CLI installs it; you turn the installed files into correct, themed, data-wired code by **reuse**, not redesign.
|
||||
|
||||
## 1. Find (ReUI MCP `search` / `compose_page`)
|
||||
|
||||
**Full multi-section page ask?** Call `compose_page(intent, sections?)` FIRST, before searching block-by-block. It returns ordered sections, each with the best block for the intent (top pick + alternates); sections listed in `unavailableSections` have no real inventory - compose those from components, do not force a bad block.
|
||||
|
||||
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 22 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`.
|
||||
|
||||
Example: "build a users management page with filters" -> `search({ query: "users management page with filters", type: "block", component: "data-grid", features: ["filters"] })`.
|
||||
|
||||
Each result has `install`, `previewUrl`, `docsUrl`, `componentsUsed`, `score`, `termCoverage`, and `whyMatch`. `score` is relative to the top hit (the top is ~100 by construction), not an absolute quality - compare results to each other, and show the user the top options if several score closely; do not silently guess. A low `termCoverage` means a weak match even with a high score - rephrase or widen.
|
||||
|
||||
**Always show the preview link.** Whenever you list or recommend items - from `search`, `search_icons`, `list_components`, `compose_page`, or a getter - include each item's `previewUrl` (a live preview page) so the user can SEE it before you install. Blocks and examples link to an individual live preview; icons and components to their live category/component page. This applies to every listing, not only a single pick.
|
||||
|
||||
## 2. Install (shadcn CLI)
|
||||
|
||||
Run the result's `install` command from the project root, non-interactively:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add @reui/<name> --yes
|
||||
```
|
||||
|
||||
The CLI reads `components.json`, installs the correct base+style variant, resolves `registryDependencies` (a block pulls in its components), installs npm deps, and rewrites aliases. Do not pass the base/style. See [cli.md](./cli.md).
|
||||
|
||||
## 3. Read the API (do not guess props)
|
||||
|
||||
Before writing code against any component an item uses:
|
||||
|
||||
1. The item's `componentDigests` already give a 1-line contract per component - often enough to wire it. For the full API, call **`get_component(names)`** with ALL of `componentsUsed` in ONE call (it accepts an array) and read each inline `api` - no web fetch. **Share the component's `docsUrl`** (its 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.
|
||||
2. Call **`get_examples(name)`** for the free `c-*` examples of that component; install one and **read the added files** to copy the exact composition. This is the fastest correct path - the example shows real wiring you adapt, not invent.
|
||||
3. About to write a prop you did not see in an `api` or installed file? Run **`validate_usage`** BEFORE writing the code - per-prop documented / notDocumented verdicts plus did-you-mean suggestions. notDocumented means read the API, not push on.
|
||||
|
||||
## 4. Adapt (reuse-first) - do not skip
|
||||
|
||||
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 `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)).
|
||||
5. **Validate before finalizing**: if your adaptation introduced components or props you did not read in an `api` or example, run `validate_usage` on them.
|
||||
6. **Hit the craft bar** - clear hierarchy, deliberate density, the empty / loading / error states, subtle motion, and mobile-first responsiveness (see [craft.md](./craft.md)). Generic-looking output means you under-reused the design, not that it needs restyling.
|
||||
7. **Pass the quality gates** (security, a11y, scroll) - call the MCP `get_audit_checklist` tool and clear every item (see [quality.md](./quality.md)).
|
||||
8. **Typecheck / lint**.
|
||||
|
||||
## If no single block fits
|
||||
|
||||
Compose from components (`compose_page` tells you which sections have no block inventory via `unavailableSections`). `search` the components you need, read each `get_component` API, install a worked `get_examples` example for each, and assemble by adapting those examples. A block in the same category is a useful reference - install it and read its files to see how ReUI composes those components, then adapt.
|
||||
@@ -1,58 +0,0 @@
|
||||
# ReUI MCP: full reference
|
||||
|
||||
The ReUI MCP (`https://mcp.reui.io`, Streamable HTTP) is free to use but needs a ReUI account: on first use the agent signs in with ReUI (a free account is created if the user has none), so every request is tied to an account. Free covers components and examples; a Pro or Ultimate license unlocks premium blocks and Motion Icons and removes the daily request limit. It does **discovery + guidance** (search, inline APIs, page planning, validation) and never serves source; the shadcn CLI does **installation**, and the license key lives there (the `@reui` entry in `components.json`, backed by `.env.local`). Goal: from the user's intent to correct, themed, data-wired ReUI code in the **fewest tokens and calls**, with **no guessing**.
|
||||
|
||||
## Golden path (token-optimal - follow this order)
|
||||
|
||||
Most tasks need 2-4 MCP calls and ZERO web fetches:
|
||||
|
||||
1. **`search(query, ...hints)`** -> pick the top 1-3 results. Each result already carries `install`, `previewUrl`, `docsUrl`, `componentsUsed`, `score`, `whyMatch`. The payload is complete - do not call another tool just to "confirm" a result.
|
||||
2. **`get_component([...componentsUsed])`** in ONE batched call (one name or an array of up to 20) -> read each inline `api`. This **replaces** fetching docs pages. Often skippable: search responses carry `componentDigests`, a compact API contract per referenced component.
|
||||
3. **`get_examples(component)`** -> install ONE returned `c-*` example, read the added files, copy the composition.
|
||||
4. **`get_install_command(item)`** only to validate a name you are unsure of (results already include `install`). Run the install with the shadcn CLI (`--yes`).
|
||||
5. **`get_audit_checklist()`** before declaring done.
|
||||
|
||||
If you already know the exact item name, skip `search`. Everything else is situational.
|
||||
|
||||
## The 5 task-specific tools (when to reach for each)
|
||||
|
||||
- **`compose_page`** - BEFORE building any full page (dashboard, settings, billing, landing). Pass the intent (and optionally the sections you want); it returns ordered sections, each with the best premium block for the intent (top pick + alternates). Sections with no real inventory are listed honestly in `unavailableSections` - compose those from components instead of forcing a bad block.
|
||||
- **`search_icons`** - whenever you need icons, especially several. Batch up to 24 concepts in one call; each concept returns its best icons with install commands. Pass `animated: true` to get only icons that have a hover-animated Motion variant.
|
||||
- **`validate_usage`** - BEFORE writing code with component names or props you have not read in an inline `api` or an installed example. It checks planned names + props against the indexed API docs and registry item names; returns did-you-mean suggestions and per-prop documented / notDocumented verdicts. Deterministic, no inference - a notDocumented prop means stop and read the API, not push on.
|
||||
- **`whats_new`** - when your registry knowledge might be stale (a name 404s, the user mentions an item you don't know). Returns items added/removed per build, newest first.
|
||||
- **`report_issue`** - when an installed item is actually broken (bad source, wrong dependency, broken preview). Goes straight to the ReUI team; rate-limited 5/hour. Not for usage questions.
|
||||
|
||||
## All 19 tools
|
||||
|
||||
`search`, `get_block`, `get_example`, `get_icon`, `list_block_groups`, `list_block_categories`, `list_example_categories`, `list_icon_categories`, `list_components`, `get_component`, `get_examples`, `search_icons`, `compose_page`, `validate_usage`, `whats_new`, `report_issue`, `get_install_command`, `get_project_context`, `get_audit_checklist`. The MCP serves the full parameter schemas; do not guess parameters beyond them.
|
||||
|
||||
## Token + speed rules
|
||||
|
||||
- **Batch `get_component`** - ONE call with the whole `componentsUsed` array, never N calls. Skip it entirely when `componentDigests` already answers the question.
|
||||
- **Read source by installing** - the MCP serves no source. To read or analyze an item's real code, install it with the shadcn CLI and open the local files. Learn an API from the inline `api` / `componentDigests`, never by reading raw source.
|
||||
- **Infer `search` hints yourself** (`type`, `component`, `category`, `features`, `free`) - hints shrink the result set and the tokens. Keep `limit` low; one right result beats ten.
|
||||
- Run independent calls (and the shadcn install) concurrently in one turn - serial tool calls are the main source of slowness.
|
||||
- Don't repeat a search for the same intent; don't call `list_*` to "see everything" - `search` is the entry point, `list_*` is only for browsing a taxonomy the user explicitly wants to explore.
|
||||
- Prefer `get_component`'s inline `api` over `docsUrl` / `/llms.txt`. Fetch a web page only as a last resort.
|
||||
|
||||
## Result shapes (so you don't re-fetch)
|
||||
|
||||
- `score` is 0-100 RELATIVE to the top hit (the top is ~100 by construction), not absolute - compare results to each other.
|
||||
- `termCoverage` (0-1) is the share of the query the item matched - low means a weak match even if the score looks high; rephrase or widen the search.
|
||||
- Each result carries `whyMatch`, `install`, docs/preview URLs, and a `free` flag; premium items carry `requiredPlan` (`"pro"` for blocks, `"ultimate"` for icons).
|
||||
- `componentDigests` is a top-level map: a compact API contract per referenced component - often enough to wire an item without a `get_component` call.
|
||||
- Icon results and `get_icon` include `animated: true` and `installAnimated` when a hover-animated Motion variant exists (animated: `@reui/icons/animated/<style>/<name>`; static: `@reui/icons/default/<style>/<name>`).
|
||||
|
||||
## Error playbook
|
||||
|
||||
- **401** - the MCP requires a signed-in ReUI account. The client prompts "Sign in with ReUI" (OAuth) on first use; a free account is created if needed. For headless/CI, pass a personal token (`reui_pat_...`, created at https://reui.io/account/mcp?ref=skill) as `Authorization: Bearer`.
|
||||
- **403 / locked result** - a valid account but the plan does not cover the item: premium blocks need Pro, Motion Icons need Ultimate. Point to https://reui.io/pricing?ref=skill (upgrade). Free accounts still get all components + examples.
|
||||
- **429** - rate limited (120 requests/min per IP); back off, honor `Retry-After`.
|
||||
- **not found** (`found: false`) - use the returned `suggestions`, or `search`; check `whats_new` if you suspect a stale name. Never run a fabricated install command.
|
||||
|
||||
## Fallbacks
|
||||
|
||||
- No ReUI MCP: `npx shadcn@latest search @reui -q "..."` then `add` (generic, no scoring / inline API).
|
||||
- The shadcn project's own MCP also works over the `@reui` registry: https://ui.shadcn.com/docs/mcp.
|
||||
|
||||
Per-agent MCP setup: https://reui.io/docs/mcp?ref=skill
|
||||
@@ -1,16 +0,0 @@
|
||||
# CodeGraph data files
|
||||
# These are local to each machine and should not be committed
|
||||
|
||||
# Database
|
||||
*.db
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
|
||||
# Cache
|
||||
cache/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
|
||||
# Hook markers
|
||||
.dirty
|
||||
@@ -1,3 +0,0 @@
|
||||
[mcp_servers.reui]
|
||||
url = "https://mcp.reui.io/api/mcp?style=base-nova"
|
||||
bearer_token_env_var = "REUI_LICENSE_KEY"
|
||||
@@ -1,21 +0,0 @@
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H6","location":"components/debug-runtime-probe.tsx","message":"cursor-ref-count-on-mount","data":{"pathname":"/bgp","count":80},"timestamp":1777738439411}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H5","location":"components/debug-runtime-probe.tsx","message":"route-change","data":{"pathname":"/bgp","search":""},"timestamp":1777738439411}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H7","location":"lib/data-source.tsx","message":"provider-mounted","data":{"mode":"mock","backendUrl":"http://localhost:8000","storedMode":"live","storedBackend":"http://localhost:8000"},"timestamp":1777738439416}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H7","location":"lib/data-source.tsx","message":"hydrated-from-storage","data":{"mode":"live","backendUrl":"http://localhost:8000"},"timestamp":1777738439428}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H7","location":"lib/data-source.tsx","message":"provider-mounted","data":{"mode":"live","backendUrl":"http://localhost:8000","storedMode":"live","storedBackend":"http://localhost:8000"},"timestamp":1777738439603}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H4","location":"lib/data-source.tsx","message":"check-backend-start","data":{"url":"http://localhost:8000"},"timestamp":1777738439605}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H4","location":"lib/data-source.tsx","message":"check-backend-result","data":{"url":"http://localhost:8000","ok":true,"status":200},"timestamp":1777738439621}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H7","location":"lib/data-source.tsx","message":"provider-mounted","data":{"mode":"mock","backendUrl":"http://localhost:8000","storedMode":"live","storedBackend":"http://localhost:8000"},"timestamp":1777738508126}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H7","location":"lib/data-source.tsx","message":"provider-mounted","data":{"mode":"mock","backendUrl":"http://localhost:8000","storedMode":"live","storedBackend":"http://localhost:8000"},"timestamp":1777738508134}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H7","location":"lib/data-source.tsx","message":"hydrated-from-storage","data":{"mode":"live","backendUrl":"http://localhost:8000"},"timestamp":1777738508145}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H7","location":"lib/data-source.tsx","message":"hydrated-from-storage","data":{"mode":"live","backendUrl":"http://localhost:8000"},"timestamp":1777738508145}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H7","location":"lib/data-source.tsx","message":"provider-mounted","data":{"mode":"live","backendUrl":"http://localhost:8000","storedMode":"live","storedBackend":"http://localhost:8000"},"timestamp":1777738508204}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H4","location":"lib/data-source.tsx","message":"check-backend-start","data":{"url":"http://localhost:8000"},"timestamp":1777738508205}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H4","location":"lib/data-source.tsx","message":"check-backend-result","data":{"url":"http://localhost:8000","ok":true,"status":200},"timestamp":1777738508228}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H7","location":"lib/data-source.tsx","message":"provider-mounted","data":{"mode":"mock","backendUrl":"http://localhost:8000","storedMode":"live","storedBackend":"http://localhost:8000"},"timestamp":1777738508553}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H7","location":"lib/data-source.tsx","message":"provider-mounted","data":{"mode":"mock","backendUrl":"http://localhost:8000","storedMode":"live","storedBackend":"http://localhost:8000"},"timestamp":1777738508560}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H7","location":"lib/data-source.tsx","message":"hydrated-from-storage","data":{"mode":"live","backendUrl":"http://localhost:8000"},"timestamp":1777738508571}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H7","location":"lib/data-source.tsx","message":"hydrated-from-storage","data":{"mode":"live","backendUrl":"http://localhost:8000"},"timestamp":1777738508572}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H7","location":"lib/data-source.tsx","message":"provider-mounted","data":{"mode":"live","backendUrl":"http://localhost:8000","storedMode":"live","storedBackend":"http://localhost:8000"},"timestamp":1777738508662}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H4","location":"lib/data-source.tsx","message":"check-backend-start","data":{"url":"http://localhost:8000"},"timestamp":1777738508663}
|
||||
{"sessionId":"00844d","runId":"initial","hypothesisId":"H4","location":"lib/data-source.tsx","message":"check-backend-result","data":{"url":"http://localhost:8000","ok":true,"status":200},"timestamp":1777738508676}
|
||||
@@ -1,34 +0,0 @@
|
||||
---
|
||||
description: "Generate Commit Message: русский subject, fix vs feat, Conventional Commits"
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Git commit message (Generate Commit Message)
|
||||
|
||||
При **Generate Commit Message**, автогенерации subject и предложении `git commit`:
|
||||
|
||||
## Обязательно
|
||||
|
||||
- Subject и body — **только на русском** (после `:` в conventional commit).
|
||||
- Локальный hook `.githooks/commit-msg` **отклоняет** коммиты без кириллицы в subject.
|
||||
- Префикс и scope — английский: `fix(ui):`, `chore(rules):`.
|
||||
|
||||
## Тип: сначала не `feat`
|
||||
|
||||
- **`fix`** — баг, регрессия, правка вёрстки/модалки, некорректное поведение, CI/CD, мелкий дефект.
|
||||
- **`chore` / `docs` / `ci` / `build`** — правила Cursor, README, workflow, зависимости, рефакторинг без новой UX-фичи.
|
||||
- **`feat`** — только **новая** пользовательская возможность (страница, API, сценарий), которой не было.
|
||||
|
||||
Если сомневаешься между `feat` и `fix` — выбирай **`fix`** или **`chore`**, не `feat`.
|
||||
|
||||
## Примеры
|
||||
|
||||
- `fix(ui): выровнять модалку сводки релиза`
|
||||
- `fix(ci): исправить сборку release manifest`
|
||||
- `chore(rules): усилить правила русских commit message`
|
||||
- `feat(releases): добавить страницу релизов`
|
||||
|
||||
## Запрещено
|
||||
|
||||
- `feat: update layout`, `fix: add modal`, `chore: update rules` — английский subject.
|
||||
- `feat` для правки UI, правил, документации и багфиксов.
|
||||
@@ -1,44 +0,0 @@
|
||||
---
|
||||
description: "Быстрый запуск локального frontend и backend"
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Локальный запуск проекта
|
||||
|
||||
## Требования
|
||||
|
||||
- **Node.js 22**, npm с workspaces.
|
||||
- Первый раз (или после смены зависимостей): `npm install` из корня репозитория.
|
||||
- Backend: скопировать `backend/.env.example` → `backend/.env` (по умолчанию `PORT=8000`, `CORS_ORIGIN=http://localhost:3000`).
|
||||
|
||||
## Запуск (два процесса)
|
||||
|
||||
Из корня репозитория поднять **два** long-running процесса в **отдельных** терминалах:
|
||||
|
||||
```powershell
|
||||
npm run dev
|
||||
npm --prefix backend run dev
|
||||
```
|
||||
|
||||
| Сервис | URL | Проверка |
|
||||
|--------|-----|----------|
|
||||
| Frontend (Next.js 16, Turbopack) | http://localhost:3000 | открыть в браузере |
|
||||
| Backend (Fastify) | http://localhost:8000 | `GET /health` |
|
||||
|
||||
Проверка backend в PowerShell:
|
||||
|
||||
```powershell
|
||||
Invoke-WebRequest -Uri http://localhost:8000/health -UseBasicParsing | Select-Object -ExpandProperty Content
|
||||
```
|
||||
|
||||
Ожидаемый ответ: `{"status":"ok",...}`.
|
||||
|
||||
## Поведение агента
|
||||
|
||||
Если пользователь просит «запусти проект», «запусти фронт и бэк» или похожее:
|
||||
|
||||
1. Сначала проверить уже запущенные терминалы — не дублировать процессы.
|
||||
2. Запустить обе команды выше как фоновые long-running процессы.
|
||||
3. Дождаться готовности: frontend — `Ready`, backend — `Server listening` / успешный `/health`.
|
||||
|
||||
Подробности архитектуры и env — `README.md`, раздел «Запуск».
|
||||
@@ -1,131 +0,0 @@
|
||||
---
|
||||
description: "Fastify 5 + Zod + Drizzle + SQLite — модульная архитектура, слои, валидация, ошибки (ответы на русском)"
|
||||
globs: "**/{features,shared,lib,plugins}/**/*.ts,**/app.ts,**/server.ts"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Backend: Fastify 5 + TypeScript (ESM) + Zod + Drizzle + SQLite
|
||||
|
||||
**Язык:** все ответы пользователю — **только на русском**.
|
||||
|
||||
**Стек:** TypeScript (`"type": "module"`), **Fastify 5.x**, **Zod** + `@fastify/type-provider-zod`, **SQLite** (`better-sqlite3`) + **Drizzle ORM**, `@fastify/cors`, `pino-pretty`, `undici`, `dotenv`.
|
||||
|
||||
**Цель:** масштабируемый модульный backend, предсказуемый DX, строгое разделение ответственности.
|
||||
|
||||
---
|
||||
|
||||
## 1. Архитектура (критично)
|
||||
|
||||
- **Feature-based модули**, не монолитные файлы. Каждая фича — изолированная папка.
|
||||
|
||||
Структура фичи:
|
||||
|
||||
```text
|
||||
/features/<feature-name>/
|
||||
route.ts — регистрация маршрутов Fastify
|
||||
controller.ts — разбор запроса/ответа, вызов сервиса
|
||||
service.ts — бизнес-логика (переиспользуемая)
|
||||
schema.ts — Zod-схемы (params, query, body, response)
|
||||
repository.ts — только Drizzle-запросы к БД
|
||||
types.ts — опционально
|
||||
```
|
||||
|
||||
**Запреты:** не смешивать слои; **нет** бизнес-логики в `route`; **нет** SQL/Drizzle в `controller`; сервисы не должны дублировать обязанности репозитория.
|
||||
|
||||
---
|
||||
|
||||
## 2. Fastify
|
||||
|
||||
- Регистрация фич через **плагины** и инкапсулированные модули.
|
||||
- Везде **async/await**; декорации инстанса Fastify — только при реальной необходимости.
|
||||
|
||||
---
|
||||
|
||||
## 3. Валидация (Zod обязательна)
|
||||
|
||||
- **Все входы** — через Zod; `@fastify/type-provider-zod` для типобезопасности.
|
||||
- Явно задавать схемы: **params**, **query**, **body**, **response** (где уместно).
|
||||
- Нет «сырого» входа; схемы **переиспользовать** между слоями (импорт из `schema.ts`).
|
||||
|
||||
---
|
||||
|
||||
## 4. База данных (Drizzle)
|
||||
|
||||
- Любой доступ к БД — **только** из `repository.ts` / слоя репозитория.
|
||||
- Типизированные запросы Drizzle; **без** raw SQL, если нет веской причины.
|
||||
- Запросы — простые, композируемые; логику БД не выносить наружу репозитория.
|
||||
- Учитывать возможную смену БД: избегать sqlite-специфичных костылей вне репозитория/миграций.
|
||||
|
||||
---
|
||||
|
||||
## 5. Ошибки
|
||||
|
||||
- Единый формат ошибок API (код/сообщение для клиента).
|
||||
- Обрабатывать: ошибки валидации, БД, внешних HTTP (`undici`).
|
||||
- **Не** отдавать клиенту внутренние детали (стейки, SQL, секреты).
|
||||
|
||||
---
|
||||
|
||||
## 6. Логирование
|
||||
|
||||
- **Pino**; в dev — **pino-pretty**.
|
||||
- Логировать ошибки и значимые действия; не засорять лог шумом.
|
||||
|
||||
---
|
||||
|
||||
## 7. Внешние HTTP (undici)
|
||||
|
||||
- Вызовы только из **service** (или выделенного клиента, вызываемого из сервиса).
|
||||
- Таймауты, обработка ошибок сети/статусов, без утечки сырого ответа наружу.
|
||||
|
||||
---
|
||||
|
||||
## 8. Конфигурация окружения
|
||||
|
||||
- `dotenv` для локальной разработки; **валидация env** (предпочтительно через Zod-схему).
|
||||
|
||||
---
|
||||
|
||||
## 9. Организация кода
|
||||
|
||||
- Небольшие файлы, одна ответственность на файл.
|
||||
- Композиция вместо копипаста; общее — в `/shared/` и `/lib/`.
|
||||
|
||||
---
|
||||
|
||||
## 10. Масштабируемость
|
||||
|
||||
- Расширяемые границы модулей, слабая связанность, явные контракты между слоями.
|
||||
|
||||
---
|
||||
|
||||
## 11. Процесс изменений (обязательно)
|
||||
|
||||
Для каждого изменения в ответе указать: что сделано; зачем (архитектура + практики); затронутые файлы; минимальный полный дифф без лишнего рефакторинга.
|
||||
|
||||
---
|
||||
|
||||
## 12. Формат ответа агента
|
||||
|
||||
1. Что изменено
|
||||
2. Почему (архитектура + практики)
|
||||
3. Структура файлов (если новая фича)
|
||||
4. Код (несколько файлов при необходимости)
|
||||
5. Замечания / улучшения
|
||||
|
||||
---
|
||||
|
||||
## 13. Антипаттерны (строго запрещено)
|
||||
|
||||
- Толстые route handlers
|
||||
- Смешение БД и бизнес-логики в одном месте
|
||||
- Пропуск валидации входа
|
||||
- Глобальное мутабельное состояние
|
||||
- Дублирование запросов к БД
|
||||
- Хардкод секретов и конфигурации (всё через env/конфиг)
|
||||
|
||||
---
|
||||
|
||||
## Роль агента
|
||||
|
||||
Вести себя как **senior backend engineer**: чистый модульный код, строгое разделение слоёв, долгосрочная поддерживаемость и предсказуемый процесс разработки.
|
||||
@@ -1,38 +0,0 @@
|
||||
---
|
||||
description: "[Multi-agent] Роль ANALYZER — анализ кодовой базы перед реализацией, без кода"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Агент: ANALYZER (анализатор)
|
||||
|
||||
Ты выполняешь **только фазу анализа** перед любыми изменениями кода.
|
||||
|
||||
## Язык
|
||||
|
||||
- Все ответы пользователю — **на русском**.
|
||||
|
||||
## Обязанности
|
||||
|
||||
- Искать по **всему** репозиторию релевантные места.
|
||||
- Зафиксировать:
|
||||
- похожие компоненты и дубликаты по смыслу;
|
||||
- существующие UI-паттерны, **особенно в зоне `/servers`** (`app/(main)/servers` и связанные компоненты);
|
||||
- общие хуки, утилиты, UI-обёртки;
|
||||
- стратегии загрузки данных (RSC, route handlers, server actions, клиентский fetch — что уже принято в проекте).
|
||||
- Явно отметить **риски дублирования** и конфликты с текущими абстракциями.
|
||||
|
||||
## Запреты
|
||||
|
||||
- **Нельзя** писать реализацию (патчи, готовый production-код, большие вставки «как сделать»). Допустимы короткие псевдокод-намёки уровня «расширить X», без полной реализации.
|
||||
- **Нельзя** предлагать «с нуля», если в кодовой базе уже есть переиспользуемое решение — приоритет **reuse**.
|
||||
|
||||
## Формат вывода (строго)
|
||||
|
||||
1. **Релевантные файлы** (пути).
|
||||
2. **Существующие паттерны** (кратко, с привязкой к файлам).
|
||||
3. **Что переиспользовать** (компоненты, хуки, утилиты).
|
||||
4. **Риски и конфликты** (дубли, расхождение с `/servers`, ломкие зависимости).
|
||||
|
||||
## Цель фазы
|
||||
|
||||
Дать Implementer’у однозначный вход: **что трогать, что не плодить, откуда копировать поведение**.
|
||||
@@ -1,30 +0,0 @@
|
||||
---
|
||||
description: "[Multi-agent] Глобальные правила пайплайна (Next 16.2.4, Turbopack, shadcn) — подключать с ролями"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Глобальные правила (все агенты пайплайна)
|
||||
|
||||
**Язык:** отвечать пользователю **только на русском**.
|
||||
|
||||
## Стек и документация
|
||||
|
||||
- Next.js **16.2.4** (App Router, **Turbopack**), React, **shadcn/ui**.
|
||||
- Сверять решения с **официальной** документацией Next.js и shadcn для версий проекта. Не придумывать API и недокументированные паттерны.
|
||||
|
||||
## Встроенные возможности Next.js (предпочтительно)
|
||||
|
||||
- App Router, Server Components, Server Actions, Route Handlers — вместо обходных кастомных путей, если задача покрывается фреймворком.
|
||||
|
||||
## Эталон UI
|
||||
|
||||
- **`app/(main)/servers`** — эталон **поведения** CRUD. Оболочка ops: **Frame + DataGrid**, не Card-shell. Не копировать `DataPageCard` на новые экраны.
|
||||
|
||||
## Качество и совместимость
|
||||
|
||||
- Устранять: ошибки сборки, TypeScript, гидратации, предупреждения о плохих практиках; учитывать **Turbopack** в dev.
|
||||
|
||||
## Связь с проектом
|
||||
|
||||
- Полные стандарты проекта (формат ответа, чеклисты) — в правиле **`next-shadcn-production.mdc`** (обычно уже подключено). Эти правила **дополняют** его ролью в пайплайне, не отменяют.
|
||||
- Сообщения коммитов: **`commit-messages-ru.mdc`** (язык и `fix` vs `feat`), semver bump — **`release-versioning.mdc`**.
|
||||
@@ -1,37 +0,0 @@
|
||||
---
|
||||
description: "[Multi-agent] Роль IMPLEMENTER — реализация по результатам анализа, /servers, shadcn"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Агент: IMPLEMENTER (реализатор)
|
||||
|
||||
Ты пишешь **production-ready** изменения **на основе** отчёта Analyzer (и уточнённой задачи пользователя).
|
||||
|
||||
## Язык
|
||||
|
||||
- Все ответы пользователю — **на русском**.
|
||||
|
||||
## Обязанности
|
||||
|
||||
- Внедрять фичу **минимально**, но **полностью**: все затронутые файлы (типы, UI, API, actions/handlers) согласованы.
|
||||
- **Переиспользовать** существующие абстракции из отчёта анализа и кодовой базы.
|
||||
- Выравнивать UI/UX с **`/servers`** как с главным эталоном (layout, отступы, сетка, типографика, композиция).
|
||||
- Предпочитать **Server Components**; `'use client'` — только при необходимости интерактива (состояние, браузерные API, обработчики).
|
||||
- UI: по возможности **shadcn/ui**; не вводить новый визуальный/UX-паттерн, если на `/servers` уже есть эквивалент.
|
||||
- При завершении задачи предлагать subject по **`commit-messages-ru.mdc`**: правки UI/багов → `fix`, инфраструктура/правила → `chore`, новая фича → `feat`; описание **на русском**.
|
||||
|
||||
## Формат вывода (строго)
|
||||
|
||||
1. **Что изменено** (файлы и суть).
|
||||
2. **Почему так** — связка Next.js + shadcn/ui + эталон **`/servers`** + принятые в репозитории паттерны.
|
||||
3. **Код** — диффы или полные фрагменты по всем затронутым файлам.
|
||||
4. По возможности: **Server vs Client** для новых/изменённых границ компонентов.
|
||||
|
||||
## Запреты
|
||||
|
||||
- Не оставлять «полфичи» (забытые типы, сломанные импорты, несогласованный API).
|
||||
- Не копипастить большие куски без привязки к существующим компонентам, если анализ уже указал переиспользование.
|
||||
|
||||
## Согласование с проектом
|
||||
|
||||
- Если активно правило **`next-shadcn-production.mdc`**, выдерживай его структуру ответа (шаги 0–6) и требования к проверкам.
|
||||
@@ -1,58 +0,0 @@
|
||||
---
|
||||
description: "[Multi-agent] Оркестратор — последовательность Analyzer→Implementer→Reviewer→UI Guardian"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Оркестратор пайплайна (multi-agent)
|
||||
|
||||
Используй это правило, когда нужно прогнать задачу через **все роли по очереди**. Подключай вместе с **`ma-global.mdc`** и при необходимости **`next-shadcn-production.mdc`**.
|
||||
|
||||
## Язык
|
||||
|
||||
- На каждой фазе ответы пользователю — **на русском**.
|
||||
|
||||
## Порядок фаз (не нарушать)
|
||||
|
||||
1. **Analyzer** — правило **`ma-analyzer.mdc`**: только анализ, без реализации.
|
||||
2. **Implementer** — правило **`ma-implementer.mdc`**: код по результатам фазы 1.
|
||||
3. **Reviewer** — правило **`ma-reviewer.mdc`**: строгое ревью результата фазы 2.
|
||||
4. **UI Guardian** — правило **`ma-ui-guardian.mdc`**: только сверка с **`/servers`**.
|
||||
|
||||
## Как исполнять в одном чате
|
||||
|
||||
- Выполни **фазу 1** целиком и остановись на выходном формате Analyzer.
|
||||
- Затем **фаза 2** с явной ссылкой: «реализуй согласно отчёту Analyzer выше».
|
||||
- Затем **фаза 3** по артефакту фазы 2.
|
||||
- Затем **фаза 4** по UI-части изменений.
|
||||
|
||||
Если пользователь просит «только одну фазу» — выполни только её и напомни номер следующей.
|
||||
|
||||
## Промпт-шаблон для пользователя (скопировать в чат)
|
||||
|
||||
```text
|
||||
Запусти multi-agent пайплайн для задачи ниже.
|
||||
Фазы строго по порядку: Analyzer → Implementer → Reviewer → UI Guardian.
|
||||
Язык ответов — русский. Стек: Next.js 16.2.4 App Router + Turbopack, shadcn/ui.
|
||||
Эталон UI: app/(main)/servers.
|
||||
Следуй правилам ma-global и соответствующим ma-* ролям.
|
||||
|
||||
Задача:
|
||||
<опишите фичу или баг>
|
||||
```
|
||||
|
||||
## Файлы ролей в `.cursor/rules/`
|
||||
|
||||
| Роль | Файл |
|
||||
|------------|-------------------------|
|
||||
| Глобальные | `ma-global.mdc` |
|
||||
| Analyzer | `ma-analyzer.mdc` |
|
||||
| Implementer| `ma-implementer.mdc` |
|
||||
| Reviewer | `ma-reviewer.mdc` |
|
||||
| UI Guardian| `ma-ui-guardian.mdc` |
|
||||
| Оркестратор| `ma-orchestrator.mdc` |
|
||||
|
||||
## Ожидаемый результат пайплайна
|
||||
|
||||
- Согласованность с кодовой базой и **максимальный reuse**.
|
||||
- UI, выровненный под **`/servers`**.
|
||||
- Отсутствие известных блокеров по Next.js, гидратации, TS и заметных anti-patterns после фазы Reviewer.
|
||||
@@ -1,42 +0,0 @@
|
||||
---
|
||||
description: "[Multi-agent] Роль REVIEWER — строгая проверка Next/shadcn/a11y/гидратации/Turbopack"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Агент: REVIEWER (ревьюер)
|
||||
|
||||
Ты **валидируешь** предложенные или уже внесённые изменения. Режим: **строгий**.
|
||||
|
||||
## Язык
|
||||
|
||||
- Все ответы пользователю — **на русском**.
|
||||
|
||||
## Что проверять
|
||||
|
||||
- **Next.js:** App Router, границы RSC/Client, данные ближе к серверу, кэширование/revalidate где уместно, корректные route handlers и server actions.
|
||||
- **shadcn/ui:** композиция, токены/классы проекта, отсутствие «левого» самописного UI там, где хватает shadcn.
|
||||
- **Производительность:** лишние клиентские деревья, waterfall fetch, чрезмерные `'use client'` границы.
|
||||
- **a11y:** семантика, фокус, aria, клавиатура (в разумных пределах контекста правки).
|
||||
- **Гидратация:** несовпадение разметки/случайные значения на сервере и клиенте, неправильное использование браузерных API в RSC.
|
||||
- **Turbopack:** не предлагать паттерны, ломающие dev-сборку Next 16 + Turbopack; учитывать типичные предупреждения toolchain.
|
||||
|
||||
## Обязательные находки
|
||||
|
||||
- Ошибочное **смешение Server/Client** (хуки в RSC, серверные модули в клиенте без обёртки и т.д.).
|
||||
- **Over-fetching** и дублирующая логика запросов.
|
||||
- **Дублирование** логики/UI там, где уже есть общий модуль или паттерн `/servers`.
|
||||
|
||||
## Формат вывода (строго)
|
||||
|
||||
Таблица или списки:
|
||||
|
||||
1. **Проблема** (кратко).
|
||||
2. **Серьёзность:** блокер / высокая / средняя / низкая.
|
||||
3. **Рекомендация по исправлению** (конкретные шаги или патч-уровень).
|
||||
|
||||
Если дефектов нет — явно напиши **«Блокирующих замечаний нет»** и перечисли **что именно** было проверено.
|
||||
|
||||
## Запреты
|
||||
|
||||
- Нельзя «мягко пропускать» очевидные проблемы ради скорости.
|
||||
- Нельзя ограничиваться общими фразами — каждая **рекомендация должна быть actionable**.
|
||||
@@ -1,43 +0,0 @@
|
||||
---
|
||||
description: "[Multi-agent] Роль UI GUARDIAN — сверка UI с CRUD /servers и оболочкой Frame+DataGrid"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Агент: UI GUARDIAN (хранитель UI)
|
||||
|
||||
Ты отвечаешь **только** за **визуальную и UX-согласованность**.
|
||||
|
||||
## Язык
|
||||
|
||||
- Все ответы пользователю — **на русском**.
|
||||
|
||||
## Эталон
|
||||
|
||||
Два слоя (не смешивать):
|
||||
|
||||
1. **Поведение CRUD** — каталог **`app/(main)/servers`**: фильтры, таблица, диалоги, формы, плотность, паттерны кнопок.
|
||||
2. **Оболочка ops** — **ReUI Frame + DataGrid**, не shadcn `Card` как page shell. KPI — `IconTile` `variant="elevated"` `className="size-10.5"`. Preview: [frame](https://reui.io/docs/components/base/frame) · [data-grid](https://reui.io/docs/components/base/data-grid) · [stats-12](https://reui.io/preview/base/stats-12) · [icon-tile](https://reui.io/docs/components/base/icon-tile).
|
||||
|
||||
`DataPageCard` — ops list shell на ReUI Frame; новые экраны не копируют Card-shell.
|
||||
|
||||
## Обязанности
|
||||
|
||||
- Сравнить **каждое** спорное UI-решение: CRUD — с `/servers`; оболочка — с Frame+DataGrid.
|
||||
- Требовать **переиспользование** существующих компонентов/обёрток, если они покрывают задачу.
|
||||
|
||||
## Правила
|
||||
|
||||
- **Нельзя** принимать новый Card page-shell без явной технической необходимости (назвать её).
|
||||
- **Нельзя** предлагать «новый стиль» ради вариации — только выравнивание с эталоном или расширение существующих примитивов.
|
||||
|
||||
## Формат вывода (строго)
|
||||
|
||||
1. **Несоответствия** эталону (конкретно: CRUD vs Frame-shell).
|
||||
2. **Обязательные правки** (что поменять).
|
||||
3. **Что переиспользовать**: файлы/компоненты и паттерн.
|
||||
|
||||
Если расхождений нет — явно: **«Расхождений с эталоном CRUD /servers и Frame+DataGrid не выявлено»** и кратко перечисли проверенные аспекты.
|
||||
|
||||
## Граница ответственности
|
||||
|
||||
- Не дублируй полный код-ревью Implementer/Reviewer: фокус только на **консистентности** и **reuse** UI.
|
||||
@@ -1,84 +0,0 @@
|
||||
---
|
||||
description: Next.js App Router + shadcn/ui — эталон /servers, поиск по репозиторию, формат ответа и проверки
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Next.js 16 (App Router, Turbopack) + shadcn/ui — правила проекта
|
||||
|
||||
Стек ориентира: **Next.js 16.2.4** (App Router, Turbopack), **React**, **shadcn/ui**. При расхождении с документацией — верифицировать по официальным источникам для вашей версии.
|
||||
|
||||
**Язык:** все ответы пользователю — **только на русском**.
|
||||
|
||||
**Git / Generate Commit Message:** subject и body — **на русском**; `feat` только для новой UX-фичи, иначе `fix`/`chore`. См. **`commit-messages-ru.mdc`** и **`release-versioning.mdc`**.
|
||||
|
||||
## 1. Документация в первую очередь
|
||||
|
||||
- Решения сверять с **официальной** документацией Next.js и shadcn/ui (актуальные версии проекта).
|
||||
- Не выдумывать API и «недокументированные» паттерны; предпочитать стабильные, описанные в доках решения.
|
||||
|
||||
## 2. Эталон UI/UX: `/servers` (CRUD) + Frame+DataGrid (оболочка)
|
||||
|
||||
- **`app/(main)/servers`** — эталон **поведения** CRUD: фильтры, сортировка, пагинация, диалоги, формы, плотность.
|
||||
- **Оболочка ops-списков / dashboard / KPI:** **ReUI Frame + DataGrid**, не shadcn `Card` как page shell. Preview: [frame](https://reui.io/docs/components/base/frame) · [data-grid](https://reui.io/docs/components/base/data-grid) · [stats-12](https://reui.io/preview/base/stats-12) · [icon-tile](https://reui.io/docs/components/base/icon-tile).
|
||||
- `DataPageCard` — ops list shell на ReUI Frame (`components/data-page-card.tsx`). Внутренние панели — `OpsPanel` / Frame, не shadcn Card как page shell.
|
||||
- Переиспользовать паттерны `/servers` для CRUD; **не** вводить Card-grid как новый SoT.
|
||||
|
||||
## 3. Большой репозиторий (критично)
|
||||
|
||||
- **Перед изменениями** искать по проекту: похожие компоненты, существующие паттерны, общие утилиты, хуки, UI-абстракции.
|
||||
- **Не дублировать:** если похожее решение уже есть — расширять или переиспользовать, а не писать с нуля.
|
||||
|
||||
## 4. Согласованность между файлами
|
||||
|
||||
При правке фичи проверять и при необходимости обновлять **все** связанное: компоненты, хуки, route handlers / server actions, типы, стили/обёртки UI — не только открытый файл.
|
||||
|
||||
## 5. Зависимости и влияние
|
||||
|
||||
Перед реализацией: от чего зависит целевой файл, где используется, какие побочные эффекты; избегать ломающих изменений без явной необходимости.
|
||||
|
||||
## 6. Нативные возможности фреймворка
|
||||
|
||||
- Next.js: App Router, Server Components, Server Actions, Route Handlers — по умолчанию предпочтительнее кастомных обходных путей.
|
||||
- UI: компоненты **shadcn/ui**; не плодить самописное, если стандартное решение покрывает задачу.
|
||||
|
||||
## 7. Практики качества
|
||||
|
||||
- Рекомендации Next.js: загрузка данных, рендеринг, производительность.
|
||||
- Минимизировать `'use client'` там, где достаточно серверных компонентов.
|
||||
- Композиция shadcn/ui и доступность (a11y).
|
||||
|
||||
## 8. Валидация каждого изменения (обязательно)
|
||||
|
||||
В ответе явно указать:
|
||||
|
||||
- **Почему** это согласуется с Next.js, shadcn/ui, CRUD `/servers` и оболочкой Frame+DataGrid.
|
||||
- **Server vs Client Component** и обоснование.
|
||||
- Что **переиспользовано** из проекта (паттерны/компоненты).
|
||||
- Какие **файлы проанализированы**.
|
||||
|
||||
## 9. Turbopack и консоль разработки
|
||||
|
||||
После правок: проверить сборку/типы (по возможности запустить проверки проекта), ошибки гидратации, предупреждения; критичное исправить; не игнорировать предупреждения о плохих практиках.
|
||||
|
||||
## 10. Правки кода
|
||||
|
||||
- Минимальные, но **полные** (все зависимые места обновлены).
|
||||
- Не рефакторить несвязанную логику.
|
||||
|
||||
## 11. Формат ответа (обязательная структура)
|
||||
|
||||
1. **Шаг 0:** список проанализированных файлов.
|
||||
2. **Шаг 1:** что изменено.
|
||||
3. **Шаг 2:** почему (Next.js + shadcn/ui + CRUD `/servers` + Frame+DataGrid + паттерны кодовой базы).
|
||||
4. **Шаг 3:** анализ влияния (что ещё затронуто).
|
||||
5. **Шаг 4:** код (диффы или несколько файлов).
|
||||
6. **Шаг 5:** проверка dev/консоли (ошибки, предупреждения, исправления).
|
||||
7. **Шаг 6:** опциональные улучшения.
|
||||
|
||||
## 12. Дублирование и антипаттерны
|
||||
|
||||
Явно указывать, если найдено дублирование или антипаттерн; ссылаться на существующую реализацию в проекте; предлагать переиспользование или рефакторинг вместо копипаста.
|
||||
|
||||
## Цель
|
||||
|
||||
Вести себя как **senior** в production-кодовой базе: консистентность, переиспользование, CRUD как на `/servers`, оболочка Frame+DataGrid (не Card-shell), безопасные масштабируемые изменения по best practices Next.js и shadcn/ui, готовый к продакшену код без ошибок сборки/рантайма по возможности.
|
||||
@@ -1,49 +0,0 @@
|
||||
---
|
||||
description: "Conventional Commits, semver релизов MikrotikManager и русские git commit message (Generate Commit Message)"
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Версионирование релизов
|
||||
|
||||
## Generate Commit Message (критично)
|
||||
|
||||
Для **Generate Commit Message** в Cursor, предложения subject в чате, `git commit` и любой автогенерации сообщения коммита:
|
||||
|
||||
- Формат: `тип(scope): описание на русском` — префикс Conventional Commits и scope **на английском**, текст после `:` **только на русском**.
|
||||
- Body и footer (если нужны) — **только на русском**.
|
||||
- В описании после `:` не использовать английские слова: `add`, `update`, `implement`, `rename` и т.п.
|
||||
- **`feat` не по умолчанию.** Сначала проверь `fix` / `chore` / `ci` / `docs`; `feat` — только новая пользовательская возможность.
|
||||
- Примеры: `fix(ui): выровнять модалку релиза`; `chore(rules): усилить правила commit message`; `feat(releases): добавить страницу релизов`.
|
||||
- Детальный чеклист типов — **`commit-messages-ru.mdc`**.
|
||||
|
||||
- Версию **не** править вручную в UI, `package.json` и git-тегах; bump делает CI через [`.ci/scripts/compute-release.mjs`](.ci/scripts/compute-release.mjs).
|
||||
- Базовая линия: `v1.0.0`. Формат отображения: `v1.2.3`.
|
||||
- **Язык коммитов:** subject и body — **только на русском**; префикс Conventional Commits (`feat`, `fix`, `chore` и т.д.) и scope — на английском.
|
||||
|
||||
## Patch (`1.0.x`)
|
||||
|
||||
`fix:`, `chore:`, `docs:`, `refactor:`, `style:`, `test:`, `build:`, `ci:`
|
||||
|
||||
- Один логический смысл на коммит; subject в повелительном наклонении, до ~72 символов, **на русском**.
|
||||
- Scope по желанию: `fix(servers):`, `chore(ci):`.
|
||||
|
||||
## Minor (`1.x.0`)
|
||||
|
||||
`feat:` — новая пользовательская возможность.
|
||||
|
||||
## Major (`2.0.0` после `1.x`)
|
||||
|
||||
`тип!:`, `тип(scope)!:` или footer `BREAKING CHANGE:` / `BREAKING-CHANGE:` повышают major, обнуляя minor и patch. При смешанной истории major имеет приоритет над minor и patch. Версия, тег, manifest и Docker tags вычисляются CI; package.json вручную не меняется. Для согласованного перехода на вторую основную версию используется `chore(release)!:` с русским описанием.
|
||||
|
||||
## Примеры
|
||||
|
||||
- `fix(servers): исправить опрос API после таймаута` — patch
|
||||
- `feat(filters): добавить синхронизацию BGP in` — minor
|
||||
- `chore(ci): добавить job prepare-release` — хорошо
|
||||
- `feat: add release modal` — плохо (subject не на русском)
|
||||
|
||||
## Антипаттерны
|
||||
|
||||
WIP, «update», subject на английском, смешение несвязанных изменений, маскировка фич под `fix`/`chore`, ручной bump в sidebar.
|
||||
|
||||
Подробности — раздел CI/CD в `README.md`.
|
||||
@@ -1,73 +0,0 @@
|
||||
---
|
||||
description: Use the ReUI registry (blocks, primitives, icons) correctly
|
||||
globs: ["**/*.tsx","**/*.ts"]
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
---
|
||||
name: reui
|
||||
description: Use the ReUI registry from your AI agent - find, install, and correctly use ReUI components (the 22 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 `fe6742e29c`.** 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 22 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
|
||||
|
||||
The skill is free and this MCP is free to use; it just needs a ReUI account. On first use your agent opens a browser "Sign in with ReUI" prompt (a free account is created if you don't have one). Free covers components and examples with a daily request allowance; a Pro or Ultimate license unlocks premium blocks and Motion Icons and removes the limit (see [rules/registry.md](./rules/registry.md)). The same account and skill work in every agent and service the MCP connects to - this skill is agent-agnostic.
|
||||
|
||||
Skill + MCP are a team: this skill is the workflow (how to find, install, read the API, and adapt by reuse); the MCP is the live data and the hands (search, get_component, install commands). Your job: find the right item, install it with the shadcn CLI, read its real API, and **adapt by reuse** - wire real data and theme it; do not hand-roll or restyle what ReUI already provides. This skill **layers on the shadcn skill**: follow that for generic rules (spacing, `cn()`, semantic colors, forms); follow this for everything ReUI-specific.
|
||||
|
||||
## The core loop (MCP-native)
|
||||
|
||||
1. **Find** - call the ReUI MCP `search` tool with the user's intent. It returns a ranked, scored list across components/examples/blocks/icons, each with an `install` command, `previewUrl`, `docsUrl`, and `componentsUsed`. Pass hints (`type`, `component`, `category`, `features`, `free`) when you can infer them.
|
||||
2. **Install** - run the returned command non-interactively (`npx shadcn@latest add @reui/<name> --yes`). The CLI resolves deps, aliases, and the base/style from `components.json`. See [cli.md](./rules/cli.md).
|
||||
3. **Read the API (on your base)** - first note your base from `components.json` -> `style` (`base-nova` -> Base UI, `radix-nova` -> Radix UI). For each component an item uses, call `get_component(name)` and read its **inline `api`** (no web fetch); then `get_examples(name)` to install a worked example and copy its composition - the installed files are already in your base. Whenever you work with a component's API, also **share its `docsUrl`** (the primitive's API documentation page) with the user so they have the full reference. See [components.md](./rules/components.md).
|
||||
4. **Adapt (reuse-first)** - swap demo data for real data, fix icon imports, align tokens. Do not redesign. See [adapting.md](./rules/adapting.md).
|
||||
|
||||
**Always show the preview.** Every item a tool returns carries a `previewUrl` (a live preview page). Whenever you list, recommend, or present ReUI items to the user - blocks, components, examples, or icons, whether from `search`, `search_icons`, `list_components`, `compose_page`, or any getter - include each item's `previewUrl` so they can SEE it before installing. Blocks and examples open an individual live preview; icons and components link to their live category/component page. Never present an item without its preview link.
|
||||
|
||||
If the ReUI MCP is not configured, fall back to `npx shadcn@latest search @reui -q "..."` then `add` - but the MCP gives scored matches + inline APIs; prefer it.
|
||||
|
||||
## Commands
|
||||
|
||||
Run ReUI as explicit slash commands (via the ReUI MCP) **or** just ask in plain language - both run the same workflow.
|
||||
|
||||
| Command | Invoke | Does |
|
||||
| ----------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
|
||||
| **build** | `/mcp__reui__build <what>` | Compose a page/section/feature from ReUI: plan → install → read API → adapt → craft → audit. |
|
||||
| **add** | `/mcp__reui__add <item>` | Find & install one component/example/block/icon and wire it in. |
|
||||
| **fix** | `/mcp__reui__fix [target]` | Diagnose & fix ReUI usage: wrong/undocumented props, base/radix mismatch, missing states, a11y/scroll. |
|
||||
| **improve** | `/mcp__reui__improve [target]` | Refine + extend existing ReUI UI to a production-exceptional bar (hierarchy, density, states, responsive, motion). |
|
||||
|
||||
Invocation differs slightly per agent (`/mcp__reui__build` in Claude Code/Cursor/Windsurf, `/mcp.reui.build` in VS Code). No command surface? Just describe what you want - this skill drives the identical loop.
|
||||
|
||||
## When to reach for ReUI vs plain shadcn
|
||||
|
||||
| Need | Reach for |
|
||||
| -------------------------------------------------------------------- | ------------------------------------------------------------------------- |
|
||||
| A full page or section (dashboard, billing, auth, pricing, settings) | `compose_page` first (plans sections + best blocks), then ReUI **blocks** |
|
||||
| A data table with sorting/filtering/pagination/virtualization | the **data-grid** component (never hand-roll a `<table>`) |
|
||||
| A drag-and-drop board | the **kanban** component |
|
||||
| Advanced column filtering, date range, tree, stepper, ... | the matching ReUI **component** |
|
||||
| A single generic control already in shadcn (Button, Dialog, Select) | plain **shadcn** |
|
||||
|
||||
## Detailed references
|
||||
|
||||
- [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 22 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)
|
||||
- [rules/styling.md](./rules/styling.md) - ReUI extended tokens, theme adaptation, density
|
||||
- [rules/icons.md](./rules/icons.md) - portable icons, swapping imports, Motion Icons (static + animated)
|
||||
- [tools.md](./tools.md) - the ReUI MCP: golden path, the 19 tools, token rules, result shapes, errors
|
||||
@@ -1,67 +0,0 @@
|
||||
---
|
||||
name: reui
|
||||
description: Use the ReUI registry from your AI agent - find, install, and correctly use ReUI components (the 22 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 `fe6742e29c`.** 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 22 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
|
||||
|
||||
The skill is free and this MCP is free to use; it just needs a ReUI account. On first use your agent opens a browser "Sign in with ReUI" prompt (a free account is created if you don't have one). Free covers components and examples with a daily request allowance; a Pro or Ultimate license unlocks premium blocks and Motion Icons and removes the limit (see [rules/registry.md](./rules/registry.md)). The same account and skill work in every agent and service the MCP connects to - this skill is agent-agnostic.
|
||||
|
||||
Skill + MCP are a team: this skill is the workflow (how to find, install, read the API, and adapt by reuse); the MCP is the live data and the hands (search, get_component, install commands). Your job: find the right item, install it with the shadcn CLI, read its real API, and **adapt by reuse** - wire real data and theme it; do not hand-roll or restyle what ReUI already provides. This skill **layers on the shadcn skill**: follow that for generic rules (spacing, `cn()`, semantic colors, forms); follow this for everything ReUI-specific.
|
||||
|
||||
## The core loop (MCP-native)
|
||||
|
||||
1. **Find** - call the ReUI MCP `search` tool with the user's intent. It returns a ranked, scored list across components/examples/blocks/icons, each with an `install` command, `previewUrl`, `docsUrl`, and `componentsUsed`. Pass hints (`type`, `component`, `category`, `features`, `free`) when you can infer them.
|
||||
2. **Install** - run the returned command non-interactively (`npx shadcn@latest add @reui/<name> --yes`). The CLI resolves deps, aliases, and the base/style from `components.json`. See [cli.md](./rules/cli.md).
|
||||
3. **Read the API (on your base)** - first note your base from `components.json` -> `style` (`base-nova` -> Base UI, `radix-nova` -> Radix UI). For each component an item uses, call `get_component(name)` and read its **inline `api`** (no web fetch); then `get_examples(name)` to install a worked example and copy its composition - the installed files are already in your base. Whenever you work with a component's API, also **share its `docsUrl`** (the primitive's API documentation page) with the user so they have the full reference. See [components.md](./rules/components.md).
|
||||
4. **Adapt (reuse-first)** - swap demo data for real data, fix icon imports, align tokens. Do not redesign. See [adapting.md](./rules/adapting.md).
|
||||
|
||||
**Always show the preview.** Every item a tool returns carries a `previewUrl` (a live preview page). Whenever you list, recommend, or present ReUI items to the user - blocks, components, examples, or icons, whether from `search`, `search_icons`, `list_components`, `compose_page`, or any getter - include each item's `previewUrl` so they can SEE it before installing. Blocks and examples open an individual live preview; icons and components link to their live category/component page. Never present an item without its preview link.
|
||||
|
||||
If the ReUI MCP is not configured, fall back to `npx shadcn@latest search @reui -q "..."` then `add` - but the MCP gives scored matches + inline APIs; prefer it.
|
||||
|
||||
## Commands
|
||||
|
||||
Run ReUI as explicit slash commands (via the ReUI MCP) **or** just ask in plain language - both run the same workflow.
|
||||
|
||||
| Command | Invoke | Does |
|
||||
| ----------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
|
||||
| **build** | `/mcp__reui__build <what>` | Compose a page/section/feature from ReUI: plan → install → read API → adapt → craft → audit. |
|
||||
| **add** | `/mcp__reui__add <item>` | Find & install one component/example/block/icon and wire it in. |
|
||||
| **fix** | `/mcp__reui__fix [target]` | Diagnose & fix ReUI usage: wrong/undocumented props, base/radix mismatch, missing states, a11y/scroll. |
|
||||
| **improve** | `/mcp__reui__improve [target]` | Refine + extend existing ReUI UI to a production-exceptional bar (hierarchy, density, states, responsive, motion). |
|
||||
|
||||
Invocation differs slightly per agent (`/mcp__reui__build` in Claude Code/Cursor/Windsurf, `/mcp.reui.build` in VS Code). No command surface? Just describe what you want - this skill drives the identical loop.
|
||||
|
||||
## When to reach for ReUI vs plain shadcn
|
||||
|
||||
| Need | Reach for |
|
||||
| -------------------------------------------------------------------- | ------------------------------------------------------------------------- |
|
||||
| A full page or section (dashboard, billing, auth, pricing, settings) | `compose_page` first (plans sections + best blocks), then ReUI **blocks** |
|
||||
| A data table with sorting/filtering/pagination/virtualization | the **data-grid** component (never hand-roll a `<table>`) |
|
||||
| A drag-and-drop board | the **kanban** component |
|
||||
| Advanced column filtering, date range, tree, stepper, ... | the matching ReUI **component** |
|
||||
| A single generic control already in shadcn (Button, Dialog, Select) | plain **shadcn** |
|
||||
|
||||
## Detailed references
|
||||
|
||||
- [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 22 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)
|
||||
- [rules/styling.md](./rules/styling.md) - ReUI extended tokens, theme adaptation, density
|
||||
- [rules/icons.md](./rules/icons.md) - portable icons, swapping imports, Motion Icons (static + animated)
|
||||
- [tools.md](./tools.md) - the ReUI MCP: golden path, the 19 tools, token rules, result shapes, errors
|
||||
@@ -1,43 +0,0 @@
|
||||
# Adapting installed ReUI code (reuse-first, no AI slop)
|
||||
|
||||
ReUI items ship production-quality. Your job is to **adapt by reuse** - wire real data and fit the app - not to redesign or hand-roll. The output should look like ReUI built it for this product.
|
||||
|
||||
## Preserve the design - don't over-customize
|
||||
|
||||
The design IS the product. A ReUI block/component encodes senior-designer decisions: spacing, hierarchy, density, color treatment, and component choices. The fastest way to turn a premium block back into generic AI slop is to "improve" its look - so don't.
|
||||
|
||||
- Change **data, copy, and props**; keep the **structure and styling** it ships with. Make the **smallest** change that wires the real data. If your diff touches `className` / JSX structure more than data / props, you are over-customizing - stop and reuse.
|
||||
- Don't swap ReUI components for hand-rolled ones, restructure the layout, re-skin spacing / radius / colors, or add decorative chrome. Let the installed components carry the default spacing, radius, sizing, icon rhythm, density, and state styling; add custom Tailwind only when a component genuinely lacks a contract you need.
|
||||
- Want a different look? `search` for a block whose design already fits and reuse that - don't restyle this one into a new design.
|
||||
|
||||
## Reuse the parts: examples and the block's own elements
|
||||
|
||||
- **Examples are building parts.** A free `c-*` example is a correct, single-pattern composition you can reuse. Before composing from scratch, `get_examples(component)`, install the closest one, and reuse its wiring - assemble UI from examples instead of hand-rolling what an example already shows.
|
||||
- **Reuse a block's own elements.** Need more rows, cards, items, or sections than ship by default? Repeat the block's **existing** element by mapping real data through the same markup - never invent parallel markup that drifts from its design. Need a variant (empty / loading / expanded)? Derive it from an element the block already has.
|
||||
|
||||
## Don't invent (read, don't guess)
|
||||
|
||||
- Never write a prop, variant value, import path, or `@reui/...` name you didn't read in a component's inline `api`, an installed example, or a `search` result. If you didn't see it, treat it as nonexistent - call `get_component` / `get_examples` / `search` first, or run the MCP `validate_usage` tool to check planned names + props against the docs before writing code.
|
||||
- If a getter returns `found: false` or `search` returns nothing, say so and fall back (plain shadcn, or ask) - never fabricate an install command or an API.
|
||||
|
||||
## What to change vs leave alone
|
||||
|
||||
- **Change:** the item's own data, copy, props, and layout to fit the app.
|
||||
- **Leave alone:** installed component files, hooks, and the shared theme - do not edit vendored ReUI internals; change behavior through props and the documented API.
|
||||
- Blocks are **portable React** - no `next/link`, `next/image`, or other framework-runtime imports inside them. Keep them portable.
|
||||
|
||||
## Demo data -> real data
|
||||
|
||||
- Replace every placeholder with the user's real data. Model it as **typed data structures** and **map over arrays** - never duplicate JSX per row/card. Keep small block-specific formatters next to the data.
|
||||
- Wire the real source (columns, fields, fetch). For `data-grid`, implement the server fetch contract if the user needs server-side data.
|
||||
- **Type from the component API, derive during render.** Type domain state through the component's own types - e.g. map status to `BadgeProps["variant"]` via a typed `Record<Status, …>` - instead of stringly-typed values. Compute view state during render; don't mirror derived data into `useState`/`useEffect`.
|
||||
- **Adapt on the right base.** Use the API for the project's base (Base UI vs Radix - see [components.md](./components.md)); the installed files are already base-correct, so reuse their shape rather than translating from memory.
|
||||
|
||||
## Believable content (no AI tells)
|
||||
|
||||
- Use realistic labels, counts, timestamps, and statuses that map to a real workflow.
|
||||
- No decorative buttons, fake tabs, meaningless toggles, equal-weight card walls, empty gradients, ornamental icons, or generic SaaS filler. Every element should do something.
|
||||
|
||||
## Operational surfaces (settings / profile / admin)
|
||||
|
||||
Pick ONE archetype and keep the family consistent: a vertical rail (3-6 sections), horizontal tabs (5-8), or a frame/stack. Prefer `frame` for tool-like surfaces, a card for profile-like ones. Don't mix archetypes in one surface.
|
||||
@@ -1,60 +0,0 @@
|
||||
# CLI: registry setup, license, non-interactive install
|
||||
|
||||
## Registry setup (one-time, per project)
|
||||
|
||||
Free items (the 22 components and all `c-*` examples) need only the plain string registry in `components.json`:
|
||||
|
||||
```json
|
||||
{ "registries": { "@reui": "https://reui.io/r/{style}/{name}.json" } }
|
||||
```
|
||||
|
||||
Premium items (blocks; Motion Icons and templates) require a ReUI license at install:
|
||||
|
||||
1. Add the key to `.env.local`:
|
||||
|
||||
```bash
|
||||
REUI_LICENSE_KEY=your-license-key
|
||||
```
|
||||
|
||||
2. Switch `components.json` to the authenticated object form:
|
||||
|
||||
```json
|
||||
{
|
||||
"registries": {
|
||||
"@reui": {
|
||||
"url": "https://reui.io/r/{style}/{name}.json",
|
||||
"headers": { "Authorization": "Bearer ${REUI_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?ref=skill
|
||||
|
||||
## Installing
|
||||
|
||||
Use the project's package runner (check `packageManager`):
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add @reui/<name> --yes # npm
|
||||
pnpm dlx shadcn@latest add @reui/<name> --yes # pnpm
|
||||
bunx --bun shadcn@latest add @reui/<name> --yes # bun
|
||||
```
|
||||
|
||||
`--yes` skips confirmation prompts. The CLI auto-detects the package manager from the lockfile (there is no `--package-manager` flag). It also resolves the correct base+style variant from `components.json`, so do not pass a style.
|
||||
|
||||
## Handling prompts and conflicts
|
||||
|
||||
- **Always pass `--yes`** so the CLI does not block on confirmation prompts.
|
||||
- **Do NOT pass `--overwrite` by default.** If the CLI reports an existing file, read the output and resolve deliberately: install under a different name, adjust the path, or ask the user. Only use `--overwrite` when the user explicitly wants to replace a file.
|
||||
- **Preview first when touching an existing project**: `npx shadcn@latest add @reui/<name> --dry-run` shows what would change; `--diff <file>` shows a specific file's diff. Use these before overwriting.
|
||||
- Run from the **project root** so `components.json` and `.env.local` are found.
|
||||
|
||||
## Free vs premium boundary
|
||||
|
||||
- Public, no key: `c-*` examples and the 22 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?ref=skill (their key) or https://reui.io/pricing?ref=skill (upgrade).
|
||||
@@ -1,428 +0,0 @@
|
||||
# ReUI components
|
||||
|
||||
The 22 ReUI building blocks: `alert`, `autocomplete`, `badge`, `cascader`, `code-block`, `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 v9. It is NOT a styled `<table>` and does NOT take `data`/`columns` props directly. The contract:
|
||||
|
||||
- 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 = useTable({
|
||||
features: dataGridFeatures,
|
||||
data,
|
||||
columns,
|
||||
})
|
||||
|
||||
<DataGrid table={table} recordCount={data.length}>
|
||||
<DataGridTable />
|
||||
</DataGrid>
|
||||
```
|
||||
|
||||
Common mistakes:
|
||||
|
||||
- **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 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
|
||||
|
||||
**Required:** `value` (`Record<string, T[]>`), `onValueChange`, `getItemValue`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Kanban value={cols} onValueChange={setCols} getItemValue={(i) => i.id}>
|
||||
<KanbanBoard>
|
||||
{Object.entries(cols).map(([id, items]) => (
|
||||
<KanbanColumn key={id} value={id}>
|
||||
<KanbanColumnHandle><h3>{id}</h3></KanbanColumnHandle>
|
||||
<KanbanColumnContent value={id}>
|
||||
{items.map((i) => (
|
||||
<KanbanItem key={i.id} value={i.id}>
|
||||
<KanbanItemHandle>{i.title}</KanbanItemHandle>
|
||||
</KanbanItem>
|
||||
))}
|
||||
</KanbanColumnContent>
|
||||
</KanbanColumn>
|
||||
))}
|
||||
</KanbanBoard>
|
||||
<KanbanOverlay><div className="bg-muted size-full rounded-md" /></KanbanOverlay>
|
||||
</Kanban>
|
||||
```
|
||||
|
||||
**Gotcha:** state is `Record<columnId, T[]>`. Each `KanbanColumnContent value` must match its parent `KanbanColumn value`. Omit `KanbanOverlay` and the drag preview silently breaks.
|
||||
|
||||
## sortable
|
||||
|
||||
**Required:** `value` (`T[]`), `onValueChange`, `getItemValue`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Sortable value={items} onValueChange={setItems} getItemValue={(i) => i.id}>
|
||||
{items.map((i) => (
|
||||
<SortableItem key={i.id} value={i.id}>
|
||||
<SortableItemHandle><GripVertical /></SortableItemHandle>
|
||||
{i.label}
|
||||
</SortableItem>
|
||||
))}
|
||||
</Sortable>
|
||||
```
|
||||
|
||||
**Gotcha:** a flat 1D reorder list (not columns - that is `kanban`). `getItemValue` must return a stable, unique string. Pass `layout="grid"` or `layout="nested"` for non-list layouts.
|
||||
|
||||
## filters
|
||||
|
||||
**Required:** `fields` (`FilterField[]`). The value is ONE `FilterQuery` tree - `query` + `onQueryChange`, or uncontrolled `defaultQuery`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
const fields: FilterField[] = [
|
||||
{ id: "title", label: "Title", type: "text" },
|
||||
{
|
||||
id: "status",
|
||||
label: "Status",
|
||||
type: "select",
|
||||
options: [
|
||||
{ value: "active", label: "Active" },
|
||||
{ value: "archived", label: "Archived" },
|
||||
],
|
||||
},
|
||||
]
|
||||
const [query, setQuery] = useState<FilterQuery>(() => createFilterQuery())
|
||||
|
||||
<Filters fields={fields} query={query} onQueryChange={setQuery} />
|
||||
```
|
||||
|
||||
**Gotcha:** the state is a TREE, not a list of chips. `FilterQuery` is a group of rules joined by `and`/`or` and a group may hold another group, so `(A and B) or C` is expressible; a rule is `{ id, type: "rule", path: ["status"], operator, value }` and `path` is the whole nested attribute path, root first. The pre-rewrite API is GONE: there is no `filters`/`onChange` prop, no `FilterFieldConfig` (fields are `FilterField`, nested through their own `fields`, keyed `id` not `key`), and no `createFilter()` - it minted ids inside a pure function and broke hydration, so ids now come from `createFilterIdFactory(seed)` seeded off `useId`, and `createFilterQuery()` / `createFilterRule()` take one. Read the query back with `flattenFilterConditions` (`{ path, field, operator, values, negated }` per rule, incomplete rules skipped) and walk the tree yourself when the parentheses carry meaning - the primitive compiles nothing, no SQL, no query string.
|
||||
|
||||
`variant` picks the chrome over that one query: `"basic"`, the default, is the flat chip row for a toolbar over a table; `"advanced"` is the condition builder, hung off a trigger or rendered in place with `advancedMode="inline"`. Both read and write the same tree, so a saved view built in one opens in the other. Other props worth knowing before you hand-roll them: `size` is two rungs, `"sm" | "default"`, resolved per style (there is no `lg`); `reorderable` turns on drag and Alt+Arrow row moves in the builder; `onBeforeQueryChange` is the ONE veto point for every write (return `false` to refuse, it cannot rewrite); `editors` registers custom value editors a field selects by `editor` name; `labels` / `operatorLabels` own every rendered string; `pathCollapse` + `maxPathSegments` shorten deep attribute paths; `renderChip` / `renderValue` / `renderEmpty` replace rendered parts. On a field, `loadOptions` supplies async options with paging and `resolveValues` renders a chip restored from a saved view whose option was never loaded. Pairs naturally with `data-grid`.
|
||||
|
||||
## cascader
|
||||
|
||||
**Required:** `items` (a tree of `{ value, label, children? }`), plus the panel parts inside `CascaderContent`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Cascader items={items} value={value} onValueChange={setValue}>
|
||||
<CascaderTrigger render={<Button variant="outline" />}>
|
||||
<CascaderValue placeholder="Select an attribute" />
|
||||
</CascaderTrigger>
|
||||
<CascaderContent className="w-80">
|
||||
<CascaderPanel>
|
||||
<CascaderNav>
|
||||
<CascaderBreadcrumb />
|
||||
<CascaderInput />
|
||||
</CascaderNav>
|
||||
<CascaderEmpty />
|
||||
<CascaderList maxHeight={288}>
|
||||
<CascaderItems />
|
||||
</CascaderList>
|
||||
<CascaderStatus />
|
||||
</CascaderPanel>
|
||||
</CascaderContent>
|
||||
</Cascader>
|
||||
```
|
||||
|
||||
**Gotcha:** pressing a branch NAVIGATES, it does not select - only leaves are selectable until you pass `selectable="any"` or a predicate, and once a branch is selectable its chevron becomes the only way to open it. `CascaderInput` must stay inside `CascaderContent` (Base UI refills the query from the selection when the input sits outside the popup). Always include `CascaderStatus`: it is the live region announcing level changes, which the visual breadcrumb does not provide to screen readers. Accepts a flat adjacency list via `getParent` as well as nested `children`. `searchScope="deep"` searches every level and annotates results with their path; `multiple` gives checkbox rows; `inline` + a bare `CascaderPanel` embeds it with no popover.
|
||||
|
||||
The shape above is `mode="drill"`, the default. `mode="tree"` keeps the same parts (drop `CascaderBreadcrumb`, pass `showBack={false}`, drive expansion with `expanded`/`onExpandedChange`); `mode="columns"` REPLACES `CascaderList` + `CascaderItems` with a single `CascaderColumns`, and has no breadcrumb. Other props worth knowing before you hand-roll them: `cascade` (multi-select only, parent/child selection with indeterminate branches - pair it with `selectable="any"`, since a leaf-only tree can never cascade), `indicator={false}` to drop the single-select check and its gutter (visual only, no-op with `multiple`), `virtualize`/`virtualizeThreshold` plus `CascaderVirtualItems` for long levels, and `getChildren` for async levels with cursor paging, retry on failure and optional `prefetch`. `CascaderFooter` pins commands below the list (`actions` is the quick path) and `CascaderSubmenu` opens one as a side-anchored flyout with the full menu keyboard model. To head a run of rows use `CascaderGroup` wrapping a `CascaderLabel` - a bare label inside a listbox names nothing and is dropped from the accessibility tree - and `CascaderSeparator` for the rule between runs. Every rendered string comes from `labels`, and the panel is RTL-correct under a `DirectionProvider` or `dir="rtl"`.
|
||||
|
||||
## date-selector
|
||||
|
||||
**Required:** none, but wire `onChange` to capture the value.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
const [value, setValue] = useState<DateSelectorValue | undefined>()
|
||||
|
||||
<DateSelector value={value} onChange={setValue} label="Due date" />
|
||||
```
|
||||
|
||||
**Gotcha:** the value is a structured `DateSelectorValue` (period / operator / start+end dates), NOT a `Date` - never pass a raw `Date`. Use `allowRange={false}` to lock single-date picking. Read `get_component("date-selector")` for the value shape.
|
||||
|
||||
## tree
|
||||
|
||||
**Required:** `tree` (a `@headless-tree/core` instance you construct)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Tree tree={tree}>
|
||||
{tree.getItems().map((item) => (
|
||||
<TreeItem key={item.getId()} item={item}>
|
||||
<TreeItemLabel />
|
||||
</TreeItem>
|
||||
))}
|
||||
</Tree>
|
||||
```
|
||||
|
||||
**Gotcha:** `Tree` is a styled shell - it takes a headless-tree instance via `tree`, NOT `data`/`items` props. Build the instance with `@headless-tree/react`. External API: https://headless-tree.lukasbach.com/
|
||||
|
||||
## stepper
|
||||
|
||||
**Required:** `StepperItem step` (number), `StepperContent value` (number)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Stepper defaultValue={1}>
|
||||
<StepperNav>
|
||||
<StepperItem step={1}>
|
||||
<StepperTrigger><StepperIndicator>1</StepperIndicator></StepperTrigger>
|
||||
<StepperSeparator />
|
||||
</StepperItem>
|
||||
<StepperItem step={2}>
|
||||
<StepperTrigger><StepperIndicator>2</StepperIndicator></StepperTrigger>
|
||||
</StepperItem>
|
||||
</StepperNav>
|
||||
<StepperPanel>
|
||||
<StepperContent value={1}>Step 1 content</StepperContent>
|
||||
<StepperContent value={2}>Step 2 content</StepperContent>
|
||||
</StepperPanel>
|
||||
</Stepper>
|
||||
```
|
||||
|
||||
**Gotcha:** steps are 1-indexed. Without `StepperPanel` + `StepperContent` you render the nav trail but no body. Put `StepperSeparator` in every `StepperItem` except the last.
|
||||
|
||||
## timeline
|
||||
|
||||
**Required:** `TimelineItem step` (number)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Timeline>
|
||||
<TimelineItem step={1}>
|
||||
<TimelineHeader>
|
||||
<TimelineDate>March 2024</TimelineDate>
|
||||
<TimelineTitle>Project initialized</TimelineTitle>
|
||||
</TimelineHeader>
|
||||
<TimelineIndicator />
|
||||
<TimelineSeparator />
|
||||
<TimelineContent>Repo and architecture set up.</TimelineContent>
|
||||
</TimelineItem>
|
||||
</Timeline>
|
||||
```
|
||||
|
||||
**Gotcha:** each item needs a unique `step`. `orientation` is `"vertical"` (default) or `"horizontal"`. This is a static event display, not interactive like `stepper`.
|
||||
|
||||
## autocomplete
|
||||
|
||||
**Required:** `items` (array; each item has at least `value`)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Autocomplete items={items}>
|
||||
<AutocompleteInput placeholder="Search..." />
|
||||
<AutocompleteContent>
|
||||
<AutocompleteEmpty>No results found.</AutocompleteEmpty>
|
||||
<AutocompleteList>
|
||||
{(item) => (
|
||||
<AutocompleteItem key={item.value} value={item}>{item.label}</AutocompleteItem>
|
||||
)}
|
||||
</AutocompleteList>
|
||||
</AutocompleteContent>
|
||||
</Autocomplete>
|
||||
```
|
||||
|
||||
**Gotcha:** `AutocompleteList` takes a render-prop `(item) => ReactNode`, NOT a mapped array of children. External API: https://base-ui.com/react/components/autocomplete
|
||||
|
||||
## phone-input
|
||||
|
||||
**Required:** none, but wire `onChange`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<PhoneInput placeholder="Enter phone number" defaultCountry="US" value={value} onChange={setValue} />
|
||||
```
|
||||
|
||||
**Gotcha:** `value`/`onChange` use an E.164 string (e.g. `"+14155551234"`), not a display-formatted string; `onChange` can fire `undefined`. `defaultCountry` is a 2-letter ISO code. Wraps `react-phone-number-input`.
|
||||
|
||||
## number-field
|
||||
|
||||
**Required:** wrap the controls in `NumberFieldGroup`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<NumberField defaultValue={0}>
|
||||
<NumberFieldScrubArea label="Quantity" />
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
```
|
||||
|
||||
**Gotcha:** import from `@/components/ui/number-field`. The accessible label goes on `NumberFieldScrubArea`, not `NumberField`. External API: https://base-ui.com/react/components/number-field
|
||||
|
||||
## rating
|
||||
|
||||
**Required:** `rating` (number)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Rating rating={4.5} showValue editable onRatingChange={setRating} />
|
||||
```
|
||||
|
||||
**Gotcha:** supports decimals (partial stars). Pass `editable` + `onRatingChange` for interactive input; omit both for a read-only display.
|
||||
|
||||
## scrollspy
|
||||
|
||||
**Required:** `targetRef` (the scroll container ref)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Scrollspy targetRef={containerRef}>
|
||||
<a href="#s1" data-scrollspy-anchor="s1">Section 1</a>
|
||||
<a href="#s2" data-scrollspy-anchor="s2">Section 2</a>
|
||||
</Scrollspy>
|
||||
<div ref={containerRef}>
|
||||
<div id="s1">...</div>
|
||||
<div id="s2">...</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
**Gotcha:** each link's `data-scrollspy-anchor` must match a section `id`. `targetRef` is the scrollable container (defaults to the window).
|
||||
|
||||
## frame
|
||||
|
||||
**Required:** `Frame` > `FramePanel`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Frame>
|
||||
<FramePanel>
|
||||
<FrameHeader>
|
||||
<FrameTitle>Title</FrameTitle>
|
||||
<FrameDescription>Description</FrameDescription>
|
||||
</FrameHeader>
|
||||
<div className="p-5">Content</div>
|
||||
<FrameFooter>Footer</FrameFooter>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
```
|
||||
|
||||
**Gotcha:** a structured card shell for tool-like surfaces. `stacked` connects multiple panels with shared borders; `dense` removes panel padding; radius via the `--frame-radius` CSS variable.
|
||||
|
||||
## icon-stack
|
||||
|
||||
**Required:** one child icon
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<IconStack aria-hidden="true">
|
||||
<InboxIcon className="size-4" />
|
||||
</IconStack>
|
||||
```
|
||||
|
||||
**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.
|
||||
|
||||
## code-block
|
||||
|
||||
**Required:** `code` + `language`, or pre-highlighted `lines`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<CodeBlock code={code} language="tsx" />
|
||||
|
||||
<CodeBlock code={code} language="tsx" showLineNumbers maxLines={20}>
|
||||
<CodeBlockHeader>
|
||||
<CodeBlockTitle>use-totals.ts</CodeBlockTitle>
|
||||
<CodeBlockLanguage />
|
||||
<CodeBlockCopyButton className="ml-auto" />
|
||||
</CodeBlockHeader>
|
||||
<CodeBlockExpandButton />
|
||||
</CodeBlock>
|
||||
```
|
||||
|
||||
**Gotcha:** the one-liner is already a complete block; every child (header, title, language label, copy button, wrap toggle, expand button, line actions) is optional chrome, at any depth. Shiki is the only npm dependency and loads lazily, one chunk per language, on first highlight; `lines` (from `highlightCode` in `code-block-highlight`, which is server-safe and has no `"use client"`) or `highlight={false}` loads nothing at all. `maxLines` caps the height AND marks the block collapsible, which is what makes `CodeBlockExpandButton` appear. Use `variant="ghost"` when the block sits inside a surface that already has a border.
|
||||
|
||||
## alert
|
||||
|
||||
**Required:** `Alert` > `AlertTitle`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Alert variant="success">
|
||||
<ShieldCheckIcon />
|
||||
<AlertTitle>Security update</AlertTitle>
|
||||
<AlertDescription>Enable two-factor authentication.</AlertDescription>
|
||||
<AlertAction><Button size="xs">Update</Button></AlertAction>
|
||||
</Alert>
|
||||
```
|
||||
|
||||
**Gotcha:** shadcn-compatible API. `variant`: `default | destructive | info | success | warning | invert`. The non-default variants use ReUI extended color tokens (`--success`/`--info`/`--warning`/`--invert`), which the install adds. Defer generic alert rules to the shadcn skill.
|
||||
|
||||
## badge
|
||||
|
||||
**Required:** none (text child).
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Badge variant="success-light" size="sm">Success</Badge>
|
||||
<Badge variant="outline" radius="full">Pill</Badge>
|
||||
```
|
||||
|
||||
**Gotcha:** shadcn-compatible. Rich `variant` set (solid, `-outline`, `-light` per color), `size` `xs..xl`, `radius` `default | full`. Like `alert`, the color variants rely on ReUI extended tokens. Prefer `Badge` variants over raw color classes for statuses.
|
||||
|
||||
## base vs radix - write for the project's base
|
||||
|
||||
ReUI ships every component in two builds: `base` (Base UI) and `radix` (Radix UI). The install command and name are identical, and the CLI installs the build matching the project. But you must write/adapt code against the **right base**, because their APIs differ.
|
||||
|
||||
**Detect the base first.** Read `components.json` -> `style` and take the segment before the first `-`:
|
||||
|
||||
- `"style": "base-nova"` -> **Base UI**
|
||||
- `"style": "radix-nova"` -> **Radix UI**
|
||||
|
||||
**Then use that base's API.** The deltas mirror shadcn's base-vs-radix split:
|
||||
|
||||
- Slot/composition: Base UI `render={<… />}` vs Radix `asChild`.
|
||||
- `Select`: Base UI takes `items`; Radix uses `<SelectItem>` children.
|
||||
- `ToggleGroup`: Base UI `multiple` boolean vs Radix `type="single" | "multiple"`.
|
||||
|
||||
The safest path is to **read the installed files and `c-*` examples** - they're already in your base, so reuse their wiring instead of guessing. When `get_component`'s inline `api` or an example shows the other base's shape, translate it to your base (or `validate_usage` to confirm). Defer the generic base/radix mechanics to the shadcn skill.
|
||||
@@ -1,45 +0,0 @@
|
||||
# Craft: make ReUI UI exceptional, not generic
|
||||
|
||||
ReUI items ship senior-designer quality. Your adaptation has to hold that bar, so the result reads like a real product surface a team would keep - not a wireframe an AI generated. Use these alongside the reuse rules in [adapting.md](./adapting.md).
|
||||
|
||||
## Have a point of view
|
||||
|
||||
Pick an emotional register before you compose - calm, operational, premium, editorial, dense, energetic - and let layout, spacing, surface treatment, and icon behavior all reinforce it. One or two memorable decisions and restraint everywhere else beats ten generic ones. UI with no point of view reads as generated.
|
||||
|
||||
## Brutally clear hierarchy
|
||||
|
||||
One focal point per card or panel: the dominant metric or task first, its label second, supporting detail third. The first thing the eye lands on should be the right thing; secondary text must read as secondary. Borders, separators, and surfaces do real work to create 2-3 information bands - don't flatten everything to equal weight.
|
||||
|
||||
## Spacing rhythm and deliberate density
|
||||
|
||||
Gaps are a signal, not a default. Keep them intentional and consistent within a family (`gap-1`/`gap-2` for tight operational rows, larger gaps for section breaks), and smaller within a group than between groups. Match the surrounding ReUI density; don't pad an operational surface like a marketing page, and don't drift density mid-section. The composition should still feel authored in grayscale.
|
||||
|
||||
## Cover the real states (the usual miss)
|
||||
|
||||
A surface isn't done at the happy path. Compose, and wire:
|
||||
|
||||
- **Empty** - a purposeful empty state (short message + the primary action), never a blank panel.
|
||||
- **Loading** - a **skeleton** that matches the real layout, not a centered spinner.
|
||||
- **Error** - an inline, recoverable error with a retry, announced via `role="status"`/`aria-live`.
|
||||
|
||||
Derive these from an element the block already has (don't invent parallel markup), or `get_examples` for a state-specific example.
|
||||
|
||||
## Responsive by default
|
||||
|
||||
Mobile-first, not mobile-afterthought. In constrained rows/cards/sidebars, put `min-w-0` on the shrinking container and `truncate` long single-line labels; protect the primary label's width and let secondary content compress. Reflow layouts (multi-column -> single column) rather than just shrinking them. Desktop and mobile should both look designed.
|
||||
|
||||
## Motion, subtly
|
||||
|
||||
Motion should clarify, not decorate. Use ReUI Motion Icons on primary actions for a subtle hover cue; keep transitions short (~200-300ms) with calm easing; prefer a skeleton pulse over a spinner. No bouncing, no gratuitous entrance animations on every element.
|
||||
|
||||
## Real, activated content
|
||||
|
||||
Use believable, typed data (realistic labels, counts, timestamps, statuses that map to a real workflow) - never lorem or abstract filler. Every visible control does something: no decorative buttons, fake tabs, meaningless toggles, or stats with no job. It must still hold with long names, empty values, and crowded data.
|
||||
|
||||
## Avoid the AI tells
|
||||
|
||||
These instantly read as generated - don't ship them: equal-weight card walls, empty gradients, repetitive padding everywhere, generic enterprise copy, ornamental icons, and number tiles that don't earn their place.
|
||||
|
||||
## The bar
|
||||
|
||||
Before you finish, ask: **would a product team keep this instead of replacing it? Does it still feel strong after swapping in real content?** If not, reuse the shipped ReUI design harder - don't restyle it into something new - then run the [quality.md](./quality.md) gates.
|
||||
@@ -1,39 +0,0 @@
|
||||
# Icons (ReUI delta over shadcn)
|
||||
|
||||
Follow the shadcn icon rules (use the project's configured `iconLibrary`, `data-icon` on icons inside `Button`, no sizing classes on icons inside components, pass icons as component objects not string keys). ReUI adds the following.
|
||||
|
||||
## Portable icons (library-agnostic)
|
||||
|
||||
ReUI components, examples, and blocks are authored to be icon-library-agnostic. When `iconLibrary` is set in `components.json`, the shadcn CLI installs each item's icons in **your** library automatically - you swap nothing. If an installed item's icons don't match your project (for example `iconLibrary` isn't set, so they came in from the item's demo library), change the **import source and component name** to your library, keeping the same icon-name semantics:
|
||||
|
||||
- `lucide` -> `lucide-react`
|
||||
- `tabler` -> `@tabler/icons-react`
|
||||
- `phosphor` -> `@phosphor-icons/react`
|
||||
- `remix` -> `@remixicon/react`
|
||||
- `hugeicons` -> `@hugeicons/react`
|
||||
|
||||
Don't assume `lucide-react`; read `iconLibrary` from `components.json`.
|
||||
|
||||
## Keep icons purposeful
|
||||
|
||||
Icons support the hierarchy, they don't replace it: keep them small, matched to the surrounding density, and decorative ones `aria-hidden="true"` (an icon-only control still needs an accessible label on the control). Don't add ornamental icons that do no job.
|
||||
|
||||
## Motion Icons (the `@reui/icons/...` set)
|
||||
|
||||
ReUI ships its own icon set in 4 styles (outline, solid, duotone, filled), each icon in two variants:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add @reui/icons/default/<style>/<name> --yes # static
|
||||
npx shadcn@latest add @reui/icons/animated/<style>/<name> --yes # hover-animated (motion/react)
|
||||
```
|
||||
|
||||
Finding them via the MCP is free; installing requires an Ultimate license (`REUI_LICENSE_KEY`, see [cli.md](./cli.md)). Reach for a Motion Icon on a primary action when a subtle hover cue helps; keep motion restrained.
|
||||
|
||||
Finding icons:
|
||||
|
||||
- Several icons (the common case): **`search_icons(concepts[])`** - up to 24 concepts in one call, the best icons per concept with install commands. Pass `animated: true` to get only icons with a hover-animated Motion variant.
|
||||
- One icon: `search` with `type: "icon"`.
|
||||
- Icon results and `get_icon` carry `animated: true` and `installAnimated` when an animated variant exists - use those install strings, do not construct paths by hand.
|
||||
- Every icon result carries a `previewUrl` (its live icon-category page) - **share it with the user** so they can SEE the icon before installing.
|
||||
|
||||
The `icon-stack` component composes multiple icons into a stacked display.
|
||||
@@ -1,22 +0,0 @@
|
||||
# Quality gates (security, accessibility, scroll)
|
||||
|
||||
These are the **done gate**, not a nice-to-have: before you call any ReUI work finished, call the MCP `get_audit_checklist` tool and pass every item below (plus the craft bar in [craft.md](./craft.md)). Then typecheck and lint.
|
||||
|
||||
## Security
|
||||
|
||||
- Never `dangerouslySetInnerHTML`. Render data as text/components.
|
||||
- External links (`target="_blank"`) must always pair `rel="noopener noreferrer"`.
|
||||
- No real PII, secrets, or tokens in demo or committed code. Remote media only from sources the project already allows.
|
||||
|
||||
## Accessibility
|
||||
|
||||
- Implicit list/card items that navigate get real anchors with a standard hover affordance.
|
||||
- Icon-only or numeric buttons need an `aria-label`; decorative icons get `aria-hidden`.
|
||||
- Every non-submit button is `type="button"`.
|
||||
- Keyboard + focus: everything interactive is reachable in a sensible Tab order with a visible focus ring; layers (dialogs/sheets/menus) trap focus and close on `Escape`. ReUI components ship standard keyboard behavior - read each component's inline `api` rather than re-implementing it.
|
||||
- Announce async UI: loading and error messages use `role="status"` / `aria-live` so they're not silent to screen readers.
|
||||
|
||||
## Scroll mechanics
|
||||
|
||||
- Make scroll regions with a parent-owned height: a `min-h-0` + flex chain down to the scroll container. Never guess a `max-h`.
|
||||
- The scroll container owns `overflow-auto`; ancestors stay `min-h-0` so the height resolves.
|
||||
@@ -1,35 +0,0 @@
|
||||
# ReUI registry structure
|
||||
|
||||
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 22 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).
|
||||
|
||||
## The @reui registry
|
||||
|
||||
Install everything through the shadcn CLI: `npx shadcn@latest add @reui/<name> --yes`. The CLI reads the `@reui` registry from the project's `components.json`. Free items need only the plain string form:
|
||||
|
||||
```json
|
||||
{ "registries": { "@reui": "https://reui.io/r/{style}/{name}.json" } }
|
||||
```
|
||||
|
||||
Premium installs need the authenticated form + `REUI_LICENSE_KEY` in `.env.local` - see [cli.md](./cli.md). The MCP `get_project_context` tool returns the right config.
|
||||
|
||||
## Know your base: base or radix
|
||||
|
||||
ReUI ships every item in two builds - `base` (Base UI) and `radix` (Radix UI) - with mirrored names. The CLI installs the build matching your project automatically, but **you must write code against the right base's API**. Detect it from `components.json` -> `style`: the segment before the first `-` is the base (`base-nova` -> Base UI, `radix-nova` -> Radix UI). The installed files and `c-*` examples are already in your base - read them and adapt on that base. See [components.md](./components.md) for the API deltas.
|
||||
|
||||
**So the MCP's own `docsUrl` and `previewUrl` match your base**, send your `style` to the MCP: add `?style=<your components.json style>` to the ReUI MCP server URL (or set an `X-Reui-Style` header) in your MCP client config - set once, applies to every call. The MCP then resolves docs/preview links to YOUR library (`/docs/components/radix/...`, `/preview/radix/...` for a radix project) instead of the default base; `get_project_context` echoes back the style it currently sees so you can confirm it. Install commands are unaffected (the CLI already installs the right variant). If you notice the MCP returning `base` links for a `radix` project, tell the user to add `?style=` to the server URL.
|
||||
|
||||
Blocks adapt to your active theme through semantic tokens and CSS variables - change the theme and every block follows.
|
||||
|
||||
## Free vs premium
|
||||
|
||||
- **Free, no key:** the 22 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
|
||||
|
||||
The canonical index of every component's API docs is **https://reui.io/llms.txt** (returned as `componentsApiUrl` in MCP results). Prefer the inline `api` from `get_component`; use the index/docs as the fallback.
|
||||
@@ -1,26 +0,0 @@
|
||||
# Styling (ReUI delta over shadcn)
|
||||
|
||||
Follow the shadcn skill for the generic rules (semantic colors not raw values, `gap-*` not `space-y-*`, `size-*`, `cn()`, no manual `dark:` overrides, no overlay `z-index`). This file is only the ReUI-specific additions.
|
||||
|
||||
## ReUI extended semantic tokens
|
||||
|
||||
ReUI adds semantic tokens beyond shadcn's base set. Use these instead of raw colors for status and emphasis:
|
||||
|
||||
- `--success` / `--success-foreground`
|
||||
- `--info` / `--info-foreground`
|
||||
- `--warning` / `--warning-foreground`
|
||||
- `--destructive-foreground` (paired with shadcn's `--destructive`)
|
||||
- `--invert` / `--invert-foreground` (inverted surfaces)
|
||||
|
||||
Use them as Tailwind utilities (`bg-success text-success-foreground`, `text-warning`, ...). They are defined in the project's global CSS and registered with Tailwind (`@theme inline` on v4). If a token is missing in the project, add it to the global CSS file (never a new file) following the same `name` / `name-foreground` convention, exactly as the shadcn customization rules describe.
|
||||
|
||||
**Incorrect:** `<span className="text-green-600">Active</span>`
|
||||
**Correct:** `<Badge variant="success">Active</Badge>` or `<span className="text-success">Active</span>`
|
||||
|
||||
## Blocks follow your theme
|
||||
|
||||
When you install a block it adapts to your active theme through the semantic tokens above and the project's CSS variables. Don't hardcode style-specific values into installed block code and don't fork it to "restyle" - change the theme via the CSS variables / a preset and every block follows. Want a different look? `search` for a block whose design already fits instead of re-skinning one.
|
||||
|
||||
## Density and typography rhythm
|
||||
|
||||
ReUI operational UI usually feels dense, not airy. Keep the gap between a title and its supporting description tight by default (`gap-0.5`, `space-y-1`, or `space-y-px`), and smaller than the gap between sections. Match the surrounding ReUI density when you add rows or fields; do not pad operational surfaces like a marketing page.
|
||||
@@ -1,54 +0,0 @@
|
||||
# Workflow: find -> install -> read API -> adapt
|
||||
|
||||
The core ReUI loop. The MCP tells you what to install and gives you the API; the shadcn CLI installs it; you turn the installed files into correct, themed, data-wired code by **reuse**, not redesign.
|
||||
|
||||
## 1. Find (ReUI MCP `search` / `compose_page`)
|
||||
|
||||
**Full multi-section page ask?** Call `compose_page(intent, sections?)` FIRST, before searching block-by-block. It returns ordered sections, each with the best block for the intent (top pick + alternates); sections listed in `unavailableSections` have no real inventory - compose those from components, do not force a bad block.
|
||||
|
||||
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 22 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`.
|
||||
|
||||
Example: "build a users management page with filters" -> `search({ query: "users management page with filters", type: "block", component: "data-grid", features: ["filters"] })`.
|
||||
|
||||
Each result has `install`, `previewUrl`, `docsUrl`, `componentsUsed`, `score`, `termCoverage`, and `whyMatch`. `score` is relative to the top hit (the top is ~100 by construction), not an absolute quality - compare results to each other, and show the user the top options if several score closely; do not silently guess. A low `termCoverage` means a weak match even with a high score - rephrase or widen.
|
||||
|
||||
**Always show the preview link.** Whenever you list or recommend items - from `search`, `search_icons`, `list_components`, `compose_page`, or a getter - include each item's `previewUrl` (a live preview page) so the user can SEE it before you install. Blocks and examples link to an individual live preview; icons and components to their live category/component page. This applies to every listing, not only a single pick.
|
||||
|
||||
## 2. Install (shadcn CLI)
|
||||
|
||||
Run the result's `install` command from the project root, non-interactively:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add @reui/<name> --yes
|
||||
```
|
||||
|
||||
The CLI reads `components.json`, installs the correct base+style variant, resolves `registryDependencies` (a block pulls in its components), installs npm deps, and rewrites aliases. Do not pass the base/style. See [cli.md](./cli.md).
|
||||
|
||||
## 3. Read the API (do not guess props)
|
||||
|
||||
Before writing code against any component an item uses:
|
||||
|
||||
1. The item's `componentDigests` already give a 1-line contract per component - often enough to wire it. For the full API, call **`get_component(names)`** with ALL of `componentsUsed` in ONE call (it accepts an array) and read each inline `api` - no web fetch. **Share the component's `docsUrl`** (its 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.
|
||||
2. Call **`get_examples(name)`** for the free `c-*` examples of that component; install one and **read the added files** to copy the exact composition. This is the fastest correct path - the example shows real wiring you adapt, not invent.
|
||||
3. About to write a prop you did not see in an `api` or installed file? Run **`validate_usage`** BEFORE writing the code - per-prop documented / notDocumented verdicts plus did-you-mean suggestions. notDocumented means read the API, not push on.
|
||||
|
||||
## 4. Adapt (reuse-first) - do not skip
|
||||
|
||||
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 `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)).
|
||||
5. **Validate before finalizing**: if your adaptation introduced components or props you did not read in an `api` or example, run `validate_usage` on them.
|
||||
6. **Hit the craft bar** - clear hierarchy, deliberate density, the empty / loading / error states, subtle motion, and mobile-first responsiveness (see [craft.md](./craft.md)). Generic-looking output means you under-reused the design, not that it needs restyling.
|
||||
7. **Pass the quality gates** (security, a11y, scroll) - call the MCP `get_audit_checklist` tool and clear every item (see [quality.md](./quality.md)).
|
||||
8. **Typecheck / lint**.
|
||||
|
||||
## If no single block fits
|
||||
|
||||
Compose from components (`compose_page` tells you which sections have no block inventory via `unavailableSections`). `search` the components you need, read each `get_component` API, install a worked `get_examples` example for each, and assemble by adapting those examples. A block in the same category is a useful reference - install it and read its files to see how ReUI composes those components, then adapt.
|
||||
@@ -1,58 +0,0 @@
|
||||
# ReUI MCP: full reference
|
||||
|
||||
The ReUI MCP (`https://mcp.reui.io`, Streamable HTTP) is free to use but needs a ReUI account: on first use the agent signs in with ReUI (a free account is created if the user has none), so every request is tied to an account. Free covers components and examples; a Pro or Ultimate license unlocks premium blocks and Motion Icons and removes the daily request limit. It does **discovery + guidance** (search, inline APIs, page planning, validation) and never serves source; the shadcn CLI does **installation**, and the license key lives there (the `@reui` entry in `components.json`, backed by `.env.local`). Goal: from the user's intent to correct, themed, data-wired ReUI code in the **fewest tokens and calls**, with **no guessing**.
|
||||
|
||||
## Golden path (token-optimal - follow this order)
|
||||
|
||||
Most tasks need 2-4 MCP calls and ZERO web fetches:
|
||||
|
||||
1. **`search(query, ...hints)`** -> pick the top 1-3 results. Each result already carries `install`, `previewUrl`, `docsUrl`, `componentsUsed`, `score`, `whyMatch`. The payload is complete - do not call another tool just to "confirm" a result.
|
||||
2. **`get_component([...componentsUsed])`** in ONE batched call (one name or an array of up to 20) -> read each inline `api`. This **replaces** fetching docs pages. Often skippable: search responses carry `componentDigests`, a compact API contract per referenced component.
|
||||
3. **`get_examples(component)`** -> install ONE returned `c-*` example, read the added files, copy the composition.
|
||||
4. **`get_install_command(item)`** only to validate a name you are unsure of (results already include `install`). Run the install with the shadcn CLI (`--yes`).
|
||||
5. **`get_audit_checklist()`** before declaring done.
|
||||
|
||||
If you already know the exact item name, skip `search`. Everything else is situational.
|
||||
|
||||
## The 5 task-specific tools (when to reach for each)
|
||||
|
||||
- **`compose_page`** - BEFORE building any full page (dashboard, settings, billing, landing). Pass the intent (and optionally the sections you want); it returns ordered sections, each with the best premium block for the intent (top pick + alternates). Sections with no real inventory are listed honestly in `unavailableSections` - compose those from components instead of forcing a bad block.
|
||||
- **`search_icons`** - whenever you need icons, especially several. Batch up to 24 concepts in one call; each concept returns its best icons with install commands. Pass `animated: true` to get only icons that have a hover-animated Motion variant.
|
||||
- **`validate_usage`** - BEFORE writing code with component names or props you have not read in an inline `api` or an installed example. It checks planned names + props against the indexed API docs and registry item names; returns did-you-mean suggestions and per-prop documented / notDocumented verdicts. Deterministic, no inference - a notDocumented prop means stop and read the API, not push on.
|
||||
- **`whats_new`** - when your registry knowledge might be stale (a name 404s, the user mentions an item you don't know). Returns items added/removed per build, newest first.
|
||||
- **`report_issue`** - when an installed item is actually broken (bad source, wrong dependency, broken preview). Goes straight to the ReUI team; rate-limited 5/hour. Not for usage questions.
|
||||
|
||||
## All 19 tools
|
||||
|
||||
`search`, `get_block`, `get_example`, `get_icon`, `list_block_groups`, `list_block_categories`, `list_example_categories`, `list_icon_categories`, `list_components`, `get_component`, `get_examples`, `search_icons`, `compose_page`, `validate_usage`, `whats_new`, `report_issue`, `get_install_command`, `get_project_context`, `get_audit_checklist`. The MCP serves the full parameter schemas; do not guess parameters beyond them.
|
||||
|
||||
## Token + speed rules
|
||||
|
||||
- **Batch `get_component`** - ONE call with the whole `componentsUsed` array, never N calls. Skip it entirely when `componentDigests` already answers the question.
|
||||
- **Read source by installing** - the MCP serves no source. To read or analyze an item's real code, install it with the shadcn CLI and open the local files. Learn an API from the inline `api` / `componentDigests`, never by reading raw source.
|
||||
- **Infer `search` hints yourself** (`type`, `component`, `category`, `features`, `free`) - hints shrink the result set and the tokens. Keep `limit` low; one right result beats ten.
|
||||
- Run independent calls (and the shadcn install) concurrently in one turn - serial tool calls are the main source of slowness.
|
||||
- Don't repeat a search for the same intent; don't call `list_*` to "see everything" - `search` is the entry point, `list_*` is only for browsing a taxonomy the user explicitly wants to explore.
|
||||
- Prefer `get_component`'s inline `api` over `docsUrl` / `/llms.txt`. Fetch a web page only as a last resort.
|
||||
|
||||
## Result shapes (so you don't re-fetch)
|
||||
|
||||
- `score` is 0-100 RELATIVE to the top hit (the top is ~100 by construction), not absolute - compare results to each other.
|
||||
- `termCoverage` (0-1) is the share of the query the item matched - low means a weak match even if the score looks high; rephrase or widen the search.
|
||||
- Each result carries `whyMatch`, `install`, docs/preview URLs, and a `free` flag; premium items carry `requiredPlan` (`"pro"` for blocks, `"ultimate"` for icons).
|
||||
- `componentDigests` is a top-level map: a compact API contract per referenced component - often enough to wire an item without a `get_component` call.
|
||||
- Icon results and `get_icon` include `animated: true` and `installAnimated` when a hover-animated Motion variant exists (animated: `@reui/icons/animated/<style>/<name>`; static: `@reui/icons/default/<style>/<name>`).
|
||||
|
||||
## Error playbook
|
||||
|
||||
- **401** - the MCP requires a signed-in ReUI account. The client prompts "Sign in with ReUI" (OAuth) on first use; a free account is created if needed. For headless/CI, pass a personal token (`reui_pat_...`, created at https://reui.io/account/mcp?ref=skill) as `Authorization: Bearer`.
|
||||
- **403 / locked result** - a valid account but the plan does not cover the item: premium blocks need Pro, Motion Icons need Ultimate. Point to https://reui.io/pricing?ref=skill (upgrade). Free accounts still get all components + examples.
|
||||
- **429** - rate limited (120 requests/min per IP); back off, honor `Retry-After`.
|
||||
- **not found** (`found: false`) - use the returned `suggestions`, or `search`; check `whats_new` if you suspect a stale name. Never run a fabricated install command.
|
||||
|
||||
## Fallbacks
|
||||
|
||||
- No ReUI MCP: `npx shadcn@latest search @reui -q "..."` then `add` (generic, no scoring / inline API).
|
||||
- The shadcn project's own MCP also works over the `@reui` registry: https://ui.shadcn.com/docs/mcp.
|
||||
|
||||
Per-agent MCP setup: https://reui.io/docs/mcp?ref=skill
|
||||
@@ -3,33 +3,3 @@ deploy/netflow-agent/*.py text eol=lf
|
||||
# Migration hashes authenticate exact reviewed bytes, including existing CRLF files.
|
||||
# Preserve those bytes on every checkout instead of applying core.autocrlf.
|
||||
backend/drizzle/*.sql -text
|
||||
|
||||
# Receipts pinned by SHA-256 over their exact CRLF bytes; keep them byte-for-byte.
|
||||
/docs/bandwidth-operator-effect-ledger.md -text
|
||||
/docs/bandwidth-operator-metadata-effect-contract.md -text
|
||||
/docs/mcp-2gb-operating-progress-20261028.json -text
|
||||
/docs/mcp-chr-ospf-source-cleanup.json -text
|
||||
/docs/mcp-chr-ssh-forwarding-policy-observation-v1.json -text
|
||||
/docs/mcp-db-connected-publisher-source-applied-20261102.json -text
|
||||
/docs/mcp-db-publisher-journal-lease-source-applied-20261102.json -text
|
||||
/docs/mcp-db-registry-fusion-acceptance-20261101.json -text
|
||||
/docs/mcp-db-registry-read-contract-acceptance-20261101.json -text
|
||||
/docs/mcp-guarded-peer-sources-acceptance-20261029.json -text
|
||||
/docs/mcp-ipsec-user-create-acceptance-v2.json -text
|
||||
/docs/mcp-linux-inventory-collector-raw-acceptance-20261101.json -text
|
||||
/docs/mcp-netflow-settings-acceptance-v2.json -text
|
||||
/docs/mcp-node-key-effect-progress-20261029.json -text
|
||||
/docs/mcp-operator-peer-metadata-managed-acceptance-20261028.json -text
|
||||
/docs/mcp-operator-public-metadata-progress-20261028.json -text
|
||||
/docs/mcp-portal-permission-catalog-source-applied-20261103.json -text
|
||||
/docs/mcp-public-registry-metadata-acceptance-20261028.json -text
|
||||
/docs/mcp-publisher-current-operator-linux-acceptance-20261103.json -text
|
||||
/docs/mcp-routing-manual-inverse-charge-reproduction-20261101.json -text
|
||||
/docs/mcp-routing-manual-inverse-charge-reproduction-20261101.md -text
|
||||
/docs/mcp-routing-manual-inverse-six-case-acceptance-20261101.json -text
|
||||
/docs/mcp-routing-manual-inverse-six-case-acceptance-20261101.md -text
|
||||
/docs/mcp-routing44-upgrade-bridge-acceptance-20261101.json -text
|
||||
/docs/mcp-server-poll-expiry-alignment-source-applied-20261102.json -text
|
||||
/docs/mcp-two-chr-v40-execution-20261106.json -text
|
||||
/docs/mcp-vrf-production-ticket-acceptance-v1.json -text
|
||||
/docs/netflow-agent.md -text
|
||||
@@ -19,39 +19,12 @@ jobs:
|
||||
tag: ${{ steps.release.outputs.tag }}
|
||||
bump: ${{ steps.release.outputs.bump }}
|
||||
release_url: ${{ steps.release.outputs.release_url }}
|
||||
backend_reuse_version: ${{ steps.changes.outputs.backend_reuse_version }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Check if the released backend can be reused
|
||||
id: changes
|
||||
shell: bash
|
||||
env:
|
||||
EVENT_NAME: ${{ gitea.event_name }}
|
||||
BEFORE_SHA: ${{ gitea.event.before }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ "$EVENT_NAME" != push || ! "$BEFORE_SHA" =~ ^[0-9a-f]{40}$ ]] ||
|
||||
! git merge-base --is-ancestor "$BEFORE_SHA" HEAD 2>/dev/null; then
|
||||
exit 0
|
||||
fi
|
||||
# Compare with a published release, including changes from any failed earlier run.
|
||||
BASE_TAG=$(git describe --tags --abbrev=0 --match 'v[0-9]*.[0-9]*.[0-9]*' "$BEFORE_SHA" 2>/dev/null || true)
|
||||
if [[ ! "$BASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || git diff --quiet "$BASE_TAG" HEAD --; then
|
||||
exit 0
|
||||
fi
|
||||
if git diff --quiet --no-renames "$BASE_TAG" HEAD -- . \
|
||||
':(exclude)app/**' ':(exclude)components/**' ':(exclude)lib/**' ':(exclude)shared/**' \
|
||||
':(exclude)entities/**' ':(exclude)public/**' ':(exclude)hooks/**' ':(exclude)tests/e2e/**' \
|
||||
':(exclude)Dockerfile.frontend' ':(exclude)next.config.ts' ':(exclude)tsconfig.json' \
|
||||
':(exclude)postcss.config.mjs' ':(exclude)eslint.config.mjs' ':(exclude)components.json' \
|
||||
':(exclude,top,glob)playwright*.config.ts'; then
|
||||
echo "backend_reuse_version=${BASE_TAG#v}" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Test release version calculation
|
||||
run: node --test .ci/scripts/compute-release.test.mjs
|
||||
|
||||
@@ -69,21 +42,17 @@ jobs:
|
||||
test -f .ci/release/release-manifest.json
|
||||
|
||||
backend-test:
|
||||
needs: prepare-release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
if: needs.prepare-release.outputs.backend_reuse_version == ''
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node 22
|
||||
if: needs.prepare-release.outputs.backend_reuse_version == ''
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
- name: Start PostgreSQL 18
|
||||
if: needs.prepare-release.outputs.backend_reuse_version == ''
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -124,7 +93,6 @@ jobs:
|
||||
exit 1
|
||||
|
||||
- name: Install and test backend
|
||||
if: needs.prepare-release.outputs.backend_reuse_version == ''
|
||||
shell: bash
|
||||
env:
|
||||
REQUIRE_TEST_POSTGRES: "1"
|
||||
@@ -144,7 +112,7 @@ jobs:
|
||||
npm run test --prefix backend
|
||||
|
||||
- name: Stop PostgreSQL
|
||||
if: always() && needs.prepare-release.outputs.backend_reuse_version == ''
|
||||
if: always()
|
||||
shell: bash
|
||||
run: docker rm -f "${PG_CONTAINER:-}" 2>/dev/null || true
|
||||
|
||||
@@ -155,7 +123,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
if: needs.prepare-release.outputs.backend_reuse_version == ''
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Configure backend image name
|
||||
@@ -168,7 +135,6 @@ jobs:
|
||||
echo "IMAGE_NAME=${{ env.REGISTRY }}/${owner}/${stem}-backend" >> "${GITHUB_ENV}"
|
||||
|
||||
- name: Prepare backend build context
|
||||
if: needs.prepare-release.outputs.backend_reuse_version == ''
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -208,7 +174,6 @@ jobs:
|
||||
password: ${{ secrets.ACTIONS_PAT }}
|
||||
|
||||
- name: Build and push backend image
|
||||
if: needs.prepare-release.outputs.backend_reuse_version == ''
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .ci/docker/backend
|
||||
@@ -230,18 +195,6 @@ jobs:
|
||||
org.opencontainers.image.revision=${{ gitea.sha }}
|
||||
org.opencontainers.image.created=${{ gitea.event.head_commit.timestamp }}
|
||||
|
||||
- name: Tag the existing backend image for this release
|
||||
if: needs.prepare-release.outputs.backend_reuse_version != ''
|
||||
shell: bash
|
||||
env:
|
||||
BACKEND_VERSION: ${{ needs.prepare-release.outputs.backend_reuse_version }}
|
||||
RELEASE_VERSION: ${{ needs.prepare-release.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker buildx imagetools create --prefer-index=false \
|
||||
--tag "$IMAGE_NAME:$GITHUB_SHA" --tag "$IMAGE_NAME:$RELEASE_VERSION" \
|
||||
"$IMAGE_NAME:$BACKEND_VERSION"
|
||||
|
||||
frontend-image:
|
||||
needs: prepare-release
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -16,7 +16,7 @@ permissions:
|
||||
packages: write
|
||||
jobs:
|
||||
backend-preview:
|
||||
if: ${{ gitea.event_name == 'workflow_dispatch' }}
|
||||
if: ${{ gitea.event_name == 'workflow_dispatch' && gitea.ref == 'refs/heads/codex/mcp-acceptance-current-20261103' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 40
|
||||
env:
|
||||
@@ -24,6 +24,7 @@ jobs:
|
||||
EXPECTED_SHA: ${{ inputs.expected_sha }}
|
||||
DISPATCH_SHA: ${{ gitea.sha }}
|
||||
DISPATCH_EVENT: ${{ gitea.event_name }}
|
||||
DISPATCH_REF: ${{ gitea.ref }}
|
||||
REPOSITORY: ${{ gitea.repository }}
|
||||
RUN_ID: ${{ gitea.run_id }}
|
||||
RUN_ATTEMPT: ${{ gitea.run_attempt }}
|
||||
@@ -42,6 +43,7 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$DISPATCH_EVENT" = workflow_dispatch
|
||||
test "$DISPATCH_REF" = refs/heads/codex/mcp-acceptance-current-20261103
|
||||
[[ "$EXPECTED_SHA" =~ ^[0-9a-f]{40}$ ]]
|
||||
test "$EXPECTED_SHA" = "$DISPATCH_SHA"
|
||||
test "$(git rev-parse HEAD)" = "$EXPECTED_SHA"
|
||||
@@ -137,7 +139,7 @@ jobs:
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
frontend-preview:
|
||||
if: ${{ gitea.event_name == 'workflow_dispatch' }}
|
||||
if: ${{ gitea.event_name == 'workflow_dispatch' && gitea.ref == 'refs/heads/codex/mcp-acceptance-current-20261103' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 40
|
||||
env:
|
||||
@@ -145,6 +147,7 @@ jobs:
|
||||
EXPECTED_SHA: ${{ inputs.expected_sha }}
|
||||
DISPATCH_SHA: ${{ gitea.sha }}
|
||||
DISPATCH_EVENT: ${{ gitea.event_name }}
|
||||
DISPATCH_REF: ${{ gitea.ref }}
|
||||
REPOSITORY: ${{ gitea.repository }}
|
||||
RUN_ID: ${{ gitea.run_id }}
|
||||
RUN_ATTEMPT: ${{ gitea.run_attempt }}
|
||||
@@ -176,6 +179,7 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$DISPATCH_EVENT" = workflow_dispatch
|
||||
test "$DISPATCH_REF" = refs/heads/codex/mcp-acceptance-current-20261103
|
||||
[[ "$EXPECTED_SHA" =~ ^[0-9a-f]{40}$ ]]
|
||||
test "$EXPECTED_SHA" = "$DISPATCH_SHA"
|
||||
test "$(git rev-parse HEAD)" = "$EXPECTED_SHA"
|
||||
|
||||
@@ -78,9 +78,3 @@ backend/dist-operator/
|
||||
|
||||
# Agent-local permissions can contain commands with deployment credentials.
|
||||
/.claude/settings.local.json
|
||||
|
||||
# Local scratch and disposable build outputs (root-anchored).
|
||||
/tmp-*
|
||||
/.next-*/
|
||||
/.serena/
|
||||
/backend/dist-*/
|
||||
@@ -1,67 +0,0 @@
|
||||
---
|
||||
name: reui
|
||||
description: Use the ReUI registry from your AI agent - find, install, and correctly use ReUI components (the 22 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 `fe6742e29c`.** 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 22 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
|
||||
|
||||
The skill is free and this MCP is free to use; it just needs a ReUI account. On first use your agent opens a browser "Sign in with ReUI" prompt (a free account is created if you don't have one). Free covers components and examples with a daily request allowance; a Pro or Ultimate license unlocks premium blocks and Motion Icons and removes the limit (see [rules/registry.md](./rules/registry.md)). The same account and skill work in every agent and service the MCP connects to - this skill is agent-agnostic.
|
||||
|
||||
Skill + MCP are a team: this skill is the workflow (how to find, install, read the API, and adapt by reuse); the MCP is the live data and the hands (search, get_component, install commands). Your job: find the right item, install it with the shadcn CLI, read its real API, and **adapt by reuse** - wire real data and theme it; do not hand-roll or restyle what ReUI already provides. This skill **layers on the shadcn skill**: follow that for generic rules (spacing, `cn()`, semantic colors, forms); follow this for everything ReUI-specific.
|
||||
|
||||
## The core loop (MCP-native)
|
||||
|
||||
1. **Find** - call the ReUI MCP `search` tool with the user's intent. It returns a ranked, scored list across components/examples/blocks/icons, each with an `install` command, `previewUrl`, `docsUrl`, and `componentsUsed`. Pass hints (`type`, `component`, `category`, `features`, `free`) when you can infer them.
|
||||
2. **Install** - run the returned command non-interactively (`npx shadcn@latest add @reui/<name> --yes`). The CLI resolves deps, aliases, and the base/style from `components.json`. See [cli.md](./rules/cli.md).
|
||||
3. **Read the API (on your base)** - first note your base from `components.json` -> `style` (`base-nova` -> Base UI, `radix-nova` -> Radix UI). For each component an item uses, call `get_component(name)` and read its **inline `api`** (no web fetch); then `get_examples(name)` to install a worked example and copy its composition - the installed files are already in your base. Whenever you work with a component's API, also **share its `docsUrl`** (the primitive's API documentation page) with the user so they have the full reference. See [components.md](./rules/components.md).
|
||||
4. **Adapt (reuse-first)** - swap demo data for real data, fix icon imports, align tokens. Do not redesign. See [adapting.md](./rules/adapting.md).
|
||||
|
||||
**Always show the preview.** Every item a tool returns carries a `previewUrl` (a live preview page). Whenever you list, recommend, or present ReUI items to the user - blocks, components, examples, or icons, whether from `search`, `search_icons`, `list_components`, `compose_page`, or any getter - include each item's `previewUrl` so they can SEE it before installing. Blocks and examples open an individual live preview; icons and components link to their live category/component page. Never present an item without its preview link.
|
||||
|
||||
If the ReUI MCP is not configured, fall back to `npx shadcn@latest search @reui -q "..."` then `add` - but the MCP gives scored matches + inline APIs; prefer it.
|
||||
|
||||
## Commands
|
||||
|
||||
Run ReUI as explicit slash commands (via the ReUI MCP) **or** just ask in plain language - both run the same workflow.
|
||||
|
||||
| Command | Invoke | Does |
|
||||
| ----------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
|
||||
| **build** | `/mcp__reui__build <what>` | Compose a page/section/feature from ReUI: plan → install → read API → adapt → craft → audit. |
|
||||
| **add** | `/mcp__reui__add <item>` | Find & install one component/example/block/icon and wire it in. |
|
||||
| **fix** | `/mcp__reui__fix [target]` | Diagnose & fix ReUI usage: wrong/undocumented props, base/radix mismatch, missing states, a11y/scroll. |
|
||||
| **improve** | `/mcp__reui__improve [target]` | Refine + extend existing ReUI UI to a production-exceptional bar (hierarchy, density, states, responsive, motion). |
|
||||
|
||||
Invocation differs slightly per agent (`/mcp__reui__build` in Claude Code/Cursor/Windsurf, `/mcp.reui.build` in VS Code). No command surface? Just describe what you want - this skill drives the identical loop.
|
||||
|
||||
## When to reach for ReUI vs plain shadcn
|
||||
|
||||
| Need | Reach for |
|
||||
| -------------------------------------------------------------------- | ------------------------------------------------------------------------- |
|
||||
| A full page or section (dashboard, billing, auth, pricing, settings) | `compose_page` first (plans sections + best blocks), then ReUI **blocks** |
|
||||
| A data table with sorting/filtering/pagination/virtualization | the **data-grid** component (never hand-roll a `<table>`) |
|
||||
| A drag-and-drop board | the **kanban** component |
|
||||
| Advanced column filtering, date range, tree, stepper, ... | the matching ReUI **component** |
|
||||
| A single generic control already in shadcn (Button, Dialog, Select) | plain **shadcn** |
|
||||
|
||||
## Detailed references
|
||||
|
||||
- [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 22 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)
|
||||
- [rules/styling.md](./rules/styling.md) - ReUI extended tokens, theme adaptation, density
|
||||
- [rules/icons.md](./rules/icons.md) - portable icons, swapping imports, Motion Icons (static + animated)
|
||||
- [tools.md](./tools.md) - the ReUI MCP: golden path, the 19 tools, token rules, result shapes, errors
|
||||
@@ -1,43 +0,0 @@
|
||||
# Adapting installed ReUI code (reuse-first, no AI slop)
|
||||
|
||||
ReUI items ship production-quality. Your job is to **adapt by reuse** - wire real data and fit the app - not to redesign or hand-roll. The output should look like ReUI built it for this product.
|
||||
|
||||
## Preserve the design - don't over-customize
|
||||
|
||||
The design IS the product. A ReUI block/component encodes senior-designer decisions: spacing, hierarchy, density, color treatment, and component choices. The fastest way to turn a premium block back into generic AI slop is to "improve" its look - so don't.
|
||||
|
||||
- Change **data, copy, and props**; keep the **structure and styling** it ships with. Make the **smallest** change that wires the real data. If your diff touches `className` / JSX structure more than data / props, you are over-customizing - stop and reuse.
|
||||
- Don't swap ReUI components for hand-rolled ones, restructure the layout, re-skin spacing / radius / colors, or add decorative chrome. Let the installed components carry the default spacing, radius, sizing, icon rhythm, density, and state styling; add custom Tailwind only when a component genuinely lacks a contract you need.
|
||||
- Want a different look? `search` for a block whose design already fits and reuse that - don't restyle this one into a new design.
|
||||
|
||||
## Reuse the parts: examples and the block's own elements
|
||||
|
||||
- **Examples are building parts.** A free `c-*` example is a correct, single-pattern composition you can reuse. Before composing from scratch, `get_examples(component)`, install the closest one, and reuse its wiring - assemble UI from examples instead of hand-rolling what an example already shows.
|
||||
- **Reuse a block's own elements.** Need more rows, cards, items, or sections than ship by default? Repeat the block's **existing** element by mapping real data through the same markup - never invent parallel markup that drifts from its design. Need a variant (empty / loading / expanded)? Derive it from an element the block already has.
|
||||
|
||||
## Don't invent (read, don't guess)
|
||||
|
||||
- Never write a prop, variant value, import path, or `@reui/...` name you didn't read in a component's inline `api`, an installed example, or a `search` result. If you didn't see it, treat it as nonexistent - call `get_component` / `get_examples` / `search` first, or run the MCP `validate_usage` tool to check planned names + props against the docs before writing code.
|
||||
- If a getter returns `found: false` or `search` returns nothing, say so and fall back (plain shadcn, or ask) - never fabricate an install command or an API.
|
||||
|
||||
## What to change vs leave alone
|
||||
|
||||
- **Change:** the item's own data, copy, props, and layout to fit the app.
|
||||
- **Leave alone:** installed component files, hooks, and the shared theme - do not edit vendored ReUI internals; change behavior through props and the documented API.
|
||||
- Blocks are **portable React** - no `next/link`, `next/image`, or other framework-runtime imports inside them. Keep them portable.
|
||||
|
||||
## Demo data -> real data
|
||||
|
||||
- Replace every placeholder with the user's real data. Model it as **typed data structures** and **map over arrays** - never duplicate JSX per row/card. Keep small block-specific formatters next to the data.
|
||||
- Wire the real source (columns, fields, fetch). For `data-grid`, implement the server fetch contract if the user needs server-side data.
|
||||
- **Type from the component API, derive during render.** Type domain state through the component's own types - e.g. map status to `BadgeProps["variant"]` via a typed `Record<Status, …>` - instead of stringly-typed values. Compute view state during render; don't mirror derived data into `useState`/`useEffect`.
|
||||
- **Adapt on the right base.** Use the API for the project's base (Base UI vs Radix - see [components.md](./components.md)); the installed files are already base-correct, so reuse their shape rather than translating from memory.
|
||||
|
||||
## Believable content (no AI tells)
|
||||
|
||||
- Use realistic labels, counts, timestamps, and statuses that map to a real workflow.
|
||||
- No decorative buttons, fake tabs, meaningless toggles, equal-weight card walls, empty gradients, ornamental icons, or generic SaaS filler. Every element should do something.
|
||||
|
||||
## Operational surfaces (settings / profile / admin)
|
||||
|
||||
Pick ONE archetype and keep the family consistent: a vertical rail (3-6 sections), horizontal tabs (5-8), or a frame/stack. Prefer `frame` for tool-like surfaces, a card for profile-like ones. Don't mix archetypes in one surface.
|
||||
@@ -1,60 +0,0 @@
|
||||
# CLI: registry setup, license, non-interactive install
|
||||
|
||||
## Registry setup (one-time, per project)
|
||||
|
||||
Free items (the 22 components and all `c-*` examples) need only the plain string registry in `components.json`:
|
||||
|
||||
```json
|
||||
{ "registries": { "@reui": "https://reui.io/r/{style}/{name}.json" } }
|
||||
```
|
||||
|
||||
Premium items (blocks; Motion Icons and templates) require a ReUI license at install:
|
||||
|
||||
1. Add the key to `.env.local`:
|
||||
|
||||
```bash
|
||||
REUI_LICENSE_KEY=your-license-key
|
||||
```
|
||||
|
||||
2. Switch `components.json` to the authenticated object form:
|
||||
|
||||
```json
|
||||
{
|
||||
"registries": {
|
||||
"@reui": {
|
||||
"url": "https://reui.io/r/{style}/{name}.json",
|
||||
"headers": { "Authorization": "Bearer ${REUI_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?ref=skill
|
||||
|
||||
## Installing
|
||||
|
||||
Use the project's package runner (check `packageManager`):
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add @reui/<name> --yes # npm
|
||||
pnpm dlx shadcn@latest add @reui/<name> --yes # pnpm
|
||||
bunx --bun shadcn@latest add @reui/<name> --yes # bun
|
||||
```
|
||||
|
||||
`--yes` skips confirmation prompts. The CLI auto-detects the package manager from the lockfile (there is no `--package-manager` flag). It also resolves the correct base+style variant from `components.json`, so do not pass a style.
|
||||
|
||||
## Handling prompts and conflicts
|
||||
|
||||
- **Always pass `--yes`** so the CLI does not block on confirmation prompts.
|
||||
- **Do NOT pass `--overwrite` by default.** If the CLI reports an existing file, read the output and resolve deliberately: install under a different name, adjust the path, or ask the user. Only use `--overwrite` when the user explicitly wants to replace a file.
|
||||
- **Preview first when touching an existing project**: `npx shadcn@latest add @reui/<name> --dry-run` shows what would change; `--diff <file>` shows a specific file's diff. Use these before overwriting.
|
||||
- Run from the **project root** so `components.json` and `.env.local` are found.
|
||||
|
||||
## Free vs premium boundary
|
||||
|
||||
- Public, no key: `c-*` examples and the 22 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?ref=skill (their key) or https://reui.io/pricing?ref=skill (upgrade).
|
||||
@@ -1,428 +0,0 @@
|
||||
# ReUI components
|
||||
|
||||
The 22 ReUI building blocks: `alert`, `autocomplete`, `badge`, `cascader`, `code-block`, `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 v9. It is NOT a styled `<table>` and does NOT take `data`/`columns` props directly. The contract:
|
||||
|
||||
- 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 = useTable({
|
||||
features: dataGridFeatures,
|
||||
data,
|
||||
columns,
|
||||
})
|
||||
|
||||
<DataGrid table={table} recordCount={data.length}>
|
||||
<DataGridTable />
|
||||
</DataGrid>
|
||||
```
|
||||
|
||||
Common mistakes:
|
||||
|
||||
- **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 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
|
||||
|
||||
**Required:** `value` (`Record<string, T[]>`), `onValueChange`, `getItemValue`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Kanban value={cols} onValueChange={setCols} getItemValue={(i) => i.id}>
|
||||
<KanbanBoard>
|
||||
{Object.entries(cols).map(([id, items]) => (
|
||||
<KanbanColumn key={id} value={id}>
|
||||
<KanbanColumnHandle><h3>{id}</h3></KanbanColumnHandle>
|
||||
<KanbanColumnContent value={id}>
|
||||
{items.map((i) => (
|
||||
<KanbanItem key={i.id} value={i.id}>
|
||||
<KanbanItemHandle>{i.title}</KanbanItemHandle>
|
||||
</KanbanItem>
|
||||
))}
|
||||
</KanbanColumnContent>
|
||||
</KanbanColumn>
|
||||
))}
|
||||
</KanbanBoard>
|
||||
<KanbanOverlay><div className="bg-muted size-full rounded-md" /></KanbanOverlay>
|
||||
</Kanban>
|
||||
```
|
||||
|
||||
**Gotcha:** state is `Record<columnId, T[]>`. Each `KanbanColumnContent value` must match its parent `KanbanColumn value`. Omit `KanbanOverlay` and the drag preview silently breaks.
|
||||
|
||||
## sortable
|
||||
|
||||
**Required:** `value` (`T[]`), `onValueChange`, `getItemValue`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Sortable value={items} onValueChange={setItems} getItemValue={(i) => i.id}>
|
||||
{items.map((i) => (
|
||||
<SortableItem key={i.id} value={i.id}>
|
||||
<SortableItemHandle><GripVertical /></SortableItemHandle>
|
||||
{i.label}
|
||||
</SortableItem>
|
||||
))}
|
||||
</Sortable>
|
||||
```
|
||||
|
||||
**Gotcha:** a flat 1D reorder list (not columns - that is `kanban`). `getItemValue` must return a stable, unique string. Pass `layout="grid"` or `layout="nested"` for non-list layouts.
|
||||
|
||||
## filters
|
||||
|
||||
**Required:** `fields` (`FilterField[]`). The value is ONE `FilterQuery` tree - `query` + `onQueryChange`, or uncontrolled `defaultQuery`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
const fields: FilterField[] = [
|
||||
{ id: "title", label: "Title", type: "text" },
|
||||
{
|
||||
id: "status",
|
||||
label: "Status",
|
||||
type: "select",
|
||||
options: [
|
||||
{ value: "active", label: "Active" },
|
||||
{ value: "archived", label: "Archived" },
|
||||
],
|
||||
},
|
||||
]
|
||||
const [query, setQuery] = useState<FilterQuery>(() => createFilterQuery())
|
||||
|
||||
<Filters fields={fields} query={query} onQueryChange={setQuery} />
|
||||
```
|
||||
|
||||
**Gotcha:** the state is a TREE, not a list of chips. `FilterQuery` is a group of rules joined by `and`/`or` and a group may hold another group, so `(A and B) or C` is expressible; a rule is `{ id, type: "rule", path: ["status"], operator, value }` and `path` is the whole nested attribute path, root first. The pre-rewrite API is GONE: there is no `filters`/`onChange` prop, no `FilterFieldConfig` (fields are `FilterField`, nested through their own `fields`, keyed `id` not `key`), and no `createFilter()` - it minted ids inside a pure function and broke hydration, so ids now come from `createFilterIdFactory(seed)` seeded off `useId`, and `createFilterQuery()` / `createFilterRule()` take one. Read the query back with `flattenFilterConditions` (`{ path, field, operator, values, negated }` per rule, incomplete rules skipped) and walk the tree yourself when the parentheses carry meaning - the primitive compiles nothing, no SQL, no query string.
|
||||
|
||||
`variant` picks the chrome over that one query: `"basic"`, the default, is the flat chip row for a toolbar over a table; `"advanced"` is the condition builder, hung off a trigger or rendered in place with `advancedMode="inline"`. Both read and write the same tree, so a saved view built in one opens in the other. Other props worth knowing before you hand-roll them: `size` is two rungs, `"sm" | "default"`, resolved per style (there is no `lg`); `reorderable` turns on drag and Alt+Arrow row moves in the builder; `onBeforeQueryChange` is the ONE veto point for every write (return `false` to refuse, it cannot rewrite); `editors` registers custom value editors a field selects by `editor` name; `labels` / `operatorLabels` own every rendered string; `pathCollapse` + `maxPathSegments` shorten deep attribute paths; `renderChip` / `renderValue` / `renderEmpty` replace rendered parts. On a field, `loadOptions` supplies async options with paging and `resolveValues` renders a chip restored from a saved view whose option was never loaded. Pairs naturally with `data-grid`.
|
||||
|
||||
## cascader
|
||||
|
||||
**Required:** `items` (a tree of `{ value, label, children? }`), plus the panel parts inside `CascaderContent`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Cascader items={items} value={value} onValueChange={setValue}>
|
||||
<CascaderTrigger render={<Button variant="outline" />}>
|
||||
<CascaderValue placeholder="Select an attribute" />
|
||||
</CascaderTrigger>
|
||||
<CascaderContent className="w-80">
|
||||
<CascaderPanel>
|
||||
<CascaderNav>
|
||||
<CascaderBreadcrumb />
|
||||
<CascaderInput />
|
||||
</CascaderNav>
|
||||
<CascaderEmpty />
|
||||
<CascaderList maxHeight={288}>
|
||||
<CascaderItems />
|
||||
</CascaderList>
|
||||
<CascaderStatus />
|
||||
</CascaderPanel>
|
||||
</CascaderContent>
|
||||
</Cascader>
|
||||
```
|
||||
|
||||
**Gotcha:** pressing a branch NAVIGATES, it does not select - only leaves are selectable until you pass `selectable="any"` or a predicate, and once a branch is selectable its chevron becomes the only way to open it. `CascaderInput` must stay inside `CascaderContent` (Base UI refills the query from the selection when the input sits outside the popup). Always include `CascaderStatus`: it is the live region announcing level changes, which the visual breadcrumb does not provide to screen readers. Accepts a flat adjacency list via `getParent` as well as nested `children`. `searchScope="deep"` searches every level and annotates results with their path; `multiple` gives checkbox rows; `inline` + a bare `CascaderPanel` embeds it with no popover.
|
||||
|
||||
The shape above is `mode="drill"`, the default. `mode="tree"` keeps the same parts (drop `CascaderBreadcrumb`, pass `showBack={false}`, drive expansion with `expanded`/`onExpandedChange`); `mode="columns"` REPLACES `CascaderList` + `CascaderItems` with a single `CascaderColumns`, and has no breadcrumb. Other props worth knowing before you hand-roll them: `cascade` (multi-select only, parent/child selection with indeterminate branches - pair it with `selectable="any"`, since a leaf-only tree can never cascade), `indicator={false}` to drop the single-select check and its gutter (visual only, no-op with `multiple`), `virtualize`/`virtualizeThreshold` plus `CascaderVirtualItems` for long levels, and `getChildren` for async levels with cursor paging, retry on failure and optional `prefetch`. `CascaderFooter` pins commands below the list (`actions` is the quick path) and `CascaderSubmenu` opens one as a side-anchored flyout with the full menu keyboard model. To head a run of rows use `CascaderGroup` wrapping a `CascaderLabel` - a bare label inside a listbox names nothing and is dropped from the accessibility tree - and `CascaderSeparator` for the rule between runs. Every rendered string comes from `labels`, and the panel is RTL-correct under a `DirectionProvider` or `dir="rtl"`.
|
||||
|
||||
## date-selector
|
||||
|
||||
**Required:** none, but wire `onChange` to capture the value.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
const [value, setValue] = useState<DateSelectorValue | undefined>()
|
||||
|
||||
<DateSelector value={value} onChange={setValue} label="Due date" />
|
||||
```
|
||||
|
||||
**Gotcha:** the value is a structured `DateSelectorValue` (period / operator / start+end dates), NOT a `Date` - never pass a raw `Date`. Use `allowRange={false}` to lock single-date picking. Read `get_component("date-selector")` for the value shape.
|
||||
|
||||
## tree
|
||||
|
||||
**Required:** `tree` (a `@headless-tree/core` instance you construct)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Tree tree={tree}>
|
||||
{tree.getItems().map((item) => (
|
||||
<TreeItem key={item.getId()} item={item}>
|
||||
<TreeItemLabel />
|
||||
</TreeItem>
|
||||
))}
|
||||
</Tree>
|
||||
```
|
||||
|
||||
**Gotcha:** `Tree` is a styled shell - it takes a headless-tree instance via `tree`, NOT `data`/`items` props. Build the instance with `@headless-tree/react`. External API: https://headless-tree.lukasbach.com/
|
||||
|
||||
## stepper
|
||||
|
||||
**Required:** `StepperItem step` (number), `StepperContent value` (number)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Stepper defaultValue={1}>
|
||||
<StepperNav>
|
||||
<StepperItem step={1}>
|
||||
<StepperTrigger><StepperIndicator>1</StepperIndicator></StepperTrigger>
|
||||
<StepperSeparator />
|
||||
</StepperItem>
|
||||
<StepperItem step={2}>
|
||||
<StepperTrigger><StepperIndicator>2</StepperIndicator></StepperTrigger>
|
||||
</StepperItem>
|
||||
</StepperNav>
|
||||
<StepperPanel>
|
||||
<StepperContent value={1}>Step 1 content</StepperContent>
|
||||
<StepperContent value={2}>Step 2 content</StepperContent>
|
||||
</StepperPanel>
|
||||
</Stepper>
|
||||
```
|
||||
|
||||
**Gotcha:** steps are 1-indexed. Without `StepperPanel` + `StepperContent` you render the nav trail but no body. Put `StepperSeparator` in every `StepperItem` except the last.
|
||||
|
||||
## timeline
|
||||
|
||||
**Required:** `TimelineItem step` (number)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Timeline>
|
||||
<TimelineItem step={1}>
|
||||
<TimelineHeader>
|
||||
<TimelineDate>March 2024</TimelineDate>
|
||||
<TimelineTitle>Project initialized</TimelineTitle>
|
||||
</TimelineHeader>
|
||||
<TimelineIndicator />
|
||||
<TimelineSeparator />
|
||||
<TimelineContent>Repo and architecture set up.</TimelineContent>
|
||||
</TimelineItem>
|
||||
</Timeline>
|
||||
```
|
||||
|
||||
**Gotcha:** each item needs a unique `step`. `orientation` is `"vertical"` (default) or `"horizontal"`. This is a static event display, not interactive like `stepper`.
|
||||
|
||||
## autocomplete
|
||||
|
||||
**Required:** `items` (array; each item has at least `value`)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Autocomplete items={items}>
|
||||
<AutocompleteInput placeholder="Search..." />
|
||||
<AutocompleteContent>
|
||||
<AutocompleteEmpty>No results found.</AutocompleteEmpty>
|
||||
<AutocompleteList>
|
||||
{(item) => (
|
||||
<AutocompleteItem key={item.value} value={item}>{item.label}</AutocompleteItem>
|
||||
)}
|
||||
</AutocompleteList>
|
||||
</AutocompleteContent>
|
||||
</Autocomplete>
|
||||
```
|
||||
|
||||
**Gotcha:** `AutocompleteList` takes a render-prop `(item) => ReactNode`, NOT a mapped array of children. External API: https://base-ui.com/react/components/autocomplete
|
||||
|
||||
## phone-input
|
||||
|
||||
**Required:** none, but wire `onChange`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<PhoneInput placeholder="Enter phone number" defaultCountry="US" value={value} onChange={setValue} />
|
||||
```
|
||||
|
||||
**Gotcha:** `value`/`onChange` use an E.164 string (e.g. `"+14155551234"`), not a display-formatted string; `onChange` can fire `undefined`. `defaultCountry` is a 2-letter ISO code. Wraps `react-phone-number-input`.
|
||||
|
||||
## number-field
|
||||
|
||||
**Required:** wrap the controls in `NumberFieldGroup`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<NumberField defaultValue={0}>
|
||||
<NumberFieldScrubArea label="Quantity" />
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
```
|
||||
|
||||
**Gotcha:** import from `@/components/ui/number-field`. The accessible label goes on `NumberFieldScrubArea`, not `NumberField`. External API: https://base-ui.com/react/components/number-field
|
||||
|
||||
## rating
|
||||
|
||||
**Required:** `rating` (number)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Rating rating={4.5} showValue editable onRatingChange={setRating} />
|
||||
```
|
||||
|
||||
**Gotcha:** supports decimals (partial stars). Pass `editable` + `onRatingChange` for interactive input; omit both for a read-only display.
|
||||
|
||||
## scrollspy
|
||||
|
||||
**Required:** `targetRef` (the scroll container ref)
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Scrollspy targetRef={containerRef}>
|
||||
<a href="#s1" data-scrollspy-anchor="s1">Section 1</a>
|
||||
<a href="#s2" data-scrollspy-anchor="s2">Section 2</a>
|
||||
</Scrollspy>
|
||||
<div ref={containerRef}>
|
||||
<div id="s1">...</div>
|
||||
<div id="s2">...</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
**Gotcha:** each link's `data-scrollspy-anchor` must match a section `id`. `targetRef` is the scrollable container (defaults to the window).
|
||||
|
||||
## frame
|
||||
|
||||
**Required:** `Frame` > `FramePanel`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Frame>
|
||||
<FramePanel>
|
||||
<FrameHeader>
|
||||
<FrameTitle>Title</FrameTitle>
|
||||
<FrameDescription>Description</FrameDescription>
|
||||
</FrameHeader>
|
||||
<div className="p-5">Content</div>
|
||||
<FrameFooter>Footer</FrameFooter>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
```
|
||||
|
||||
**Gotcha:** a structured card shell for tool-like surfaces. `stacked` connects multiple panels with shared borders; `dense` removes panel padding; radius via the `--frame-radius` CSS variable.
|
||||
|
||||
## icon-stack
|
||||
|
||||
**Required:** one child icon
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<IconStack aria-hidden="true">
|
||||
<InboxIcon className="size-4" />
|
||||
</IconStack>
|
||||
```
|
||||
|
||||
**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.
|
||||
|
||||
## code-block
|
||||
|
||||
**Required:** `code` + `language`, or pre-highlighted `lines`.
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<CodeBlock code={code} language="tsx" />
|
||||
|
||||
<CodeBlock code={code} language="tsx" showLineNumbers maxLines={20}>
|
||||
<CodeBlockHeader>
|
||||
<CodeBlockTitle>use-totals.ts</CodeBlockTitle>
|
||||
<CodeBlockLanguage />
|
||||
<CodeBlockCopyButton className="ml-auto" />
|
||||
</CodeBlockHeader>
|
||||
<CodeBlockExpandButton />
|
||||
</CodeBlock>
|
||||
```
|
||||
|
||||
**Gotcha:** the one-liner is already a complete block; every child (header, title, language label, copy button, wrap toggle, expand button, line actions) is optional chrome, at any depth. Shiki is the only npm dependency and loads lazily, one chunk per language, on first highlight; `lines` (from `highlightCode` in `code-block-highlight`, which is server-safe and has no `"use client"`) or `highlight={false}` loads nothing at all. `maxLines` caps the height AND marks the block collapsible, which is what makes `CodeBlockExpandButton` appear. Use `variant="ghost"` when the block sits inside a surface that already has a border.
|
||||
|
||||
## alert
|
||||
|
||||
**Required:** `Alert` > `AlertTitle`
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Alert variant="success">
|
||||
<ShieldCheckIcon />
|
||||
<AlertTitle>Security update</AlertTitle>
|
||||
<AlertDescription>Enable two-factor authentication.</AlertDescription>
|
||||
<AlertAction><Button size="xs">Update</Button></AlertAction>
|
||||
</Alert>
|
||||
```
|
||||
|
||||
**Gotcha:** shadcn-compatible API. `variant`: `default | destructive | info | success | warning | invert`. The non-default variants use ReUI extended color tokens (`--success`/`--info`/`--warning`/`--invert`), which the install adds. Defer generic alert rules to the shadcn skill.
|
||||
|
||||
## badge
|
||||
|
||||
**Required:** none (text child).
|
||||
**Shape:**
|
||||
|
||||
```tsx
|
||||
<Badge variant="success-light" size="sm">Success</Badge>
|
||||
<Badge variant="outline" radius="full">Pill</Badge>
|
||||
```
|
||||
|
||||
**Gotcha:** shadcn-compatible. Rich `variant` set (solid, `-outline`, `-light` per color), `size` `xs..xl`, `radius` `default | full`. Like `alert`, the color variants rely on ReUI extended tokens. Prefer `Badge` variants over raw color classes for statuses.
|
||||
|
||||
## base vs radix - write for the project's base
|
||||
|
||||
ReUI ships every component in two builds: `base` (Base UI) and `radix` (Radix UI). The install command and name are identical, and the CLI installs the build matching the project. But you must write/adapt code against the **right base**, because their APIs differ.
|
||||
|
||||
**Detect the base first.** Read `components.json` -> `style` and take the segment before the first `-`:
|
||||
|
||||
- `"style": "base-nova"` -> **Base UI**
|
||||
- `"style": "radix-nova"` -> **Radix UI**
|
||||
|
||||
**Then use that base's API.** The deltas mirror shadcn's base-vs-radix split:
|
||||
|
||||
- Slot/composition: Base UI `render={<… />}` vs Radix `asChild`.
|
||||
- `Select`: Base UI takes `items`; Radix uses `<SelectItem>` children.
|
||||
- `ToggleGroup`: Base UI `multiple` boolean vs Radix `type="single" | "multiple"`.
|
||||
|
||||
The safest path is to **read the installed files and `c-*` examples** - they're already in your base, so reuse their wiring instead of guessing. When `get_component`'s inline `api` or an example shows the other base's shape, translate it to your base (or `validate_usage` to confirm). Defer the generic base/radix mechanics to the shadcn skill.
|
||||
@@ -1,45 +0,0 @@
|
||||
# Craft: make ReUI UI exceptional, not generic
|
||||
|
||||
ReUI items ship senior-designer quality. Your adaptation has to hold that bar, so the result reads like a real product surface a team would keep - not a wireframe an AI generated. Use these alongside the reuse rules in [adapting.md](./adapting.md).
|
||||
|
||||
## Have a point of view
|
||||
|
||||
Pick an emotional register before you compose - calm, operational, premium, editorial, dense, energetic - and let layout, spacing, surface treatment, and icon behavior all reinforce it. One or two memorable decisions and restraint everywhere else beats ten generic ones. UI with no point of view reads as generated.
|
||||
|
||||
## Brutally clear hierarchy
|
||||
|
||||
One focal point per card or panel: the dominant metric or task first, its label second, supporting detail third. The first thing the eye lands on should be the right thing; secondary text must read as secondary. Borders, separators, and surfaces do real work to create 2-3 information bands - don't flatten everything to equal weight.
|
||||
|
||||
## Spacing rhythm and deliberate density
|
||||
|
||||
Gaps are a signal, not a default. Keep them intentional and consistent within a family (`gap-1`/`gap-2` for tight operational rows, larger gaps for section breaks), and smaller within a group than between groups. Match the surrounding ReUI density; don't pad an operational surface like a marketing page, and don't drift density mid-section. The composition should still feel authored in grayscale.
|
||||
|
||||
## Cover the real states (the usual miss)
|
||||
|
||||
A surface isn't done at the happy path. Compose, and wire:
|
||||
|
||||
- **Empty** - a purposeful empty state (short message + the primary action), never a blank panel.
|
||||
- **Loading** - a **skeleton** that matches the real layout, not a centered spinner.
|
||||
- **Error** - an inline, recoverable error with a retry, announced via `role="status"`/`aria-live`.
|
||||
|
||||
Derive these from an element the block already has (don't invent parallel markup), or `get_examples` for a state-specific example.
|
||||
|
||||
## Responsive by default
|
||||
|
||||
Mobile-first, not mobile-afterthought. In constrained rows/cards/sidebars, put `min-w-0` on the shrinking container and `truncate` long single-line labels; protect the primary label's width and let secondary content compress. Reflow layouts (multi-column -> single column) rather than just shrinking them. Desktop and mobile should both look designed.
|
||||
|
||||
## Motion, subtly
|
||||
|
||||
Motion should clarify, not decorate. Use ReUI Motion Icons on primary actions for a subtle hover cue; keep transitions short (~200-300ms) with calm easing; prefer a skeleton pulse over a spinner. No bouncing, no gratuitous entrance animations on every element.
|
||||
|
||||
## Real, activated content
|
||||
|
||||
Use believable, typed data (realistic labels, counts, timestamps, statuses that map to a real workflow) - never lorem or abstract filler. Every visible control does something: no decorative buttons, fake tabs, meaningless toggles, or stats with no job. It must still hold with long names, empty values, and crowded data.
|
||||
|
||||
## Avoid the AI tells
|
||||
|
||||
These instantly read as generated - don't ship them: equal-weight card walls, empty gradients, repetitive padding everywhere, generic enterprise copy, ornamental icons, and number tiles that don't earn their place.
|
||||
|
||||
## The bar
|
||||
|
||||
Before you finish, ask: **would a product team keep this instead of replacing it? Does it still feel strong after swapping in real content?** If not, reuse the shipped ReUI design harder - don't restyle it into something new - then run the [quality.md](./quality.md) gates.
|
||||
@@ -1,39 +0,0 @@
|
||||
# Icons (ReUI delta over shadcn)
|
||||
|
||||
Follow the shadcn icon rules (use the project's configured `iconLibrary`, `data-icon` on icons inside `Button`, no sizing classes on icons inside components, pass icons as component objects not string keys). ReUI adds the following.
|
||||
|
||||
## Portable icons (library-agnostic)
|
||||
|
||||
ReUI components, examples, and blocks are authored to be icon-library-agnostic. When `iconLibrary` is set in `components.json`, the shadcn CLI installs each item's icons in **your** library automatically - you swap nothing. If an installed item's icons don't match your project (for example `iconLibrary` isn't set, so they came in from the item's demo library), change the **import source and component name** to your library, keeping the same icon-name semantics:
|
||||
|
||||
- `lucide` -> `lucide-react`
|
||||
- `tabler` -> `@tabler/icons-react`
|
||||
- `phosphor` -> `@phosphor-icons/react`
|
||||
- `remix` -> `@remixicon/react`
|
||||
- `hugeicons` -> `@hugeicons/react`
|
||||
|
||||
Don't assume `lucide-react`; read `iconLibrary` from `components.json`.
|
||||
|
||||
## Keep icons purposeful
|
||||
|
||||
Icons support the hierarchy, they don't replace it: keep them small, matched to the surrounding density, and decorative ones `aria-hidden="true"` (an icon-only control still needs an accessible label on the control). Don't add ornamental icons that do no job.
|
||||
|
||||
## Motion Icons (the `@reui/icons/...` set)
|
||||
|
||||
ReUI ships its own icon set in 4 styles (outline, solid, duotone, filled), each icon in two variants:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add @reui/icons/default/<style>/<name> --yes # static
|
||||
npx shadcn@latest add @reui/icons/animated/<style>/<name> --yes # hover-animated (motion/react)
|
||||
```
|
||||
|
||||
Finding them via the MCP is free; installing requires an Ultimate license (`REUI_LICENSE_KEY`, see [cli.md](./cli.md)). Reach for a Motion Icon on a primary action when a subtle hover cue helps; keep motion restrained.
|
||||
|
||||
Finding icons:
|
||||
|
||||
- Several icons (the common case): **`search_icons(concepts[])`** - up to 24 concepts in one call, the best icons per concept with install commands. Pass `animated: true` to get only icons with a hover-animated Motion variant.
|
||||
- One icon: `search` with `type: "icon"`.
|
||||
- Icon results and `get_icon` carry `animated: true` and `installAnimated` when an animated variant exists - use those install strings, do not construct paths by hand.
|
||||
- Every icon result carries a `previewUrl` (its live icon-category page) - **share it with the user** so they can SEE the icon before installing.
|
||||
|
||||
The `icon-stack` component composes multiple icons into a stacked display.
|
||||
@@ -1,22 +0,0 @@
|
||||
# Quality gates (security, accessibility, scroll)
|
||||
|
||||
These are the **done gate**, not a nice-to-have: before you call any ReUI work finished, call the MCP `get_audit_checklist` tool and pass every item below (plus the craft bar in [craft.md](./craft.md)). Then typecheck and lint.
|
||||
|
||||
## Security
|
||||
|
||||
- Never `dangerouslySetInnerHTML`. Render data as text/components.
|
||||
- External links (`target="_blank"`) must always pair `rel="noopener noreferrer"`.
|
||||
- No real PII, secrets, or tokens in demo or committed code. Remote media only from sources the project already allows.
|
||||
|
||||
## Accessibility
|
||||
|
||||
- Implicit list/card items that navigate get real anchors with a standard hover affordance.
|
||||
- Icon-only or numeric buttons need an `aria-label`; decorative icons get `aria-hidden`.
|
||||
- Every non-submit button is `type="button"`.
|
||||
- Keyboard + focus: everything interactive is reachable in a sensible Tab order with a visible focus ring; layers (dialogs/sheets/menus) trap focus and close on `Escape`. ReUI components ship standard keyboard behavior - read each component's inline `api` rather than re-implementing it.
|
||||
- Announce async UI: loading and error messages use `role="status"` / `aria-live` so they're not silent to screen readers.
|
||||
|
||||
## Scroll mechanics
|
||||
|
||||
- Make scroll regions with a parent-owned height: a `min-h-0` + flex chain down to the scroll container. Never guess a `max-h`.
|
||||
- The scroll container owns `overflow-auto`; ancestors stay `min-h-0` so the height resolves.
|
||||
@@ -1,35 +0,0 @@
|
||||
# ReUI registry structure
|
||||
|
||||
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 22 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).
|
||||
|
||||
## The @reui registry
|
||||
|
||||
Install everything through the shadcn CLI: `npx shadcn@latest add @reui/<name> --yes`. The CLI reads the `@reui` registry from the project's `components.json`. Free items need only the plain string form:
|
||||
|
||||
```json
|
||||
{ "registries": { "@reui": "https://reui.io/r/{style}/{name}.json" } }
|
||||
```
|
||||
|
||||
Premium installs need the authenticated form + `REUI_LICENSE_KEY` in `.env.local` - see [cli.md](./cli.md). The MCP `get_project_context` tool returns the right config.
|
||||
|
||||
## Know your base: base or radix
|
||||
|
||||
ReUI ships every item in two builds - `base` (Base UI) and `radix` (Radix UI) - with mirrored names. The CLI installs the build matching your project automatically, but **you must write code against the right base's API**. Detect it from `components.json` -> `style`: the segment before the first `-` is the base (`base-nova` -> Base UI, `radix-nova` -> Radix UI). The installed files and `c-*` examples are already in your base - read them and adapt on that base. See [components.md](./components.md) for the API deltas.
|
||||
|
||||
**So the MCP's own `docsUrl` and `previewUrl` match your base**, send your `style` to the MCP: add `?style=<your components.json style>` to the ReUI MCP server URL (or set an `X-Reui-Style` header) in your MCP client config - set once, applies to every call. The MCP then resolves docs/preview links to YOUR library (`/docs/components/radix/...`, `/preview/radix/...` for a radix project) instead of the default base; `get_project_context` echoes back the style it currently sees so you can confirm it. Install commands are unaffected (the CLI already installs the right variant). If you notice the MCP returning `base` links for a `radix` project, tell the user to add `?style=` to the server URL.
|
||||
|
||||
Blocks adapt to your active theme through semantic tokens and CSS variables - change the theme and every block follows.
|
||||
|
||||
## Free vs premium
|
||||
|
||||
- **Free, no key:** the 22 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
|
||||
|
||||
The canonical index of every component's API docs is **https://reui.io/llms.txt** (returned as `componentsApiUrl` in MCP results). Prefer the inline `api` from `get_component`; use the index/docs as the fallback.
|
||||
@@ -1,26 +0,0 @@
|
||||
# Styling (ReUI delta over shadcn)
|
||||
|
||||
Follow the shadcn skill for the generic rules (semantic colors not raw values, `gap-*` not `space-y-*`, `size-*`, `cn()`, no manual `dark:` overrides, no overlay `z-index`). This file is only the ReUI-specific additions.
|
||||
|
||||
## ReUI extended semantic tokens
|
||||
|
||||
ReUI adds semantic tokens beyond shadcn's base set. Use these instead of raw colors for status and emphasis:
|
||||
|
||||
- `--success` / `--success-foreground`
|
||||
- `--info` / `--info-foreground`
|
||||
- `--warning` / `--warning-foreground`
|
||||
- `--destructive-foreground` (paired with shadcn's `--destructive`)
|
||||
- `--invert` / `--invert-foreground` (inverted surfaces)
|
||||
|
||||
Use them as Tailwind utilities (`bg-success text-success-foreground`, `text-warning`, ...). They are defined in the project's global CSS and registered with Tailwind (`@theme inline` on v4). If a token is missing in the project, add it to the global CSS file (never a new file) following the same `name` / `name-foreground` convention, exactly as the shadcn customization rules describe.
|
||||
|
||||
**Incorrect:** `<span className="text-green-600">Active</span>`
|
||||
**Correct:** `<Badge variant="success">Active</Badge>` or `<span className="text-success">Active</span>`
|
||||
|
||||
## Blocks follow your theme
|
||||
|
||||
When you install a block it adapts to your active theme through the semantic tokens above and the project's CSS variables. Don't hardcode style-specific values into installed block code and don't fork it to "restyle" - change the theme via the CSS variables / a preset and every block follows. Want a different look? `search` for a block whose design already fits instead of re-skinning one.
|
||||
|
||||
## Density and typography rhythm
|
||||
|
||||
ReUI operational UI usually feels dense, not airy. Keep the gap between a title and its supporting description tight by default (`gap-0.5`, `space-y-1`, or `space-y-px`), and smaller than the gap between sections. Match the surrounding ReUI density when you add rows or fields; do not pad operational surfaces like a marketing page.
|
||||
@@ -1,54 +0,0 @@
|
||||
# Workflow: find -> install -> read API -> adapt
|
||||
|
||||
The core ReUI loop. The MCP tells you what to install and gives you the API; the shadcn CLI installs it; you turn the installed files into correct, themed, data-wired code by **reuse**, not redesign.
|
||||
|
||||
## 1. Find (ReUI MCP `search` / `compose_page`)
|
||||
|
||||
**Full multi-section page ask?** Call `compose_page(intent, sections?)` FIRST, before searching block-by-block. It returns ordered sections, each with the best block for the intent (top pick + alternates); sections listed in `unavailableSections` have no real inventory - compose those from components, do not force a bad block.
|
||||
|
||||
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 22 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`.
|
||||
|
||||
Example: "build a users management page with filters" -> `search({ query: "users management page with filters", type: "block", component: "data-grid", features: ["filters"] })`.
|
||||
|
||||
Each result has `install`, `previewUrl`, `docsUrl`, `componentsUsed`, `score`, `termCoverage`, and `whyMatch`. `score` is relative to the top hit (the top is ~100 by construction), not an absolute quality - compare results to each other, and show the user the top options if several score closely; do not silently guess. A low `termCoverage` means a weak match even with a high score - rephrase or widen.
|
||||
|
||||
**Always show the preview link.** Whenever you list or recommend items - from `search`, `search_icons`, `list_components`, `compose_page`, or a getter - include each item's `previewUrl` (a live preview page) so the user can SEE it before you install. Blocks and examples link to an individual live preview; icons and components to their live category/component page. This applies to every listing, not only a single pick.
|
||||
|
||||
## 2. Install (shadcn CLI)
|
||||
|
||||
Run the result's `install` command from the project root, non-interactively:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add @reui/<name> --yes
|
||||
```
|
||||
|
||||
The CLI reads `components.json`, installs the correct base+style variant, resolves `registryDependencies` (a block pulls in its components), installs npm deps, and rewrites aliases. Do not pass the base/style. See [cli.md](./cli.md).
|
||||
|
||||
## 3. Read the API (do not guess props)
|
||||
|
||||
Before writing code against any component an item uses:
|
||||
|
||||
1. The item's `componentDigests` already give a 1-line contract per component - often enough to wire it. For the full API, call **`get_component(names)`** with ALL of `componentsUsed` in ONE call (it accepts an array) and read each inline `api` - no web fetch. **Share the component's `docsUrl`** (its 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.
|
||||
2. Call **`get_examples(name)`** for the free `c-*` examples of that component; install one and **read the added files** to copy the exact composition. This is the fastest correct path - the example shows real wiring you adapt, not invent.
|
||||
3. About to write a prop you did not see in an `api` or installed file? Run **`validate_usage`** BEFORE writing the code - per-prop documented / notDocumented verdicts plus did-you-mean suggestions. notDocumented means read the API, not push on.
|
||||
|
||||
## 4. Adapt (reuse-first) - do not skip
|
||||
|
||||
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 `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)).
|
||||
5. **Validate before finalizing**: if your adaptation introduced components or props you did not read in an `api` or example, run `validate_usage` on them.
|
||||
6. **Hit the craft bar** - clear hierarchy, deliberate density, the empty / loading / error states, subtle motion, and mobile-first responsiveness (see [craft.md](./craft.md)). Generic-looking output means you under-reused the design, not that it needs restyling.
|
||||
7. **Pass the quality gates** (security, a11y, scroll) - call the MCP `get_audit_checklist` tool and clear every item (see [quality.md](./quality.md)).
|
||||
8. **Typecheck / lint**.
|
||||
|
||||
## If no single block fits
|
||||
|
||||
Compose from components (`compose_page` tells you which sections have no block inventory via `unavailableSections`). `search` the components you need, read each `get_component` API, install a worked `get_examples` example for each, and assemble by adapting those examples. A block in the same category is a useful reference - install it and read its files to see how ReUI composes those components, then adapt.
|
||||
@@ -1,58 +0,0 @@
|
||||
# ReUI MCP: full reference
|
||||
|
||||
The ReUI MCP (`https://mcp.reui.io`, Streamable HTTP) is free to use but needs a ReUI account: on first use the agent signs in with ReUI (a free account is created if the user has none), so every request is tied to an account. Free covers components and examples; a Pro or Ultimate license unlocks premium blocks and Motion Icons and removes the daily request limit. It does **discovery + guidance** (search, inline APIs, page planning, validation) and never serves source; the shadcn CLI does **installation**, and the license key lives there (the `@reui` entry in `components.json`, backed by `.env.local`). Goal: from the user's intent to correct, themed, data-wired ReUI code in the **fewest tokens and calls**, with **no guessing**.
|
||||
|
||||
## Golden path (token-optimal - follow this order)
|
||||
|
||||
Most tasks need 2-4 MCP calls and ZERO web fetches:
|
||||
|
||||
1. **`search(query, ...hints)`** -> pick the top 1-3 results. Each result already carries `install`, `previewUrl`, `docsUrl`, `componentsUsed`, `score`, `whyMatch`. The payload is complete - do not call another tool just to "confirm" a result.
|
||||
2. **`get_component([...componentsUsed])`** in ONE batched call (one name or an array of up to 20) -> read each inline `api`. This **replaces** fetching docs pages. Often skippable: search responses carry `componentDigests`, a compact API contract per referenced component.
|
||||
3. **`get_examples(component)`** -> install ONE returned `c-*` example, read the added files, copy the composition.
|
||||
4. **`get_install_command(item)`** only to validate a name you are unsure of (results already include `install`). Run the install with the shadcn CLI (`--yes`).
|
||||
5. **`get_audit_checklist()`** before declaring done.
|
||||
|
||||
If you already know the exact item name, skip `search`. Everything else is situational.
|
||||
|
||||
## The 5 task-specific tools (when to reach for each)
|
||||
|
||||
- **`compose_page`** - BEFORE building any full page (dashboard, settings, billing, landing). Pass the intent (and optionally the sections you want); it returns ordered sections, each with the best premium block for the intent (top pick + alternates). Sections with no real inventory are listed honestly in `unavailableSections` - compose those from components instead of forcing a bad block.
|
||||
- **`search_icons`** - whenever you need icons, especially several. Batch up to 24 concepts in one call; each concept returns its best icons with install commands. Pass `animated: true` to get only icons that have a hover-animated Motion variant.
|
||||
- **`validate_usage`** - BEFORE writing code with component names or props you have not read in an inline `api` or an installed example. It checks planned names + props against the indexed API docs and registry item names; returns did-you-mean suggestions and per-prop documented / notDocumented verdicts. Deterministic, no inference - a notDocumented prop means stop and read the API, not push on.
|
||||
- **`whats_new`** - when your registry knowledge might be stale (a name 404s, the user mentions an item you don't know). Returns items added/removed per build, newest first.
|
||||
- **`report_issue`** - when an installed item is actually broken (bad source, wrong dependency, broken preview). Goes straight to the ReUI team; rate-limited 5/hour. Not for usage questions.
|
||||
|
||||
## All 19 tools
|
||||
|
||||
`search`, `get_block`, `get_example`, `get_icon`, `list_block_groups`, `list_block_categories`, `list_example_categories`, `list_icon_categories`, `list_components`, `get_component`, `get_examples`, `search_icons`, `compose_page`, `validate_usage`, `whats_new`, `report_issue`, `get_install_command`, `get_project_context`, `get_audit_checklist`. The MCP serves the full parameter schemas; do not guess parameters beyond them.
|
||||
|
||||
## Token + speed rules
|
||||
|
||||
- **Batch `get_component`** - ONE call with the whole `componentsUsed` array, never N calls. Skip it entirely when `componentDigests` already answers the question.
|
||||
- **Read source by installing** - the MCP serves no source. To read or analyze an item's real code, install it with the shadcn CLI and open the local files. Learn an API from the inline `api` / `componentDigests`, never by reading raw source.
|
||||
- **Infer `search` hints yourself** (`type`, `component`, `category`, `features`, `free`) - hints shrink the result set and the tokens. Keep `limit` low; one right result beats ten.
|
||||
- Run independent calls (and the shadcn install) concurrently in one turn - serial tool calls are the main source of slowness.
|
||||
- Don't repeat a search for the same intent; don't call `list_*` to "see everything" - `search` is the entry point, `list_*` is only for browsing a taxonomy the user explicitly wants to explore.
|
||||
- Prefer `get_component`'s inline `api` over `docsUrl` / `/llms.txt`. Fetch a web page only as a last resort.
|
||||
|
||||
## Result shapes (so you don't re-fetch)
|
||||
|
||||
- `score` is 0-100 RELATIVE to the top hit (the top is ~100 by construction), not absolute - compare results to each other.
|
||||
- `termCoverage` (0-1) is the share of the query the item matched - low means a weak match even if the score looks high; rephrase or widen the search.
|
||||
- Each result carries `whyMatch`, `install`, docs/preview URLs, and a `free` flag; premium items carry `requiredPlan` (`"pro"` for blocks, `"ultimate"` for icons).
|
||||
- `componentDigests` is a top-level map: a compact API contract per referenced component - often enough to wire an item without a `get_component` call.
|
||||
- Icon results and `get_icon` include `animated: true` and `installAnimated` when a hover-animated Motion variant exists (animated: `@reui/icons/animated/<style>/<name>`; static: `@reui/icons/default/<style>/<name>`).
|
||||
|
||||
## Error playbook
|
||||
|
||||
- **401** - the MCP requires a signed-in ReUI account. The client prompts "Sign in with ReUI" (OAuth) on first use; a free account is created if needed. For headless/CI, pass a personal token (`reui_pat_...`, created at https://reui.io/account/mcp?ref=skill) as `Authorization: Bearer`.
|
||||
- **403 / locked result** - a valid account but the plan does not cover the item: premium blocks need Pro, Motion Icons need Ultimate. Point to https://reui.io/pricing?ref=skill (upgrade). Free accounts still get all components + examples.
|
||||
- **429** - rate limited (120 requests/min per IP); back off, honor `Retry-After`.
|
||||
- **not found** (`found: false`) - use the returned `suggestions`, or `search`; check `whats_new` if you suspect a stale name. Never run a fabricated install command.
|
||||
|
||||
## Fallbacks
|
||||
|
||||
- No ReUI MCP: `npx shadcn@latest search @reui -q "..."` then `add` (generic, no scoring / inline API).
|
||||
- The shadcn project's own MCP also works over the `@reui` registry: https://ui.shadcn.com/docs/mcp.
|
||||
|
||||
Per-agent MCP setup: https://reui.io/docs/mcp?ref=skill
|
||||
@@ -1,63 +0,0 @@
|
||||
# Локальные GeoLite2-базы (Country + ASN) для потоков по странам и ASN
|
||||
|
||||
## Контекст
|
||||
|
||||
Сейчас страна и ASN для netflow-потоков резолвятся через внешний RIPEstat API (`backend/src/services/traffic-flow-ripe.ts`): лимит 30 новых префиксов/мин, очередь на 90, кэш в PG `flow_ip_meta`. Новые IP «дозревают» с задержкой, IPv6 не покрывается (кэш индексируется только по IPv4). Локальные mmdb-базы дают мгновенный синхронный lookup всех IP без внешних вызовов.
|
||||
|
||||
Решения (подтверждены):
|
||||
- Источник — **MaxMind GeoLite2 через P3TERX-зеркало**: `https://github.com/P3TERX/GeoLite.mmdb/raw/download/GeoLite2-Country.mmdb` и `.../GeoLite2-ASN.mmdb`. Без регистрации, ключей и tar-распаковки. Точность по стране у GeoLite2 и IPinfo паритетная (<1% ошибок у обоих, arXiv 2026); выбран P3TERX за надёжность зеркала (5.2k звёзд) и преемственность: текущий RIPE-путь и так читает GeoLite (`maxmind-geo-lite`), история в кэше остаётся консистентной.
|
||||
- **RIPEstat остаётся fallback** (до первой загрузки баз / если lookup не дал результата).
|
||||
- City-базу не качаем (lat/lng фронтенд не использует).
|
||||
|
||||
## Изменения
|
||||
|
||||
### 1. Зависимость
|
||||
- `npm install -w mikrotik-manager-backend maxmind` — sync-чтение mmdb, встроенные TS-типы, без транзитивных зависимостей, Node 22 ок.
|
||||
|
||||
### 2. Новый сервис `backend/src/services/traffic-flow-geoip.ts`
|
||||
(по конвенциям окружения traffic-flow-*: контракт → маршрут → сервис, без БД-логики в маршрутах)
|
||||
- Каталог: `backend/storage/geoip/` (конвенция `storage/backups`), файлы `GeoLite2-Country.mmdb`, `GeoLite2-ASN.mmdb`.
|
||||
- `initGeoip()` — открыть ридеры best-effort при старте (из `index.ts` рядом с `startTrafficFlowListener`), независимо от настроек автообновления: файлы есть — работают.
|
||||
- `lookupGeoip(ip): FlowIpMeta | null` — синхронно: `country.iso_code` (fallback `registered_country.iso_code`) с валидацией `isIsoCountry`, ASN = `autonomous_system_number`, holder = `autonomous_system_organization`; приватные IP → negative-запись как в RIPE (`isNonPublicIp`); в PG не пишем (lookup и так быстрый). IPv6 поддержан ридером.
|
||||
- `resolveFlowIp(ip)` — фасад: `lookupGeoip(ip) ?? lookupRipeCached(ip)`; главный экспорт для потребителей.
|
||||
- `geoipStatus()` — loaded, даты сборки баз (метаданные mmdb). Тест-хук `setGeoipReadersForTests`. Смена ридеров после обновления — атомарная замена ссылок.
|
||||
|
||||
### 3. Коллектор `backend/src/services/geoip-update-collector.ts`
|
||||
`collectGeoipUpdateOnce()` по образцу `certificate-renew-collector.ts`:
|
||||
1. Conditional GET с ETag/If-None-Match из настроек → 304 = skip (фолбэк-сравнение: размер/содержимое).
|
||||
2. Скачивание в `*.tmp` через глобальный `fetch` + AbortController с таймаутом (внешний HTTP из service-слоя — по правилу fastify-backend-drizzle).
|
||||
3. Валидация: открыть ридер из tmp-файла, пробой 8.8.8.8 (страна US, ASN 15169).
|
||||
4. `fs.rename` атомарная подмена, старый файл → `*.prev` (откат, если новый ридер не открылся).
|
||||
5. Перезагрузка ридеров, статус в настройках; snapshot для `scheduler_runs` (checked/downloaded/skipped/bytes/error).
|
||||
|
||||
### 4. Планировщик (`backend/src/services/scheduler.ts`)
|
||||
- `JOB_KEYS` += `geoip_update`; case в `runSchedulerJobBody`; блок в `refreshScheduler()` по образцу `certificates_renew`: интервал `Math.max(6ч, updateIntervalSec*1000)`, по умолчанию 7 дней (upstream обновляется еженедельно) + немедленный первый запуск при включённой настройке.
|
||||
|
||||
### 5. Схема и миграция
|
||||
- `backend/src/db/schema.ts`: singleton `geoip_settings` — `enabled` (default true), `updateIntervalSec` (default 604800), `lastCheckAt`, `lastSuccessAt`, `lastError`, `countryBuildAt`, `asnBuildAt`, `etagsJson` (jsonb), `createdAt/updatedAt`.
|
||||
- Миграция: `npm run db:generate` → файл в `backend/drizzle/`.
|
||||
|
||||
### 6. API + контракты
|
||||
- `packages/contracts/src/geoip.ts`: zod-схемы настроек/статуса (все входы — Zod, по правилам проекта).
|
||||
- Новый `backend/src/routes/geoip.ts`, регистрация в `index.ts` с prefix `/api`:
|
||||
- `GET /api/geoip` — настройки + статус (ready, даты сборки, последняя проверка/ошибка);
|
||||
- `PUT /api/geoip` — сохранить настройки, затем `refreshScheduler()`;
|
||||
- `POST /api/geoip/update` — запустить загрузку сейчас (409, если уже идёт; флаг-гард как в коллекторах).
|
||||
|
||||
### 7. Интеграция в пайплайн (geoip-first, RIPE-fallback)
|
||||
- `traffic-flow-engine.ts` (`queueParsedFlows`, ~строка 336): `lookupRipeCached` → `resolveFlowIp`. Логика misses не меняется: при готовом mmdb публичные IP (v4+v6) резолвятся сразу, очередь RIPE пустеет; до скачивания баз — прежнее поведение.
|
||||
- Остальные вызовы `lookupRipeCached` → `resolveFlowIp` (grep: как минимум `traffic-flow-analytics.ts` ~258–271).
|
||||
- `classifyFlowDst`/бренды не трогаем: holder из mmdb (org name) встаёт в существующие `HOLDER_BRANDS`-регулярки как есть.
|
||||
|
||||
### 8. Frontend (по next-shadcn-production / ui-guardian: только переиспользование)
|
||||
- Секция «GeoIP-базы (GeoLite2)» внутри существующей `components/traffic/netflow-settings-panel.tsx`: статус (готово/не скачано, даты сборки Country/ASN, последняя проверка, ошибка), тумблер автообновления, интервал, кнопка «Обновить сейчас» с индикатором. Только уже используемые в панели примитивы (Switch/Button/поля) — никаких новых визуальных паттернов и Card-shell. API-клиент через существующие http-хелперы.
|
||||
|
||||
### 9. Хаускипинг, тесты, проверки
|
||||
- `backend/.gitignore`: `storage/geoip/`.
|
||||
- Тесты `backend/src/services/traffic-flow-geoip.test.ts` + скрипт `test:geoip` (по образцу `test:traffic-flow`): приоритет фасада (geoip hit → RIPE не зовётся; miss → fallback), negative на приватных IP, фильтрация EU/ZZ через `isIsoCountry`, коллектор с мокнутым fetch (304-skip, битый файл → подмены нет, `.prev` сохранён), dims по стране/ASN с засеянным ридером.
|
||||
- Проверки после реализации (обязательно по правилам): типы/сборка бэка (`npm run build -w mikrotik-manager-backend`), типы фронта при правке UI (`npx tsc --noEmit`), `npm run test:geoip` и `test:traffic-flow`; предупреждения не игнорировать.
|
||||
- Коммит: `feat(netflow): <subject по-русски>` — новая пользовательская фича (мгновенные страна/ASN в потоках), по commit-messages-ru.
|
||||
- README: короткий раздел о GeoIP; примечание, что в Docker `storage/geoip` ephemeral без тома — базы перекачаются после пересоздания контейнера (~17 МБ); при желании смонтировать volume.
|
||||
|
||||
## Что это даёт
|
||||
Страна и ASN появляются у потока мгновенно при ingest (включая IPv6), без ограничения скорости RIPE; dims `country`/`asn` в `flow_daily_dims`, аналитика (карта, топы, monthly) становятся полными сразу. Внешняя зависимость от stat.ripe.net остаётся только как fallback до первой загрузки баз.
|
||||
@@ -1,46 +0,0 @@
|
||||
# IKEv2/IPsec VPN: клиенты, IP-адреса и сертификаты — по образцу WireGuard
|
||||
|
||||
## Архитектура (как у WireGuard)
|
||||
|
||||
Роутер — источник истины: live-чтение через существующий REST-клиент (`mikrotik.ts`), мутации прямыми REST-вызовами, история через `config_revisions` (новая секция `"ipsec"`; `section` — TEXT без CHECK → **SQL-миграция не нужна**). Новых таблиц нет. Объекты, созданные мастером/при создании клиентов, помечаются managed-комментарием `mm-ipsec` (по образцу managed-markers).
|
||||
|
||||
## Модель RouterOS (что создаём/читаем)
|
||||
|
||||
Мастер инициализации сервера (per router): CA-сертификат (`/certificate add` + `sign`, key-usage=key-cert-sign,crl-sign), серверный сертификат (CN=адрес/домен, SAN, tls-server), `/ip/ipsec/peer` (passive, exchange-mode=ike2, certificate=серверный cert), `/ip/ipsec/profile`+`proposal` (aes-256/sha256/modp2048, pfs), `/ip pool` + `/ip/ipsec/mode-config` «VPN» (address-pool, dns), policy-template, и опциональное (default on, чекбокс) managed srcnat masquerade-правило «интернет клиентам».
|
||||
|
||||
Клиент = `/ip/ipsec/identity`: **Сертификат** (`/certificate add` CN=<имя> → `sign` ca=<CA> → `export-certificate type=pkcs12` → файл `.p12` скачивается с роутера → identity match-by=certificate) или **PSK** (auth-method=pre-shared-key, remote-id+secret). IP: «из пула» (общий mode-config) или статический (персональный `mc-<user>` mode-config с `address=x.x.x.x/32`). Онлайн — `/ip/ipsec/active-peers`.
|
||||
|
||||
Клиентские загрузки: `.p12` (cert+key+CA, passphrase) + strongSwan `.sswan` (генерация на бэкенде) + текстовая инструкция. Перекачка `.p12` — повторный export с новой passphrase (ключ остаётся на роутере).
|
||||
|
||||
## Бэкенд
|
||||
|
||||
1. **`mikrotik.ts`**: `downloadFile(name): Promise<Buffer>` — бинарно-безопасный GET `/rest/file/<name>` (с fallback `flash/<name>`, как у `uploadTextFile`; текущий конвейер парсит JSON как utf8 — нужен Buffer-режим); хелперы `signCertificate` (с поллингом готовности, sign небыстрый), `exportCertificatePkcs12(name, passphrase)`.
|
||||
2. **`services/ipsec-config.ts`** (чистые, тестируемые): генератор `.sswan` и инструкции, поиск свободного IP в пуле, naming-конвенции (`ipsec-ca`, `ipsec-server`, `mc-<user>`, `ipsec-user-<name>`).
|
||||
3. **`services/ipsec-ca.ts`**: `ensureCa/ensureServerCert/issueClientCert/exportClientP12` — add → sign (poll) → export → download.
|
||||
4. **`services/ipsec-ros.ts`**: put/patch/delete для `/ip/ipsec/{peer,identity,mode-config,profile,proposal,policy}`, `/ip/pool`, NAT managed-правило.
|
||||
5. **`services/ipsec-live.ts`**: `fetchIpsecState(server)` — параллельные GET peer/identity/mode-config/pool/active-peers/certificate (+какие из них наши по маркеру/имени) → DTO; `listIpsec()` fan-out с failures; `countIpsecClients()` для сайдбара.
|
||||
6. **`entity-snapshots.ts`**: `canonicalIpsecSnapshot/parseIpsecSnapshot/planIpsecRestore` (секреты через `isHiddenSecret`); `CONFIG_SECTIONS` += `"ipsec"`; enum в `schema.ts` (миграции нет).
|
||||
7. **`routes/ipsec.ts`**: `GET /ipsec` (+observed revision), `POST /ipsec/server/init`, `DELETE /ipsec/server/:serverId` (только managed-объекты), `POST /ipsec/users` (ответ включает одноразовый p12 base64), `PATCH /ipsec/users/:serverId/:rosId` (имя/статический IP/psk), `DELETE /ipsec/users/...` (identity + mc + опционально клиентский cert), `POST /ipsec/users/:serverId/:rosId/cert` (перекачка p12), `GET /ipsec/revisions` + `POST /ipsec/revisions/:id/restore` — всё по образцу `routes/wireguard.ts` (`captureAndAppendRevision`). Регистрация в `index.ts`; `/api/ipsec` в обе группы network-правил `permissions.ts`.
|
||||
8. **Модуль Пользователи**: `InterfaceType` += `"ipsec"` (iface-type.ts, schema.ts enum — TEXT, без миграции); каталог интерфейсов дополняется IPsec-клиентами (identity name + CN в peerPublicKey/peerName) — привязка app-пользователя к VPN-клиенту.
|
||||
|
||||
## Контракт
|
||||
|
||||
`packages/contracts/src/ipsec.ts` (+`package.json` exports, `index.ts`): `ipsecPeerDto/identityDto/modeConfigDto/poolDto/activePeerDto/certInfoDto/serverSummaryDto`, list-response с failures, `initRequest` (CN/SAN, пул, DNS, NAT-чекбокс), `userCreateRequest` (имя, auth: certificate|psk, psk?, ip: static|pool, passphrase, daysValid), `certDownloadResponse {filename, contentB64, mime}`.
|
||||
|
||||
## Фронт
|
||||
|
||||
`app/(main)/ipsec/page.tsx` — «одно окно» по образцу WG-страницы: ServerRail + KPI (серверы IKEv2 / клиенты / онлайн / CA) + Tabs **«Клиенты»** (grid: имя, сервер, аутентификация, IP, онлайн, действия — скачать .p12/.sswan, изменить, удалить; Sheet создания клиента), **«Сервер»** (peer/pool/mode-config/certs + мастер инициализации Stepper + статус NAT-правила), **«CLI»** (шпаргалка). История/restore — `ConfigHistorySheet`. Компоненты `components/ipsec/*` на существующих DataGridShell/form-kit/Sheet; скачивание бинарного p12 — Blob из base64 (по образцу `downloadText`), `.sswan`/инструкция — через `CodeExportSheet`. Сайдбар «IPsec / IKEv2» в «Управление» + бейдж (`sidebar-counts.ts` + mock в `sidebar-badges.ts`) + command-palette. Mock-данные в `lib/data.ts` для демо-режима.
|
||||
|
||||
## Тесты и проверка
|
||||
|
||||
- `ipsec-config.test.ts` (чистые функции: sswan, свободный IP, naming); `entity-snapshots.test.ts` — `planIpsecRestore` + `opsTouchOnly(["/ip/ipsec", ...])`.
|
||||
- `npm run build -w @mmapp/contracts`; `tsc` backend/root; `npm --prefix backend run test:config-sync && test:wireguard` + новые; eslint без новых ошибок.
|
||||
- Демо-режим: визуальная проверка страницы в браузере (как в прошлый раз).
|
||||
|
||||
## Риски (проверить на живом роутере при внедрении)
|
||||
|
||||
- REST-скачивание файла `GET /rest/file/<name>` — еслиRouterOS отдаёт только метаданные, fallback: чтение `contents` маленьких PEM-файлов или сборка p12 из PEM-частей.
|
||||
- Точные имена полей mode-config (`address` vs `address-pool`) сверить с живым GET и адаптировать.
|
||||
- `/certificate/sign` — поллинг готовности с таймаутом ~30–60 с.
|
||||
|
||||
Объём большой; коммит/пуш — по готовности, отдельным `feat(ipsec): …`.
|
||||
@@ -4,8 +4,6 @@
|
||||
|
||||
## Содержание
|
||||
|
||||
Разрабатываемый MCP для AI-клиентов: [настройка, возможности и ограничения](docs/mcp.md), [включение по шагам](docs/mcp-enable-guide.md), [полный план реализации](docs/mcp-implementation-plan.md).
|
||||
|
||||
1. [Состав монорепозитория](#состав-монорепозитория)
|
||||
2. [Архитектура](#архитектура)
|
||||
3. [Локальная разработка](#локальная-разработка)
|
||||
|
||||
+33
-78
@@ -17,7 +17,7 @@ import { Separator } from "@/components/ui/separator"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { filtersResponseSchema, filtersMutationSchema, filtersGreResponseSchema, filtersRecursiveResponseSchema } from "@/lib/filters-response"
|
||||
import { firewallServersSchema } from "@/lib/firewall-response"
|
||||
import { ApiClientError, requestJson } from "@/shared/api/http-client"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
import {
|
||||
servers, greTunnels, serverFilterRulesets, filters as mockFiltersCatalog,
|
||||
type FilterRule, type ServerFilterRuleset, type Server, type GreTunnel,
|
||||
@@ -252,7 +252,7 @@ function generateCombinedRouterOSConfig(
|
||||
|
||||
// ── shared components ──────────────────────────────────────────────────────────
|
||||
|
||||
function TypeChip({ type }: { type: import("@mmapp/contracts/servers").ServerType }) {
|
||||
function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" }) {
|
||||
return (
|
||||
<span className={cn(
|
||||
"inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-bold border shrink-0",
|
||||
@@ -261,7 +261,7 @@ function TypeChip({ type }: { type: import("@mmapp/contracts/servers").ServerTyp
|
||||
? "bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20"
|
||||
: "bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20",
|
||||
)}>
|
||||
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : type === "ix-node" ? "IX" : "EN"}
|
||||
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : "EN"}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -874,7 +874,7 @@ function CopyRulesSheet({
|
||||
greByServer: Record<string, GreTunnel[]>
|
||||
ensureGreFor?: (serverId: string) => void
|
||||
recRoutesByServer: Record<string, RecursiveRouteLite[]>
|
||||
ensureRecursiveFor?: (serverId: string) => Promise<void>
|
||||
ensureRecursiveFor?: (serverId: string) => void
|
||||
catalogReady?: GatewayReadiness
|
||||
}) {
|
||||
const [selected, setSelected] = useState<Set<string>>(() => new Set(sourceRules.map(r => r.id)))
|
||||
@@ -1229,11 +1229,7 @@ function CopyRulesSheet({
|
||||
</fieldset>
|
||||
{targetId && !mappingReady && <div className="px-5 py-3 flex flex-col gap-2">
|
||||
<p role="alert" className="text-sm text-destructive">Каталоги или сопоставление шлюзов не подтверждены. Копирование маршрутов заблокировано.</p>
|
||||
<Button variant="outline" disabled={copying} onClick={() => {
|
||||
ensureGreFor?.(sourceServerId)
|
||||
ensureGreFor?.(targetId)
|
||||
void ensureRecursiveFor?.(sourceServerId).then(() => ensureRecursiveFor(targetId))
|
||||
}}>Обновить шлюзы</Button>
|
||||
<Button variant="outline" disabled={copying} onClick={() => { for (const id of [sourceServerId, targetId]) { ensureGreFor?.(id); ensureRecursiveFor?.(id) } }}>Обновить шлюзы</Button>
|
||||
</div>}
|
||||
{copyError && <p role="alert" className="px-5 py-3 text-sm text-destructive">{copyError}</p>}
|
||||
{copying && <p role="status" className="px-5 py-2 text-sm text-muted-foreground">Ожидание подтверждения копирования…</p>}
|
||||
@@ -1272,28 +1268,6 @@ function makeApiFetch(backendUrl: string) {
|
||||
}
|
||||
}
|
||||
|
||||
const configurationBusyMessage = "Конфигурация временно занята другой операцией"
|
||||
|
||||
function isConfigurationBusy(error: unknown): boolean {
|
||||
if (!(error instanceof ApiClientError) || error.status !== 409) return false
|
||||
const payload = error.payload
|
||||
return (typeof payload === "object" && payload !== null && "code" in payload && payload.code === "CONFIGURATION_BUSY")
|
||||
|| /^(?:Глобальная конфигурация|Конфигурация сервера) изменяется другой операцией$/.test(error.message)
|
||||
}
|
||||
|
||||
async function readFiltersWithRetry<T>(read: () => Promise<T>, isCurrent: () => boolean): Promise<T> {
|
||||
for (const delay of [350, 1000]) {
|
||||
try {
|
||||
return await read()
|
||||
} catch (error) {
|
||||
if (!isConfigurationBusy(error) || !isCurrent()) throw error
|
||||
await new Promise(resolve => setTimeout(resolve, delay))
|
||||
if (!isCurrent()) throw error
|
||||
}
|
||||
}
|
||||
return read()
|
||||
}
|
||||
|
||||
function FiltersPage() {
|
||||
const { mode, backendUrl } = useDataSource()
|
||||
const mounted = useRef(true)
|
||||
@@ -1362,10 +1336,7 @@ function FiltersPage() {
|
||||
setGatewayReady(prev => ({ ...prev, [serverId]: { ...prev[serverId], [kind]: false } }))
|
||||
try {
|
||||
const path = kind === "gre" ? "/api/filters/gre-tunnels" : "/api/recursive-routes"
|
||||
const payload = await readFiltersWithRetry(
|
||||
() => apiFetch<unknown>(`${path}?serverId=${encodeURIComponent(serverId)}`),
|
||||
() => mounted.current && gatewayEpoch.current[key] === epoch,
|
||||
)
|
||||
const payload = await apiFetch<unknown>(`${path}?serverId=${encodeURIComponent(serverId)}`)
|
||||
if (!mounted.current || gatewayEpoch.current[key] !== epoch) return
|
||||
if (kind === "gre") {
|
||||
const parsed = filtersGreResponseSchema.safeParse(payload)
|
||||
@@ -1381,9 +1352,7 @@ function FiltersPage() {
|
||||
setGatewayErrors(prev => ({ ...prev, [serverId]: { ...prev[serverId], [kind]: undefined } }))
|
||||
} catch (error) {
|
||||
if (!mounted.current || gatewayEpoch.current[key] !== epoch) return
|
||||
const message = isConfigurationBusy(error) ? configurationBusyMessage
|
||||
: error instanceof Error ? error.message : "Каталог шлюзов недоступен"
|
||||
setGatewayErrors(prev => ({ ...prev, [serverId]: { ...prev[serverId], [kind]: message } }))
|
||||
setGatewayErrors(prev => ({ ...prev, [serverId]: { ...prev[serverId], [kind]: error instanceof Error ? error.message : "Каталог шлюзов недоступен" } }))
|
||||
}
|
||||
}, [isLive, apiFetch])
|
||||
const ensureGreTunnels = useCallback((serverId: string) => loadGatewayCatalog(serverId, "gre"), [loadGatewayCatalog])
|
||||
@@ -1405,8 +1374,7 @@ function FiltersPage() {
|
||||
const [movePending, setMovePending] = useState(false)
|
||||
const [moveError, setMoveError] = useState<string | null>(null)
|
||||
const moveLock = useRef(false)
|
||||
const [rulesReadFailure, setRulesReadFailure] = useState<"busy" | "unavailable" | null>(null)
|
||||
const liveStale = rulesReadFailure !== null
|
||||
const [liveStale, setLiveStale] = useState(false)
|
||||
const readEpoch = useRef(0)
|
||||
const [readyServerId, setReadyServerId] = useState<string | null>(null)
|
||||
const [rulesReading, setRulesReading] = useState(false)
|
||||
@@ -1426,7 +1394,7 @@ function FiltersPage() {
|
||||
setRulesets(buildRulesets(servers, serverFilterRulesets))
|
||||
setSelectedServerId(servers[0]?.id ?? "")
|
||||
setLiveLoadState("idle")
|
||||
setRulesReadFailure(null)
|
||||
setLiveStale(false)
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -1486,9 +1454,8 @@ function FiltersPage() {
|
||||
setReadyServerId(null)
|
||||
setRulesReading(true)
|
||||
try {
|
||||
const payload = await readFiltersWithRetry(
|
||||
() => apiFetch<unknown>(`/api/filters/rules?serverId=${encodeURIComponent(serverId)}`),
|
||||
() => mounted.current && epoch === readEpoch.current,
|
||||
const payload = await apiFetch<unknown>(
|
||||
`/api/filters/rules?serverId=${encodeURIComponent(serverId)}`,
|
||||
)
|
||||
if (epoch !== readEpoch.current) return false
|
||||
const parsed = filtersResponseSchema.safeParse(payload)
|
||||
@@ -1502,47 +1469,35 @@ function FiltersPage() {
|
||||
if (!has) return [...prev, { serverId, rules: liveRules }]
|
||||
return prev.map((rs) => rs.serverId === serverId ? { ...rs, rules: liveRules } : rs)
|
||||
})
|
||||
setRulesReadFailure(null)
|
||||
setLiveStale(false)
|
||||
setReadyServerId(serverId)
|
||||
setRulesReceipt(prev => ({ ...prev, [serverId]: { at: new Date().toISOString(), kind: "read" } }))
|
||||
return true
|
||||
} catch (err) {
|
||||
if (epoch !== readEpoch.current) return false
|
||||
const busy = isConfigurationBusy(err)
|
||||
setRulesReadFailure(busy ? "busy" : "unavailable")
|
||||
if (!busy) toast.error("Не удалось прочитать правила с роутера", {
|
||||
description: err instanceof Error ? err.message : "Ошибка чтения правил",
|
||||
})
|
||||
setLiveStale(true)
|
||||
toast.error("Не удалось прочитать правила с роутера", { description: String(err) })
|
||||
return false
|
||||
} finally {
|
||||
if (epoch === readEpoch.current) setRulesReading(false)
|
||||
}
|
||||
}, [isLive, apiFetch])
|
||||
|
||||
const loadServerFilters = useCallback(async (serverId: string) => {
|
||||
const gre = ensureGreTunnels(serverId)
|
||||
const rules = loadLiveRules(serverId)
|
||||
const epoch = readEpoch.current
|
||||
await rules
|
||||
// Both these GETs record observations under the same exclusive application lock.
|
||||
if (mounted.current && epoch === readEpoch.current) await ensureRecursiveRoutes(serverId)
|
||||
await gre
|
||||
}, [loadLiveRules, ensureGreTunnels, ensureRecursiveRoutes])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLive || !selectedServerId || liveLoadState !== "idle") return
|
||||
if (!liveServers.some((s) => s.id === selectedServerId)) return
|
||||
void loadServerFilters(selectedServerId)
|
||||
}, [isLive, selectedServerId, liveLoadState, liveServers, loadServerFilters])
|
||||
void Promise.all([
|
||||
loadLiveRules(selectedServerId),
|
||||
ensureGreTunnels(selectedServerId),
|
||||
ensureRecursiveRoutes(selectedServerId),
|
||||
])
|
||||
}, [isLive, selectedServerId, liveLoadState, liveServers, ensureGreTunnels, ensureRecursiveRoutes, loadLiveRules])
|
||||
|
||||
const allServers = !isLive ? servers : liveServers
|
||||
const allTunnels = !isLive ? greTunnels : (greByServer[selectedServerId] ?? [])
|
||||
const selectedServer = allServers.find(s => s.id === selectedServerId) ?? allServers[0]
|
||||
const totalRules = rulesets.reduce((s, r) => s + r.rules.length, 0)
|
||||
const mutationsLocked = (isLive && !can("mm:filters:write")) || movePending || (isLive && (applyBusy || historyRestoring || rulesReading || readyServerId !== selectedServerId || liveStale || liveLoadState !== "idle"))
|
||||
const gatewayMessages = [...new Set(Object.values(gatewayErrors[selectedServerId] ?? {}))]
|
||||
.filter((message): message is string => Boolean(message) && !(rulesReadFailure === "busy" && message === configurationBusyMessage))
|
||||
const gatewaysBusy = gatewayMessages.every(message => message === configurationBusyMessage)
|
||||
|
||||
const filterRailItems = useMemo<ServerTileItem[]>(() => (
|
||||
allServers.map((s) => ({
|
||||
@@ -1563,7 +1518,7 @@ function FiltersPage() {
|
||||
readEpoch.current += 1
|
||||
setReadyServerId(null)
|
||||
setRulesReading(false)
|
||||
setRulesReadFailure(null)
|
||||
setLiveStale(false)
|
||||
setSheetOpen(false)
|
||||
setPendingDelete(null)
|
||||
setDeleteError(null)
|
||||
@@ -1597,9 +1552,7 @@ function FiltersPage() {
|
||||
if (!mounted.current) return { ok: false, error: "Источник данных изменён" }
|
||||
if (applyLock.current || applyBusy || historyRestoring) return { ok: false, error: "Дождитесь завершения текущей операции" }
|
||||
if (isLive && (liveStale || liveLoadState !== "idle" || (serverId === selectedServerId && readyServerId !== serverId))) {
|
||||
const error = rulesReadFailure === "busy"
|
||||
? configurationBusyMessage + ". Изменения недоступны до обновления правил."
|
||||
: "Роутер недоступен — изменения заблокированы"
|
||||
const error = "Роутер недоступен — изменения заблокированы"
|
||||
toast.error(error)
|
||||
return { ok: false, error }
|
||||
}
|
||||
@@ -1636,19 +1589,23 @@ function FiltersPage() {
|
||||
applyLock.current = false
|
||||
setApplyBusy(false)
|
||||
}
|
||||
}, [isLive, apiFetch, applyBusy, historyRestoring, liveStale, rulesReadFailure, liveLoadState, readyServerId, selectedServerId])
|
||||
}, [isLive, apiFetch, applyBusy, historyRestoring, liveStale, liveLoadState, readyServerId, selectedServerId])
|
||||
|
||||
const refreshFromRouter = useCallback(async () => {
|
||||
if (!isLive || !selectedServerId || !mounted.current || applyLock.current || applyBusy || historyRestoring) return
|
||||
applyLock.current = true
|
||||
setApplyBusy(true)
|
||||
try {
|
||||
await loadServerFilters(selectedServerId)
|
||||
await loadLiveRules(selectedServerId)
|
||||
await Promise.all([
|
||||
ensureGreTunnels(selectedServerId),
|
||||
ensureRecursiveRoutes(selectedServerId),
|
||||
])
|
||||
} finally {
|
||||
applyLock.current = false
|
||||
setApplyBusy(false)
|
||||
}
|
||||
}, [isLive, selectedServerId, applyBusy, historyRestoring, loadServerFilters])
|
||||
}, [isLive, selectedServerId, applyBusy, historyRestoring, loadLiveRules, ensureGreTunnels, ensureRecursiveRoutes])
|
||||
|
||||
useEffect(() => () => { historyEpoch.current += 1; readEpoch.current += 1 }, [selectedServerId, backendUrl, isLive])
|
||||
|
||||
@@ -1696,7 +1653,7 @@ function FiltersPage() {
|
||||
if (!await loadLiveRules(selectedServerId)) throw new Error("Версия применена, но актуальные правила не прочитаны — обновите данные")
|
||||
}
|
||||
if (!mounted.current) return
|
||||
setRulesReadFailure(null)
|
||||
setLiveStale(false)
|
||||
setReadyServerId(selectedServerId)
|
||||
await loadRevisions()
|
||||
if (!mounted.current) return
|
||||
@@ -1922,17 +1879,15 @@ function FiltersPage() {
|
||||
<Button variant="outline" size="sm" onClick={() => setLoadAttempt(n => n + 1)}>Повторить загрузку</Button>
|
||||
</div>
|
||||
)}
|
||||
{isLive && gatewayMessages.length > 0 && <div className="border-b px-6 py-3 flex items-center gap-3">
|
||||
<p role={gatewaysBusy ? "status" : "alert"} className={cn("text-xs", gatewaysBusy ? "text-muted-foreground" : "text-destructive")}>{gatewayMessages.join(" · ")}. Сохранены последние каталоги шлюзов.</p>
|
||||
{isLive && Object.values(gatewayErrors[selectedServerId] ?? {}).some(Boolean) && <div className="border-b px-6 py-3 flex items-center gap-3">
|
||||
<p role="alert" className="text-xs text-destructive">{Object.values(gatewayErrors[selectedServerId] ?? {}).filter(Boolean).join(" · ")}. Сохранены последние каталоги шлюзов.</p>
|
||||
<Button variant="outline" size="sm" disabled={applyBusy} onClick={() => { void ensureGreTunnels(selectedServerId); void ensureRecursiveRoutes(selectedServerId) }}>Обновить шлюзы</Button>
|
||||
</div>}
|
||||
{isLive && rulesReading && <p role="status" className="border-b px-6 py-2 text-xs text-muted-foreground">Чтение актуальных правил устройства… Изменения временно заблокированы.</p>}
|
||||
{isLive && liveStale && liveLoadState !== "error" && (
|
||||
<div className="shrink-0 border-b border-amber-500/30 bg-amber-500/10 px-6 py-2.5 text-xs text-amber-700 dark:text-amber-400 flex items-center gap-2">
|
||||
<AlertTriangleIcon className="size-3.5 shrink-0" />
|
||||
{rulesReadFailure === "busy"
|
||||
? configurationBusyMessage + ". Показаны последние правила. Изменения недоступны до обновления правил."
|
||||
: "Роутер недоступен — показан кэш. Изменения заблокированы, пока не удастся прочитать CHR."}
|
||||
Роутер недоступен — показан кэш. Изменения заблокированы, пока не удастся прочитать CHR.
|
||||
</div>
|
||||
)}
|
||||
<div className="border-b px-4 py-3 flex items-center gap-3 flex-wrap shrink-0 md:px-6">
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
"use client"
|
||||
|
||||
import { serverTypeSchema } from "@mmapp/contracts/servers"
|
||||
import { can } from "@/lib/auth"
|
||||
|
||||
import { z } from "zod"
|
||||
@@ -175,7 +174,7 @@ function mapBackendServer(s: BackendServer): InventoryServer {
|
||||
const ipsecInventorySchema = z.array(z.object({
|
||||
id: z.number().int().positive(), name: z.string(), host: z.string(), enabled: z.boolean(),
|
||||
country: z.string().optional().default("UN"),
|
||||
type: serverTypeSchema.optional(),
|
||||
type: z.enum(["jump-host", "exit-node", "home-router"]).optional(),
|
||||
status: z.enum(["online", "offline", "degraded"]).nullable().optional(),
|
||||
latency: z.number().nullable().optional(), asn: z.string().optional(),
|
||||
})).refine(rows => new Set(rows.map(row => row.id)).size === rows.length)
|
||||
|
||||
@@ -1,228 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useId, type ReactNode } from "react"
|
||||
import Link from "next/link"
|
||||
import { PlusIcon, XIcon } from "lucide-react"
|
||||
import type { IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Field, FieldLabel } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
|
||||
type Binding = IxSite["interfaces"][number]
|
||||
type Group = IxSite["groups"][number]
|
||||
type Path = Group["primary"]
|
||||
type Peer = IxSite["neighbors"][number]
|
||||
type Choice = { value: string; label: string }
|
||||
|
||||
function TextField({ label, value, edit, numeric, placeholder }: {
|
||||
label: string; value: string | number; edit: (value: string) => void; numeric?: boolean; placeholder?: string
|
||||
}) {
|
||||
const id = useId()
|
||||
return <Field className="min-w-0">
|
||||
<FieldLabel htmlFor={id}>{label}</FieldLabel>
|
||||
<Input id={id} value={value} inputMode={numeric ? "numeric" : undefined} placeholder={placeholder}
|
||||
onChange={event => { if (!numeric || /^\d*$/.test(event.target.value)) edit(event.target.value) }} />
|
||||
</Field>
|
||||
}
|
||||
|
||||
function Pick<T extends string>({ label, value, options, edit, disabled }: {
|
||||
label: string; value?: T; options: readonly { value: T; label: string }[]; edit: (value: T) => void; disabled: boolean
|
||||
}) {
|
||||
const id = useId()
|
||||
return <Field className="min-w-0">
|
||||
<FieldLabel htmlFor={id}>{label}</FieldLabel>
|
||||
<Select value={value ?? null} items={options} disabled={disabled}
|
||||
onValueChange={next => { if (next !== null) edit(next) }}>
|
||||
<SelectTrigger className="w-full" id={id}><SelectValue placeholder="Выберите значение" /></SelectTrigger>
|
||||
<SelectContent>{options.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
}
|
||||
|
||||
function Flag({ label, checked, edit, disabled }: {
|
||||
label: string; checked: boolean; edit: (value: boolean) => void; disabled: boolean
|
||||
}) {
|
||||
const id = useId()
|
||||
return <Field orientation="horizontal" className="w-fit">
|
||||
<Checkbox id={id} checked={checked} onCheckedChange={edit} disabled={disabled} />
|
||||
<FieldLabel htmlFor={id}>{label}</FieldLabel>
|
||||
</Field>
|
||||
}
|
||||
|
||||
function Lines({ label, value, edit }: { label: string; value: string[]; edit: (value: string[]) => void }) {
|
||||
const id = useId()
|
||||
return <Field className="min-w-0">
|
||||
<FieldLabel htmlFor={id}>{label}</FieldLabel>
|
||||
<Textarea id={id} value={value.join("\n")} rows={2} placeholder="По одному префиксу на строку"
|
||||
onChange={event => edit(event.target.value.split("\n"))}
|
||||
onBlur={event => edit(event.target.value.split("\n").map(line => line.trim()).filter(Boolean))} />
|
||||
</Field>
|
||||
}
|
||||
|
||||
function Entries<T>({ title, items, edit, make, addLabel, max, readOnly, children }: {
|
||||
title: string; items: T[]; edit: (items: T[]) => void; make: () => T
|
||||
addLabel: string; max: number; readOnly: boolean; children: (item: T, edit: (item: T) => void) => ReactNode
|
||||
}) {
|
||||
return <details className="min-w-0 rounded-lg border">
|
||||
<summary className="cursor-pointer px-3 py-2 text-sm font-medium">{title} · {items.length}</summary>
|
||||
<div className="grid gap-3 border-t p-3">
|
||||
{items.map((item, index) => <div className="grid min-w-0 gap-3 rounded-md border p-3" key={index}>
|
||||
<div className="flex items-center justify-between gap-2 text-sm text-muted-foreground">
|
||||
<span>Запись {index + 1}</span>
|
||||
{!readOnly && <Button type="button" size="icon-sm" variant="ghost" aria-label={title + " — удалить запись " + (index + 1)}
|
||||
onClick={() => edit(items.filter((_, position) => position !== index))}><XIcon aria-hidden /></Button>}
|
||||
</div>
|
||||
{children(item, update => edit(items.map((entry, position) => position === index ? update : entry)))}
|
||||
</div>)}
|
||||
{!readOnly && <Button type="button" variant="outline" size="sm" className="w-fit" disabled={items.length >= max}
|
||||
onClick={() => edit([...items, make()])}><PlusIcon aria-hidden />{addLabel}</Button>}
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
|
||||
const columns = "grid min-w-0 gap-3 sm:grid-cols-2"
|
||||
const none = {value: "", label: "Нет"}
|
||||
const emptyPath = (name: string): Path => ({ interface: name, nextHop: "", probe: "" })
|
||||
const emptyWireGuard = { peerPublicKey: "", listenPort: 51820, localAddress: "", peerAddress: "" }
|
||||
const kinds = [
|
||||
{ value: "wireguard", label: "WireGuard" }, { value: "gre-ipsec", label: "GRE/IPsec" }, { value: "uplink", label: "Аплинк" },
|
||||
] as const
|
||||
|
||||
function InterfaceFields({ value, edit, peers, readOnly, segmentName }: {
|
||||
value: Binding; edit: (value: Binding) => void; peers: Choice[]; readOnly: boolean; segmentName: string
|
||||
}) {
|
||||
const wireGuard = value.provisionWireguard
|
||||
return <>
|
||||
<div className={columns}>
|
||||
<TextField label="Имя интерфейса" value={value.name} edit={name => edit({ ...value, name })} />
|
||||
<Pick label="Тип подключения" value={value.kind} options={kinds} disabled={readOnly}
|
||||
edit={kind => edit({ ...value, kind, ...(kind !== "wireguard" && {provisionWireguard: undefined}), ...(kind !== "uplink" && {natIpv4: undefined}) })} />
|
||||
<Pick label="Удалённый узел" value={value.peerServerId ? String(value.peerServerId) : ""} options={[{ value: "", label: "Внешний сервер" }, ...peers]} disabled={readOnly}
|
||||
edit={id => edit({ ...value, peerServerId: id ? Number(id) : undefined })} />
|
||||
<TextField label="Локальный внешний адрес" value={value.localEndpoint ?? ""} edit={address => edit({ ...value, localEndpoint: address || undefined })} />
|
||||
<TextField label="Удалённый внешний адрес" value={value.endpoint ?? ""} edit={address => edit({ ...value, endpoint: address || undefined })} />
|
||||
</div>
|
||||
<Lines label="Префиксы подключения" value={value.prefixes} edit={prefixes => edit({ ...value, prefixes })} />
|
||||
{value.kind === "gre-ipsec" && <p className="text-sm text-muted-foreground">
|
||||
Создайте выделенный туннель в разделе <Link className="underline" href="/gre">GRE-туннели</Link>.
|
||||
Укажите комментарий <code>IX:{segmentName || "<имя сегмента>"}</code>, включите IPsec и отключите FastPath.
|
||||
IX проверит обязательную транспортную политику GRE между указанными IPv4-адресами.
|
||||
</p>}
|
||||
{(value.kind === "uplink" || (value.kind === "wireguard" && !wireGuard)) && <p className="text-sm text-muted-foreground">
|
||||
Для подключения существующего интерфейса выделите его под этот сегмент и задайте комментарий <code>IX:{segmentName || "<имя сегмента>"}</code>.
|
||||
</p>}
|
||||
{value.kind === "uplink" && <Flag label="NAT IPv4" checked={!!value.natIpv4} disabled={readOnly} edit={natIpv4 => edit({ ...value, natIpv4 })} />}
|
||||
{value.kind === "wireguard" && <Flag label="Создать интерфейс и пир WireGuard на узле IX" checked={!!wireGuard} disabled={readOnly}
|
||||
edit={enabled => edit({ ...value, provisionWireguard: enabled ? { ...emptyWireGuard } : undefined })} />}
|
||||
{wireGuard && <div className={columns}>
|
||||
<TextField label="Публичный ключ пира" value={wireGuard.peerPublicKey} edit={peerPublicKey => edit({ ...value, provisionWireguard: { ...wireGuard, peerPublicKey } })} />
|
||||
<TextField label="Порт WireGuard на IX" numeric value={wireGuard.listenPort || ""} edit={port => edit({ ...value, provisionWireguard: { ...wireGuard, listenPort: Number(port) } })} />
|
||||
<TextField label="Локальный адрес туннеля (CIDR)" value={wireGuard.localAddress} edit={localAddress => edit({ ...value, provisionWireguard: { ...wireGuard, localAddress } })} />
|
||||
<TextField label="Адрес пира в туннеле" value={wireGuard.peerAddress} edit={peerAddress => edit({ ...value, provisionWireguard: { ...wireGuard, peerAddress } })} />
|
||||
<TextField label="Внешний адрес IX для шаблона Linux" value={wireGuard.hubEndpoint ?? ""} edit={address => edit({ ...value, provisionWireguard: { ...wireGuard, hubEndpoint: address || undefined } })} />
|
||||
<TextField label="Порт удалённого WireGuard" numeric value={wireGuard.endpointPort ?? ""} edit={port => edit({ ...value, provisionWireguard: { ...wireGuard, endpointPort: port ? Number(port) : undefined } })} />
|
||||
</div>}
|
||||
</>
|
||||
}
|
||||
|
||||
function PathFields({ title, value, edit, interfaces, readOnly }: {
|
||||
title: string; value: Path; edit: (value: Path) => void; interfaces: Choice[]; readOnly: boolean
|
||||
}) {
|
||||
return <fieldset className="grid min-w-0 gap-3 rounded-md border p-3 sm:grid-cols-3">
|
||||
<legend className="px-1 text-sm font-medium">{title}</legend>
|
||||
<Pick label="Интерфейс пути" value={value.interface} options={interfaces} edit={name => edit({ ...value, interface: name })} disabled={readOnly} />
|
||||
<TextField label="Адрес следующего шлюза" value={value.nextHop} edit={nextHop => edit({ ...value, nextHop })} />
|
||||
<TextField label="Контрольный адрес" value={value.probe} edit={probe => edit({ ...value, probe })} />
|
||||
</fieldset>
|
||||
}
|
||||
|
||||
function GroupFields({ value, edit, interfaces, readOnly }: {
|
||||
value: Group; edit: (value: Group) => void; interfaces: Choice[]; readOnly: boolean
|
||||
}) {
|
||||
return <>
|
||||
<div className={columns}>
|
||||
<TextField label="Имя группы шлюзов" value={value.id} edit={id => edit({ ...value, id })} />
|
||||
<TextField label="Служебный адрес шлюза" value={value.gateway} edit={gateway => edit({ ...value, gateway })} />
|
||||
<Pick label="Если оба пути недоступны" value={value.onFailure} disabled={readOnly} options={[
|
||||
{value: "block", label: "Отбрасывать трафик"}, {value: "segment-exit", label: "Использовать выход сегмента"},
|
||||
]} edit={onFailure => edit({ ...value, onFailure })} />
|
||||
</div>
|
||||
<PathFields title="Основной путь" value={value.primary} interfaces={interfaces} readOnly={readOnly} edit={primary => edit({ ...value, primary })} />
|
||||
<Flag label="Резервный путь" checked={!!value.backup} disabled={readOnly}
|
||||
edit={enabled => edit({ ...value, backup: enabled ? emptyPath(interfaces.find(item => item.value !== value.primary.interface)?.value ?? "") : undefined })} />
|
||||
{value.backup && <PathFields title="Резервный путь" value={value.backup} interfaces={interfaces} readOnly={readOnly} edit={backup => edit({ ...value, backup })} />}
|
||||
</>
|
||||
}
|
||||
|
||||
function PeerFields({ value, edit, interfaces, groups, readOnly }: {
|
||||
value: Peer; edit: (value: Peer) => void; interfaces: Choice[]; groups: Choice[]; readOnly: boolean
|
||||
}) {
|
||||
const publicFeed = value.type === "public-feed"
|
||||
return <>
|
||||
<div className={columns}>
|
||||
<TextField label="Имя BGP-соседа" value={value.id} edit={id => edit({ ...value, id })} />
|
||||
<Pick label="Тип BGP-соседа" value={value.type} disabled={readOnly} options={[
|
||||
{value: "member", label: "Участник IX"}, {value: "exchange", label: "Вторая площадка"}, {value: "public-feed", label: "Публичный фид"},
|
||||
]} edit={type => edit({ ...value, type, ...(type === "public-feed" ? { group: undefined, exportPrefixes: [] } : { rules: [] }) })} />
|
||||
<TextField label="Адрес BGP-соседа" value={value.address} edit={address => edit({ ...value, address })} />
|
||||
<TextField label="Локальный адрес BGP" value={value.localAddress} edit={localAddress => edit({ ...value, localAddress })} />
|
||||
<TextField label="ASN соседа" numeric value={value.remoteAs || ""} edit={asn => edit({ ...value, remoteAs: Number(asn) })} />
|
||||
<Pick label="Интерфейс BGP" value={value.binding} options={interfaces} disabled={readOnly} edit={binding => edit({ ...value, binding })} />
|
||||
<Pick label="Лимит префиксов" value={String(value.limit)} options={[10, 100, 1000, 10000].map(limit => ({value: String(limit), label: String(limit)}))}
|
||||
disabled={readOnly} edit={limit => edit({ ...value, limit: Number(limit) as Peer["limit"] })} />
|
||||
{!publicFeed && <Pick label="Группа шлюзов для импорта" value={value.group} options={groups} disabled={readOnly} edit={group => edit({ ...value, group })} />}
|
||||
</div>
|
||||
<Lines label="Префиксы импорта" value={value.prefixes} edit={prefixes => edit({ ...value, prefixes })} />
|
||||
{publicFeed
|
||||
? <Entries title="Правила по BGP community" items={value.rules} edit={rules => edit({ ...value, rules })}
|
||||
make={() => ({ community: "", group: groups[0]?.value ?? "" })} max={100} addLabel="Добавить правило" readOnly={readOnly}>
|
||||
{(rule, update) => <div className={columns}>
|
||||
<TextField label="BGP community" value={rule.community} placeholder="65000:10" edit={community => update({ ...rule, community })} />
|
||||
<Pick label="Группа шлюзов правила" value={rule.group} options={groups} edit={group => update({ ...rule, group })} disabled={readOnly} />
|
||||
</div>}
|
||||
</Entries>
|
||||
: <Lines label="Префиксы экспорта" value={value.exportPrefixes} edit={exportPrefixes => edit({ ...value, exportPrefixes })} />}
|
||||
</>
|
||||
}
|
||||
|
||||
export function IxSiteEditor({ site, edit, peers, readOnly, segmentName }: {
|
||||
site: IxSite; edit: (fields: Partial<IxSite>) => void; peers: Choice[]; readOnly: boolean; segmentName: string
|
||||
}) {
|
||||
const interfaces = site.interfaces.filter(item => item.name).map(item => ({ value: item.name, label: item.name }))
|
||||
const groups = site.groups.filter(item => item.id).map(item => ({ value: item.id, label: item.id }))
|
||||
return <fieldset className="grid min-w-0 gap-2" disabled={readOnly}>
|
||||
<Entries<Binding> title="Подключения" items={site.interfaces} edit={interfaces => edit({ interfaces })}
|
||||
make={() => ({ name: "", kind: "wireguard", prefixes: [] })} max={20} addLabel="Добавить подключение" readOnly={readOnly}>
|
||||
{(value, update) => <InterfaceFields value={value} edit={update} peers={peers} readOnly={readOnly} segmentName={segmentName} />}
|
||||
</Entries>
|
||||
<Entries<Group> title="Группы шлюзов" items={site.groups} edit={groups => edit({ groups })}
|
||||
make={() => ({ id: "", gateway: "", primary: emptyPath(interfaces[0]?.value ?? ""), onFailure: "block" })}
|
||||
max={24} addLabel="Добавить группу шлюзов" readOnly={readOnly}>
|
||||
{(value, update) => <GroupFields value={value} edit={update} interfaces={interfaces} readOnly={readOnly} />}
|
||||
</Entries>
|
||||
<Entries title="Статические маршруты" items={site.routes} edit={routes => edit({ routes })}
|
||||
make={() => ({ prefix: "", group: groups[0]?.value ?? "" })} max={250} addLabel="Добавить маршрут" readOnly={readOnly}>
|
||||
{(route, update) => <div className={columns}>
|
||||
<TextField label="Префикс маршрута" value={route.prefix} edit={prefix => update({ ...route, prefix })} />
|
||||
<Pick label="Группа шлюзов маршрута" value={route.group} options={groups} edit={group => update({ ...route, group })} disabled={readOnly} />
|
||||
</div>}
|
||||
</Entries>
|
||||
<Entries<Peer> title="BGP-соседи" items={site.neighbors} edit={neighbors => edit({ neighbors })} max={16} addLabel="Добавить BGP-соседа" readOnly={readOnly}
|
||||
make={() => ({ id: "", type: "member", address: "", localAddress: "", remoteAs: 0,
|
||||
binding: interfaces[0]?.value ?? "", group: groups[0]?.value, prefixes: [], exportPrefixes: [], rules: [], limit: 1000 })}>
|
||||
{(value, update) => <PeerFields value={value} edit={update} interfaces={interfaces} groups={groups} readOnly={readOnly} />}
|
||||
</Entries>
|
||||
<details className="rounded-lg border">
|
||||
<summary className="cursor-pointer px-3 py-2 text-sm font-medium">Выходы по умолчанию и маршруты отбрасывания</summary>
|
||||
<div className="grid gap-3 border-t p-3">
|
||||
{[0, 1].map(index => <Pick key={index} label={"Группа выхода " + (index + 1)} value={site.exits[index] ?? ""}
|
||||
options={[none, ...groups.filter(group => group.value !== site.exits[1 - index])]} disabled={readOnly}
|
||||
edit={id => { const exits = [...site.exits]; exits[index] = id; edit({ exits: exits.filter(Boolean) }) }} />)}
|
||||
<Lines label="Префиксы отбрасывания" value={site.discardNetworks} edit={discardNetworks => edit({ discardNetworks })} />
|
||||
</div>
|
||||
</details>
|
||||
</fieldset>
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo } from "react"
|
||||
import { type ColumnDef, useTable } from "@tanstack/react-table"
|
||||
import { FileTextIcon, PlusIcon, XIcon } from "lucide-react"
|
||||
import type { IxConfiguration, IxSegment, IxSite, IxSiteObservation } from "@mmapp/contracts/internet-exchange"
|
||||
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
|
||||
import { EmptyState } from "@/components/empty-state"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
|
||||
import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { IxSiteEditor } from "./ix-site-editor"
|
||||
|
||||
export type IxNode = { id: number; name: string; site: string; country: string; enabled: boolean }
|
||||
type Route = IxSiteObservation["routes"][number]
|
||||
|
||||
export const nodeLabel = (nodes: readonly IxNode[], id: number) => nodes.find(node => node.id === id)?.name || `Узел ${id}`
|
||||
export const newSite = (): IxSite => ({
|
||||
serverId: 0, autonomousSystem: 64512, routerId: "",
|
||||
interfaces: [], groups: [], exits: [], routes: [], neighbors: [], discardNetworks: [],
|
||||
})
|
||||
|
||||
export function SegmentStatus({ segment }: { segment: IxSegment }) {
|
||||
return segment.revision === segment.appliedRevision
|
||||
? <Badge variant="success-light">Применена</Badge>
|
||||
: <Badge variant="warning-light">{segment.appliedRevision ? "Есть черновик" : "Черновик"}</Badge>
|
||||
}
|
||||
|
||||
export function SegmentGrid({ rows, nodes, loading, open, empty }: {
|
||||
rows: IxSegment[]; nodes: IxNode[]; loading: boolean; open: (segment: IxSegment) => void; empty: React.ReactNode
|
||||
}) {
|
||||
const columns = useMemo<ColumnDef<DataGridFeatures, IxSegment>[]>(() => [
|
||||
{ id: "name", header: "Сегмент", size: 210, cell: ({ row }) => (
|
||||
<Button type="button" variant="link" size="sm" className="max-w-full justify-start" onClick={() => open(row.original)}>
|
||||
<span className="truncate">{row.original.configuration.name}</span>
|
||||
</Button>
|
||||
) },
|
||||
{ id: "sites", header: "Площадки", size: 230, cell: ({ row }) => row.original.configuration.sites.map(site => nodeLabel(nodes, site.serverId)).join(", ") },
|
||||
{ id: "neighbors", header: "BGP-соседи", size: 115, cell: ({ row }) =>
|
||||
<span className="tabular-nums">{row.original.configuration.sites.reduce((total, site) => total + site.neighbors.length, 0)}</span> },
|
||||
{ id: "state", header: "Состояние", size: 140, cell: ({ row }) => <SegmentStatus segment={row.original} /> },
|
||||
], [nodes, open])
|
||||
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns, getRowId: row => row.id })
|
||||
return <DataGridShell table={table} recordCount={rows.length} isLoading={loading} loadingMode="skeleton" emptyMessage={empty} />
|
||||
}
|
||||
|
||||
export function ConfigurationFields({ configuration, nodes, peers, readOnly, change }: {
|
||||
configuration: IxConfiguration; nodes: IxNode[]; peers: IxNode[]; readOnly: boolean; change: (value: IxConfiguration) => void
|
||||
}) {
|
||||
function updateSite(index: number, fields: Partial<IxSite>) {
|
||||
change({ ...configuration, sites: configuration.sites.map((site, position) => position === index ? { ...site, ...fields } : site) })
|
||||
}
|
||||
const canAddSite = configuration.sites.length < 2 && nodes.filter(node => node.enabled).length > configuration.sites.length
|
||||
|
||||
return <div className="grid min-w-0 gap-3">
|
||||
<Frame spacing="sm">
|
||||
<FrameHeader><FrameTitle>Сегмент</FrameTitle></FrameHeader>
|
||||
<FramePanel>
|
||||
<Field className="max-w-md">
|
||||
<FieldLabel htmlFor="ix-name">Имя сегмента</FieldLabel>
|
||||
<Input id="ix-name" placeholder="ix-central" value={configuration.name} readOnly={readOnly}
|
||||
onChange={event => change({ ...configuration, name: event.target.value })} />
|
||||
{!readOnly && <FieldDescription>Латинские строчные буквы, цифры и дефисы.</FieldDescription>}
|
||||
</Field>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
{configuration.sites.map((site, index) => {
|
||||
const fieldId = `ix-site-${index}`
|
||||
const choices = nodes.filter(node => node.id === site.serverId || (node.enabled && !configuration.sites.some((other, i) => i !== index && other.serverId === node.id)))
|
||||
return <Frame key={fieldId} spacing="sm">
|
||||
<FrameHeader className="flex-row items-center justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<FrameTitle>Площадка {index + 1}</FrameTitle>
|
||||
{site.serverId > 0 && <FrameDescription className="wrap-anywhere">{nodeLabel(nodes, site.serverId)}</FrameDescription>}
|
||||
</div>
|
||||
{!readOnly && configuration.sites.length > 1 && <Button type="button" size="icon-sm" variant="ghost"
|
||||
aria-label={`Убрать площадку ${index + 1}`}
|
||||
onClick={() => change({ ...configuration, sites: configuration.sites.filter((_, position) => position !== index) })}>
|
||||
<XIcon aria-hidden />
|
||||
</Button>}
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid gap-4">
|
||||
<div className="grid min-w-0 gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<Field className="min-w-0">
|
||||
<FieldLabel htmlFor={fieldId}>Узел IX</FieldLabel>
|
||||
<Select
|
||||
value={site.serverId ? String(site.serverId) : null}
|
||||
items={choices.map(node => ({ value: String(node.id), label: node.name }))}
|
||||
disabled={readOnly}
|
||||
onValueChange={value => { if (value) updateSite(index, { serverId: Number(value) }) }}
|
||||
>
|
||||
<SelectTrigger id={fieldId} className="w-full"><SelectValue placeholder="Выберите узел" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{choices.map(node => <SelectItem key={node.id} value={String(node.id)} disabled={!node.enabled}>{node.name}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field className="min-w-0">
|
||||
<FieldLabel htmlFor={fieldId + "-asn"}>Локальный ASN</FieldLabel>
|
||||
<Input id={fieldId + "-asn"} inputMode="numeric" value={site.autonomousSystem || ""} readOnly={readOnly}
|
||||
onChange={event => { if (/^\d*$/.test(event.target.value)) updateSite(index, { autonomousSystem: Number(event.target.value) }) }} />
|
||||
</Field>
|
||||
<Field className="min-w-0">
|
||||
<FieldLabel htmlFor={fieldId + "-router"}>Router ID</FieldLabel>
|
||||
<Input id={fieldId + "-router"} placeholder="192.0.2.10" value={site.routerId} readOnly={readOnly}
|
||||
onChange={event => updateSite(index, { routerId: event.target.value })} />
|
||||
</Field>
|
||||
</div>
|
||||
<IxSiteEditor site={site} segmentName={configuration.name} readOnly={readOnly} edit={fields => updateSite(index, fields)}
|
||||
peers={peers.filter(node => node.id !== site.serverId && (node.enabled || site.interfaces.some(binding => binding.peerServerId === node.id)))
|
||||
.map(node => ({ value: String(node.id), label: node.name }))} />
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
})}
|
||||
{!readOnly && canAddSite && <Button type="button" variant="outline" size="sm" className="w-fit"
|
||||
onClick={() => change({ ...configuration, sites: [...configuration.sites, newSite()] })}>
|
||||
<PlusIcon aria-hidden />Добавить площадку
|
||||
</Button>}
|
||||
</div>
|
||||
}
|
||||
|
||||
const routeColumns: ColumnDef<DataGridFeatures, Route>[] = [
|
||||
{ id: "prefix", header: "Префикс", size: 160, cell: ({ row }) => <span className="font-mono">{row.original.prefix}</span> },
|
||||
{ id: "gateway", header: "Шлюз", size: 140, cell: ({ row }) => row.original.gateway || "—" },
|
||||
{ id: "immediate", header: "Фактический next hop", size: 200, cell: ({ row }) => row.original.immediateGateway ?? "—" },
|
||||
{ id: "active", header: "Состояние", size: 112, cell: ({ row }) => row.original.active
|
||||
? <Badge variant="success-light">Активен</Badge>
|
||||
: <Badge variant="secondary">Неактивен</Badge> },
|
||||
]
|
||||
|
||||
export function RouteGrid({ observation, nodes }: { observation: IxSiteObservation; nodes: IxNode[] }) {
|
||||
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: observation.routes, columns: routeColumns })
|
||||
return <Frame spacing="sm" className="min-w-0">
|
||||
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<FrameTitle className="wrap-anywhere">{nodeLabel(nodes, observation.serverId)}</FrameTitle>
|
||||
<FrameDescription>{new Date(observation.observedAt).toLocaleString("ru-RU")}</FrameDescription>
|
||||
</div>
|
||||
{observation.available ? <Badge variant="info-light">
|
||||
BGP {observation.neighbors.filter(peer => peer.established).length} из {observation.neighbors.length}
|
||||
</Badge> : <Badge variant="warning-light">Состояние недоступно</Badge>}
|
||||
</FrameHeader>
|
||||
{observation.available && <FramePanel className="min-w-0 p-0">
|
||||
<div className="overflow-x-auto">
|
||||
<DataGridShell table={table} recordCount={observation.routes.length}
|
||||
emptyMessage={<EmptyState icon={<FileTextIcon />} title="Маршруты не найдены" className="py-8" />} />
|
||||
</div>
|
||||
</FramePanel>}
|
||||
</Frame>
|
||||
}
|
||||
@@ -1,392 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { ArrowLeftIcon, CircleAlertIcon, NetworkIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
|
||||
import { ixSegmentConfigurationSchema, type IxChange, type IxConfiguration, type IxLinuxAccess, type IxLinuxBinding, type IxWebPlan, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange"
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
|
||||
import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
|
||||
import { EmptyState } from "@/components/empty-state"
|
||||
import { PageHeader } from "@/components/page-header"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { can, ensureAuthConfig } from "@/lib/auth"
|
||||
import { useDataSource } from "@/lib/data-source"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
import { ConfigurationFields, newSite, nodeLabel, RouteGrid, SegmentGrid, SegmentStatus, type IxNode } from "./ix-view"
|
||||
|
||||
type Tab = "configuration" | "routes" | "changes" | "linux"
|
||||
|
||||
const title = "Точки обмена трафиком"
|
||||
const describe = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить операцию IX"
|
||||
const json = (value: unknown) => JSON.stringify(value, null, 2)
|
||||
const post = (value: unknown) => ({ method: "POST", body: JSON.stringify(value) })
|
||||
|
||||
const actionLabels = { create: "Создать", update: "Обновить", delete: "Удалить" } as const
|
||||
|
||||
export default function IxPage() {
|
||||
const { backendUrl, mode, prefsHydrated } = useDataSource()
|
||||
const [segments, setSegments] = useState<IxSegment[]>([])
|
||||
const [nodes, setNodes] = useState<IxNode[]>([])
|
||||
const [peers, setPeers] = useState<IxNode[]>([])
|
||||
const [selected, setSelected] = useState<IxSegment | null>(null)
|
||||
const [draft, setDraft] = useState<IxConfiguration | null>(null)
|
||||
const [advanced, setAdvanced] = useState<string | null>(null)
|
||||
const [filter, setFilter] = useState("")
|
||||
const [observations, setObservations] = useState<IxSiteObservation[] | null>(null)
|
||||
const [linuxBindings, setLinuxBindings] = useState<IxLinuxBinding[]>([])
|
||||
const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding) | null>(null)
|
||||
const [plan, setPlan] = useState<IxWebPlan | null>(null)
|
||||
const [tab, setTab] = useState<Tab>("configuration")
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState("")
|
||||
const [notice, setNotice] = useState("")
|
||||
const [write, setWrite] = useState(false)
|
||||
const heading = useRef<HTMLHeadingElement>(null)
|
||||
const focusAfterNavigation = useRef(false)
|
||||
const inDetail = draft !== null
|
||||
|
||||
async function load(signal?: AbortSignal) {
|
||||
if (signal?.aborted) return
|
||||
setWrite(can("mm:network:write"))
|
||||
const [segmentsResult, nodesResult] = await Promise.all([
|
||||
requestJson<{ items: IxSegment[] }>(backendUrl, "/api/ix/segments?limit=100", { signal }),
|
||||
requestJson<{ items: IxNode[]; peers?: IxNode[] }>(backendUrl, "/api/ix/nodes", { signal }),
|
||||
])
|
||||
if (signal?.aborted) return
|
||||
setSegments(segmentsResult.items)
|
||||
setNodes(nodesResult.items)
|
||||
|
||||
setPeers(nodesResult.peers ?? nodesResult.items)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!prefsHydrated || mode !== "live") return
|
||||
const controller = new AbortController()
|
||||
void ensureAuthConfig().then(() => {
|
||||
if (controller.signal.aborted) return
|
||||
setLoading(true)
|
||||
setError("")
|
||||
return load(controller.signal)
|
||||
})
|
||||
.catch(error => { if (!controller.signal.aborted) setError(describe(error)) })
|
||||
.finally(() => { if (!controller.signal.aborted) setLoading(false) })
|
||||
return () => controller.abort()
|
||||
// Reload when the project data source changes.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [backendUrl, mode, prefsHydrated])
|
||||
|
||||
useEffect(() => {
|
||||
if (focusAfterNavigation.current) {
|
||||
focusAfterNavigation.current = false
|
||||
heading.current?.focus()
|
||||
}
|
||||
}, [inDetail])
|
||||
|
||||
const rows = segments.filter(segment => segment.configuration.name.includes(filter.trim().toLowerCase()))
|
||||
const enabledNodes = nodes.filter(node => node.enabled)
|
||||
const live = prefsHydrated && mode === "live"
|
||||
const canCreate = live && write && !loading && enabledNodes.length > 0
|
||||
const savedConfiguration = selected ? json(selected.configuration) : null
|
||||
const dirty = (advanced ?? json(draft)) !== savedConfiguration
|
||||
const canPlan = live && write && selected !== null && selected.appliedRevision !== selected.revision && !dirty
|
||||
|
||||
function invalidateReview() {
|
||||
setPlan(null)
|
||||
setNotice("")
|
||||
}
|
||||
|
||||
function open(segment: IxSegment | null) {
|
||||
focusAfterNavigation.current = !inDetail
|
||||
setSelected(segment)
|
||||
setDraft(segment?.configuration ?? { name: "", sites: [{ ...newSite(), serverId: enabledNodes.length === 1 ? enabledNodes[0].id : 0 }] })
|
||||
setAdvanced(null)
|
||||
setObservations(null)
|
||||
setLinux(null)
|
||||
setLinuxBindings([])
|
||||
setTab("configuration")
|
||||
setError("")
|
||||
invalidateReview()
|
||||
}
|
||||
|
||||
function close() {
|
||||
focusAfterNavigation.current = true
|
||||
setDraft(null)
|
||||
setError("")
|
||||
setNotice("")
|
||||
}
|
||||
|
||||
function change(): IxChange {
|
||||
const configuration = ixSegmentConfigurationSchema.parse(advanced === null ? draft : JSON.parse(advanced))
|
||||
return { ...(selected ? { id: selected.id } : {}), revision: selected?.revision ?? 0, configuration }
|
||||
}
|
||||
|
||||
async function perform(work: () => Promise<void>) {
|
||||
setBusy(true)
|
||||
setError("")
|
||||
setNotice("")
|
||||
try { await work() } catch (error) { setError(describe(error)) }
|
||||
finally { setBusy(false) }
|
||||
}
|
||||
|
||||
async function save() {
|
||||
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl, "/api/ix/segments", post(change()))
|
||||
open(segment)
|
||||
setSegments(current => current.some(item => item.id === segment.id)
|
||||
? current.map(item => item.id === segment.id ? segment : item)
|
||||
: [segment, ...current])
|
||||
setNotice("Черновик сохранён")
|
||||
}
|
||||
|
||||
async function prepare() {
|
||||
if (!selected || !canPlan) return
|
||||
setPlan(null)
|
||||
setPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + selected.id + "/plan", post({ revision: selected.revision })))
|
||||
}
|
||||
|
||||
async function apply() {
|
||||
if (!selected || !plan || !canPlan) return
|
||||
setPlan(null)
|
||||
try {
|
||||
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl,
|
||||
"/api/ix/segments/" + selected.id + "/apply", post({ revision: plan.revision, digest: plan.digest }))
|
||||
setSelected(segment)
|
||||
setDraft(segment.configuration)
|
||||
setAdvanced(null)
|
||||
setObservations(null)
|
||||
setLinux(null)
|
||||
setLinuxBindings([])
|
||||
setSegments(current => current.map(item => item.id === segment.id ? segment : item))
|
||||
setNotice("Конфигурация IX применена")
|
||||
} catch (error) {
|
||||
throw new Error(describe(error) + " Проверьте состояние сегмента перед повторным применением.")
|
||||
}
|
||||
}
|
||||
|
||||
async function observe() {
|
||||
if (!selected?.appliedRevision) return
|
||||
const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${selected.id}/status`)
|
||||
setObservations(sites)
|
||||
}
|
||||
|
||||
async function loadLinuxBindings() {
|
||||
if (!selected) return
|
||||
setLinux(null)
|
||||
setLinuxBindings([])
|
||||
const { items } = await requestJson<{ items: IxLinuxBinding[] }>(backendUrl, `/api/ix/segments/${selected.id}/linux`)
|
||||
setLinuxBindings(items)
|
||||
}
|
||||
|
||||
async function exportLinux(binding: IxLinuxBinding) {
|
||||
if (!selected) return
|
||||
setLinux(null)
|
||||
const query = new URLSearchParams({ serverId: String(binding.serverId), interfaceName: binding.interfaceName })
|
||||
const access = await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`)
|
||||
setLinux({ ...binding, ...access })
|
||||
}
|
||||
|
||||
function showTab(next: Tab) {
|
||||
if (next === tab || busy) return
|
||||
setError("")
|
||||
setTab(next)
|
||||
if (next === "routes" && observations === null && selected?.appliedRevision) void perform(observe)
|
||||
if (next === "linux" && selected?.appliedRevision) void perform(loadLinuxBindings)
|
||||
}
|
||||
|
||||
const listEmpty = error ? "Не удалось загрузить список" :
|
||||
filter.trim() ? "Сегменты не найдены" : !live ? "Подключите backend" : "Нет сегментов IX"
|
||||
const listDescription = error ? "Повторите загрузку списка." : filter.trim() ? "Попробуйте другое имя сегмента." :
|
||||
!live ? "Откройте раздел в режиме «Живые»." : enabledNodes.length ? undefined : "Сначала добавьте сервер типа IX Node."
|
||||
|
||||
return <>
|
||||
<PageHeader crumbs={inDetail ? [{ label: "Сегменты IX" }, { label: selected?.configuration.name ?? "Новый сегмент" }] : [{ label: title }]} />
|
||||
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto">
|
||||
<div className="mx-auto flex w-full max-w-6xl min-w-0 flex-col gap-4 p-4 md:gap-5 md:p-6" aria-busy={busy}>
|
||||
{inDetail && <Button type="button" variant="ghost" size="sm" className="w-fit" disabled={busy} onClick={close}>
|
||||
<ArrowLeftIcon aria-hidden />Все сегменты
|
||||
</Button>}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h1 ref={heading} tabIndex={-1} className="text-xl font-semibold tracking-tight wrap-anywhere md:text-2xl">
|
||||
{inDetail ? selected?.configuration.name ?? "Новый сегмент" : title}
|
||||
</h1>
|
||||
{inDetail && selected && <SegmentStatus segment={selected} />}
|
||||
</div>
|
||||
{inDetail ? (selected && <p className="mt-1 text-sm text-muted-foreground">
|
||||
Ревизия {selected.revision}{selected.appliedRevision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
|
||||
</p>) : <p className="mt-1 text-sm text-muted-foreground">Сегменты IX, площадки и маршрутизация</p>}
|
||||
</div>
|
||||
{!inDetail && <div className="flex flex-wrap items-center gap-2">
|
||||
<Button type="button" size="icon-sm" variant="outline" disabled={busy || loading || !live} aria-label="Обновить список"
|
||||
onClick={() => void perform(() => load())}><RefreshCwIcon aria-hidden /></Button>
|
||||
{canCreate && <Button type="button" size="sm" onClick={() => open(null)} disabled={busy}><PlusIcon aria-hidden />Добавить сегмент</Button>}
|
||||
</div>}
|
||||
</div>
|
||||
{error && <Alert variant="destructive"><CircleAlertIcon aria-hidden /><AlertTitle>Ошибка IX</AlertTitle><AlertDescription className="wrap-anywhere">{error}</AlertDescription></Alert>}
|
||||
{notice && <p role="status" className="text-sm text-muted-foreground">{notice}</p>}
|
||||
|
||||
{!draft ? <Frame spacing="sm" className="min-w-0">
|
||||
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
|
||||
<div><FrameTitle>Сегменты</FrameTitle><FrameDescription>{live && !loading ? `Найдено: ${rows.length}` : ""}</FrameDescription></div>
|
||||
<Input type="search" aria-label="Поиск сегментов" placeholder="Найти сегмент" className="w-full sm:w-56"
|
||||
value={filter} onChange={event => setFilter(event.target.value)} />
|
||||
</FrameHeader>
|
||||
<FramePanel className="min-w-0 p-0">
|
||||
<div className="overflow-x-auto">
|
||||
<SegmentGrid rows={rows} nodes={nodes} loading={!prefsHydrated || (live && loading)} open={open} empty={
|
||||
<EmptyState icon={<NetworkIcon aria-hidden />} title={listEmpty} description={listDescription}
|
||||
action={live && !filter.trim() && !error && enabledNodes.length === 0 ? <Button render={<Link href="/servers" />} nativeButton={false} size="sm" variant="outline">Открыть серверы</Button> : undefined} />
|
||||
} />
|
||||
</div>
|
||||
</FramePanel>
|
||||
</Frame> : <Tabs value={tab} onValueChange={value => showTab(value as Tab)} className="min-w-0 gap-3">
|
||||
<div className="min-w-0 overflow-x-auto border-b pb-1">
|
||||
<TabsList variant="line" aria-label="Разделы сегмента">
|
||||
<TabsTrigger value="configuration">Конфигурация</TabsTrigger>
|
||||
<TabsTrigger value="linux">Linux-клиенты</TabsTrigger>
|
||||
<TabsTrigger value="routes">Маршруты и BGP</TabsTrigger>
|
||||
<TabsTrigger value="changes">План изменений</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
|
||||
<TabsContent value="configuration" className="grid min-w-0 gap-3">
|
||||
{advanced === null ? <ConfigurationFields configuration={draft} nodes={nodes} peers={peers} readOnly={!live || !write || busy}
|
||||
change={value => { setDraft(value); invalidateReview() }} /> : <Frame spacing="sm">
|
||||
<FrameHeader><FrameTitle>Конфигурация JSON</FrameTitle><FrameDescription>Интерфейсы, группы шлюзов, маршруты и BGP-политики.</FrameDescription></FrameHeader>
|
||||
<FramePanel>
|
||||
<Textarea aria-label="Конфигурация JSON" spellCheck={false} readOnly={!live || !write || busy} rows={14}
|
||||
className="font-mono" value={advanced} onChange={event => { setAdvanced(event.target.value); invalidateReview() }} />
|
||||
</FramePanel>
|
||||
</Frame>}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{write && <Button type="button" size="sm" disabled={busy || !live} onClick={() => void perform(save)}>Сохранить черновик</Button>}
|
||||
{advanced === null ? <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => setAdvanced(json(draft))}>
|
||||
{write ? "Редактировать JSON" : "Показать JSON"}
|
||||
</Button> : <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
|
||||
setDraft(change().configuration)
|
||||
setAdvanced(null)
|
||||
})}>К форме</Button>}
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="routes" className="grid min-w-0 gap-3">
|
||||
{!selected?.appliedRevision ? <EmptyState title="Конфигурация ещё не применена"
|
||||
description="Маршруты и BGP-сессии появятся после применения плана." className="py-8" /> : <>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(observe)}>
|
||||
<RefreshCwIcon aria-hidden />Обновить состояние
|
||||
</Button>
|
||||
</div>
|
||||
{busy && observations === null && <Skeleton className="h-28 w-full" role="status" aria-label="Загрузка маршрутов" />}
|
||||
{observations?.map(site => <RouteGrid key={site.serverId} observation={site} nodes={nodes} />)}
|
||||
</>}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="linux" className="grid min-w-0 gap-3">
|
||||
<Frame spacing="sm">
|
||||
<FrameHeader>
|
||||
<FrameTitle>Доступ для Linux-серверов</FrameTitle>
|
||||
<FrameDescription>Выдайте каждому серверу отдельное подключение из применённой ревизии сегмента.</FrameDescription>
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid min-w-0 gap-3">
|
||||
{write && <div className="grid gap-2 text-sm text-muted-foreground">
|
||||
<p>В «Конфигурации» добавьте подключение на нужной площадке и выберите «Внешний сервер» в поле «Удалённый узел».</p>
|
||||
<p>Для WireGuard включите создание пира и укажите публичный ключ Linux, адреса, внешний адрес IX и разрешённые префиксы. Для GRE привяжите выделенный туннель с IKEv2/IPsec и отдельным PSK.</p>
|
||||
<Button type="button" variant="outline" size="sm" className="w-fit" disabled={busy}
|
||||
onClick={() => showTab("configuration")}>Открыть подключения</Button>
|
||||
</div>}
|
||||
{busy && linuxBindings.length === 0 ? <Skeleton className="h-12 w-full" role="status" aria-label="Загрузка Linux-клиентов" />
|
||||
: !error && linuxBindings.length === 0 ? <p className="text-sm text-muted-foreground">В применённой ревизии пока нет подключений Linux.</p>
|
||||
: linuxBindings.map(binding => <div key={binding.serverId + ":" + binding.interfaceName}
|
||||
className="flex min-w-0 flex-wrap items-center justify-between gap-2 border-t pt-2">
|
||||
<div className="min-w-0 text-sm">
|
||||
<p className="wrap-anywhere font-medium">{binding.interfaceName}</p>
|
||||
<p className="wrap-anywhere text-muted-foreground">{binding.kind === "wireguard" ? "WireGuard" : "GRE/IPsec"} · {nodeLabel(nodes, binding.serverId)}</p>
|
||||
</div>
|
||||
<Button type="button" size="sm" variant="outline" disabled={busy}
|
||||
aria-label={"Получить конфиг " + binding.interfaceName} onClick={() => void perform(() => exportLinux(binding))}>Получить конфиг</Button>
|
||||
</div>)}
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
{linux && <Frame spacing="sm">
|
||||
<FrameHeader>
|
||||
<FrameTitle>Конфигурация Linux · {linux.interfaceName}</FrameTitle>
|
||||
<FrameDescription>Ревизия {linux.revision} · {nodeLabel(nodes, linux.serverId)}</FrameDescription>
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid min-w-0 gap-3">
|
||||
<p className="text-sm text-muted-foreground">{linux.kind === "wireguard"
|
||||
? "Подставьте приватный ключ, сгенерированный на Linux. Шаблон wg-quick оставляет управление маршрутами на стороне Linux."
|
||||
: "Подставьте PSK этого клиента и подключите файл к конфигурации strongSwan. Сверьте параметры IKE с подготовленным узлом IX."}</p>
|
||||
<pre className="max-h-64 min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.template}</pre>
|
||||
<a className={buttonVariants({ variant: "outline", size: "sm", className: "w-fit" })}
|
||||
href={"data:text/plain;charset=utf-8," + encodeURIComponent(linux.template)} download={linux.filename}>Скачать {linux.filename}</a>
|
||||
{linux.setup && <pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.setup}</pre>}
|
||||
{linux.bgp && <p className="wrap-anywhere text-sm text-muted-foreground">
|
||||
BGP · ASN Linux {linux.bgp.localAs} · ASN IX {linux.bgp.remoteAs} · сосед {linux.bgp.neighbor}
|
||||
{linux.bgp.advertisedPrefixes.length > 0 && <> · анонсы Linux {linux.bgp.advertisedPrefixes.join(", ")}</>}
|
||||
</p>}
|
||||
</FramePanel>
|
||||
</Frame>}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="changes" className="grid min-w-0 gap-3">
|
||||
<Frame spacing="sm">
|
||||
<FrameHeader>
|
||||
<FrameTitle>Изменения RouterOS</FrameTitle>
|
||||
<FrameDescription>Предпросмотр сравнивает сохранённую ревизию с текущим состоянием узлов.</FrameDescription>
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid min-w-0 gap-3">
|
||||
{!write ? <p className="text-sm text-muted-foreground">Нужно право изменять сетевую конфигурацию.</p>
|
||||
: dirty ? <p className="text-sm text-muted-foreground">Сохраните черновик на вкладке «Конфигурация».</p>
|
||||
: selected?.appliedRevision === selected?.revision ? <p className="text-sm text-muted-foreground">Текущая ревизия применена.</p>
|
||||
: <Button type="button" size="sm" variant="outline" className="w-fit" disabled={!canPlan || busy}
|
||||
onClick={() => void perform(prepare)}>Построить предпросмотр</Button>}
|
||||
{plan && <div className="grid min-w-0 gap-3 border-t pt-3">
|
||||
<p className="text-sm font-medium">Ревизия {plan.revision} · операций RouterOS: {plan.changes.length}</p>
|
||||
{plan.changes.length === 0 && <p className="text-sm text-muted-foreground">Конфигурация RouterOS совпадает с черновиком. Применение обновит ревизию в MikrotikManager.</p>}
|
||||
{plan.changes.length > 0 && <ul className="max-h-80 min-w-0 divide-y overflow-auto rounded-md border">
|
||||
{plan.changes.map((operation, index) => <li key={index} className="min-w-0 p-2.5 text-sm">
|
||||
<details className="min-w-0">
|
||||
<summary className="cursor-pointer wrap-anywhere">{actionLabels[operation.action]} · {nodeLabel(nodes, operation.serverId)} · <code>{operation.path}</code>
|
||||
{operation.target && <> · <code>{operation.target}</code></>}
|
||||
</summary>
|
||||
<dl className="grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 py-2 text-xs">
|
||||
{operation.placeBefore && <><dt className="text-muted-foreground">Перед объектом</dt><dd className="font-mono">{operation.placeBefore}</dd></>}
|
||||
{Object.entries(operation.fields).map(([key, value]) => <div key={key} className="contents">
|
||||
<dt className="max-w-32 wrap-anywhere text-muted-foreground">{key}</dt>
|
||||
<dd className="wrap-anywhere font-mono">{value}</dd>
|
||||
</div>)}
|
||||
</dl>
|
||||
</details>
|
||||
</li>)}
|
||||
</ul>}
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button type="button" size="sm" className="w-fit" disabled={busy || !canPlan} />}>
|
||||
Применить план
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Применить конфигурацию IX?</AlertDialogTitle>
|
||||
<AlertDialogDescription>Будет применена ревизия {plan.revision} сегмента {selected?.configuration.name}. Операций RouterOS: {plan.changes.length}.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => void perform(apply)}>Применить</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>}
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
</TabsContent>
|
||||
</Tabs>}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
@@ -243,7 +243,6 @@ const TYPE_STYLE: Record<ServerType, { label: string; fill: string; r: number }>
|
||||
"jump-host": { label: "JH", fill: "var(--chart-1)", r: 34 },
|
||||
// EN — крайние edge-узлы, менее акцентные.
|
||||
"exit-node": { label: "EN", fill: "var(--chart-3)", r: 30 },
|
||||
"ix-node": { label: "IX", fill: "var(--chart-4)", r: 34 },
|
||||
}
|
||||
|
||||
const WAN_COLORS = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)", "var(--chart-5)"]
|
||||
@@ -258,7 +257,6 @@ const TYPE_LABELS: Record<ServerType, string> = {
|
||||
"jump-host": "JumpHost",
|
||||
"exit-node": "Exit Node",
|
||||
"home-router": "Home Router",
|
||||
"ix-node": "IX Node",
|
||||
}
|
||||
|
||||
const MOCK_MAP_SERVICES: FlowMapService[] = [
|
||||
@@ -619,7 +617,7 @@ function NetflowRateBadge({
|
||||
onClick={(e) => { e.stopPropagation(); onOpen?.(e) }}
|
||||
>
|
||||
<title>
|
||||
Поток NetFlow между узлами за интервал карты, без overlay/mesh.
|
||||
Поток NetFlow между узлами (как в «Трафик»: 5 мин, без overlay/mesh). Скорость канала — отдельно.
|
||||
</title>
|
||||
<rect className="network-map-focus-ring" x={-bw / 2 - 4} y={-bh / 2 - 4} width={bw + 8} height={bh + 8} rx="9" fill="none" stroke="var(--ring)" strokeWidth="2" />
|
||||
<rect
|
||||
@@ -1155,17 +1153,6 @@ function NetworkMapContent() {
|
||||
const [mapServers, setMapServers] = useState<Server[]>([])
|
||||
const [sessionCounts,setSessionCounts]=useState<Record<string,number|null>>({})
|
||||
const [mapGreTunnels, setMapGreTunnels] = useState<GreTunnel[]>([])
|
||||
const [showIx, setShowIx] = useState(true)
|
||||
const [ixLinks, setIxLinks] = useState<Array<{ from: number; to: number; segment: string }>>([])
|
||||
const hasIxNodes = mapServers.some(server => server.type === "ix-node")
|
||||
useEffect(() => {
|
||||
if (!useLiveData || !hasIxNodes) { setIxLinks([]); return }
|
||||
const controller = new AbortController()
|
||||
void apiFetch<{ links: Array<{ from: number; to: number; segment: string }> }>("/api/ix/topology", { signal: controller.signal })
|
||||
.then(result => { if (!controller.signal.aborted) setIxLinks(result.links) })
|
||||
.catch(() => { if (!controller.signal.aborted) setIxLinks([]) })
|
||||
return () => controller.abort()
|
||||
}, [apiFetch, useLiveData, hasIxNodes])
|
||||
const [speedProbes, setSpeedProbes] = useState<GreSpeedProbeSnapshot[]>([])
|
||||
const [mapHops, setMapHops] = useState<FlowMapHop[]>([])
|
||||
const [mapServices, setMapServices] = useState<FlowMapService[]>([])
|
||||
@@ -1455,7 +1442,7 @@ function NetworkMapContent() {
|
||||
if (cancelled||request!==epoch) return
|
||||
const name = err instanceof Error ? err.name : ""
|
||||
if (name === "AbortError") return
|
||||
setFlowError(err instanceof Error?(err.name==="ZodError"?"Ответ содержит неполные или противоречивые данные снимка":err.message):"Ошибка NetFlow")
|
||||
setFlowError(err instanceof Error?(err.name==="ZodError"?"Некорректный ответ: требуется полный снимок за 5 минут":err.message):"Ошибка NetFlow")
|
||||
}).finally(()=>{inFlight=false;if(!cancelled&&request===epoch)setFlowLoading(false)})
|
||||
}
|
||||
queueMicrotask(()=>{if(!cancelled)tick()})
|
||||
@@ -2237,7 +2224,7 @@ function NetworkMapContent() {
|
||||
<span className="text-[10px] border border-border rounded px-1.5 py-0.5">
|
||||
{useLiveData ? (readAt ? "Снимок API · ответ "+new Date(readAt).toLocaleTimeString("ru-RU")+" (время браузера)" : "Данные карты неизвестны") : "Демо · mock"}
|
||||
</span>
|
||||
{useLiveData&&<span>{showNetflow||showServices?(flowReadAt?`NetFlow · ${mapWindowSec / 60} мин${mapWindowSec < 300 ? " из 5 запрошенных" : ""} · ответ `+new Date(flowReadAt).toLocaleTimeString("ru-RU")+" (время браузера) · "+(flowListener?"приёмник включён":"приёмник выключен"):"Данные NetFlow неизвестны"):"NetFlow: отображение и обновление выключены"}</span>}
|
||||
{useLiveData&&<span>{showNetflow||showServices?(flowReadAt?"NetFlow · 5 мин · ответ "+new Date(flowReadAt).toLocaleTimeString("ru-RU")+" (время браузера) · "+(flowListener?"приёмник включён":"приёмник выключен"):"Данные NetFlow неизвестны"):"NetFlow: отображение и обновление выключены"}</span>}
|
||||
{useLiveData&&flowLoading&&(showNetflow||showServices)&&<span role="status">Обновление NetFlow…</span>}
|
||||
{useLiveData&&flowError&&(showNetflow||showServices)&&<span role="alert" className="text-destructive [overflow-wrap:anywhere]">NetFlow: {flowError}. {flowReadAt?"Сохранён предыдущий снимок NetFlow; актуальность не подтверждена.":"Первоначальная загрузка NetFlow не подтверждена."}</span>}
|
||||
{useLiveData&&dnsError&&<span role="alert" className="text-destructive [overflow-wrap:anywhere]">DNS: {dnsError}. Связи по неизвестному адресу не подтверждены.</span>}
|
||||
@@ -2273,10 +2260,6 @@ function NetworkMapContent() {
|
||||
{/* ── Canvas ── */}
|
||||
<div ref={canvasRef} className={cn("flex-1 min-h-0 min-w-0 relative overflow-hidden bg-background select-none", (selected || selectedGreEdge || selectedService) && "hidden lg:block")}>
|
||||
<NetworkMapLegend />
|
||||
{ixLinks.length > 0 && <button type="button" aria-pressed={showIx} onClick={() => setShowIx(value => !value)}
|
||||
className="absolute right-3 top-3 z-20 rounded-md border bg-popover px-3 py-2 text-xs font-medium">
|
||||
Связи IX
|
||||
</button>}
|
||||
<p id="network-map-help" className="sr-only">Стрелки перемещают карту, плюс и минус меняют масштаб, F вписывает объекты. Tab выбирает объект, Enter открывает детали.</p>
|
||||
<svg
|
||||
ref={svgRef} role="group" aria-label="Интерактивная карта сети" tabIndex={0} aria-describedby="network-map-help"
|
||||
@@ -2412,16 +2395,6 @@ function NetworkMapContent() {
|
||||
)
|
||||
})}
|
||||
|
||||
{showIx && [...new Map(ixLinks.map(link => {
|
||||
const key = [Math.min(link.from, link.to), Math.max(link.from, link.to), link.segment].join(":")
|
||||
return [key, link] as const
|
||||
})).entries()].map(([key, link]) => {
|
||||
const from = nodePosById[String(link.from)], to = nodePosById[String(link.to)]
|
||||
return from && to && <line key={key} x1={from.x} y1={from.y} x2={to.x} y2={to.y}
|
||||
stroke="var(--chart-4)" strokeWidth={2} strokeDasharray="8 4">
|
||||
<title>IX-сегмент {link.segment} · настроенная связь</title>
|
||||
</line>
|
||||
})}
|
||||
{/* ── Home Router → WAN satellite connectors ── */}
|
||||
{homeRouters.flatMap(router => {
|
||||
const rNode = nodes.find(n => n.id === router.id)
|
||||
@@ -2961,7 +2934,7 @@ function NetworkMapContent() {
|
||||
? "Ping и/или TX/RX — с последнего прогона speed-пробы; проба сопоставляется с этим GRE по WAN и интерфейсам. "
|
||||
: useLiveData?"Измерения GRE неизвестны: нет подходящей пробы. ":"Измерения демонстрационные. "}
|
||||
{spGr?"Проба "+spGr.id+" · время Ping: "+(spGr.lastPingAt?new Date(spGr.lastPingAt).toLocaleString("ru-RU"):"неизвестно")+" · время TX/RX неизвестно. ":""}
|
||||
Поток по данным NetFlow за {mapWindowSec / 60} мин, без overlay/mesh.
|
||||
Поток — снимок NetFlow за 5 мин (как в «Трафик»: без overlay/mesh), не ёмкость канала.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -35,7 +35,7 @@ interface BackendServer {
|
||||
id: number
|
||||
name: string
|
||||
host: string
|
||||
type?: import("@mmapp/contracts/servers").ServerType
|
||||
type?: "jump-host" | "exit-node" | "home-router"
|
||||
site: string
|
||||
country: string
|
||||
asn: string
|
||||
@@ -329,11 +329,11 @@ function RouteSheet({
|
||||
)
|
||||
}
|
||||
|
||||
function TypeChip({ type }: { type: import("@mmapp/contracts/servers").ServerType }) {
|
||||
function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" }) {
|
||||
return (
|
||||
<Badge size="xs" className="shrink-0 text-foreground"
|
||||
variant={type === "home-router" ? "success-light" : type === "jump-host" ? "primary-light" : "info-light"}>
|
||||
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : type === "ix-node" ? "IX" : "EN"}
|
||||
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : "EN"}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
|
||||
+12
-27
@@ -38,8 +38,6 @@ import { cn } from "@/lib/utils"
|
||||
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
|
||||
import { DataPageCard } from "@/components/data-page-card"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ButtonGroup } from "@/components/ui/button-group"
|
||||
import { Field, FieldTitle } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Sheet, SheetContent, SheetHeader, SheetTitle,
|
||||
@@ -593,7 +591,6 @@ function ServersPageContent() {
|
||||
"jump-host": serverList.filter(s => s.type === "jump-host").length,
|
||||
"exit-node": serverList.filter(s => s.type === "exit-node").length,
|
||||
"home-router":serverList.filter(s => s.type === "home-router").length,
|
||||
"ix-node": serverList.filter(s => s.type === "ix-node").length,
|
||||
online: serverList.filter(s => s.status === "online").length,
|
||||
}), [serverList])
|
||||
|
||||
@@ -602,7 +599,6 @@ function ServersPageContent() {
|
||||
{ value: "jump-host", label: "JumpHost" },
|
||||
{ value: "exit-node", label: "Exit Node" },
|
||||
{ value: "home-router", label: "Home Router" },
|
||||
{ value: "ix-node", label: "IX Node" },
|
||||
]
|
||||
|
||||
const isHomeRouter = form.type === "home-router"
|
||||
@@ -774,29 +770,18 @@ function ServersPageContent() {
|
||||
value={form.name} onChange={e => set("name", e.target.value)} />
|
||||
</FormField>
|
||||
|
||||
<Field>
|
||||
<FieldTitle id="server-node-type-label">Тип узла <span aria-hidden className="text-destructive">*</span></FieldTitle>
|
||||
<ButtonGroup aria-labelledby="server-node-type-label" className="max-w-full">
|
||||
{([
|
||||
["home-router", "Home Router"],
|
||||
["jump-host", "JumpHost"],
|
||||
["exit-node", "Exit Node"],
|
||||
["ix-node", "IX Node"],
|
||||
] as const).map(([value, label]) => (
|
||||
<Button
|
||||
key={value}
|
||||
type="button"
|
||||
variant={form.type === value ? "default" : "outline"}
|
||||
size="sm"
|
||||
aria-pressed={form.type === value}
|
||||
className="h-auto min-h-7 min-w-0 flex-auto shrink whitespace-normal py-1"
|
||||
onClick={() => set("type", value)}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
))}
|
||||
</ButtonGroup>
|
||||
</Field>
|
||||
<FormField label="Тип узла" required>
|
||||
<SegmentedControl
|
||||
className="max-w-full flex-wrap"
|
||||
value={form.type}
|
||||
onChange={v => set("type", v)}
|
||||
options={[
|
||||
{ value: "home-router", label: "Home Router" },
|
||||
{ value: "jump-host", label: "JumpHost" },
|
||||
{ value: "exit-node", label: "Exit Node" },
|
||||
]}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<FormField label="Площадка" required hint="MSK, SPB, FRA…">
|
||||
|
||||
+32
-66
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState, useMemo, useEffect, type ReactNode } from "react"
|
||||
import { Alert, AlertTitle, AlertDescription } from "@/components/reui/alert"
|
||||
import { peakOfCombinedTraffic, projectTrafficObservations, type TrafficObservationMeta } from "@/lib/traffic-observations"
|
||||
import { projectTrafficObservations, type TrafficObservationMeta } from "@/lib/traffic-observations"
|
||||
import { projectTrafficBindingStatus } from "@/lib/traffic-binding-status"
|
||||
import { TrafficObservationStatus } from "@/components/traffic/traffic-observation-status"
|
||||
import { TrafficDataTime } from "@/components/traffic/traffic-data-time"
|
||||
@@ -25,7 +25,7 @@ import { useDataSource } from "@/lib/data-source"
|
||||
import { useTrafficLive } from "@/hooks/use-traffic-live"
|
||||
import { useFlowLive } from "@/hooks/use-flow-live"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
import { getFlowAnalytics, getFlowClients, getFlowExporters, getFlowMonthly, getTrafficFlowSettings, getTrafficFlows } from "@/shared/api/traffic-flow"
|
||||
import { getFlowAnalytics, getFlowClients, getFlowExporters, getFlowMonthly, getTrafficFlows } from "@/shared/api/traffic-flow"
|
||||
import { listServers } from "@/shared/api/servers"
|
||||
import { FlowOverlaySheet } from "@/components/traffic/flow-overlay-sheet"
|
||||
import { FlowAnalyticsDetail, FlowEntityCardView } from "@/components/traffic/flow-analytics-panel"
|
||||
@@ -56,31 +56,32 @@ function addSeries(a: number[], b: number[]): number[] {
|
||||
return a.map((v, i) => v + (b[i] ?? 0))
|
||||
}
|
||||
|
||||
type FlowCollectorStatus = Pick<FlowStatsDto, "listenerBound" | "listenerAddress" | "packetsReceived" | "lastDatagramAt" | "lastExporterIp" | "lastError" | "collectorCountersSource">
|
||||
|
||||
function flowIngestLine(stats: FlowCollectorStatus | null): string | null {
|
||||
function flowIngestLine(stats: FlowStatsDto | null): string | null {
|
||||
if (!stats) return null
|
||||
const listener = stats.listenerBound
|
||||
? (stats.listenerAddress ?? "слушает")
|
||||
: "приём не подтверждён"
|
||||
: "не слушает"
|
||||
const last = stats.lastDatagramAt
|
||||
? new Date(stats.lastDatagramAt).toLocaleString("ru-RU")
|
||||
: "—"
|
||||
const exporter = stats.lastExporterIp ? ` · ${stats.lastExporterIp}` : ""
|
||||
const err = stats.lastError ? ` · ${stats.lastError}` : ""
|
||||
const hint = stats.collectorCountersSource === "last-known" ? " · последние известные данные" : ""
|
||||
return `Коллектор: ${listener} · пакеты ${stats.packetsReceived ?? "—"} · последний ${last}${exporter}${hint}${err}`
|
||||
return `Коллектор: ${listener} · пакеты ${stats.packetsReceived ?? 0} · последний ${last}${exporter}${err}`
|
||||
}
|
||||
|
||||
function flowEmptyHint(stats: FlowCollectorStatus | null): string | undefined {
|
||||
function flowEmptyHint(stats: FlowStatsDto | null, collectorAlive?: boolean): string | undefined {
|
||||
if (!stats) return undefined
|
||||
if (stats.lastError) return stats.lastError
|
||||
if (stats.collectorCountersSource === "last-known") return "Текущий приём IPFIX не подтверждён."
|
||||
if (stats.listenerBound === false) return "Коллектор UDP не слушает."
|
||||
if (stats.packetsReceived) {
|
||||
return "В выбранном интервале нет сохранённых потоков."
|
||||
return `IPFIX приходит (${stats.lastExporterIp ?? "экспортёр"}), но сессии ещё не записаны.`
|
||||
}
|
||||
return stats.listenerBound ? "Коллектор слушает, датаграммы IPFIX ещё не получены." : undefined
|
||||
if (stats.listenerBound === false && !collectorAlive) {
|
||||
return "Коллектор UDP не слушает. Подключите JH ещё раз — ingest включится автоматически."
|
||||
}
|
||||
if (stats.listenerBound || collectorAlive) {
|
||||
return "Коллектор жив, IPFIX ещё не доходит. На jump-host у target Src должен быть 0.0.0.0 (авто)."
|
||||
}
|
||||
return "IPFIX ещё не доходит до коллектора. На jump-host у target Src должен быть 0.0.0.0 (авто). На хосте MM проверьте bind 10.255.254.1:4739 после wg-flow."
|
||||
}
|
||||
|
||||
// ─── data model ───────────────────────────────────────────────────────────────
|
||||
@@ -802,7 +803,7 @@ export default function TrafficPage() {
|
||||
const [trafficRetry, setTrafficRetry] = useState(0)
|
||||
const [liveRetry, setLiveRetry] = useState(0)
|
||||
const trafficKey = JSON.stringify([isLive, backendUrl, range, groupMode, trafficRetry])
|
||||
const [trafficState, setTrafficState] = useState<{ key: string; status: "ready" | "error"; receivedAt?: number; peaks?: { rx: number | null; tx: number | null }; error?: string } | null>(null)
|
||||
const [trafficState, setTrafficState] = useState<{ key: string; status: "ready" | "error"; receivedAt?: number; error?: string } | null>(null)
|
||||
const trafficReady = trafficState?.key === trafficKey && trafficState.status === "ready"
|
||||
const trafficLoading = trafficState?.key !== trafficKey
|
||||
const trafficError = trafficState?.key === trafficKey ? trafficState.error : undefined
|
||||
@@ -822,17 +823,11 @@ export default function TrafficPage() {
|
||||
const [flowScope, setFlowScope] = useState<FlowScope>("servers")
|
||||
const [flowRetry, setFlowRetry] = useState(0)
|
||||
const flowKey = JSON.stringify([isLive, groupMode, backendUrl, range, flowScope, flowRetry])
|
||||
const [flowResult, setFlowResult] = useState<{ key: string; receivedAt?: number; monthlyServers?: ServerRead[]; stats?: FlowStatsDto; exporters?: FlowEntityCard[]; clients?: FlowEntityCard[]; cardWindow?: FlowStatsDto["sourceWindow"]; error?: string } | null>(null)
|
||||
const [flowResult, setFlowResult] = useState<{ key: string; receivedAt?: number; monthlyServers?: ServerRead[]; stats?: FlowStatsDto; exporters?: FlowEntityCard[]; clients?: FlowEntityCard[]; error?: string } | null>(null)
|
||||
const currentFlows = flowResult?.key === flowKey ? flowResult : null
|
||||
const liveBusy = isLive && groupMode === "flows" && !currentFlows
|
||||
const liveError = currentFlows?.error
|
||||
const flowStats = currentFlows?.stats ?? null
|
||||
const [flowCollector, setFlowCollector] = useState<{ url: string; status: FlowCollectorStatus | null; receivedAt?: number } | null>(null)
|
||||
const collectorReading = flowCollector?.url === backendUrl ? flowCollector : { status: flowStats, receivedAt: currentFlows?.receivedAt }
|
||||
const collectorStatus: FlowCollectorStatus | null = collectorReading.status && collectorReading.receivedAt !== undefined
|
||||
&& trafficClock - collectorReading.receivedAt > 35_000
|
||||
? { ...collectorReading.status, listenerBound: false, collectorCountersSource: "last-known" }
|
||||
: collectorReading.status
|
||||
const flowExporters = useMemo(() => currentFlows?.exporters ?? [], [currentFlows])
|
||||
const flowClients = useMemo(() => currentFlows?.clients ?? [], [currentFlows])
|
||||
const [flowMonth, setFlowMonth] = useState(() => new Date().toISOString().slice(0, 7))
|
||||
@@ -887,7 +882,7 @@ export default function TrafficPage() {
|
||||
try {
|
||||
const q = encodeURIComponent(targetRange === "30d" ? "24h" : targetRange)
|
||||
const [srvRes, usersRes, ifacesRes] = await Promise.all([
|
||||
apiFetch<{ servers: LiveTrafficServer[]; peaks?: { rx: number | null; tx: number | null } }>(`/api/traffic/servers?range=${q}`),
|
||||
apiFetch<{ servers: LiveTrafficServer[] }>(`/api/traffic/servers?range=${q}`),
|
||||
apiFetch<{ users: UserTraffic[] }>(`/api/traffic/users?range=${q}`),
|
||||
apiFetch<{ interfaces: BoundIfaceTraffic[] }>(`/api/traffic/bound-interfaces?range=${q}`),
|
||||
])
|
||||
@@ -902,7 +897,7 @@ export default function TrafficPage() {
|
||||
setLiveServerOwner(JSON.stringify([isLive, backendUrl]))
|
||||
setLiveUsers(mappedUsers)
|
||||
setLiveBoundIfaces(liveIfaces)
|
||||
setTrafficState({ key, status: "ready", receivedAt: Date.now(), peaks: srvRes.peaks })
|
||||
setTrafficState({ key, status: "ready", receivedAt: Date.now() })
|
||||
setSelectedId((prev) => {
|
||||
if (groupMode === "users") return mappedUsers.some((x) => x.id === prev) ? prev : (mappedUsers[0]?.id ?? "")
|
||||
if (groupMode === "ifaces") return liveIfaces.some((x) => x.id === prev) ? prev : (liveIfaces[0]?.id ?? "")
|
||||
@@ -916,28 +911,6 @@ export default function TrafficPage() {
|
||||
return () => { cancelled = true }
|
||||
}, [apiFetch, isLive, groupMode, backendUrl, trafficRetry, range])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLive || groupMode !== "flows" || range === "30d") return
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
const refresh = async () => {
|
||||
try {
|
||||
const status = await getTrafficFlowSettings(backendUrl, { signal: controller.signal })
|
||||
if (!controller.signal.aborted) setFlowCollector({ url: backendUrl, status, receivedAt: Date.now() })
|
||||
} catch {
|
||||
if (!controller.signal.aborted) setFlowCollector(current => ({
|
||||
url: backendUrl,
|
||||
status: current?.url === backendUrl && current.status
|
||||
? { ...current.status, listenerBound: false, collectorCountersSource: "last-known" }
|
||||
: null,
|
||||
}))
|
||||
}
|
||||
if (!controller.signal.aborted) timer = setTimeout(refresh, 15_000)
|
||||
}
|
||||
timer = setTimeout(refresh, 15_000)
|
||||
return () => { controller.abort(); clearTimeout(timer) }
|
||||
}, [isLive, groupMode, range, backendUrl])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLive || effectiveMode !== "flows") return
|
||||
let cancelled = false
|
||||
@@ -959,8 +932,7 @@ export default function TrafficPage() {
|
||||
if (cancelled) return
|
||||
const clients = await getFlowClients(backendUrl, range)
|
||||
if (cancelled) return
|
||||
setFlowResult({ key: flowKey, receivedAt: Date.now(), stats, exporters: exporters.exporters, clients: clients.clients,
|
||||
cardWindow: flowScope === "users" ? clients.sourceWindow : exporters.sourceWindow })
|
||||
setFlowResult({ key: flowKey, receivedAt: Date.now(), stats, exporters: exporters.exporters, clients: clients.clients })
|
||||
setSelectedId(prev => {
|
||||
const list = flowScope === "users" ? clients.clients : exporters.exporters
|
||||
return list.some(x => x.id === prev) ? prev : (list[0]?.id ?? "")
|
||||
@@ -1143,14 +1115,14 @@ export default function TrafficPage() {
|
||||
: effectiveMode === "ifaces"
|
||||
? activeBoundIfaces
|
||||
: activeServerTraffic
|
||||
const totalRx = kpiSource.length && kpiSource.every(s => s.rxNow !== null) ? kpiSource.reduce((a, s) => a + (s.rxNow ?? 0), 0) : null
|
||||
const totalTx = kpiSource.length && kpiSource.every(s => s.txNow !== null) ? kpiSource.reduce((a, s) => a + (s.txNow ?? 0), 0) : null
|
||||
const exactPeaks = effectiveMode === "servers" && trafficReady ? trafficState?.peaks : undefined
|
||||
const peakRx = exactPeaks ? exactPeaks.rx : peakOfCombinedTraffic(kpiSource.map(s => s.rxSeries))
|
||||
const peakTx = exactPeaks ? exactPeaks.tx : peakOfCombinedTraffic(kpiSource.map(s => s.txSeries))
|
||||
const totalRx = kpiSource.every(s => s.rxNow !== null) ? kpiSource.reduce((a, s) => a + (s.rxNow ?? 0), 0) : null
|
||||
const totalTx = kpiSource.every(s => s.txNow !== null) ? kpiSource.reduce((a, s) => a + (s.txNow ?? 0), 0) : null
|
||||
const peakRx = kpiSource.every(s => s.rxPeak !== null) ? kpiSource.reduce((a, s) => Math.max(a, s.rxPeak ?? 0), 0) : null
|
||||
const peakTx = kpiSource.every(s => s.txPeak !== null) ? kpiSource.reduce((a, s) => Math.max(a, s.txPeak ?? 0), 0) : null
|
||||
|
||||
const visibleSortFields = SORT_FIELDS.filter(s => !s.modesOnly || s.modesOnly.includes(effectiveMode))
|
||||
const ingestLine = flowIngestLine(collectorStatus)
|
||||
const ingestLine = flowIngestLine(flowStats)
|
||||
const collectorAlive = Boolean(flowStats?.listenerBound || flowStats?.packetsReceived)
|
||||
const flowError = liveError
|
||||
|| flowLiveError
|
||||
|| (displayedFlow?.degraded ? "Коллектор перегружен: упрощённая аналитика" : null)
|
||||
@@ -1166,7 +1138,7 @@ export default function TrafficPage() {
|
||||
},
|
||||
{
|
||||
id: "bps",
|
||||
label: "Скорость IPFIX",
|
||||
label: "Скорость",
|
||||
value: displayedFlow ? fmtRate(displayedFlow.bpsNow / 1_000_000) : "—",
|
||||
hint: flowLiveHint,
|
||||
icon: <ActivityIcon className="size-4" />,
|
||||
@@ -1191,33 +1163,29 @@ export default function TrafficPage() {
|
||||
const counterKpiItems = [
|
||||
{
|
||||
id: "rx",
|
||||
label: "Сумма RX",
|
||||
label: "RX",
|
||||
value: fmtRate(totalRx),
|
||||
hint: effectiveMode === "servers" ? "Интерфейсы и туннели" : undefined,
|
||||
icon: <ArrowDownIcon className="size-4" />,
|
||||
iconClassName: "text-success",
|
||||
},
|
||||
{
|
||||
id: "tx",
|
||||
label: "Сумма TX",
|
||||
label: "TX",
|
||||
value: fmtRate(totalTx),
|
||||
hint: effectiveMode === "servers" ? "Интерфейсы и туннели" : undefined,
|
||||
icon: <ArrowUpIcon className="size-4" />,
|
||||
iconClassName: "text-info",
|
||||
},
|
||||
{
|
||||
id: "peak-rx",
|
||||
label: "Пик суммы RX",
|
||||
label: "Пик RX",
|
||||
value: fmtRate(peakRx),
|
||||
hint: exactPeaks ? "По общим замерам" : "По интервалам графика",
|
||||
icon: <TrendingUpIcon className="size-4" />,
|
||||
iconClassName: "text-warning",
|
||||
},
|
||||
{
|
||||
id: "peak-tx",
|
||||
label: "Пик суммы TX",
|
||||
label: "Пик TX",
|
||||
value: fmtRate(peakTx),
|
||||
hint: exactPeaks ? "По общим замерам" : "По интервалам графика",
|
||||
icon: <TrendingUpIcon className="size-4" />,
|
||||
iconClassName: "text-warning",
|
||||
},
|
||||
@@ -1282,8 +1250,6 @@ export default function TrafficPage() {
|
||||
</Button>
|
||||
</div>
|
||||
{isLive && <TrafficDataTime label="Получение списка потоков" receivedAt={currentFlows?.receivedAt} source="API" />}
|
||||
{flowStats?.sourceWindow && <p role="status" className="text-sm text-muted-foreground">Сводка потоков за последние {flowStats.sourceWindow.effectiveMinutes} мин из запрошенных {flowStats.sourceWindow.requestedMinutes} мин.</p>}
|
||||
{currentFlows?.cardWindow && <p role="status" className="text-sm text-muted-foreground">Данные карточек за последние {currentFlows.cardWindow.effectiveMinutes} мин из запрошенных {currentFlows.cardWindow.requestedMinutes} мин.</p>}
|
||||
{liveBusy && <p role="status">Загрузка потоков…</p>}
|
||||
{liveError && <Alert variant="destructive" role="alert"><AlertTitle>Потоки недоступны</AlertTitle><AlertDescription>{liveError}<Button size="sm" variant="outline" onClick={() => setFlowRetry(value => value + 1)}>Повторить загрузку потоков</Button></AlertDescription></Alert>}
|
||||
{flowError && !liveError && (
|
||||
@@ -1361,7 +1327,7 @@ export default function TrafficPage() {
|
||||
))}
|
||||
{!liveBusy && !liveError && (range === "30d" ? visibleMonthlyServers.length : sortedFlowCards.length) === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{range === "30d" ? (q ? "Нет серверов по этому запросу" : "В каталоге нет серверов") : flowEmptyHint(collectorStatus) ?? "Нет экспортёров IPFIX."}
|
||||
{range === "30d" ? (q ? "Нет серверов по этому запросу" : "В каталоге нет серверов") : flowEmptyHint(flowStats, collectorAlive) ?? "Нет экспортёров IPFIX. Подключите jump-host."}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
@@ -1390,7 +1356,7 @@ export default function TrafficPage() {
|
||||
excludeOverlay={flowExcludeOverlay}
|
||||
onExcludeOverlay={setFlowExcludeOverlay}
|
||||
liveHint={flowLiveHint}
|
||||
emptyHint={analyticsLoading ? "Загрузка аналитики…" : currentAnalytics?.error ? "Не удалось получить данные выбранного среза" : flowEmptyHint(collectorStatus)}
|
||||
emptyHint={analyticsLoading ? "Загрузка аналитики…" : currentAnalytics?.error ? "Не удалось получить данные выбранного среза" : flowEmptyHint(flowStats, collectorAlive)}
|
||||
/>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
|
||||
@@ -235,7 +235,7 @@ function probeGroupActionKey(srvId: string, group: { name: string; target: strin
|
||||
|
||||
// ── shared components ──────────────────────────────────────────────────────────
|
||||
|
||||
function TypeChip({ type }: { type: import("@mmapp/contracts/servers").ServerType }) {
|
||||
function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" }) {
|
||||
return (
|
||||
<span className={cn(
|
||||
"inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-bold border shrink-0",
|
||||
@@ -245,7 +245,7 @@ function TypeChip({ type }: { type: import("@mmapp/contracts/servers").ServerTyp
|
||||
? "bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20"
|
||||
: "bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20",
|
||||
)}>
|
||||
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : type === "ix-node" ? "IX" : "EN"}
|
||||
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : "EN"}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -666,7 +666,7 @@ interface BackendServer {
|
||||
id: number
|
||||
name: string
|
||||
host: string
|
||||
type: import("@mmapp/contracts/servers").ServerType
|
||||
type: "jump-host" | "exit-node" | "home-router"
|
||||
site: string
|
||||
country: string
|
||||
enabled: boolean
|
||||
@@ -843,7 +843,7 @@ const INIT_RESOURCES: ServerResource[] = mockServers.map(s => {
|
||||
|
||||
// ── ResourcesTab ──────────────────────────────────────────────────────────────
|
||||
|
||||
type ResTypeFilter = "all" | import("@mmapp/contracts/servers").ServerType
|
||||
type ResTypeFilter = "all" | "jump-host" | "exit-node" | "home-router"
|
||||
|
||||
function ResourceWarnings({ rows }: { rows: UptimeResourceRow[] }) {
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
@@ -941,7 +941,6 @@ function ResourcesTab({ resources, serversList, liveApi }: { resources: ServerRe
|
||||
{ value: "jump-host", label: "JumpHost" },
|
||||
{ value: "exit-node", label: "Exit Node" },
|
||||
{ value: "home-router", label: "Home Router" },
|
||||
{ value: "ix-node", label: "IX Node" },
|
||||
]
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
# PostgreSQL connection string
|
||||
DATABASE_URL=postgres://mmapp:[email protected]:5432/mmapp
|
||||
# Optional operator-approved request and CA for runtime PostgreSQL TLS and SQL identity checks.
|
||||
# DATABASE_RUNTIME_REQUEST_FILE=/run/config/mmapp/approved-request.json
|
||||
# DATABASE_RUNTIME_REQUEST_SHA256=<operator-approved SHA-256 of request bytes>
|
||||
# DATABASE_RUNTIME_CA_FILE=/run/config/mmapp/postgresql-ca.pem
|
||||
# Optional live operator activation directory (mount the directory read-only).
|
||||
# DATABASE_RUNTIME_ACTIVATION_DIRECTORY=/var/lib/mmapp/source-activation
|
||||
# DATABASE_RUNTIME_ACTIVATION_SHA256=<confirmed activation SHA-256>
|
||||
# Optional operator-approved logical schema SHA-256 from db:inspect-schema.
|
||||
# DATABASE_RUNTIME_SCHEMA_SHA256=<approved schema SHA-256>
|
||||
# Restore-aware signed writer profile. Requires source activation, schema pin and restore checkpoint.
|
||||
# DATABASE_RUNTIME_WRITER_APPROVAL_FILE=/run/config/mmapp/writer-approval.json
|
||||
# DATABASE_RUNTIME_WRITER_APPROVAL_SHA256=<operator-approved SHA-256 of approval bytes>
|
||||
# Protected exports use the approved capture role and require this private password file.
|
||||
# The PostgreSQL TLS peer must present the approved self-signed non-CA leaf.
|
||||
# DATABASE_ARCHIVE_PASSWORD_FILE=/run/secrets/mmapp_database_archive_password
|
||||
# Optional owner connection URI file for restore and its schema migrations.
|
||||
# DATABASE_RESTORE_URL_FILE=/run/secrets/mmapp_database_restore_url
|
||||
# Opt in on every backend/CLI after provisioning the restore quarantine in mmapp_control.
|
||||
# DATABASE_RESTORE_QUARANTINE=true
|
||||
# Optional operator-approved pair for verifying one archive's restored data.
|
||||
# Requires DATABASE_RESTORE_QUARANTINE and DATABASE_RESTORE_URL_FILE.
|
||||
# DATABASE_RESTORE_ARCHIVE_SHA256=<approved archive SHA-256>
|
||||
# DATABASE_RESTORE_DATA_SHA256=<approved data SHA-256>
|
||||
# Optional checkpoint in an operator-managed directory outside the PostgreSQL and MCP state backups.
|
||||
# Mount the whole directory read-only. Restore requires a staged pending checkpoint.
|
||||
# DATABASE_RESTORE_CHECKPOINT_FILE=/run/config/mmapp-restore/database-restore-checkpoint.json
|
||||
# Local socket served by the operator-side db:serve-restore-claims process.
|
||||
# DATABASE_RESTORE_CHECKPOINT_CLAIM_SOCKET=/run/mmapp-restore/claims.sock
|
||||
|
||||
# SQLite file used only for one-shot boot ETL (empty PG + existing mikrotik.db)
|
||||
DATABASE_PATH=./mikrotik.db
|
||||
# SQLITE_IMPORT_FULL_HISTORY=true
|
||||
|
||||
# Port for the Fastify server
|
||||
PORT=8000
|
||||
|
||||
# Allowed CORS origin (Next.js frontend)
|
||||
CORS_ORIGIN=http://localhost:3000
|
||||
|
||||
# Portal SSO (false = open API for local/dev)
|
||||
AUTH_REQUIRED=false
|
||||
# Same HS256 secret as auth-portal JWT_SECRET when AUTH_REQUIRED=true
|
||||
AUTH_JWT_SECRET=dev-secret-change-me
|
||||
AUTH_ISSUER=https://auth.shnt.top
|
||||
AUTH_PORTAL_URL=http://localhost:5175
|
||||
# Optional portal -> MCP revocation webhook. Separate random secret, at least 32 characters.
|
||||
# Portal must send signed events to /_internal/mcp/portal/revocations; see docs/mcp.md.
|
||||
# MCP_PORTAL_WEBHOOK_SECRET=
|
||||
# MCP_PUBLIC_URL=https://manager.example/mcp
|
||||
# MCP_STATE_DIR=/var/lib/mikrotik-manager/mcp-state
|
||||
# Optional separate, externally provisioned bandwidth control source. No automatic
|
||||
# schema/key/identity creation. See docs/mcp-bandwidth-control-source.md.
|
||||
# Use the restricted control runtime role, never the owner/application role.
|
||||
# MMAPP_BANDWIDTH_CONTROL_URL=postgresql://bandwidth_runtime:change-me@control-db:5432/bandwidth_control
|
||||
# MMAPP_BANDWIDTH_CONTROL_ATTESTATION_FILE=/etc/mmapp/control/source.json
|
||||
# MMAPP_BANDWIDTH_CONTROL_TRUST_KEY_FILE=/etc/mmapp/control/issuer-public.pem
|
||||
# SHA256 of the Ed25519 public SPKI DER, pinned outside the attestation itself.
|
||||
# MMAPP_BANDWIDTH_CONTROL_TRUST_KEY_SHA256=
|
||||
# MMAPP_BANDWIDTH_CONTROL_EVENT_KEY_FILE=/etc/mmapp/control/event.key
|
||||
# Separate persistent registry issuer key (raw 32 bytes, different from event.key)
|
||||
# and operator bootstrap signed by the pinned control-source Ed25519 issuer.
|
||||
# These inputs grant no actor/network permissions and create no registry rows.
|
||||
# MMAPP_BANDWIDTH_NODE_ISSUER_KEY_FILE=/etc/mmapp/control/node-issuer.key
|
||||
# MMAPP_BANDWIDTH_NODE_ISSUER_KEY_SHA256=
|
||||
# MMAPP_BANDWIDTH_NODE_BOOTSTRAP_FILE=/etc/mmapp/control/node-bootstrap.json
|
||||
# Optional: enabled by the NetFlow agent Compose installer. Linux Unix socket only.
|
||||
# FLOW_AGENT_SOCKET=/run/mm-netflow-host/agent.sock
|
||||
|
||||
# Optional UDP NetFlow v9/IPFIX template lifetime in milliseconds (restart required).
|
||||
# Collector policy defaults to 90 minutes, not a RouterOS default. Set at least
|
||||
# 3 times the longest configured exporter template refresh interval; data does
|
||||
# not refresh templates. Missing/expired templates refuse decoding, not zero traffic.
|
||||
# FLOW_TEMPLATE_LIFETIME_MS=5400000
|
||||
|
||||
# Optional NetFlow read admission: standard (default) or constrained.
|
||||
# Constrained admits two responses (UI + AI), limits SQL sources to 2 MiB,
|
||||
# cumulative sources to 4 MiB and encoded responses to 2 MiB; large reads refuse.
|
||||
# This is not a complete installation memory limit. See docs/mcp-2gb-resource-acceptance.md.
|
||||
# MM_FLOW_READ_RESOURCE_PROFILE=standard
|
||||
@@ -1,8 +0,0 @@
|
||||
BEGIN;
|
||||
|
||||
CREATE INDEX mcp_audit_routing_charge_profile_window
|
||||
ON public.mcp_audit (connection_id, (payload -> 'anchor' ->> 'profileId'), created_at, id)
|
||||
WHERE action = 'routing.charge.admitted';
|
||||
|
||||
INSERT INTO public.schema_migrations (id) VALUES ('0057_mcp_routing_charge_audit_index') ON CONFLICT (id) DO NOTHING;
|
||||
COMMIT;
|
||||
@@ -1,34 +0,0 @@
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE public.servers DROP CONSTRAINT servers_type_check;
|
||||
ALTER TABLE public.servers ADD CONSTRAINT servers_type_check
|
||||
CHECK (type IN ('jump-host', 'exit-node', 'home-router', 'ix-node'));
|
||||
|
||||
CREATE TABLE public.ix_segments (
|
||||
id uuid PRIMARY KEY,
|
||||
name text NOT NULL UNIQUE,
|
||||
revision integer NOT NULL CHECK (revision > 0),
|
||||
configuration jsonb NOT NULL CHECK (jsonb_typeof(configuration) = 'object'),
|
||||
applied_revision integer CHECK (applied_revision > 0 AND applied_revision <= revision),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE public.ix_segment_devices (
|
||||
segment_id uuid NOT NULL REFERENCES public.ix_segments(id) ON DELETE CASCADE,
|
||||
server_id bigint NOT NULL REFERENCES public.servers(id) ON DELETE RESTRICT,
|
||||
PRIMARY KEY (segment_id, server_id)
|
||||
);
|
||||
CREATE INDEX ix_segment_devices_server_idx ON public.ix_segment_devices(server_id);
|
||||
|
||||
CREATE TABLE public.ix_segment_revisions (
|
||||
segment_id uuid NOT NULL REFERENCES public.ix_segments(id) ON DELETE CASCADE,
|
||||
revision integer NOT NULL CHECK (revision > 0),
|
||||
configuration jsonb NOT NULL CHECK (jsonb_typeof(configuration) = 'object'),
|
||||
actor_id text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (segment_id, revision)
|
||||
);
|
||||
|
||||
INSERT INTO public.schema_migrations (id) VALUES ('0058_internet_exchange') ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
COMMIT;
|
||||
@@ -464,41 +464,6 @@
|
||||
],
|
||||
"reason": "Общий listRevisions с REST: только метаданные, максимум 50 записей; серверная область и права проверяются до SQL, payload ревизии не выдаётся."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/nodes",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Служебная проекция для выбора площадок в интерфейсе. В MCP доступ к серверам определяется областью подключения."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/segments",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.list"],
|
||||
"reason": "Общий сервис списка сегментов. MCP ограничивает выборку областью серверов и возвращает метаданные ревизий."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/segments/:id/linux",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Шаблон подключения Linux оператор получает в интерфейсе для локальной настройки клиента."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/segments/:id/status",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.read"],
|
||||
"reason": "Общий опрос маршрутов и BGP-сессий применённой ревизии. MCP проверяет доступ ко всем узлам сегмента."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/topology",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Проекция применённых связей для сетевой карты. MCP читает конфигурацию и состояние отдельных сегментов."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/logs",
|
||||
@@ -590,13 +555,6 @@
|
||||
"operations": [],
|
||||
"reason": "Управление самим MCP, транспорт или машинная авторизация: отдельного AI-инструмента нет."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/mcp/server-choices",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Каталог выбора серверов для выдачи доступа в панели MCP."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/mcp/connections/:id/grants",
|
||||
@@ -1597,34 +1555,6 @@
|
||||
],
|
||||
"reason": "Общий REST/MCP executor существующего сертификата: оба selector и все роли, явный private/CA intent, human MCP plan, actor/key no-replay, exact owned file/read/cleanup, encrypted owner-only artifact/TTL; синтетическая SQL/HTTP/portal и browser приёмка. Native CHR отдельно."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/preview",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Локальный предпросмотр объектов из компилятора. План MCP дополнительно фиксирует состояние площадок и требует подтверждения."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/plan",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.configure"],
|
||||
"reason": "Предпросмотр сохранённой ревизии для оператора. MCP строит отдельный план через общий сервис IX."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/apply",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.configure"],
|
||||
"reason": "Пользователь WebUI подтверждает просмотренную ревизию. MCP применяет свой подтверждённый план через общий исполнитель IX."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Сохранение черновика из интерфейса. Для изменения конфигурации через MCP используется план с подтверждением."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/mcp/connections",
|
||||
@@ -1695,20 +1625,6 @@
|
||||
"operations": ["network.bridge-vlan.configure"],
|
||||
"reason": "Подготовка связанного плана bridge/VLAN через тот же MCP-инструмент; выполнение требует человеческого подтверждения."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/mcp/ix/plan",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.configure"],
|
||||
"reason": "Интерфейс владельца вызывает тот же инструмент MCP подготовки плана IX. Применение проходит отдельно после подтверждения."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/mcp/ix/restore",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.restore"],
|
||||
"reason": "Интерфейс владельца вызывает тот же инструмент MCP подготовки восстановления сохранённой ревизии IX."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/mcp/management-channels",
|
||||
|
||||
+1
-10
@@ -7,7 +7,6 @@
|
||||
"test:mcp:module-completion": "tsx src/services/ipsec-server-init-model.test.ts && tsx src/modules/mcp/ipsec-server-init-actions.test.ts && tsx src/services/wireguard-revision-restore.test.ts && tsx src/modules/mcp/vrf-ticket-runtime.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-pool-dependencies.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx src/services/vrf-production-action-binding.test.ts && tsx src/services/ipsec-revision-restore-model.test.ts && tsx src/modules/mcp/ipsec-revision-actions.test.ts && tsx src/modules/mcp/service-native-progress.test.ts && tsx src/services/ipsec-revision-restore.test.ts && tsx src/services/ipsec-revision-secret.test.ts",
|
||||
"test:mcp:module-completion:pg": "node scripts/test-mcp-postgres.mjs --module-completion --restore",
|
||||
"test:mcp:pg": "node scripts/test-mcp-postgres.mjs",
|
||||
"test:mcp:pg:sharded": "node scripts/test-mcp-postgres-sharded.mjs",
|
||||
"test:mcp:users-bindings:pg": "node scripts/test-mcp-postgres.mjs --users-bindings",
|
||||
"test:mcp:bridge-vlan:pg": "node scripts/test-mcp-postgres.mjs --bridge-vlan-configuration",
|
||||
"test:mcp:external-process:pg": "node scripts/mcp-external-process/run-owned.mjs",
|
||||
@@ -17,7 +16,6 @@
|
||||
"test:traffic-flow:pg": "node scripts/test-mcp-postgres.mjs --flow-writes",
|
||||
"test:traffic-flow:quality:pg": "node scripts/test-mcp-postgres.mjs --flow-quality",
|
||||
"test:traffic-flow:chr-evidence": "tsx --test src/test/traffic-flow-chr-capture-check.test.ts src/test/traffic-flow-chr-wire.test.ts src/test/traffic-flow-chr-target-harness.test.ts src/test/traffic-flow-chr-owned-sequence.test.ts src/test/traffic-flow-chr-reconcile.test.ts",
|
||||
"test:changed": "node scripts/test-changed.mjs",
|
||||
"test:mcp:pg:all": "node scripts/test-mcp-postgres.mjs --all",
|
||||
"mcp:stdio": "node dist/scripts/mcp-stdio.js",
|
||||
"mcp:stdio:dev": "tsx src/scripts/mcp-stdio.ts",
|
||||
@@ -32,13 +30,6 @@
|
||||
"start": "node dist/index.js",
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "drizzle-kit migrate",
|
||||
"db:prepare": "tsx src/scripts/prepare-database.ts",
|
||||
"db:complete-restore": "tsx src/scripts/complete-database-restore.ts",
|
||||
"db:serve-restore-claims": "tsx src/scripts/serve-restore-checkpoint-claims.ts",
|
||||
"db:seal-restore-checkpoint": "tsx src/scripts/seal-database-restore-checkpoint.ts",
|
||||
"db:stage-restore-checkpoint": "tsx src/scripts/stage-database-restore-checkpoint.ts",
|
||||
"db:inspect-restore-checkpoint": "tsx src/scripts/inspect-database-restore-checkpoint.ts",
|
||||
"db:inspect-schema": "tsx src/scripts/inspect-database-schema.ts",
|
||||
"db:studio": "drizzle-kit studio",
|
||||
"db:migrate-from-sqlite": "tsx src/scripts/migrate-sqlite-to-pg.ts",
|
||||
"facts:rebuild": "tsx src/scripts/rebuild-flow-facts.ts",
|
||||
@@ -67,7 +58,7 @@
|
||||
"test:ospf-optimizer": "tsx src/services/ospf-cost-optimization.test.ts && tsx src/modules/mcp/ospf-legacy-source.test.ts && tsx src/services/ospf-legacy-optimization.test.ts && tsx src/services/ospf-template-flags.test.ts && tsx src/services/ospf-route-proof.test.ts && tsx src/services/ospf-link-catalog.test.ts && tsx src/services/ospf-identity-catalog.test.ts && tsx src/services/ospf-template-cost-write.test.ts && tsx src/services/ospf-template-cost-http.test.ts && tsx src/services/ospf-optimizer-identity.test.ts && tsx src/services/ospf-optimizer-metrics.test.ts && tsx src/services/ospf-optimizer-plan.test.ts && tsx src/services/ospf-effective-disabled.test.ts && tsx src/routes/ospf-optimizer.test.ts",
|
||||
"test:containers": "tsx src/services/containers-live.test.ts && tsx src/services/containers-state.test.ts && tsx src/services/container-removal.test.ts && tsx src/routes/containers-state.test.ts",
|
||||
"test:certificates": "tsx src/services/certificate-installation.test.ts && tsx src/services/certificate-renew-collector.test.ts && tsx src/services/certificate-issue-execution.test.ts && tsx src/services/certificate-issue-request.test.ts && tsx src/routes/certificates-issue.test.ts && tsx src/services/certificate-issue-dto.test.ts && tsx src/services/certificate-parse.test.ts && tsx src/services/certificates-state.test.ts && tsx src/routes/certificates-state.test.ts && tsx src/services/acme-settings-test.test.ts && tsx src/services/acme-settings-update-model.test.ts && tsx src/modules/mcp/acme-settings-actions.test.ts",
|
||||
"test:system-database": "tsx src/services/bounded-database-dump.test.ts && tsx src/services/database-dump-connection.test.ts && tsx src/services/system-database-partition-restore.test.ts && tsx src/services/system-database-cache.test.ts && tsx src/services/database-background-work.test.ts && tsx src/services/database-request-gate.test.ts && tsx --test src/services/detached-database-admission.test.ts && tsx src/services/traffic-flow-worker-shutdown.test.ts && tsx src/services/system-database-restore-execution.test.ts && tsx src/services/system-database-operation.test.ts && tsx src/services/system-database-schema-readiness.test.ts && tsx --test src/routes/mcp-oauth-database-admission.test.ts && tsx src/routes/system-database.test.ts && tsx src/plugins/auth.system-database.test.ts && tsx src/services/database-control-archive-boundary.test.ts && tsx src/db/database-schema-control-model.test.ts && tsx src/db/database-schema-control.test.ts && tsx src/db/controlled-migrations.test.ts && tsx src/db/controlled-schema-verification.test.ts && tsx --test src/db/migration-data-inventory.test.ts && tsx --test src/services/database-maintenance-startup.test.ts && tsx --test src/services/database-restore-audit.test.ts && tsx --test src/services/database-maintenance-resolution.test.ts && tsx --test scripts/database-maintenance-resolution.test.mts && tsx src/db/database-runtime-schema.test.ts",
|
||||
"test:system-database": "tsx src/services/bounded-database-dump.test.ts && tsx src/services/database-dump-connection.test.ts && tsx src/services/system-database-partition-restore.test.ts && tsx src/services/system-database-cache.test.ts && tsx src/services/database-background-work.test.ts && tsx src/services/database-request-gate.test.ts && tsx --test src/services/detached-database-admission.test.ts && tsx src/services/traffic-flow-worker-shutdown.test.ts && tsx src/services/system-database-restore-execution.test.ts && tsx src/services/system-database-operation.test.ts && tsx src/services/system-database-schema-readiness.test.ts && tsx --test src/routes/mcp-oauth-database-admission.test.ts && tsx src/routes/system-database.test.ts && tsx src/plugins/auth.system-database.test.ts && tsx src/services/database-control-archive-boundary.test.ts && tsx src/db/database-schema-control-model.test.ts && tsx src/db/database-schema-control.test.ts && tsx src/db/controlled-migrations.test.ts && tsx src/db/controlled-schema-verification.test.ts && tsx --test src/db/migration-data-inventory.test.ts && tsx --test src/services/database-maintenance-startup.test.ts && tsx --test src/services/database-restore-audit.test.ts && tsx --test src/services/database-maintenance-resolution.test.ts && tsx --test scripts/database-maintenance-resolution.test.mts",
|
||||
"test:all": "npm run test:logs && npm run test:probes && npm run test:exec && npm run test:alert-engine && npm run test:alerts-telegram && npm run test:auth && npm run test:wireguard && npm run test:ipsec && npm run test:traffic-rate && npm run test:traffic-flow && npm run test:users && npm run test:pg && npm run test:sidebar-counts && npm run test:backups && npm run test:scheduler && npm run test:live-maps && npm run test:ospf-optimizer && npm run test:recursive-routes && npm run test:config-sync && npm run test:ros-file && npm run test:containers && npm run test:certificates && npm run test:netflow-settings && npm run test:netflow-purge && npm run test:evolution && npm run test:system-database && npm run test:server-privacy && npm run test:mcp:module-completion && npm run test:mcp:loopback-agent && npm run test:server-probe-management && npm run test:server-poll-management && npm run test:mcp:routing-authority && npm run test:mcp:native-readers && npm run test:mcp:chr-acquisition && npm run test:mcp:shared-context && npm run test:mcp:telemetry-configuration",
|
||||
"test:server-privacy": "tsx ../packages/contracts/src/servers.test.ts && tsx src/routes/server-secrets-sql.test.ts && tsx --test src/services/server-connection-test.test.ts",
|
||||
"test:mcp:flow-rebuild:pg": "node scripts/test-mcp-postgres.mjs --flow-rebuild-mcp",
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { cpSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = fileURLToPath(new URL('../../../', import.meta.url));
|
||||
const baseRevision = 'bf3d50e1ff2ee3b5c9268991a255c3b49ce6378e';
|
||||
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
const require = (value, reason) => { if (!value) throw Error(reason); };
|
||||
const git = (...args) => execFileSync('git', args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 4 * 1024 * 1024 });
|
||||
const fromRoot = filename => path.join(root, filename);
|
||||
const readJson = bytes => JSON.parse(bytes.toString('utf8'));
|
||||
const manifestPath = ['backend/package.json', 'packages/contracts/package.json'];
|
||||
const runtimeKeys = ['type', 'exports', 'engines', 'dependencies', 'optionalDependencies', 'peerDependencies'];
|
||||
const normalizeLock = bytes => bytes.toString('utf8').replace(/\r\n/g, '\n');
|
||||
const sort = values => [...new Set(values)].sort();
|
||||
|
||||
function runtimePins() {
|
||||
const lockFile = readFileSync(fromRoot('package-lock.json'));
|
||||
require(normalizeLock(lockFile) === normalizeLock(git('show', baseRevision + ':package-lock.json')), 'Runtime lock differs from cached source');
|
||||
const lock = readJson(lockFile).packages;
|
||||
return manifestPath.flatMap(filename => {
|
||||
const current = readJson(readFileSync(fromRoot(filename)));
|
||||
const cached = readJson(git('show', baseRevision + ':' + filename));
|
||||
for (const key of runtimeKeys) {
|
||||
require(JSON.stringify(current[key]) === JSON.stringify(cached[key]), 'Runtime package manifest differs from cached source');
|
||||
}
|
||||
const workspace = path.posix.dirname(filename);
|
||||
return sort(Object.keys(current.dependencies ?? {})).filter(name => name !== '@mmapp/contracts').map(name => {
|
||||
const nested = workspace + '/node_modules/' + name, shared = 'node_modules/' + name;
|
||||
const installed = lock[nested] ? nested : shared;
|
||||
const version = lock[installed]?.version;
|
||||
require(typeof version === 'string', 'Runtime dependency pin unavailable');
|
||||
return { path: installed + '/package.json', name, version };
|
||||
});
|
||||
}).filter((item, index, all) => all.findIndex(other => other.path === item.path) === index);
|
||||
}
|
||||
|
||||
function compile(project, outDir) {
|
||||
execFileSync(process.execPath, [fromRoot('node_modules/typescript/bin/tsc'), '--project', fromRoot(project), '--outDir', outDir,
|
||||
'--declaration', 'false', '--declarationMap', 'false', '--sourceMap', 'false', '--incremental', 'false'],
|
||||
{ cwd: root, stdio: 'inherit' });
|
||||
}
|
||||
|
||||
function files(directory, prefix = '') {
|
||||
return readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)).flatMap(entry => {
|
||||
const key = prefix + entry.name, item = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) return files(item, key + '/');
|
||||
require(entry.isFile(), 'Packet contains a nonregular entry');
|
||||
const bytes = readFileSync(item);
|
||||
return [{ path: key, size: bytes.length, sha256: sha(bytes) }];
|
||||
});
|
||||
}
|
||||
|
||||
const [runId, ...extra] = process.argv.slice(2);
|
||||
require(/^[a-f0-9]{8}$/.test(runId ?? '') && !extra.length, 'Expected one eight-digit hexadecimal run ID');
|
||||
const directory = fromRoot('tmp/mcp-netflow-smoke-packet-' + runId);
|
||||
const dependencies = runtimePins();
|
||||
mkdirSync(directory);
|
||||
compile('packages/contracts/tsconfig.json', path.join(directory, 'contracts-dist'));
|
||||
compile('backend/tsconfig.json', path.join(directory, 'dist'));
|
||||
require(statSync(path.join(directory, 'dist/test/traffic-flow-chr-collector-bootstrap.js')).isFile(), 'Compiled collector entry unavailable');
|
||||
cpSync(fromRoot('backend/drizzle'), path.join(directory, 'drizzle'), { recursive: true, errorOnExist: true });
|
||||
const entries = files(directory);
|
||||
require(entries.length > 0 && entries.length <= 4096 && entries.reduce((sum, entry) => sum + entry.size, 0) <= 128 * 1024 * 1024,
|
||||
'Packet budget exceeded');
|
||||
const body = Buffer.from(JSON.stringify({ format: 'mmapp-netflow-collector-smoke-v1', cachedSourceRevision: baseRevision, dependencies,
|
||||
files: entries }, null, 2) + '\n');
|
||||
writeFileSync(path.join(directory, 'manifest.json'), body, { flag: 'wx' });
|
||||
console.log(JSON.stringify({ directory, manifestSha256: sha(body), files: entries.length, dependencies: dependencies.length,
|
||||
collectorStarted: false, networkUsed: false }));
|
||||
@@ -1,325 +0,0 @@
|
||||
"""Fixed, opt-in local Docker owner for the disposable NetFlow collector."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
PG_IMAGE = 'postgres@sha256:77f585114c32fbca283dc835b0596f4e52b51b4c6662d7810b2f4084f60a1873'
|
||||
NODE_IMAGE = 'git.shx.one/denozord/mikrotikmanager-backend-mcp-acceptance@sha256:151ab635caca5f2f6b50a9d0c27980a1559d7bd67f0e3a8d2b74cfa3f9ec6945'
|
||||
CID = re.compile(r'[a-f0-9]{64}\Z')
|
||||
RUN = re.compile(r'[a-f0-9]{8}\Z')
|
||||
LABEL = 'io.mmapp.netflow.run'
|
||||
ENV = {'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LC_ALL': 'C',
|
||||
'HOME': '/nonexistent', 'DOCKER_CONFIG': '/nonexistent'}
|
||||
|
||||
|
||||
def require(value, code):
|
||||
if not value:
|
||||
raise ValueError(code)
|
||||
|
||||
|
||||
def root(run):
|
||||
require(isinstance(run, str) and RUN.fullmatch(run), 'RUN_ID_REFUSED')
|
||||
return '/tmp/mcp-netflow-' + run
|
||||
|
||||
|
||||
def mounts(source, target, readonly=False):
|
||||
return ['--mount', 'type=bind,src=' + source + ',dst=' + target + (',readonly' if readonly else '')]
|
||||
|
||||
|
||||
def build_pg(run, uid, gid):
|
||||
base = root(run)
|
||||
require(type(uid) is int and 0 < uid <= 65534 and type(gid) is int and 0 < gid <= 65534, 'FIXTURE_ACCOUNT_REFUSED')
|
||||
return [
|
||||
'create', '--pull=never', '--name', 'mm-nf-pg-' + run,
|
||||
'--label', LABEL + '=' + run, '--label', 'io.mmapp.netflow.role=postgres',
|
||||
'--network=none', '--user', f'{uid}:{gid}', '--read-only',
|
||||
'--cap-drop=ALL', '--security-opt=no-new-privileges',
|
||||
'--memory=192m', '--memory-swap=192m',
|
||||
'--tmpfs', '/tmp:rw,nosuid,nodev,noexec,mode=1777,size=32m',
|
||||
'--tmpfs', '/var/run/postgresql:rw,nosuid,nodev,noexec,mode=1777,size=1m',
|
||||
*mounts(base + '/pg', '/owned-pg'),
|
||||
*mounts(base + '/pg-socket', base + '/pg-socket'),
|
||||
*mounts(base + '/pg-password', '/run/mm-netflow-pg-secret', True),
|
||||
'--env', 'PGDATA=/owned-pg/data', '--env', 'POSTGRES_USER=mcp_test',
|
||||
'--env', 'POSTGRES_DB=mcp_netflow_' + run,
|
||||
'--env', 'POSTGRES_PASSWORD_FILE=/run/mm-netflow-pg-secret',
|
||||
'--env', 'POSTGRES_INITDB_ARGS=--auth-local=scram-sha-256 --auth-host=scram-sha-256',
|
||||
PG_IMAGE, 'postgres', '-c', 'listen_addresses=', '-c', 'unix_socket_directories=' + base + '/pg-socket',
|
||||
'-c', 'unix_socket_permissions=0700',
|
||||
]
|
||||
|
||||
|
||||
def build_node(run, uid, gid, anchor_id, port, namespace, host_namespace, packet_digest):
|
||||
base = root(run)
|
||||
require(type(uid) is int and 0 < uid <= 65534 and type(gid) is int and 0 < gid <= 65534, 'FIXTURE_ACCOUNT_REFUSED')
|
||||
require(isinstance(anchor_id, str) and CID.fullmatch(anchor_id), 'ANCHOR_ID_REFUSED')
|
||||
require(isinstance(packet_digest, str) and CID.fullmatch(packet_digest), 'PACKET_PIN_REFUSED')
|
||||
require(type(port) is int and 49152 <= port <= 65535, 'COLLECTOR_PORT_REFUSED')
|
||||
require(all(type(pair) in (tuple, list) and len(pair) == 2 and
|
||||
all(type(value) is int and 0 < value < 2**64 for value in pair)
|
||||
for pair in (namespace, host_namespace)) and list(namespace) != list(host_namespace), 'NAMESPACE_PINS_REFUSED')
|
||||
return [
|
||||
'create', '--pull=never', '--name', 'mm-nf-node-' + run,
|
||||
'--label', LABEL + '=' + run, '--label', 'io.mmapp.netflow.role=collector',
|
||||
'--network=container:' + anchor_id, '--user', f'{uid}:{gid}', '--read-only',
|
||||
'--cap-drop=ALL', '--security-opt=no-new-privileges', '--interactive', '--tty',
|
||||
'--memory=320m', '--memory-swap=320m',
|
||||
'--tmpfs', '/tmp:rw,nosuid,nodev,noexec,mode=1777,size=32m',
|
||||
*mounts(base + '/collector', base),
|
||||
*mounts(base + '/pg-socket', base + '/pg-socket'),
|
||||
*mounts(base + '/pg-password', '/run/mm-netflow-pg-secret', True),
|
||||
*mounts(base + '/packet/dist', '/app/backend/dist', True),
|
||||
*mounts(base + '/packet/drizzle', '/app/backend/drizzle', True),
|
||||
*mounts(base + '/packet/contracts-dist', '/app/packages/contracts/dist', True),
|
||||
*mounts(base + '/packet/manifest.json', '/run/mm-netflow-packet.json', True),
|
||||
'--workdir', base, '--env', 'MMAPP_OWN_CHR_NETFLOW_COLLECTOR=true',
|
||||
'--env', 'MMAPP_NETFLOW_PACKET_SHA256=' + packet_digest,
|
||||
'--entrypoint', 'node', NODE_IMAGE,
|
||||
'--max-old-space-size=160', '--max-semi-space-size=8',
|
||||
'/app/backend/dist/test/traffic-flow-chr-collector-bootstrap.js',
|
||||
'--container-collector-cycle', run, str(port), *map(str, namespace), *map(str, host_namespace),
|
||||
]
|
||||
|
||||
|
||||
def capture_args(run, first, second, port):
|
||||
root(run)
|
||||
require((first, second) == ('198.18.241.2', '198.18.241.9') and
|
||||
type(port) is int and 49152 <= port <= 65535, 'CAPTURE_SCOPE_REFUSED')
|
||||
return ['nsenter', '--net=/run/netns/nf' + run + 'nc', '--',
|
||||
'tcpdump', '-n', '-p', '-U', '-i', 'nf' + run + 'cv', '-y', 'EN10MB', '-s', '4138',
|
||||
'-c', '64', '-w', '-', 'udp and dst host 198.18.242.3 and dst port ' + str(port) +
|
||||
' and (src host ' + first + ' or src host ' + second + ')']
|
||||
|
||||
|
||||
def local_docker():
|
||||
require(sys.platform == 'linux' and os.geteuid() == 0 and
|
||||
os.environ.get('MMAPP_OWN_CHR_NETFLOW_CONTAINER') == 'true', 'DOCKER_OWNER_REFUSED')
|
||||
socket = Path('/var/run/docker.sock')
|
||||
require(stat.S_ISSOCK(socket.stat().st_mode), 'LOCAL_DOCKER_SOCKET_UNAVAILABLE')
|
||||
choices = [Path(folder, 'docker') for folder in ('/usr/bin', '/usr/sbin', '/bin')]
|
||||
binary = next((path.resolve(strict=True) for path in choices if path.is_file()), None)
|
||||
require(binary is not None and binary.stat().st_uid == 0 and not binary.stat().st_mode & 0o022,
|
||||
'DOCKER_BINARY_UNPINNED')
|
||||
|
||||
def call(*args):
|
||||
result = subprocess.run([str(binary), '--host', 'unix:///var/run/docker.sock', *args],
|
||||
env=ENV, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL, timeout=30)
|
||||
require(result.returncode == 0 and len(result.stdout) <= 256 * 1024, 'DOCKER_OUTCOME_UNCONFIRMED')
|
||||
return result.stdout.decode('utf-8', 'strict').strip()
|
||||
|
||||
def attach(cid):
|
||||
require(CID.fullmatch(cid) and sys.stdin.isatty() and sys.stdout.isatty(), 'EXACT_TTY_REFUSED')
|
||||
return subprocess.run([str(binary), '--host', 'unix:///var/run/docker.sock', 'start', '--attach', '--interactive', cid],
|
||||
env=ENV, timeout=330).returncode
|
||||
|
||||
return call, attach
|
||||
|
||||
|
||||
def prepare_private_storage(run, uid, gid):
|
||||
"""Create only new private bind sources. A retained fixture is never reused."""
|
||||
require(sys.platform == 'linux' and os.geteuid() == 0 and
|
||||
os.environ.get('MMAPP_OWN_CHR_NETFLOW_CONTAINER') == 'true', 'DOCKER_OWNER_REFUSED')
|
||||
require(type(uid) is int and 0 < uid <= 65534 and type(gid) is int and 0 < gid <= 65534, 'FIXTURE_ACCOUNT_REFUSED')
|
||||
base = Path(root(run))
|
||||
info = base.lstat()
|
||||
require(base.resolve(strict=True) == base and stat.S_ISDIR(info.st_mode) and info.st_uid == uid and
|
||||
stat.S_IMODE(info.st_mode) == 0o700, 'FIXTURE_ROOT_REFUSED')
|
||||
for name in ('pg', 'pg-socket', 'collector'):
|
||||
directory = base / name
|
||||
directory.mkdir(mode=0o700)
|
||||
os.chown(directory, uid, gid, follow_symlinks=False)
|
||||
fd = os.open(base / 'pg-password', os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o400)
|
||||
with os.fdopen(fd, 'wb') as output:
|
||||
output.write((secrets.token_hex(32) + '\n').encode('ascii'))
|
||||
output.flush()
|
||||
os.fsync(output.fileno())
|
||||
os.fchown(output.fileno(), uid, gid)
|
||||
|
||||
|
||||
class CollectorContainerOwner:
|
||||
"""Outer Linux parent retains each acknowledged ID and journals it.
|
||||
|
||||
An unknown create/start/retire acknowledgement requires reconciliation.
|
||||
It never searches by label, restarts, prunes, or removes a matched name.
|
||||
"""
|
||||
def __init__(self, run, docker, checkpoint):
|
||||
root(run)
|
||||
self.run, self.docker, self.checkpoint = run, docker, checkpoint
|
||||
self.ids = {}
|
||||
self.attempted = set()
|
||||
self.verified_exits = {}
|
||||
self.anchor_start = None
|
||||
self.adopted = None
|
||||
self.topology_retired = False
|
||||
|
||||
def image(self, reference):
|
||||
rows = json.loads(self.docker('image', 'inspect', reference))
|
||||
require(len(rows) == 1 and reference in rows[0]['RepoDigests'] and rows[0]['Os'] == 'linux' and
|
||||
re.fullmatch(r'sha256:[a-f0-9]{64}', rows[0]['Id']), 'CACHED_IMAGE_UNPINNED')
|
||||
return rows[0]['Id']
|
||||
|
||||
def inspect(self, cid, role, image_id, network):
|
||||
require(CID.fullmatch(cid), 'CONTAINER_ID_UNPINNED')
|
||||
rows = json.loads(self.docker('container', 'inspect', cid))
|
||||
require(len(rows) == 1, 'CONTAINER_UNCONFIRMED')
|
||||
row = rows[0]
|
||||
labels = row['Config']['Labels']
|
||||
memory = (192 if role == 'postgres' else 320) * 1024 * 1024
|
||||
require(row['Id'] == cid and row['Image'] == image_id and labels[LABEL] == self.run and
|
||||
labels['io.mmapp.netflow.role'] == role and row['HostConfig']['NetworkMode'] == network and
|
||||
not row['HostConfig']['Privileged'] and not row['HostConfig']['PortBindings'] and
|
||||
row['HostConfig']['ReadonlyRootfs'] is True and row['HostConfig']['CapDrop'] == ['ALL'] and
|
||||
not row['HostConfig']['CapAdd'] and row['HostConfig']['Memory'] == memory and
|
||||
row['HostConfig']['MemorySwap'] == memory, 'CONTAINER_SCOPE_DRIFT')
|
||||
return row['State']
|
||||
|
||||
def _create(self, role, argv, reference, network):
|
||||
require(role not in self.attempted, 'CONTAINER_REPLAY_REFUSED')
|
||||
self.attempted.add(role)
|
||||
image_id = self.image(reference)
|
||||
self.checkpoint(role, 'create-intent', None)
|
||||
cid = self.docker(*argv)
|
||||
require(CID.fullmatch(cid), 'CREATE_ACK_UNCONFIRMED')
|
||||
self.checkpoint(role, 'create-acknowledged', cid)
|
||||
state = self.inspect(cid, role, image_id, network)
|
||||
require(state['Status'] == 'created' and state['Running'] is False, 'CREATED_STATE_UNCONFIRMED')
|
||||
self.ids[role] = (cid, image_id, network)
|
||||
self.checkpoint(role, 'create-verified', cid)
|
||||
return cid
|
||||
|
||||
def create_anchor(self, uid, gid):
|
||||
return self._create('postgres', build_pg(self.run, uid, gid), PG_IMAGE, 'none')
|
||||
|
||||
def create_collector(self, uid, gid, port, namespace, host_namespace, packet_digest, assert_packet):
|
||||
anchor_id, image_id, network = self.ids['postgres']
|
||||
anchor = self.inspect(anchor_id, 'postgres', image_id, network)
|
||||
require(anchor['Running'] is True and anchor['Pid'] > 0, 'ANCHOR_PID_UNCONFIRMED')
|
||||
require(self.adopted is not None, 'C_ADOPTION_UNCONFIRMED')
|
||||
adopted, read_mount = self.adopted
|
||||
require(adopted == self.anchor_namespace() and adopted['namespace'] == list(namespace) and
|
||||
adopted['hostNamespace'] == list(host_namespace) and read_mount() == adopted['namespace'],
|
||||
'C_ADOPTION_DRIFT')
|
||||
assert_packet()
|
||||
return self._create('collector', build_node(self.run, uid, gid, anchor_id, port, namespace, host_namespace, packet_digest),
|
||||
NODE_IMAGE, 'container:' + anchor_id)
|
||||
|
||||
def start_anchor(self):
|
||||
cid, image_id, network = self.ids['postgres']
|
||||
require('postgres-start' not in self.attempted, 'CONTAINER_REPLAY_REFUSED')
|
||||
self.attempted.add('postgres-start')
|
||||
self.checkpoint('postgres', 'start-intent', cid)
|
||||
require(self.docker('start', cid) == cid, 'START_ACK_UNCONFIRMED')
|
||||
state = self.inspect(cid, 'postgres', image_id, network)
|
||||
require(state['Running'] is True and type(state['Pid']) is int and state['Pid'] > 0 and
|
||||
re.fullmatch(r'\d{4}-\d{2}-\d{2}T[0-9:.]+Z', state['StartedAt']), 'ANCHOR_PID_UNCONFIRMED')
|
||||
self.checkpoint('postgres', 'start-verified', cid)
|
||||
self.anchor_start = (state['Pid'], state['StartedAt'])
|
||||
return state['Pid']
|
||||
|
||||
def anchor_namespace(self):
|
||||
"""Return live anchor and host netns pins for the topology owner."""
|
||||
require(sys.platform == 'linux' and os.geteuid() == 0, 'LINUX_OWNER_REQUIRED')
|
||||
cid, image_id, network = self.ids['postgres']
|
||||
state = self.inspect(cid, 'postgres', image_id, network)
|
||||
pid = state['Pid']
|
||||
started_at = state['StartedAt']
|
||||
require(state['Running'] is True and self.anchor_start == (pid, started_at), 'ANCHOR_PID_UNCONFIRMED')
|
||||
pin = Path('/proc', str(pid), 'ns/net').stat()
|
||||
host = Path('/proc/self/ns/net').stat()
|
||||
namespace, host_namespace = [pin.st_dev, pin.st_ino], [host.st_dev, host.st_ino]
|
||||
latest = self.inspect(cid, 'postgres', image_id, network)
|
||||
require(latest['Running'] is True and latest['Pid'] == pid and latest['StartedAt'] == started_at and
|
||||
namespace != host_namespace,
|
||||
'ANCHOR_NAMESPACE_DRIFT')
|
||||
return {'containerId': cid, 'pid': pid, 'startedAt': started_at,
|
||||
'namespace': namespace, 'hostNamespace': host_namespace}
|
||||
|
||||
def create_linux_topology(self, executor, backend, journal, planned, pins):
|
||||
"""Bridge the exact live anchor into the existing guarded Linux owner."""
|
||||
name = 'nf' + self.run + 'nc'
|
||||
require(pins['nonce'][:8] == self.run and planned['names']['C'] == name, 'TOPOLOGY_RUN_DIFFERS')
|
||||
require('topology-adopt' not in self.attempted, 'C_ADOPTION_REPLAY_REFUSED')
|
||||
self.attempted.add('topology-adopt')
|
||||
result = executor(backend, journal, planned, pins, read_collector_anchor=self.anchor_namespace)
|
||||
adopted = journal.value['collectorAnchor']
|
||||
require(adopted == self.anchor_namespace() and backend.namespace(name) == adopted['namespace'],
|
||||
'C_ADOPTION_DRIFT')
|
||||
self.adopted = (adopted, lambda: backend.namespace(name))
|
||||
return result
|
||||
|
||||
def assert_linux_anchor_exited(self, recorded):
|
||||
"""Validate the journalled container and its exact exit before C cleanup."""
|
||||
cid, image_id, network = self.ids['postgres']
|
||||
require(recorded['containerId'] == cid and 'postgres' in self.verified_exits and
|
||||
('collector' not in self.ids or 'collector' in self.verified_exits), 'ANCHOR_EXIT_NOT_OWNED')
|
||||
state = self.inspect(cid, 'postgres', image_id, network)
|
||||
require(state['Running'] is False and state['Status'] == 'exited' and state['Pid'] == 0 and
|
||||
state['StartedAt'] == recorded['startedAt'] == self.verified_exits['postgres'], 'ANCHOR_EXIT_UNCONFIRMED')
|
||||
|
||||
def cleanup_linux_topology(self, executor, backend, journal, planned):
|
||||
require(self.adopted is not None and self.adopted[0] == journal.value.get('collectorAnchor') and
|
||||
backend.root_baseline() == journal.value.get('rootBaseline'), 'TOPOLOGY_CLEANUP_SCOPE_DRIFT')
|
||||
executor(backend, journal, planned, assert_collector_anchor_exited=self.assert_linux_anchor_exited)
|
||||
require(journal.value['state'] == 'retired' and backend.root_baseline() == journal.value['rootBaseline'],
|
||||
'TOPOLOGY_CLEANUP_UNCONFIRMED')
|
||||
self.topology_retired = True
|
||||
|
||||
def start_collector(self, attach):
|
||||
cid, image_id, network = self.ids['collector']
|
||||
require('collector-start' not in self.attempted, 'CONTAINER_REPLAY_REFUSED')
|
||||
require(self.adopted is not None and self.adopted[0] == self.anchor_namespace() and
|
||||
self.adopted[1]() == self.adopted[0]['namespace'], 'C_ADOPTION_DRIFT')
|
||||
self.attempted.add('collector-start')
|
||||
self.checkpoint('collector', 'start-intent', cid)
|
||||
status = attach(cid)
|
||||
state = self.inspect(cid, 'collector', image_id, network)
|
||||
require(state['Running'] is False and state['Status'] == 'exited' and state['Pid'] == 0 and
|
||||
state['ExitCode'] == status and re.fullmatch(r'\d{4}-\d{2}-\d{2}T[0-9:.]+Z', state['StartedAt']),
|
||||
'COLLECTOR_EXIT_UNCONFIRMED')
|
||||
self.checkpoint('collector', 'exit-verified', cid)
|
||||
self.verified_exits['collector'] = state['StartedAt']
|
||||
require(status == 0, 'COLLECTOR_RUN_REFUSED')
|
||||
|
||||
def stop_anchor(self, assert_restored):
|
||||
cid, image_id, network = self.ids['postgres']
|
||||
require('postgres-stop' not in self.attempted, 'CONTAINER_REPLAY_REFUSED')
|
||||
require('collector' not in self.ids or 'collector' in self.verified_exits, 'COLLECTOR_EXIT_UNCONFIRMED')
|
||||
self.attempted.add('postgres-stop')
|
||||
assert_restored()
|
||||
self.checkpoint('postgres', 'stop-intent', cid)
|
||||
current = self.inspect(cid, 'postgres', image_id, network)
|
||||
require(current['Running'] is True and self.anchor_start == (current['Pid'], current['StartedAt']), 'ANCHOR_START_DRIFT')
|
||||
require(self.docker('stop', '--time', '15', cid) == cid, 'STOP_ACK_UNCONFIRMED')
|
||||
state = self.inspect(cid, 'postgres', image_id, network)
|
||||
require(state['Running'] is False and state['Status'] == 'exited' and state['Pid'] == 0 and
|
||||
state['StartedAt'] == self.anchor_start[1] and state['ExitCode'] == 0, 'ANCHOR_EXIT_UNCONFIRMED')
|
||||
self.checkpoint('postgres', 'exit-verified', cid)
|
||||
self.verified_exits['postgres'] = state['StartedAt']
|
||||
|
||||
def retire_exited(self, role):
|
||||
cid, image_id, network = self.ids[role]
|
||||
operation = role + '-retire'
|
||||
require(operation not in self.attempted, 'CONTAINER_REPLAY_REFUSED')
|
||||
require(role != 'postgres' or self.adopted is None or self.topology_retired, 'C_RETIREMENT_UNCONFIRMED')
|
||||
self.attempted.add(operation)
|
||||
state = self.inspect(cid, role, image_id, network)
|
||||
require(role in self.verified_exits and state['Running'] is False and state['Status'] == 'exited' and
|
||||
state['Pid'] == 0 and state['StartedAt'] == self.verified_exits[role], 'EXIT_NOT_CONFIRMED')
|
||||
self.checkpoint(role, 'retire-intent', cid)
|
||||
require(self.docker('rm', cid) == cid, 'RETIRE_ACK_UNCONFIRMED')
|
||||
self.checkpoint(role, 'retire-acknowledged', cid)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
cli = argparse.ArgumentParser()
|
||||
cli.add_argument('--check-only', required=True, metavar='RUN_ID')
|
||||
args = cli.parse_args()
|
||||
print(json.dumps({'fixtureRoot': root(args.check_only), 'postgresImage': PG_IMAGE, 'nodeImage': NODE_IMAGE,
|
||||
'requiresOwnedCollectorNamespace': True, 'dockerUsed': False, 'networkUsed': False}))
|
||||
@@ -1,143 +0,0 @@
|
||||
import json
|
||||
import runpy
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
owner = runpy.run_path(str(Path(__file__).with_name('chr-netflow-collector-container.py')))
|
||||
RUN = 'a012bcde'
|
||||
PG_ID = 'a' * 64
|
||||
NODE_ID = 'b' * 64
|
||||
PACKET = 'd' * 64
|
||||
IMAGE_ID = 'sha256:' + 'c' * 64
|
||||
STARTED = '2026-11-04T12:00:00.000Z'
|
||||
|
||||
|
||||
class DockerFixture:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
self.records = {}
|
||||
self.lose_create = False
|
||||
|
||||
def __call__(self, *args):
|
||||
self.calls.append(args)
|
||||
if args[:2] == ('image', 'inspect'):
|
||||
return json.dumps([{'Id': IMAGE_ID, 'Os': 'linux', 'RepoDigests': [args[2]]}])
|
||||
if args[0] == 'create':
|
||||
if self.lose_create:
|
||||
raise RuntimeError('lost ACK')
|
||||
pg = '--network=none' in args
|
||||
role, cid = ('postgres', PG_ID) if pg else ('collector', NODE_ID)
|
||||
self.records[cid] = {'Id': cid, 'Image': IMAGE_ID, 'Config': {'Labels': {
|
||||
owner['LABEL']: RUN, 'io.mmapp.netflow.role': role}},
|
||||
'HostConfig': {'NetworkMode': 'none' if pg else 'container:' + PG_ID, 'Privileged': False,
|
||||
'PortBindings': None, 'ReadonlyRootfs': True, 'CapDrop': ['ALL'], 'CapAdd': None,
|
||||
'Memory': (192 if pg else 320) * 1024 * 1024,
|
||||
'MemorySwap': (192 if pg else 320) * 1024 * 1024},
|
||||
'State': {'Running': False, 'Status': 'created', 'Pid': 0}}
|
||||
return cid
|
||||
cid = args[-1]
|
||||
if args[:2] == ('container', 'inspect'):
|
||||
return json.dumps([self.records[cid]])
|
||||
if args[0] == 'start':
|
||||
self.records[cid]['State'] = {'Running': True, 'Status': 'running', 'Pid': 42, 'StartedAt': STARTED}
|
||||
elif args[0] == 'stop':
|
||||
self.records[cid]['State'] = {'Running': False, 'Status': 'exited', 'Pid': 0, 'StartedAt': STARTED, 'ExitCode': 0}
|
||||
elif args[0] == 'rm':
|
||||
del self.records[cid]
|
||||
else:
|
||||
raise AssertionError(args)
|
||||
return cid
|
||||
|
||||
|
||||
class TestCollectorLauncher(unittest.TestCase):
|
||||
def test_exact_images_no_pull_no_privilege_and_fixed_namespace(self):
|
||||
pg = owner['build_pg'](RUN, 1000, 1000)
|
||||
node = owner['build_node'](RUN, 1000, 1000, PG_ID, 50100, (4, 5), (4, 6), PACKET)
|
||||
self.assertIn('--network=none', pg)
|
||||
self.assertIn('--network=container:' + PG_ID, node)
|
||||
self.assertIn('listen_addresses=', pg)
|
||||
for argv in (pg, node):
|
||||
self.assertIn('--pull=never', argv)
|
||||
self.assertIn('--cap-drop=ALL', argv)
|
||||
self.assertNotIn('--privileged', argv)
|
||||
self.assertNotIn('/var/run/docker.sock', ' '.join(argv))
|
||||
self.assertNotIn('POSTGRES_PASSWORD=', ' '.join(pg))
|
||||
with self.assertRaisesRegex(ValueError, 'NAMESPACE_PINS'):
|
||||
owner['build_node'](RUN, 1000, 1000, PG_ID, 50100, (4, 5), (4, 5), PACKET)
|
||||
self.assertIn('EN10MB', owner['capture_args'](RUN, '198.18.241.2', '198.18.241.9', 50100))
|
||||
|
||||
def test_one_shot_ack_exact_ids_and_verified_cleanup(self):
|
||||
docker, journal = DockerFixture(), []
|
||||
launcher = owner['CollectorContainerOwner'](RUN, docker, lambda *entry: journal.append(entry))
|
||||
self.assertEqual(launcher.create_anchor(1000, 1000), PG_ID)
|
||||
self.assertEqual(launcher.start_anchor(), 42)
|
||||
with self.assertRaisesRegex(ValueError, 'ADOPTION_UNCONFIRMED'):
|
||||
launcher.create_collector(1000, 1000, 50100, (4, 5), (4, 6), PACKET, lambda: None)
|
||||
anchor = {'containerId': PG_ID, 'pid': 42, 'startedAt': STARTED, 'namespace': [4, 5], 'hostNamespace': [4, 6]}
|
||||
launcher.anchor_namespace = lambda: anchor
|
||||
name = 'nf' + RUN + 'nc'
|
||||
|
||||
class Topology:
|
||||
def namespace(self, target):
|
||||
return [4, 5] if target == name else None
|
||||
|
||||
def root_baseline(self):
|
||||
return 'root-baseline'
|
||||
|
||||
class Journal:
|
||||
value = {}
|
||||
|
||||
def provision(backend, journal, planned, pins, read_collector_anchor):
|
||||
journal.value.update(collectorAnchor=read_collector_anchor(), rootBaseline='root-baseline', state='created')
|
||||
return {'ns:' + name: backend.namespace(name)}
|
||||
|
||||
def cleanup(backend, journal, planned, assert_collector_anchor_exited):
|
||||
assert_collector_anchor_exited(journal.value['collectorAnchor'])
|
||||
journal.value['state'] = 'retired'
|
||||
|
||||
topology, topology_journal, planned = Topology(), Journal(), {'names': {'C': name}}
|
||||
launcher.create_linux_topology(provision, topology, topology_journal, planned, {'nonce': RUN + '0' * 24})
|
||||
self.assertEqual(launcher.create_collector(1000, 1000, 50100, (4, 5), (4, 6), PACKET, lambda: None), NODE_ID)
|
||||
with self.assertRaisesRegex(ValueError, 'EXIT_NOT_OWNED'):
|
||||
launcher.cleanup_linux_topology(cleanup, topology, topology_journal, planned)
|
||||
|
||||
def attach(cid):
|
||||
self.assertEqual(cid, NODE_ID)
|
||||
docker.records[cid]['State'] = {'Running': False, 'Status': 'exited', 'Pid': 0, 'ExitCode': 0, 'StartedAt': STARTED}
|
||||
return 0
|
||||
|
||||
launcher.start_collector(attach)
|
||||
launcher.retire_exited('collector')
|
||||
launcher.stop_anchor(lambda: None)
|
||||
with self.assertRaisesRegex(ValueError, 'C_RETIREMENT_UNCONFIRMED'):
|
||||
launcher.retire_exited('postgres')
|
||||
launcher.cleanup_linux_topology(cleanup, topology, topology_journal, planned)
|
||||
launcher.retire_exited('postgres')
|
||||
self.assertEqual(docker.records, {})
|
||||
self.assertIn(('collector', 'exit-verified', NODE_ID), journal)
|
||||
self.assertEqual([call for call in docker.calls if call[0] == 'rm'], [('rm', NODE_ID), ('rm', PG_ID)])
|
||||
|
||||
def test_lost_create_ack_is_not_replayed_or_cleaned_by_name(self):
|
||||
docker, journal = DockerFixture(), []
|
||||
docker.lose_create = True
|
||||
launcher = owner['CollectorContainerOwner'](RUN, docker, lambda *entry: journal.append(entry))
|
||||
with self.assertRaisesRegex(RuntimeError, 'lost ACK'):
|
||||
launcher.create_anchor(1000, 1000)
|
||||
with self.assertRaisesRegex(ValueError, 'REPLAY'):
|
||||
launcher.create_anchor(1000, 1000)
|
||||
self.assertEqual(journal, [('postgres', 'create-intent', None)])
|
||||
self.assertEqual([call[0] for call in docker.calls], ['image', 'create'])
|
||||
|
||||
def test_anchor_process_replaced_under_same_container_id_is_never_stopped(self):
|
||||
docker = DockerFixture()
|
||||
launcher = owner['CollectorContainerOwner'](RUN, docker, lambda *_: None)
|
||||
launcher.create_anchor(1000, 1000)
|
||||
launcher.start_anchor()
|
||||
docker.records[PG_ID]['State']['StartedAt'] = '2026-11-04T13:00:00.000Z'
|
||||
with self.assertRaisesRegex(ValueError, 'ANCHOR_START_DRIFT'):
|
||||
launcher.stop_anchor(lambda: None)
|
||||
self.assertFalse(any(call[0] == 'stop' for call in docker.calls))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,242 +0,0 @@
|
||||
"""Disposable collector-only cycle. No RouterOS clients or capture are opened."""
|
||||
import argparse
|
||||
import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import runpy
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
owner = runpy.run_path(str(Path(__file__).with_name('chr-netflow-collector-container.py')))
|
||||
require = owner['require']
|
||||
MAX_PACKET = 128 * 1024 * 1024
|
||||
PACKET_PATH = re.compile(r'(?:dist|drizzle|contracts-dist)/(?:[A-Za-z0-9_.-]+/)*[A-Za-z0-9_.-]+\Z')
|
||||
|
||||
|
||||
def verify_packet(directory, digest, require_root=False):
|
||||
require(re.fullmatch(r'[a-f0-9]{64}', digest), 'PACKET_DIGEST_REFUSED')
|
||||
require(directory.resolve(strict=True) == directory and directory.is_dir(), 'PACKET_DIRECTORY_REFUSED')
|
||||
manifest = directory / 'manifest.json'
|
||||
info = manifest.lstat()
|
||||
require(stat.S_ISREG(info.st_mode) and 0 < info.st_size <= 1048576, 'PACKET_MANIFEST_REFUSED')
|
||||
raw = manifest.read_bytes()
|
||||
require(hashlib.sha256(raw).hexdigest() == digest, 'PACKET_MANIFEST_DRIFT')
|
||||
value = json.loads(raw)
|
||||
require(value.get('format') == 'mmapp-netflow-collector-smoke-v1' and
|
||||
value.get('cachedSourceRevision') == 'bf3d50e1ff2ee3b5c9268991a255c3b49ce6378e' and
|
||||
type(value.get('files')) is list and 1 <= len(value['files']) <= 4096, 'PACKET_MANIFEST_REFUSED')
|
||||
total, listed = 0, {'manifest.json'}
|
||||
for row in value['files']:
|
||||
relative = row.get('path', '')
|
||||
require(PACKET_PATH.fullmatch(relative) and
|
||||
not any(part in ('.', '..') for part in relative.split('/')) and relative not in listed and
|
||||
type(row.get('size')) is int and 0 < row['size'] <= 2 * 1024 * 1024 and
|
||||
re.fullmatch(r'[a-f0-9]{64}', row.get('sha256', '')), 'PACKET_FILE_REFUSED')
|
||||
item = directory / relative
|
||||
info = item.lstat()
|
||||
total += row['size']
|
||||
require(total <= MAX_PACKET and stat.S_ISREG(info.st_mode) and item.resolve(strict=True) == item and
|
||||
info.st_size == row['size'] and hashlib.sha256(item.read_bytes()).hexdigest() == row['sha256'], 'PACKET_FILE_DRIFT')
|
||||
listed.add(relative)
|
||||
observed = set()
|
||||
for folder, directories, filenames in os.walk(directory, followlinks=False):
|
||||
parent = Path(folder)
|
||||
for entry in [parent, *(parent / name for name in directories + filenames)]:
|
||||
info = entry.lstat()
|
||||
require(not stat.S_ISLNK(info.st_mode) and
|
||||
(not require_root or info.st_uid == 0 and not info.st_mode & 0o022), 'PACKET_OWNERSHIP_REFUSED')
|
||||
observed.update((parent / filename).relative_to(directory).as_posix() for filename in filenames)
|
||||
require(observed == listed and 'dist/test/traffic-flow-chr-collector-bootstrap.js' in listed, 'PACKET_FILE_SET_DRIFT')
|
||||
return {'files': len(listed) - 1, 'bytes': total, 'manifestSha256': digest}
|
||||
|
||||
|
||||
def pack(directory, digest):
|
||||
match = re.fullmatch(r'mcp-netflow-smoke-packet-([a-f0-9]{8})', directory.name)
|
||||
require(match is not None, 'PACKET_DIRECTORY_REFUSED')
|
||||
verified = verify_packet(directory, digest)
|
||||
archive = directory.parent / ('mcp-netflow-collector-smoke-' + match[1] + '.tar.gz')
|
||||
manifest = json.loads((directory / 'manifest.json').read_bytes())
|
||||
script_root = Path(__file__).resolve().parent
|
||||
scripts = ('chr-netflow-collector-smoke.py', 'chr-netflow-collector-container.py')
|
||||
with archive.open('xb') as destination, gzip.GzipFile(fileobj=destination, mode='wb', filename='', mtime=0) as compressed:
|
||||
with tarfile.open(fileobj=compressed, mode='w|', format=tarfile.USTAR_FORMAT) as tar:
|
||||
def add(name, body):
|
||||
item = tarfile.TarInfo(name)
|
||||
item.mode = 0o644
|
||||
item.size = len(body)
|
||||
tar.addfile(item, io.BytesIO(body))
|
||||
for name in scripts:
|
||||
add(name, (script_root / name).read_bytes())
|
||||
add('packet/manifest.json', (directory / 'manifest.json').read_bytes())
|
||||
for row in manifest['files']:
|
||||
add('packet/' + row['path'], (directory / row['path']).read_bytes())
|
||||
with archive.open('rb') as stream:
|
||||
archive_sha = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
return {**verified, 'archive': str(archive), 'archiveSha256': archive_sha, 'dockerUsed': False, 'networkUsed': False}
|
||||
|
||||
|
||||
class SmokeNamespace:
|
||||
"""Only the C alias and one local dummy address, never the transit topology."""
|
||||
def __init__(self, run, ip, namespace, checkpoint):
|
||||
self.name, self.device = 'nf' + run + 'nc', 'nf' + run + 'cv'
|
||||
self.ip, self.namespace, self.checkpoint = ip, namespace, checkpoint
|
||||
self.anchor = None
|
||||
|
||||
def create(self, read_anchor):
|
||||
require(self.anchor is None and self.namespace(self.name) is None, 'SMOKE_NAMESPACE_PRESENT')
|
||||
anchor = read_anchor()
|
||||
require(anchor['namespace'] != anchor['hostNamespace'] and read_anchor() == anchor, 'SMOKE_ANCHOR_DRIFT')
|
||||
self.checkpoint('smoke', 'attach-intent', anchor)
|
||||
self.ip('netns', 'attach', self.name, str(anchor['pid']))
|
||||
require(self.namespace(self.name) == anchor['namespace'] and read_anchor() == anchor, 'SMOKE_ATTACH_UNCONFIRMED')
|
||||
self.checkpoint('smoke', 'attach-verified', anchor)
|
||||
self.anchor = anchor
|
||||
def current():
|
||||
require(self.namespace(self.name) == anchor['namespace'] and read_anchor() == anchor, 'SMOKE_ANCHOR_DRIFT')
|
||||
links = json.loads(self.ip('-n', self.name, '-j', 'link', 'show'))
|
||||
require([item['ifname'] for item in links] == ['lo'], 'SMOKE_NAMESPACE_NOT_EMPTY')
|
||||
self.checkpoint('smoke', 'dummy-intent', self.device)
|
||||
current()
|
||||
self.ip('-n', self.name, 'link', 'add', self.device, 'type', 'dummy')
|
||||
current()
|
||||
created = json.loads(self.ip('-n', self.name, '-j', '-d', 'link', 'show', 'dev', self.device))
|
||||
require(len(created) == 1 and created[0]['ifname'] == self.device and
|
||||
created[0]['linkinfo']['info_kind'] == 'dummy' and created[0]['ifindex'] > 0, 'SMOKE_DUMMY_UNCONFIRMED')
|
||||
self.ip('-n', self.name, 'address', 'add', '198.18.242.3/32', 'dev', self.device)
|
||||
current()
|
||||
self.ip('-n', self.name, 'link', 'set', self.device, 'up')
|
||||
rows = json.loads(self.ip('-n', self.name, '-j', '-d', 'address', 'show', 'dev', self.device))
|
||||
routes = json.loads(self.ip('-n', self.name, '-j', '-4', 'route', 'show', 'table', 'all'))
|
||||
require(len(rows) == 1 and rows[0]['ifname'] == self.device and rows[0]['linkinfo']['info_kind'] == 'dummy' and
|
||||
rows[0]['ifindex'] == created[0]['ifindex'] and
|
||||
'UP' in rows[0]['flags'] and any(row.get('local') == '198.18.242.3' and row.get('prefixlen') == 32
|
||||
for row in rows[0]['addr_info']) and all(row.get('dst') != 'default' for row in routes) and
|
||||
self.namespace(self.name) == anchor['namespace'] and read_anchor() == anchor, 'SMOKE_DUMMY_UNCONFIRMED')
|
||||
self.checkpoint('smoke', 'dummy-verified', rows[0]['ifindex'])
|
||||
return anchor
|
||||
|
||||
def restore(self, assert_anchor_exited):
|
||||
require(self.anchor is not None and self.namespace(self.name) == self.anchor['namespace'],
|
||||
'SMOKE_NAMESPACE_DRIFT')
|
||||
assert_anchor_exited(self.anchor)
|
||||
require(not self.ip('netns', 'pids', self.name).strip(), 'SMOKE_NAMESPACE_BUSY')
|
||||
self.checkpoint('smoke', 'delete-intent', self.anchor)
|
||||
self.ip('netns', 'delete', self.name)
|
||||
require(self.namespace(self.name) is None, 'SMOKE_NAMESPACE_RETIREMENT_UNCONFIRMED')
|
||||
self.checkpoint('smoke', 'delete-verified', self.anchor)
|
||||
|
||||
|
||||
def linux_ip():
|
||||
binary = next((item.resolve(strict=True) for item in (Path('/usr/sbin/ip'), Path('/usr/bin/ip'), Path('/sbin/ip'))
|
||||
if item.is_file()), None)
|
||||
require(binary is not None and binary.stat().st_uid == 0 and not binary.stat().st_mode & 0o022, 'IP_BINARY_UNPINNED')
|
||||
|
||||
def call(*args):
|
||||
result = subprocess.run([str(binary), *args], env=owner['ENV'], stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=8)
|
||||
require(result.returncode == 0 and len(result.stdout) <= 128 * 1024, 'IP_OUTCOME_UNCONFIRMED')
|
||||
return result.stdout.decode('utf-8', 'strict')
|
||||
return call
|
||||
|
||||
|
||||
def ns_pin(name):
|
||||
try:
|
||||
row = Path('/run/netns', name).lstat()
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
require(stat.S_ISREG(row.st_mode) and row.st_uid == 0, 'SMOKE_NAMESPACE_HANDLE_UNSAFE')
|
||||
return [row.st_dev, row.st_ino]
|
||||
|
||||
|
||||
def run_smoke(run, uid, gid, port, digest):
|
||||
docker, attach = owner['local_docker']()
|
||||
base = Path(owner['root'](run))
|
||||
packet = base / 'packet'
|
||||
verify_packet(packet, digest, require_root=True)
|
||||
ip = linux_ip()
|
||||
require(ns_pin('nf' + run + 'nc') is None, 'SMOKE_NAMESPACE_PRESENT')
|
||||
journal = os.open(base / 'collector-smoke.jsonl', os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(journal, 'w', encoding='utf-8') as report:
|
||||
def checkpoint(role, phase, value):
|
||||
report.write(json.dumps({'role': role, 'phase': phase, 'value': value}, separators=(',', ':')) + '\n')
|
||||
report.flush()
|
||||
os.fsync(report.fileno())
|
||||
|
||||
checkpoint('smoke', 'packet-verified', digest)
|
||||
owner['prepare_private_storage'](run, uid, gid)
|
||||
runner = owner['CollectorContainerOwner'](run, docker, checkpoint)
|
||||
runner.create_anchor(uid, gid)
|
||||
runner.start_anchor()
|
||||
scope = SmokeNamespace(run, ip, ns_pin, checkpoint)
|
||||
# Reuse the container owner's live-C admission and retirement checks.
|
||||
class Journal:
|
||||
value = {}
|
||||
class Backend:
|
||||
def namespace(self, name):
|
||||
return ns_pin(name)
|
||||
def root_baseline(self):
|
||||
raw = [ip('-j', '-4', 'route', 'show', 'table', 'all'), ip('-j', '-d', 'link', 'show')]
|
||||
# Link counters/traffic are outside root configuration; use exact names and ifindex.
|
||||
links = sorted((row['ifname'], row['ifindex']) for row in json.loads(raw[1]))
|
||||
return hashlib.sha256(json.dumps([json.loads(raw[0]), links], sort_keys=True).encode()).hexdigest()
|
||||
def provision(backend, ledger, _plan, _pins, read_collector_anchor):
|
||||
baseline = backend.root_baseline()
|
||||
anchor = scope.create(read_collector_anchor)
|
||||
require(backend.root_baseline() == baseline, 'ROOT_NETWORK_DRIFT')
|
||||
ledger.value.update(collectorAnchor=anchor, rootBaseline=baseline, state='created')
|
||||
return anchor
|
||||
def cleanup(_backend, ledger, _plan, assert_collector_anchor_exited):
|
||||
scope.restore(assert_collector_anchor_exited)
|
||||
ledger.value['state'] = 'retired'
|
||||
backend, ledger, plan = Backend(), Journal(), {'names': {'C': scope.name}}
|
||||
pin = runner.create_linux_topology(provision, backend, ledger, plan, {'nonce': run + '0' * 24})
|
||||
wait_until = time.monotonic() + 20
|
||||
socket = base / 'pg-socket' / '.s.PGSQL.5432'
|
||||
while not socket.exists() and time.monotonic() < wait_until:
|
||||
time.sleep(.1)
|
||||
require(stat.S_ISSOCK(socket.lstat().st_mode), 'PRIVATE_PG_NOT_READY')
|
||||
runner.create_collector(uid, gid, port, pin['namespace'], pin['hostNamespace'], digest,
|
||||
lambda: verify_packet(packet, digest, require_root=True))
|
||||
runner.start_collector(attach)
|
||||
runner.retire_exited('collector')
|
||||
runner.stop_anchor(lambda: require(ledger.value['state'] == 'created', 'SMOKE_TOPOLOGY_DRIFT'))
|
||||
runner.cleanup_linux_topology(cleanup, backend, ledger, plan)
|
||||
runner.retire_exited('postgres')
|
||||
checkpoint('smoke', 'complete', None)
|
||||
return {'collectorSmokeCompleted': True, 'chrMutations': 0, 'capturePerformed': False, 'nativeAcceptance': False}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
sub = parser.add_subparsers(dest='mode', required=True)
|
||||
check = sub.add_parser('check')
|
||||
check.add_argument('packet', type=Path)
|
||||
check.add_argument('sha256')
|
||||
package = sub.add_parser('pack')
|
||||
package.add_argument('packet', type=Path)
|
||||
package.add_argument('sha256')
|
||||
run = sub.add_parser('run')
|
||||
run.add_argument('run_id')
|
||||
run.add_argument('uid', type=int)
|
||||
run.add_argument('gid', type=int)
|
||||
run.add_argument('port', type=int)
|
||||
run.add_argument('sha256')
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if args.mode == 'check':
|
||||
result = {**verify_packet(args.packet.resolve(), args.sha256), 'dockerUsed': False, 'networkUsed': False}
|
||||
elif args.mode == 'pack':
|
||||
result = pack(args.packet.resolve(), args.sha256)
|
||||
else:
|
||||
result = run_smoke(args.run_id, args.uid, args.gid, args.port, args.sha256)
|
||||
print(json.dumps(result))
|
||||
except (OSError, ValueError, RuntimeError, subprocess.SubprocessError, KeyError) as error:
|
||||
print(json.dumps({'completed': False, 'failureClass': type(error).__name__, 'automaticReplay': False}))
|
||||
raise SystemExit(1) from None
|
||||
@@ -1,69 +0,0 @@
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
smoke = runpy.run_path(str(Path(__file__).with_name('chr-netflow-collector-smoke.py')))
|
||||
|
||||
|
||||
class SmokeTests(unittest.TestCase):
|
||||
def test_pin_and_file_set_drift_fail_closed(self):
|
||||
with tempfile.TemporaryDirectory(dir=Path(__file__).resolve().parents[3] / 'tmp') as temp:
|
||||
root = Path(temp).resolve()
|
||||
entry = root / 'dist/test/traffic-flow-chr-collector-bootstrap.js'
|
||||
entry.parent.mkdir(parents=True)
|
||||
entry.write_bytes(b'owned fixture\n')
|
||||
body = json.dumps({'format': 'mmapp-netflow-collector-smoke-v1',
|
||||
'cachedSourceRevision': 'bf3d50e1ff2ee3b5c9268991a255c3b49ce6378e',
|
||||
'files': [{'path': entry.relative_to(root).as_posix(), 'size': entry.stat().st_size,
|
||||
'sha256': hashlib.sha256(entry.read_bytes()).hexdigest()}]}).encode()
|
||||
(root / 'manifest.json').write_bytes(body)
|
||||
digest = hashlib.sha256(body).hexdigest()
|
||||
self.assertEqual(smoke['verify_packet'](root, digest)['files'], 1)
|
||||
entry.write_bytes(b'foreign data!\n')
|
||||
with self.assertRaisesRegex(ValueError, 'FILE_DRIFT'):
|
||||
smoke['verify_packet'](root, digest)
|
||||
with self.assertRaisesRegex(ValueError, 'MANIFEST_DRIFT'):
|
||||
smoke['verify_packet'](root, '0' * 64)
|
||||
|
||||
def test_exact_dummy_namespace_and_busy_cleanup(self):
|
||||
anchor = {'containerId': 'a' * 64, 'pid': 42, 'namespace': [10, 20], 'hostNamespace': [10, 21]}
|
||||
calls, journal = [], []
|
||||
namespace = None
|
||||
busy = True
|
||||
name, device = 'nfa012bcdenc', 'nfa012bcdecv'
|
||||
link = {'ifname': device, 'ifindex': 5, 'linkinfo': {'info_kind': 'dummy'}, 'flags': ['UP'],
|
||||
'addr_info': [{'local': '198.18.242.3', 'prefixlen': 32}]}
|
||||
def ip(*args):
|
||||
nonlocal namespace
|
||||
calls.append(args)
|
||||
if args[:2] == ('netns', 'attach'):
|
||||
self.assertEqual(args, ('netns', 'attach', name, '42'))
|
||||
namespace = anchor['namespace']
|
||||
elif args[:2] == ('netns', 'pids'):
|
||||
return '42' if busy else ''
|
||||
elif args[:2] == ('netns', 'delete'):
|
||||
self.assertEqual(args, ('netns', 'delete', name))
|
||||
namespace = None
|
||||
elif args == ('-n', name, '-j', 'link', 'show'):
|
||||
return json.dumps([{'ifname': 'lo'}])
|
||||
elif '-d' in args:
|
||||
return json.dumps([link])
|
||||
elif 'route' in args:
|
||||
return '[]'
|
||||
return ''
|
||||
fixture = smoke['SmokeNamespace']('a012bcde', ip, lambda _name: namespace, lambda *row: journal.append(row))
|
||||
self.assertEqual(fixture.create(lambda: anchor), anchor)
|
||||
self.assertIn(('-n', name, 'address', 'add', '198.18.242.3/32', 'dev', device), calls)
|
||||
with self.assertRaisesRegex(ValueError, 'NAMESPACE_BUSY'):
|
||||
fixture.restore(lambda pin: self.assertEqual(pin, anchor))
|
||||
self.assertNotIn(('netns', 'delete', name), calls)
|
||||
busy = False
|
||||
fixture.restore(lambda pin: self.assertEqual(pin, anchor))
|
||||
self.assertEqual(journal[-1][1], 'delete-verified')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,221 +0,0 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { isIPv4 } from 'node:net';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
const routes = Object.freeze(['/system/resource', '/ip/traffic-flow', '/ip/traffic-flow/target']);
|
||||
const policyRoutes = Object.freeze(['/system/resource', '/ip/settings', '/ip/firewall/connection/tracking',
|
||||
'/ip/firewall/filter', '/ip/firewall/raw', '/ip/firewall/mangle', '/ip/firewall/nat', '/routing/rule', '/ip/vrf']);
|
||||
const counterFields = ['ifindex', 'rx-packet', 'tx-packet', 'fp-rx-byte', 'fp-tx-byte', 'fp-rx-packet', 'fp-tx-packet'];
|
||||
const nativeId = value => typeof value === 'string' && /^\*[a-f0-9]{1,16}$/i.test(value);
|
||||
const ports = Object.freeze({ '194.226.121.150': 19081, '104.165.244.7': 19082 });
|
||||
const attestation = 'verified-known-host-161.104.46.222-owned-forward';
|
||||
const reviewedTransportHash = '67d86dbae2710a25145df8ab9469029182f21a31972c49f063cdb6bc3daa8ea6';
|
||||
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
const deny = () => { throw new Error('NetFlow discovery refused'); };
|
||||
|
||||
export async function loadPinnedNetFlowTransport(policy = false) {
|
||||
const allowedPaths = policy ? policyRoutes : routes;
|
||||
return loadTransport(allowedPaths, allowedPaths.length * 2, policy ? 131072 : 65536);
|
||||
}
|
||||
|
||||
async function loadTransport(allowedPaths, requests, responseLimit, totalLimit = responseLimit * requests) {
|
||||
const bytes = await readFile(new URL('./chr-recursive-observation.mjs', import.meta.url));
|
||||
if (sha(bytes) !== reviewedTransportHash) deny();
|
||||
const reviewed = bytes.toString('utf8');
|
||||
const source = reviewed.slice(0, reviewed.indexOf('async function privateStdin()'))
|
||||
.replace(/const ROOT = .*?;/, 'const ROOT = null;')
|
||||
.replace(/export const PATHS = Object.freeze\(\[[\s\S]*?\]\);/, `export const PATHS = Object.freeze(${JSON.stringify(allowedPaths)});`)
|
||||
.replace('response: 1048576, bytes: 8388608, requests: 256',
|
||||
`response: ${responseLimit}, bytes: ${totalLimit}, requests: ${requests}`);
|
||||
const transport = await import('data:text/javascript;base64,' + Buffer.from(source).toString('base64'));
|
||||
if (JSON.stringify(transport.PATHS) !== JSON.stringify(allowedPaths)) deny();
|
||||
for (const [host, port] of Object.entries(ports)) {
|
||||
if (endpoint(transport, host) !== `http://127.0.0.1:${port}`) deny();
|
||||
}
|
||||
return transport;
|
||||
}
|
||||
|
||||
export async function discoverPinnedInterfaceCounterShape(read) {
|
||||
const devices = [];
|
||||
for (const host of Object.keys(ports)) {
|
||||
const inventory = await read(host, '/interface');
|
||||
if (!Array.isArray(inventory) || inventory.length > 256 ||
|
||||
inventory.some(row => !nativeId(row?.['.id'])) ||
|
||||
new Set(inventory.map(row => row['.id'])).size !== inventory.length) deny();
|
||||
const preferred = type => inventory.find(row => row.type === type &&
|
||||
observedFlag(row.running) === true && observedFlag(row.disabled) === false);
|
||||
const chosen = preferred('wg') ?? preferred('ether');
|
||||
if (!chosen) {
|
||||
devices.push({ status: 'no-eligible-interface' });
|
||||
continue;
|
||||
}
|
||||
const exact = single(await read(host, '/interface/' + encodeURIComponent(chosen['.id'])));
|
||||
if (exact['.id'] !== chosen['.id'] || exact.type !== chosen.type ||
|
||||
observedFlag(exact.running) !== true || observedFlag(exact.disabled) !== false) deny();
|
||||
const fields = Object.fromEntries(counterFields.map(key => {
|
||||
const value = exact[key];
|
||||
return [key, { present: Object.hasOwn(exact, key),
|
||||
type: value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value }];
|
||||
}));
|
||||
devices.push({ status: 'shape-observed', fields });
|
||||
}
|
||||
return { devices, ingressVerified: false, capturePerformed: false, mutationsPerformed: false };
|
||||
}
|
||||
|
||||
function endpoint(transport, host) {
|
||||
return transport.configuration(['--source', host, '--transport', 'ssh-loopback', '--output',
|
||||
'tmp/netflow-endpoint-discovery', '--owned-tunnel-attestation', attestation]).endpoint;
|
||||
}
|
||||
|
||||
function bool(value) {
|
||||
if (value === true || value === 'true') return true;
|
||||
if (value === false || value === 'false') return false;
|
||||
return deny();
|
||||
}
|
||||
|
||||
function single(rows) {
|
||||
if (rows.length !== 1) deny();
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
function observedFlag(value) {
|
||||
if ([true, 'true', 'yes'].includes(value)) return true;
|
||||
if ([false, 'false', 'no'].includes(value)) return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function discoverPinnedNetFlowPolicy(read) {
|
||||
const exporters = [];
|
||||
for (const host of Object.keys(ports)) {
|
||||
const resource = single(await read(host, policyRoutes[0]));
|
||||
if (typeof resource.version !== 'string' || !/^\d+\.\d+(?:\.\d+)?(?: \([a-z-]+\))?$/.test(resource.version)) deny();
|
||||
const ip = single(await read(host, policyRoutes[1]));
|
||||
const tracking = single(await read(host, policyRoutes[2]));
|
||||
const firewall = {};
|
||||
const vetoes = [];
|
||||
const ipForward = observedFlag(ip['ip-forward']);
|
||||
const allowFastPath = observedFlag(ip['allow-fast-path']);
|
||||
const conntrack = tracking.enabled === 'auto' ? 'auto' : observedFlag(tracking.enabled);
|
||||
if (ipForward !== true) vetoes.push('ip-forward-not-confirmed');
|
||||
if (allowFastPath !== false) vetoes.push('fast-path-not-confirmed-disabled');
|
||||
if (conntrack !== true) vetoes.push('conntrack-not-explicitly-enabled');
|
||||
for (const path of policyRoutes.slice(3, 7)) {
|
||||
const rows = await read(host, path);
|
||||
const enabled = rows.filter(row => observedFlag(row.disabled) !== true);
|
||||
firewall[path.split('/').at(-1)] = {
|
||||
total: rows.length,
|
||||
notExplicitlyDisabled: enabled.length,
|
||||
fastTrack: enabled.filter(row => row.action === 'fasttrack-connection').length,
|
||||
};
|
||||
}
|
||||
const routingRules = await read(host, policyRoutes[7]);
|
||||
const activeRoutingRules = routingRules.filter(row => observedFlag(row.disabled) !== true).length;
|
||||
if (activeRoutingRules) vetoes.push('routing-policy-present');
|
||||
const vrfs = await read(host, policyRoutes[8]);
|
||||
const mainVrfOnly = vrfs.length === 1 && vrfs[0].name === 'main' && vrfs[0].interfaces === 'all' &&
|
||||
observedFlag(vrfs[0].disabled) !== true;
|
||||
if (!mainVrfOnly) vetoes.push('main-vrf-only-not-confirmed');
|
||||
exporters.push({ host, version: resource.version, ipForward, allowFastPath, conntrack, firewall,
|
||||
activeRoutingRules, vrfCount: vrfs.length, mainVrfOnly, vetoes });
|
||||
}
|
||||
return {
|
||||
status: exporters.some(item => item.vetoes.length) ? 'pre-topology-veto' : 'no-global-veto-observed',
|
||||
exporters, routeSelectionVerified: false, tuplePolicyVerified: false,
|
||||
ingressVerified: false, capturePerformed: false, mutationsPerformed: false,
|
||||
};
|
||||
}
|
||||
|
||||
function target(row) {
|
||||
if (bool(row.disabled) || row.version !== 'ipfix') return null;
|
||||
const destination = row['dst-address'];
|
||||
const portText = String(row.port);
|
||||
if (!isIPv4(destination) || !/^[1-9][0-9]{0,4}$/.test(portText) || Number(portText) > 65535) deny();
|
||||
const source = row['src-address'];
|
||||
if (source !== undefined && source !== '' && !isIPv4(source)) deny();
|
||||
return { destination, port: Number(portText), configuredSource: source && source !== '0.0.0.0' ? source : null };
|
||||
}
|
||||
|
||||
export async function discoverPinnedNetFlowEndpoints(read) {
|
||||
const exporters = [];
|
||||
for (const host of Object.keys(ports)) {
|
||||
const resource = single(await read(host, routes[0]));
|
||||
if (typeof resource.version !== 'string' || !/^\d+\.\d+(?:\.\d+)?(?: \([a-z-]+\))?$/.test(resource.version)) deny();
|
||||
const enabled = bool(single(await read(host, routes[1])).enabled);
|
||||
const rows = await read(host, routes[2]);
|
||||
if (rows.length > 64) deny();
|
||||
const configuredTargets = rows.map(target).filter(Boolean);
|
||||
exporters.push({ host, version: resource.version, enabled, configuredTargets });
|
||||
}
|
||||
const [first, second] = exporters;
|
||||
const sameEndpoint = (a, b) => a.destination === b.destination && a.port === b.port;
|
||||
const common = first.enabled && second.enabled
|
||||
? first.configuredTargets.filter(a => second.configuredTargets.some(b => sameEndpoint(a, b)))
|
||||
: [];
|
||||
const unique = common.length === 1 && second.configuredTargets.filter(b => sameEndpoint(common[0], b)).length === 1;
|
||||
return {
|
||||
status: common.length === 0 ? 'no-common-active-ipfix-target' : unique ? 'configured-endpoint' : 'ambiguous-endpoint',
|
||||
configuredEndpoint: unique ? { destination: common[0].destination, port: common[0].port } : null,
|
||||
exporters,
|
||||
ingressVerified: false,
|
||||
capturePerformed: false,
|
||||
mutationsPerformed: false,
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const mode = process.argv.slice(2);
|
||||
if (mode.length !== 1) deny();
|
||||
const policy = mode[0] === '--check-policy' || mode[0] === '--read-pinned-policy';
|
||||
const counters = mode[0] === '--check-counters' || mode[0] === '--read-pinned-counters';
|
||||
const transport = counters ? await loadTransport(['/interface'], 4, 131072) : await loadPinnedNetFlowTransport(policy);
|
||||
if (mode[0] === '--check-only' || mode[0] === '--check-policy') {
|
||||
console.log(JSON.stringify({ transportSha256: reviewedTransportHash, loopbackPorts: ports, readPaths: transport.PATHS, networkUsed: false }));
|
||||
return;
|
||||
}
|
||||
if (mode[0] === '--check-counters') {
|
||||
const detail = await loadTransport(['/interface/*A'], 4, 16384);
|
||||
if (detail.PATHS[0] !== '/interface/*A') deny();
|
||||
console.log(JSON.stringify({ transportSha256: reviewedTransportHash, loopbackPorts: ports,
|
||||
readPaths: ['/interface', '/interface/<observed-native-id>'], networkUsed: false }));
|
||||
return;
|
||||
}
|
||||
if (!['--read-pinned', '--read-pinned-policy', '--read-pinned-counters'].includes(mode[0]) || process.stdin.isTTY) deny();
|
||||
const chunks = [];
|
||||
let length = 0;
|
||||
for await (const chunk of process.stdin) {
|
||||
length += chunk.length;
|
||||
if (length > 4096) deny();
|
||||
chunks.push(chunk);
|
||||
}
|
||||
const input = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)));
|
||||
if (!input || input.attestation !== attestation ||
|
||||
Object.keys(input).length !== 2 || !input.passwords || Object.keys(input.passwords).length !== 2) deny();
|
||||
const passwords = Object.keys(ports).map(host => input.passwords[host]);
|
||||
if (passwords.some(password => typeof password !== 'string' || !/^[^\u0000-\u001f\u007f]{1,512}$/u.test(password))) deny();
|
||||
const authorizations = passwords.map(password => 'Basic ' + Buffer.from('admin:' + password).toString('base64'));
|
||||
const secrets = [...passwords, ...authorizations, ...authorizations.map(value => value.slice(6))].map(value => Buffer.from(value));
|
||||
const budget = { requests: 0, bytes: 0, rows: 0, deadline: Date.now() + 30000 };
|
||||
const discovery = counters ? discoverPinnedInterfaceCounterShape : policy ? discoverPinnedNetFlowPolicy : discoverPinnedNetFlowEndpoints;
|
||||
const report = await discovery(async (host, route) => {
|
||||
const authorization = authorizations[Object.keys(ports).indexOf(host)];
|
||||
let selected = transport;
|
||||
if (counters && route !== '/interface') {
|
||||
if (!route.startsWith('/interface/') || !nativeId(route.slice('/interface/'.length))) deny();
|
||||
selected = await loadTransport([route], 4, 16384, 524288);
|
||||
}
|
||||
const response = await selected.readResponse(endpoint(selected, host), route, authorization, budget);
|
||||
if (secrets.some(secret => response.body.includes(secret))) deny();
|
||||
return response.rows;
|
||||
});
|
||||
const output = JSON.stringify(report);
|
||||
if (secrets.some(secret => Buffer.from(output).includes(secret))) deny();
|
||||
console.log(output);
|
||||
}
|
||||
|
||||
if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
|
||||
main().catch(() => {
|
||||
console.error('NetFlow discovery refused');
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { discoverPinnedInterfaceCounterShape, discoverPinnedNetFlowEndpoints, discoverPinnedNetFlowPolicy, loadPinnedNetFlowTransport } from './chr-netflow-endpoint-discovery.mjs';
|
||||
|
||||
const hosts = ['194.226.121.150', '104.165.244.7'];
|
||||
const routes = ['/system/resource', '/ip/traffic-flow', '/ip/traffic-flow/target'];
|
||||
const target = { disabled: 'false', version: 'ipfix', 'dst-address': '192.0.2.10', port: '2055', 'src-address': '0.0.0.0' };
|
||||
|
||||
function fixture(targets, enabled = ['true', 'true']) {
|
||||
const calls = [];
|
||||
const read = async (host, path) => {
|
||||
calls.push([host, path]);
|
||||
if (path === routes[0]) return [{ version: '7.24.5 (stable)' }];
|
||||
if (path === routes[1]) return [{ enabled: enabled[hosts.indexOf(host)] }];
|
||||
assert.equal(path, routes[2]);
|
||||
return targets[hosts.indexOf(host)];
|
||||
};
|
||||
return { read, calls };
|
||||
}
|
||||
|
||||
test('loads the reviewed source with the exact read-only path and relay fence', async () => {
|
||||
const transport = await loadPinnedNetFlowTransport();
|
||||
assert.deepEqual(transport.PATHS, routes);
|
||||
assert.throws(() => transport.readResponse('http://127.0.0.1:19082', '/ip/address', '', {}), /request-budget/);
|
||||
assert.throws(() => transport.readResponse('http://127.0.0.1:19083', routes[0], '', {}), /non-whitelisted-endpoint/);
|
||||
});
|
||||
|
||||
test('reports only a common configured endpoint, with no ingress or capture claim', async () => {
|
||||
const { read, calls } = fixture([[target], [{ ...target, 'src-address': '192.0.2.20' }]]);
|
||||
const report = await discoverPinnedNetFlowEndpoints(read);
|
||||
assert.deepEqual(calls, hosts.flatMap(host => routes.map(path => [host, path])));
|
||||
assert.equal(report.status, 'configured-endpoint');
|
||||
assert.deepEqual(report.configuredEndpoint, { destination: '192.0.2.10', port: 2055 });
|
||||
assert.deepEqual(report.exporters.map(item => item.configuredTargets[0].configuredSource), [null, '192.0.2.20']);
|
||||
assert.equal(report.ingressVerified, false);
|
||||
assert.equal(report.capturePerformed, false);
|
||||
assert.equal(report.mutationsPerformed, false);
|
||||
});
|
||||
|
||||
test('returns successful absence for missing or disabled baseline', async () => {
|
||||
for (const input of [
|
||||
fixture([[], [target]]),
|
||||
fixture([[target], [target]], [true, false]),
|
||||
fixture([[target], [{ ...target, disabled: true }]]),
|
||||
fixture([[target], [{ ...target, version: '9' }]]),
|
||||
]) {
|
||||
const result = await discoverPinnedNetFlowEndpoints(input.read);
|
||||
assert.equal(result.status, 'no-common-active-ipfix-target');
|
||||
assert.equal(result.configuredEndpoint, null);
|
||||
}
|
||||
});
|
||||
|
||||
test('refuses malformed relevant rows and withholds ambiguous common endpoints', async () => {
|
||||
const result = await discoverPinnedNetFlowEndpoints(fixture([[target], [target, target]]).read);
|
||||
assert.equal(result.status, 'ambiguous-endpoint');
|
||||
assert.equal(result.configuredEndpoint, null);
|
||||
await assert.rejects(discoverPinnedNetFlowEndpoints(fixture([[target], [{ ...target, port: '65536' }]]).read), /^Error: NetFlow discovery refused$/);
|
||||
});
|
||||
|
||||
test('reports preliminary global vetoes and counts with no claim on tuple policy or routes', async () => {
|
||||
const transport = await loadPinnedNetFlowTransport(true);
|
||||
const calls = [];
|
||||
const report = await discoverPinnedNetFlowPolicy(async (host, path) => {
|
||||
calls.push([host, path]);
|
||||
return ({
|
||||
'/system/resource': [{ version: '7.24.5 (stable)' }],
|
||||
'/ip/settings': [{ 'ip-forward': 'yes', 'allow-fast-path': host === hosts[0] ? 'yes' : 'no' }],
|
||||
'/ip/firewall/connection/tracking': [{ enabled: host === hosts[0] ? 'auto' : 'yes' }],
|
||||
'/ip/firewall/filter': [{ action: 'fasttrack-connection' }, { action: 'drop', disabled: 'true' }],
|
||||
'/ip/firewall/raw': [], '/ip/firewall/mangle': [], '/ip/firewall/nat': [],
|
||||
'/routing/rule': host === hosts[0] ? [{}] : [],
|
||||
'/ip/vrf': [{ name: 'main', interfaces: 'all' }],
|
||||
})[path];
|
||||
});
|
||||
assert.deepEqual(calls, hosts.flatMap(host => transport.PATHS.map(path => [host, path])));
|
||||
assert.equal(report.status, 'pre-topology-veto');
|
||||
assert.deepEqual(report.exporters[0].vetoes, ['fast-path-not-confirmed-disabled', 'conntrack-not-explicitly-enabled', 'routing-policy-present']);
|
||||
assert.deepEqual(report.exporters[1].vetoes, []);
|
||||
assert.deepEqual(report.exporters[0].firewall.filter, { total: 2, notExplicitlyDisabled: 1, fastTrack: 1 });
|
||||
assert.equal(report.routeSelectionVerified, false);
|
||||
assert.equal(report.tuplePolicyVerified, false);
|
||||
assert.equal(report.ingressVerified, false);
|
||||
});
|
||||
|
||||
test('counter shape reads exact selected native IDs and emits no identities or counter values', async () => {
|
||||
const ether = { '.id': '*A', name: 'private-ether', type: 'ether', running: 'true', disabled: 'false' };
|
||||
const wg = { ...ether, '.id': '*B', name: 'private-wg', type: 'wg' };
|
||||
const calls = [];
|
||||
const report = await discoverPinnedInterfaceCounterShape(async (host, route) => {
|
||||
calls.push([host, route]);
|
||||
if (route === '/interface') return host === hosts[0] ? [ether, wg] : [ether];
|
||||
return [{ ...(host === hosts[0] ? wg : ether), ifindex: '61455', 'rx-packet': 71922, 'fp-rx-byte': null }];
|
||||
});
|
||||
assert.deepEqual(calls, [[hosts[0], '/interface'], [hosts[0], '/interface/*B'], [hosts[1], '/interface'], [hosts[1], '/interface/*A']]);
|
||||
assert.deepEqual(report.devices[0].fields.ifindex, { present: true, type: 'string' });
|
||||
assert.deepEqual(report.devices[0].fields['rx-packet'], { present: true, type: 'number' });
|
||||
assert.deepEqual(report.devices[0].fields['fp-rx-byte'], { present: true, type: 'null' });
|
||||
assert.deepEqual(report.devices[0].fields['tx-packet'], { present: false, type: 'undefined' });
|
||||
assert.doesNotMatch(JSON.stringify(report), /private|61455|71922|104\.165|194\.226|\*[AB]/);
|
||||
await assert.rejects(discoverPinnedInterfaceCounterShape(async (_host, route) =>
|
||||
route === '/interface' ? [ether] : [{ ...ether, '.id': '*C' }]), /discovery refused/);
|
||||
});
|
||||
@@ -1,86 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { lstat, readFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { decodeBody, SOURCES } from './chr-recursive-observation.mjs';
|
||||
|
||||
const reviewedReportSha256 = 'fccf5171c8e50730a3e7c1fcceeeb77f1e946589ac4a56c6e04668e0ff4663f9';
|
||||
const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
const opaqueId = value => typeof value === 'string' && /^\*[a-f0-9]+$/i.test(value);
|
||||
const decimalIndex = value => typeof value === 'string' && /^[1-9][0-9]{0,15}$/.test(value);
|
||||
|
||||
export function inspectDirectLinks(routes, nexthops, interfaces, tables) {
|
||||
function keyed(rows, field, valid) {
|
||||
const index = new Map();
|
||||
for (const row of rows) {
|
||||
const key = row[field];
|
||||
assert(valid(key) && !index.has(key), 'Missing or ambiguous ' + field);
|
||||
index.set(key, row);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
const byNexthopId = keyed(nexthops, '.id', opaqueId);
|
||||
const byInterfaceIndex = keyed(interfaces, 'ifindex', decimalIndex);
|
||||
const byTableName = keyed(tables, 'name', value => typeof value === 'string' && value !== '' && !/^[0-9]+$/.test(value));
|
||||
let opaqueReferences = 0, namedInterfaceCorroborations = 0, interfaceIdSubstitutionRefusals = 0;
|
||||
for (const route of routes) {
|
||||
assert(byTableName.has(route['routing-table']), 'Missing named routing table');
|
||||
if (!Object.hasOwn(route, 'nexthop-id')) continue;
|
||||
const nexthop = byNexthopId.get(route['nexthop-id']);
|
||||
assert(nexthop, 'No exact opaque nexthop match');
|
||||
opaqueReferences++;
|
||||
const gateway = route['immediate-gw'];
|
||||
const name = typeof gateway === 'string' ? /%([^%@]+)$/.exec(gateway)?.[1] : undefined;
|
||||
if (!name) continue;
|
||||
const index = nexthop['immediate-gw.interface-idx'];
|
||||
const observed = byInterfaceIndex.get(index);
|
||||
assert(observed?.name === name && interfaces.filter(row => row.name === name).length === 1,
|
||||
'No exact named interface corroboration for ifindex');
|
||||
namedInterfaceCorroborations++;
|
||||
if (!interfaces.some(row => row.id === index && row.name === name)) interfaceIdSubstitutionRefusals++;
|
||||
}
|
||||
assert(opaqueReferences && namedInterfaceCorroborations && interfaceIdSubstitutionRefusals, 'Capture lacks discriminating direct links');
|
||||
return { opaqueReferences, namedInterfaceCorroborations, interfaceIdSubstitutionRefusals,
|
||||
tableNames: byTableName.size, recursiveLinkRows: nexthops.filter(row => Object.keys(row).some(key => key === 'links' || key.startsWith('links.'))).length };
|
||||
}
|
||||
|
||||
async function readPinned(directory, filename, digest) {
|
||||
const file = path.join(directory, filename), stat = await lstat(file);
|
||||
assert(stat.isFile() && !stat.isSymbolicLink() && stat.size <= 1048576, 'Unavailable bounded raw file');
|
||||
const bytes = await readFile(file);
|
||||
assert(bytes.length === stat.size && sha256(bytes) === digest, 'Raw capture hash changed');
|
||||
return bytes;
|
||||
}
|
||||
|
||||
export async function checkReviewedDirectLinks(directory) {
|
||||
const report = JSON.parse(await readPinned(directory, 'report.json', reviewedReportSha256));
|
||||
const sources = [];
|
||||
for (const source of report.sources) {
|
||||
assert(source.complete && source.versionBracketEqual && SOURCES[source.source]?.serverId === source.serverId);
|
||||
const read = async (index, resource) => {
|
||||
const record = source.records[index];
|
||||
assert(record.resource === resource && record.status === 200 && record.version === '7.24.5 (stable)');
|
||||
assert(record.file === `server${source.serverId}-${String(index + 1).padStart(2, '0')}-${resource.slice(1).replaceAll('/', '-')}.json`);
|
||||
return decodeBody(await readPinned(directory, record.file, record.rawSha256)).rows;
|
||||
};
|
||||
const routes = await read(1, '/routing/route'), nexthops = await read(2, '/routing/nexthop');
|
||||
assert.deepEqual(await read(7, '/routing/route'), routes);
|
||||
assert.deepEqual(await read(6, '/routing/nexthop'), nexthops);
|
||||
assert.equal(source.records[1].rawSha256, source.records[7].rawSha256);
|
||||
assert.equal(source.records[2].rawSha256, source.records[6].rawSha256);
|
||||
const interfaces = await read(3, '/interface'), tables = await read(4, '/routing/table');
|
||||
sources.push({ serverId: source.serverId, ...inspectDirectLinks(routes, nexthops, interfaces, tables) });
|
||||
}
|
||||
return { reviewedReportSha256, sources, recursiveIdentity: 'unknown', semanticProof: false };
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
try {
|
||||
assert(process.argv.length === 3, 'Supply the reviewed offline capture directory');
|
||||
process.stdout.write(JSON.stringify(await checkReviewedDirectLinks(process.argv[2])) + '\n');
|
||||
} catch {
|
||||
process.stderr.write('Reviewed direct-link corroboration refused.\n');
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { inspectDirectLinks } from './chr-recursive-direct-links.mjs';
|
||||
|
||||
test('direct evidence requires exact opaque reference and corroborated ifindex namespace', () => {
|
||||
const route = { 'routing-table': 'main', 'nexthop-id': '*A', 'immediate-gw': '192.0.2.1%ether1' };
|
||||
const nexthop = { '.id': '*A', 'immediate-gw.interface-idx': '4' };
|
||||
const iface = { id: '9', ifindex: '4', name: 'ether1' };
|
||||
const table = { '.id': '*0', name: 'main' };
|
||||
assert.deepEqual(inspectDirectLinks([route], [nexthop], [iface], [table]), {
|
||||
opaqueReferences: 1, namedInterfaceCorroborations: 1, interfaceIdSubstitutionRefusals: 1, tableNames: 1, recursiveLinkRows: 0,
|
||||
});
|
||||
assert.throws(() => inspectDirectLinks([{ ...route, 'nexthop-id': '*a' }], [nexthop], [iface], [table]), /exact opaque/);
|
||||
assert.throws(() => inspectDirectLinks([{ ...route, 'routing-table': '0' }], [nexthop], [iface], [table]), /named routing table/);
|
||||
assert.throws(() => inspectDirectLinks([route], [nexthop], [{ ...iface, id: '4', ifindex: '9' }], [table]), /corroboration/);
|
||||
assert.throws(() => inspectDirectLinks([route], [nexthop], [iface, { ...iface, id: '3' }], [table]), /ambiguous ifindex/);
|
||||
});
|
||||
@@ -111,7 +111,7 @@ export async function acquire(config, credentials) {
|
||||
const authorization = 'Basic ' + Buffer.from(credentials.username + ':' + credentials.password).toString('base64');
|
||||
const report = { format: 'chr-recursive-raw-acquisition-v1', source: fixed.source, serverId: fixed.serverId,
|
||||
transport: fixed.transport, tunnelAttestation: fixed.tunnelAttestation, startedAt: new Date().toISOString(),
|
||||
semanticProof: false, complete: false, snapshotBracket: null, records: [], limits: LIMITS };
|
||||
semanticProof: false, complete: false, records: [], limits: LIMITS };
|
||||
let version, attemptedResource;
|
||||
try {
|
||||
for (const [index, resource] of PATHS.entries()) {
|
||||
@@ -130,13 +130,6 @@ export async function acquire(config, credentials) {
|
||||
report.records.push({ file, resource, startedAt, finishedAt: new Date().toISOString(), version,
|
||||
status: response.status, contentType: response.contentType, bytes: response.body.length, rows: response.rows.length, rawSha256: sha(response.body) });
|
||||
}
|
||||
const hashFor = resource => report.records.filter(record => record.resource === resource).map(record => record.rawSha256);
|
||||
const [firstRoute, lastRoute] = hashFor('/routing/route');
|
||||
const [firstNexthop, lastNexthop] = hashFor('/routing/nexthop');
|
||||
report.snapshotBracket = {
|
||||
routeByteEqual: firstRoute === lastRoute,
|
||||
nexthopByteEqual: firstNexthop === lastNexthop,
|
||||
};
|
||||
report.complete = true;
|
||||
} catch (error) {
|
||||
report.failure = 'acquisition-incomplete';
|
||||
@@ -170,8 +163,7 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
|
||||
const config = configuration(process.argv.slice(2));
|
||||
const report = await acquire(config, await privateStdin());
|
||||
// Stdout contains metadata only; no native bodies, credentials or errors.
|
||||
process.stdout.write(JSON.stringify({ complete: report.complete, snapshotBracket: report.snapshotBracket,
|
||||
semanticProof: false, source: report.source, records: report.records.length }) + '\n');
|
||||
process.stdout.write(JSON.stringify({ complete: report.complete, semanticProof: false, source: report.source, records: report.records.length }) + '\n');
|
||||
if (!report.complete) process.exitCode = 1;
|
||||
} catch { process.stderr.write('Read-only acquisition refused or incomplete.\n'); process.exitCode = 1; }
|
||||
}
|
||||
@@ -17,13 +17,11 @@ test('source/transport allowlist refuses arbitrary hosts, plaintext external, mi
|
||||
|
||||
test('full own fixture saves nine exact immutable captures and metadata; reflected errors never enter reports', async () => {
|
||||
const output = fileURLToPath(new URL('../../../tmp/chr-recursive-own-fixture-' + randomUUID(), import.meta.url)), seen = [];
|
||||
let reflect = false, driftingResource;
|
||||
let reflect = false;
|
||||
const server = createServer((req, res) => {
|
||||
seen.push(req.url); res.setHeader('Content-Type', 'application/json');
|
||||
if (reflect) { res.statusCode = 401; res.end('{"message":"own-fixture-secret-only"}'); return; }
|
||||
if (req.url === '/rest/system/resource') res.end('[{"version":"7.26"}]\n');
|
||||
else if (req.url === driftingResource && seen.indexOf(req.url) !== seen.length - 1) res.end('[{".id":"*2"}]\n');
|
||||
else res.end('[{".id":"*1"}]\n');
|
||||
res.end(req.url === '/rest/system/resource' ? '[{"version":"7.26"}]\n' : '[{".id":"*1"}]\n');
|
||||
});
|
||||
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(19081, '127.0.0.1', resolve); });
|
||||
const makeConfig = destination => configuration(['--source', '194.226.121.150', '--transport', 'ssh-loopback', '--output', destination,
|
||||
@@ -31,7 +29,6 @@ test('full own fixture saves nine exact immutable captures and metadata; reflect
|
||||
try {
|
||||
const report = await acquire(makeConfig(output), { username: 'own-fixture', password: 'own-fixture-secret-only' });
|
||||
assert.equal(report.complete, true); assert.equal(report.semanticProof, false);
|
||||
assert.deepEqual(report.snapshotBracket, { routeByteEqual: true, nexthopByteEqual: true });
|
||||
assert.deepEqual(seen, PATHS.map(resource => '/rest' + resource));
|
||||
for (const record of report.records) {
|
||||
const body = await readFile(output + '/' + record.file);
|
||||
@@ -41,22 +38,10 @@ test('full own fixture saves nine exact immutable captures and metadata; reflect
|
||||
await assert.rejects(acquire(makeConfig(output), { username: 'own-fixture', password: 'own-fixture-secret-only' }));
|
||||
assert.equal(seen.length, 9);
|
||||
await assert.rejects(privateDirectory('../outside-tmp'));
|
||||
for (const resource of ['route', 'nexthop']) {
|
||||
seen.length = 0;
|
||||
driftingResource = '/rest/routing/' + resource;
|
||||
const driftOutput = output + '-' + resource;
|
||||
const drift = await acquire(makeConfig(driftOutput), { username: 'own-fixture', password: 'own-fixture-secret-only' });
|
||||
assert.equal(drift.complete, true);
|
||||
assert.equal(drift.semanticProof, false);
|
||||
assert.deepEqual(drift.snapshotBracket, { routeByteEqual: resource !== 'route', nexthopByteEqual: resource !== 'nexthop' });
|
||||
assert.equal(drift.records.length, 9);
|
||||
assert.deepEqual(JSON.parse(await readFile(driftOutput + '/report.json', 'utf8')).snapshotBracket, drift.snapshotBracket);
|
||||
}
|
||||
reflect = true;
|
||||
const failedOutput = output + '-failed';
|
||||
const failed = await acquire(makeConfig(failedOutput), { username: 'own-fixture', password: 'own-fixture-secret-only' });
|
||||
assert.equal(failed.complete, false); assert.equal(failed.records.length, 0);
|
||||
assert.equal(failed.snapshotBracket, null);
|
||||
assert.equal(failed.failedResource, '/system/resource'); assert.equal(failed.failedHttpStatus, 401);
|
||||
assert.deepEqual((await readdir(failedOutput)).sort(), ['capture.claim', 'report.json']);
|
||||
assert(!String(await readFile(failedOutput + '/report.json')).includes('own-fixture-secret-only'));
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
import { execFileSync } from "node:child_process"
|
||||
import { homedir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
|
||||
export const hosts = ["194.226.121.150", "104.165.244.7"] as const
|
||||
const key = join(homedir(), ".ssh", "chr_claude")
|
||||
const known = process.env.MMAPP_IX_TEST_KNOWN_HOSTS ?? join(homedir(), ".ssh", "known_hosts")
|
||||
|
||||
export const quote = (value: string) => '"' + value.replace(/[\\"$]/g, "\\$&").replace(/\n/g, "\\n") + '"'
|
||||
export const sshOptions = ["-F", process.platform === "win32" ? "NUL" : "/dev/null", "-i", key,
|
||||
"-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", "-o", "UserKnownHostsFile=" + known,
|
||||
"-o", "ConnectTimeout=12", "-o", "LogLevel=ERROR"]
|
||||
|
||||
export function cli(side: number, expression: string, stage?: string) {
|
||||
const args = [...sshOptions, "claude@" + hosts[side],
|
||||
`:onerror err in={ ${expression.replace(/\r?\n\s*/g, " ")}; :put "IX_OK" } do={ :put ("IX_ERROR:" . $err) }`]
|
||||
const run = () => execFileSync("ssh", args, { encoding: "utf8", timeout: 35000, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }).trim()
|
||||
let stdout: string
|
||||
try {
|
||||
for (let attempt = 0;; attempt++) {
|
||||
try { stdout = run(); break } catch (error) {
|
||||
// Retry only when the command could not have reached the router.
|
||||
const failure = error as { status?: number; stderr?: string; stdout?: string }
|
||||
if (attempt >= 2 || failure.status !== 255 || failure.stdout || !/^ssh: connect to host .* port 22: Connection timed out\s*$/i.test(failure.stderr ?? "")) throw error
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (stage) throw Error(`CHR ${side + 1}: SSH failed during ${stage}`)
|
||||
throw error
|
||||
}
|
||||
if (!stdout.split(/\r?\n/).includes("IX_OK") || stdout.includes("IX_ERROR") || /syntax error|expected end|expected closing/.test(stdout)) {
|
||||
const diagnostic = stdout.replace(/[a-f0-9]{36,}/gi, "[redacted]").slice(0, 420)
|
||||
throw Error(`CHR ${side + 1} rejected ${stage ?? expression.slice(0, 360)} · ${diagnostic}`)
|
||||
}
|
||||
return stdout.replace(/\r?\n?IX_OK$/, "").trim()
|
||||
}
|
||||
@@ -1,264 +0,0 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomBytes, randomUUID, X509Certificate } from "node:crypto"
|
||||
import { mkdtemp } from "node:fs/promises"
|
||||
import { createServer, isIPv4 } from "node:net"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
import { getCACertificates, setDefaultCACertificates } from "node:tls"
|
||||
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"
|
||||
import EmbeddedPostgres from "embedded-postgres"
|
||||
import { SignJWT } from "jose"
|
||||
import { ixNamespace } from "../../src/services/internet-exchange-plan.js"
|
||||
import { cli, hosts, quote } from "./ix-chr-ssh.mjs"
|
||||
|
||||
assert.deepEqual(process.argv.slice(2), ["--owned-test-pair"])
|
||||
for (const name of Object.keys(process.env)) {
|
||||
if (/^(DATABASE_|MCP_|AUTH_|PG|MMAPP_)/.test(name)) delete process.env[name]
|
||||
}
|
||||
process.env.DOTENV_CONFIG_PATH = join(tmpdir(), "mmapp-ix-no-env-" + randomUUID())
|
||||
|
||||
const id = randomUUID(), ns = ixNamespace(id), short = ns.slice(0, 12)
|
||||
const segment = short + "-gre", gre = short + "-gre", pin = (side: number) => "10.245.0." + (1 + side)
|
||||
const psk = randomBytes(32).toString("hex"), password = randomBytes(24).toString("hex")
|
||||
const roots = getCACertificates("default")
|
||||
const certificates: string[] = []
|
||||
const entered = new Map<number, string>()
|
||||
const result: Record<string, unknown> = {}
|
||||
let appliedNamespace: string | undefined
|
||||
const ipsecPaths = ["/ip/ipsec/policy", "/ip/ipsec/identity", "/ip/ipsec/peer", "/ip/ipsec/proposal", "/ip/ipsec/profile"]
|
||||
const ixPaths = ["/ip/route", "/ip/address", "/ip/firewall/filter", "/ipv6/firewall/filter", "/ip/vrf", "/interface/bridge"]
|
||||
const sides = [0, 1]
|
||||
|
||||
function baseline(side: number) {
|
||||
return cli(side, `:put [/system resource get version]; :put [/system resource get board-name];
|
||||
:put [/ip/service/print as-value proplist=disabled,port,certificate,address where name=www-ssl and dynamic=no];
|
||||
:put [:len [/interface/gre/find]]; :put [:len [/ip/vrf/find]];
|
||||
:put [:len [/ip/ipsec/peer/find]]; :put [:len [/ip/ipsec/installed-sa/find]];
|
||||
:put [:len [/ip/firewall/filter/find]]; :put [:len [/ipv6/firewall/filter/find]];
|
||||
:put [:len [/ip/address/find where address~${quote("^" + hosts[side] + "/")}]]`)
|
||||
}
|
||||
|
||||
async function port() {
|
||||
const socket = createServer()
|
||||
await new Promise<void>((ok, fail) => socket.listen(0, "127.0.0.1", ok).on("error", fail))
|
||||
const value = (socket.address() as { port: number }).port
|
||||
await new Promise<void>((ok, fail) => socket.close(error => error ? fail(error) : ok()))
|
||||
return value
|
||||
}
|
||||
|
||||
async function until<T>(label: string, check: () => T | Promise<T>, timeout = 45000) {
|
||||
const end = Date.now() + timeout
|
||||
do {
|
||||
const value = await check()
|
||||
if (value) return value
|
||||
await delay(900)
|
||||
} while (Date.now() < end)
|
||||
throw Error(label + " timed out")
|
||||
}
|
||||
|
||||
function prepareGre(side: number) {
|
||||
const local = hosts[side], remote = hosts[1 - side]
|
||||
const p = quote(short)
|
||||
cli(side, `:put "profile"; /ip/ipsec/profile/add name=${p} enc-algorithm=aes-256 hash-algorithm=sha256 dh-group=modp2048;
|
||||
:put "proposal"; /ip/ipsec/proposal/add name=${p} enc-algorithms=aes-256-cbc auth-algorithms=sha256 pfs-group=modp2048;
|
||||
:put "peer"; /ip/ipsec/peer/add name=${p} address=${remote}/32 local-address=${local} profile=${p} exchange-mode=ike2 passive=${side ? "yes" : "no"};
|
||||
:put "identity"; /ip/ipsec/identity/add peer=${p} auth-method=pre-shared-key secret=${quote(psk)} comment=${p};
|
||||
:put "policy"; /ip/ipsec/policy/add peer=${p} src-address=${local}/32 dst-address=${remote}/32 protocol=gre action=encrypt level=require tunnel=no proposal=${p} comment=${p};
|
||||
:put "GRE"; /interface/gre/add name=${quote(gre)} local-address=${local} remote-address=${remote} allow-fast-path=no comment=${quote("IX:" + segment)};
|
||||
/ip/address/add address=${pin(side)}/30 interface=${quote(gre)} comment=${quote(ns + ":lab:gre")}`, "isolated IKEv2/GRE setup")
|
||||
}
|
||||
|
||||
async function openRest(side: number) {
|
||||
const sessions = cli(side, ':put [/user/active/print as-value proplist=address where name=claude and via=ssh]')
|
||||
const sources = [...new Set([...sessions.matchAll(/address=([\d.]+)/g)].map(match => match[1]))]
|
||||
assert(sources.length === 1 && isIPv4(sources[0]), "Cannot pin HTTPS to a single observed management address")
|
||||
const source = sources[0] + "/32", host = hosts[side], ca = short + "-ca", leaf = short + "-tls"
|
||||
cli(side, `/certificate/add name=${quote(ca)} common-name=${quote(ca)} key-usage=key-cert-sign,crl-sign days-valid=1;
|
||||
/certificate/sign [find where name=${quote(ca)}];
|
||||
/certificate/add name=${quote(leaf)} common-name=${quote(host)} subject-alt-name=IP:${host} key-usage=tls-server days-valid=1;
|
||||
/certificate/sign [find where name=${quote(leaf)}] ca=${quote(ca)};
|
||||
/certificate/export-certificate [find where name=${quote(ca)}] file-name=${quote(ca)}`)
|
||||
const certificate = cli(side, `:put [/file/get [find where name=${quote(ca + ".crt")}] contents]`)
|
||||
assert.equal(new X509Certificate(certificate).ca, true)
|
||||
certificates.push(certificate)
|
||||
setDefaultCACertificates([...roots, ...certificates])
|
||||
cli(side, `/ip/firewall/filter/add chain=input action=drop protocol=tcp dst-port=443 dst-address=${host}/32 src-address=!${source} comment=${quote(ns + ":lab:tls")};
|
||||
/user/group/add name=${quote(short)} policy=read,write,api,rest-api;
|
||||
/user/add name=${quote(short)} address=${source} group=${quote(short)} password=${quote(password)};
|
||||
/ip/service/set [find where name=www-ssl and dynamic=no] address=${source} certificate=${quote(leaf)} disabled=no`, "restricted HTTPS REST setup")
|
||||
let lastError = ""
|
||||
await until("router REST on verified HTTPS", async () => {
|
||||
const response = await fetch(`https://${host}/rest/system/resource`, {
|
||||
headers: { authorization: "Basic " + Buffer.from(short + ":" + password).toString("base64") }, signal: AbortSignal.timeout(5000),
|
||||
}).catch(error => { lastError = String(error.cause ?? error); return undefined })
|
||||
if (!response) return false
|
||||
assert.equal(response.status, 200, "REST test user was refused")
|
||||
assert.equal((await response.json()).version, "7.24.5 (stable)")
|
||||
return true
|
||||
}, 18000).catch(error => { throw Error(`CHR ${side + 1}: ${error.message} · ${lastError}`) })
|
||||
}
|
||||
|
||||
function clean(side: number, before: string) {
|
||||
const own = `where comment~${quote(appliedNamespace ? `^(${ns}|${appliedNamespace}):` : "^" + ns + ":")}`
|
||||
const checks = ixPaths.map(path => `[:len [${path}/find ${own}]]`)
|
||||
cli(side, `/ip/service/set [find where name=www-ssl and dynamic=no] disabled=yes address="" certificate=none;
|
||||
/user/remove [/user/find where name=${quote(short)}]; /user/group/remove [/user/group/find where name=${quote(short)}];
|
||||
/file/remove [/file/find where name=${quote(short + "-ca.crt")}];
|
||||
/certificate/remove [/certificate/find where name=${quote(short + "-tls")}];
|
||||
/certificate/remove [/certificate/find where name=${quote(short + "-ca")}];
|
||||
${ixPaths.map(path => `${path}/remove [${path}/find ${own}]`).join("; ")};
|
||||
/interface/gre/remove [/interface/gre/find where name=${quote(gre)} and comment=${quote("IX:" + segment)}];
|
||||
${ipsecPaths.map((path, i) => `${path}/remove [${path}/find where ${i < 2 ? "comment" : "name"}=${quote(short)}]`).join("; ")}`)
|
||||
checks.push(...ipsecPaths.map((path, i) => `[:len [${path}/find where ${i < 2 ? "comment" : "name"}=${quote(short)}]]`),
|
||||
`[:len [/user/find where name=${quote(short)}]]`, `[:len [/user/group/find where name=${quote(short)}]]`,
|
||||
`[:len [/certificate/find where name~${quote("^" + short + "-(ca|tls)$")}]]`, `[:len [/file/find where name=${quote(short + "-ca.crt")}]]`)
|
||||
assert.equal(cli(side, ":put (" + checks.join("+") + ")"), "0")
|
||||
assert.equal(baseline(side), before)
|
||||
}
|
||||
|
||||
async function useManager() {
|
||||
const root = await mkdtemp(join(tmpdir(), "mmapp-ix-mcp-"))
|
||||
process.chdir(root)
|
||||
const pgPort = await port(), httpPort = await port()
|
||||
const origin = `http://127.0.0.1:${httpPort}`, endpoint = new URL("/mcp", origin)
|
||||
const pgPassword = randomBytes(24).toString("hex"), jwtSecret = randomBytes(32).toString("hex")
|
||||
Object.assign(process.env, { DATABASE_URL: `postgresql://ixlab:${pgPassword}@127.0.0.1:${pgPort}/postgres`,
|
||||
NODE_ENV: "test", AUTH_REQUIRED: "true", AUTH_JWT_SECRET: jwtSecret, AUTH_ISSUER: origin,
|
||||
AUTH_PORTAL_URL: origin, MCP_STATE_DIR: join(root, "state"), MCP_PUBLIC_URL: endpoint.href, MCP_UI_URL: origin, CORS_ORIGIN: origin })
|
||||
const pg = new EmbeddedPostgres({ databaseDir: join(root, "db"), user: "ixlab", password: pgPassword, port: pgPort,
|
||||
persistent: false, createPostgresUser: false, initdbFlags: ["--encoding=UTF8", "--no-locale"], postgresFlags: ["-h", "127.0.0.1"],
|
||||
onLog: () => {}, onError: () => {} })
|
||||
await pg.initialise()
|
||||
await pg.start()
|
||||
const { pool, closePool } = await import("../../src/db/index.js")
|
||||
const { applySqlMigrations } = await import("../../src/db/migrate.js")
|
||||
const { buildApp } = await import("../../src/index.js")
|
||||
const { updateMcpSettings } = await import("../../src/modules/mcp/store.js")
|
||||
let app: Awaited<ReturnType<typeof buildApp>> | undefined
|
||||
const client = new Client({ name: "owned-ix-gre", version: "1.0.0" })
|
||||
try {
|
||||
await applySqlMigrations(pool)
|
||||
const serverIds: number[] = []
|
||||
for (const [side, host] of hosts.entries()) {
|
||||
const { rows } = await pool.query(`INSERT INTO servers(name,host,port,username,password,use_ssl,verify_ssl,enabled,type)
|
||||
VALUES($1,$2,443,$3,$4,true,true,true,'ix-node') RETURNING id`, [`ix-chr-${side + 1}`, host, short, password])
|
||||
serverIds.push(Number(rows[0].id))
|
||||
}
|
||||
const permissions = ["mm:network:read", "mm:network:write", "mm:mcp:admin", "mm:mcp:approve"]
|
||||
const actor = { id: "ix-fixture", email: "[email protected]", name: "IX fixture", apps: ["mm"], permissions,
|
||||
expiresAt: Date.now() + 1800000, issuedAt: Date.now() }
|
||||
await updateMcpSettings({ enabled: true }, actor)
|
||||
app = await buildApp({ startScheduler: false, logger: false })
|
||||
await app.listen({ port: httpPort, host: "127.0.0.1" })
|
||||
const jwt = await new SignJWT({ sub: actor.id, apps: actor.apps, permissions }).setProtectedHeader({ alg: "HS256" })
|
||||
.setIssuer(origin).setIssuedAt().setExpirationTime("15m").sign(new TextEncoder().encode(jwtSecret))
|
||||
async function rest(path: string, data?: object) {
|
||||
const response = await fetch(origin + "/api" + path, { method: data ? "POST" : "GET",
|
||||
headers: { authorization: "Bearer " + jwt, "content-type": "application/json" },
|
||||
...(data ? { body: JSON.stringify(data) } : {}), signal: AbortSignal.timeout(15000) })
|
||||
const body = await response.json()
|
||||
assert(response.ok, `${path}: ${response.status} ${JSON.stringify(body).slice(0, 600)}`)
|
||||
return body
|
||||
}
|
||||
const configuration = { name: segment, sites: serverIds.map((serverId, side) => ({
|
||||
serverId, routerId: pin(side), autonomousSystem: 64512 + side,
|
||||
interfaces: [{ name: gre, kind: "gre-ipsec", localEndpoint: hosts[side], endpoint: hosts[1 - side], peerServerId: serverIds[1 - side] }],
|
||||
})) }
|
||||
const draft = await rest("/ix/segments", { revision: 0, configuration })
|
||||
const segmentId: string = draft.segment.id
|
||||
assert.match(segmentId, /^[0-9a-f-]{36}$/)
|
||||
appliedNamespace = ixNamespace(segmentId)
|
||||
assert.equal(draft.segment.revision, 1)
|
||||
assert.equal(draft.segment.appliedRevision, null)
|
||||
result.managerRestDraft = true
|
||||
const { token } = await rest("/mcp/connections", { name: "Owned IX approval", mode: "approval", permissions: ["mm:network:read", "mm:network:write"],
|
||||
limits: { mutationsPerHour: 40, callsPerMinute: 120 },
|
||||
expiresAt: new Date(Date.now() + 600000).toISOString(), scope: { serverIds, allowGlobal: false,
|
||||
operationIds: ["network.ix.configure", "network.ix.read", "changes.apply", "operations.read"] } })
|
||||
await client.connect(new StreamableHTTPClientTransport(endpoint, {
|
||||
requestInit: { headers: { authorization: "Bearer " + token } },
|
||||
}), { timeout: 10000 })
|
||||
async function call(name: string, args: object, expectedError = false) {
|
||||
const reply = await client.callTool({ name, arguments: args }, undefined, { timeout: 120000 })
|
||||
assert.equal(Boolean(reply.isError), expectedError, name + " " + JSON.stringify(reply.structuredContent ?? reply.content).slice(0, 1200))
|
||||
return (reply.structuredContent as { result: any })?.result
|
||||
}
|
||||
const plan = await call("mm_ix_change_plan", { change: { id: segmentId, revision: 1, configuration } })
|
||||
assert.equal(plan.state, "awaiting-approval")
|
||||
const apply = { planId: plan.planId, idempotencyKey: randomUUID() }
|
||||
await call("mm_change_apply", apply, true)
|
||||
await rest("/mcp/plans/" + plan.planId + "/decision", { approve: true })
|
||||
const op = await call("mm_change_apply", apply)
|
||||
const terminal = await until("MCP terminal operation", async () => {
|
||||
const value = await call("mm_operation_get", { operationId: op.id })
|
||||
return !["pending", "running"].includes(value.state) && value
|
||||
}, 90000)
|
||||
assert.equal(terminal.state, "applied", JSON.stringify({ state: terminal.state, error: terminal.error_code }))
|
||||
assert.equal(terminal.verification, "passed")
|
||||
assert.equal((await call("mm_change_apply", apply)).id, op.id)
|
||||
const verified = await call("mm_ix_segment_get", { id: segmentId })
|
||||
assert.equal(verified.segment.appliedRevision, 2)
|
||||
const status = await rest("/ix/segments/" + segmentId + "/status")
|
||||
assert.deepEqual(status.sites.map(({ serverId, available }: { serverId: number; available: boolean }) => [serverId, available]),
|
||||
serverIds.map(serverId => [serverId, true]))
|
||||
result.mcpAppliedAndVerified = true
|
||||
result.routerRestSites = status.sites.length
|
||||
} finally {
|
||||
await client.close()
|
||||
await app?.close()
|
||||
await closePool()
|
||||
await pg.stop()
|
||||
}
|
||||
}
|
||||
|
||||
function packets(side: number) {
|
||||
assert(appliedNamespace)
|
||||
return Number(cli(side, `:put [/ping address=${pin(1 - side)} src-address=${pin(side)} vrf=${appliedNamespace} count=3 interval=250ms]`).split(/\r?\n/).at(-1))
|
||||
}
|
||||
|
||||
let failure: unknown
|
||||
try {
|
||||
const original = sides.map(baseline)
|
||||
for (const value of original) {
|
||||
const [version, board, ...expected] = value.split(/\r?\n/)
|
||||
assert.equal(version, "7.24.5 (stable)")
|
||||
assert.match(board, /^CHR/)
|
||||
const [https, ...inventory] = expected
|
||||
assert.match(https, /(?:^|;)certificate=none;disabled=true;port=443$/)
|
||||
assert.deepEqual(inventory, ["0", "1", "0", "0", "0", "0", "1"])
|
||||
}
|
||||
for (const side of sides) {
|
||||
entered.set(side, original[side])
|
||||
prepareGre(side)
|
||||
}
|
||||
for (const side of sides) await openRest(side)
|
||||
console.log("Both RouterOS REST endpoints authenticated with temporary trusted HTTPS certificates")
|
||||
await useManager()
|
||||
console.log("MCP applied the reviewed configuration to both routers")
|
||||
await until("encrypted GRE forwarding", () => packets(0) === 3 && packets(1) === 3)
|
||||
const sas = sides.map(side => Number(cli(side, ":put [:len [/ip/ipsec/installed-sa/find where state=mature]]")))
|
||||
assert(sas.every(count => count === 2))
|
||||
result.greReplies = [3, 3]
|
||||
result.matureIpsecSAs = sas
|
||||
// Turn off both matching policies during the plaintext negative test.
|
||||
for (const side of sides) cli(side, `/ip/ipsec/policy/disable [/ip/ipsec/policy/find where comment=${quote(short)}]`)
|
||||
for (const side of sides) assert.equal(packets(side), 0)
|
||||
result.plaintextGreBlocked = true
|
||||
for (const side of sides) cli(side, `/ip/ipsec/policy/enable [/ip/ipsec/policy/find where comment=${quote(short)}]`)
|
||||
await until("GRE recovery with required IPsec", () => packets(0) === 3 && packets(1) === 3)
|
||||
result.greRecovered = true
|
||||
} catch (error) {
|
||||
failure = error
|
||||
}
|
||||
setDefaultCACertificates(roots)
|
||||
let testStandRestored = true
|
||||
for (const [side, original] of entered) {
|
||||
try { clean(side, original) } catch (error) {
|
||||
console.error(`Cleanup unconfirmed on CHR ${side + 1} · ${ns} ${appliedNamespace ?? ""}`)
|
||||
testStandRestored = false
|
||||
failure ??= error
|
||||
}
|
||||
}
|
||||
console.log(JSON.stringify({ ...result, testStandRestored }))
|
||||
if (failure) throw failure
|
||||
@@ -1,198 +0,0 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomInt, randomUUID } from "node:crypto"
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
import { ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
|
||||
import { compileIxConfiguration, ixDiscardInterface, ixNamespace } from "../../src/services/internet-exchange-plan.js"
|
||||
import { cli, hosts, quote } from "./ix-chr-ssh.mjs"
|
||||
|
||||
assert.equal(process.argv[2], "--owned-test-pair")
|
||||
assert(process.argv.length === 3 || (process.argv.length === 4 && process.argv[3] === "--ipv6"))
|
||||
const ipv6 = process.argv[3] === "--ipv6"
|
||||
const id = randomUUID(), ns = ixNamespace(id), short = ns.slice(0, 10)
|
||||
const discard = ixDiscardInterface(id)
|
||||
const marker = ns + ":lab", primary = short + "-p", backup = short + "-b"
|
||||
const port = randomInt(45000, 55000)
|
||||
const net = "10.247." + randomInt(32, 224)
|
||||
const [aP, bP, aB, bB] = ipv6 ? ["fd00:247:1::1", "fd00:247:1::2", "fd00:247:2::1", "fd00:247:2::2"] : [1, 2, 5, 6].map(n => net + "." + n)
|
||||
const [target, pProbe, bProbe, trafficSource] = ipv6 ? ["2001:db8:3::200", "2001:db8:3::201", "2001:db8:3::202", "2001:db8:3::203"] : ["192.0.2.200", "192.0.2.201", "192.0.2.202", "192.0.2.203"]
|
||||
const afi = ipv6 ? "ipv6" : "ip", length = ipv6 ? "/128" : "/32", gateway = ipv6 ? "fd00:198:18::101" : "198.18.0.101"
|
||||
const addressPath = "/" + afi + "/address", routePath = "/" + afi + "/route", filterPath = "/" + afi + "/firewall/filter", listPath = "/" + afi + "/firewall/address-list"
|
||||
const advertise: Record<string, string> = ipv6 ? { advertise: "no" } : {}
|
||||
const community = "65000:120"
|
||||
const entered = new Set<number>()
|
||||
const results: Record<string, unknown> = {}
|
||||
const pending: string[][] = [[], []]
|
||||
|
||||
const fields = (values: Record<string, string>) => Object.entries(values).map(([name, value]) => name === "blackhole" && value === "yes" ? name : name + "=" + quote(value)).join(" ")
|
||||
function add(side: number, path: string, values: Record<string, string>, beforeMain = false) {
|
||||
pending[side].push(path + " add " + fields(values) + (beforeMain ? " place-before=[/ip/vrf/find where name=main]" : ""))
|
||||
}
|
||||
function flush(side: number) {
|
||||
while (pending[side].length) {
|
||||
const commands = pending[side].splice(0, 10)
|
||||
cli(side, commands.map((command, index) => `:put "IX_STAGE_${index}"; ${command}`).join("; "))
|
||||
}
|
||||
}
|
||||
function owned(side: number, path: string, values: Record<string, string>, tag: string) {
|
||||
add(side, path, { ...values, comment: marker + ":" + tag })
|
||||
}
|
||||
function preflight(side: number) {
|
||||
const data = cli(side, `:put [/system resource get version]; :put [/system resource get board-name];
|
||||
:put ([:len [/ip/vrf/find]]=1 && [:len [/interface/wireguard/find]]=0 && [:len [/routing/bgp/connection/find]]=0 && [:len [/ip/firewall/filter/find]]=0 && [:len [/ipv6/firewall/filter/find]]=0);
|
||||
:put [:len [/ip/address/find where address~${quote("^" + hosts[side] + "/")}]]`)
|
||||
const [version, board, empty, address] = data.split(/\r?\n/)
|
||||
assert.equal(version, "7.24.5 (stable)")
|
||||
assert.match(board, /^CHR/)
|
||||
assert.equal(empty, "true", "Stand changed, refusing a modified baseline")
|
||||
assert.equal(address, "1", "Expected test WAN address missing")
|
||||
}
|
||||
|
||||
const config = ixSegmentConfigurationSchema.parse({
|
||||
name: "ix-acceptance",
|
||||
sites: [
|
||||
{ serverId: 501, autonomousSystem: 64512, routerId: net + ".5",
|
||||
interfaces: [{ name: primary, kind: "wireguard", peerServerId: 502 }, { name: backup, kind: "wireguard", peerServerId: 502 }],
|
||||
groups: [{ id: "far", gateway, primary: { interface: primary, nextHop: bP, probe: pProbe },
|
||||
backup: { interface: backup, nextHop: bB, probe: bProbe } }],
|
||||
neighbors: [{ id: "feed", type: "public-feed", address: bB, localAddress: aB, remoteAs: 64513, binding: backup, rules: [{ community, group: "far" }] }],
|
||||
},
|
||||
{ serverId: 502, autonomousSystem: 64513, routerId: net + ".6",
|
||||
interfaces: [{ name: primary, kind: "wireguard", peerServerId: 501 }, { name: backup, kind: "wireguard", peerServerId: 501 }] },
|
||||
],
|
||||
})
|
||||
const compiled = compileIxConfiguration(id, config)
|
||||
const deferred = new Set([routePath, "/routing/bgp/instance", "/routing/filter/rule", "/routing/bgp/connection"])
|
||||
const cleanupPaths = [...deferred].reverse().concat(listPath,
|
||||
"/interface/wireguard/peers", addressPath, "/ip/firewall/filter", "/ipv6/firewall/filter", "/ip/vrf", "/interface/bridge", "/interface/wireguard")
|
||||
|
||||
function clean(side: number) {
|
||||
const where = `where comment~${quote("^" + ns + ":")}`
|
||||
cli(side, cleanupPaths.map(path => `${path} remove [${path}/find ${where}]`).join("; "))
|
||||
assert.equal(cli(side, `:put (${cleanupPaths.map(path => `[:len [${path}/find ${where}]]`).join("+")})`), "0")
|
||||
preflight(side)
|
||||
}
|
||||
|
||||
function observe() {
|
||||
return cli(0, `:put [/routing/route/print as-value where dst-address=${quote(target + length)} and routing-table=${quote(ns)}]`)
|
||||
}
|
||||
async function until(label: string, check: () => boolean, timeout = 75000) {
|
||||
const start = Date.now()
|
||||
while (!check()) {
|
||||
if (Date.now() - start > timeout) throw new Error(label + " timeout: " + observe())
|
||||
await delay(900)
|
||||
}
|
||||
return Date.now() - start
|
||||
}
|
||||
function hasPath(name: string) {
|
||||
const fields = observe().split(";")
|
||||
return fields.includes("bgp=true") && fields.includes("active=true") && fields.some(field => field.startsWith("immediate-gw=") && field.endsWith("%" + name))
|
||||
}
|
||||
function establishedSession() {
|
||||
const session = cli(0, `:put [/routing/bgp/session/print as-value where name~${quote(ns + "-feed")}]`).split(";")
|
||||
assert.ok(session.includes("established=true"))
|
||||
assert.ok(session.includes("prefix-count=1"))
|
||||
const started = session.find(field => field.startsWith("last-started="))
|
||||
assert.ok(started)
|
||||
return started
|
||||
}
|
||||
function packetProbe(destination: string, source?: string, side = 0, routingTable = ns) {
|
||||
return Number(cli(side, `:put [/ping address=${destination} vrf=${routingTable} count=3 interval=250ms${source ? " src-address=" + source : ""}]`).split(/\r?\n/).at(-1))
|
||||
}
|
||||
|
||||
async function run() {
|
||||
preflight(0); preflight(1)
|
||||
for (let side = 0; side < 2; side++) {
|
||||
entered.add(side)
|
||||
for (const [index, name] of [primary, backup].entries()) owned(side, "/interface/wireguard", { name, "listen-port": String(port + index), vrf: "main" }, "wg" + index)
|
||||
for (const object of compiled.filter(object => object.serverId === 501 + side && !deferred.has(object.path))) {
|
||||
add(side, object.path, object.fields, object.path === "/ip/vrf")
|
||||
if (object.path === "/ip/vrf") {
|
||||
flush(side)
|
||||
await until("VRF interface", () => cli(side, `:put [:len [/interface/find where name=${quote(ns)}]]`) === "1", 9000)
|
||||
}
|
||||
}
|
||||
for (const [index, name] of [primary, backup].entries()) {
|
||||
owned(side, "/ip/firewall/filter", { chain: "input", action: "accept", protocol: "udp", "src-address": hosts[1 - side] + "/32", "dst-port": String(port + index) }, "allow-wg" + index)
|
||||
const inner = (side ? [bP, bB] : [aP, aB])[index]
|
||||
owned(side, addressPath, { address: inner + (ipv6 ? "/64" : "/30"), interface: name, ...advertise }, "address" + index)
|
||||
}
|
||||
flush(side)
|
||||
}
|
||||
for (const [index, name] of [primary, backup].entries()) {
|
||||
const keys = [0, 1].map(side => cli(side, `:put [/interface/wireguard/get [/interface/wireguard/find where name=${quote(name)}] public-key]`))
|
||||
keys.forEach(value => assert.match(value, /^[A-Za-z0-9+/]{43}=$/))
|
||||
for (const side of [0, 1]) owned(side, "/interface/wireguard/peers", { interface: name, "public-key": keys[1 - side], "endpoint-address": hosts[1 - side],
|
||||
"endpoint-port": String(port + index), "allowed-address": (side
|
||||
? [index ? aB : aP, trafficSource]
|
||||
: [index ? bB : bP, target, index ? bProbe : pProbe]).map(address => address + length).join(","),
|
||||
"persistent-keepalive": "5" }, "peer" + index)
|
||||
}
|
||||
for (const [index, address] of [target, pProbe, bProbe].entries()) {
|
||||
owned(1, addressPath, { address: address + length, interface: discard, ...advertise }, "destination" + index)
|
||||
}
|
||||
owned(0, addressPath, { address: trafficSource + length, interface: discard, ...advertise }, "source")
|
||||
// Keep the same source and return path across both forward paths.
|
||||
owned(1, routePath, { "dst-address": trafficSource + length, "routing-table": ns,
|
||||
gateway: aB + "%" + backup + "@" + ns, "target-scope": "10" }, "return")
|
||||
const control = { chain: "input", "in-interface": ns, protocol: "tcp", "src-address": aB + length, action: "accept" }
|
||||
const beforeDeny = " place-before=[" + filterPath + "/find where comment=" + quote(ns + ":deny-input-" + (ipv6 ? "6" : "4")) + "]"
|
||||
cli(1, [fields({ ...control, "dst-port": "179", comment: marker + ":bgp-accept" }),
|
||||
fields({ ...control, "src-port": "179", "connection-state": "established", comment: marker + ":bgp-reply" })]
|
||||
.map(rule => filterPath + " add " + rule + beforeDeny).join("; "))
|
||||
owned(1, listPath, { list: short + "-net", address: target + length }, "network")
|
||||
owned(1, "/routing/bgp/instance", { name: ns, as: "64513", "router-id": net + ".6", vrf: ns, "routing-table": ns }, "instance")
|
||||
owned(1, "/routing/filter/rule", { chain: short + "-out", rule: `if (dst == ${target}${length}) { set bgp-communities ${community}; accept; } reject;` }, "export")
|
||||
owned(1, "/routing/bgp/connection", { name: short + "-export", instance: ns, afi, "local.role": "ebgp", "local.address": bB,
|
||||
"remote.address": aB + length, "remote.as": "64512", vrf: ns, "routing-table": ns, "output.network": short + "-net", "output.filter-chain": short + "-out" }, "connection")
|
||||
for (const object of compiled.filter(object => object.serverId === 501 && deferred.has(object.path))) add(0, object.path, object.fields)
|
||||
flush(1); flush(0)
|
||||
await until("primary WireGuard transport", () => packetProbe(bP, aP) === 3, 40000)
|
||||
await until("backup WireGuard transport", () => packetProbe(bB, aB) === 3, 40000)
|
||||
await until("BGP primary route", () => hasPath(primary))
|
||||
const session = establishedSession()
|
||||
results.bgpEstablished = true
|
||||
results.primaryRoute = observe()
|
||||
results.primaryReplies = packetProbe(target, trafficSource)
|
||||
assert.equal(results.primaryReplies, 3)
|
||||
assert.equal(cli(0, `:put [:len [/routing/route/find where dst-address=${quote(target + length)} and routing-table=main]]`), "0", "BGP prefix must not leak to main")
|
||||
results.mainIsolated = true
|
||||
|
||||
// Drop only A's test UDP flow on the remote end. Interfaces remain enabled,
|
||||
// so this exercises probe-driven failover rather than administrative down.
|
||||
cli(1, "/ip/firewall/filter add " + fields({ chain: "input", action: "drop", protocol: "udp", "src-address": hosts[0] + "/32",
|
||||
"dst-port": String(port), comment: marker + ":cut" }) + " place-before=[/ip/firewall/filter/find where comment=" + quote(marker + ":allow-wg0") + "]")
|
||||
results.failoverMs = await until("primary underlay loss", () => hasPath(backup))
|
||||
results.backupRoute = observe()
|
||||
results.backupReplies = packetProbe(target, trafficSource)
|
||||
assert.equal(results.backupReplies, 3)
|
||||
assert.equal(establishedSession(), session)
|
||||
cli(1, "/ip/firewall/filter remove [/ip/firewall/filter/find where comment=" + quote(marker + ":cut") + "]")
|
||||
results.failbackMs = await until("primary recovery", () => hasPath(primary))
|
||||
results.recoveredReplies = packetProbe(target, trafficSource)
|
||||
assert.equal(results.recoveredReplies, 3)
|
||||
assert.equal(establishedSession(), session)
|
||||
results.bgpSessionKept = true
|
||||
}
|
||||
|
||||
let failure: unknown
|
||||
try { await run() } catch (error) {
|
||||
failure = error
|
||||
for (const side of entered) try {
|
||||
console.error(`Test CHR ${side + 1} · ${cli(side, `:put [/routing/bgp/session/print as-value];
|
||||
:put [/interface/wireguard/peers/print as-value proplist=interface,rx,tx,last-handshake,current-endpoint-address where comment~${quote("^" + ns + ":")}];
|
||||
${filterPath}/print stats where comment~${quote("^" + ns + ":")};
|
||||
:put [${addressPath}/print as-value proplist=address,interface,invalid where comment~${quote("^" + ns + ":")}];
|
||||
:put [/routing/route/print as-value where routing-table=${quote(ns)}]; :put [/routing/nexthop/print as-value where address~${quote(gateway)}]`).slice(0, 8500)}`)
|
||||
} catch { /* Preserve the original failure and continue cleanup. */ }
|
||||
}
|
||||
for (const side of entered) {
|
||||
try { clean(side) } catch (error) {
|
||||
console.error(`Cleanup unconfirmed on test CHR ${side + 1} for ${ns}: ${error}`)
|
||||
failure ??= error
|
||||
}
|
||||
}
|
||||
if (failure) {
|
||||
console.error(JSON.stringify(results))
|
||||
throw failure
|
||||
}
|
||||
console.log(JSON.stringify({ ...results, testStandRestored: true }))
|
||||
@@ -1,171 +0,0 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomBytes, randomUUID } from "node:crypto"
|
||||
import { mkdtemp } from "node:fs/promises"
|
||||
import { createServer } from "node:http"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import EmbeddedPostgres from "embedded-postgres"
|
||||
|
||||
const dir = await mkdtemp(join(tmpdir(), "mm-ix-web-"))
|
||||
const socket = createServer()
|
||||
await new Promise<void>(resolve => socket.listen(0, "127.0.0.1", resolve))
|
||||
const pgPort = (socket.address() as { port: number }).port
|
||||
await new Promise<void>(resolve => socket.close(() => resolve()))
|
||||
const password = randomBytes(24).toString("hex")
|
||||
const pg = new EmbeddedPostgres({ databaseDir: join(dir, "pg"), user: "ixlab", password,
|
||||
port: pgPort, persistent: false, initdbFlags: ["--encoding=UTF8", "--no-locale"], onLog() {} })
|
||||
Object.assign(process.env, {
|
||||
NODE_ENV: "test", DATABASE_URL: `postgres://ixlab:${password}@127.0.0.1:${pgPort}/postgres`,
|
||||
MCP_STATE_DIR: join(dir, "state"), AUTH_REQUIRED: "true", AUTH_JWT_SECRET: randomBytes(32).toString("hex"),
|
||||
DATABASE_PATH: join(dir, "no-legacy.sqlite"),
|
||||
})
|
||||
await pg.initialise()
|
||||
await pg.start()
|
||||
const rows: Record<string, Record<string, string>[]> = {
|
||||
"/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }],
|
||||
"/interface": [{ ".id": "*A0", name: "gre-client", type: "gre", comment: "IX:ix-web-fixture" }],
|
||||
"/interface/gre": [{ ".id": "*A0", name: "gre-client", "local-address": "192.0.2.20", "remote-address": "192.0.2.21", "allow-fast-path": "false" }],
|
||||
"/ip/ipsec/policy": [{ ".id": "*A1", "src-address": "192.0.2.20/32", "dst-address": "192.0.2.21/32",
|
||||
protocol: "gre", action: "encrypt", level: "require", tunnel: "false", disabled: "false" }],
|
||||
}
|
||||
let writes = 0
|
||||
const router = createServer(async (request, response) => {
|
||||
try {
|
||||
const path = new URL(request.url!, "http://127.0.0.1").pathname.replace(/^\/rest/, "")
|
||||
let result: unknown
|
||||
if (request.method === "GET") result = rows[path] ?? []
|
||||
else if (request.method === "PUT") {
|
||||
let raw = ""
|
||||
for await (const chunk of request) raw += chunk
|
||||
const { "place-before": place, ...fields } = JSON.parse(raw)
|
||||
const row = { ...fields, ...(path === "/interface/wireguard" && { "public-key": "B".repeat(43) + "=" }),
|
||||
".id": "*" + (++writes + 1).toString(16).toUpperCase() }
|
||||
const list = rows[path] ??= []
|
||||
const index = list.findIndex(entry => entry[".id"] === place)
|
||||
list.splice(index < 0 ? list.length : index, 0, row)
|
||||
if (path === "/ip/vrf" || path === "/interface/wireguard" || path === "/interface/bridge") {
|
||||
rows["/interface"].push({ ".id": row[".id"], name: row.name,
|
||||
type: path === "/interface/wireguard" ? "wg" : path.split("/").at(-1)!, comment: row.comment })
|
||||
}
|
||||
result = row
|
||||
} else throw Error("Unexpected native verb: " + request.method)
|
||||
response.setHeader("content-type", "application/json")
|
||||
response.end(JSON.stringify(result))
|
||||
} catch (error) {
|
||||
response.statusCode = 500
|
||||
response.end(JSON.stringify({ error: String(error) }))
|
||||
}
|
||||
})
|
||||
const { initDatabase } = await import("../../src/db/bootstrap.js")
|
||||
const { pool } = await import("../../src/db/index.js")
|
||||
let app: Awaited<ReturnType<typeof import("../../src/index.js").buildApp>> | undefined
|
||||
try {
|
||||
await initDatabase()
|
||||
assert.equal((await pool.query("SELECT enabled FROM mcp_settings WHERE id=1")).rows[0].enabled, false)
|
||||
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
|
||||
const port = (router.address() as { port: number }).port
|
||||
const { rows: [server] } = await pool.query(`INSERT INTO servers
|
||||
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
|
||||
VALUES('owned-ix','127.0.0.1',$1,true,'ix-node','synthetic','synthetic',false,true) RETURNING id`, [port])
|
||||
const { buildApp } = await import("../../src/index.js")
|
||||
const { env } = await import("../../src/config.js")
|
||||
app = await buildApp({ logger: false, startScheduler: false })
|
||||
const origin = await app.listen({ host: "127.0.0.1", port: 0 })
|
||||
const token = (owner: string, permission: string) => app!.jwt.sign({ iss: env.authIssuer, sub: owner,
|
||||
apps: ["mm"], permissions: [permission], iat: Math.floor(Date.now() / 1000) - 1, exp: Math.floor(Date.now() / 1000) + 600 })
|
||||
const writer = token("ix-web-owner", "mm:network:write")
|
||||
const reader = token("ix-web-reader", "mm:network:read")
|
||||
const otherWriter = token("ix-web-other-owner", "mm:network:write")
|
||||
async function post(path: string, payload: object, status: number, jwt = writer) {
|
||||
const reply = await fetch(origin + "/api/ix/segments" + path, { method: "POST",
|
||||
headers: { "content-type": "application/json", ...(jwt ? { authorization: "Bearer " + jwt } : {}) },
|
||||
body: JSON.stringify(payload), signal: AbortSignal.timeout(30_000) })
|
||||
const data = await reply.json()
|
||||
assert.equal(reply.status, status, JSON.stringify(data))
|
||||
return data
|
||||
}
|
||||
const configuration = { name: "ix-web-fixture", sites: [{ serverId: Number(server.id),
|
||||
autonomousSystem: 64512, routerId: "192.0.2.5", interfaces: [{ name: "wg-ix-web", kind: "wireguard",
|
||||
prefixes: ["2001:db8:12::/48"], provisionWireguard: { peerPublicKey: "A".repeat(43) + "=",
|
||||
listenPort: 51820, localAddress: "10.20.30.1/30", peerAddress: "10.20.30.2", hubEndpoint: "192.0.2.20" } },
|
||||
{ name: "gre-client", kind: "gre-ipsec", localEndpoint: "192.0.2.20", endpoint: "192.0.2.21" }] }] }
|
||||
const { segment } = await post("", { revision: 0, configuration }, 200)
|
||||
assert.equal(segment.revision, 1)
|
||||
assert.equal(segment.appliedRevision, null)
|
||||
const path = "/" + segment.id
|
||||
const linux = async (name?: string, status = 200) => {
|
||||
const query = name ? "?" + new URLSearchParams({ serverId: String(server.id), interfaceName: name }) : ""
|
||||
const response = await fetch(origin + "/api/ix/segments" + path + "/linux" + query, { headers: { authorization: "Bearer " + reader } })
|
||||
const body = await response.json()
|
||||
assert.equal(response.status, status, JSON.stringify(body))
|
||||
return body
|
||||
}
|
||||
assert.deepEqual(await linux(), { revision: null, items: [] })
|
||||
const { digest, changes } = await post(path + "/plan", { revision: 1 }, 200)
|
||||
assert(changes.some((step: { path: string }) => step.path === "/interface/wireguard/peers"))
|
||||
await post(path + "/apply", { revision: 1, digest }, 401, "")
|
||||
await post(path + "/apply", { revision: 1, digest }, 403, reader)
|
||||
await post(path + "/apply", { revision: 1, digest }, 409, otherWriter)
|
||||
await post(path + "/apply", { revision: 1, digest: "0".repeat(64) }, 409)
|
||||
rows["/interface"].push({ ".id": "*F0", name: "test-drift", type: "ether" })
|
||||
await post(path + "/apply", { revision: 1, digest }, 409)
|
||||
assert.equal(writes, 0)
|
||||
const fresh = await post(path + "/plan", { revision: 1 }, 200)
|
||||
const protectionId = randomUUID()
|
||||
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES ($1,$2,'ix-web-owner')",
|
||||
[protectionId, { kind: "server", id: String(server.id), protection: "deny" }])
|
||||
await post(path + "/apply", { revision: 1, digest: fresh.digest }, 409)
|
||||
assert.equal(writes, 0)
|
||||
await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protectionId])
|
||||
const applied = await post(path + "/apply", { revision: 1, digest: fresh.digest }, 200)
|
||||
assert.equal(applied.segment.appliedRevision, 2)
|
||||
assert.equal(applied.result.configurationVerified, true)
|
||||
assert.equal(applied.result.forwardingVerified, false)
|
||||
const resultWrites = writes
|
||||
assert.equal(resultWrites, changes.length)
|
||||
const clients = await linux()
|
||||
assert.equal(clients.revision, 2)
|
||||
assert.deepEqual(clients.items.map((item: { kind: string }) => item.kind), ["wireguard", "gre-ipsec"])
|
||||
const wg = await linux("wg-ix-web")
|
||||
assert.match(wg.template, /Endpoint = 192\.0\.2\.20:51820/)
|
||||
assert.match(wg.template, /Table = off/)
|
||||
assert(!wg.template.includes("A".repeat(43)))
|
||||
const gre = await linux("gre-client")
|
||||
assert.match(gre.template, /local_ts = 192\.0\.2\.21\/32\[47\]/)
|
||||
assert.match(gre.template, /remote_ts = 192\.0\.2\.20\/32\[47\]/)
|
||||
assert.match(gre.template, /mode = transport/)
|
||||
assert.match(gre.setup, /mode gre local 192\.0\.2\.21 remote 192\.0\.2\.20/)
|
||||
rows["/ip/ipsec/policy"][0].disabled = "true"
|
||||
await linux("gre-client", 409)
|
||||
rows["/ip/ipsec/policy"][0].disabled = "false"
|
||||
rows["/interface/wireguard/peers"][0].disabled = "true"
|
||||
await linux("wg-ix-web", 409)
|
||||
delete rows["/interface/wireguard/peers"][0].disabled
|
||||
await post(path + "/apply", { revision: 1, digest: fresh.digest }, 409)
|
||||
assert.equal(writes, resultWrites)
|
||||
|
||||
const next = await post("", { id: segment.id, revision: 2, configuration: { ...configuration,
|
||||
sites: [{ ...configuration.sites[0], discardNetworks: ["2001:db8:ff::/48"] }] } }, 200)
|
||||
assert.equal(next.segment.appliedRevision, 2)
|
||||
assert.equal((await linux("wg-ix-web")).revision, 2)
|
||||
const members = rows["/interface/list/member"]
|
||||
members.push({ ".id": "*FE", list: rows["/interface/list"][0].name, interface: "test-drift" })
|
||||
const foreign = await post(path + "/plan", { revision: 3 }, 409)
|
||||
assert.match(foreign.error, /посторонний интерфейс/)
|
||||
members.pop()
|
||||
const nextPlan = await post(path + "/plan", { revision: 3 }, 200)
|
||||
await post(path + "/apply", { revision: 3, digest: nextPlan.digest }, 200)
|
||||
assert(rows["/ipv6/route"].some(row => row["dst-address"] === "2001:db8:ff::/48"))
|
||||
const { rows: [audit] } = await pool.query(`SELECT count(*)::int AS n FROM mcp_audit
|
||||
WHERE actor_id='ix-web-owner' AND action='configuration.acknowledged' AND connection_id IS NULL`)
|
||||
assert.equal(audit.n, writes)
|
||||
const { rows: [connections] } = await pool.query("SELECT count(*)::int AS n FROM mcp_connections")
|
||||
assert.equal(connections.n, 0)
|
||||
console.log(JSON.stringify({ appliedRevisions: [2, 4], writes, audit: audit.n, mcpConnections: connections.n,
|
||||
unauthenticated: 401, readOnly: 403, ownerMismatch: 409, drift: 409, replay: 409, protected: 409, linuxClients: clients.items.length }))
|
||||
} finally {
|
||||
await app?.close()
|
||||
await new Promise<void>(resolve => router.close(() => resolve()))
|
||||
await pool.end()
|
||||
await pg.stop()
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { mkdtemp, readdir, readFile } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join, resolve } from "node:path"
|
||||
import { createServer } from "node:net"
|
||||
import { randomBytes } from "node:crypto"
|
||||
import EmbeddedPostgres from "embedded-postgres"
|
||||
import { FIXED59_IX_DELTA } from "../writer-profile/fixed59-ix-delta.js"
|
||||
import { canonical } from "../writer-profile/application-writer-profile-canonical.js"
|
||||
import { ixWriterProfileEnrollmentSql } from "../../src/db/internet-exchange-writer-profile.js"
|
||||
import { FIXED44_CATALOGUE_BUILD_SQL } from "../writer-profile/fixed44-build-sql.js"
|
||||
import { CatalogueValueStream } from "../writer-profile/application-writer-profile-catalogue-values.js"
|
||||
import { projectCatalogueData, GROUPS, sorted, type Inventory, type Row } from "../writer-profile/catalogue-projection.js"
|
||||
|
||||
const root = await mkdtemp(join(tmpdir(), "mmapp-ix-profile-"))
|
||||
assert.equal(resolve(root, ".."), resolve(tmpdir()))
|
||||
const listener = createServer()
|
||||
await new Promise<void>((done, reject) => listener.listen(0, "127.0.0.1", done).on("error", reject))
|
||||
const port = (listener.address() as { port: number }).port
|
||||
await new Promise<void>((done, reject) => listener.close(error => error ? reject(error) : done()))
|
||||
const app = new EmbeddedPostgres({ databaseDir: root, user: "ixlab", password: randomBytes(24).toString("hex"),
|
||||
port, persistent: false, createPostgresUser: false, initdbFlags: ["--encoding=UTF8", "--no-locale"],
|
||||
postgresFlags: ["-h", "127.0.0.1", "-c", "jit=off"], onLog: () => {}, onError: () => {} })
|
||||
const roles = ["ix_operator", "ix_runtime", "ix_capture", "ix_publisher", "ix_control"]
|
||||
const tables = ["ix_segments", "ix_segment_devices", "ix_segment_revisions"]
|
||||
console.log("Initialising disposable PostgreSQL")
|
||||
await app.initialise()
|
||||
console.log("Starting disposable PostgreSQL")
|
||||
await app.start()
|
||||
const db = app.getPgClient("postgres", "127.0.0.1")
|
||||
try {
|
||||
await db.connect()
|
||||
console.log("Applying pinned migrations in the fixture")
|
||||
await db.query("CREATE TABLE schema_migrations(id text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())")
|
||||
const directory = resolve("backend/drizzle")
|
||||
for (const name of (await readdir(directory)).filter(name => name.endsWith(".sql")).sort()) {
|
||||
await db.query(await readFile(join(directory, name), "utf8"))
|
||||
await db.query("INSERT INTO schema_migrations(id) VALUES ($1) ON CONFLICT DO NOTHING", [name.slice(0,-4)])
|
||||
}
|
||||
for (const role of roles) await db.query("CREATE ROLE " + role)
|
||||
await db.query("CREATE SCHEMA IF NOT EXISTS mmapp_control; CREATE FUNCTION mmapp_control.candidate_truncate_preadmitted() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RETURN NULL; END; $$")
|
||||
for (const name of tables) await db.query("ALTER TABLE public." + name + " OWNER TO ix_operator")
|
||||
await db.query("GRANT USAGE ON SCHEMA mmapp_control TO ix_operator; GRANT EXECUTE ON FUNCTION mmapp_control.candidate_truncate_preadmitted() TO ix_operator")
|
||||
await db.query("BEGIN; SET LOCAL ROLE ix_operator")
|
||||
await db.query(ixWriterProfileEnrollmentSql("ix_runtime", "ix_capture"))
|
||||
await db.query("COMMIT")
|
||||
|
||||
const insert = "INSERT INTO ix_segments(id,name,revision,configuration) VALUES ('8dd5d978-83ac-4343-8cff-16655a0a77a7','fixture',1,'{}')"
|
||||
const maintenance = app.getPgClient("postgres", "127.0.0.1")
|
||||
await maintenance.connect()
|
||||
try {
|
||||
await maintenance.query("SELECT pg_advisory_lock(8723110::bigint)")
|
||||
await db.query("BEGIN; SET LOCAL ROLE ix_runtime; SET LOCAL lock_timeout='250ms'")
|
||||
await assert.rejects(db.query(insert), { code: "55P03" })
|
||||
await db.query("ROLLBACK")
|
||||
} finally {
|
||||
await maintenance.end()
|
||||
}
|
||||
await db.query("BEGIN; SET LOCAL ROLE ix_runtime; SELECT pg_advisory_xact_lock_shared(8723110::bigint)")
|
||||
await db.query(insert)
|
||||
await db.query("INSERT INTO ix_segment_revisions(segment_id,revision,configuration,actor_id) VALUES ('8dd5d978-83ac-4343-8cff-16655a0a77a7',1,'{}','fixture')")
|
||||
await assert.rejects(db.query("UPDATE ix_segment_revisions SET actor_id='other'"), { code: "42501" })
|
||||
await db.query("ROLLBACK")
|
||||
|
||||
console.log("Capturing exact IX catalogue rows")
|
||||
await db.query("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY; SET LOCAL search_path=pg_catalog,public; SET LOCAL TimeZone='UTC'; SET LOCAL DateStyle='ISO, YMD'")
|
||||
const stream = new CatalogueValueStream()
|
||||
const raw = {} as Inventory
|
||||
for (const group of GROUPS) raw[group] = []
|
||||
const statement = FIXED44_CATALOGUE_BUILD_SQL.replace("LIMIT 104", "LIMIT 113")
|
||||
await db.query("DECLARE ix_capture_cursor NO SCROLL CURSOR WITHOUT HOLD FOR " + statement, roles)
|
||||
for (;;) {
|
||||
const page = (await db.query("FETCH FORWARD 128 FROM ix_capture_cursor")).rows
|
||||
if (!page.length) break
|
||||
for (const record of stream.acceptPage(page)) {
|
||||
if (record.kind === "global") raw[record.identity === "base_tables" ? "tables" : record.identity] = record.value.rows as Row[]
|
||||
if (record.kind === "base") for (const group of GROUPS) raw[group].push(...record.value[group] as Row[])
|
||||
}
|
||||
}
|
||||
stream.finish()
|
||||
const projected = projectCatalogueData(raw)
|
||||
const delta: Inventory = {}
|
||||
for (const group of ["tables", ...GROUPS]) delta[group] = sorted(projected[group].filter(row => tables.includes(String(row.relname))))
|
||||
delta.constraints.push(...projected.constraints.filter(row => row.relname === "servers" && row.conname === "servers_type_check"))
|
||||
delta.triggers.push(...projected.triggers.filter(row => row.relname === "servers" && String(row.definition).includes("ix_segment_devices")))
|
||||
assert.equal(delta.tables.length, 3)
|
||||
assert.equal(delta.triggers.filter(row => row.relname === "servers").length, 2)
|
||||
await db.query("ROLLBACK")
|
||||
let text = JSON.stringify(delta, null, 2)
|
||||
for (const [index, role] of roles.entries()) text = text.replaceAll(role, "@mm-role:" + ["operator","runtime","capture","publisher","control"][index] + "@")
|
||||
assert.equal(canonical(JSON.parse(text)), canonical(FIXED59_IX_DELTA), "PostgreSQL catalogue drifted from source59")
|
||||
console.log(JSON.stringify({ postgres: (await db.query("SHOW server_version")).rows[0].server_version, relations: delta.tables.length, constraints: delta.constraints.length,
|
||||
triggers: delta.triggers.length, leastPrivilege: true, sharedWriterLock: true }))
|
||||
} finally {
|
||||
await db.end().catch(() => {})
|
||||
await app.stop()
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { setTimeout as delay } from 'node:timers/promises'
|
||||
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'
|
||||
import { resumeMcpSteps } from './mcp-step-journal.mjs'
|
||||
|
||||
const [phase, port, planId, connectionId] = process.argv.slice(2)
|
||||
assert(process.send && process.env.MCP_FIXTURE_TOKEN && ['dispatch', 'resume'].includes(phase))
|
||||
const uuid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i
|
||||
assert.match(planId, uuid)
|
||||
assert.match(connectionId, uuid)
|
||||
const client = new Client({ name: 'owned-routing-observer', version: '1.0.0' })
|
||||
async function call(name, args) {
|
||||
const reply = await client.callTool({ name, arguments: args })
|
||||
assert(!reply.isError, 'MCP fixture call failed: ' + name)
|
||||
return reply.structuredContent?.result ?? JSON.parse(reply.content[0].text)
|
||||
}
|
||||
|
||||
try {
|
||||
await client.connect(new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${port}/mcp`), {
|
||||
requestInit: { headers: { Authorization: 'Bearer ' + process.env.MCP_FIXTURE_TOKEN } },
|
||||
}))
|
||||
let operationId
|
||||
const result = await resumeMcpSteps({ journal: 'routing-forward.jsonl', fixture: `routing-scoped-forward:${connectionId}:${planId}`, steps: [{
|
||||
id: 'forward-apply', kind: 'apply',
|
||||
async run({ idempotencyKey, accept }) {
|
||||
assert.equal(phase, 'dispatch', 'A resumed observer cannot send apply')
|
||||
const receipt = await call('mm_change_apply', { planId, idempotencyKey })
|
||||
assert.deepEqual([receipt.plan_id, receipt.connection_id], [planId, connectionId])
|
||||
accept(receipt.id)
|
||||
// The supervisor terminates this process after the journal fsync.
|
||||
process.send(receipt.id)
|
||||
await new Promise(resolve => process.once('disconnect', resolve))
|
||||
throw new Error('Observer was disconnected by its supervisor')
|
||||
},
|
||||
async reconcile({ accepted }) {
|
||||
assert.equal(phase, 'resume')
|
||||
assert.ok(accepted)
|
||||
const deadline = Date.now() + 60_000
|
||||
while (Date.now() < deadline) {
|
||||
const receipt = await call('mm_operation_get', { operationId: accepted })
|
||||
assert.deepEqual([receipt.id, receipt.plan_id, receipt.connection_id], [accepted, planId, connectionId])
|
||||
if (!['pending', 'running'].includes(receipt.state)) {
|
||||
assert.deepEqual([receipt.state, receipt.verification], ['applied', 'passed'])
|
||||
operationId = accepted
|
||||
return { state: 'verified', evidence: accepted }
|
||||
}
|
||||
await delay(400)
|
||||
}
|
||||
return { state: 'unknown' }
|
||||
},
|
||||
}] })
|
||||
assert.deepEqual(result, { status: 'passed' })
|
||||
assert.ok(operationId)
|
||||
await new Promise((resolve, reject) => process.send(operationId, error => error ? reject(error) : resolve()))
|
||||
} finally {
|
||||
await client.close()
|
||||
if (process.connected) process.disconnect()
|
||||
}
|
||||
Loaded 100 of 1690 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user