@seip/bluebird-js 0.1.2 → 0.1.5

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 (43) hide show
  1. package/.vscode/extensions.json +7 -0
  2. package/.vscode/settings.json +10 -0
  3. package/AGENTS.md +495 -454
  4. package/README.md +528 -353
  5. package/app/routes/web.js +47 -55
  6. package/app/views/about.jsx +98 -0
  7. package/app/views/components/Header.jsx +42 -0
  8. package/app/views/components/LiveCounter.jsx +66 -0
  9. package/app/views/dashboard.jsx +300 -0
  10. package/app/views/index.jsx +123 -0
  11. package/app/views/layouts/main/view.jsx +201 -0
  12. package/app/views/legal/terms.html +29 -19
  13. package/app/views/login.jsx +141 -0
  14. package/core/actions.d.ts +4 -0
  15. package/core/actions.js +329 -0
  16. package/core/app.js +38 -6
  17. package/core/cli/doctor.js +3 -4
  18. package/core/cli/init.js +20 -6
  19. package/core/cli/migrate.js +418 -145
  20. package/core/cli/view.js +76 -11
  21. package/core/database.js +6 -10
  22. package/core/debug.js +1 -1
  23. package/core/html.d.ts +54 -42
  24. package/core/html.js +473 -217
  25. package/core/index.d.ts +1385 -1190
  26. package/core/jsx.d.ts +38 -0
  27. package/core/jsx.js +1432 -0
  28. package/core/model.js +271 -61
  29. package/core/render-cache.js +212 -212
  30. package/core/render.d.ts +20 -2
  31. package/core/render.js +459 -51
  32. package/core/validate.js +1 -1
  33. package/core/view-loader.js +360 -24
  34. package/package.json +9 -3
  35. package/public/js/bluebird-client.js +3160 -1780
  36. package/public/js/tailwind.js +8 -0
  37. package/app/views/about.js +0 -63
  38. package/app/views/dashboard.js +0 -147
  39. package/app/views/index.js +0 -80
  40. package/app/views/layouts/main/view.js +0 -81
  41. package/app/views/login.js +0 -80
  42. package/public/css/bluebird.min.css +0 -2
  43. package/public/js/bluebird.min.js +0 -1073
