@seip/bluebird-js 0.1.6 → 0.2.0

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 (152) hide show
  1. package/.vscode/extensions.json +7 -7
  2. package/.vscode/settings.json +10 -10
  3. package/AGENTS.md +266 -116
  4. package/README.md +258 -245
  5. package/app/models/user.js +19 -0
  6. package/app/resources/html/home.html +137 -0
  7. package/app/resources/html/layouts/main.html +54 -0
  8. package/app/resources/html/notFound.html +14 -0
  9. package/app/resources/html/terms.html +46 -0
  10. package/app/resources/index.html +27 -0
  11. package/app/resources/layouts/AppLayout.jsx +89 -0
  12. package/app/resources/main.jsx +18 -0
  13. package/app/resources/pages/Dashboard.jsx +98 -0
  14. package/app/resources/pages/Home.jsx +140 -0
  15. package/app/resources/pages/Login.jsx +35 -0
  16. package/app/resources/pages/NotFound.jsx +16 -0
  17. package/app/resources/pages/Register.jsx +55 -0
  18. package/app/resources/routes.jsx +54 -0
  19. package/app/resources/spa.js +67 -0
  20. package/app/resources/styles.css +9 -0
  21. package/app/routes/api.js +85 -50
  22. package/app/routes/auth.js +209 -0
  23. package/app/routes/web.js +49 -37
  24. package/core/ai.d.ts +151 -151
  25. package/core/ai.js +1071 -1051
  26. package/core/app.d.ts +2 -18
  27. package/core/app.js +978 -792
  28. package/core/auth.d.ts +2 -13
  29. package/core/auth.js +444 -326
  30. package/core/cli/backup.js +167 -167
  31. package/core/cli/build.js +37 -0
  32. package/core/cli/dev.js +155 -0
  33. package/core/cli/doctor.js +37 -2
  34. package/core/cli/export.js +191 -0
  35. package/core/cli/init.js +101 -332
  36. package/core/cli/nginx.js +1 -1
  37. package/core/cli/templates.js +139 -0
  38. package/core/cli/view.js +73 -136
  39. package/core/config.js +44 -2
  40. package/core/csrf.js +156 -24
  41. package/core/database.js +737 -684
  42. package/core/debug.js +1 -1
  43. package/core/html.js +8 -1
  44. package/core/index.d.ts +1286 -1431
  45. package/core/paths.js +55 -0
  46. package/core/ratelimit.js +10 -1
  47. package/core/react/client/api.js +237 -0
  48. package/core/react/client/auth.js +236 -0
  49. package/core/react/client/components.js +1321 -0
  50. package/core/react/client/i18n.js +338 -0
  51. package/core/react/client/index.d.ts +249 -0
  52. package/core/react/client/index.js +49 -0
  53. package/core/react/client/router.js +26 -0
  54. package/core/react/client/theme.css +512 -0
  55. package/core/render-cache.js +250 -212
  56. package/core/render.d.ts +25 -21
  57. package/core/render.js +613 -603
  58. package/core/router.d.ts +2 -3
  59. package/core/router.js +171 -171
  60. package/core/seo.js +10 -0
  61. package/core/spa.js +599 -0
  62. package/core/view-loader.js +81 -455
  63. package/core/vite-plugin.d.ts +18 -0
  64. package/core/vite-plugin.js +162 -0
  65. package/core/vite.js +250 -145
  66. package/index.js +22 -18
  67. package/jsconfig.json +5 -3
  68. package/package.json +114 -92
  69. package/production.md +8 -3
  70. package/public/js/bluebird.js +1160 -0
  71. package/templates/_auth/app/database.js +19 -0
  72. package/templates/_auth/app/models/user.js +22 -0
  73. package/templates/_auth/app/routes/auth-router.js +304 -0
  74. package/templates/_base/app/resources/html/layouts/main.html +55 -0
  75. package/templates/_base/app/resources/html/notFound.html +14 -0
  76. package/templates/_base/app/resources/index.html +27 -0
  77. package/templates/_base/app/resources/styles.css +9 -0
  78. package/templates/api/app/models/note.js +18 -0
  79. package/templates/api/app/routes/api.js +82 -0
  80. package/templates/api/app/routes/auth.js +11 -0
  81. package/templates/api/index.js +19 -0
  82. package/templates/api/template.json +13 -0
  83. package/templates/auth/app/mail.js +11 -0
  84. package/templates/auth/app/models/password_reset.js +18 -0
  85. package/templates/auth/app/resources/html/home.html +21 -0
  86. package/templates/auth/app/resources/html/partials/nav.html +2 -0
  87. package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
  88. package/templates/auth/app/resources/main.jsx +18 -0
  89. package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
  90. package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
  91. package/templates/auth/app/resources/pages/Login.jsx +36 -0
  92. package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
  93. package/templates/auth/app/resources/pages/Profile.jsx +99 -0
  94. package/templates/auth/app/resources/pages/Register.jsx +50 -0
  95. package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
  96. package/templates/auth/app/resources/routes.jsx +54 -0
  97. package/templates/auth/app/resources/spa.js +29 -0
  98. package/templates/auth/app/routes/api.js +17 -0
  99. package/templates/auth/app/routes/auth.js +13 -0
  100. package/templates/auth/app/routes/web.js +21 -0
  101. package/templates/auth/index.js +19 -0
  102. package/templates/auth/template.json +15 -0
  103. package/templates/blank/app/models/.gitkeep +0 -0
  104. package/templates/blank/app/resources/html/home.html +27 -0
  105. package/templates/blank/app/resources/html/partials/nav.html +1 -0
  106. package/templates/blank/app/resources/main.jsx +16 -0
  107. package/templates/blank/app/resources/pages/Home.jsx +42 -0
  108. package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
  109. package/templates/blank/app/resources/routes.jsx +15 -0
  110. package/templates/blank/app/resources/spa.js +24 -0
  111. package/templates/blank/app/routes/api.js +11 -0
  112. package/templates/blank/app/routes/web.js +21 -0
  113. package/templates/blank/index.js +13 -0
  114. package/templates/blank/template.json +12 -0
  115. package/templates/blog/app/lib/blog.js +149 -0
  116. package/templates/blog/app/models/post.js +22 -0
  117. package/templates/blog/app/resources/html/home.html +28 -0
  118. package/templates/blog/app/resources/html/not-found.html +5 -0
  119. package/templates/blog/app/resources/html/partials/nav.html +2 -0
  120. package/templates/blog/app/resources/html/partials/post-card.html +9 -0
  121. package/templates/blog/app/resources/html/post.html +8 -0
  122. package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
  123. package/templates/blog/app/resources/main.jsx +18 -0
  124. package/templates/blog/app/resources/pages/Login.jsx +31 -0
  125. package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
  126. package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
  127. package/templates/blog/app/resources/pages/Posts.jsx +83 -0
  128. package/templates/blog/app/resources/pages/Register.jsx +43 -0
  129. package/templates/blog/app/resources/routes.jsx +51 -0
  130. package/templates/blog/app/resources/spa.js +25 -0
  131. package/templates/blog/app/resources/styles.css +40 -0
  132. package/templates/blog/app/routes/api.js +77 -0
  133. package/templates/blog/app/routes/auth.js +10 -0
  134. package/templates/blog/app/routes/web.js +114 -0
  135. package/templates/blog/index.js +21 -0
  136. package/templates/blog/template.json +14 -0
  137. package/vite.config.js +11 -0
  138. package/app/views/about.jsx +0 -98
  139. package/app/views/components/Header.jsx +0 -42
  140. package/app/views/components/LiveCounter.jsx +0 -66
  141. package/app/views/dashboard.jsx +0 -300
  142. package/app/views/index.jsx +0 -123
  143. package/app/views/layouts/main/view.jsx +0 -201
  144. package/app/views/legal/terms.html +0 -29
  145. package/app/views/login.jsx +0 -141
  146. package/core/actions.d.ts +0 -4
  147. package/core/actions.js +0 -329
  148. package/core/jsx.d.ts +0 -38
  149. package/core/jsx.js +0 -1432
  150. package/core/vite.d.ts +0 -3
  151. package/public/js/bluebird-client.js +0 -3161
  152. package/public/js/tailwind.js +0 -8
