@colveor/admin 0.0.0-stage → 0.5.2

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.
Files changed (154) hide show
  1. package/LICENSE.md +106 -0
  2. package/TAILWINDADMIN-LICENSE +21 -0
  3. package/dist/account/data.d.ts +1 -0
  4. package/dist/account/data.js +44 -0
  5. package/dist/account/profile.d.ts +6 -0
  6. package/dist/account/profile.js +118 -0
  7. package/dist/account/sessions.d.ts +1 -0
  8. package/dist/account/sessions.js +26 -0
  9. package/dist/account/shared.d.ts +26 -0
  10. package/dist/account/shared.js +44 -0
  11. package/dist/account/two-factor.d.ts +5 -0
  12. package/dist/account/two-factor.js +60 -0
  13. package/dist/actions.d.ts +39 -0
  14. package/dist/actions.js +81 -0
  15. package/dist/api/audit.gen.d.ts +80 -0
  16. package/dist/api/audit.gen.js +43 -0
  17. package/dist/api/auth.gen.d.ts +537 -0
  18. package/dist/api/auth.gen.js +313 -0
  19. package/dist/api/errors.gen.d.ts +16 -0
  20. package/dist/api/errors.gen.js +2 -0
  21. package/dist/api/gormx.gen.d.ts +60 -0
  22. package/dist/api/gormx.gen.js +16 -0
  23. package/dist/api/health.gen.d.ts +103 -0
  24. package/dist/api/health.gen.js +23 -0
  25. package/dist/api/index.gen.d.ts +21 -0
  26. package/dist/api/index.gen.js +22 -0
  27. package/dist/api/invitations.gen.d.ts +128 -0
  28. package/dist/api/invitations.gen.js +57 -0
  29. package/dist/api/ledger.gen.d.ts +269 -0
  30. package/dist/api/ledger.gen.js +113 -0
  31. package/dist/api/msgtemplate.gen.d.ts +31 -0
  32. package/dist/api/msgtemplate.gen.js +2 -0
  33. package/dist/api/notifications.gen.d.ts +66 -0
  34. package/dist/api/notifications.gen.js +28 -0
  35. package/dist/api/outbox.gen.d.ts +8 -0
  36. package/dist/api/outbox.gen.js +2 -0
  37. package/dist/api/queue.gen.d.ts +112 -0
  38. package/dist/api/queue.gen.js +15 -0
  39. package/dist/api/rbac.gen.d.ts +406 -0
  40. package/dist/api/rbac.gen.js +191 -0
  41. package/dist/api/reauth.gen.d.ts +289 -0
  42. package/dist/api/reauth.gen.js +122 -0
  43. package/dist/api/recorded_payments.gen.d.ts +171 -0
  44. package/dist/api/recorded_payments.gen.js +79 -0
  45. package/dist/api/sessions.gen.d.ts +64 -0
  46. package/dist/api/sessions.gen.js +48 -0
  47. package/dist/api/settings.gen.d.ts +147 -0
  48. package/dist/api/settings.gen.js +69 -0
  49. package/dist/api/storage.gen.d.ts +327 -0
  50. package/dist/api/storage.gen.js +208 -0
  51. package/dist/api/support_access.gen.d.ts +155 -0
  52. package/dist/api/support_access.gen.js +131 -0
  53. package/dist/api/users.gen.d.ts +407 -0
  54. package/dist/api/users.gen.js +159 -0
  55. package/dist/api/verification.gen.d.ts +427 -0
  56. package/dist/api/verification.gen.js +280 -0
  57. package/dist/api/webhooks.gen.d.ts +110 -0
  58. package/dist/api/webhooks.gen.js +45 -0
  59. package/dist/auth-layout.d.ts +9 -0
  60. package/dist/auth-layout.js +5 -0
  61. package/dist/client.d.ts +41 -0
  62. package/dist/client.js +72 -0
  63. package/dist/config.d.ts +27 -0
  64. package/dist/config.js +82 -0
  65. package/dist/dates.d.ts +4 -0
  66. package/dist/dates.js +16 -0
  67. package/dist/header.d.ts +12 -0
  68. package/dist/header.js +105 -0
  69. package/dist/icons.d.ts +2 -0
  70. package/dist/icons.js +15 -0
  71. package/dist/index.d.ts +28 -0
  72. package/dist/index.js +42 -0
  73. package/dist/kit/avatar.d.ts +5 -0
  74. package/dist/kit/avatar.js +16 -0
  75. package/dist/kit/badge.d.ts +10 -0
  76. package/dist/kit/badge.js +31 -0
  77. package/dist/kit/card.d.ts +12 -0
  78. package/dist/kit/card.js +7 -0
  79. package/dist/kit/code-area.d.ts +15 -0
  80. package/dist/kit/code-area.js +69 -0
  81. package/dist/kit/dropdown.d.ts +26 -0
  82. package/dist/kit/dropdown.js +67 -0
  83. package/dist/kit/filter-tabs.d.ts +9 -0
  84. package/dist/kit/filter-tabs.js +7 -0
  85. package/dist/kit/modal.d.ts +8 -0
  86. package/dist/kit/modal.js +15 -0
  87. package/dist/kit/page-header.d.ts +13 -0
  88. package/dist/kit/page-header.js +13 -0
  89. package/dist/kit/search.d.ts +4 -0
  90. package/dist/kit/search.js +16 -0
  91. package/dist/kit/tooltip.d.ts +17 -0
  92. package/dist/kit/tooltip.js +52 -0
  93. package/dist/message-editor.d.ts +9 -0
  94. package/dist/message-editor.js +80 -0
  95. package/dist/money.d.ts +10 -0
  96. package/dist/money.js +17 -0
  97. package/dist/next.d.ts +6 -0
  98. package/dist/next.js +19 -0
  99. package/dist/pages/account.d.ts +1 -0
  100. package/dist/pages/account.js +47 -0
  101. package/dist/pages/audit.d.ts +1 -0
  102. package/dist/pages/audit.js +88 -0
  103. package/dist/pages/forgot-password.d.ts +1 -0
  104. package/dist/pages/forgot-password.js +73 -0
  105. package/dist/pages/ledger.d.ts +1 -0
  106. package/dist/pages/ledger.js +132 -0
  107. package/dist/pages/roles.d.ts +1 -0
  108. package/dist/pages/roles.js +102 -0
  109. package/dist/pages/settings.d.ts +1 -0
  110. package/dist/pages/settings.js +86 -0
  111. package/dist/pages/sign-in.d.ts +5 -0
  112. package/dist/pages/sign-in.js +117 -0
  113. package/dist/pages/status.d.ts +1 -0
  114. package/dist/pages/status.js +122 -0
  115. package/dist/pages/support.d.ts +1 -0
  116. package/dist/pages/support.js +90 -0
  117. package/dist/pages/teams.d.ts +1 -0
  118. package/dist/pages/teams.js +94 -0
  119. package/dist/pages/users.d.ts +1 -0
  120. package/dist/pages/users.js +158 -0
  121. package/dist/pages/webhooks.d.ts +1 -0
  122. package/dist/pages/webhooks.js +88 -0
  123. package/dist/permissions.d.ts +5 -0
  124. package/dist/permissions.js +31 -0
  125. package/dist/proof.d.ts +10 -0
  126. package/dist/proof.js +78 -0
  127. package/dist/proxy.d.ts +10 -0
  128. package/dist/proxy.js +166 -0
  129. package/dist/retry.d.ts +8 -0
  130. package/dist/retry.js +30 -0
  131. package/dist/router.d.ts +13 -0
  132. package/dist/router.js +14 -0
  133. package/dist/setting-fields.d.ts +12 -0
  134. package/dist/setting-fields.js +102 -0
  135. package/dist/setting-list.d.ts +22 -0
  136. package/dist/setting-list.js +78 -0
  137. package/dist/shell.d.ts +40 -0
  138. package/dist/shell.js +97 -0
  139. package/dist/support.d.ts +37 -0
  140. package/dist/support.js +76 -0
  141. package/dist/table.d.ts +40 -0
  142. package/dist/table.js +73 -0
  143. package/dist/ui.d.ts +39 -0
  144. package/dist/ui.js +56 -0
  145. package/dist/user-actions.d.ts +30 -0
  146. package/dist/user-actions.js +129 -0
  147. package/dist/user-roles.d.ts +4 -0
  148. package/dist/user-roles.js +51 -0
  149. package/dist/user-row-menu.d.ts +14 -0
  150. package/dist/user-row-menu.js +45 -0
  151. package/dist/version.d.ts +1 -0
  152. package/dist/version.js +3 -0
  153. package/package.json +59 -4
  154. package/README.md +0 -3
