@colveor/admin 0.5.2 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,366 @@
1
+ # @colveor/admin
2
+
3
+ The admin panel for APIs built on **colveor-go**: its pages, its API
4
+ client and the building blocks to make your own pages look and work the
5
+ same.
6
+
7
+ Start a panel with
8
+ [`@colveor/create-admin`](https://www.npmjs.com/package/@colveor/create-admin),
9
+ which sets all of this up:
10
+
11
+ ```sh
12
+ npm create @colveor/admin@latest my-admin
13
+ ```
14
+
15
+ This README is the reference for what the package gives you once you have
16
+ a panel.
17
+
18
+ - [Pages](#pages)
19
+ - [How it fits together](#how-it-fits-together)
20
+ - [Building your own pages](#building-your-own-pages)
21
+ - [Talking to the API](#talking-to-the-api)
22
+ - [Building blocks](#building-blocks)
23
+ - [Versions](#versions)
24
+ - [Using it without the template](#using-it-without-the-template)
25
+
26
+ ## Pages
27
+
28
+ Each page is shown only to admins holding its permission, and hidden when
29
+ its API module is off.
30
+
31
+ | Page | Import | Permission |
32
+ | ---------------------------------------------------------- | -------------------------------------- | -------------------------------------------------------------------------- |
33
+ | Sign in (password or emailed code, then two-step) | `@colveor/admin/pages/sign-in` | none |
34
+ | Forgot password | `@colveor/admin/pages/forgot-password` | none |
35
+ | My account (profile, password, two-step, devices, my data) | `@colveor/admin/pages/account` | signed in |
36
+ | Users | `@colveor/admin/pages/users` | `users.read` |
37
+ | Roles | `@colveor/admin/pages/roles` | `rbac.read` |
38
+ | Teams | `@colveor/admin/pages/teams` | `teams.suspend` |
39
+ | Support access | `@colveor/admin/pages/support` | `support.request` or `support.read` |
40
+ | Settings | `@colveor/admin/pages/settings` | `settings.read` |
41
+ | Audit log | `@colveor/admin/pages/audit` | `audit.read` |
42
+ | Webhook events | `@colveor/admin/pages/webhooks` | `webhooks.read` |
43
+ | System status | `@colveor/admin/pages/status` | `health.read` |
44
+ | Ledger | `@colveor/admin/pages/ledger` | `ledger.approve`, `ledger.manage` or `ledger.adjust` (each shows its part) |
45
+
46
+ A panel mounts a page with one line, so updating the package updates the
47
+ page:
48
+
49
+ ```ts
50
+ // app/(admin)/(colveor)/users/page.tsx
51
+ export { default } from "@colveor/admin/pages/users";
52
+ ```
53
+
54
+ Changes ask for what the API asks: a reason for the audit log on every
55
+ admin change, and "confirm it's you" before sensitive ones (a secret
56
+ setting, resetting someone's two-step verification).
57
+
58
+ ## How it fits together
59
+
60
+ ```
61
+ browser ──► the panel's Next server ──► the colveor-go API
62
+ /api/colveor/<path> <path>
63
+ (the proxy: tokens in httpOnly cookies)
64
+ ```
65
+
66
+ | Export | What it is |
67
+ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
68
+ | `@colveor/admin` | The building blocks, the API client and the API's types. |
69
+ | `@colveor/admin/next` | `<NextAdmin>`: the shell with Next's router. The only file that imports Next. |
70
+ | `@colveor/admin/proxy` | The proxy route handler (plain web `Request` and `Response`). |
71
+ | `@colveor/admin/banner` | `printBanner()`: the COLVEOR ADMIN banner at server start, with the API it talks to (the template's `instrumentation.ts`). Node only. |
72
+ | `@colveor/admin/pages/*` | The pages above. |
73
+
74
+ The pages and building blocks are plain React 19. Only
75
+ `@colveor/admin/next` depends on Next (16 or later), so another React setup
76
+ needs only a router adapter (`<ColveorAdmin router={...}>`).
77
+
78
+ **The shell** wraps every page (the template's `app/providers.tsx`):
79
+
80
+ ```tsx
81
+ "use client";
82
+ import { NextAdmin } from "@colveor/admin/next";
83
+ import config from "../admin.config";
84
+
85
+ export default function Providers({ children }) {
86
+ return <NextAdmin config={config}>{children}</NextAdmin>;
87
+ }
88
+ ```
89
+
90
+ It loads the signed-in admin's roles and permissions before showing a
91
+ page, sends a signed-out admin to the sign-in page (with `?next=` back),
92
+ and loads the permissions again on each page, so a role change shows at
93
+ once.
94
+
95
+ **`admin.config.ts`**:
96
+
97
+ ```ts
98
+ import { defineConfig } from "@colveor/admin";
99
+
100
+ export default defineConfig({
101
+ name: "Acme Admin", // the menu and the browser tab
102
+ logo: "/logo.svg", // optional, above the menu
103
+ signInPath: "/login", // optional, the default
104
+ nav: [ // your items, after the framework's
105
+ {
106
+ label: "Invoices",
107
+ href: "/invoices",
108
+ permission: "invoices.read", // or a list: any one of them
109
+ group: "Sales", // the menu heading it goes under
110
+ icon: <InvoiceIcon />, // optional
111
+ },
112
+ ],
113
+ });
114
+ ```
115
+
116
+ ## Building your own pages
117
+
118
+ A page in `app/(admin)/(project)/` is a normal Next page. Build it from
119
+ the package's pieces and it matches ours: the same header, cards, tables,
120
+ dialogs, dates and permission checks.
121
+
122
+ ```tsx
123
+ "use client";
124
+
125
+ import {
126
+ Badge,
127
+ DataTable,
128
+ PageHeader,
129
+ RequirePermission,
130
+ RowMenu,
131
+ api,
132
+ formatDate,
133
+ useAction,
134
+ } from "@colveor/admin";
135
+ import { useState } from "react";
136
+
137
+ type Invoice = { id: string; number: string; status: string; created_at: string };
138
+
139
+ export default function InvoicesPage() {
140
+ const { run, dialogs } = useAction();
141
+ const [reload, setReload] = useState(0);
142
+
143
+ const cancel = (i: Invoice) =>
144
+ run((o) => api.post(`/v1/invoices/${i.id}/cancel`, undefined, o)).then(() =>
145
+ setReload((n) => n + 1),
146
+ );
147
+
148
+ return (
149
+ <RequirePermission keys={["invoices.read"]}>
150
+ <PageHeader title="Invoices" crumbs={[{ label: "Sales" }]} />
151
+ <DataTable<Invoice>
152
+ title="Invoices"
153
+ path="/v1/invoices"
154
+ reload={reload}
155
+ download="invoices"
156
+ columns={[
157
+ { header: "Number", cell: (i) => i.number },
158
+ { header: "Status", cell: (i) => <Badge tone="green">{i.status}</Badge> },
159
+ { header: "Date", sortKey: "created_at", cell: (i) => formatDate(i.created_at) },
160
+ {
161
+ header: "",
162
+ cell: (i) => (
163
+ <RowMenu items={[{ label: "Cancel", danger: true, onSelect: () => cancel(i) }]} />
164
+ ),
165
+ },
166
+ ]}
167
+ />
168
+ {dialogs}
169
+ </RequirePermission>
170
+ );
171
+ }
172
+ ```
173
+
174
+ Then add it to `nav` in `admin.config.ts`.
175
+
176
+ A file that uses React hooks must start with `"use client"`.
177
+
178
+ ## Talking to the API
179
+
180
+ The browser never calls the API directly: the page calls
181
+ `/api/colveor/<API path>` on the panel's own server, and the proxy forwards
182
+ it to `COLVEOR_API_URL`.
183
+
184
+ ```ts
185
+ // app/api/colveor/[...path]/route.ts
186
+ export {
187
+ handler as DELETE,
188
+ handler as GET,
189
+ handler as PATCH,
190
+ handler as POST,
191
+ handler as PUT,
192
+ } from "@colveor/admin/proxy";
193
+ ```
194
+
195
+ - **Tokens never reach the page.** The proxy moves them from the API's
196
+ responses into `httpOnly`, `SameSite=Lax` cookies (`Secure` over HTTPS).
197
+ Nothing is kept in `localStorage`, and the API needs no CORS setup.
198
+ - **Refreshing is automatic.** An expired access token is refreshed and
199
+ the call retried; calls that arrive together share one refresh. A refresh
200
+ that fails signs the admin out.
201
+ - **Run one panel server** (or route a session to the same one): the shared
202
+ refresh is kept in the server's memory, and a refresh token works only
203
+ once.
204
+ - **Trust the panel server on the API:** add its address to the API's
205
+ `SERVER_TRUSTED_PROXIES`, so rate limits, sessions and the audit log see
206
+ each admin's own IP.
207
+ - `createProxy({ apiUrl, prefix })` makes a handler with other settings
208
+ (default: `COLVEOR_API_URL` and `/api/colveor`).
209
+
210
+ ### The client
211
+
212
+ ```ts
213
+ import { ApiError, api, gormx, rbac } from "@colveor/admin";
214
+
215
+ const roles = await api.get<rbac.RoleResponse[]>("/v1/rbac/roles");
216
+ const page = await api.get<gormx.Page<rbac.RoleMemberResponse>>(`/v1/rbac/roles/${id}/users`, {
217
+ limit: 50,
218
+ });
219
+
220
+ try {
221
+ await api.patch(`/v1/settings/${key}`, { value }, { reason: "Raise the limit for the launch" });
222
+ } catch (err) {
223
+ if (err instanceof ApiError && err.code === "settings.invalid_value") {
224
+ // err.status, err.code, err.message, err.data
225
+ }
226
+ }
227
+ ```
228
+
229
+ `api.get(path, query)`, `api.post` / `put` / `patch(path, body, options)`
230
+ and `api.delete(path, options)`. `options`: `reason` (`X-Reason`),
231
+ `reauthToken` (`X-Reauth-Token`) and `idempotencyKey` (`Idempotency-Key`).
232
+ `signOut()` signs the admin out.
233
+
234
+ ### The API's types
235
+
236
+ Generated from colveor-go's Go contracts, one namespace per module: the
237
+ request and response shapes, error codes and permission keys.
238
+
239
+ ```ts
240
+ import { rbac, settings, users } from "@colveor/admin";
241
+
242
+ const user: users.UserResponse = await api.get(`/v1/users/${id}`);
243
+ if (useCan(rbac.PermissionManage)) {
244
+ /* ... */
245
+ }
246
+ if (err.code === users.ErrCodeNotFound) {
247
+ /* ... */
248
+ }
249
+ ```
250
+
251
+ A field the API may leave out is optional (`next_page?: string`): check it
252
+ with `== null`. Lists use the standard page, `gormx.Page<T>`: `items`,
253
+ `next_page`, `previous_page`, `total`.
254
+
255
+ ### Changes that need a reason or "confirm it's you"
256
+
257
+ ```tsx
258
+ const { run, dialogs } = useAction();
259
+
260
+ const suspend = () => run((o) => api.post(`/v1/users/${id}/suspend`, undefined, o));
261
+
262
+ return <>{button}{dialogs}</>;
263
+ ```
264
+
265
+ `run` sends the change. When the API asks for a reason, it shows a reason
266
+ dialog; when it asks the admin to confirm it's them, it shows the
267
+ re-authentication dialog (password, authenticator code, emailed code, PIN
268
+ or recovery code). Then it sends again, with a new idempotency key each
269
+ time. If the admin closes a dialog, `run` rejects with `Cancelled`:
270
+
271
+ ```ts
272
+ try {
273
+ await run(send);
274
+ } catch (err) {
275
+ if (!(err instanceof Cancelled)) setError(err.message);
276
+ }
277
+ ```
278
+
279
+ ## Building blocks
280
+
281
+ **Page layout**
282
+
283
+ | Block | Use |
284
+ | --------------------------------------- | -------------------------------------------------------------------------- |
285
+ | `<PageHeader title crumbs actions>` | The top of every page: its title and breadcrumb (Home • Sales • Invoices). |
286
+ | `<Card title about info actions flush>` | A box with a title, a "?" (`info`) and icon buttons on the right. |
287
+ | `<Modal title onClose footer size>` | A dialog; Escape closes it. `size="xl"` for an editor with a preview. |
288
+ | `<FilterTabs tabs value onChange>` | Segmented tabs that pick what a list shows. |
289
+
290
+ **Lists**
291
+
292
+ | Block | Use |
293
+ | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
294
+ | `<DataTable path columns query limit reload>` | One list endpoint, a page at a time, with the total. Also `title` (in a card), `actions`, `toolbar`, `download` (CSV of the page shown), `onRowClick`, `transform` (join another endpoint's data, one call per page) and a column's `sortKey` (the API sorts the whole list). |
295
+ | `<RowMenu items>` | A row's "…" menu; its clicks don't open the row. |
296
+ | `<SearchToggle placeholder onSearch>` | A search icon that opens into a box, for a card's header. |
297
+
298
+ **Small pieces**
299
+
300
+ | Block | Use |
301
+ | ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
302
+ | `<Badge tone>` | A coloured pill: `brand`, `green`, `amber`, `red`, `purple`, `sky`, `gray`. `roleTone(slug)` gives a role the same colour everywhere; `humanize(slug)` its label. |
303
+ | `<Avatar name url className>` | A photo, or initials. |
304
+ | `<Tooltip tip label>`, `<InfoTip>` | A tip shown on click; `InfoTip` is the "?" in a circle. |
305
+ | `<CodeArea value onChange lang singleLine>` | A text box that colours HTML and Go template actions (`{{.Code}}`). |
306
+ | `<CodeInput value onChange onComplete>` | A one-time code, one box per digit. |
307
+ | `<Dropdown>`, `iconButton` | The header's menus and round icon buttons. |
308
+ | `formatDate(v)`, `formatDateTime(v)` | Every date as "1 Dec, 2026" (and "1 Dec, 2026, 14:05"). |
309
+
310
+ **Permissions and the shell**
311
+
312
+ | Block | Use |
313
+ | -------------------------------------------- | ---------------------------------------------------------------- |
314
+ | `<RequirePermission keys fallback>` | Shows its children only to admins holding every key. |
315
+ | `useCan(...keys)` | The same, as a boolean. |
316
+ | `useAdmin()` | The config, the router, the admin's roles and permissions. |
317
+ | `useNav()` | The menu this admin may open: the framework's items, then yours. |
318
+ | `NavSearch`, `NotificationsMenu`, `UserMenu` | The header's search, notifications and account menu. |
319
+
320
+ **Users** (for your own user screens)
321
+
322
+ | Block | Use |
323
+ | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
324
+ | `useUserActions(user, onChange)` | The admin's actions on a user (suspend, sign out everywhere, reset two-step, unlock PINs), each for its permission. |
325
+ | `<UserActions>`, `<UserRoles>`, `<UserSessions>`, `<UserRowMenu>` | The user page's parts. |
326
+ | `<TeamSupportGrants team>` | A team's support access grants, for your own team screens. |
327
+
328
+ ### Styling
329
+
330
+ The package's components use Tailwind classes and the theme's `brand-*`
331
+ colours, so the panel's Tailwind must scan the package. The template's
332
+ `app/globals.css` does it:
333
+
334
+ ```css
335
+ @import "tailwindcss";
336
+ @source "../node_modules/@colveor/admin/dist";
337
+ ```
338
+
339
+ The animations (`animate-fade-in`, `animate-pop-in`, `animate-slide-down`,
340
+ `animate-slide-in`) are defined there too, and turn off for admins who ask
341
+ for reduced motion.
342
+
343
+ ## Versions
344
+
345
+ `@colveor/admin` has the major and minor version of the colveor-go release
346
+ it is built for: 0.5.x works with a colveor-go 0.5.x API. The System status
347
+ page warns when the API's version doesn't match (`version` is exported).
348
+ Changes that break your own pages are listed under **Breaking** in
349
+ colveor-go's changelog, with what to do.
350
+
351
+ ## Using it without the template
352
+
353
+ The template is the supported setup. Without it, a Next 16 app needs:
354
+
355
+ 1. `@colveor/admin`, `next`, `react` and `react-dom` 19.
356
+ 2. Tailwind 4 scanning `node_modules/@colveor/admin/dist`, with a theme
357
+ that defines the `brand-*` colours (copy the template's `globals.css`).
358
+ 3. The proxy route at `app/api/colveor/[...path]/route.ts`, and
359
+ `COLVEOR_API_URL` on the server.
360
+ 4. `<NextAdmin config={config}>` around the app, in a client component.
361
+ 5. A page per framework page you want, each a one-line re-export.
362
+
363
+ ## License
364
+
365
+ Proprietary: see `LICENSE.md`. Parts of the look come from TailwindAdmin
366
+ (MIT, `TAILWINDADMIN-LICENSE`).
@@ -0,0 +1 @@
1
+ export declare function printBanner(): void;
package/dist/banner.js ADDED
@@ -0,0 +1,49 @@
1
+ // The COLVEOR ADMIN banner the panel's server prints as it starts (the
2
+ // template's instrumentation.ts), in the brand colours (#465FFF into
3
+ // violet), with the API it talks to. Only in a terminal: in Docker or a log
4
+ // file the output stays plain. Node only: never import it in a page.
5
+ import { version } from "./version";
6
+ const LETTERS = {
7
+ C: [" ██████╗", "██╔════╝", "██║ ", "██║ ", "╚██████╗", " ╚═════╝"],
8
+ O: [" ██████╗ ", "██╔═══██╗", "██║ ██║", "██║ ██║", "╚██████╔╝", " ╚═════╝ "],
9
+ L: ["██╗ ", "██║ ", "██║ ", "██║ ", "███████╗", "╚══════╝"],
10
+ V: ["██╗ ██╗", "██║ ██║", "██║ ██║", "╚██╗ ██╔╝", " ╚████╔╝ ", " ╚═══╝ "],
11
+ E: ["███████╗", "██╔════╝", "█████╗ ", "██╔══╝ ", "███████╗", "╚══════╝"],
12
+ R: ["██████╗ ", "██╔══██╗", "██████╔╝", "██╔══██╗", "██║ ██║", "╚═╝ ╚═╝"],
13
+ };
14
+ export function printBanner() {
15
+ if (!process.stdout.isTTY) {
16
+ return;
17
+ }
18
+ const env = process.env;
19
+ const colour = !("NO_COLOR" in env) && env.TERM !== "dumb";
20
+ const truecolour = colour && /truecolor|24bit/i.test(env.COLORTERM ?? "");
21
+ const paint = (t, s) => {
22
+ if (!colour) {
23
+ return s;
24
+ }
25
+ if (!truecolour) {
26
+ return `\x1b[${t < 0.5 ? 94 : 95}m${s}\x1b[39m`;
27
+ }
28
+ const [r, g, b] = [70, 95, 255].map((c, i) => Math.round(c + ([158, 119, 237][i] - c) * t));
29
+ return `\x1b[38;2;${r};${g};${b}m${s}\x1b[39m`;
30
+ };
31
+ const dim = (s) => (colour ? `\x1b[2m${s}\x1b[22m` : s);
32
+ const red = (s) => (colour ? `\x1b[31m${s}\x1b[39m` : s);
33
+ const rows = [0, 1, 2, 3, 4, 5].map((r) => [..."COLVEOR"].map((ch) => LETTERS[ch][r]).join(""));
34
+ const width = rows[0].length;
35
+ const art = rows.map((row) => ` ${[...row].map((ch, i) => (ch === " " ? ch : paint(i / (width - 1), ch))).join("")}`);
36
+ const label = "A D M I N";
37
+ const tag = `@colveor/admin ${version}`;
38
+ const api = env.COLVEOR_API_URL
39
+ ? env.COLVEOR_API_URL
40
+ : red("COLVEOR_API_URL is not set: copy .env.example to .env.local");
41
+ console.log([
42
+ "",
43
+ ...art,
44
+ ` ${paint(1, label)}${" ".repeat(Math.max(1, width - label.length - tag.length))}${dim(tag)}`,
45
+ "",
46
+ ` ${paint(0, "▸")} ${dim("API ")} ${api}`,
47
+ "",
48
+ ].join("\n"));
49
+ }
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const version = "0.5.2";
1
+ export declare const version = "0.5.3";
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // This package's version: the colveor-go release it is built for (the same
2
2
  // major and minor). test/rules.test.ts keeps it equal to package.json's.
3
- export const version = "0.5.2";
3
+ export const version = "0.5.3";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colveor/admin",
3
- "version": "0.5.2",
3
+ "version": "0.5.3",
4
4
  "description": "The admin panel pages for apps built on colveor-go.",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "type": "module",
@@ -9,6 +9,10 @@
9
9
  "types": "./dist/index.d.ts",
10
10
  "default": "./dist/index.js"
11
11
  },
12
+ "./banner": {
13
+ "types": "./dist/banner.d.ts",
14
+ "default": "./dist/banner.js"
15
+ },
12
16
  "./proxy": {
13
17
  "types": "./dist/proxy.d.ts",
14
18
  "default": "./dist/proxy.js"