@@ -0,0 +1,35 @@
1
+ import { Card, Form, Input, Link, SubmitButton, useAuth } from "@seip/bluebird-js/react";
2
+
3
+ /**
4
+ * Sign-in page bound to `POST /api/auth/login` via `useAuth().login`.
5
+ */
6
+ export default function Login() {
7
+ const { login, registerEnabled } = useAuth();
8
+
9
+ return (
10
+ <div className="mx-auto max-w-md py-8">
11
+ <Card variant="glass" title="Sign in" description="Access your Bluebird workspace.">
12
+ <Form
13
+ onSubmitRequest={(values) => login(values)}
14
+ successMessage="Welcome back!"
15
+ className="space-y-4"
16
+ >
17
+ <Input name="email" type="email" label="Email" placeholder="you@example.com" autoComplete="email" required />
18
+ <Input name="password" type="password" label="Password" placeholder="Minimum 6 characters" autoComplete="current-password" required />
19
+ <SubmitButton className="w-full" loadingText="Signing in...">
20
+ Sign In
21
+ </SubmitButton>
22
+ </Form>
23
+
24
+ {registerEnabled ? (
25
+ <p className="mt-5 text-center text-sm text-muted-foreground">
26
+ New here?{" "}
27
+ <Link to="/register" className="font-semibold text-foreground underline-offset-4 hover:underline">
28
+ Create an account
29
+ </Link>
30
+ </p>
31
+ ) : null}
32
+ </Card>
33
+ </div>
34
+ );
35
+ }
@@ -0,0 +1,16 @@
1
+ import { Card, Link } from "@seip/bluebird-js/react";
2
+
3
+ /**
4
+ * Fallback view for unmatched client routes inside `/app`.
5
+ */
6
+ export default function NotFound() {
7
+ return (
8
+ <div className="mx-auto max-w-md py-12">
9
+ <Card variant="glass" title="Page not found" description="The requested route does not exist in this workspace.">
10
+ <Link to="/" className="btn btn-primary btn-sm">
11
+ Back to Home
12
+ </Link>
13
+ </Card>
14
+ </div>
15
+ );
16
+ }
@@ -0,0 +1,55 @@
1
+ import { Card, Form, Input, Link, SubmitButton, useAuth } from "@seip/bluebird-js/react";
2
+
3
+ /**
4
+ * Registration page bound to `POST /api/auth/register` when enabled on the backend.
5
+ */
6
+ export default function Register() {
7
+ const { register, registerEnabled } = useAuth();
8
+
9
+ if (!registerEnabled) {
10
+ return (
11
+ <div className="mx-auto max-w-md py-8">
12
+ <Card variant="glass" title="Registration disabled" description="Self-registration is disabled for this application.">
13
+ <Link to="/login" className="btn btn-outline btn-sm">
14
+ Return to Sign In
15
+ </Link>
16
+ </Card>
17
+ </div>
18
+ );
19
+ }
20
+
21
+ return (
22
+ <div className="mx-auto max-w-md py-8">
23
+ <Card variant="glass" title="Create account" description="Register a new user account.">
24
+ <Form
25
+ onSubmitRequest={(values) => register(values)}
26
+ successMessage="Account created!"
27
+ className="space-y-4"
28
+ >
29
+ <Input name="name" type="text" label="Name" placeholder="Alex Rivera" autoComplete="name" required />
30
+ <Input name="email" type="email" label="Email" placeholder="alex@example.com" autoComplete="email" required />
31
+ <Input
32
+ name="password"
33
+ type="password"
34
+ label="Password"
35
+ hint="At least 6 characters"
36
+ placeholder="Choose a strong password"
37
+ autoComplete="new-password"
38
+ minLength={6}
39
+ required
40
+ />
41
+ <SubmitButton className="w-full" loadingText="Creating account...">
42
+ Create Account
43
+ </SubmitButton>
44
+ </Form>
45
+
46
+ <p className="mt-5 text-center text-sm text-muted-foreground">
47
+ Already registered?{" "}
48
+ <Link to="/login" className="font-semibold text-foreground underline-offset-4 hover:underline">
49
+ Sign in
50
+ </Link>
51
+ </p>
52
+ </Card>
53
+ </div>
54
+ );
55
+ }
@@ -0,0 +1,54 @@
1
+ import { Suspense, lazy } from "react";
2
+ import { GuestOnly, PageSkeleton, RequireAuth, createRouter } from "@seip/bluebird-js/react";
3
+ import AppLayout from "./layouts/AppLayout.jsx";
4
+
5
+ const Home = lazy(() => import("./pages/Home.jsx"));
6
+ const Login = lazy(() => import("./pages/Login.jsx"));
7
+ const Register = lazy(() => import("./pages/Register.jsx"));
8
+ const Dashboard = lazy(() => import("./pages/Dashboard.jsx"));
9
+ const NotFound = lazy(() => import("./pages/NotFound.jsx"));
10
+
11
+ /**
12
+ * Wraps lazy route components in a full-width Suspense fallback.
13
+ * @param {import('react').ReactNode} element
14
+ * @returns {import('react').ReactNode}
15
+ */
16
+ function withSuspense(element) {
17
+ return <Suspense fallback={<PageSkeleton />}>{element}</Suspense>;
18
+ }
19
+
20
+ /**
21
+ * React Router configuration: browser router under `/app` on the server, hash router in static exports.
22
+ */
23
+ export const router = createRouter(
24
+ [
25
+ {
26
+ path: "/",
27
+ element: <AppLayout />,
28
+ children: [
29
+ {
30
+ index: true,
31
+ element: withSuspense(<Home />),
32
+ },
33
+ {
34
+ element: <GuestOnly redirectTo="/dashboard" />,
35
+ children: [
36
+ { path: "login", element: withSuspense(<Login />) },
37
+ { path: "register", element: withSuspense(<Register />) },
38
+ ],
39
+ },
40
+ {
41
+ element: <RequireAuth redirectTo="/login" />,
42
+ children: [
43
+ { path: "dashboard", element: withSuspense(<Dashboard />) },
44
+ ],
45
+ },
46
+ {
47
+ path: "*",
48
+ element: withSuspense(<NotFound />),
49
+ },
50
+ ],
51
+ },
52
+ ],
53
+ { basename: "/app" }
54
+ );
@@ -0,0 +1,67 @@
1
+ /**
2
+ * React SPA shell configuration shared by `routerWeb.spa(spa.mount, spa)` (web, per-URL SEO)
3
+ * and `npx bluebird-js export` (static HTML/JS/CSS build for Electron, Capacitor, or any static host).
4
+ * The shell template is `app/resources/index.html`; the React entry is `app/resources/main.jsx`.
5
+ * @type {import('@seip/bluebird-js/core/index.js').SpaOptions & { mount: string }}
6
+ */
7
+ const spa = {
8
+ mount: "/app",
9
+ lang: "en",
10
+ titleTemplate: "%s — Bluebird App",
11
+ title: "Workspace",
12
+ description: "Bluebird.js client-rendered React SPA powered by Vite, React Router, and Tailwind CSS v4.",
13
+ keywords: "bluebird-js, react, react-router, vite, tailwind, spa",
14
+ canonical: true,
15
+ head: [{ tag: "link", rel: "icon", href: "/images/favicon.ico" }],
16
+ htmlAttrs: { class: "dark", "data-theme": "dark" },
17
+ bodyAttrs: {
18
+ class: "min-h-screen bg-app text-foreground antialiased",
19
+ },
20
+ skeleton: "app",
21
+ meta: {
22
+ "*": {
23
+ title: "Workspace",
24
+ description: "Bluebird.js React Router application.",
25
+ robots: "noindex, nofollow",
26
+ skeleton: "app",
27
+ },
28
+ "/": {
29
+ title: "React SPA",
30
+ description: "Client-side React demo with carousel, toasts, Tailwind dark/light theme, and Auth.",
31
+ robots: "index, follow",
32
+ skeleton: "page",
33
+ jsonld: {
34
+ "@context": "https://schema.org",
35
+ "@type": "WebApplication",
36
+ name: "Bluebird App",
37
+ applicationCategory: "DeveloperApplication",
38
+ },
39
+ },
40
+ login: {
41
+ title: "Sign In",
42
+ description: "Sign in to your Bluebird account.",
43
+ keywords: "login, authentication, bluebird",
44
+ robots: "index, follow",
45
+ skeleton: "auth",
46
+ jsonld: {
47
+ "@context": "https://schema.org",
48
+ "@type": "WebPage",
49
+ name: "Sign In",
50
+ },
51
+ },
52
+ "/app/register": {
53
+ title: "Create Account",
54
+ description: "Register a new account.",
55
+ robots: "index, follow",
56
+ skeleton: "auth",
57
+ },
58
+ dashboard: {
59
+ title: "Dashboard",
60
+ description: "Authenticated user dashboard.",
61
+ robots: "noindex, nofollow",
62
+ skeleton: "app",
63
+ },
64
+ },
65
+ };
66
+
67
+ export default spa;
@@ -0,0 +1,9 @@
1
+ @import "tailwindcss";
2
+ @source "./";
3
+ @source "../../public/js";
4
+
5
+ @custom-variant dark (&:where(.dark, .dark *, [data-theme="dark"], [data-theme="dark"] *));
6
+
7
+ @theme {
8
+ --font-sans: "Inter", ui-sans-serif, system-ui, -apple-system, sans-serif;
9
+ }
package/app/routes/api.js CHANGED
@@ -1,50 +1,85 @@
1
- import Router from "@seip/bluebird-js/core/router.js";
2
- import Validator from "@seip/bluebird-js/core/validate.js";
3
- import Cache from "@seip/bluebird-js/core/cache.js";
4
- import Auth from "@seip/bluebird-js/core/auth.js";
5
-
6
- const routerApi = new Router("/api");
7
-
8
- routerApi.get("/", (req, res) => {
9
- res.json({ api: true, message: "Blue Bird API", time: Date.now() });
10
- });
11
-
12
- routerApi.get("/users", (req, res) => {
13
- const users = [
14
- { name: "John Doe", email: "john.doe@example.com" },
15
- { name: "Jane Doe", email: "jane.doe@example.com" },
16
- ];
17
- res.json(users);
18
- });
19
-
20
- const loginSchema = {
21
- email: { required: true, email: true },
22
- password: { required: true, min: 6 },
23
- };
24
-
25
- const loginValidator = new Validator(loginSchema, "en");
26
-
27
- routerApi.post("/login", loginValidator.middleware(), (req, res) => {
28
- res.json({ message: "Login successful", body: req.body });
29
- });
30
-
31
- routerApi.get("/cache", Cache.middleware(60), async (req, res) => {
32
- await new Promise((resolve) => setTimeout(resolve, 2000));
33
- res.json({ message: "Cache successful" });
34
- });
35
-
36
- routerApi.get("/auth_generate", async (req, res) => {
37
- const token = await Auth.login(res, { id: 1, name: "John Doe" }, "auth");
38
- res.json({ message: "Auth successful", token });
39
- });
40
-
41
- routerApi.get("/auth_logout", async (req, res) => {
42
- await Auth.logout(res, "auth", {}, req);
43
- res.json({ message: "Logged out" });
44
- });
45
-
46
- routerApi.get("/auth_verify", Auth.protect(), (req, res) => {
47
- res.json({ message: "Auth successful", user: req.user });
48
- });
49
-
50
- export default routerApi;
1
+ import Router from "@seip/bluebird-js/core/router.js";
2
+ import Validator from "@seip/bluebird-js/core/validate.js";
3
+ import Cache from "@seip/bluebird-js/core/cache.js";
4
+ import Auth from "@seip/bluebird-js/core/auth.js";
5
+ import Csrf from "@seip/bluebird-js/core/csrf.js";
6
+
7
+ const routerApi = new Router("/api");
8
+ routerApi.use(Csrf.middleware());
9
+
10
+ routerApi.get("/", (req, res) => {
11
+ res.ok({ message: "Blue Bird API", time: Date.now() });
12
+ });
13
+
14
+ routerApi.get("/cache", Cache.middleware(60), async (req, res) => {
15
+ res.ok({ message: "Cached response", time: Date.now() });
16
+ });
17
+
18
+ routerApi.get("/admin/stats", Auth.protect({ roles: "admin" }), (req, res) => {
19
+ res.ok({ role: req.user.role, uptime: Math.floor(process.uptime()) }, "Admin metrics");
20
+ });
21
+
22
+ const demoTasks = [
23
+ { id: 1, title: "Render landing page via HTML {{ }} SSR", status: "done" },
24
+ { id: 2, title: "Serve React Router SPA via router.spa('/app')", status: "active" },
25
+ { id: 3, title: "Sync AuthProvider session with /api/auth/me", status: "active" },
26
+ ];
27
+
28
+ routerApi.get("/tasks", Auth.protect(), (req, res) => {
29
+ res.ok(demoTasks, "Tasks loaded");
30
+ });
31
+
32
+ const taskValidator = new Validator(
33
+ {
34
+ title: { required: true, min: 3, max: 140 },
35
+ },
36
+ "en"
37
+ );
38
+
39
+ routerApi.post("/tasks", Auth.protect(), taskValidator.middleware(), (req, res) => {
40
+ const newTask = {
41
+ id: Date.now(),
42
+ title: String(req.body.title).trim(),
43
+ status: "active",
44
+ };
45
+ demoTasks.unshift(newTask);
46
+ if (demoTasks.length > 15) demoTasks.pop();
47
+ res.created(newTask, `Task "${newTask.title}" created`);
48
+ });
49
+
50
+ routerApi.post("/tasks/clear", Auth.protect(), (req, res) => {
51
+ demoTasks.splice(3);
52
+ res.ok(demoTasks, "Task list restored");
53
+ });
54
+
55
+ routerApi.delete("/tasks/:id", Auth.protect(), (req, res) => {
56
+ const id = Number(req.params.id);
57
+ const idx = demoTasks.findIndex((t) => Number(t.id) === id);
58
+ if (idx !== -1 && demoTasks.length > 1) {
59
+ const [removed] = demoTasks.splice(idx, 1);
60
+ return res.ok(removed, `Task #${id} deleted`);
61
+ }
62
+ return res.ok({ id }, "Task processed");
63
+ });
64
+
65
+ routerApi.get("/stream", (req, res) => {
66
+ const stream = res.sse({ keepAliveMs: 15000, retry: 3000 });
67
+ let tick = 1;
68
+
69
+ const sendMetrics = () => {
70
+ const memMb = Math.round((process.memoryUsage().rss / 1024 / 1024) * 10) / 10;
71
+ stream.send({
72
+ tick,
73
+ uptime: Math.floor(process.uptime()),
74
+ rssMb: memMb,
75
+ timestamp: new Date().toLocaleTimeString(),
76
+ });
77
+ tick++;
78
+ };
79
+
80
+ sendMetrics();
81
+ const timer = setInterval(sendMetrics, 2000);
82
+ stream.onClose(() => clearInterval(timer));
83
+ });
84
+
85
+ export default routerApi;
@@ -0,0 +1,209 @@
1
+ import Router from "@seip/bluebird-js/core/router.js";
2
+ import Auth from "@seip/bluebird-js/core/auth.js";
3
+ import Hash from "@seip/bluebird-js/core/hash.js";
4
+ import Validator from "@seip/bluebird-js/core/validate.js";
5
+ import App from "@seip/bluebird-js/core/app.js";
6
+ import Csrf from "@seip/bluebird-js/core/csrf.js";
7
+ import { DB_TYPE } from "@seip/bluebird-js/core/database.js";
8
+ import User from "../models/user.js";
9
+
10
+ /** @type {Promise<string>|null} */
11
+ let dummyHash = null;
12
+
13
+ /**
14
+ * Verifies a password in constant work: unknown emails are checked against a dummy hash so response
15
+ * times do not reveal which accounts exist.
16
+ * @param {string} password
17
+ * @param {string|undefined} storedHash
18
+ * @returns {Promise<boolean>}
19
+ */
20
+ async function verifyPassword(password, storedHash) {
21
+ if (storedHash) return Hash.verify(password, storedHash);
22
+ dummyHash ??= Hash.make("bluebird-dummy-password");
23
+ await Hash.verify(password, await dummyHash);
24
+ return false;
25
+ }
26
+
27
+ /**
28
+ * Strips sensitive fields and returns a public user summary for tokens and API responses.
29
+ * @param {Object} user
30
+ * @returns {{ id: number|string, name: string, email: string, role: string }}
31
+ */
32
+ function toPublicUser(user) {
33
+ return {
34
+ id: user.id,
35
+ name: user.name,
36
+ email: user.email,
37
+ role: user.role || "user",
38
+ };
39
+ }
40
+
41
+ /**
42
+ * Signs the user in. Browser sessions receive an HttpOnly cookie; bearer clients (`X-Auth-Mode: token`,
43
+ * used by static exports in Electron/Capacitor) receive the token in the JSON body instead.
44
+ * @param {import('express').Request} req
45
+ * @param {import('express').Response} res
46
+ * @param {Object} publicUser
47
+ * @returns {Promise<{ user: Object, token?: string }>}
48
+ */
49
+ async function issueSession(req, res, publicUser) {
50
+ const tokenMode = String(req.headers["x-auth-mode"] || "").toLowerCase() === "token";
51
+ const token = await Auth.login(res, publicUser, "auth", tokenMode ? { setCookie: false } : {});
52
+ return tokenMode ? { user: publicUser, token } : { user: publicUser };
53
+ }
54
+
55
+ /**
56
+ * Creates a REST authentication router (`/login`, `/logout`, `/me`, and optional `/register`).
57
+ * Registration is disabled by default and enabled via `{ register: true }`.
58
+ * @param {Object} [options={}]
59
+ * @param {string} [options.basePath="/api/auth"] - Base mount path.
60
+ * @param {boolean} [options.register=false] - Enable `POST /register`.
61
+ * @param {string} [options.defaultRole="user"] - Default role assigned to newly registered users.
62
+ * @param {Object|false} [options.rateLimit] - Rate limiting config applied to login and registration.
63
+ * @returns {Router}
64
+ */
65
+ export function createAuthRouter(options = {}) {
66
+ const {
67
+ basePath = "/api/auth",
68
+ register = false,
69
+ defaultRole = "user",
70
+ rateLimit = { max: 25, windowMs: 60000 },
71
+ } = options;
72
+
73
+ const routerAuth = new Router(basePath);
74
+ routerAuth.use(Csrf.middleware());
75
+ const memoryUsers = new Map();
76
+ let schemaReady = false;
77
+ let memorySeq = 1;
78
+
79
+ /**
80
+ * Ensures the `users` table exists when backed by a SQL database.
81
+ * @returns {Promise<void>}
82
+ */
83
+ async function ensureUsersTable() {
84
+ if (schemaReady || DB_TYPE === "none") return;
85
+ const db = User.getDatabase();
86
+ await db.init();
87
+ await db.query(User.toDDL(db.type));
88
+ schemaReady = true;
89
+ }
90
+
91
+ /**
92
+ * Finds a user record by email including the hashed password field.
93
+ * @param {string} email
94
+ * @returns {Promise<Object|null>}
95
+ */
96
+ async function findByEmail(email) {
97
+ const cleanEmail = String(email || "").trim().toLowerCase();
98
+ if (DB_TYPE === "none") {
99
+ return memoryUsers.get(cleanEmail) || null;
100
+ }
101
+ await ensureUsersTable();
102
+ return User.find({ email: cleanEmail }, { withHidden: true });
103
+ }
104
+
105
+ /**
106
+ * Creates a user record with a hashed password and default role.
107
+ * @param {{ name: string, email: string, password: string, role: string }} payload
108
+ * @returns {Promise<Object>}
109
+ */
110
+ async function createUser(payload) {
111
+ const cleanEmail = String(payload.email || "").trim().toLowerCase();
112
+ if (DB_TYPE === "none") {
113
+ const record = {
114
+ id: memorySeq++,
115
+ name: String(payload.name).trim(),
116
+ email: cleanEmail,
117
+ password: await Hash.make(payload.password),
118
+ role: payload.role || defaultRole,
119
+ };
120
+ memoryUsers.set(cleanEmail, record);
121
+ return record;
122
+ }
123
+ await ensureUsersTable();
124
+ const id = await User.create({
125
+ name: String(payload.name).trim(),
126
+ email: cleanEmail,
127
+ password: payload.password,
128
+ role: payload.role || defaultRole,
129
+ });
130
+ return User.find(id);
131
+ }
132
+
133
+ const loginValidator = new Validator(
134
+ {
135
+ email: { required: true, email: true },
136
+ password: { required: true, min: 6 },
137
+ },
138
+ "en"
139
+ );
140
+
141
+ const registerValidator = new Validator(
142
+ {
143
+ name: { required: true, min: 2, max: 150 },
144
+ email: { required: true, email: true },
145
+ password: { required: true, min: 6, max: 120 },
146
+ },
147
+ "en"
148
+ );
149
+
150
+ const limiter = rateLimit ? App.rateLimit(rateLimit) : (req, res, next) => next();
151
+
152
+ routerAuth.get("/me", Auth.optional(), (req, res) => {
153
+ const user = req.user ? toPublicUser(req.user) : null;
154
+ res.ok(
155
+ {
156
+ user,
157
+ authenticated: Boolean(user),
158
+ registerEnabled: Boolean(register),
159
+ },
160
+ user ? "Authenticated" : "Guest session"
161
+ );
162
+ });
163
+
164
+ routerAuth.post("/login", limiter, loginValidator.middleware(), async (req, res) => {
165
+ const email = String(req.body.email || "").trim().toLowerCase();
166
+ const password = String(req.body.password || "");
167
+ const found = await findByEmail(email);
168
+
169
+ if (!(await verifyPassword(password, found?.password))) {
170
+ return res.error("Invalid email or password", 401, [
171
+ { field: "email", message: "Invalid email or password" },
172
+ ]);
173
+ }
174
+
175
+ return res.ok(await issueSession(req, res, toPublicUser(found)), "Signed in");
176
+ });
177
+
178
+ routerAuth.post("/register", limiter, registerValidator.middleware(), async (req, res) => {
179
+ if (!register) {
180
+ return res.forbidden("Registration is disabled");
181
+ }
182
+
183
+ const email = String(req.body.email || "").trim().toLowerCase();
184
+ const existing = await findByEmail(email);
185
+ if (existing) {
186
+ return res.error("Email is already registered", 409, [
187
+ { field: "email", message: "Email is already registered" },
188
+ ]);
189
+ }
190
+
191
+ const created = await createUser({
192
+ name: req.body.name,
193
+ email,
194
+ password: req.body.password,
195
+ role: defaultRole,
196
+ });
197
+
198
+ return res.created(await issueSession(req, res, toPublicUser(created)), "Account created");
199
+ });
200
+
201
+ routerAuth.post("/logout", async (req, res) => {
202
+ await Auth.logout(res, "auth", {}, req);
203
+ return res.ok({ loggedOut: true }, "Signed out");
204
+ });
205
+
206
+ return routerAuth;
207
+ }
208
+
209
+ export default createAuthRouter({ register: true });