package/dist/proxy.js ADDED
@@ -0,0 +1,166 @@
1
+ // The proxy between the panel and the API (docs/admin.md, Talking to the
2
+ // API). The browser calls /api/colveor/<API path>; this forwards the call
3
+ // to the API with the access token, which, like the refresh token, lives
4
+ // in an httpOnly cookie the page's scripts can't read.
5
+ //
6
+ // Plain web Request and Response, so it runs as a Next route handler
7
+ // (app/api/colveor/[...path]/route.ts) or anywhere else that has fetch.
8
+ const ACCESS = "admin_access";
9
+ const REFRESH = "admin_refresh";
10
+ // Headers not passed on: the proxy sets its own, or fetch does.
11
+ const DROPPED = ["host", "cookie", "authorization", "connection", "content-length"];
12
+ // Responses that may carry new tokens: sign-in, sign-up, the second factor.
13
+ const ISSUERS = ["/v1/auth/", "/v1/reauth/2fa/verify"];
14
+ /** A Next route handler for every method: export { handler as GET, ... }. */
15
+ export function createProxy(options = {}) {
16
+ const prefix = options.prefix ?? "/api/colveor";
17
+ // An error the page shows like the API's own ({ code, message }).
18
+ const fail = (status, code, message) => Response.json({ status, code, message }, { status });
19
+ const forward = async (req) => {
20
+ const apiUrl = (options.apiUrl ?? process.env.COLVEOR_API_URL ?? "").replace(/\/$/, "");
21
+ if (apiUrl === "") {
22
+ return fail(500, "admin.api_url_missing", "COLVEOR_API_URL is not set on the panel server.");
23
+ }
24
+ const url = new URL(req.url);
25
+ const path = url.pathname.slice(prefix.length) + url.search;
26
+ const secure = url.protocol === "https:";
27
+ const cookies = readCookies(req.headers.get("cookie"));
28
+ const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.arrayBuffer();
29
+ const send = (access) => fetch(apiUrl + path, {
30
+ method: req.method,
31
+ headers: forwardHeaders(req, access),
32
+ body,
33
+ redirect: "manual",
34
+ });
35
+ const setCookies = [];
36
+ let access = cookies[ACCESS];
37
+ // The access cookie expires a little before its token: refresh first.
38
+ if (access === undefined && cookies[REFRESH] !== undefined) {
39
+ access = await refreshInto(apiUrl, req, cookies[REFRESH], setCookies, secure);
40
+ }
41
+ let res = await send(access);
42
+ // An expired or outdated token (roles changed): refresh once and retry.
43
+ if (res.status === 401 && cookies[REFRESH] !== undefined && setCookies.length === 0) {
44
+ access = await refreshInto(apiUrl, req, cookies[REFRESH], setCookies, secure);
45
+ if (access !== undefined) {
46
+ res = await send(access);
47
+ }
48
+ }
49
+ if (path.startsWith("/v1/auth/logout")) {
50
+ setCookies.push(...clearCookies(secure));
51
+ }
52
+ if (res.ok && ISSUERS.some((p) => path.startsWith(p)) && isJSON(res)) {
53
+ const data = (await res.json());
54
+ if (data.access_token !== undefined) {
55
+ setCookies.push(...tokenCookies(data, secure));
56
+ data.access_token = undefined;
57
+ data.refresh_token = undefined;
58
+ }
59
+ return respond(res, JSON.stringify(data), setCookies);
60
+ }
61
+ return respond(res, res.body, setCookies);
62
+ };
63
+ return (req) => forward(req).catch(() => fail(502, "admin.api_unreachable", "The panel server could not reach the API."));
64
+ }
65
+ /** The proxy with the default options. */
66
+ export const handler = createProxy();
67
+ // A refresh token works once: the API ends the session when one is used
68
+ // twice. Requests that arrive together (a page loading its data) share one
69
+ // refresh, and a request that still carries the old cookie a moment later
70
+ // reuses its result. Kept in memory: run one panel server, or route a
71
+ // session to the same one.
72
+ const refreshes = new Map();
73
+ const REUSE_MS = 30_000;
74
+ async function refreshInto(apiUrl, req, refreshToken, setCookies, secure) {
75
+ const now = Date.now();
76
+ for (const [key, entry] of refreshes) {
77
+ if (now - entry.at > REUSE_MS) {
78
+ refreshes.delete(key);
79
+ }
80
+ }
81
+ let entry = refreshes.get(refreshToken);
82
+ if (entry === undefined) {
83
+ entry = {
84
+ at: now,
85
+ tokens: fetch(`${apiUrl}/v1/auth/refresh`, {
86
+ method: "POST",
87
+ headers: forwardHeaders(req, undefined, { "content-type": "application/json" }),
88
+ body: JSON.stringify({ refresh_token: refreshToken }),
89
+ }).then((res) => (res.ok ? res.json() : undefined)),
90
+ };
91
+ refreshes.set(refreshToken, entry);
92
+ }
93
+ const tokens = await entry.tokens.catch(() => undefined);
94
+ if (tokens?.access_token === undefined) {
95
+ setCookies.push(...clearCookies(secure));
96
+ return undefined;
97
+ }
98
+ setCookies.push(...tokenCookies(tokens, secure));
99
+ return tokens.access_token;
100
+ }
101
+ function forwardHeaders(req, access, extra = {}) {
102
+ const headers = new Headers();
103
+ for (const [name, value] of req.headers) {
104
+ if (!DROPPED.includes(name)) {
105
+ headers.set(name, value);
106
+ }
107
+ }
108
+ for (const [name, value] of Object.entries(extra)) {
109
+ headers.set(name, value);
110
+ }
111
+ if (access !== undefined) {
112
+ headers.set("authorization", `Bearer ${access}`);
113
+ }
114
+ return headers;
115
+ }
116
+ function tokenCookies(tokens, secure) {
117
+ // Gone a little before the token expires, so the next call refreshes
118
+ // instead of failing first.
119
+ const accessAge = Math.max((tokens.expires_in ?? 60) - 30, 1);
120
+ const out = [cookie(ACCESS, tokens.access_token ?? "", accessAge, secure)];
121
+ if (tokens.refresh_token !== undefined) {
122
+ // A session cookie: closing the browser signs the admin out.
123
+ out.push(cookie(REFRESH, tokens.refresh_token, undefined, secure));
124
+ }
125
+ return out;
126
+ }
127
+ function clearCookies(secure) {
128
+ return [cookie(ACCESS, "", 0, secure), cookie(REFRESH, "", 0, secure)];
129
+ }
130
+ function cookie(name, value, maxAge, secure) {
131
+ const parts = [`${name}=${encodeURIComponent(value)}`, "Path=/", "HttpOnly", "SameSite=Lax"];
132
+ if (maxAge !== undefined) {
133
+ parts.push(`Max-Age=${maxAge}`);
134
+ }
135
+ if (secure) {
136
+ parts.push("Secure");
137
+ }
138
+ return parts.join("; ");
139
+ }
140
+ function readCookies(header) {
141
+ const out = {};
142
+ for (const part of (header ?? "").split(";")) {
143
+ const i = part.indexOf("=");
144
+ if (i > 0) {
145
+ out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
146
+ }
147
+ }
148
+ return out;
149
+ }
150
+ function isJSON(res) {
151
+ return (res.headers.get("content-type") ?? "").includes("application/json");
152
+ }
153
+ function respond(res, body, setCookies) {
154
+ const headers = new Headers(res.headers);
155
+ // fetch already decoded the body.
156
+ headers.delete("content-encoding");
157
+ headers.delete("content-length");
158
+ for (const c of setCookies) {
159
+ headers.append("set-cookie", c);
160
+ }
161
+ return new Response(body, {
162
+ status: res.status,
163
+ statusText: res.statusText,
164
+ headers,
165
+ });
166
+ }
@@ -0,0 +1,8 @@
1
+ import type { SendOptions } from "./client";
2
+ export interface Asker {
3
+ /** Asks why the change is made. Rejects when the user cancels. */
4
+ reason(): Promise<string>;
5
+ /** Re-authenticates for action and returns the token. Rejects on cancel. */
6
+ stepUp(action: string, methods?: string[]): Promise<string>;
7
+ }
8
+ export declare function sendAsking<T>(send: (options: SendOptions) => Promise<T>, ask: Asker): Promise<T>;
package/dist/retry.js ADDED
@@ -0,0 +1,30 @@
1
+ // useAction's loop, apart from React so it can be tested: send, and when
2
+ // the API refuses for a missing reason or re-authentication, ask for it
3
+ // and send again. Only type imports, so node runs it as is.
4
+ export async function sendAsking(send, ask) {
5
+ let options = { idempotencyKey: crypto.randomUUID() };
6
+ for (;;) {
7
+ try {
8
+ return await send(options);
9
+ }
10
+ catch (err) {
11
+ const { code, data = {} } = (err ?? {});
12
+ // Each changed request gets a new key: the API keeps a refused
13
+ // response under its key, and would send the refusal again.
14
+ if (code === "request.reason_required") {
15
+ options = { ...options, reason: await ask.reason(), idempotencyKey: crypto.randomUUID() };
16
+ }
17
+ else if (code === "reauth.required") {
18
+ const methods = Array.isArray(data.methods) ? data.methods : undefined;
19
+ options = {
20
+ ...options,
21
+ reauthToken: await ask.stepUp(String(data.action ?? ""), methods),
22
+ idempotencyKey: crypto.randomUUID(),
23
+ };
24
+ }
25
+ else {
26
+ throw err;
27
+ }
28
+ }
29
+ }
30
+ }
@@ -0,0 +1,13 @@
1
+ import { type ComponentType, type ReactNode } from "react";
2
+ export interface LinkProps {
3
+ href: string;
4
+ className?: string;
5
+ onClick?: () => void;
6
+ children?: ReactNode;
7
+ }
8
+ export interface Router {
9
+ pathname: string;
10
+ navigate(href: string): void;
11
+ Link: ComponentType<LinkProps>;
12
+ }
13
+ export declare function browserRouter(): Router;
package/dist/router.js ADDED
@@ -0,0 +1,14 @@
1
+ // How the package's pages read the URL and move between pages without
2
+ // importing a framework: <ColveorAdmin router={...}> sets it. next.tsx has
3
+ // Next's; without one, the browser's own (full page loads).
4
+ import { createElement } from "react";
5
+ function BrowserLink(props) {
6
+ return createElement("a", props);
7
+ }
8
+ export function browserRouter() {
9
+ return {
10
+ pathname: typeof window === "undefined" ? "/" : window.location.pathname,
11
+ navigate: (href) => window.location.assign(href),
12
+ Link: BrowserLink,
13
+ };
14
+ }
@@ -0,0 +1,12 @@
1
+ import type * as settings from "./api/settings.gen";
2
+ type Setting = settings.SettingResponse;
3
+ export declare const input = "w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm text-gray-800 focus:border-brand-300 focus:outline-none focus:ring-3 focus:ring-brand-500/10 disabled:opacity-60 dark:border-gray-700 dark:text-white/90";
4
+ export declare function SettingRow(props: {
5
+ setting: Setting;
6
+ canManage: boolean;
7
+ onSaved(s: Setting): void;
8
+ }): import("react").JSX.Element;
9
+ export declare function SendTest({ channel }: {
10
+ channel: "sms" | "mail";
11
+ }): import("react").JSX.Element;
12
+ export {};
@@ -0,0 +1,102 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ // One setting's row on the settings page (its form for its type), and the
4
+ // test SMS or email the sms and mail settings can send.
5
+ import { useEffect, useState } from "react";
6
+ import { Cancelled, useAction } from "./actions";
7
+ import { api } from "./client";
8
+ import { InfoTip } from "./kit/tooltip";
9
+ import { MessageEditor } from "./message-editor";
10
+ import { ListSetting, listItems } from "./setting-list";
11
+ export const input = "w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm text-gray-800 focus:border-brand-300 focus:outline-none focus:ring-3 focus:ring-brand-500/10 disabled:opacity-60 dark:border-gray-700 dark:text-white/90";
12
+ export function SettingRow(props) {
13
+ const { setting: s, canManage } = props;
14
+ const [draft, setDraft] = useState(s.value);
15
+ const [error, setError] = useState("");
16
+ const [busy, setBusy] = useState(false);
17
+ const { run, dialogs } = useAction();
18
+ const editable = canManage && s.is_editable;
19
+ const [editing, setEditing] = useState(false);
20
+ useEffect(() => setDraft(s.value), [s.value]);
21
+ const save = async (event) => {
22
+ event.preventDefault();
23
+ setError("");
24
+ let value;
25
+ try {
26
+ value = parse(s.type, draft);
27
+ }
28
+ catch {
29
+ setError("This isn't valid JSON.");
30
+ return;
31
+ }
32
+ setBusy(true);
33
+ try {
34
+ props.onSaved(await run((o) => api.patch(`/v1/settings/${encodeURIComponent(s.key)}`, { value }, o)));
35
+ }
36
+ catch (err) {
37
+ if (!(err instanceof Cancelled)) {
38
+ setError(err instanceof Error ? err.message : String(err));
39
+ }
40
+ }
41
+ finally {
42
+ setBusy(false);
43
+ }
44
+ };
45
+ // A list of records: a table with a popup (setting-list.tsx).
46
+ const list = listItems(s);
47
+ if (list !== undefined) {
48
+ return _jsx(ListSetting, { setting: s, schema: list, editable: editable, onSaved: props.onSaved });
49
+ }
50
+ // The dialogs go beside the form: one has a form of its own.
51
+ return (_jsxs(_Fragment, { children: [_jsxs("form", { onSubmit: save, className: "grid gap-4 px-6 py-5 xl:grid-cols-[minmax(0,1fr)_minmax(0,18rem)_auto] xl:items-start", children: [_jsxs("div", { children: [_jsxs("p", { className: "flex items-center gap-2 font-medium text-gray-800 capitalize dark:text-white/90", children: [(s.key.split(".").pop() ?? s.key).replaceAll("_", " "), _jsx(InfoTip, { label: `About ${s.key}`, children: s.description })] }), _jsx("p", { className: "font-mono text-xs text-gray-400", children: s.key }), error !== "" && _jsx("p", { className: "mt-2 text-sm text-red-600", children: error })] }), s.is_message ? (_jsx("button", { type: "button", onClick: () => setEditing(true), className: "rounded-lg border border-brand-500 px-4 py-2 text-sm font-medium text-brand-500 transition-colors hover:bg-brand-500 hover:text-white", children: editable ? "Edit message" : "View message" })) : (_jsx(ValueInput, { setting: s, value: draft, disabled: !editable, onChange: setDraft })), editable && !s.is_message && (_jsx("button", { type: "submit", disabled: busy || draft === s.value, className: "rounded-lg bg-brand-500 px-4 py-2 text-sm font-medium text-white hover:bg-brand-600 disabled:opacity-40", children: "Save" }))] }), editing && (_jsx(MessageEditor, { setting: s, editable: editable, onSaved: props.onSaved, onClose: () => setEditing(false) })), dialogs] }));
52
+ }
53
+ function ValueInput(props) {
54
+ const { setting: s, value, disabled, onChange } = props;
55
+ const label = `Value of ${s.key}`;
56
+ switch (s.type) {
57
+ case "boolean":
58
+ return (_jsxs("label", { className: "flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300", children: [_jsx("input", { type: "checkbox", checked: value === "true", disabled: disabled, onChange: (e) => onChange(String(e.target.checked)), className: "size-5 rounded border-gray-300 text-brand-500" }), value === "true" ? "On" : "Off"] }));
59
+ case "number":
60
+ return (_jsx("input", { type: "number", step: "any", "aria-label": label, value: value, disabled: disabled, onChange: (e) => onChange(e.target.value), className: input }));
61
+ case "json":
62
+ return (_jsx("textarea", { "aria-label": label, rows: Math.min(8, value.split("\n").length + 1), value: value, disabled: disabled, onChange: (e) => onChange(e.target.value), className: `${input} font-mono text-xs` }));
63
+ default:
64
+ // A secret shows as its masked hint; sending the hint back keeps it.
65
+ return (_jsx("input", { type: s.type === "secret" ? "password" : "text", autoComplete: "off", "aria-label": label, value: value, disabled: disabled, onFocus: (e) => s.type === "secret" && e.target.select(), onChange: (e) => onChange(e.target.value), className: input }));
66
+ }
67
+ }
68
+ /** The value as the API takes it: a number, true or false, JSON, a string. */
69
+ function parse(type, draft) {
70
+ switch (type) {
71
+ case "number":
72
+ return Number(draft);
73
+ case "boolean":
74
+ return draft === "true";
75
+ case "json":
76
+ return JSON.parse(draft);
77
+ default:
78
+ return draft;
79
+ }
80
+ }
81
+ export function SendTest({ channel }) {
82
+ const [result, setResult] = useState("");
83
+ const [busy, setBusy] = useState(false);
84
+ const sms = channel === "sms";
85
+ const send = async (event) => {
86
+ event.preventDefault();
87
+ const to = String(new FormData(event.currentTarget).get("to"));
88
+ setBusy(true);
89
+ setResult("");
90
+ try {
91
+ await api.post(`/v1/settings/test/${channel}`, sms ? { phone: to } : { email: to });
92
+ setResult("Sent. Check that it arrived.");
93
+ }
94
+ catch (err) {
95
+ setResult(err instanceof Error ? err.message : String(err));
96
+ }
97
+ finally {
98
+ setBusy(false);
99
+ }
100
+ };
101
+ return (_jsxs("form", { onSubmit: send, className: "flex flex-wrap items-center gap-3 border-t border-gray-100 px-6 py-4 dark:border-gray-800", children: [_jsx("span", { className: "text-sm text-gray-700 dark:text-gray-300", children: sms ? "Send a test SMS to" : "Send a test email to" }), _jsx("input", { required: true, name: "to", type: sms ? "tel" : "email", placeholder: sms ? "+233201234567" : "you@example.com", "aria-label": sms ? "Phone number" : "Email address", className: `${input} max-w-60` }), _jsx("button", { type: "submit", disabled: busy, className: "rounded-lg border border-gray-300 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-40 dark:border-gray-700 dark:text-gray-300", children: "Send" }), result !== "" && _jsx("span", { className: "text-sm text-gray-500 dark:text-gray-400", children: result })] }));
102
+ }
@@ -0,0 +1,22 @@
1
+ import type * as settings from "./api/settings.gen";
2
+ type Setting = settings.SettingResponse;
3
+ interface Field {
4
+ title?: string;
5
+ description?: string;
6
+ pattern?: string;
7
+ }
8
+ interface ItemSchema {
9
+ title?: string;
10
+ required?: string[];
11
+ "x-order"?: string[];
12
+ properties?: Record<string, Field>;
13
+ }
14
+ /** The schema of a list setting's records, or undefined for another kind. */
15
+ export declare function listItems(s: Setting): ItemSchema | undefined;
16
+ export declare function ListSetting(props: {
17
+ setting: Setting;
18
+ schema: ItemSchema;
19
+ editable: boolean;
20
+ onSaved(s: Setting): void;
21
+ }): import("react").JSX.Element;
22
+ export {};
@@ -0,0 +1,78 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ // A setting that is a list of records (its schema: an array of objects,
4
+ // such as verification.test_phones): a table, and a popup to add or edit
5
+ // one, like Firebase's test phone numbers. Each change saves the whole
6
+ // list at once, through the usual PATCH (with its reason); the API checks
7
+ // it again.
8
+ import { useState } from "react";
9
+ import { Cancelled, useAction } from "./actions";
10
+ import { api } from "./client";
11
+ import { RowMenu } from "./kit/dropdown";
12
+ import { Modal } from "./kit/modal";
13
+ import { InfoTip } from "./kit/tooltip";
14
+ import { input } from "./setting-fields";
15
+ import { Alert } from "./ui";
16
+ /** The schema of a list setting's records, or undefined for another kind. */
17
+ export function listItems(s) {
18
+ const schema = s.schema;
19
+ return schema?.type === "array" && schema.items?.type === "object" ? schema.items : undefined;
20
+ }
21
+ export function ListSetting(props) {
22
+ const { setting: s, schema, editable } = props;
23
+ const items = JSON.parse(s.value || "[]");
24
+ const fields = schema["x-order"] ?? Object.keys(schema.properties ?? {});
25
+ const noun = schema.title ?? "Item";
26
+ // The record open in the popup: its index, or -1 for a new one.
27
+ const [open, setOpen] = useState(null);
28
+ const [error, setError] = useState("");
29
+ const [busy, setBusy] = useState(false);
30
+ const { run, dialogs } = useAction();
31
+ const save = async (list) => {
32
+ setError("");
33
+ setBusy(true);
34
+ try {
35
+ props.onSaved(await run((o) => api.patch(`/v1/settings/${encodeURIComponent(s.key)}`, { value: list }, o)));
36
+ setOpen(null);
37
+ }
38
+ catch (err) {
39
+ if (!(err instanceof Cancelled)) {
40
+ setError(err instanceof Error ? err.message : String(err));
41
+ }
42
+ }
43
+ finally {
44
+ setBusy(false);
45
+ }
46
+ };
47
+ const remove = (i) => {
48
+ if (window.confirm(`Remove ${items[i][fields[0]] ?? "this one"}?`)) {
49
+ save(items.filter((_, j) => j !== i));
50
+ }
51
+ };
52
+ return (_jsxs("div", { className: "px-6 py-5", children: [_jsxs("div", { className: "flex flex-wrap items-start justify-between gap-3", children: [_jsxs("div", { children: [_jsxs("p", { className: "flex items-center gap-2 font-medium text-gray-800 capitalize dark:text-white/90", children: [(s.key.split(".").pop() ?? s.key).replaceAll("_", " "), _jsx(InfoTip, { label: `About ${s.key}`, children: s.description })] }), _jsx("p", { className: "font-mono text-xs text-gray-400", children: s.key })] }), editable && (_jsxs("button", { type: "button", onClick: () => {
53
+ setError("");
54
+ setOpen(-1);
55
+ }, className: "rounded-lg bg-brand-500 px-4 py-2 text-sm font-medium text-white hover:bg-brand-600", children: ["Add ", noun.toLowerCase()] }))] }), error !== "" && open === null && (_jsx("div", { className: "mt-3", children: _jsx(Alert, { children: error }) })), _jsxs("div", { className: "mt-4 overflow-x-auto rounded-xl border border-gray-200 dark:border-gray-800", children: [_jsxs("table", { className: "min-w-full text-left text-sm", children: [_jsx("thead", { className: "border-b border-gray-200 bg-gray-50/50 text-gray-500 dark:border-gray-800 dark:bg-white/[0.02] dark:text-gray-400", children: _jsxs("tr", { children: [fields.map((f) => (_jsx("th", { className: "px-4 py-2.5 font-medium", children: schema.properties?.[f]?.title ?? f }, f))), editable && _jsx("th", { className: "w-12 px-4 py-2.5" })] }) }), _jsx("tbody", { className: "divide-y divide-gray-100 text-gray-800 dark:divide-gray-800 dark:text-white/90", children: items.map((item, i) => (_jsxs("tr", { children: [fields.map((f) => (_jsx("td", { className: "px-4 py-2.5 font-mono text-xs", children: item[f] ?? "" }, f))), editable && (_jsx("td", { className: "px-2 py-1 text-right", children: _jsx(RowMenu, { items: [
56
+ {
57
+ label: "Edit",
58
+ onSelect: () => {
59
+ setError("");
60
+ setOpen(i);
61
+ },
62
+ },
63
+ { label: "Remove", danger: true, onSelect: () => remove(i) },
64
+ ] }) }))] }, `${item[fields[0]]}-${i}`))) })] }), items.length === 0 && (_jsxs("p", { className: "px-4 py-4 text-sm text-gray-500 dark:text-gray-400", children: ["None yet", editable ? `: add a ${noun.toLowerCase()} to start.` : "."] }))] }), open !== null && (_jsx(ItemForm, { title: open === -1 ? `Add ${noun.toLowerCase()}` : `Edit ${noun.toLowerCase()}`, schema: schema, fields: fields, item: open === -1 ? {} : items[open], busy: busy, error: error, dialogs: dialogs, onClose: () => setOpen(null), onSave: (item) => save(open === -1 ? [...items, item] : items.map((x, j) => (j === open ? item : x))) })), open === null && dialogs] }));
65
+ }
66
+ function ItemForm(props) {
67
+ const submit = (event) => {
68
+ event.preventDefault();
69
+ const data = new FormData(event.currentTarget);
70
+ props.onSave(Object.fromEntries(props.fields.map((f) => [f, String(data.get(f) ?? "").trim()])));
71
+ };
72
+ return (_jsxs(Modal, { title: props.title, onClose: props.onClose, children: [_jsxs("form", { onSubmit: submit, className: "space-y-4", children: [props.error !== "" && _jsx(Alert, { children: props.error }), props.fields.map((f, i) => {
73
+ const field = props.schema.properties?.[f] ?? {};
74
+ return (_jsxs("label", { className: "block", children: [_jsx("span", { className: "mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-300", children: field.title ?? f }), _jsx("input", { name: f, defaultValue: props.item[f] ?? "", required: props.schema.required?.includes(f), pattern: field.pattern, title: field.description,
75
+ // biome-ignore lint/a11y/noAutofocus: the popup opens to type in it
76
+ autoFocus: i === 0, className: `${input} font-mono` }), field.description && (_jsx("span", { className: "mt-1 block text-xs text-gray-500 dark:text-gray-400", children: field.description }))] }, f));
77
+ }), _jsxs("div", { className: "flex justify-end gap-3 pt-2", children: [_jsx("button", { type: "button", onClick: props.onClose, className: "rounded-lg border border-gray-300 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-white/5", children: "Cancel" }), _jsx("button", { type: "submit", disabled: props.busy, className: "rounded-lg bg-brand-500 px-5 py-2 text-sm font-medium text-white hover:bg-brand-600 disabled:opacity-40", children: "Save" })] })] }), props.dialogs] }));
78
+ }
@@ -0,0 +1,40 @@
1
+ import { type ReactNode } from "react";
2
+ import { type AdminConfig, type NavItem } from "./config";
3
+ import { type Router } from "./router";
4
+ interface Admin {
5
+ config: AdminConfig;
6
+ router: Router;
7
+ roles: string[];
8
+ permissions: Set<string>;
9
+ }
10
+ /** The panel's config and router, on any page under <ColveorAdmin>. */
11
+ export declare function useConfig(): {
12
+ config: AdminConfig;
13
+ router: Router;
14
+ };
15
+ /** The pages shown before sign-in: they skip the permission check. */
16
+ export declare function isPublicPath(config: AdminConfig, pathname: string): boolean;
17
+ export interface ColveorAdminProps {
18
+ config: AdminConfig;
19
+ /** Default: the browser's (full page loads). Next: @colveor/admin/next. */
20
+ router?: Router;
21
+ children: ReactNode;
22
+ }
23
+ export declare function ColveorAdmin({ config, router, children }: ColveorAdminProps): import("react").JSX.Element | null;
24
+ /** The config, the router and the signed-in user's roles and permissions. */
25
+ export declare function useAdmin(): Admin;
26
+ /** Whether the signed-in user holds every one of these permissions. */
27
+ export declare function useCan(...keys: string[]): boolean;
28
+ /** Shows children only to users holding every one of keys. */
29
+ export declare function RequirePermission(props: {
30
+ keys: string[];
31
+ fallback?: ReactNode;
32
+ children: ReactNode;
33
+ }): ReactNode;
34
+ /** The menu this user may open: the framework's pages, then the project's. */
35
+ export declare function useNav(): NavItem[];
36
+ /** A plain frame (menu and header) for a panel whose template has none. */
37
+ export declare function AdminLayout({ children }: {
38
+ children: ReactNode;
39
+ }): import("react").JSX.Element;
40
+ export {};
package/dist/shell.js ADDED
@@ -0,0 +1,97 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ // The shell: signs the user in when needed, loads what they may do, and
4
+ // gives the pages the config, the router and the permission checks.
5
+ import { createContext, useContext, useEffect, useMemo, useState } from "react";
6
+ import { ApiError, call, signOut } from "./client";
7
+ import { coreNav } from "./config";
8
+ import { browserRouter } from "./router";
9
+ const AdminContext = createContext(null);
10
+ // The config and router, for every page, signed in or not (sign in, forgot
11
+ // password).
12
+ const ConfigContext = createContext(null);
13
+ /** The panel's config and router, on any page under <ColveorAdmin>. */
14
+ export function useConfig() {
15
+ const c = useContext(ConfigContext);
16
+ if (c === null) {
17
+ throw new Error("useConfig is used outside <ColveorAdmin>");
18
+ }
19
+ return c;
20
+ }
21
+ /** The pages shown before sign-in: they skip the permission check. */
22
+ export function isPublicPath(config, pathname) {
23
+ const signIn = config.signInPath ?? "/login";
24
+ return pathname === signIn || pathname === "/forgot-password";
25
+ }
26
+ export function ColveorAdmin({ config, router, children }) {
27
+ const r = useMemo(() => router ?? browserRouter(), [router]);
28
+ const signInPath = config.signInPath ?? "/login";
29
+ const onSignIn = isPublicPath(config, r.pathname);
30
+ const [me, setMe] = useState(null);
31
+ const [failed, setFailed] = useState("");
32
+ useEffect(() => {
33
+ if (onSignIn) {
34
+ return;
35
+ }
36
+ call("/v1/rbac/me/permissions")
37
+ .then(setMe)
38
+ .catch((err) => {
39
+ if (err instanceof ApiError && err.status === 401) {
40
+ r.navigate(`${signInPath}?next=${encodeURIComponent(r.pathname)}`);
41
+ }
42
+ else {
43
+ setFailed(err instanceof Error ? err.message : String(err));
44
+ }
45
+ });
46
+ // Again on each page (the router changes with the path): a role
47
+ // change shows on the next page.
48
+ }, [onSignIn, signInPath, r]);
49
+ const admin = useMemo(() => me && {
50
+ config,
51
+ router: r,
52
+ roles: me.roles,
53
+ permissions: new Set(me.permissions),
54
+ }, [me, config, r]);
55
+ const shared = useMemo(() => ({ config, router: r }), [config, r]);
56
+ if (onSignIn) {
57
+ return _jsx(ConfigContext.Provider, { value: shared, children: children });
58
+ }
59
+ if (failed !== "") {
60
+ return (_jsxs("p", { role: "alert", className: "p-6 text-sm text-red-600", children: ["The panel could not reach the API: ", failed] }));
61
+ }
62
+ if (admin === null) {
63
+ return null;
64
+ }
65
+ return (_jsx(ConfigContext.Provider, { value: shared, children: _jsx(AdminContext.Provider, { value: admin, children: children }) }));
66
+ }
67
+ /** The config, the router and the signed-in user's roles and permissions. */
68
+ export function useAdmin() {
69
+ const admin = useContext(AdminContext);
70
+ if (admin === null) {
71
+ throw new Error("useAdmin is used outside <ColveorAdmin>");
72
+ }
73
+ return admin;
74
+ }
75
+ /** Whether the signed-in user holds every one of these permissions. */
76
+ export function useCan(...keys) {
77
+ const { permissions } = useAdmin();
78
+ return keys.every((k) => permissions.has(k));
79
+ }
80
+ /** Shows children only to users holding every one of keys. */
81
+ export function RequirePermission(props) {
82
+ return useCan(...props.keys) ? props.children : (props.fallback ?? null);
83
+ }
84
+ /** The menu this user may open: the framework's pages, then the project's. */
85
+ export function useNav() {
86
+ const { config, permissions } = useAdmin();
87
+ return [...coreNav, ...(config.nav ?? [])].filter((item) => item.permission === undefined || [item.permission].flat().some((p) => permissions.has(p)));
88
+ }
89
+ /** A plain frame (menu and header) for a panel whose template has none. */
90
+ export function AdminLayout({ children }) {
91
+ const { config, router } = useAdmin();
92
+ const nav = useNav();
93
+ const { Link } = router;
94
+ return (_jsxs("div", { className: "flex min-h-screen bg-gray-50 dark:bg-gray-900", children: [_jsxs("aside", { className: "w-64 shrink-0 border-r border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-gray-900", children: [_jsxs("div", { className: "mb-8 flex items-center gap-3", children: [config.logo !== undefined && _jsx("img", { src: config.logo, alt: "", className: "h-8" }), _jsx("span", { className: "text-lg font-medium text-gray-800 dark:text-white/90", children: config.name })] }), _jsx("nav", { className: "space-y-1", children: nav.map((item) => (_jsx(Link, { href: item.href, className: `block rounded-lg px-3 py-2 text-sm ${router.pathname.startsWith(item.href)
95
+ ? "bg-brand-50 text-brand-500"
96
+ : "text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-white/5"}`, children: item.label }, item.href))) })] }), _jsxs("div", { className: "flex-1", children: [_jsx("header", { className: "flex justify-end border-b border-gray-200 bg-white px-6 py-3 dark:border-gray-800 dark:bg-gray-900", children: _jsx("button", { type: "button", onClick: () => signOut(config.signInPath), className: "text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400", children: "Sign out" }) }), _jsx("main", { className: "p-6", children: children })] })] }));
97
+ }
@@ -0,0 +1,37 @@
1
+ import { type ReactNode } from "react";
2
+ import * as support from "./api/support_access.gen";
3
+ import { type SendOptions } from "./client";
4
+ export type Grant = support.GrantResponse;
5
+ export declare function GrantStatus({ grant }: {
6
+ grant: Grant;
7
+ }): import("react").JSX.Element;
8
+ /** The columns every grant table shows; extra ones go after. */
9
+ export declare function grantColumns(extra?: {
10
+ header: string;
11
+ cell(g: Grant): ReactNode;
12
+ }[]): ({
13
+ header: string;
14
+ cell(g: Grant): ReactNode;
15
+ } | {
16
+ header: string;
17
+ cell: (g: Grant) => import("react").JSX.Element;
18
+ })[];
19
+ /** Runs a change on a grant, showing its error; bumps reload after. */
20
+ export declare function useGrantChange(): {
21
+ change: (send: (o: SendOptions) => Promise<unknown>) => Promise<void>;
22
+ error: string;
23
+ reload: number;
24
+ refresh: () => void;
25
+ dialogs: ReactNode;
26
+ };
27
+ /**
28
+ * The support grants on team and the teams below it, with Approve and Deny
29
+ * for a pending one and Revoke for an open one. Needs support.manage in the
30
+ * team, from the user's own role.
31
+ */
32
+ export declare function TeamSupportGrants({ team }: {
33
+ team: {
34
+ kind: string;
35
+ id: string;
36
+ };
37
+ }): import("react").JSX.Element;