@seip/bluebird-js 0.0.0-stage → 0.0.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 (73) hide show
  1. package/.env_example +54 -0
  2. package/AGENTS.md +403 -0
  3. package/LICENSE +21 -0
  4. package/README.md +284 -2
  5. package/app/routes/api.js +50 -0
  6. package/app/routes/web.js +53 -0
  7. package/app/views/about.html +161 -0
  8. package/app/views/dashboard.html +140 -0
  9. package/app/views/index.html +150 -0
  10. package/app/views/login.html +144 -0
  11. package/core/app.d.ts +18 -0
  12. package/core/app.js +644 -0
  13. package/core/auth.d.ts +13 -0
  14. package/core/auth.js +326 -0
  15. package/core/cache.d.ts +17 -0
  16. package/core/cache.js +475 -0
  17. package/core/cli/doctor.js +287 -0
  18. package/core/cli/ecosystem.js +162 -0
  19. package/core/cli/init.js +779 -0
  20. package/core/cli/migrate.js +541 -0
  21. package/core/cli/model.js +66 -0
  22. package/core/cli/nginx.js +199 -0
  23. package/core/cli/route.js +121 -0
  24. package/core/cli/swagger.js +45 -0
  25. package/core/cli/view.js +77 -0
  26. package/core/config.d.ts +3 -0
  27. package/core/config.js +111 -0
  28. package/core/csrf.d.ts +3 -0
  29. package/core/csrf.js +114 -0
  30. package/core/database.d.ts +15 -0
  31. package/core/database.js +636 -0
  32. package/core/debug.d.ts +3 -0
  33. package/core/debug.js +250 -0
  34. package/core/hash.d.ts +3 -0
  35. package/core/hash.js +194 -0
  36. package/core/index.d.ts +1071 -0
  37. package/core/logger.d.ts +3 -0
  38. package/core/logger.js +124 -0
  39. package/core/middleware.d.ts +3 -0
  40. package/core/middleware.js +28 -0
  41. package/core/model.d.ts +19 -0
  42. package/core/model.js +600 -0
  43. package/core/queue.d.ts +13 -0
  44. package/core/queue.js +172 -0
  45. package/core/ratelimit.d.ts +3 -0
  46. package/core/ratelimit.js +145 -0
  47. package/core/redis.d.ts +21 -0
  48. package/core/redis.js +230 -0
  49. package/core/render.d.ts +3 -0
  50. package/core/render.js +676 -0
  51. package/core/router.d.ts +3 -0
  52. package/core/router.js +171 -0
  53. package/core/seo.d.ts +3 -0
  54. package/core/seo.js +106 -0
  55. package/core/swagger.d.ts +3 -0
  56. package/core/swagger.js +60 -0
  57. package/core/upload.d.ts +13 -0
  58. package/core/upload.js +102 -0
  59. package/core/util/colors.js +82 -0
  60. package/core/validate.d.ts +15 -0
  61. package/core/validate.js +364 -0
  62. package/core/vite.d.ts +3 -0
  63. package/core/vite.js +145 -0
  64. package/core/ws.d.ts +13 -0
  65. package/core/ws.js +245 -0
  66. package/index.js +18 -0
  67. package/jsconfig.json +15 -0
  68. package/package.json +84 -3
  69. package/production.md +273 -0
  70. package/public/css/bluebird.min.css +2 -0
  71. package/public/images/favicon.ico +0 -0
  72. package/public/js/bluebird-client.js +1663 -0
  73. package/public/js/bluebird.min.js +1073 -0