@@ -0,0 +1,329 @@
1
+ import Csrf from "./csrf.js";
2
+ import Validator from "./validate.js";
3
+ import Render from "./render.js";
4
+
5
+ const DEFAULT_MAX_BYTES = 64 * 1024;
6
+ const DEFAULT_MAX_DEPTH = 6;
7
+ const DEFAULT_MAX_KEYS = 100;
8
+ const BANNED_KEYS = new Set(["__proto__", "constructor", "prototype"]);
9
+
10
+ /**
11
+ * Recursively sanitizes and validates an incoming action payload object to prevent
12
+ * prototype pollution (`__proto__`, `constructor`, `prototype`), excessive nesting depth,
13
+ * and key-flooding memory attacks.
14
+ *
15
+ * @param {any} input
16
+ * @param {number} [maxDepth=DEFAULT_MAX_DEPTH]
17
+ * @param {number} [maxKeys=DEFAULT_MAX_KEYS]
18
+ * @param {number} [currentDepth=0]
19
+ * @param {{ count: number }} [keyCounter={ count: 0 }]
20
+ * @returns {any}
21
+ */
22
+ export function sanitizeActionPayload(
23
+ input,
24
+ maxDepth = DEFAULT_MAX_DEPTH,
25
+ maxKeys = DEFAULT_MAX_KEYS,
26
+ currentDepth = 0,
27
+ keyCounter = { count: 0 }
28
+ ) {
29
+ if (input === null || input === undefined) return input;
30
+ if (typeof input !== "object") return input;
31
+
32
+ if (currentDepth > maxDepth) {
33
+ const err = new Error("Payload nesting depth limit exceeded.");
34
+ err.statusCode = 413;
35
+ throw err;
36
+ }
37
+
38
+ if (Array.isArray(input)) {
39
+ if (input.length > maxKeys) {
40
+ const err = new Error(`Payload array length exceeds maximum allowed (${maxKeys}).`);
41
+ err.statusCode = 413;
42
+ throw err;
43
+ }
44
+ return input.map((item) =>
45
+ sanitizeActionPayload(item, maxDepth, maxKeys, currentDepth + 1, keyCounter)
46
+ );
47
+ }
48
+
49
+ const clean = Object.create(null);
50
+ const entries = Object.entries(input);
51
+ for (const [k, v] of entries) {
52
+ if (BANNED_KEYS.has(k)) continue;
53
+ keyCounter.count++;
54
+ if (keyCounter.count > maxKeys) {
55
+ const err = new Error(`Payload key count exceeds maximum allowed (${maxKeys}).`);
56
+ err.statusCode = 413;
57
+ throw err;
58
+ }
59
+ clean[k] = sanitizeActionPayload(v, maxDepth, maxKeys, currentDepth + 1, keyCounter);
60
+ }
61
+
62
+ return { ...clean };
63
+ }
64
+
65
+ /**
66
+ * Parses byte size strings like "64kb", "1mb", or numbers into integer bytes.
67
+ * @param {number|string} [limit]
68
+ * @returns {number}
69
+ */
70
+ export function parseByteLimit(limit) {
71
+ if (typeof limit === "number" && limit > 0) return limit;
72
+ if (typeof limit === "string") {
73
+ const match = limit.trim().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb)?$/i);
74
+ if (match) {
75
+ const num = parseFloat(match[1]);
76
+ const unit = (match[2] || "b").toLowerCase();
77
+ if (unit === "mb") return Math.floor(num * 1024 * 1024);
78
+ if (unit === "kb") return Math.floor(num * 1024);
79
+ return Math.floor(num);
80
+ }
81
+ }
82
+ return DEFAULT_MAX_BYTES;
83
+ }
84
+
85
+ /**
86
+ * Native Server Actions manager for Bluebird.js.
87
+ * Wraps server mutation handlers with automatic CSRF verification, strict payload size/depth/key
88
+ * guards, optional schema validation, and reactive partial SSR re-rendering.
89
+ */
90
+ export class Actions {
91
+ /**
92
+ * Defines a single server action or a map of server actions with security and validation options.
93
+ *
94
+ * @example
95
+ * // Single action with schema validation and 32KB max payload
96
+ * export const actions = {
97
+ * updateProfile: Actions.define(
98
+ * {
99
+ * schema: { name: { required: true, min: 2 } },
100
+ * maxBytes: "32kb",
101
+ * },
102
+ * async ({ body, req, user }) => {
103
+ * await User.update(user.id, body, { only: ["name"] });
104
+ * return { updated: true };
105
+ * }
106
+ * ),
107
+ * };
108
+ *
109
+ * @param {Object|Function} optionsOrMap - Options object, action map, or handler function.
110
+ * @param {Function} [handlerFn] - Action handler function when first argument is options.
111
+ * @returns {Object}
112
+ */
113
+ static define(optionsOrMap, handlerFn) {
114
+ if (typeof optionsOrMap === "function") {
115
+ return {
116
+ __bb_action__: true,
117
+ options: {},
118
+ handler: optionsOrMap,
119
+ };
120
+ }
121
+
122
+ if (typeof handlerFn === "function") {
123
+ return {
124
+ __bb_action__: true,
125
+ options: optionsOrMap || {},
126
+ handler: handlerFn,
127
+ };
128
+ }
129
+
130
+ if (optionsOrMap && typeof optionsOrMap === "object") {
131
+ const out = {};
132
+ for (const [key, val] of Object.entries(optionsOrMap)) {
133
+ if (typeof val === "function") {
134
+ out[key] = { __bb_action__: true, options: {}, handler: val };
135
+ } else if (val && typeof val === "object" && typeof val.handler === "function") {
136
+ out[key] = {
137
+ __bb_action__: true,
138
+ options: val.options || val,
139
+ handler: val.handler,
140
+ };
141
+ }
142
+ }
143
+ return out;
144
+ }
145
+
146
+ return {};
147
+ }
148
+
149
+ /**
150
+ * Express route handler that dispatches incoming POST requests to the matching Server Action
151
+ * exported by a view module (`export const actions = { ... }`).
152
+ *
153
+ * Security checks performed automatically before invoking the action:
154
+ * 1. CSRF verification (header `x-csrf-token` or body `_csrf` matched against signed `_csrf` cookie).
155
+ * 2. Payload byte size guard (`Content-Length` and serialized body byte length, default 64KB).
156
+ * 3. Prototype pollution & deep-nesting guard (`__proto__`, `constructor`, `prototype`, maxDepth, maxKeys).
157
+ * 4. Optional `Validator` schema check if `schema` is configured on the action.
158
+ *
159
+ * @param {string} viewName - View name associated with the route.
160
+ * @param {Record<string, any>} actionsMap - Exported `actions` object from the view module.
161
+ * @returns {Function} Express route handler.
162
+ */
163
+ static createDispatcher(viewName, actionsMap) {
164
+ return async (req, res) => {
165
+ const actionName =
166
+ req.headers["x-bluebird-action"] ||
167
+ req.body?._action ||
168
+ req.query?._action ||
169
+ "default";
170
+
171
+ const rawAction =
172
+ actionsMap[actionName] ||
173
+ (actionName === "default" && typeof actionsMap === "function" ? actionsMap : null);
174
+
175
+ if (!rawAction) {
176
+ return res.status(404).json({
177
+ status: "error",
178
+ message: `Action '${String(actionName)}' not found on view '${viewName}'.`,
179
+ });
180
+ }
181
+
182
+ const actionDef =
183
+ typeof rawAction === "function"
184
+ ? { options: {}, handler: rawAction }
185
+ : rawAction;
186
+ const opts = actionDef.options || {};
187
+ const handler = actionDef.handler;
188
+
189
+ if (typeof handler !== "function") {
190
+ return res.status(404).json({
191
+ status: "error",
192
+ message: `Invalid handler for action '${String(actionName)}'.`,
193
+ });
194
+ }
195
+
196
+ const maxBytes = parseByteLimit(opts.maxBytes ?? opts.limit ?? DEFAULT_MAX_BYTES);
197
+ const maxDepth = opts.maxDepth ?? DEFAULT_MAX_DEPTH;
198
+ const maxKeys = opts.maxKeys ?? DEFAULT_MAX_KEYS;
199
+
200
+ const contentLength = parseInt(req.headers["content-length"] || "0", 10);
201
+ if (contentLength > maxBytes) {
202
+ return res.status(413).json({
203
+ status: "error",
204
+ message: `Action payload too large (exceeds ${maxBytes} bytes).`,
205
+ });
206
+ }
207
+
208
+ const rawBodyStr = JSON.stringify(req.body || {});
209
+ if (Buffer.byteLength(rawBodyStr, "utf-8") > maxBytes) {
210
+ return res.status(413).json({
211
+ status: "error",
212
+ message: `Action payload size exceeds maximum allowed (${maxBytes} bytes).`,
213
+ });
214
+ }
215
+
216
+ if (opts.csrf !== false) {
217
+ const cookieToken = req.cookies?.["_csrf"];
218
+ const headerToken =
219
+ req.headers["x-csrf-token"] ||
220
+ req.body?._csrf ||
221
+ req.query?._csrf;
222
+
223
+ if (
224
+ !cookieToken ||
225
+ !headerToken ||
226
+ cookieToken !== headerToken ||
227
+ !Csrf.verifyToken(headerToken)
228
+ ) {
229
+ return res.status(403).json({
230
+ status: "error",
231
+ message: "Invalid or missing CSRF token for server action.",
232
+ });
233
+ }
234
+ }
235
+
236
+ let safeBody = {};
237
+ try {
238
+ safeBody = sanitizeActionPayload(req.body || {}, maxDepth, maxKeys);
239
+ delete safeBody._csrf;
240
+ delete safeBody._action;
241
+ } catch (err) {
242
+ return res.status(err.statusCode || 400).json({
243
+ status: "error",
244
+ message: err.message || "Invalid action payload.",
245
+ });
246
+ }
247
+
248
+ if (opts.schema) {
249
+ const validator =
250
+ opts.schema instanceof Validator
251
+ ? opts.schema
252
+ : new Validator(opts.schema, req.lang || "en");
253
+ const validation = await validator.validate(safeBody);
254
+ if (!validation.success) {
255
+ return res.status(400).json({
256
+ status: "error",
257
+ message: validation.message?.[0] || "Validation failed.",
258
+ errors: validation.errors,
259
+ });
260
+ }
261
+ }
262
+
263
+ const ctx = {
264
+ req,
265
+ res,
266
+ user: req.user,
267
+ body: safeBody,
268
+ payload: safeBody,
269
+ params: req.params || {},
270
+ query: req.query || {},
271
+ action: String(actionName),
272
+ };
273
+
274
+ const result = await handler(ctx, safeBody);
275
+ if (res.headersSent) return;
276
+
277
+ if (result && typeof result === "object" && typeof result.redirect === "string") {
278
+ return Render.redirect(req, res, result.redirect);
279
+ }
280
+
281
+ const wantsPartial =
282
+ req.headers["x-bluebird-partial"] === "1" ||
283
+ req.query?._partial === "1" ||
284
+ (result && typeof result === "object" && result.reRender === true);
285
+
286
+ if (wantsPartial) {
287
+ const extraProps =
288
+ result && typeof result === "object" && !Array.isArray(result)
289
+ ? result.props || result
290
+ : {};
291
+ return Render.send(res, viewName, {
292
+ user: req.user,
293
+ params: req.params,
294
+ query: req.query,
295
+ actionResult: result,
296
+ ...extraProps,
297
+ _layout: false,
298
+ });
299
+ }
300
+
301
+ const expectsJson =
302
+ req.headers["x-bluebird-action"] ||
303
+ req.headers["x-requested-with"] === "XMLHttpRequest" ||
304
+ req.headers.accept?.includes("application/json");
305
+
306
+ if (expectsJson) {
307
+ return res.status(200).json({
308
+ status: "success",
309
+ action: String(actionName),
310
+ data: result ?? null,
311
+ });
312
+ }
313
+
314
+ const extraProps =
315
+ result && typeof result === "object" && !Array.isArray(result)
316
+ ? result.props || result
317
+ : {};
318
+ return Render.send(res, viewName, {
319
+ user: req.user,
320
+ params: req.params,
321
+ query: req.query,
322
+ actionResult: result,
323
+ ...extraProps,
324
+ });
325
+ };
326
+ }
327
+ }
328
+
329
+ export default Actions;
package/core/app.js CHANGED
@@ -224,6 +224,8 @@ class App {
224
224
  this.compression = options.compression ?? false;
225
225
  this.security = options.security ?? true;
226
226
  this.rateLimit = options.rateLimit ?? false;
227
+ this.noAutoDiscoverRoutes = Boolean(options.noAutoDiscoverRoutes);
228
+ this.autoRoutes = this.noAutoDiscoverRoutes ? false : (options.autoRoutes ?? true);
227
229
  this.trustProxy = options.trustProxy ?? !this.desktop;
228
230
  this.debug = options.debug !== undefined ? Boolean(options.debug) : (props.debug || process.env.DEBUG === "true");
229
231
  this._loggerInstance = null;
@@ -296,16 +298,30 @@ class App {
296
298
  */
297
299
  _setupCoreMiddlewares() {
298
300
  if (this.compression) {
301
+ let compressionMiddleware = null;
299
302
  import("compression")
300
303
  .then((mod) => {
301
304
  const comp = mod.default || mod;
302
- this.app.use(comp());
305
+ compressionMiddleware = comp();
303
306
  })
304
307
  .catch(() => {});
308
+
309
+ this.app.use((req, res, next) => {
310
+ if (compressionMiddleware) {
311
+ return compressionMiddleware(req, res, next);
312
+ }
313
+ next();
314
+ });
305
315
  }
306
316
 
307
- if (this.json) this.app.use(express.json());
308
- if (this.urlencoded) this.app.use(express.urlencoded({ extended: true }));
317
+ if (this.json) {
318
+ const jsonOpts = typeof this.json === "object" ? this.json : { limit: "256kb" };
319
+ this.app.use(express.json(jsonOpts));
320
+ }
321
+ if (this.urlencoded) {
322
+ const urlOpts = typeof this.urlencoded === "object" ? { extended: true, ...this.urlencoded } : { extended: true, limit: "256kb" };
323
+ this.app.use(express.urlencoded(urlOpts));
324
+ }
309
325
  if (this.cookieParser) this.app.use(nativeCookieParser);
310
326
 
311
327
  if (this.security) {
@@ -454,7 +470,7 @@ class App {
454
470
  });
455
471
  }
456
472
 
457
- this._dispatchRoutes();
473
+ await this._dispatchRoutes();
458
474
 
459
475
  if (this.notFound) this._notFoundDefault();
460
476
 
@@ -514,16 +530,28 @@ class App {
514
530
  }
515
531
 
516
532
  /**
517
- * Attaches all registered routes to the Express application, including automatic SEO routes.
533
+ * Attaches all registered routes to the Express application, including automatic view routes and SEO routes.
518
534
  * @private
519
535
  */
520
- _dispatchRoutes() {
536
+ async _dispatchRoutes() {
521
537
  if (props.debug) {
522
538
  const debug = new Debug();
523
539
  const debugRouter = debug.getRouter();
524
540
  this.app.use(debugRouter.path, debugRouter.router);
525
541
  }
526
542
 
543
+ let autoViewRouter = null;
544
+ if (this.autoRoutes) {
545
+ try {
546
+ const [{ default: Router }, { default: Render }] = await Promise.all([
547
+ import("./router.js"),
548
+ import("./render.js"),
549
+ ]);
550
+ autoViewRouter = new Router("/");
551
+ await Render.autoRoutes(autoViewRouter);
552
+ } catch {}
553
+ }
554
+
527
555
  const hasSeoRouter = this.routes.some((r) => r._seo) || Seo.getRoutes().length > 0;
528
556
  if (hasSeoRouter) {
529
557
  this.app.get("/sitemap.xml", (req, res) => {
@@ -539,6 +567,10 @@ class App {
539
567
  this.routes.forEach((route) => {
540
568
  this.app.use(route.path, route.router);
541
569
  });
570
+
571
+ if (autoViewRouter) {
572
+ this.app.use(autoViewRouter.path, autoViewRouter.router);
573
+ }
542
574
  }
543
575
 
544
576
  /**
@@ -60,10 +60,9 @@ function findSampleStaticAsset() {
60
60
  if (!fs.existsSync(publicDir)) return null;
61
61
 
62
62
  const candidates = [
63
- "css/style.css",
64
- "js/index.js",
65
- "favicon.ico",
66
- "images/logo.png",
63
+ "js/tailwind.js",
64
+ "js/bluebird-client.js",
65
+ "images/favicon.ico",
67
66
  ];
68
67
 
69
68
  for (const candidate of candidates) {
package/core/cli/init.js CHANGED
@@ -290,7 +290,7 @@ ${dbEnvBlock}
290
290
  version: "1.0.0",
291
291
  type: "module",
292
292
  dependencies: {
293
- "@seip/bluebird-js": "^0.1.0",
293
+ "@seip/bluebird-js": "^0.1.5",
294
294
  },
295
295
  };
296
296
  }
@@ -326,7 +326,7 @@ ${dbEnvBlock}
326
326
  pkg.dependencies = {};
327
327
  }
328
328
  if (!pkg.dependencies["@seip/bluebird-js"]) {
329
- pkg.dependencies["@seip/bluebird-js"] = "^0.1.0";
329
+ pkg.dependencies["@seip/bluebird-js"] = "^0.1.5";
330
330
  }
331
331
 
332
332
  fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
@@ -424,9 +424,14 @@ window.__BLUEBIRD_ISLANDS__ = window.__BLUEBIRD_ISLANDS__ || {};
424
424
  window.__BLUEBIRD_ISLANDS__["RadioPlayer"] = RadioPlayer;
425
425
  window.__BLUEBIRD_ISLANDS__["LiveCounter"] = LiveCounter;
426
426
 
427
- window.__BLUEBIRD_MOUNT__ = (el, Component, props) => {
427
+ window.__BLUEBIRD_MOUNT__ = (el, Component, props, hydrate = false) => {
428
+ const element = React.createElement(Component, props);
429
+ if (hydrate && el.innerHTML.trim().length > 0 && typeof ReactDOM.hydrateRoot === "function") {
430
+ const root = ReactDOM.hydrateRoot(el, element);
431
+ return () => root.unmount();
432
+ }
428
433
  const root = ReactDOM.createRoot(el);
429
- root.render(React.createElement(Component, props));
434
+ root.render(element);
430
435
  return () => root.unmount();
431
436
  };
432
437
 
@@ -577,7 +582,16 @@ export default function LiveCounter({ initial = 0, label = "Interactive Counter"
577
582
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
578
583
  <title>{{ title }}</title>
579
584
  <meta name="description" content="{{ description }}">
580
- <link rel="stylesheet" href="/css/bluebird.min.css">
585
+ <link rel="preconnect" href="https://fonts.googleapis.com">
586
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
587
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
588
+ <script src="/js/tailwind.js"></script>
589
+ <style type="text/tailwindcss">
590
+ @custom-variant dark (&:where(.dark, .dark *, [data-theme="dark"], [data-theme="dark"] *));
591
+ @theme {
592
+ --font-sans: 'Inter', system-ui, -apple-system, sans-serif;
593
+ }
594
+ </style>
581
595
  {{{ bluebirdHead }}}
582
596
  </head>
583
597
  <body style="padding: 2rem; max-width: 800px; margin: 0 auto; font-family: system-ui, sans-serif;">
@@ -856,7 +870,7 @@ function showHelp() {
856
870
  console.log(` ${colors.green("npx bluebird-js doctor")} Runs system audit and HTTP smoke tests`);
857
871
  console.log(` ${colors.green("npx bluebird-js make:model <Name>")} Generates a new BaseModel class`);
858
872
  console.log(` ${colors.green("npx bluebird-js make:route <name> [--auth]")} Scaffolds REST route with validation`);
859
- console.log(` ${colors.green("npx bluebird-js make:view <name> [--ejs]")} Scaffolds HTML or EJS template`);
873
+ console.log(` ${colors.green("npx bluebird-js make:view <name> [--jsx|--js|--html]")} Scaffolds React JSX, JS or HTML view`);
860
874
  console.log(` ${colors.green("npx bluebird-js make:migration <name> [--model <M>]")} Creates new SQL migration`);
861
875
  console.log(` ${colors.green("npx bluebird-js migrate")} Applies pending SQL migrations`);
862
876
  console.log(` ${colors.green("npx bluebird-js migrate:status")} Displays applied migration batches`);