@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.
- package/.env_example +54 -0
- package/AGENTS.md +403 -0
- package/LICENSE +21 -0
- package/README.md +284 -2
- package/app/routes/api.js +50 -0
- package/app/routes/web.js +53 -0
- package/app/views/about.html +161 -0
- package/app/views/dashboard.html +140 -0
- package/app/views/index.html +150 -0
- package/app/views/login.html +144 -0
- package/core/app.d.ts +18 -0
- package/core/app.js +644 -0
- package/core/auth.d.ts +13 -0
- package/core/auth.js +326 -0
- package/core/cache.d.ts +17 -0
- package/core/cache.js +475 -0
- package/core/cli/doctor.js +287 -0
- package/core/cli/ecosystem.js +162 -0
- package/core/cli/init.js +779 -0
- package/core/cli/migrate.js +541 -0
- package/core/cli/model.js +66 -0
- package/core/cli/nginx.js +199 -0
- package/core/cli/route.js +121 -0
- package/core/cli/swagger.js +45 -0
- package/core/cli/view.js +77 -0
- package/core/config.d.ts +3 -0
- package/core/config.js +111 -0
- package/core/csrf.d.ts +3 -0
- package/core/csrf.js +114 -0
- package/core/database.d.ts +15 -0
- package/core/database.js +636 -0
- package/core/debug.d.ts +3 -0
- package/core/debug.js +250 -0
- package/core/hash.d.ts +3 -0
- package/core/hash.js +194 -0
- package/core/index.d.ts +1071 -0
- package/core/logger.d.ts +3 -0
- package/core/logger.js +124 -0
- package/core/middleware.d.ts +3 -0
- package/core/middleware.js +28 -0
- package/core/model.d.ts +19 -0
- package/core/model.js +600 -0
- package/core/queue.d.ts +13 -0
- package/core/queue.js +172 -0
- package/core/ratelimit.d.ts +3 -0
- package/core/ratelimit.js +145 -0
- package/core/redis.d.ts +21 -0
- package/core/redis.js +230 -0
- package/core/render.d.ts +3 -0
- package/core/render.js +676 -0
- package/core/router.d.ts +3 -0
- package/core/router.js +171 -0
- package/core/seo.d.ts +3 -0
- package/core/seo.js +106 -0
- package/core/swagger.d.ts +3 -0
- package/core/swagger.js +60 -0
- package/core/upload.d.ts +13 -0
- package/core/upload.js +102 -0
- package/core/util/colors.js +82 -0
- package/core/validate.d.ts +15 -0
- package/core/validate.js +364 -0
- package/core/vite.d.ts +3 -0
- package/core/vite.js +145 -0
- package/core/ws.d.ts +13 -0
- package/core/ws.js +245 -0
- package/index.js +18 -0
- package/jsconfig.json +15 -0
- package/package.json +84 -3
- package/production.md +273 -0
- package/public/css/bluebird.min.css +2 -0
- package/public/images/favicon.ico +0 -0
- package/public/js/bluebird-client.js +1663 -0
- package/public/js/bluebird.min.js +1073 -0
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import colors from "../util/colors.js";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Parses .env file to extract APP_URL and PORT.
|
|
9
|
+
* @returns {{ domain: string, port: number, appUrl: string }}
|
|
10
|
+
*/
|
|
11
|
+
function getEnvConfig() {
|
|
12
|
+
const env = { ...process.env };
|
|
13
|
+
const envPath = path.resolve(process.cwd(), ".env");
|
|
14
|
+
if (fs.existsSync(envPath)) {
|
|
15
|
+
const content = fs.readFileSync(envPath, "utf-8");
|
|
16
|
+
content.split(/\r?\n/).forEach((line) => {
|
|
17
|
+
line = line.trim();
|
|
18
|
+
if (line && !line.startsWith("#") && line.includes("=")) {
|
|
19
|
+
const idx = line.indexOf("=");
|
|
20
|
+
const key = line.substring(0, idx).trim();
|
|
21
|
+
const value = line.substring(idx + 1).trim().replace(/^['"]|['"]$/g, "");
|
|
22
|
+
env[key] = value;
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
let domain = "";
|
|
28
|
+
if (env.APP_URL) {
|
|
29
|
+
try {
|
|
30
|
+
const parsedUrl = new URL(env.APP_URL.includes("://") ? env.APP_URL : `http://${env.APP_URL}`);
|
|
31
|
+
domain = parsedUrl.hostname;
|
|
32
|
+
} catch {
|
|
33
|
+
domain = env.APP_URL.replace(/^https?:\/\//, "").replace(/\/.*$/, "").replace(/:\d+$/, "").trim();
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const port = parseInt(env.PORT || "3000", 10);
|
|
38
|
+
return { domain, port, appUrl: env.APP_URL || "" };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Generates Host Nginx reverse proxy configuration snippet with upstream keepalive,
|
|
43
|
+
* direct public/ static asset delivery via try_files, and 5M body limit.
|
|
44
|
+
*/
|
|
45
|
+
function generateNginxConfig() {
|
|
46
|
+
const rawArgs = process.argv.slice(2);
|
|
47
|
+
const filteredArgs = rawArgs.filter(
|
|
48
|
+
(a) => a !== "nginx:conf" && a !== "nginx:host" && a !== "nginx" && !a.endsWith("nginx.js") && !a.endsWith("init.js")
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
const envConfig = getEnvConfig();
|
|
52
|
+
|
|
53
|
+
let domainArg = null;
|
|
54
|
+
let portArg = null;
|
|
55
|
+
let rootPathArg = null;
|
|
56
|
+
|
|
57
|
+
for (let i = 0; i < filteredArgs.length; i++) {
|
|
58
|
+
const arg = filteredArgs[i];
|
|
59
|
+
if (arg === "--root" && filteredArgs[i + 1]) {
|
|
60
|
+
rootPathArg = filteredArgs[++i];
|
|
61
|
+
} else if (arg.startsWith("--root=")) {
|
|
62
|
+
rootPathArg = arg.split("=")[1];
|
|
63
|
+
} else if (!isNaN(Number(arg))) {
|
|
64
|
+
portArg = arg;
|
|
65
|
+
} else if (arg.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(arg)) {
|
|
66
|
+
rootPathArg = arg;
|
|
67
|
+
} else if (!arg.startsWith("-") && !domainArg) {
|
|
68
|
+
domainArg = arg;
|
|
69
|
+
} else if (!arg.startsWith("-") && !rootPathArg) {
|
|
70
|
+
rootPathArg = arg;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
let domain = domainArg || envConfig.domain;
|
|
75
|
+
let port = portArg ? parseInt(portArg, 10) : envConfig.port;
|
|
76
|
+
const projectRoot = (rootPathArg || process.cwd()).replace(/\\/g, "/").replace(/\/$/, "");
|
|
77
|
+
const publicRoot = `${projectRoot}/public`;
|
|
78
|
+
|
|
79
|
+
if (!domain) {
|
|
80
|
+
domain = "example.com";
|
|
81
|
+
console.log(colors.yellow("[INFO] No domain provided and APP_URL is not configured in .env. Defaulting to 'example.com'."));
|
|
82
|
+
} else if (!domainArg && envConfig.domain) {
|
|
83
|
+
console.log(colors.cyan(`[INFO] Using domain '${domain}', port ${port}, and root '${projectRoot}'.`));
|
|
84
|
+
console.log(colors.gray(` (Override via: npx bluebird-js nginx:conf <domain> [port] [/var/www/project])\n`));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
domain = domain.replace(/^https?:\/\//, "").replace(/\/.*$/, "").replace(/:\d+$/, "").trim();
|
|
88
|
+
const upstreamName = `bluebird_${domain.replace(/[^a-zA-Z0-9_]/g, "_")}`;
|
|
89
|
+
|
|
90
|
+
const nginxSnippet = `# =============================================================
|
|
91
|
+
# Bluebird Host Nginx Reverse Proxy Configuration
|
|
92
|
+
# File: /etc/nginx/sites-available/${domain}
|
|
93
|
+
# =============================================================
|
|
94
|
+
|
|
95
|
+
map $http_upgrade $connection_upgrade {
|
|
96
|
+
default upgrade;
|
|
97
|
+
'' "";
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
upstream ${upstreamName} {
|
|
101
|
+
server 127.0.0.1:${port};
|
|
102
|
+
keepalive 64;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
server {
|
|
106
|
+
listen 80;
|
|
107
|
+
listen [::]:80;
|
|
108
|
+
server_name ${domain};
|
|
109
|
+
|
|
110
|
+
# Public static directory served directly by Nginx
|
|
111
|
+
root ${publicRoot};
|
|
112
|
+
|
|
113
|
+
# Maximum request body size for file uploads (5MB)
|
|
114
|
+
client_max_body_size 5M;
|
|
115
|
+
|
|
116
|
+
# Gzip compression for text/assets
|
|
117
|
+
gzip on;
|
|
118
|
+
gzip_vary on;
|
|
119
|
+
gzip_min_length 1024;
|
|
120
|
+
gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;
|
|
121
|
+
|
|
122
|
+
# Security: Block hidden files (.env, .git, etc.)
|
|
123
|
+
location ~* /\\.(env|git|svn|htaccess) {
|
|
124
|
+
deny all;
|
|
125
|
+
return 404;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
# Vite compiled production bundles (immutable long-term cache)
|
|
129
|
+
location /dist/ {
|
|
130
|
+
try_files $uri =404;
|
|
131
|
+
expires 365d;
|
|
132
|
+
add_header Cache-Control "public, max-age=31536000, immutable";
|
|
133
|
+
access_log off;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
# Static assets in public/ (CSS, JS, images, fonts, media)
|
|
137
|
+
location ~* \\.(?:css|js|mjs|jpg|jpeg|gif|png|ico|svg|webp|avif|woff|woff2|ttf|eot|mp4|webm|mp3)$ {
|
|
138
|
+
try_files $uri =404;
|
|
139
|
+
expires 30d;
|
|
140
|
+
add_header Cache-Control "public, max-age=2592000, immutable";
|
|
141
|
+
access_log off;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
# Serve static files from public/ if they exist, otherwise proxy to Bluebird
|
|
145
|
+
location / {
|
|
146
|
+
try_files $uri @bluebird;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
# Reverse proxy to Bluebird Node.js upstream with persistent keepalive connections
|
|
150
|
+
location @bluebird {
|
|
151
|
+
proxy_pass http://${upstreamName};
|
|
152
|
+
proxy_http_version 1.1;
|
|
153
|
+
|
|
154
|
+
# Persistent keepalive & WebSocket upgrade support
|
|
155
|
+
proxy_set_header Upgrade $http_upgrade;
|
|
156
|
+
proxy_set_header Connection $connection_upgrade;
|
|
157
|
+
|
|
158
|
+
# Standard proxy headers
|
|
159
|
+
proxy_set_header Host $host;
|
|
160
|
+
proxy_set_header X-Real-IP $remote_addr;
|
|
161
|
+
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
162
|
+
proxy_set_header X-Forwarded-Proto $scheme;
|
|
163
|
+
proxy_set_header X-Forwarded-Host $host;
|
|
164
|
+
proxy_set_header X-Forwarded-Port $server_port;
|
|
165
|
+
|
|
166
|
+
# Proxy timeouts
|
|
167
|
+
proxy_connect_timeout 60s;
|
|
168
|
+
proxy_send_timeout 60s;
|
|
169
|
+
proxy_read_timeout 60s;
|
|
170
|
+
}
|
|
171
|
+
}`;
|
|
172
|
+
|
|
173
|
+
console.log(colors.bold.cyan("============================================================="));
|
|
174
|
+
console.log(colors.bold.cyan(` Host Nginx Configuration & Let's Encrypt Setup for: ${domain}`));
|
|
175
|
+
console.log(colors.bold.cyan("============================================================="));
|
|
176
|
+
console.log("");
|
|
177
|
+
console.log(colors.yellow("1. Create the site configuration file on your VPS:"));
|
|
178
|
+
console.log(colors.green(` sudo nano /etc/nginx/sites-available/${domain}`));
|
|
179
|
+
console.log("");
|
|
180
|
+
console.log(colors.yellow("2. Paste the following configuration block:"));
|
|
181
|
+
console.log("");
|
|
182
|
+
console.log(colors.white(nginxSnippet));
|
|
183
|
+
console.log("");
|
|
184
|
+
console.log(colors.yellow("3. Enable the site configuration:"));
|
|
185
|
+
console.log(colors.green(` sudo ln -s /etc/nginx/sites-available/${domain} /etc/nginx/sites-enabled/`));
|
|
186
|
+
console.log("");
|
|
187
|
+
console.log(colors.yellow("4. Test Nginx syntax:"));
|
|
188
|
+
console.log(colors.green(" sudo nginx -t"));
|
|
189
|
+
console.log("");
|
|
190
|
+
console.log(colors.yellow("5. Reload Nginx to apply changes:"));
|
|
191
|
+
console.log(colors.green(" sudo systemctl reload nginx"));
|
|
192
|
+
console.log("");
|
|
193
|
+
console.log(colors.yellow("6. Provision free SSL certificate with Certbot (Let's Encrypt):"));
|
|
194
|
+
console.log(colors.green(` sudo certbot --nginx -d ${domain}`));
|
|
195
|
+
console.log("");
|
|
196
|
+
console.log(colors.bold.cyan("============================================================="));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
generateNginxConfig();
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import colors from "../util/colors.js";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* CLI tool for scaffolding RESTful routes.
|
|
9
|
+
*/
|
|
10
|
+
class RouteCLI {
|
|
11
|
+
/**
|
|
12
|
+
* Creates a new RESTful route file with Validation, Cache, and optional Auth.
|
|
13
|
+
*/
|
|
14
|
+
create() {
|
|
15
|
+
const rawArgs = process.argv.slice(2);
|
|
16
|
+
const args = rawArgs.filter(
|
|
17
|
+
(a) => a !== "route" && a !== "make:route" && !a.endsWith("route.js")
|
|
18
|
+
);
|
|
19
|
+
|
|
20
|
+
let routeName = args.find((a) => !a.startsWith("-"));
|
|
21
|
+
const withAuth = args.some((a) => a === "--auth" || a === "-a");
|
|
22
|
+
|
|
23
|
+
if (!routeName) {
|
|
24
|
+
console.log(colors.red("[ERROR] Missing route name."));
|
|
25
|
+
console.log("");
|
|
26
|
+
console.log("Usage:");
|
|
27
|
+
console.log(" npx bluebird-js make:route <name> [--auth]");
|
|
28
|
+
console.log("");
|
|
29
|
+
console.log("Examples:");
|
|
30
|
+
console.log(" npx bluebird-js make:route products");
|
|
31
|
+
console.log(" npx bluebird-js make:route articles --auth");
|
|
32
|
+
process.exit(1);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
routeName = routeName.toLowerCase().replace(/[^a-z0-9_-]/g, "");
|
|
36
|
+
const singularName = routeName.endsWith("s") ? routeName.slice(0, -1) : routeName;
|
|
37
|
+
const pascalName = routeName.charAt(0).toUpperCase() + routeName.slice(1);
|
|
38
|
+
const routerVarName = `router${pascalName}`;
|
|
39
|
+
const basePath = `/${routeName}`;
|
|
40
|
+
|
|
41
|
+
const routesFolder = path.resolve(process.cwd(), "app/routes");
|
|
42
|
+
if (!fs.existsSync(routesFolder)) {
|
|
43
|
+
fs.mkdirSync(routesFolder, { recursive: true });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const filename = `${routeName}.js`;
|
|
47
|
+
const filePath = path.join(routesFolder, filename);
|
|
48
|
+
if (fs.existsSync(filePath)) {
|
|
49
|
+
console.log(colors.yellow(`[WARN] Route file '${filename}' already exists at app/routes/${filename}.`));
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const authImport = withAuth
|
|
54
|
+
? 'import Auth from "@seip/bluebird-js/core/auth.js";\n'
|
|
55
|
+
: "";
|
|
56
|
+
|
|
57
|
+
const authProtect = withAuth ? "Auth.protect(), " : "";
|
|
58
|
+
|
|
59
|
+
const content = `import Router from "@seip/bluebird-js/core/router.js";
|
|
60
|
+
import Validator from "@seip/bluebird-js/core/validate.js";
|
|
61
|
+
import Cache from "@seip/bluebird-js/core/cache.js";
|
|
62
|
+
${authImport}const ${routerVarName} = new Router("${basePath}");
|
|
63
|
+
|
|
64
|
+
const ${singularName}Schema = {
|
|
65
|
+
name: { required: true, min: 2, max: 255 },
|
|
66
|
+
description: { required: false },
|
|
67
|
+
price: { required: false }
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const validate${pascalName} = new Validator(${singularName}Schema, "en");
|
|
71
|
+
|
|
72
|
+
${routerVarName}.get("/", Cache.middleware(60), (req, res) => {
|
|
73
|
+
res.ok({ ${routeName}: [] }, "${pascalName} list retrieved successfully");
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
${routerVarName}.get("/:id", Cache.middleware(60), (req, res) => {
|
|
77
|
+
const { id } = req.params;
|
|
78
|
+
res.ok({ ${singularName}: { id } }, "${pascalName} retrieved successfully");
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
${routerVarName}.post("/", ${authProtect}validate${pascalName}.middleware(), async (req, res) => {
|
|
82
|
+
const data = req.body;
|
|
83
|
+
|
|
84
|
+
await Cache.delete("${basePath}");
|
|
85
|
+
|
|
86
|
+
res.created({ ${singularName}: data }, "${pascalName} created successfully");
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
${routerVarName}.put("/:id", ${authProtect}validate${pascalName}.middleware(), async (req, res) => {
|
|
90
|
+
const { id } = req.params;
|
|
91
|
+
const data = req.body;
|
|
92
|
+
|
|
93
|
+
await Cache.delete("${basePath}");
|
|
94
|
+
await Cache.delete(\`${basePath}/\${id}\`);
|
|
95
|
+
|
|
96
|
+
res.ok({ ${singularName}: { id, ...data } }, "${pascalName} updated successfully");
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
${routerVarName}.delete("/:id", ${authProtect}async (req, res) => {
|
|
100
|
+
const { id } = req.params;
|
|
101
|
+
|
|
102
|
+
await Cache.delete("${basePath}");
|
|
103
|
+
await Cache.delete(\`${basePath}/\${id}\`);
|
|
104
|
+
|
|
105
|
+
res.ok({ id }, "${pascalName} deleted successfully");
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
export default ${routerVarName};
|
|
109
|
+
`;
|
|
110
|
+
|
|
111
|
+
fs.writeFileSync(filePath, content, "utf-8");
|
|
112
|
+
console.log(colors.green(`[OK] Route '${routeName}' created at app/routes/${filename}`));
|
|
113
|
+
console.log("");
|
|
114
|
+
console.log(colors.cyan("To register this route, import it in index.js:"));
|
|
115
|
+
console.log(colors.gray(` import ${routerVarName} from "./app/routes/${filename}";`));
|
|
116
|
+
console.log(colors.gray(` Add ${routerVarName} to the routes array in new App({ routes: [...] })`));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const routeCLI = new RouteCLI();
|
|
121
|
+
routeCLI.create();
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { execSync } from "node:child_process";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
|
|
6
|
+
const require = createRequire(import.meta.url);
|
|
7
|
+
|
|
8
|
+
class SwaggerCli {
|
|
9
|
+
install() {
|
|
10
|
+
const dependencies = this.checkDependencies();
|
|
11
|
+
if (dependencies.missingDependencies.length > 0) {
|
|
12
|
+
console.log("Installing dependencies...");
|
|
13
|
+
console.log(`Installing swagger-jsdoc...`);
|
|
14
|
+
execSync(`npm install swagger-jsdoc@6.2.8`, { stdio: "inherit" });
|
|
15
|
+
console.log(`Installing swagger-ui-express...`);
|
|
16
|
+
execSync(`npm install swagger-ui-express@5.0.1`, { stdio: "inherit" });
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
checkDependencies() {
|
|
20
|
+
const dependencies = [
|
|
21
|
+
"swagger-jsdoc",
|
|
22
|
+
"swagger-ui-express"
|
|
23
|
+
];
|
|
24
|
+
const missingDependencies = [];
|
|
25
|
+
dependencies.forEach(dependency => {
|
|
26
|
+
if (!this.checkDependency(dependency)) {
|
|
27
|
+
missingDependencies.push(dependency);
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
return {
|
|
31
|
+
missingDependencies
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
checkDependency(dependency) {
|
|
35
|
+
try {
|
|
36
|
+
require.resolve(dependency);
|
|
37
|
+
return true;
|
|
38
|
+
} catch (error) {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const swaggerExecutor = new SwaggerCli();
|
|
45
|
+
swaggerExecutor.install();
|
package/core/cli/view.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import colors from "../util/colors.js";
|
|
6
|
+
|
|
7
|
+
const VIEWS_DIR = path.resolve(process.cwd(), "app/views");
|
|
8
|
+
|
|
9
|
+
const rawArgs = process.argv.slice(2);
|
|
10
|
+
const args = rawArgs.filter(
|
|
11
|
+
(a) => a !== "view" && a !== "make:view" && !a.endsWith("view.js")
|
|
12
|
+
);
|
|
13
|
+
const viewName = args.find((a) => !a.startsWith("-"));
|
|
14
|
+
const useEjs = rawArgs.some((a) => a === "--ejs");
|
|
15
|
+
|
|
16
|
+
if (!viewName) {
|
|
17
|
+
console.log(colors.red("[ERROR] Missing view name."));
|
|
18
|
+
console.log("Usage: npx bluebird-js make:view <name> [--ejs]");
|
|
19
|
+
process.exit(1);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const cleanName = viewName.toLowerCase().replace(/[^a-z0-9_-]/g, "_");
|
|
23
|
+
const ext = useEjs ? ".ejs" : ".html";
|
|
24
|
+
const fileName = `${cleanName}${ext}`;
|
|
25
|
+
const filePath = path.join(VIEWS_DIR, fileName);
|
|
26
|
+
|
|
27
|
+
if (!fs.existsSync(VIEWS_DIR)) {
|
|
28
|
+
fs.mkdirSync(VIEWS_DIR, { recursive: true });
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (fs.existsSync(filePath)) {
|
|
32
|
+
console.log(colors.yellow(`[WARN] View '${fileName}' already exists at app/views/${fileName}.`));
|
|
33
|
+
process.exit(0);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const titleCase = cleanName.charAt(0).toUpperCase() + cleanName.slice(1);
|
|
37
|
+
|
|
38
|
+
const htmlTemplate = `<!DOCTYPE html>
|
|
39
|
+
<html lang="en">
|
|
40
|
+
<head>
|
|
41
|
+
<meta charset="UTF-8" />
|
|
42
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
43
|
+
<title>{{title}}</title>
|
|
44
|
+
<link rel="stylesheet" href="/css/style.css" />
|
|
45
|
+
</head>
|
|
46
|
+
<body>
|
|
47
|
+
<h1>${titleCase}</h1>
|
|
48
|
+
<p>{{description}}</p>
|
|
49
|
+
<script src="/js/main.js" defer></script>
|
|
50
|
+
</body>
|
|
51
|
+
</html>
|
|
52
|
+
`;
|
|
53
|
+
|
|
54
|
+
const ejsTemplate = `<!DOCTYPE html>
|
|
55
|
+
<html lang="en">
|
|
56
|
+
<head>
|
|
57
|
+
<meta charset="UTF-8" />
|
|
58
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
59
|
+
<title><%= title %></title>
|
|
60
|
+
<link rel="stylesheet" href="/css/style.css" />
|
|
61
|
+
</head>
|
|
62
|
+
<body>
|
|
63
|
+
<h1>${titleCase}</h1>
|
|
64
|
+
<p><%= description %></p>
|
|
65
|
+
<script src="/js/main.js" defer></script>
|
|
66
|
+
</body>
|
|
67
|
+
</html>
|
|
68
|
+
`;
|
|
69
|
+
|
|
70
|
+
const content = useEjs ? ejsTemplate : htmlTemplate;
|
|
71
|
+
fs.writeFileSync(filePath, content, "utf-8");
|
|
72
|
+
|
|
73
|
+
console.log(colors.green(`[OK] View '${fileName}' created at app/views/${fileName}`));
|
|
74
|
+
console.log("");
|
|
75
|
+
console.log(colors.cyan("To render this view in a route:"));
|
|
76
|
+
console.log(colors.gray(` import Render from "@seip/bluebird-js/core/render.js";`));
|
|
77
|
+
console.log(colors.gray(` routerWeb.get("/${cleanName}", Render.view("${cleanName}"));`));
|
package/core/config.d.ts
ADDED
package/core/config.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
|
|
4
|
+
let _cachedProps = null;
|
|
5
|
+
let _customUserDataDir = null;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Configuration class to manage application-wide settings, environment variables,
|
|
9
|
+
* and Electron/desktop writable data paths.
|
|
10
|
+
*/
|
|
11
|
+
class Config {
|
|
12
|
+
/**
|
|
13
|
+
* Returns the base directory of the application (process.cwd()).
|
|
14
|
+
* @returns {string}
|
|
15
|
+
*/
|
|
16
|
+
static dirname() {
|
|
17
|
+
return process.cwd();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Checks whether the application is running in Electron or Desktop mode.
|
|
22
|
+
* @returns {boolean}
|
|
23
|
+
*/
|
|
24
|
+
static isDesktop() {
|
|
25
|
+
return Boolean(
|
|
26
|
+
process.versions?.electron ||
|
|
27
|
+
process.env.DESKTOP_MODE === "true" ||
|
|
28
|
+
process.env.ELECTRON_RUN_AS_NODE ||
|
|
29
|
+
_customUserDataDir
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Sets a custom writable directory for databases, logs, and file cache (ideal for Electron app.getPath("userData")).
|
|
35
|
+
* @param {string} dirPath
|
|
36
|
+
*/
|
|
37
|
+
static setUserDataDir(dirPath) {
|
|
38
|
+
_customUserDataDir = dirPath ? path.resolve(dirPath) : null;
|
|
39
|
+
_cachedProps = null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Returns a writable base directory for persistent runtime files (SQLite DB, file cache, logs).
|
|
44
|
+
* In standard server environments, returns process.cwd().
|
|
45
|
+
* In Electron / Desktop mode or when USER_DATA_PATH is set, returns a writable user data directory
|
|
46
|
+
* to avoid EROFS errors inside read-only .asar archives.
|
|
47
|
+
* @returns {string}
|
|
48
|
+
*/
|
|
49
|
+
static userDataDir() {
|
|
50
|
+
if (_customUserDataDir) return _customUserDataDir;
|
|
51
|
+
if (process.env.USER_DATA_PATH) return path.resolve(process.env.USER_DATA_PATH);
|
|
52
|
+
|
|
53
|
+
const cwd = process.cwd();
|
|
54
|
+
if (cwd.includes(".asar") || process.versions?.electron || process.env.DESKTOP_MODE === "true") {
|
|
55
|
+
const appName = (process.env.TITLE || "bluebird-app").toLowerCase().replace(/[^a-z0-9_-]/g, "-");
|
|
56
|
+
const baseAppData =
|
|
57
|
+
process.env.APPDATA ||
|
|
58
|
+
(process.platform === "darwin"
|
|
59
|
+
? path.join(os.homedir(), "Library", "Application Support")
|
|
60
|
+
: path.join(os.homedir(), ".local", "share"));
|
|
61
|
+
return path.join(baseAppData, appName);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return cwd;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Retrieves application properties from environment variables.
|
|
69
|
+
* Results are cached after the first call.
|
|
70
|
+
* @returns {{debug: boolean, desktop: boolean, userDataDir: string, title: string, description: string, version: string, host: string, appUrl: string, port: number, jwtSecret: string, langMeta: string, static: {path: string, options: Object}}} Configuration object.
|
|
71
|
+
*/
|
|
72
|
+
static props() {
|
|
73
|
+
if (_cachedProps) return _cachedProps;
|
|
74
|
+
|
|
75
|
+
const portRaw = parseInt(process.env.PORT, 10);
|
|
76
|
+
|
|
77
|
+
_cachedProps = {
|
|
78
|
+
debug: process.env.DEBUG === "true",
|
|
79
|
+
desktop: this.isDesktop(),
|
|
80
|
+
userDataDir: this.userDataDir(),
|
|
81
|
+
descriptionMeta: process.env.DESCRIPTION_META || "",
|
|
82
|
+
keywordsMeta: process.env.KEYWORDS_META || "",
|
|
83
|
+
titleMeta: process.env.TITLE_META || "",
|
|
84
|
+
authorMeta: process.env.AUTHOR_META || "",
|
|
85
|
+
description: process.env.DESCRIPTION || "",
|
|
86
|
+
title: process.env.TITLE || "",
|
|
87
|
+
version: process.env.VERSION || "1.0.0",
|
|
88
|
+
langMeta: process.env.LANGMETA || "en",
|
|
89
|
+
host: process.env.HOST || "http://localhost",
|
|
90
|
+
appUrl: process.env.APP_URL || process.env.HOST || "http://localhost",
|
|
91
|
+
port: Number.isNaN(portRaw) ? 3000 : portRaw,
|
|
92
|
+
jwtSecret: process.env.JWT_SECRET,
|
|
93
|
+
static: {
|
|
94
|
+
path: process.env.STATIC_PATH || "public",
|
|
95
|
+
options: {},
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
return _cachedProps;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Clears the cached configuration properties to re-read environment variables.
|
|
103
|
+
* @returns {void}
|
|
104
|
+
*/
|
|
105
|
+
static reload() {
|
|
106
|
+
_cachedProps = null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export { Config };
|
|
111
|
+
export default Config;
|
package/core/csrf.d.ts
ADDED
package/core/csrf.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import Config from "./config.js";
|
|
3
|
+
|
|
4
|
+
const propsConfig = Config.props();
|
|
5
|
+
const defaultSecret = propsConfig.jwtSecret || "bluebird-csrf-secret-key-32-chars!";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Native CSRF protection module using HMAC-SHA256 signed tokens without external dependencies.
|
|
9
|
+
*/
|
|
10
|
+
class Csrf {
|
|
11
|
+
/**
|
|
12
|
+
* Generates a signed CSRF token string.
|
|
13
|
+
* @param {string} [secret] - Secret key used for signing.
|
|
14
|
+
* @returns {string} Hex encoded token in format salt.timestamp.signature.
|
|
15
|
+
*/
|
|
16
|
+
static generateToken(secret = process.env.JWT_SECRET || defaultSecret) {
|
|
17
|
+
const salt = randomBytes(16).toString("hex");
|
|
18
|
+
const timestamp = Date.now().toString(36);
|
|
19
|
+
const signature = createHmac("sha256", secret)
|
|
20
|
+
.update(`${salt}.${timestamp}`)
|
|
21
|
+
.digest("hex");
|
|
22
|
+
|
|
23
|
+
return `${salt}.${timestamp}.${signature}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Verifies the authenticity and validity of a CSRF token.
|
|
28
|
+
* @param {string} token - The CSRF token to verify.
|
|
29
|
+
* @param {string} [secret] - Secret key used for verification.
|
|
30
|
+
* @param {number} [maxAgeMs=86400000] - Maximum token age in milliseconds (default 24h).
|
|
31
|
+
* @returns {boolean} True if the token is valid.
|
|
32
|
+
*/
|
|
33
|
+
static verifyToken(token, secret = process.env.JWT_SECRET || defaultSecret, maxAgeMs = 86400000) {
|
|
34
|
+
if (!token || typeof token !== "string") return false;
|
|
35
|
+
|
|
36
|
+
const parts = token.split(".");
|
|
37
|
+
if (parts.length !== 3) return false;
|
|
38
|
+
|
|
39
|
+
const [salt, timestampStr, signature] = parts;
|
|
40
|
+
const timestamp = parseInt(timestampStr, 36);
|
|
41
|
+
|
|
42
|
+
if (isNaN(timestamp) || Date.now() - timestamp > maxAgeMs) {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const expected = createHmac("sha256", secret)
|
|
47
|
+
.update(`${salt}.${timestampStr}`)
|
|
48
|
+
.digest("hex");
|
|
49
|
+
|
|
50
|
+
const sigBuf = Buffer.from(signature);
|
|
51
|
+
const expBuf = Buffer.from(expected);
|
|
52
|
+
|
|
53
|
+
if (sigBuf.length !== expBuf.length) return false;
|
|
54
|
+
return timingSafeEqual(sigBuf, expBuf);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Express middleware that ensures valid CSRF tokens on mutating HTTP requests.
|
|
59
|
+
* @param {Object} [options={}] - Configuration options.
|
|
60
|
+
* @param {string} [options.cookieName="_csrf"] - Name of the cookie storing the CSRF token.
|
|
61
|
+
* @param {string} [options.headerName="x-csrf-token"] - Name of the request header.
|
|
62
|
+
* @param {string} [options.bodyKey="_csrf"] - Name of the body field.
|
|
63
|
+
* @param {number} [options.maxAgeMs=86400000] - Token expiration in milliseconds.
|
|
64
|
+
* @returns {Function} Express middleware.
|
|
65
|
+
*/
|
|
66
|
+
static middleware(options = {}) {
|
|
67
|
+
const cookieName = options.cookieName || "_csrf";
|
|
68
|
+
const headerName = (options.headerName || "x-csrf-token").toLowerCase();
|
|
69
|
+
const bodyKey = options.bodyKey || "_csrf";
|
|
70
|
+
const maxAgeMs = options.maxAgeMs || 86400000;
|
|
71
|
+
const secret = options.secret || process.env.JWT_SECRET || defaultSecret;
|
|
72
|
+
|
|
73
|
+
return (req, res, next) => {
|
|
74
|
+
let token = req.cookies?.[cookieName];
|
|
75
|
+
|
|
76
|
+
if (!token || !Csrf.verifyToken(token, secret, maxAgeMs)) {
|
|
77
|
+
token = Csrf.generateToken(secret);
|
|
78
|
+
if (typeof res.cookie === "function") {
|
|
79
|
+
res.cookie(cookieName, token, {
|
|
80
|
+
httpOnly: false,
|
|
81
|
+
sameSite: "lax",
|
|
82
|
+
secure: Boolean(!propsConfig.debug),
|
|
83
|
+
path: "/",
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
res.locals.csrfToken = token;
|
|
89
|
+
req.csrfToken = () => token;
|
|
90
|
+
|
|
91
|
+
const safeMethods = ["GET", "HEAD", "OPTIONS"];
|
|
92
|
+
if (safeMethods.includes(req.method)) {
|
|
93
|
+
return next();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const receivedToken =
|
|
97
|
+
req.headers[headerName] ||
|
|
98
|
+
req.body?.[bodyKey] ||
|
|
99
|
+
req.query?.[bodyKey];
|
|
100
|
+
|
|
101
|
+
if (!receivedToken || !Csrf.verifyToken(receivedToken, secret, maxAgeMs) || receivedToken !== token) {
|
|
102
|
+
return res.status(403).json({
|
|
103
|
+
status: "error",
|
|
104
|
+
message: "Invalid or missing CSRF token.",
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
next();
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export { Csrf };
|
|
114
|
+
export default Csrf;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Database,
|
|
3
|
+
DB_TYPE,
|
|
4
|
+
DatabaseQueryOptions,
|
|
5
|
+
DatabaseTransactionClient,
|
|
6
|
+
PaginatedResult,
|
|
7
|
+
} from "./index.js";
|
|
8
|
+
export default Database;
|
|
9
|
+
export {
|
|
10
|
+
Database,
|
|
11
|
+
DB_TYPE,
|
|
12
|
+
DatabaseQueryOptions,
|
|
13
|
+
DatabaseTransactionClient,
|
|
14
|
+
PaginatedResult,
|
|
15
|
+
};
|