@seip/bluebird-js 0.1.7 → 0.2.1
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/AGENTS.md +727 -620
- package/README.md +670 -607
- package/app/models/user.js +19 -0
- package/app/resources/html/home.html +137 -0
- package/app/resources/html/layouts/main.html +55 -0
- package/app/resources/html/notFound.html +14 -0
- package/app/resources/html/table.html +15 -0
- package/app/resources/html/terms.html +46 -0
- package/app/resources/index.html +27 -0
- package/app/resources/layouts/AppLayout.jsx +92 -0
- package/app/resources/main.jsx +18 -0
- package/app/resources/pages/Dashboard.jsx +93 -0
- package/app/resources/pages/Home.jsx +140 -0
- package/app/resources/pages/Login.jsx +35 -0
- package/app/resources/pages/NotFound.jsx +16 -0
- package/app/resources/pages/Register.jsx +55 -0
- package/app/resources/pages/TableDemo.jsx +85 -0
- package/app/resources/routes.jsx +59 -0
- package/app/resources/spa.js +73 -0
- package/app/resources/styles.css +9 -0
- package/app/routes/api.js +129 -50
- package/app/routes/auth.js +209 -0
- package/app/routes/web.js +89 -47
- package/core/ai.js +30 -10
- package/core/app.d.ts +2 -18
- package/core/app.js +987 -801
- package/core/auth.d.ts +2 -13
- package/core/auth.js +444 -326
- package/core/cli/build.js +37 -0
- package/core/cli/dev.js +155 -0
- package/core/cli/doctor.js +37 -2
- package/core/cli/export.js +191 -0
- package/core/cli/init.js +91 -322
- package/core/cli/nginx.js +1 -1
- package/core/cli/templates.js +139 -0
- package/core/cli/view.js +98 -161
- package/core/config.js +44 -2
- package/core/csrf.js +156 -24
- package/core/database.js +1184 -1131
- package/core/debug.js +1 -1
- package/core/html.js +8 -1
- package/core/index.d.ts +126 -310
- package/core/paths.js +55 -0
- package/core/ratelimit.js +10 -1
- package/core/react/client/api.js +239 -0
- package/core/react/client/auth.js +236 -0
- package/core/react/client/components.js +1321 -0
- package/core/react/client/datatable.js +595 -0
- package/core/react/client/i18n.js +440 -0
- package/core/react/client/index.d.ts +314 -0
- package/core/react/client/index.js +50 -0
- package/core/react/client/router.js +26 -0
- package/core/react/client/theme.css +512 -0
- package/core/render-cache.js +250 -212
- package/core/render.d.ts +25 -21
- package/core/render.js +738 -736
- package/core/router.d.ts +2 -3
- package/core/router.js +171 -171
- package/core/seo.js +10 -0
- package/core/spa.js +599 -0
- package/core/view-loader.js +155 -613
- package/core/vite-plugin.d.ts +18 -0
- package/core/vite-plugin.js +162 -0
- package/core/vite.js +250 -145
- package/index.js +22 -18
- package/jsconfig.json +5 -3
- package/package.json +114 -92
- package/production.md +8 -3
- package/public/js/bluebird.js +1886 -0
- package/templates/_auth/app/database.js +19 -0
- package/templates/_auth/app/models/user.js +22 -0
- package/templates/_auth/app/routes/auth-router.js +304 -0
- package/templates/_base/app/resources/html/layouts/main.html +55 -0
- package/templates/_base/app/resources/html/notFound.html +14 -0
- package/templates/_base/app/resources/index.html +27 -0
- package/templates/_base/app/resources/styles.css +9 -0
- package/templates/api/app/models/note.js +18 -0
- package/templates/api/app/routes/api.js +82 -0
- package/templates/api/app/routes/auth.js +11 -0
- package/templates/api/index.js +19 -0
- package/templates/api/template.json +13 -0
- package/templates/auth/app/mail.js +11 -0
- package/templates/auth/app/models/password_reset.js +18 -0
- package/templates/auth/app/resources/html/home.html +21 -0
- package/templates/auth/app/resources/html/partials/nav.html +2 -0
- package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
- package/templates/auth/app/resources/main.jsx +18 -0
- package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
- package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
- package/templates/auth/app/resources/pages/Login.jsx +36 -0
- package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
- package/templates/auth/app/resources/pages/Profile.jsx +99 -0
- package/templates/auth/app/resources/pages/Register.jsx +50 -0
- package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
- package/templates/auth/app/resources/routes.jsx +54 -0
- package/templates/auth/app/resources/spa.js +29 -0
- package/templates/auth/app/routes/api.js +17 -0
- package/templates/auth/app/routes/auth.js +13 -0
- package/templates/auth/app/routes/web.js +21 -0
- package/templates/auth/index.js +19 -0
- package/templates/auth/template.json +15 -0
- package/templates/blank/app/models/.gitkeep +0 -0
- package/templates/blank/app/resources/html/home.html +27 -0
- package/templates/blank/app/resources/html/partials/nav.html +1 -0
- package/templates/blank/app/resources/main.jsx +16 -0
- package/templates/blank/app/resources/pages/Home.jsx +42 -0
- package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
- package/templates/blank/app/resources/routes.jsx +15 -0
- package/templates/blank/app/resources/spa.js +24 -0
- package/templates/blank/app/routes/api.js +11 -0
- package/templates/blank/app/routes/web.js +21 -0
- package/templates/blank/index.js +13 -0
- package/templates/blank/template.json +12 -0
- package/templates/blog/app/lib/blog.js +149 -0
- package/templates/blog/app/models/post.js +22 -0
- package/templates/blog/app/resources/html/home.html +28 -0
- package/templates/blog/app/resources/html/not-found.html +5 -0
- package/templates/blog/app/resources/html/partials/nav.html +2 -0
- package/templates/blog/app/resources/html/partials/post-card.html +9 -0
- package/templates/blog/app/resources/html/post.html +8 -0
- package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
- package/templates/blog/app/resources/main.jsx +18 -0
- package/templates/blog/app/resources/pages/Login.jsx +31 -0
- package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
- package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
- package/templates/blog/app/resources/pages/Posts.jsx +83 -0
- package/templates/blog/app/resources/pages/Register.jsx +43 -0
- package/templates/blog/app/resources/routes.jsx +51 -0
- package/templates/blog/app/resources/spa.js +25 -0
- package/templates/blog/app/resources/styles.css +40 -0
- package/templates/blog/app/routes/api.js +77 -0
- package/templates/blog/app/routes/auth.js +10 -0
- package/templates/blog/app/routes/web.js +114 -0
- package/templates/blog/index.js +21 -0
- package/templates/blog/template.json +14 -0
- package/vite.config.js +11 -0
- package/app/views/components/Header.jsx +0 -42
- package/app/views/components/LiveCounter.jsx +0 -67
- package/app/views/layouts/main/view.jsx +0 -201
- package/app/views/legal/terms.html +0 -29
- package/app/views/pages/about.jsx +0 -98
- package/app/views/pages/dashboard.jsx +0 -278
- package/app/views/pages/index.jsx +0 -123
- package/app/views/pages/login.jsx +0 -141
- package/core/actions.d.ts +0 -4
- package/core/actions.js +0 -355
- package/core/jsx.d.ts +0 -38
- package/core/jsx.js +0 -1597
- package/core/vite.d.ts +0 -3
- package/public/js/bluebird-client.js +0 -3265
- package/public/js/tailwind.js +0 -8
package/core/ratelimit.js
CHANGED
|
@@ -7,6 +7,13 @@ import { getRedisClient } from "./cache.js";
|
|
|
7
7
|
*/
|
|
8
8
|
const memoryBuckets = new Map();
|
|
9
9
|
|
|
10
|
+
/**
|
|
11
|
+
* Monotonic counter used to isolate the buckets of each limiter instance, so a global limiter
|
|
12
|
+
* and a per-route limiter never share (and double count) the same client key.
|
|
13
|
+
* @type {number}
|
|
14
|
+
*/
|
|
15
|
+
let limiterInstanceCounter = 0;
|
|
16
|
+
|
|
10
17
|
setInterval(() => {
|
|
11
18
|
if (memoryBuckets.size === 0) return;
|
|
12
19
|
const now = Date.now();
|
|
@@ -32,6 +39,7 @@ class RateLimit {
|
|
|
32
39
|
* @param {"memory"|"redis"} [options.driver="memory"] - Storage backend.
|
|
33
40
|
* @param {Function} [options.keyGenerator] - Custom key generator: (req) => string.
|
|
34
41
|
* @param {Function} [options.skip] - Predicate to bypass rate limiting: (req) => boolean.
|
|
42
|
+
* @param {string} [options.prefix] - Bucket namespace (defaults to a deterministic per-instance id).
|
|
35
43
|
* @returns {Function} Express middleware function.
|
|
36
44
|
*/
|
|
37
45
|
static middleware(options = {}) {
|
|
@@ -46,13 +54,14 @@ class RateLimit {
|
|
|
46
54
|
? options.keyGenerator
|
|
47
55
|
: (req) => req.ip || req.socket?.remoteAddress || "unknown";
|
|
48
56
|
const skip = typeof options.skip === "function" ? options.skip : null;
|
|
57
|
+
const prefix = options.prefix ?? `i${++limiterInstanceCounter}`;
|
|
49
58
|
|
|
50
59
|
return async (req, res, next) => {
|
|
51
60
|
if (skip && skip(req)) {
|
|
52
61
|
return next();
|
|
53
62
|
}
|
|
54
63
|
|
|
55
|
-
const clientKey = `rl:${keyGenerator(req)}`;
|
|
64
|
+
const clientKey = `rl:${prefix}:${keyGenerator(req)}`;
|
|
56
65
|
const now = Date.now();
|
|
57
66
|
let count = 0;
|
|
58
67
|
let resetTime = now + windowMs;
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { t as translate } from "./i18n.js";
|
|
2
|
+
|
|
3
|
+
const isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Build-time configuration injected by `npx bluebird-js export` (`null` on the web server build).
|
|
7
|
+
* @type {{ apiUrl?: string, router?: "hash"|"browser"|"memory", basename?: string, auth?: "token"|"cookie" }|null}
|
|
8
|
+
*/
|
|
9
|
+
const EXPORT_CONFIG = typeof __BLUEBIRD_EXPORT__ !== "undefined" ? __BLUEBIRD_EXPORT__ : null;
|
|
10
|
+
|
|
11
|
+
const TOKEN_STORAGE_KEY = "bb-auth-token";
|
|
12
|
+
|
|
13
|
+
let apiBaseUrl = String(EXPORT_CONFIG?.apiUrl || "").replace(/\/+$/, "");
|
|
14
|
+
let authMode = EXPORT_CONFIG ? EXPORT_CONFIG.auth || "token" : "cookie";
|
|
15
|
+
let memoryToken = "";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Returns the static export configuration, or `null` when running from the Bluebird server.
|
|
19
|
+
* @returns {{ apiUrl?: string, router?: string, basename?: string, auth?: string }|null}
|
|
20
|
+
*/
|
|
21
|
+
export function getExportConfig() {
|
|
22
|
+
return EXPORT_CONFIG;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Checks whether the app runs from a static `npx bluebird-js export` build (Electron, Capacitor, any static host).
|
|
27
|
+
* @returns {boolean}
|
|
28
|
+
*/
|
|
29
|
+
export function isExported() {
|
|
30
|
+
return EXPORT_CONFIG !== null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Configures an optional base URL prepended to relative `/api/*` requests (useful for Electron/Capacitor builds).
|
|
35
|
+
* @param {string} baseUrl
|
|
36
|
+
*/
|
|
37
|
+
export function setApiBaseUrl(baseUrl) {
|
|
38
|
+
apiBaseUrl = String(baseUrl || "").replace(/\/+$/, "");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Configures the API client.
|
|
43
|
+
* - `auth: "cookie"` (web default): HttpOnly session cookie + `X-CSRF-Token` header.
|
|
44
|
+
* - `auth: "token"` (export default): `Authorization: Bearer` token stored in `localStorage`, no cookies.
|
|
45
|
+
* @param {{ baseUrl?: string, auth?: "cookie"|"token" }} [options={}]
|
|
46
|
+
*/
|
|
47
|
+
export function configureApi(options = {}) {
|
|
48
|
+
if (options.baseUrl !== undefined) setApiBaseUrl(options.baseUrl);
|
|
49
|
+
if (options.auth === "cookie" || options.auth === "token") authMode = options.auth;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Returns the active authentication transport (`"cookie"` or `"token"`).
|
|
54
|
+
* @returns {"cookie"|"token"}
|
|
55
|
+
*/
|
|
56
|
+
export function getAuthMode() {
|
|
57
|
+
return authMode === "token" ? "token" : "cookie";
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Returns the stored bearer token used in `"token"` auth mode.
|
|
62
|
+
* @returns {string}
|
|
63
|
+
*/
|
|
64
|
+
export function getAuthToken() {
|
|
65
|
+
try {
|
|
66
|
+
return window.localStorage.getItem(TOKEN_STORAGE_KEY) || memoryToken;
|
|
67
|
+
} catch {
|
|
68
|
+
return memoryToken;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Stores (or clears with `null`) the bearer token used in `"token"` auth mode.
|
|
74
|
+
* @param {string|null} token
|
|
75
|
+
*/
|
|
76
|
+
export function setAuthToken(token) {
|
|
77
|
+
memoryToken = token ? String(token) : "";
|
|
78
|
+
try {
|
|
79
|
+
if (memoryToken) window.localStorage.setItem(TOKEN_STORAGE_KEY, memoryToken);
|
|
80
|
+
else window.localStorage.removeItem(TOKEN_STORAGE_KEY);
|
|
81
|
+
} catch {}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Returns the configured API base URL.
|
|
86
|
+
* @returns {string}
|
|
87
|
+
*/
|
|
88
|
+
export function getApiBaseUrl() {
|
|
89
|
+
return apiBaseUrl;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Reads the double-submit CSRF token from the `_csrf` cookie.
|
|
94
|
+
* @returns {string}
|
|
95
|
+
*/
|
|
96
|
+
export function getCsrfToken() {
|
|
97
|
+
if (!isBrowser) return "";
|
|
98
|
+
const match = document.cookie.match(/(?:^|;\s*)_csrf=([^;]*)/);
|
|
99
|
+
if (!match?.[1]) return "";
|
|
100
|
+
try {
|
|
101
|
+
return decodeURIComponent(match[1]);
|
|
102
|
+
} catch {
|
|
103
|
+
return match[1];
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Normalizes array or object validation error payloads into a field-keyed map.
|
|
109
|
+
* @param {any} errors
|
|
110
|
+
* @returns {Record<string, string>|null}
|
|
111
|
+
*/
|
|
112
|
+
function normalizeErrors(errors) {
|
|
113
|
+
if (!errors) return null;
|
|
114
|
+
if (Array.isArray(errors)) {
|
|
115
|
+
const out = {};
|
|
116
|
+
for (const item of errors) {
|
|
117
|
+
if (item && typeof item === "object" && item.field && !out[item.field]) {
|
|
118
|
+
out[item.field] = String(item.message || translate("value.invalid"));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return Object.keys(out).length ? out : null;
|
|
122
|
+
}
|
|
123
|
+
if (typeof errors === "object") {
|
|
124
|
+
return errors;
|
|
125
|
+
}
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Error thrown by `api()` when an HTTP request fails or returns an error envelope.
|
|
131
|
+
*/
|
|
132
|
+
export class ApiError extends Error {
|
|
133
|
+
/**
|
|
134
|
+
* @param {string} message
|
|
135
|
+
* @param {{ status?: number, data?: any, errors?: any }} [info]
|
|
136
|
+
*/
|
|
137
|
+
constructor(message, info = {}) {
|
|
138
|
+
super(message);
|
|
139
|
+
this.name = "ApiError";
|
|
140
|
+
this.status = info.status || 0;
|
|
141
|
+
this.data = info.data ?? null;
|
|
142
|
+
this.errors = normalizeErrors(info.errors);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Resolves a request URL against the configured API base URL when applicable.
|
|
148
|
+
* @param {string} url
|
|
149
|
+
* @returns {string}
|
|
150
|
+
*/
|
|
151
|
+
function resolveUrl(url) {
|
|
152
|
+
if (!apiBaseUrl || /^https?:\/\//i.test(url)) return url;
|
|
153
|
+
return `${apiBaseUrl}${url.startsWith("/") ? url : `/${url}`}`;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Sends a fetch request to a Bluebird REST endpoint with credentials and the `X-CSRF-Token` header.
|
|
158
|
+
* Automatically serializes JSON bodies, parses JSON responses, and throws `ApiError` on failure.
|
|
159
|
+
* @template T
|
|
160
|
+
* @param {string} url
|
|
161
|
+
* @param {Object} [options={}]
|
|
162
|
+
* @param {string} [options.method="GET"]
|
|
163
|
+
* @param {any} [options.body]
|
|
164
|
+
* @param {Record<string, string>} [options.headers]
|
|
165
|
+
* @param {RequestCredentials} [options.credentials]
|
|
166
|
+
* @param {AbortSignal} [options.signal]
|
|
167
|
+
* @param {boolean} [options.raw=false] - Return the whole JSON body (e.g. `{ data, pagination }` from `res.paginate`) instead of only `data`.
|
|
168
|
+
* @returns {Promise<T>}
|
|
169
|
+
*/
|
|
170
|
+
export async function api(url, options = {}) {
|
|
171
|
+
const method = String(options.method || (options.body !== undefined ? "POST" : "GET")).toUpperCase();
|
|
172
|
+
const isForm = typeof FormData !== "undefined" && options.body instanceof FormData;
|
|
173
|
+
const headers = {
|
|
174
|
+
Accept: "application/json",
|
|
175
|
+
...(options.headers || {}),
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
const tokenMode = authMode === "token";
|
|
179
|
+
if (tokenMode) {
|
|
180
|
+
headers["X-Auth-Mode"] = "token";
|
|
181
|
+
const token = getAuthToken();
|
|
182
|
+
if (token && !headers.Authorization) headers.Authorization = `Bearer ${token}`;
|
|
183
|
+
} else if (method !== "GET" && method !== "HEAD") {
|
|
184
|
+
const csrf = getCsrfToken();
|
|
185
|
+
if (csrf && !headers["X-CSRF-Token"]) {
|
|
186
|
+
headers["X-CSRF-Token"] = csrf;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (!isForm && options.body !== undefined && !headers["Content-Type"]) {
|
|
191
|
+
headers["Content-Type"] = "application/json";
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const res = await fetch(resolveUrl(url), {
|
|
195
|
+
method,
|
|
196
|
+
credentials: options.credentials || (tokenMode ? "omit" : apiBaseUrl ? "include" : "same-origin"),
|
|
197
|
+
headers,
|
|
198
|
+
signal: options.signal,
|
|
199
|
+
body:
|
|
200
|
+
method === "GET" || method === "HEAD" || options.body === undefined
|
|
201
|
+
? undefined
|
|
202
|
+
: isForm || typeof options.body === "string"
|
|
203
|
+
? options.body
|
|
204
|
+
: JSON.stringify(options.body),
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
let data = null;
|
|
208
|
+
const contentType = res.headers.get("Content-Type") || "";
|
|
209
|
+
if (contentType.includes("application/json")) {
|
|
210
|
+
try {
|
|
211
|
+
data = await res.json();
|
|
212
|
+
} catch {}
|
|
213
|
+
} else {
|
|
214
|
+
try {
|
|
215
|
+
const text = await res.text();
|
|
216
|
+
data = text ? { message: text } : null;
|
|
217
|
+
} catch {}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (!res.ok || data?.status === "error") {
|
|
221
|
+
const rawMsg = Array.isArray(data?.message) ? data.message.join(", ") : data?.message;
|
|
222
|
+
throw new ApiError(rawMsg || data?.error || `Request failed (HTTP ${res.status})`, {
|
|
223
|
+
status: res.status,
|
|
224
|
+
data,
|
|
225
|
+
errors: data?.errors,
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (options.raw) return data;
|
|
230
|
+
return data && typeof data === "object" && "data" in data ? data.data : data;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
api.get = (url, options = {}) => api(url, { ...options, method: "GET" });
|
|
234
|
+
api.post = (url, body, options = {}) => api(url, { ...options, method: "POST", body });
|
|
235
|
+
api.put = (url, body, options = {}) => api(url, { ...options, method: "PUT", body });
|
|
236
|
+
api.patch = (url, body, options = {}) => api(url, { ...options, method: "PATCH", body });
|
|
237
|
+
api.delete = (url, options = {}) => api(url, { ...options, method: "DELETE" });
|
|
238
|
+
|
|
239
|
+
export const request = api;
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createContext,
|
|
3
|
+
createElement as h,
|
|
4
|
+
useCallback,
|
|
5
|
+
useContext,
|
|
6
|
+
useEffect,
|
|
7
|
+
useMemo,
|
|
8
|
+
useState,
|
|
9
|
+
} from "react";
|
|
10
|
+
import { Navigate, Outlet, useLocation } from "react-router";
|
|
11
|
+
import { api, getAuthMode, setAuthToken } from "./api.js";
|
|
12
|
+
import { PageSkeleton } from "./components.js";
|
|
13
|
+
import { t as translate } from "./i18n.js";
|
|
14
|
+
|
|
15
|
+
const DEFAULT_ENDPOINTS = {
|
|
16
|
+
me: "/api/auth/me",
|
|
17
|
+
login: "/api/auth/login",
|
|
18
|
+
register: "/api/auth/register",
|
|
19
|
+
logout: "/api/auth/logout",
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const AuthContext = createContext(null);
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Checks whether a user object holds at least one of the required roles.
|
|
26
|
+
* Returns `true` for any authenticated user when `roles` is omitted or empty.
|
|
27
|
+
* @param {Object|null|undefined} user
|
|
28
|
+
* @param {string|string[]|null|undefined} roles
|
|
29
|
+
* @returns {boolean}
|
|
30
|
+
*/
|
|
31
|
+
export function matchUserRole(user, roles) {
|
|
32
|
+
if (!user) return false;
|
|
33
|
+
const required = Array.isArray(roles) ? roles.filter(Boolean) : roles ? [roles] : [];
|
|
34
|
+
if (required.length === 0) return true;
|
|
35
|
+
const userRoles = new Set();
|
|
36
|
+
if (typeof user.role === "string" && user.role) userRoles.add(user.role);
|
|
37
|
+
if (Array.isArray(user.roles)) {
|
|
38
|
+
for (const r of user.roles) {
|
|
39
|
+
if (typeof r === "string" && r) userRoles.add(r);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return required.some((r) => userRoles.has(r));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Provides authentication state synchronized with `/api/auth/me`, plus `login`, `register`, `logout`,
|
|
47
|
+
* `refresh`, and `hasRole` helpers for React Router routes and components.
|
|
48
|
+
* @param {Object} props
|
|
49
|
+
* @param {Object} [props.endpoints]
|
|
50
|
+
* @param {any} [props.initialUser]
|
|
51
|
+
* @param {any} props.children
|
|
52
|
+
*/
|
|
53
|
+
export function AuthProvider({ endpoints, initialUser, children }) {
|
|
54
|
+
const urls = useMemo(() => ({ ...DEFAULT_ENDPOINTS, ...(endpoints || {}) }), [endpoints]);
|
|
55
|
+
const [user, setUser] = useState(initialUser === undefined ? null : initialUser);
|
|
56
|
+
const [loading, setLoading] = useState(initialUser === undefined);
|
|
57
|
+
const [registerEnabled, setRegisterEnabled] = useState(true);
|
|
58
|
+
|
|
59
|
+
const refresh = useCallback(
|
|
60
|
+
async (signal) => {
|
|
61
|
+
try {
|
|
62
|
+
const res = await api.get(urls.me, { signal });
|
|
63
|
+
const resolvedUser = res && typeof res === "object" && "user" in res ? res.user : res;
|
|
64
|
+
setUser(resolvedUser || null);
|
|
65
|
+
if (res && typeof res === "object" && "registerEnabled" in res) {
|
|
66
|
+
setRegisterEnabled(Boolean(res.registerEnabled));
|
|
67
|
+
}
|
|
68
|
+
return resolvedUser || null;
|
|
69
|
+
} catch (err) {
|
|
70
|
+
if (err?.name === "AbortError" || signal?.aborted) return null;
|
|
71
|
+
if (err?.status === 401 && getAuthMode() === "token") setAuthToken(null);
|
|
72
|
+
setUser(null);
|
|
73
|
+
return null;
|
|
74
|
+
} finally {
|
|
75
|
+
if (!signal?.aborted) setLoading(false);
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
[urls.me]
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
useEffect(() => {
|
|
82
|
+
if (initialUser !== undefined) return;
|
|
83
|
+
const ctrl = new AbortController();
|
|
84
|
+
refresh(ctrl.signal);
|
|
85
|
+
return () => ctrl.abort();
|
|
86
|
+
}, [initialUser, refresh]);
|
|
87
|
+
|
|
88
|
+
const login = useCallback(
|
|
89
|
+
async (credentials) => {
|
|
90
|
+
const res = await api.post(urls.login, credentials);
|
|
91
|
+
if (res && typeof res === "object" && res.token) setAuthToken(res.token);
|
|
92
|
+
const nextUser = res && typeof res === "object" && "user" in res ? res.user : res;
|
|
93
|
+
if (nextUser) {
|
|
94
|
+
setUser(nextUser);
|
|
95
|
+
} else {
|
|
96
|
+
await refresh();
|
|
97
|
+
}
|
|
98
|
+
return nextUser;
|
|
99
|
+
},
|
|
100
|
+
[urls.login, refresh]
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
const register = useCallback(
|
|
104
|
+
async (payload) => {
|
|
105
|
+
const res = await api.post(urls.register, payload);
|
|
106
|
+
if (res && typeof res === "object" && res.token) setAuthToken(res.token);
|
|
107
|
+
const nextUser = res && typeof res === "object" && "user" in res ? res.user : res;
|
|
108
|
+
if (nextUser) {
|
|
109
|
+
setUser(nextUser);
|
|
110
|
+
} else {
|
|
111
|
+
await refresh();
|
|
112
|
+
}
|
|
113
|
+
return nextUser;
|
|
114
|
+
},
|
|
115
|
+
[urls.register, refresh]
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
const logout = useCallback(async () => {
|
|
119
|
+
try {
|
|
120
|
+
await api.post(urls.logout, {});
|
|
121
|
+
} finally {
|
|
122
|
+
if (getAuthMode() === "token") setAuthToken(null);
|
|
123
|
+
setUser(null);
|
|
124
|
+
}
|
|
125
|
+
}, [urls.logout]);
|
|
126
|
+
|
|
127
|
+
const hasRole = useCallback((roles) => matchUserRole(user, roles), [user]);
|
|
128
|
+
|
|
129
|
+
const value = useMemo(
|
|
130
|
+
() => ({
|
|
131
|
+
user,
|
|
132
|
+
loading,
|
|
133
|
+
authenticated: Boolean(user),
|
|
134
|
+
registerEnabled,
|
|
135
|
+
login,
|
|
136
|
+
register,
|
|
137
|
+
logout,
|
|
138
|
+
refresh,
|
|
139
|
+
setUser,
|
|
140
|
+
hasRole,
|
|
141
|
+
}),
|
|
142
|
+
[user, loading, registerEnabled, login, register, logout, refresh, hasRole]
|
|
143
|
+
);
|
|
144
|
+
|
|
145
|
+
return h(AuthContext.Provider, { value }, children);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Returns the active auth context (`user`, `loading`, `authenticated`, `registerEnabled`, `login`, `register`, `logout`, `refresh`, `hasRole`).
|
|
150
|
+
*/
|
|
151
|
+
export function useAuth() {
|
|
152
|
+
const ctx = useContext(AuthContext);
|
|
153
|
+
if (!ctx) {
|
|
154
|
+
throw new Error("useAuth() must be used inside <AuthProvider>.");
|
|
155
|
+
}
|
|
156
|
+
return ctx;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Protects routes or components for authenticated users and optional roles.
|
|
161
|
+
* Works both as a wrapper component and as a React Router layout route (`<Outlet />`).
|
|
162
|
+
* @param {Object} [props]
|
|
163
|
+
* @param {string|string[]} [props.roles]
|
|
164
|
+
* @param {string} [props.redirectTo="/login"]
|
|
165
|
+
* @param {string} [props.forbiddenRedirect]
|
|
166
|
+
* @param {any} [props.fallback]
|
|
167
|
+
* @param {any} [props.forbidden]
|
|
168
|
+
* @param {any} [props.children]
|
|
169
|
+
*/
|
|
170
|
+
export function RequireAuth({
|
|
171
|
+
roles,
|
|
172
|
+
redirectTo = "/login",
|
|
173
|
+
forbiddenRedirect,
|
|
174
|
+
fallback,
|
|
175
|
+
forbidden,
|
|
176
|
+
children,
|
|
177
|
+
} = {}) {
|
|
178
|
+
const { user, loading, hasRole } = useAuth();
|
|
179
|
+
const location = useLocation();
|
|
180
|
+
|
|
181
|
+
if (loading) {
|
|
182
|
+
return fallback !== undefined ? fallback : h(PageSkeleton, null);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (!user) {
|
|
186
|
+
return h(Navigate, { to: redirectTo, state: { from: location }, replace: true });
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (roles && !hasRole(roles)) {
|
|
190
|
+
if (forbiddenRedirect) {
|
|
191
|
+
return h(Navigate, { to: forbiddenRedirect, replace: true });
|
|
192
|
+
}
|
|
193
|
+
if (forbidden !== undefined) {
|
|
194
|
+
return forbidden;
|
|
195
|
+
}
|
|
196
|
+
return h(
|
|
197
|
+
"div",
|
|
198
|
+
{
|
|
199
|
+
className:
|
|
200
|
+
"card mx-auto my-12 max-w-md text-center",
|
|
201
|
+
},
|
|
202
|
+
h("h2", { className: "text-lg font-semibold tracking-tight" }, translate("auth.deniedTitle")),
|
|
203
|
+
h(
|
|
204
|
+
"p",
|
|
205
|
+
{ className: "mt-1 text-sm text-muted-foreground" },
|
|
206
|
+
translate("auth.deniedText")
|
|
207
|
+
)
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return children !== undefined ? children : h(Outlet, null);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Restricts routes (such as Login or Register) to unauthenticated guests, redirecting signed-in users.
|
|
216
|
+
* Works both as a wrapper component and as a React Router layout route (`<Outlet />`).
|
|
217
|
+
* @param {Object} [props]
|
|
218
|
+
* @param {string} [props.redirectTo="/"]
|
|
219
|
+
* @param {any} [props.fallback]
|
|
220
|
+
* @param {any} [props.children]
|
|
221
|
+
*/
|
|
222
|
+
export function GuestOnly({ redirectTo = "/", fallback, children } = {}) {
|
|
223
|
+
const { user, loading } = useAuth();
|
|
224
|
+
const location = useLocation();
|
|
225
|
+
|
|
226
|
+
if (loading) {
|
|
227
|
+
return fallback !== undefined ? fallback : h(PageSkeleton, null);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (user) {
|
|
231
|
+
const target = location.state?.from?.pathname || redirectTo;
|
|
232
|
+
return h(Navigate, { to: target, replace: true });
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return children !== undefined ? children : h(Outlet, null);
|
|
236
|
+
}
|