package/core/debug.js ADDED
@@ -0,0 +1,250 @@
1
+ import Router from "./router.js";
2
+
3
+ /**
4
+ * Advanced Debug module for Blue Bird.
5
+ * Provides metrics history, route statistics and live monitoring.
6
+ */
7
+ class Debug {
8
+
9
+ constructor() {
10
+ this.router = new Router("/debug");
11
+ this.limit = 50;
12
+ this.initStore();
13
+ this.registerRoutes();
14
+ }
15
+
16
+ initStore() {
17
+ if (!global.__bluebird_debug_store__) {
18
+ global.__bluebird_debug_store__ = {
19
+ requests: [],
20
+ routes: {},
21
+ errors4xx: 0,
22
+ errors5xx: 0
23
+ };
24
+ }
25
+ }
26
+
27
+ static shouldTrack(req) {
28
+ const url = req.originalUrl || "";
29
+
30
+ if (url.startsWith("/debug")) return false;
31
+
32
+ if (/\.(json|css|js|map|png|jpg|jpeg|gif|svg|ico|webp)$/i.test(url)) {
33
+ return false;
34
+ }
35
+
36
+ if (req.method === "OPTIONS") return false;
37
+
38
+ return true;
39
+ }
40
+
41
+ static middlewareMetrics(app) {
42
+ app.use((req, res, next) => {
43
+
44
+ if (!Debug.shouldTrack(req)) return next();
45
+
46
+ const start = process.hrtime();
47
+
48
+ res.on("finish", () => {
49
+
50
+ const diff = process.hrtime(start);
51
+ const responseTime = diff[0] * 1e3 + diff[1] / 1e6;
52
+
53
+ const memory = process.memoryUsage();
54
+ const ramUsedMB = memory.rss / 1024 / 1024;
55
+
56
+ const cpuUsage = process.cpuUsage();
57
+ const cpuUsedMS = (cpuUsage.user + cpuUsage.system) / 1000;
58
+
59
+ const record = {
60
+ method: req.method,
61
+ url: req.originalUrl,
62
+ status: res.statusCode,
63
+ responseTime: Number(responseTime.toFixed(2)),
64
+ ramUsedMB: Number(ramUsedMB.toFixed(2)),
65
+ cpuUsedMS: Number(cpuUsedMS.toFixed(2)),
66
+ date: new Date().toISOString()
67
+ };
68
+
69
+ const store = global.__bluebird_debug_store__;
70
+
71
+ store.requests.unshift(record);
72
+ if (store.requests.length > 50) store.requests.pop();
73
+
74
+ const routeKey = `${req.method} ${req.route?.path || req.path}`;
75
+
76
+ if (!store.routes[routeKey]) {
77
+ store.routes[routeKey] = {
78
+ count: 0,
79
+ totalTime: 0
80
+ };
81
+ }
82
+
83
+ store.routes[routeKey].count += 1;
84
+ store.routes[routeKey].totalTime += record.responseTime;
85
+
86
+ if (record.status >= 400 && record.status < 500) store.errors4xx++;
87
+ if (record.status >= 500) store.errors5xx++;
88
+ });
89
+
90
+ next();
91
+ });
92
+ }
93
+
94
+ registerRoutes() {
95
+
96
+ this.router.get("/", (req, res) => {
97
+
98
+ const store = global.__bluebird_debug_store__;
99
+
100
+ if (req.query.fetch === "true") {
101
+ return res.json(store);
102
+ }
103
+
104
+ if (req.query.reset === "true") {
105
+ global.__bluebird_debug_store__ = {
106
+ requests: [],
107
+ routes: {},
108
+ errors4xx: 0,
109
+ errors5xx: 0
110
+ };
111
+ return res.json({ ok: true });
112
+ }
113
+
114
+ res.send(`
115
+ <!DOCTYPE html>
116
+ <html>
117
+ <head>
118
+ <script src="https://cdn.tailwindcss.com"></script>
119
+ <title>Blue Bird Debug</title>
120
+ </head>
121
+ <body class="bg-gray-100 text-gray-800 p-10">
122
+
123
+ <div class="max-w-7xl mx-auto">
124
+
125
+ <div class="flex justify-between items-center mb-8">
126
+ <h1 class="text-3xl font-bold text-blue-600">Blue Bird Debug Panel</h1>
127
+ <button onclick="resetData()" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg shadow">
128
+ Reset
129
+ </button>
130
+ </div>
131
+
132
+ <div class="grid grid-cols-3 gap-6 mb-8">
133
+
134
+ <div class="bg-white p-6 rounded-xl shadow">
135
+ <h3 class="text-gray-500 text-sm">Total Requests</h3>
136
+ <p id="totalReq" class="text-2xl font-bold">0</p>
137
+ </div>
138
+
139
+ <div class="bg-yellow-100 p-6 rounded-xl shadow">
140
+ <h3 class="text-yellow-600 text-sm">4xx Errors</h3>
141
+ <p id="err4" class="text-2xl font-bold text-yellow-700">0</p>
142
+ </div>
143
+
144
+ <div class="bg-red-100 p-6 rounded-xl shadow">
145
+ <h3 class="text-red-600 text-sm">5xx Errors</h3>
146
+ <p id="err5" class="text-2xl font-bold text-red-700">0</p>
147
+ </div>
148
+
149
+ </div>
150
+
151
+ <div class="grid grid-cols-2 gap-10">
152
+
153
+ <div class="bg-white p-6 rounded-xl shadow">
154
+ <h2 class="text-lg font-semibold mb-4">Route Stats</h2>
155
+ <table class="table-fixed w-full text-sm">
156
+ <thead>
157
+ <tr class="border-b">
158
+ <th class="text-left w-1/2 py-2">Route</th>
159
+ <th class="text-left w-1/4">Hits</th>
160
+ <th class="text-left w-1/4">Avg Time</th>
161
+ </tr>
162
+ </thead>
163
+ <tbody id="routesBody"></tbody>
164
+ </table>
165
+ </div>
166
+
167
+ <div class="bg-white p-6 rounded-xl shadow">
168
+ <h2 class="text-lg font-semibold mb-4">Last Requests</h2>
169
+ <table class="table-fixed w-full text-sm">
170
+ <thead>
171
+ <tr class="border-b">
172
+ <th class="text-left w-1/2 py-2">URL</th>
173
+ <th class="text-left w-1/6">Method</th>
174
+ <th class="text-left w-1/6">Status</th>
175
+ <th class="text-left w-1/6">Time</th>
176
+ </tr>
177
+ </thead>
178
+ <tbody id="historyBody"></tbody>
179
+ </table>
180
+ </div>
181
+
182
+ </div>
183
+
184
+ </div>
185
+
186
+ <script>
187
+ async function loadData() {
188
+ const res = await fetch('/debug?fetch=true');
189
+ const data = await res.json();
190
+
191
+ document.getElementById("totalReq").innerText = data.requests.length;
192
+ document.getElementById("err4").innerText = data.errors4xx;
193
+ document.getElementById("err5").innerText = data.errors5xx;
194
+
195
+ const routesBody = document.getElementById("routesBody");
196
+ const historyBody = document.getElementById("historyBody");
197
+
198
+ routesBody.innerHTML = "";
199
+ historyBody.innerHTML = "";
200
+
201
+ Object.entries(data.routes).forEach(([key, value]) => {
202
+ const avg = (value.totalTime / value.count).toFixed(2);
203
+ let color = "";
204
+ if (avg > 500) color = "text-red-600 font-semibold";
205
+ else if (avg > 200) color = "text-yellow-600";
206
+
207
+ routesBody.innerHTML += \`
208
+ <tr class="border-b">
209
+ <td class="py-1 truncate">\${key}</td>
210
+ <td>\${value.count}</td>
211
+ <td class="\${color}">\${avg} ms</td>
212
+ </tr>\`;
213
+ });
214
+
215
+ data.requests.forEach(r => {
216
+ historyBody.innerHTML += \`
217
+ <tr class="border-b text-xs">
218
+ <td class="truncate">\${r.url}</td>
219
+ <td>\${r.method}</td>
220
+ <td>\${r.status}</td>
221
+ <td>\${r.responseTime} ms</td>
222
+ </tr>\`;
223
+ });
224
+ }
225
+
226
+ async function resetData() {
227
+ await fetch('/debug?reset=true');
228
+ loadData();
229
+ }
230
+
231
+ loadData();
232
+ setInterval(loadData, 3000);
233
+ </script>
234
+
235
+ </body>
236
+ </html>
237
+ `);
238
+ });
239
+ }
240
+
241
+ getRouter() {
242
+ return {
243
+ path: this.router.getPath(),
244
+ router: this.router.getRouter()
245
+ };
246
+ }
247
+ }
248
+
249
+ export { Debug };
250
+ export default Debug;
package/core/hash.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { Hash, HashMakeOptions } from "./index.js";
2
+ export default Hash;
3
+ export { Hash, HashMakeOptions };
package/core/hash.js ADDED
@@ -0,0 +1,194 @@
1
+ import crypto from "node:crypto";
2
+
3
+ let bcryptModule = null;
4
+ try {
5
+ bcryptModule = (await import("bcrypt")).default || (await import("bcrypt"));
6
+ } catch {}
7
+
8
+ /**
9
+ * High-performance Password Hashing class.
10
+ * Uses native node:crypto scrypt by default (zero npm dependencies, NIST recommended),
11
+ * with seamless support for bcrypt when installed or verifying bcrypt hashes.
12
+ */
13
+ class Hash {
14
+ /**
15
+ * Hashes a plain text password using scrypt (default) or bcrypt.
16
+ * @param {string} password - The plain text password.
17
+ * @param {Object} [options={}] - Hashing options.
18
+ * @param {string} [options.driver="scrypt"] - Hashing driver ('scrypt' or 'bcrypt').
19
+ * @param {number} [options.rounds=10] - Salt rounds for bcrypt (if driver is 'bcrypt').
20
+ * @param {number} [options.N=16384] - CPU/memory cost parameter for scrypt.
21
+ * @param {number} [options.r=8] - Block size for scrypt.
22
+ * @param {number} [options.p=1] - Parallelization parameter for scrypt.
23
+ * @returns {Promise<string>} Formatted password hash string.
24
+ * @example
25
+ * const hash = await Hash.make("mySecretPassword");
26
+ * const bcryptHash = await Hash.make("mySecretPassword", { driver: "bcrypt" });
27
+ */
28
+ static async make(password, options = {}) {
29
+ if (typeof password !== "string" || !password) {
30
+ throw new Error("[HASH ERROR] Password must be a non-empty string.");
31
+ }
32
+
33
+ const driver = (options.driver || "scrypt").toLowerCase();
34
+
35
+ if (driver === "bcrypt") {
36
+ if (!bcryptModule) {
37
+ throw new Error(
38
+ "[HASH ERROR] 'bcrypt' package is not installed. Run 'npm install bcrypt' or 'npx blue-bird add bcrypt', or use the default scrypt driver.",
39
+ );
40
+ }
41
+ const rounds = options.rounds || 10;
42
+ return bcryptModule.hash(password, rounds);
43
+ }
44
+ const N = options.N || 16384;
45
+ const r = options.r || 8;
46
+ const p = options.p || 1;
47
+ const keylen = 64;
48
+ const salt = crypto.randomBytes(16);
49
+
50
+ return new Promise((resolve, reject) => {
51
+ crypto.scrypt(
52
+ password,
53
+ salt,
54
+ keylen,
55
+ { N, r, p, maxmem: 32 * 1024 * 1024 },
56
+ (err, derivedKey) => {
57
+ if (err) return reject(err);
58
+ const hashString = `$scrypt$N=${N},r=${r},p=${p}$${salt.toString("hex")}$${derivedKey.toString("hex")}`;
59
+ resolve(hashString);
60
+ },
61
+ );
62
+ });
63
+ }
64
+
65
+ /**
66
+ * Alias for make().
67
+ * @param {string} password - The plain text password.
68
+ * @param {Object} [options={}] - Options.
69
+ * @returns {Promise<string>}
70
+ */
71
+ static async hash(password, options = {}) {
72
+ return this.make(password, options);
73
+ }
74
+
75
+ /**
76
+ * Verifies a plain text password against a hash string.
77
+ * Automatically detects scrypt or bcrypt hash formats.
78
+ * Uses timing-safe comparison to protect against side-channel attacks.
79
+ *
80
+ * @param {string} password - The plain text password to check.
81
+ * @param {string} hash - The stored hash string.
82
+ * @returns {Promise<boolean>} True if password matches, false otherwise.
83
+ * @example
84
+ * const isValid = await Hash.verify("mySecretPassword", storedHash);
85
+ */
86
+ static async verify(password, hash) {
87
+ if (
88
+ typeof password !== "string" ||
89
+ !password ||
90
+ typeof hash !== "string" ||
91
+ !hash
92
+ ) {
93
+ return false;
94
+ }
95
+
96
+ if (/^\$2[aby]\$\d{2}\$/.test(hash)) {
97
+ if (!bcryptModule) {
98
+ console.error(
99
+ "[HASH ERROR] A bcrypt hash was detected, but the 'bcrypt' package is not installed. Run 'npm install bcrypt' or 'npx blue-bird add bcrypt'.",
100
+ );
101
+ return false;
102
+ }
103
+ try {
104
+ return await bcryptModule.compare(password, hash);
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+
110
+ if (hash.startsWith("$scrypt$")) {
111
+ const parts = hash.split("$");
112
+ if (parts.length !== 5) return false;
113
+
114
+ const paramsStr = parts[2];
115
+ const saltHex = parts[3];
116
+ const originalHashHex = parts[4];
117
+
118
+ if (!paramsStr || !saltHex || !originalHashHex) return false;
119
+
120
+ let N = 16384,
121
+ r = 8,
122
+ p = 1;
123
+ paramsStr.split(",").forEach((param) => {
124
+ const [k, v] = param.split("=");
125
+ if (k === "N") N = parseInt(v, 10) || N;
126
+ if (k === "r") r = parseInt(v, 10) || r;
127
+ if (k === "p") p = parseInt(v, 10) || p;
128
+ });
129
+
130
+ const salt = Buffer.from(saltHex, "hex");
131
+ const originalHash = Buffer.from(originalHashHex, "hex");
132
+
133
+ return new Promise((resolve) => {
134
+ crypto.scrypt(
135
+ password,
136
+ salt,
137
+ originalHash.length,
138
+ { N, r, p, maxmem: 32 * 1024 * 1024 },
139
+ (err, derivedKey) => {
140
+ if (err) return resolve(false);
141
+ try {
142
+ const matches = crypto.timingSafeEqual(originalHash, derivedKey);
143
+ resolve(matches);
144
+ } catch {
145
+ resolve(false);
146
+ }
147
+ },
148
+ );
149
+ });
150
+ }
151
+
152
+ return false;
153
+ }
154
+
155
+ /**
156
+ * Alias for verify().
157
+ * @param {string} password - The plain text password.
158
+ * @param {string} hash - The stored hash string.
159
+ * @returns {Promise<boolean>}
160
+ */
161
+ static async check(password, hash) {
162
+ return this.verify(password, hash);
163
+ }
164
+
165
+ /**
166
+ * Checks if a given hash needs to be rehashed to match updated security parameters.
167
+ * @param {string} hash - The stored hash string.
168
+ * @param {Object} [options={}] - Target options.
169
+ * @returns {boolean} True if the hash should be regenerated.
170
+ */
171
+ static needsRehash(hash, options = {}) {
172
+ if (!hash || typeof hash !== "string") return true;
173
+ const targetDriver = (options.driver || "scrypt").toLowerCase();
174
+
175
+ if (targetDriver === "bcrypt") {
176
+ return !/^\$2[aby]\$\d{2}\$/.test(hash);
177
+ }
178
+
179
+ if (!hash.startsWith("$scrypt$")) return true;
180
+
181
+ const parts = hash.split("$");
182
+ if (parts.length !== 5) return true;
183
+
184
+ const paramsStr = parts[2];
185
+ const targetN = options.N || 16384;
186
+ const targetR = options.r || 8;
187
+ const targetP = options.p || 1;
188
+
189
+ return !paramsStr.includes(`N=${targetN},r=${targetR},p=${targetP}`);
190
+ }
191
+ }
192
+
193
+ export { Hash };
194
+ export default Hash;