@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.
Files changed (151) hide show
  1. package/AGENTS.md +727 -620
  2. package/README.md +670 -607
  3. package/app/models/user.js +19 -0
  4. package/app/resources/html/home.html +137 -0
  5. package/app/resources/html/layouts/main.html +55 -0
  6. package/app/resources/html/notFound.html +14 -0
  7. package/app/resources/html/table.html +15 -0
  8. package/app/resources/html/terms.html +46 -0
  9. package/app/resources/index.html +27 -0
  10. package/app/resources/layouts/AppLayout.jsx +92 -0
  11. package/app/resources/main.jsx +18 -0
  12. package/app/resources/pages/Dashboard.jsx +93 -0
  13. package/app/resources/pages/Home.jsx +140 -0
  14. package/app/resources/pages/Login.jsx +35 -0
  15. package/app/resources/pages/NotFound.jsx +16 -0
  16. package/app/resources/pages/Register.jsx +55 -0
  17. package/app/resources/pages/TableDemo.jsx +85 -0
  18. package/app/resources/routes.jsx +59 -0
  19. package/app/resources/spa.js +73 -0
  20. package/app/resources/styles.css +9 -0
  21. package/app/routes/api.js +129 -50
  22. package/app/routes/auth.js +209 -0
  23. package/app/routes/web.js +89 -47
  24. package/core/ai.js +30 -10
  25. package/core/app.d.ts +2 -18
  26. package/core/app.js +987 -801
  27. package/core/auth.d.ts +2 -13
  28. package/core/auth.js +444 -326
  29. package/core/cli/build.js +37 -0
  30. package/core/cli/dev.js +155 -0
  31. package/core/cli/doctor.js +37 -2
  32. package/core/cli/export.js +191 -0
  33. package/core/cli/init.js +91 -322
  34. package/core/cli/nginx.js +1 -1
  35. package/core/cli/templates.js +139 -0
  36. package/core/cli/view.js +98 -161
  37. package/core/config.js +44 -2
  38. package/core/csrf.js +156 -24
  39. package/core/database.js +1184 -1131
  40. package/core/debug.js +1 -1
  41. package/core/html.js +8 -1
  42. package/core/index.d.ts +126 -310
  43. package/core/paths.js +55 -0
  44. package/core/ratelimit.js +10 -1
  45. package/core/react/client/api.js +239 -0
  46. package/core/react/client/auth.js +236 -0
  47. package/core/react/client/components.js +1321 -0
  48. package/core/react/client/datatable.js +595 -0
  49. package/core/react/client/i18n.js +440 -0
  50. package/core/react/client/index.d.ts +314 -0
  51. package/core/react/client/index.js +50 -0
  52. package/core/react/client/router.js +26 -0
  53. package/core/react/client/theme.css +512 -0
  54. package/core/render-cache.js +250 -212
  55. package/core/render.d.ts +25 -21
  56. package/core/render.js +738 -736
  57. package/core/router.d.ts +2 -3
  58. package/core/router.js +171 -171
  59. package/core/seo.js +10 -0
  60. package/core/spa.js +599 -0
  61. package/core/view-loader.js +155 -613
  62. package/core/vite-plugin.d.ts +18 -0
  63. package/core/vite-plugin.js +162 -0
  64. package/core/vite.js +250 -145
  65. package/index.js +22 -18
  66. package/jsconfig.json +5 -3
  67. package/package.json +114 -92
  68. package/production.md +8 -3
  69. package/public/js/bluebird.js +1886 -0
  70. package/templates/_auth/app/database.js +19 -0
  71. package/templates/_auth/app/models/user.js +22 -0
  72. package/templates/_auth/app/routes/auth-router.js +304 -0
  73. package/templates/_base/app/resources/html/layouts/main.html +55 -0
  74. package/templates/_base/app/resources/html/notFound.html +14 -0
  75. package/templates/_base/app/resources/index.html +27 -0
  76. package/templates/_base/app/resources/styles.css +9 -0
  77. package/templates/api/app/models/note.js +18 -0
  78. package/templates/api/app/routes/api.js +82 -0
  79. package/templates/api/app/routes/auth.js +11 -0
  80. package/templates/api/index.js +19 -0
  81. package/templates/api/template.json +13 -0
  82. package/templates/auth/app/mail.js +11 -0
  83. package/templates/auth/app/models/password_reset.js +18 -0
  84. package/templates/auth/app/resources/html/home.html +21 -0
  85. package/templates/auth/app/resources/html/partials/nav.html +2 -0
  86. package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
  87. package/templates/auth/app/resources/main.jsx +18 -0
  88. package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
  89. package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
  90. package/templates/auth/app/resources/pages/Login.jsx +36 -0
  91. package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
  92. package/templates/auth/app/resources/pages/Profile.jsx +99 -0
  93. package/templates/auth/app/resources/pages/Register.jsx +50 -0
  94. package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
  95. package/templates/auth/app/resources/routes.jsx +54 -0
  96. package/templates/auth/app/resources/spa.js +29 -0
  97. package/templates/auth/app/routes/api.js +17 -0
  98. package/templates/auth/app/routes/auth.js +13 -0
  99. package/templates/auth/app/routes/web.js +21 -0
  100. package/templates/auth/index.js +19 -0
  101. package/templates/auth/template.json +15 -0
  102. package/templates/blank/app/models/.gitkeep +0 -0
  103. package/templates/blank/app/resources/html/home.html +27 -0
  104. package/templates/blank/app/resources/html/partials/nav.html +1 -0
  105. package/templates/blank/app/resources/main.jsx +16 -0
  106. package/templates/blank/app/resources/pages/Home.jsx +42 -0
  107. package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
  108. package/templates/blank/app/resources/routes.jsx +15 -0
  109. package/templates/blank/app/resources/spa.js +24 -0
  110. package/templates/blank/app/routes/api.js +11 -0
  111. package/templates/blank/app/routes/web.js +21 -0
  112. package/templates/blank/index.js +13 -0
  113. package/templates/blank/template.json +12 -0
  114. package/templates/blog/app/lib/blog.js +149 -0
  115. package/templates/blog/app/models/post.js +22 -0
  116. package/templates/blog/app/resources/html/home.html +28 -0
  117. package/templates/blog/app/resources/html/not-found.html +5 -0
  118. package/templates/blog/app/resources/html/partials/nav.html +2 -0
  119. package/templates/blog/app/resources/html/partials/post-card.html +9 -0
  120. package/templates/blog/app/resources/html/post.html +8 -0
  121. package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
  122. package/templates/blog/app/resources/main.jsx +18 -0
  123. package/templates/blog/app/resources/pages/Login.jsx +31 -0
  124. package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
  125. package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
  126. package/templates/blog/app/resources/pages/Posts.jsx +83 -0
  127. package/templates/blog/app/resources/pages/Register.jsx +43 -0
  128. package/templates/blog/app/resources/routes.jsx +51 -0
  129. package/templates/blog/app/resources/spa.js +25 -0
  130. package/templates/blog/app/resources/styles.css +40 -0
  131. package/templates/blog/app/routes/api.js +77 -0
  132. package/templates/blog/app/routes/auth.js +10 -0
  133. package/templates/blog/app/routes/web.js +114 -0
  134. package/templates/blog/index.js +21 -0
  135. package/templates/blog/template.json +14 -0
  136. package/vite.config.js +11 -0
  137. package/app/views/components/Header.jsx +0 -42
  138. package/app/views/components/LiveCounter.jsx +0 -67
  139. package/app/views/layouts/main/view.jsx +0 -201
  140. package/app/views/legal/terms.html +0 -29
  141. package/app/views/pages/about.jsx +0 -98
  142. package/app/views/pages/dashboard.jsx +0 -278
  143. package/app/views/pages/index.jsx +0 -123
  144. package/app/views/pages/login.jsx +0 -141
  145. package/core/actions.d.ts +0 -4
  146. package/core/actions.js +0 -355
  147. package/core/jsx.d.ts +0 -38
  148. package/core/jsx.js +0 -1597
  149. package/core/vite.d.ts +0 -3
  150. package/public/js/bluebird-client.js +0 -3265
  151. package/public/js/tailwind.js +0 -8
