slicejs-web-framework 3.3.7 → 3.3.8

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/api/index.js CHANGED
@@ -1,286 +1,281 @@
1
- // api/index.js - Seguridad automática sin configuración
2
- import express from 'slicejs-web-framework/api/framework/express.js';
3
- import path from 'path';
4
- import fs from 'fs';
5
- import { fileURLToPath } from 'url';
6
- import { dirname } from 'path';
7
- import {
8
- securityMiddleware,
9
- sliceFrameworkProtection,
10
- suspiciousRequestLogger
11
- } from './middleware/securityMiddleware.js';
12
- import { createPublicEnvProvider } from './utils/publicEnvResolver.js';
13
-
14
- const __filename = fileURLToPath(import.meta.url);
15
- const __dirname = dirname(__filename);
16
- import sliceConfig from '../src/sliceConfig.json' with { type: 'json' };
17
-
18
- let server;
19
- const app = express();
20
-
21
- // Parsear argumentos de línea de comandos
22
- const args = process.argv.slice(2);
23
-
24
- const runMode = process.env.NODE_ENV === 'production' ? 'production' : 'development';
25
- const folderDeployed = runMode === 'production' ? 'dist' : 'src';
26
- const publicEnvProvider = createPublicEnvProvider({
27
- mode: runMode,
28
- envFilePath: path.join(__dirname, '..', '.env')
29
- });
30
-
31
- // Obtener puerto desde process.env.PORT con fallback a sliceConfig.json
32
- const PORT = process.env.PORT || sliceConfig.server?.port || 3001;
33
-
34
- // ==============================================
35
- // MIDDLEWARES DE SEGURIDAD (APLICAR PRIMERO)
36
- // ==============================================
37
-
38
- // 1. Logger de peticiones sospechosas (solo observación, no bloquea)
39
- app.use(suspiciousRequestLogger());
40
-
41
- // 2. Protección del framework - TOTALMENTE AUTOMÁTICA
42
- // Detecta automáticamente el dominio desde los headers
43
- // Funciona en localhost, IP, y cualquier dominio
44
- app.use(sliceFrameworkProtection());
45
-
46
- // 3. Middleware de seguridad general
47
- app.use(securityMiddleware({
48
- allowedExtensions: [
49
- '.js', '.css', '.html', '.json',
50
- '.svg', '.png', '.jpg', '.jpeg', '.gif',
51
- '.woff', '.woff2', '.ttf', '.ico'
52
- ],
53
- blockedPaths: [
54
- '/node_modules',
55
- '/package.json',
56
- '/package-lock.json',
57
- '/.env',
58
- '/.git',
59
- '/api/middleware'
60
- ],
61
- allowPublicAssets: true
62
- }));
63
-
64
- // ==============================================
65
- // MIDDLEWARES DE APLICACIÓN
66
- // ==============================================
67
-
68
- // Middleware global para archivos JavaScript con MIME types correctos
69
- app.use((req, res, next) => {
70
- if (req.path.endsWith('.js')) {
71
- // Forzar headers correctos para TODOS los archivos .js
72
- res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
73
- }
74
- next();
75
- });
76
-
77
- // Middleware para parsear JSON y formularios
78
- app.use(express.json());
79
- app.use(express.urlencoded({ extended: true }));
80
-
81
- // Configurar headers de CORS
82
- app.use((req, res, next) => {
83
- res.header('Access-Control-Allow-Origin', '*');
84
- res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
85
- res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
86
-
87
- if (req.method === 'OPTIONS') {
88
- res.sendStatus(200);
89
- } else {
90
- next();
91
- }
92
- });
93
-
94
- // ==============================================
95
- // RUNTIME MODE ENDPOINT
96
- // ==============================================
97
-
98
- app.get('/slice-env.json', (req, res) => {
99
- const payload = publicEnvProvider.getPayload();
100
- res.setHeader('Cache-Control', 'no-store');
101
- res.setHeader('Pragma', 'no-cache');
102
- res.setHeader('Expires', '0');
103
- res.json(payload);
104
- });
105
-
106
- // ==============================================
107
- // ARCHIVOS ESTÁTICOS (DESPUÉS DE SEGURIDAD)
108
- // ==============================================
109
-
110
- if (runMode === 'production') {
111
- app.get('/Slice/Slice.js', (req, res) => {
112
- const slicePath = path.join(__dirname, '..', 'node_modules', 'slicejs-web-framework', 'Slice', 'Slice.js');
113
- if (fs.existsSync(slicePath)) {
114
- res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
115
- return res.send(fs.readFileSync(slicePath, 'utf8'));
116
- }
117
- return res.status(404).send('Slice.js not found');
118
- });
119
-
120
- app.use('/Slice', (req, res) => res.status(404).send('Not found'));
121
- app.use('/Components', (req, res) => res.status(404).send('Not found'));
122
- }
123
-
124
- // Middleware personalizado para archivos de bundles con MIME types correctos
125
- // ⚠️ DEBE IR ANTES del middleware general para tener prioridad
126
- app.use('/bundles/', (req, res, next) => {
127
- // Solo procesar archivos .js
128
- if (req.path.endsWith('.js')) {
129
- const filePath = path.join(__dirname, `../${folderDeployed}`, 'bundles', req.path);
130
- console.log(`📂 Processing bundle: ${req.path} -> ${filePath}`);
131
-
132
- // Verificar que el archivo existe
133
- if (fs.existsSync(filePath)) {
134
- try {
135
- // Leer y servir el archivo con headers correctos
136
- const fileContent = fs.readFileSync(filePath, 'utf8');
137
- res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
138
- res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); // No cachear para permitir actualizaciones en tiempo real
139
- res.setHeader('Pragma', 'no-cache');
140
- res.setHeader('Expires', '0');
141
- console.log(`✅ Serving bundle: ${req.path} (${fileContent.length} bytes, ${Buffer.byteLength(fileContent, 'utf8')} bytes UTF-8)`);
142
- return res.send(fileContent);
143
- } catch (error) {
144
- console.log(`❌ Error reading bundle file: ${error.message}`);
145
- return res.status(500).send('Error reading bundle file');
146
- }
147
- } else {
148
- console.log(`❌ Bundle file not found: ${filePath}`);
149
- return res.status(404).send('Bundle file not found');
150
- }
151
- }
152
-
153
- // Para archivos no .js, continuar con el middleware estático normal
154
- next();
155
- });
156
-
157
- // Servir otros archivos de bundles (JSON, CSS, etc.) con el middleware estático normal
158
- app.use('/bundles/', express.static(path.join(__dirname, `../${folderDeployed}`, 'bundles')));
159
- console.log(`📦 Serving bundles from /${folderDeployed}/bundles`);
160
-
161
- // Servir framework Slice.js (solo development)
162
- if (runMode === 'development') {
163
- app.use('/Slice/', express.static(path.join(__dirname, '..', 'node_modules', 'slicejs-web-framework', 'Slice')));
164
- }
165
-
166
- // Servir archivos estáticos del proyecto con allowlist
167
- const publicFolders = Array.isArray(sliceConfig.publicFolders) ? sliceConfig.publicFolders : [];
168
- const normalizedPublicFolders = publicFolders
169
- .filter((entry) => typeof entry === 'string')
170
- .map((entry) => entry.trim())
171
- .filter((entry) => entry.length > 0)
172
- .map((entry) => (entry.startsWith('/') ? entry : `/${entry}`));
173
-
174
- if (runMode === 'development') {
175
- app.use(express.static(path.join(__dirname, `../${folderDeployed}`)));
176
- } else {
177
- app.use('/App', express.static(path.join(__dirname, `../${folderDeployed}`, 'App')));
178
- app.get('/manifest.json', (req, res) => {
179
- const manifestPath = path.join(__dirname, `../${folderDeployed}`, 'manifest.json');
180
- if (fs.existsSync(manifestPath)) {
181
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
182
- return res.send(fs.readFileSync(manifestPath, 'utf8'));
183
- }
184
- return res.status(404).send('manifest.json not found');
185
- });
186
- app.get('/service-worker.js', (req, res) => {
187
- const workerPath = path.join(__dirname, `../${folderDeployed}`, 'service-worker.js');
188
- if (fs.existsSync(workerPath)) {
189
- res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
190
- return res.send(fs.readFileSync(workerPath, 'utf8'));
191
- }
192
- return res.status(404).send('service-worker.js not found');
193
- });
194
- app.get('/routes.js', (req, res) => {
195
- const routesPath = path.join(__dirname, `../${folderDeployed}`, 'routes.js');
196
- if (fs.existsSync(routesPath)) {
197
- res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
198
- return res.send(fs.readFileSync(routesPath, 'utf8'));
199
- }
200
- return res.status(404).send('routes.js not found');
201
- });
202
- app.get('/sliceConfig.json', (req, res) => {
203
- const configPath = path.join(__dirname, `../${folderDeployed}`, 'sliceConfig.json');
204
- if (fs.existsSync(configPath)) {
205
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
206
- return res.send(fs.readFileSync(configPath, 'utf8'));
207
- }
208
- return res.status(404).send('sliceConfig.json not found');
209
- });
210
- for (const folder of normalizedPublicFolders) {
211
- app.use(folder, express.static(path.join(__dirname, `../${folderDeployed}`, folder)));
212
- }
213
- app.use('/bundles/', express.static(path.join(__dirname, `../${folderDeployed}`, 'bundles')));
214
- app.use('/dist/', express.static(path.join(__dirname, '..', 'dist')));
215
- }
216
-
217
- // ==============================================
218
- // RUTAS DE API
219
- // ==============================================
220
-
221
- // Ruta de ejemplo para API
222
- app.get('/api/status', (req, res) => {
223
- res.json({
224
- status: 'ok',
225
- mode: runMode,
226
- folder: folderDeployed,
227
- timestamp: new Date().toISOString(),
228
- framework: 'Slice.js',
229
- version: '2.0.0',
230
- security: {
231
- enabled: true,
232
- mode: 'automatic',
233
- description: 'Zero-config security - works with any domain'
234
- }
235
- });
236
- });
237
-
238
-
239
- // ==============================================
240
- // SPA FALLBACK
241
- // ==============================================
242
-
243
- // SPA fallback - servir index.html para rutas no encontradas
244
- app.get('*', (req, res) => {
245
- const indexPath = path.join(__dirname, `../${folderDeployed}`, "App", 'index.html');
246
- res.sendFile(indexPath, (err) => {
247
- if (err) {
248
- res.status(404).send(`
249
- <h1>404 - Page Not Found</h1>
250
- <p>The requested file could not be found in /${folderDeployed}</p>
251
- <p>Make sure you've run the appropriate build command:</p>
252
- <ul>
253
- <li>For development: Files should be in /src</li>
254
- <li>For production: Run "npm run slice:build" first</li>
255
- </ul>
256
- `);
257
- }
258
- });
259
- });
260
-
261
- // ==============================================
262
- // INICIO DEL SERVIDOR
263
- // ==============================================
264
-
265
- function startServer() {
266
- server = app.listen(PORT, () => {
267
- console.log(`🔒 Security middleware: active (zero-config, automatic)`);
268
- console.log(`🚀 Slice.js server running on port ${PORT}`);
269
- });
270
- }
271
-
272
- // Manejar cierre del proceso
273
- process.on('SIGINT', () => {
274
- console.log('\n🛑 Slice server stopped');
275
- process.exit(0);
276
- });
277
-
278
- process.on('SIGTERM', () => {
279
- console.log('\n🛑 Server terminated');
280
- process.exit(0);
281
- });
282
-
283
- // Iniciar servidor
284
- startServer();
285
-
286
- export default app;
1
+ // api/index.js - Seguridad automática sin configuración
2
+ import express from 'slicejs-web-framework/api/framework/express.js';
3
+ import path from 'path';
4
+ import fs from 'fs';
5
+ import { fileURLToPath } from 'url';
6
+ import { dirname } from 'path';
7
+ import {
8
+ securityMiddleware,
9
+ sliceFrameworkProtection,
10
+ suspiciousRequestLogger
11
+ } from './middleware/securityMiddleware.js';
12
+ import { createPublicEnvProvider } from './utils/publicEnvResolver.js';
13
+
14
+ const __filename = fileURLToPath(import.meta.url);
15
+ const __dirname = dirname(__filename);
16
+ import sliceConfig from '../src/sliceConfig.json' with { type: 'json' };
17
+
18
+ let server;
19
+ const app = express();
20
+
21
+ // Parsear argumentos de línea de comandos
22
+ const args = process.argv.slice(2);
23
+
24
+ const runMode = process.env.NODE_ENV === 'production' ? 'production' : 'development';
25
+ const folderDeployed = runMode === 'production' ? 'dist' : 'src';
26
+ const publicEnvProvider = createPublicEnvProvider({
27
+ mode: runMode,
28
+ envFilePath: path.join(__dirname, '..', '.env')
29
+ });
30
+
31
+ // Obtener puerto desde process.env.PORT con fallback a sliceConfig.json
32
+ const PORT = process.env.PORT || sliceConfig.server?.port || 3001;
33
+
34
+ // ==============================================
35
+ // MIDDLEWARES DE SEGURIDAD (APLICAR PRIMERO)
36
+ // ==============================================
37
+
38
+ // 1. Logger de peticiones sospechosas (solo observación, no bloquea)
39
+ app.use(suspiciousRequestLogger());
40
+
41
+ // 2. Protección del framework - TOTALMENTE AUTOMÁTICA
42
+ // Detecta automáticamente el dominio desde los headers
43
+ // Funciona en localhost, IP, y cualquier dominio
44
+ app.use(sliceFrameworkProtection());
45
+
46
+ // 3. Middleware de seguridad general
47
+ app.use(securityMiddleware({
48
+ allowedExtensions: [
49
+ '.js', '.css', '.html', '.json',
50
+ '.svg', '.png', '.jpg', '.jpeg', '.gif',
51
+ '.woff', '.woff2', '.ttf', '.ico'
52
+ ],
53
+ blockedPaths: [
54
+ '/node_modules',
55
+ '/package.json',
56
+ '/package-lock.json',
57
+ '/.env',
58
+ '/.git',
59
+ '/api/middleware'
60
+ ],
61
+ allowPublicAssets: true
62
+ }));
63
+
64
+ // ==============================================
65
+ // MIDDLEWARES DE APLICACIÓN
66
+ // ==============================================
67
+
68
+ // Middleware global para archivos JavaScript con MIME types correctos
69
+ app.use((req, res, next) => {
70
+ if (req.path.endsWith('.js')) {
71
+ // Forzar headers correctos para TODOS los archivos .js
72
+ res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
73
+ }
74
+ next();
75
+ });
76
+
77
+ // Middleware para parsear JSON y formularios
78
+ app.use(express.json());
79
+ app.use(express.urlencoded({ extended: true }));
80
+
81
+ // Configurar headers de CORS
82
+ app.use((req, res, next) => {
83
+ res.header('Access-Control-Allow-Origin', '*');
84
+ res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
85
+ res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
86
+
87
+ if (req.method === 'OPTIONS') {
88
+ res.sendStatus(200);
89
+ } else {
90
+ next();
91
+ }
92
+ });
93
+
94
+ // ==============================================
95
+ // RUNTIME MODE ENDPOINT
96
+ // ==============================================
97
+
98
+ app.get('/slice-env.json', (req, res) => {
99
+ const payload = publicEnvProvider.getPayload();
100
+ res.setHeader('Cache-Control', 'no-store');
101
+ res.setHeader('Pragma', 'no-cache');
102
+ res.setHeader('Expires', '0');
103
+ res.json(payload);
104
+ });
105
+
106
+ // ==============================================
107
+ // ARCHIVOS ESTÁTICOS (DESPUÉS DE SEGURIDAD)
108
+ // ==============================================
109
+
110
+ if (runMode === 'production') {
111
+ app.get('/Slice/Slice.js', (req, res) => {
112
+ const slicePath = path.join(__dirname, '..', 'node_modules', 'slicejs-web-framework', 'Slice', 'Slice.js');
113
+ try {
114
+ if (fs.existsSync(slicePath)) {
115
+ res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
116
+ return res.send(fs.readFileSync(slicePath, 'utf8'));
117
+ }
118
+ } catch (error) {
119
+ console.error(`Error reading Slice.js:`, error);
120
+ return res.status(500).send('Error loading framework');
121
+ }
122
+ return res.status(404).send('Slice.js not found');
123
+ });
124
+
125
+ app.use('/Slice', (req, res) => res.status(404).send('Not found'));
126
+ app.use('/Components', (req, res) => res.status(404).send('Not found'));
127
+ }
128
+
129
+ // Middleware personalizado para archivos de bundles con MIME types correctos
130
+ // ⚠️ DEBE IR ANTES del middleware general para tener prioridad
131
+ app.use('/bundles/', (req, res, next) => {
132
+ // Solo procesar archivos .js
133
+ if (req.path.endsWith('.js')) {
134
+ const filePath = path.join(__dirname, `../${folderDeployed}`, 'bundles', req.path);
135
+ console.log(`📂 Processing bundle: ${req.path} -> ${filePath}`);
136
+
137
+ // Verificar que el archivo existe
138
+ if (fs.existsSync(filePath)) {
139
+ try {
140
+ // Leer y servir el archivo con headers correctos
141
+ const fileContent = fs.readFileSync(filePath, 'utf8');
142
+ res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
143
+ res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); // No cachear para permitir actualizaciones en tiempo real
144
+ res.setHeader('Pragma', 'no-cache');
145
+ res.setHeader('Expires', '0');
146
+ console.log(`✅ Serving bundle: ${req.path} (${fileContent.length} bytes, ${Buffer.byteLength(fileContent, 'utf8')} bytes UTF-8)`);
147
+ return res.send(fileContent);
148
+ } catch (error) {
149
+ console.error(`Error reading bundle file:`, error);
150
+ return res.status(500).send('Error reading bundle file');
151
+ }
152
+ } else {
153
+ console.log(`❌ Bundle file not found: ${filePath}`);
154
+ return res.status(404).send('Bundle file not found');
155
+ }
156
+ }
157
+
158
+ // Para archivos no .js, continuar con el middleware estático normal
159
+ next();
160
+ });
161
+
162
+ // Servir otros archivos de bundles (JSON, CSS, etc.) con el middleware estático normal
163
+ app.use('/bundles/', express.static(path.join(__dirname, `../${folderDeployed}`, 'bundles')));
164
+ console.log(`📦 Serving bundles from /${folderDeployed}/bundles`);
165
+
166
+ // Servir framework Slice.js (solo development)
167
+ if (runMode === 'development') {
168
+ app.use('/Slice/', express.static(path.join(__dirname, '..', 'node_modules', 'slicejs-web-framework', 'Slice')));
169
+ }
170
+
171
+ // Servir archivos estáticos del proyecto con allowlist
172
+ const publicFolders = Array.isArray(sliceConfig.publicFolders) ? sliceConfig.publicFolders : [];
173
+ const normalizedPublicFolders = publicFolders
174
+ .filter((entry) => typeof entry === 'string')
175
+ .map((entry) => entry.trim())
176
+ .filter((entry) => entry.length > 0)
177
+ .map((entry) => (entry.startsWith('/') ? entry : `/${entry}`));
178
+
179
+ if (runMode === 'development') {
180
+ app.use(express.static(path.join(__dirname, `../${folderDeployed}`)));
181
+ } else {
182
+ app.use('/App', express.static(path.join(__dirname, `../${folderDeployed}`, 'App')));
183
+ const serveStaticFile = (req, res, filePath, contentType, fileName) => {
184
+ try {
185
+ if (fs.existsSync(filePath)) {
186
+ res.setHeader('Content-Type', contentType);
187
+ return res.send(fs.readFileSync(filePath, 'utf8'));
188
+ }
189
+ } catch (error) {
190
+ console.error(`Error reading ${fileName}:`, error);
191
+ return res.status(500).send(`Error reading ${fileName}`);
192
+ }
193
+ return res.status(404).send(`${fileName} not found`);
194
+ };
195
+
196
+ app.get('/manifest.json', (req, res) => {
197
+ const manifestPath = path.join(__dirname, `../${folderDeployed}`, 'manifest.json');
198
+ serveStaticFile(req, res, manifestPath, 'application/json; charset=utf-8', 'manifest.json');
199
+ });
200
+ app.get('/service-worker.js', (req, res) => {
201
+ const workerPath = path.join(__dirname, `../${folderDeployed}`, 'service-worker.js');
202
+ serveStaticFile(req, res, workerPath, 'application/javascript; charset=utf-8', 'service-worker.js');
203
+ });
204
+ app.get('/routes.js', (req, res) => {
205
+ const routesPath = path.join(__dirname, `../${folderDeployed}`, 'routes.js');
206
+ serveStaticFile(req, res, routesPath, 'application/javascript; charset=utf-8', 'routes.js');
207
+ });
208
+ app.get('/sliceConfig.json', (req, res) => {
209
+ const configPath = path.join(__dirname, `../${folderDeployed}`, 'sliceConfig.json');
210
+ serveStaticFile(req, res, configPath, 'application/json; charset=utf-8', 'sliceConfig.json');
211
+ });
212
+ for (const folder of normalizedPublicFolders) {
213
+ app.use(folder, express.static(path.join(__dirname, `../${folderDeployed}`, folder)));
214
+ }
215
+ app.use('/bundles/', express.static(path.join(__dirname, `../${folderDeployed}`, 'bundles')));
216
+ app.use('/dist/', express.static(path.join(__dirname, '..', 'dist')));
217
+ }
218
+
219
+ // ==============================================
220
+ // RUTAS DE API
221
+ // ==============================================
222
+
223
+ // Ruta de ejemplo para API
224
+ app.get('/api/status', (req, res) => {
225
+ res.json({
226
+ status: 'ok',
227
+ mode: runMode,
228
+ folder: folderDeployed,
229
+ timestamp: new Date().toISOString(),
230
+ framework: 'Slice.js',
231
+ version: '2.0.0',
232
+ security: {
233
+ enabled: true,
234
+ mode: 'automatic',
235
+ description: 'Zero-config security - works with any domain'
236
+ }
237
+ });
238
+ });
239
+
240
+
241
+ // ==============================================
242
+ // SPA FALLBACK
243
+ // ==============================================
244
+
245
+ // SPA fallback - servir index.html para rutas no encontradas
246
+ app.get('*', (req, res) => {
247
+ const indexPath = path.join(__dirname, `../${folderDeployed}`, "App", 'index.html');
248
+ res.sendFile(indexPath, (err) => {
249
+ if (err) {
250
+ console.error(`[SPA Fallback] Error sending ${indexPath}:`, err);
251
+ res.status(500).send(`<h1>500 - Internal Server Error</h1><p>Could not serve application file</p>`);
252
+ }
253
+ });
254
+ });
255
+
256
+ // ==============================================
257
+ // INICIO DEL SERVIDOR
258
+ // ==============================================
259
+
260
+ function startServer() {
261
+ server = app.listen(PORT, () => {
262
+ console.log(`🔒 Security middleware: active (zero-config, automatic)`);
263
+ console.log(`🚀 Slice.js server running on port ${PORT}`);
264
+ });
265
+ }
266
+
267
+ // Manejar cierre del proceso
268
+ process.on('SIGINT', () => {
269
+ console.log('\n🛑 Slice server stopped');
270
+ process.exit(0);
271
+ });
272
+
273
+ process.on('SIGTERM', () => {
274
+ console.log('\n🛑 Server terminated');
275
+ process.exit(0);
276
+ });
277
+
278
+ // Iniciar servidor
279
+ startServer();
280
+
281
+ export default app;