@@ -0,0 +1,19 @@
1
+ import { DB_TYPE } from "@seip/bluebird-js/core/database.js";
2
+
3
+ /**
4
+ * Creates the tables of the given models when they do not exist yet (`CREATE TABLE IF NOT EXISTS`),
5
+ * so a fresh project runs without a migration step. For schema changes in production use
6
+ * `npx bluebird-js make:migration` and `npx bluebird-js migrate`.
7
+ * @param {Array<typeof import('@seip/bluebird-js/core/model.js').default>} models
8
+ * @returns {Promise<void>}
9
+ */
10
+ export async function ensureSchema(models) {
11
+ if (DB_TYPE === "none") {
12
+ throw new Error("This project needs a database: set DB_TYPE (sqlite, mysql, or postgres) in .env");
13
+ }
14
+ for (const Model of models) {
15
+ const db = Model.getDatabase();
16
+ await db.init();
17
+ await db.query(Model.toDDL(db.type));
18
+ }
19
+ }
@@ -0,0 +1,22 @@
1
+ import Model from "@seip/bluebird-js/core/model.js";
2
+
3
+ /**
4
+ * Default User model supporting password hashing, hidden fields, soft deletes, and role authorization.
5
+ * `session_version` is stored in every session token; incrementing it (password change or reset,
6
+ * "sign out everywhere") invalidates all existing sessions of the account.
7
+ */
8
+ export default class User extends Model {
9
+ static table = "users";
10
+ static primaryKey = "id";
11
+ static timestamps = true;
12
+ static softDelete = true;
13
+
14
+ static schema = {
15
+ id: { type: "int", primary: true, auto: true },
16
+ name: { type: "string", length: 150, required: true },
17
+ email: { type: "string", length: 150, unique: true, required: true, email: true },
18
+ password: { type: "string", length: 255, required: true, min: 6, hidden: true, hash: true },
19
+ role: { type: "string", length: 30, default: "user" },
20
+ session_version: { type: "int", default: 0 },
21
+ };
22
+ }
@@ -0,0 +1,304 @@
1
+ import crypto from "node:crypto";
2
+ import Router from "@seip/bluebird-js/core/router.js";
3
+ import Auth from "@seip/bluebird-js/core/auth.js";
4
+ import Hash from "@seip/bluebird-js/core/hash.js";
5
+ import Validator from "@seip/bluebird-js/core/validate.js";
6
+ import App from "@seip/bluebird-js/core/app.js";
7
+ import Csrf from "@seip/bluebird-js/core/csrf.js";
8
+ import User from "../models/user.js";
9
+
10
+ /**
11
+ * Returns the public fields of a user for tokens and API responses (never the password hash).
12
+ * @param {Object} user
13
+ * @returns {{ id: number|string, name: string, email: string, role: string }}
14
+ */
15
+ export function toPublicUser(user) {
16
+ return { id: user.id, name: user.name, email: user.email, role: user.role || "user" };
17
+ }
18
+
19
+ /**
20
+ * Normalizes an email address for lookups.
21
+ * @param {unknown} email
22
+ * @returns {string}
23
+ */
24
+ function cleanEmail(email) {
25
+ return String(email || "").trim().toLowerCase();
26
+ }
27
+
28
+ /**
29
+ * Hashes a password reset token so the database never stores the usable value.
30
+ * @param {string} token
31
+ * @returns {string}
32
+ */
33
+ function hashToken(token) {
34
+ return crypto.createHash("sha256").update(token).digest("hex");
35
+ }
36
+
37
+ /** @type {Promise<string>|null} */
38
+ let dummyHash = null;
39
+
40
+ /**
41
+ * Verifies a password in constant work: unknown emails are checked against a dummy hash so response
42
+ * times do not reveal which accounts exist.
43
+ * @param {string} password
44
+ * @param {string|undefined} storedHash
45
+ * @returns {Promise<boolean>}
46
+ */
47
+ async function verifyPassword(password, storedHash) {
48
+ if (storedHash) return Hash.verify(password, storedHash);
49
+ dummyHash ??= Hash.make(crypto.randomBytes(16).toString("hex"));
50
+ await Hash.verify(password, await dummyHash);
51
+ return false;
52
+ }
53
+
54
+ /**
55
+ * Returns the session version of a user record (0 for accounts created before the column existed).
56
+ * @param {Object|null|undefined} user
57
+ * @returns {number}
58
+ */
59
+ function sessionVersion(user) {
60
+ return Number(user?.session_version || 0);
61
+ }
62
+
63
+ /**
64
+ * Signs the user in. Browser sessions receive an HttpOnly cookie; bearer clients (`X-Auth-Mode: token`,
65
+ * used by static exports in Electron/Capacitor) receive the token in the JSON body instead.
66
+ * The token carries the account's `session_version` (`sv`) so a later password change or reset revokes it.
67
+ * @param {import('express').Request} req
68
+ * @param {import('express').Response} res
69
+ * @param {Object} user - User record.
70
+ * @returns {Promise<{ user: Object, token?: string }>}
71
+ */
72
+ async function issueSession(req, res, user) {
73
+ const publicUser = toPublicUser(user);
74
+ const tokenMode = String(req.headers["x-auth-mode"] || "").toLowerCase() === "token";
75
+ const token = await Auth.login(res, { ...publicUser, sv: sessionVersion(user) }, "auth", tokenMode ? { setCookie: false } : {});
76
+ return tokenMode ? { user: publicUser, token } : { user: publicUser };
77
+ }
78
+
79
+ /**
80
+ * Loads the current user for every authenticated request: deleted accounts and sessions issued before the last
81
+ * password change or reset are rejected, and role/name/email changes apply immediately instead of at token expiry.
82
+ * @param {Object} payload - Verified token payload.
83
+ * @returns {Promise<Object|null>}
84
+ */
85
+ async function resolveSessionUser(payload) {
86
+ if (payload?.id === undefined || payload?.id === null) return null;
87
+ const user = await User.find(payload.id);
88
+ if (!user || sessionVersion(user) !== Number(payload.sv || 0)) return null;
89
+ return toPublicUser(user);
90
+ }
91
+
92
+ /**
93
+ * Creates the REST authentication router.
94
+ *
95
+ * Always: `GET /me`, `POST /login`, `POST /logout`.
96
+ * `register`: `POST /register` (`true`, or `"first-user"` to allow only the first account, e.g. a blog owner).
97
+ * `passwordReset`: `POST /forgot-password` and `POST /reset-password`.
98
+ * `profile`: `PUT /profile` (changing the email requires `current_password`), `PUT /password`, and
99
+ * `POST /logout-all` for the signed-in user.
100
+ * Every protected request reloads the user (`Auth.configure({ resolveUser })`), so password changes and resets
101
+ * sign out other sessions, and deleted accounts or role changes take effect immediately.
102
+ * @param {Object} [options={}]
103
+ * @param {string} [options.basePath="/api/auth"]
104
+ * @param {boolean|"first-user"} [options.register=false]
105
+ * @param {string} [options.defaultRole="user"]
106
+ * @param {boolean} [options.firstUserAdmin=false] - The first registered account receives the `admin` role.
107
+ * @param {false|{ model: any, send: (data: { user: Object, url: string, token: string }) => Promise<void>|void, ttlMinutes?: number, resetPath?: string }} [options.passwordReset=false]
108
+ * @param {boolean} [options.profile=false]
109
+ * @param {Object|false} [options.rateLimit] - Rate limit applied to login, register, and password endpoints.
110
+ * @returns {Router}
111
+ */
112
+ export function createAuthRouter(options = {}) {
113
+ const {
114
+ basePath = "/api/auth",
115
+ register = false,
116
+ defaultRole = "user",
117
+ firstUserAdmin = false,
118
+ passwordReset = false,
119
+ profile = false,
120
+ rateLimit = { max: 20, windowMs: 60000 },
121
+ } = options;
122
+
123
+ Auth.configure({ resolveUser: resolveSessionUser });
124
+ const routerAuth = new Router(basePath);
125
+ routerAuth.use(Csrf.middleware());
126
+ const limiter = rateLimit ? App.rateLimit(rateLimit) : (req, res, next) => next();
127
+
128
+ /**
129
+ * Checks whether self-registration is currently open.
130
+ * @returns {Promise<boolean>}
131
+ */
132
+ async function registrationOpen() {
133
+ if (register === "first-user") return (await User.count()) === 0;
134
+ return Boolean(register);
135
+ }
136
+
137
+ const loginValidator = new Validator(
138
+ { email: { required: true, email: true }, password: { required: true, min: 6 } },
139
+ "en"
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: 8, max: 120 },
146
+ },
147
+ "en"
148
+ );
149
+
150
+ routerAuth.get("/me", Auth.optional(), async (req, res) => {
151
+ const user = req.user ? toPublicUser(req.user) : null;
152
+ res.ok(
153
+ { user, authenticated: Boolean(user), registerEnabled: await registrationOpen() },
154
+ user ? "Authenticated" : "Guest session"
155
+ );
156
+ });
157
+
158
+ routerAuth.post("/login", limiter, loginValidator.middleware(), async (req, res) => {
159
+ const found = await User.find({ email: cleanEmail(req.body.email) }, { withHidden: true });
160
+ if (!(await verifyPassword(String(req.body.password || ""), found?.password))) {
161
+ return res.error("Invalid email or password", 401, [{ field: "email", message: "Invalid email or password" }]);
162
+ }
163
+ return res.ok(await issueSession(req, res, found), "Signed in");
164
+ });
165
+
166
+ routerAuth.post("/register", limiter, registerValidator.middleware(), async (req, res) => {
167
+ if (!(await registrationOpen())) return res.forbidden("Registration is disabled");
168
+
169
+ const email = cleanEmail(req.body.email);
170
+ if (await User.exists({ email })) {
171
+ return res.error("Email is already registered", 409, [{ field: "email", message: "Email is already registered" }]);
172
+ }
173
+
174
+ const isFirst = firstUserAdmin && (await User.count()) === 0;
175
+ const id = await User.create({
176
+ name: String(req.body.name).trim(),
177
+ email,
178
+ password: String(req.body.password),
179
+ role: isFirst ? "admin" : defaultRole,
180
+ });
181
+ return res.created(await issueSession(req, res, await User.find(id)), "Account created");
182
+ });
183
+
184
+ routerAuth.post("/logout", async (req, res) => {
185
+ await Auth.logout(res, "auth", {}, req);
186
+ return res.ok({ loggedOut: true }, "Signed out");
187
+ });
188
+
189
+ if (passwordReset) {
190
+ const ResetModel = passwordReset.model;
191
+ const ttlMs = (passwordReset.ttlMinutes || 60) * 60000;
192
+ const resetPath = passwordReset.resetPath || "/app/reset-password";
193
+ const forgotValidator = new Validator({ email: { required: true, email: true } }, "en");
194
+ const resetValidator = new Validator(
195
+ {
196
+ email: { required: true, email: true },
197
+ token: { required: true, min: 32 },
198
+ password: { required: true, min: 8, max: 120 },
199
+ },
200
+ "en"
201
+ );
202
+
203
+ routerAuth.post("/forgot-password", limiter, forgotValidator.middleware(), async (req, res) => {
204
+ const email = cleanEmail(req.body.email);
205
+ const user = await User.find({ email });
206
+ if (user) {
207
+ const token = crypto.randomBytes(32).toString("hex");
208
+ await ResetModel.delete({ email }, { force: true });
209
+ await ResetModel.create({
210
+ email,
211
+ token_hash: hashToken(token),
212
+ expires_at: new Date(Date.now() + ttlMs).toISOString(),
213
+ });
214
+ const origin = (process.env.APP_URL || `${req.protocol}://${req.get("host")}`).replace(/\/$/, "");
215
+ const url = `${origin}${resetPath}?token=${token}&email=${encodeURIComponent(email)}`;
216
+ await passwordReset.send({ user: toPublicUser(user), url, token });
217
+ }
218
+ return res.ok({ sent: true }, "If the email is registered, a reset link has been sent");
219
+ });
220
+
221
+ routerAuth.post("/reset-password", limiter, resetValidator.middleware(), async (req, res) => {
222
+ const email = cleanEmail(req.body.email);
223
+ const record = await ResetModel.find({ email });
224
+ const expected = Buffer.from(record?.token_hash || "", "utf8");
225
+ const given = Buffer.from(hashToken(String(req.body.token)), "utf8");
226
+ const valid =
227
+ Boolean(record) &&
228
+ expected.length === given.length &&
229
+ crypto.timingSafeEqual(expected, given) &&
230
+ Date.parse(record.expires_at) > Date.now();
231
+
232
+ if (!valid) {
233
+ return res.error("This reset link is invalid or has expired", 400, [
234
+ { field: "password", message: "This reset link is invalid or has expired" },
235
+ ]);
236
+ }
237
+
238
+ const user = await User.find({ email });
239
+ if (user) {
240
+ await User.update(user.id, { password: String(req.body.password), session_version: sessionVersion(user) + 1 });
241
+ }
242
+ await ResetModel.delete({ email }, { force: true });
243
+ return res.ok({ reset: true }, "Password updated, you can sign in now");
244
+ });
245
+ }
246
+
247
+ if (profile) {
248
+ const profileValidator = new Validator(
249
+ {
250
+ name: { required: true, min: 2, max: 150 },
251
+ email: { required: true, email: true },
252
+ current_password: { required: false },
253
+ },
254
+ "en"
255
+ );
256
+ const passwordValidator = new Validator(
257
+ { current_password: { required: true }, password: { required: true, min: 8, max: 120 } },
258
+ "en"
259
+ );
260
+
261
+ routerAuth.put("/profile", Auth.protect(), limiter, profileValidator.middleware(), async (req, res) => {
262
+ const email = cleanEmail(req.body.email);
263
+ const current = await User.find(req.user.id, { withHidden: true });
264
+ if (!current) return res.unauthorized("Account not found");
265
+ if (email !== cleanEmail(current.email)) {
266
+ const confirmed = await Hash.verify(String(req.body.current_password || ""), current.password);
267
+ if (!confirmed) {
268
+ return res.error("Enter your current password to change your email", 400, [
269
+ { field: "current_password", message: "Enter your current password to change your email" },
270
+ ]);
271
+ }
272
+ }
273
+ const taken = await User.find({ email });
274
+ if (taken && String(taken.id) !== String(req.user.id)) {
275
+ return res.error("Email is already registered", 409, [{ field: "email", message: "Email is already registered" }]);
276
+ }
277
+ await User.update(req.user.id, { name: String(req.body.name).trim(), email });
278
+ const updated = await User.find(req.user.id);
279
+ if (!updated) return res.unauthorized("Account not found");
280
+ return res.ok(await issueSession(req, res, updated), "Profile updated");
281
+ });
282
+
283
+ routerAuth.put("/password", Auth.protect(), limiter, passwordValidator.middleware(), async (req, res) => {
284
+ const found = await User.find(req.user.id, { withHidden: true });
285
+ if (!found || !(await Hash.verify(String(req.body.current_password), found.password))) {
286
+ return res.error("Current password is incorrect", 400, [
287
+ { field: "current_password", message: "Current password is incorrect" },
288
+ ]);
289
+ }
290
+ await User.update(found.id, { password: String(req.body.password), session_version: sessionVersion(found) + 1 });
291
+ const updated = await User.find(found.id);
292
+ return res.ok({ updated: true, ...(await issueSession(req, res, updated)) }, "Password changed, other sessions were signed out");
293
+ });
294
+
295
+ routerAuth.post("/logout-all", Auth.protect(), async (req, res) => {
296
+ const found = await User.find(req.user.id);
297
+ if (found) await User.update(found.id, { session_version: sessionVersion(found) + 1 });
298
+ await Auth.logout(res, "auth", {}, req);
299
+ return res.ok({ loggedOut: true }, "Signed out of every device");
300
+ });
301
+ }
302
+
303
+ return routerAuth;
304
+ }
@@ -0,0 +1,55 @@
1
+ <!DOCTYPE html>
2
+ <html lang="{{ lang }}">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <meta name="color-scheme" content="light dark">
7
+ <script>
8
+ (function(){try{var k="bb-theme",t=localStorage.getItem(k),m=document.querySelector('meta[name="color-scheme"]'),d=document.documentElement,r=t==="light"||t==="dark"?t:(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");d.classList.toggle("dark",r==="dark");d.setAttribute("data-theme",r);if(m)m.content=t==="light"||t==="dark"?t:"light dark";}catch(e){}})();
9
+ </script>
10
+ <title>{{ title }}</title>
11
+ {{#if description}}
12
+ <meta name="description" content="{{ description }}">
13
+ {{/if}}
14
+ {{#if canonical}}
15
+ <link rel="canonical" href="{{ canonical }}">
16
+ {{/if}}
17
+ {{{ headHtml }}}
18
+ <link rel="icon" href="/images/favicon.ico">
19
+ {{ vite "app/resources/styles.css" }}
20
+ <script src="/js/bluebird.js" defer></script>
21
+ </head>
22
+ <body class="min-h-screen flex flex-col bg-app text-foreground antialiased">
23
+ <header class="sticky top-0 z-30 border-b border-border/75 glass">
24
+ <nav aria-label="Primary" class="mx-auto flex max-w-5xl items-center justify-between gap-4 px-4 py-3 md:px-6">
25
+ <a href="/" class="flex items-center gap-2.5 text-sm font-semibold tracking-tight text-foreground">
26
+ <span class="inline-flex size-8 items-center justify-center rounded-lg border border-border bg-card shadow-2xs" aria-hidden="true">
27
+ <svg class="size-4 text-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 7h.01M3.4 18H12a8 8 0 0 0 8-8V7a4 4 0 0 0-7.28-2.3L2 20"/><path d="m20 7 2 .5-2 .5M10 18v3M14 17.75V21M7 18a6 6 0 0 0 3.84-10.61"/></svg>
28
+ </span>
29
+ <span class="brand whitespace-nowrap text-base">%%APP_TITLE%%</span>
30
+ </a>
31
+ <div class="flex items-center gap-1.5">
32
+ {{> nav }}
33
+ <button
34
+ type="button"
35
+ data-theme-toggle
36
+ aria-label="Toggle theme"
37
+ title="Toggle theme"
38
+ class="btn btn-ghost btn-icon btn-sm text-muted-foreground hover:text-foreground"
39
+ >
40
+ <svg class="hidden dark:block" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"/></svg>
41
+ <svg class="dark:hidden" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"/></svg>
42
+ </button>
43
+ </div>
44
+ </nav>
45
+ </header>
46
+
47
+ <main class="mx-auto w-full max-w-5xl flex-1 px-4 py-10 md:px-6">
48
+ {{{ body }}}
49
+ </main>
50
+
51
+ <footer class="border-t border-border/75 py-6 text-center text-xs text-muted-foreground">
52
+ %%APP_TITLE%% &middot; Built with Bluebird.js
53
+ </footer>
54
+ </body>
55
+ </html>
@@ -0,0 +1,14 @@
1
+ <section class="mx-auto flex max-w-md flex-col items-center py-20 text-center">
2
+ <span class="badge">
3
+ <span class="badge-dot bg-warning" aria-hidden="true"></span>
4
+ 404
5
+ </span>
6
+ <h1 class="mt-4 text-3xl font-semibold tracking-tight text-foreground">Page not found</h1>
7
+ <p class="mt-3 text-muted-foreground">
8
+ The page <code class="rounded-md bg-muted px-1.5 py-0.5 text-sm text-foreground">{{ path }}</code> does not exist or was moved.
9
+ </p>
10
+ <div class="mt-8 flex flex-wrap justify-center gap-2.5">
11
+ <a href="/" class="btn btn-primary">Back to home</a>
12
+ <a href="/app" class="btn btn-outline">Open the app</a>
13
+ </div>
14
+ </section>
@@ -0,0 +1,27 @@
1
+ <!DOCTYPE html>
2
+ <html lang="{{ lang }}"{{{ htmlAttrs }}}>
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <meta name="color-scheme" content="light dark">
7
+ <script>
8
+ (function () {
9
+ try {
10
+ var k = "bb-theme";
11
+ var t = localStorage.getItem(k);
12
+ var m = document.querySelector('meta[name="color-scheme"]');
13
+ var d = document.documentElement;
14
+ var r = t === "light" || t === "dark" ? t : (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
15
+ d.classList.toggle("dark", r === "dark");
16
+ d.setAttribute("data-theme", r);
17
+ if (m) m.content = t === "light" || t === "dark" ? t : "light dark";
18
+ } catch (e) {}
19
+ })();
20
+ </script>
21
+ {{{ head }}}
22
+ </head>
23
+ <body{{{ bodyAttrs }}}>
24
+ <div id="root" class="{{ rootClass }}">{{{ skeleton }}}</div>
25
+ {{{ scripts }}}
26
+ </body>
27
+ </html>
@@ -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
+ }
@@ -0,0 +1,18 @@
1
+ import Model from "@seip/bluebird-js/core/model.js";
2
+
3
+ /**
4
+ * Example resource owned by a user. Rename or copy it for your own resources.
5
+ */
6
+ export default class Note extends Model {
7
+ static table = "notes";
8
+ static primaryKey = "id";
9
+ static timestamps = true;
10
+ static softDelete = true;
11
+
12
+ static schema = {
13
+ id: { type: "int", primary: true, auto: true },
14
+ user_id: { type: "int", required: true },
15
+ title: { type: "string", length: 200, required: true },
16
+ content: { type: "text" },
17
+ };
18
+ }
@@ -0,0 +1,82 @@
1
+ import Router from "@seip/bluebird-js/core/router.js";
2
+ import Auth from "@seip/bluebird-js/core/auth.js";
3
+ import Csrf from "@seip/bluebird-js/core/csrf.js";
4
+ import Validator from "@seip/bluebird-js/core/validate.js";
5
+ import Note from "../models/note.js";
6
+
7
+ const routerApi = new Router("/api");
8
+ routerApi.use(Csrf.middleware());
9
+
10
+ const noteValidator = new Validator(
11
+ {
12
+ title: { required: true, min: 1, max: 200 },
13
+ content: { required: false, max: 20000 },
14
+ },
15
+ "en"
16
+ );
17
+
18
+ /**
19
+ * Finds a note that belongs to the signed-in user.
20
+ * @param {import('express').Request} req
21
+ * @returns {Promise<Object|null>}
22
+ */
23
+ function ownNote(req) {
24
+ return Note.find({ id: req.params.id, user_id: req.user.id });
25
+ }
26
+
27
+ routerApi.get("/", (req, res) => {
28
+ res.ok({
29
+ name: "%%APP_TITLE%% API",
30
+ endpoints: [
31
+ "POST /api/auth/register",
32
+ "POST /api/auth/login",
33
+ "GET /api/auth/me",
34
+ "GET /api/notes?page=1",
35
+ "POST /api/notes",
36
+ "GET /api/notes/:id",
37
+ "PUT /api/notes/:id",
38
+ "DELETE /api/notes/:id",
39
+ "GET /api/health",
40
+ ],
41
+ });
42
+ });
43
+
44
+ routerApi.get("/notes", Auth.protect(), async (req, res) => {
45
+ const result = await Note.paginate({
46
+ where: { user_id: req.user.id },
47
+ order: "updated_at DESC",
48
+ page: req.query.page,
49
+ limit: Math.min(100, parseInt(req.query.limit, 10) || 20),
50
+ });
51
+ res.paginate(result.data, { page: result.page, limit: result.limit, total: result.total, totalPages: result.totalPages });
52
+ });
53
+
54
+ routerApi.post("/notes", Auth.protect(), noteValidator.middleware(), async (req, res) => {
55
+ const id = await Note.create({
56
+ user_id: req.user.id,
57
+ title: String(req.body.title).trim(),
58
+ content: String(req.body.content || ""),
59
+ });
60
+ res.created(await Note.find(id), "Note created");
61
+ });
62
+
63
+ routerApi.get("/notes/:id", Auth.protect(), async (req, res) => {
64
+ const note = await ownNote(req);
65
+ return note ? res.ok(note) : res.notFound("Note not found");
66
+ });
67
+
68
+ routerApi.put("/notes/:id", Auth.protect(), noteValidator.middleware(), async (req, res) => {
69
+ const note = await ownNote(req);
70
+ if (!note) return res.notFound("Note not found");
71
+ await Note.update(note.id, { title: String(req.body.title).trim(), content: String(req.body.content || "") });
72
+ return res.ok(await Note.find(note.id), "Note saved");
73
+ });
74
+
75
+ routerApi.delete("/notes/:id", Auth.protect(), async (req, res) => {
76
+ const note = await ownNote(req);
77
+ if (!note) return res.notFound("Note not found");
78
+ await Note.delete(note.id);
79
+ return res.ok({ id: note.id }, "Note deleted");
80
+ });
81
+
82
+ export default routerApi;
@@ -0,0 +1,11 @@
1
+ import { createAuthRouter } from "./auth-router.js";
2
+
3
+ /**
4
+ * `/api/auth/*`: me, login, logout, register, profile, and password change.
5
+ * Every new account gets the `user` role; promote admins yourself (seed, SQL, or an admin-only endpoint).
6
+ * Send `X-Auth-Mode: token` to receive `{ user, token }` and authenticate with `Authorization: Bearer <token>`.
7
+ */
8
+ export default createAuthRouter({
9
+ register: true,
10
+ profile: true,
11
+ });
@@ -0,0 +1,19 @@
1
+ import App from "@seip/bluebird-js/core/app.js";
2
+ import { ensureSchema } from "./app/database.js";
3
+ import User from "./app/models/user.js";
4
+ import Note from "./app/models/note.js";
5
+ import routerApi from "./app/routes/api.js";
6
+ import routerAuth from "./app/routes/auth.js";
7
+
8
+ await ensureSchema([User, Note]);
9
+
10
+ /**
11
+ * Headless REST API entrypoint (no HTML views, no React, no Vite).
12
+ */
13
+ const app = new App({
14
+ routes: [routerAuth, routerApi],
15
+ port: Number(process.env.PORT || 3000),
16
+ vite: false,
17
+ });
18
+
19
+ app.run();
@@ -0,0 +1,13 @@
1
+ {
2
+ "description": "Headless REST API: JWT auth (cookie or bearer token) and a paginated CRUD resource, no frontend",
3
+ "layers": [
4
+ "_auth"
5
+ ],
6
+ "client": false,
7
+ "database": "required",
8
+ "routes": [
9
+ "/api/auth/* register, login, me, profile (cookie or bearer token)",
10
+ "/api/notes paginated CRUD example",
11
+ "/api/health health check"
12
+ ]
13
+ }
@@ -0,0 +1,11 @@
1
+ import colors from "@seip/bluebird-js/core/util/colors.js";
2
+
3
+ /**
4
+ * Delivers the password reset link. Replace the body with your mail provider (SMTP, Resend, SES, Postmark...).
5
+ * Until then the link is printed in the server console so the flow works locally.
6
+ * @param {{ user: { name: string, email: string }, url: string }} data
7
+ * @returns {Promise<void>}
8
+ */
9
+ export async function sendPasswordResetLink({ user, url }) {
10
+ console.log(colors.cyan(`[MAIL] Password reset for ${user.email}: ${url}`));
11
+ }
@@ -0,0 +1,18 @@
1
+ import Model from "@seip/bluebird-js/core/model.js";
2
+
3
+ /**
4
+ * Pending password reset requests. Only the SHA-256 hash of each token is stored.
5
+ */
6
+ export default class PasswordReset extends Model {
7
+ static table = "password_resets";
8
+ static primaryKey = "id";
9
+ static timestamps = true;
10
+ static softDelete = false;
11
+
12
+ static schema = {
13
+ id: { type: "int", primary: true, auto: true },
14
+ email: { type: "string", length: 150, required: true },
15
+ token_hash: { type: "string", length: 64, required: true },
16
+ expires_at: { type: "string", length: 40, required: true },
17
+ };
18
+ }
@@ -0,0 +1,21 @@
1
+ <section class="py-10 md:py-16">
2
+ <span class="badge">
3
+ <span class="badge-dot bg-info" aria-hidden="true"></span>
4
+ Welcome
5
+ </span>
6
+ <h1 class="mt-4 max-w-3xl text-3xl font-semibold tracking-tight text-foreground sm:text-4xl md:text-5xl md:leading-[1.1]">
7
+ {{ title }}
8
+ </h1>
9
+ <p class="mt-4 max-w-2xl text-base leading-relaxed text-muted-foreground md:text-lg">
10
+ This landing page is server-rendered from <code>app/resources/html/home.html</code>. Accounts, dashboard, and
11
+ profile live in the React app on <code>/app</code>.
12
+ </p>
13
+ <div class="mt-8 flex flex-wrap items-center gap-2.5">
14
+ <a href="/app/register" class="btn btn-primary">
15
+ Create an account
16
+ </a>
17
+ <a href="/app/login" class="btn btn-outline">
18
+ Sign in
19
+ </a>
20
+ </div>
21
+ </section>
@@ -0,0 +1,2 @@
1
+ <a href="/app/login" class="nav-link">Sign in</a>
2
+ <a href="/app/register" class="btn btn-primary btn-sm">Sign up</a>