underpost 2.7.1 → 2.7.3

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 (214) hide show
  1. package/.dockerignore +13 -13
  2. package/.env.development +7 -7
  3. package/.env.production +7 -7
  4. package/.env.test +7 -7
  5. package/.github/workflows/publish.yml +26 -0
  6. package/.github/workflows/test.yml +80 -0
  7. package/.nycrc +9 -9
  8. package/.prettierignore +12 -12
  9. package/.prettierrc +9 -9
  10. package/.vscode/extensions.json +72 -72
  11. package/.vscode/settings.json +100 -99
  12. package/Dockerfile +89 -89
  13. package/LICENSE +21 -21
  14. package/README.md +96 -96
  15. package/bin/db.js +172 -119
  16. package/bin/deploy.js +607 -661
  17. package/bin/file.js +93 -92
  18. package/bin/index.js +76 -53
  19. package/bin/ssl.js +55 -64
  20. package/bin/util.js +182 -182
  21. package/bin/vs.js +35 -35
  22. package/conf.js +251 -249
  23. package/docker-compose.yml +67 -67
  24. package/jsconfig.json +7 -7
  25. package/jsdoc.json +32 -32
  26. package/nodemon.json +6 -6
  27. package/package.json +137 -132
  28. package/prometheus.yml +36 -36
  29. package/setup.sh +24 -24
  30. package/src/api/core/core.controller.js +69 -69
  31. package/src/api/core/core.model.js +11 -11
  32. package/src/api/core/core.router.js +23 -23
  33. package/src/api/core/core.service.js +29 -29
  34. package/src/api/crypto/crypto.controller.js +51 -51
  35. package/src/api/crypto/crypto.model.js +23 -23
  36. package/src/api/crypto/crypto.router.js +20 -20
  37. package/src/api/crypto/crypto.service.js +64 -64
  38. package/src/api/default/default.controller.js +69 -69
  39. package/src/api/default/default.model.js +20 -20
  40. package/src/api/default/default.router.js +23 -23
  41. package/src/api/default/default.service.js +31 -31
  42. package/src/api/file/file.controller.js +53 -51
  43. package/src/api/file/file.model.js +19 -19
  44. package/src/api/file/file.router.js +21 -20
  45. package/src/api/file/file.service.js +76 -70
  46. package/src/api/instance/instance.controller.js +69 -69
  47. package/src/api/instance/instance.model.js +36 -36
  48. package/src/api/instance/instance.router.js +33 -33
  49. package/src/api/instance/instance.service.js +48 -48
  50. package/src/api/test/test.controller.js +59 -59
  51. package/src/api/test/test.model.js +14 -14
  52. package/src/api/test/test.router.js +21 -21
  53. package/src/api/test/test.service.js +35 -35
  54. package/src/api/user/user.build.js +16 -0
  55. package/src/api/user/user.controller.js +70 -70
  56. package/src/api/user/user.model.js +65 -65
  57. package/src/api/user/user.router.js +345 -345
  58. package/src/api/user/user.service.js +479 -479
  59. package/src/api.js +23 -23
  60. package/src/client/Default.index.js +40 -40
  61. package/src/client/components/core/Account.js +290 -290
  62. package/src/client/components/core/AgGrid.js +160 -160
  63. package/src/client/components/core/Auth.js +19 -19
  64. package/src/client/components/core/Badge.js +32 -32
  65. package/src/client/components/core/{BlockChain.js → Blockchain.js} +41 -41
  66. package/src/client/components/core/Blog.js +9 -9
  67. package/src/client/components/core/BtnIcon.js +101 -94
  68. package/src/client/components/core/CalendarCore.js +458 -319
  69. package/src/client/components/core/Chat.js +64 -64
  70. package/src/client/components/core/ColorPalette.js +5267 -5267
  71. package/src/client/components/core/CommonJs.js +735 -732
  72. package/src/client/components/core/Content.js +193 -49
  73. package/src/client/components/core/Css.js +1064 -1027
  74. package/src/client/components/core/CssCore.js +817 -796
  75. package/src/client/components/core/D3Chart.js +44 -44
  76. package/src/client/components/core/Docs.js +229 -229
  77. package/src/client/components/core/DropDown.js +164 -164
  78. package/src/client/components/core/EventsUI.js +46 -54
  79. package/src/client/components/core/FileExplorer.js +699 -624
  80. package/src/client/components/core/FullScreen.js +45 -45
  81. package/src/client/components/core/Input.js +346 -259
  82. package/src/client/components/core/JoyStick.js +77 -77
  83. package/src/client/components/core/Keyboard.js +73 -73
  84. package/src/client/components/core/LoadingAnimation.js +179 -157
  85. package/src/client/components/core/LogIn.js +187 -181
  86. package/src/client/components/core/LogOut.js +58 -52
  87. package/src/client/components/core/Logger.js +26 -26
  88. package/src/client/components/core/Modal.js +1612 -1596
  89. package/src/client/components/core/NotificationManager.js +84 -84
  90. package/src/client/components/core/Panel.js +613 -413
  91. package/src/client/components/core/PanelForm.js +468 -0
  92. package/src/client/components/core/Polyhedron.js +162 -162
  93. package/src/client/components/core/Recover.js +204 -204
  94. package/src/client/components/core/Responsive.js +53 -53
  95. package/src/client/components/core/RichText.js +51 -27
  96. package/src/client/components/core/Router.js +76 -77
  97. package/src/client/components/core/Scroll.js +34 -0
  98. package/src/client/components/core/SignUp.js +125 -125
  99. package/src/client/components/core/SocketIo.js +72 -72
  100. package/src/client/components/core/Stream.js +113 -113
  101. package/src/client/components/core/ToggleSwitch.js +87 -87
  102. package/src/client/components/core/ToolTip.js +26 -26
  103. package/src/client/components/core/Translate.js +437 -408
  104. package/src/client/components/core/Validator.js +100 -100
  105. package/src/client/components/core/VanillaJs.js +460 -457
  106. package/src/client/components/core/Wallet.js +106 -106
  107. package/src/client/components/core/Webhook.js +25 -25
  108. package/src/client/components/core/Worker.js +272 -272
  109. package/src/client/components/default/CommonDefault.js +29 -29
  110. package/src/client/components/default/CssDefault.js +13 -13
  111. package/src/client/components/default/ElementsDefault.js +38 -38
  112. package/src/client/components/default/LogInDefault.js +41 -41
  113. package/src/client/components/default/LogOutDefault.js +28 -28
  114. package/src/client/components/default/MenuDefault.js +389 -389
  115. package/src/client/components/default/RoutesDefault.js +48 -48
  116. package/src/client/components/default/SettingsDefault.js +16 -16
  117. package/src/client/components/default/SignUpDefault.js +9 -9
  118. package/src/client/components/default/SocketIoDefault.js +54 -54
  119. package/src/client/components/default/TranslateDefault.js +7 -7
  120. package/src/client/public/default/assets/mailer/api-user-check.png +0 -0
  121. package/src/client/public/default/assets/mailer/api-user-invalid-token.png +0 -0
  122. package/src/client/public/default/assets/mailer/api-user-recover.png +0 -0
  123. package/src/client/public/default/browserconfig.xml +11 -11
  124. package/src/client/public/default/manifest.webmanifest +68 -68
  125. package/src/client/public/default/plantuml/client-conf.svg +1 -0
  126. package/src/client/public/default/plantuml/client-schema.svg +1 -0
  127. package/src/client/public/default/plantuml/cron-conf.svg +1 -0
  128. package/src/client/public/default/plantuml/cron-schema.svg +1 -0
  129. package/src/client/public/default/plantuml/server-conf.svg +1 -0
  130. package/src/client/public/default/plantuml/server-schema.svg +1 -0
  131. package/src/client/public/default/plantuml/ssr-conf.svg +1 -0
  132. package/src/client/public/default/plantuml/ssr-schema.svg +1 -0
  133. package/src/client/public/default/sitemap +147 -147
  134. package/src/client/public/default/yandex-browser-manifest.json +8 -8
  135. package/src/client/public/doc/sitemap +147 -147
  136. package/src/client/public/test/sitemap +147 -147
  137. package/src/client/services/core/core.service.js +170 -152
  138. package/src/client/services/crypto/crypto.service.js +70 -70
  139. package/src/client/services/default/default.management.js +345 -345
  140. package/src/client/services/default/default.service.js +89 -89
  141. package/src/client/services/file/file.service.js +70 -70
  142. package/src/client/services/instance/instance.management.js +74 -74
  143. package/src/client/services/instance/instance.service.js +89 -89
  144. package/src/client/services/test/test.service.js +70 -70
  145. package/src/client/services/user/user.management.js +50 -50
  146. package/src/client/services/user/user.service.js +89 -89
  147. package/src/client/ssr/Render.js +16 -16
  148. package/src/client/ssr/body-components/CacheControl.js +114 -113
  149. package/src/client/ssr/body-components/DefaultSplashScreen.js +79 -79
  150. package/src/client/ssr/email-components/DefaultRecoverEmail.js +21 -21
  151. package/src/client/ssr/email-components/DefaultVerifyEmail.js +17 -17
  152. package/src/client/ssr/head-components/Css.js +241 -241
  153. package/src/client/ssr/head-components/DefaultScripts.js +3 -3
  154. package/src/client/ssr/head-components/Microdata.js +11 -11
  155. package/src/client/ssr/head-components/Production.js +1 -1
  156. package/src/client/ssr/head-components/PwaDefault.js +59 -59
  157. package/src/client/ssr/head-components/Seo.js +14 -14
  158. package/src/client/sw/default.sw.js +201 -201
  159. package/src/client/sw/template.sw.js +84 -84
  160. package/src/client.build.js +22 -22
  161. package/src/client.dev.js +21 -21
  162. package/src/cron.js +25 -25
  163. package/src/db/DataBaseProvider.js +34 -34
  164. package/src/db/mariadb/MariaDB.js +33 -33
  165. package/src/db/mongo/MongooseDB.js +137 -46
  166. package/src/dns.js +22 -22
  167. package/src/index.js +42 -29
  168. package/src/mailer/EmailRender.js +69 -69
  169. package/src/mailer/MailerProvider.js +96 -96
  170. package/src/proxy.js +22 -22
  171. package/src/runtime/lampp/Lampp.js +115 -44
  172. package/src/runtime/nginx/Nginx.js +3 -3
  173. package/src/runtime/xampp/Xampp.js +49 -49
  174. package/src/server/auth.js +235 -204
  175. package/src/server/backup.js +101 -94
  176. package/src/server/client-build-live.js +72 -72
  177. package/src/server/client-build.js +699 -699
  178. package/src/server/client-dev-server.js +60 -58
  179. package/src/server/client-formatted.js +48 -48
  180. package/src/server/client-icons.js +149 -150
  181. package/src/server/conf.js +860 -611
  182. package/src/server/dns.js +98 -98
  183. package/src/server/downloader.js +42 -42
  184. package/src/server/logger.js +190 -180
  185. package/src/server/network.js +122 -122
  186. package/src/server/peer.js +33 -33
  187. package/src/server/process.js +66 -66
  188. package/src/server/prompt-optimizer.js +28 -28
  189. package/src/server/proxy.js +118 -118
  190. package/src/server/runtime.js +444 -393
  191. package/src/server/ssl.js +120 -107
  192. package/src/server.js +25 -25
  193. package/src/ws/IoInterface.js +45 -45
  194. package/src/ws/IoServer.js +39 -39
  195. package/src/ws/core/channels/core.ws.chat.js +23 -23
  196. package/src/ws/core/channels/core.ws.mailer.js +35 -35
  197. package/src/ws/core/channels/core.ws.stream.js +31 -31
  198. package/src/ws/core/core.ws.connection.js +28 -28
  199. package/src/ws/core/core.ws.emit.js +14 -14
  200. package/src/ws/core/core.ws.server.js +24 -24
  201. package/src/ws/core/management/core.ws.chat.js +8 -8
  202. package/src/ws/core/management/core.ws.mailer.js +16 -16
  203. package/src/ws/core/management/core.ws.stream.js +8 -8
  204. package/src/ws/default/channels/default.ws.main.js +16 -16
  205. package/src/ws/default/default.ws.connection.js +22 -22
  206. package/src/ws/default/default.ws.emit.js +14 -14
  207. package/src/ws/default/default.ws.server.js +20 -20
  208. package/src/ws/default/management/default.ws.main.js +8 -8
  209. package/startup.js +11 -11
  210. package/supervisord-openssh-server.conf +4 -4
  211. package/test/api.test.js +60 -60
  212. package/bin/dns.js +0 -1
  213. package/bin/install.js +0 -357
  214. package/bin/shortcut.js +0 -44
@@ -1,393 +1,444 @@
1
- import fs from 'fs';
2
- import express from 'express';
3
- import cors from 'cors';
4
- import dotenv from 'dotenv';
5
- import fileUpload from 'express-fileupload';
6
- import swaggerUi from 'swagger-ui-express';
7
- import * as promClient from 'prom-client';
8
- import compression from 'compression';
9
-
10
- import { createServer } from 'http';
11
- import { getRootDirectory } from './process.js';
12
- import { network, listenPortController, saveRuntimeRouter, logRuntimeRouter, listenServerFactory } from './network.js';
13
- import { loggerFactory, loggerMiddleware } from './logger.js';
14
- import { newInstance } from '../client/components/core/CommonJs.js';
15
- import { Xampp } from '../runtime/xampp/Xampp.js';
16
- import { MailerProvider } from '../mailer/MailerProvider.js';
17
- import { DataBaseProvider } from '../db/DataBaseProvider.js';
18
- import { createProxyMiddleware } from 'http-proxy-middleware';
19
- import { createPeerServer } from './peer.js';
20
- import { Lampp } from '../runtime/lampp/Lampp.js';
21
-
22
- dotenv.config();
23
-
24
- const logger = loggerFactory(import.meta);
25
-
26
- const buildRuntime = async () => {
27
- const deployId = `${process.argv[3] ? process.argv[3] : 'default'}`;
28
-
29
- const collectDefaultMetrics = promClient.collectDefaultMetrics;
30
- collectDefaultMetrics();
31
-
32
- const promCounterOption = {
33
- name: `${deployId.replaceAll('-', '_')}_http_requests_total`,
34
- help: 'Total number of HTTP requests',
35
- labelNames: ['instance', 'method', 'status_code'],
36
- };
37
-
38
- // logger.info('promCounterOption', promCounterOption);
39
-
40
- const requestCounter = new promClient.Counter(promCounterOption);
41
-
42
- const ipInstance = ''; // await ip.public.ipv4();
43
- const initPort = parseInt(process.env.PORT) + 1;
44
- let currentPort = initPort;
45
- const confServer = JSON.parse(fs.readFileSync(`./conf/conf.server.json`, 'utf8'));
46
- const singleReplicaHosts = [];
47
- for (const host of Object.keys(confServer)) {
48
- if (singleReplicaHosts.length > 0 && !singleReplicaHosts.includes(host)) {
49
- currentPort += singleReplicaHosts.reduce((accumulator, currentValue) => accumulator + currentValue.replicas, 0);
50
- }
51
- const rootHostPath = `/public/${host}`;
52
- for (const path of Object.keys(confServer[host])) {
53
- confServer[host][path].port = newInstance(currentPort);
54
- const {
55
- runtime,
56
- port,
57
- client,
58
- apis,
59
- origins,
60
- directory,
61
- ws,
62
- mailer,
63
- db,
64
- redirect,
65
- peer,
66
- singleReplica,
67
- replicas,
68
- } = confServer[host][path];
69
-
70
- if (singleReplica && replicas && replicas.length > 0 && !singleReplicaHosts.includes(host)) {
71
- singleReplicaHosts.push({
72
- host,
73
- replicas: replicas.length,
74
- });
75
- continue;
76
- }
77
-
78
- const runningData = {
79
- host,
80
- path,
81
- runtime,
82
- client,
83
- meta: import.meta,
84
- };
85
-
86
- let redirectUrl;
87
- let redirectTarget;
88
- if (redirect) {
89
- redirectUrl = new URL(redirect);
90
- redirectTarget = redirect[redirect.length - 1] === '/' ? redirect.slice(0, -1) : redirect;
91
- }
92
-
93
- logger.info('Build runtime', `${host}${path}`);
94
-
95
- switch (runtime) {
96
- case 'lampp':
97
- if (!Lampp.enabled()) continue;
98
- if (!Lampp.ports.includes(port)) Lampp.ports.push(port);
99
- if (currentPort === initPort) Lampp.removeRouter();
100
- Lampp.appendRouter(`
101
-
102
- Listen ${port}
103
-
104
- <VirtualHost *:${port}>
105
- DocumentRoot "${directory ? directory.replace(path, '/') : `${getRootDirectory()}${rootHostPath}`}"
106
- ServerName ${host}:${port}
107
-
108
- <Directory "${directory ? directory.replace(path, '/') : `${getRootDirectory()}${rootHostPath}`}">
109
- Options Indexes FollowSymLinks MultiViews
110
- AllowOverride All
111
- Require all granted
112
- </Directory>
113
-
114
- ${
115
- redirect
116
- ? `
117
- RewriteEngine on
118
-
119
- RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge
120
- RewriteRule ^(.*)$ ${redirectTarget}%{REQUEST_URI} [R=302,L]
121
- `
122
- : ''
123
- }
124
-
125
- </VirtualHost>
126
-
127
- `);
128
- // ERR too many redirects:
129
- // Check: SELECT * FROM database.wp_options where option_name = 'siteurl' or option_name = 'home';
130
- // Check: wp-config.php
131
- // if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
132
- // $_SERVER['HTTPS'] = 'on';
133
- // }
134
-
135
- // ErrorDocument 404 /custom_404.html
136
- // ErrorDocument 500 /custom_50x.html
137
- // ErrorDocument 502 /custom_50x.html
138
- // ErrorDocument 503 /custom_50x.html
139
- // ErrorDocument 504 /custom_50x.html
140
-
141
- // Respond When Error Pages are Directly Requested
142
-
143
- // <Files "custom_404.html">
144
- // <If "-z %{ENV:REDIRECT_STATUS}">
145
- // RedirectMatch 404 ^/custom_404.html$
146
- // </If>
147
- // </Files>
148
-
149
- // <Files "custom_50x.html">
150
- // <If "-z %{ENV:REDIRECT_STATUS}">
151
- // RedirectMatch 404 ^/custom_50x.html$
152
- // </If>
153
- // </Files>
154
- await listenPortController(listenServerFactory(), port, runningData);
155
- break;
156
- case 'xampp':
157
- if (!Xampp.enabled()) continue;
158
- if (!Xampp.ports.includes(port)) Xampp.ports.push(port);
159
- if (currentPort === initPort) Xampp.removeRouter();
160
- Xampp.appendRouter(`
161
-
162
- Listen ${port}
163
-
164
- <VirtualHost *:${port}>
165
- DocumentRoot "${directory ? directory.replace(path, '/') : `${getRootDirectory()}${rootHostPath}`}"
166
- ServerName ${host}:${port}
167
-
168
- <Directory "${directory ? directory.replace(path, '/') : `${getRootDirectory()}${rootHostPath}`}">
169
- Options Indexes FollowSymLinks MultiViews
170
- AllowOverride All
171
- Require all granted
172
- </Directory>
173
-
174
- ${
175
- redirect
176
- ? `
177
- RewriteEngine on
178
-
179
- RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge
180
- RewriteRule ^(.*)$ ${redirectTarget}%{REQUEST_URI} [R=302,L]
181
- `
182
- : ''
183
- }
184
-
185
- </VirtualHost>
186
-
187
- `);
188
- // ERR too many redirects:
189
- // Check: SELECT * FROM database.wp_options where option_name = 'siteurl' or option_name = 'home';
190
- // Check: wp-config.php
191
- // if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
192
- // $_SERVER['HTTPS'] = 'on';
193
- // }
194
- await listenPortController(listenServerFactory(), port, runningData);
195
- break;
196
- case 'nodejs':
197
- const app = express();
198
-
199
- app.use((req, res, next) => {
200
- // const info = `${req.headers.host}${req.url}`;
201
- return next();
202
- });
203
-
204
- // https://github.com/prometheus/prometheus/blob/main/documentation/examples/prometheus.yml
205
- // https://github.com/grafana/grafana/tree/main/conf
206
- // https://medium.com/@diego.coder/monitoreo-de-aplicaciones-con-node-js-grafana-y-prometheus-afd2b33e3f91
207
- // for grafana prometheus server: host.docker.internal:9090
208
-
209
- app.use((req, res, next) => {
210
- requestCounter.inc({
211
- instance: `${host}:${port}${path}`,
212
- method: req.method,
213
- status_code: res.statusCode,
214
- });
215
- // decodeURIComponent(req.url)
216
- return next();
217
- });
218
-
219
- app.get(`${path === '/' ? '' : path}/metrics`, async (req, res) => {
220
- res.set('Content-Type', promClient.register.contentType);
221
- return res.end(await promClient.register.metrics());
222
- });
223
-
224
- // set logger
225
- app.use(loggerMiddleware(import.meta));
226
-
227
- // instance public static
228
- app.use('/', express.static(directory ? directory : `.${rootHostPath}`));
229
-
230
- // js src compression
231
- app.use(compression({ filter: shouldCompress }));
232
- function shouldCompress(req, res) {
233
- if (req.headers['x-no-compression']) {
234
- // don't compress responses with this request header
235
- return false;
236
- }
237
-
238
- // fallback to standard filter function
239
- return compression.filter(req, res);
240
- }
241
-
242
- // parse requests of content-type - application/json
243
- app.use(express.json({ limit: '100MB' }));
244
-
245
- // parse requests of content-type - application/x-www-form-urlencoded
246
- app.use(express.urlencoded({ extended: true, limit: '20MB' }));
247
-
248
- // file upload middleware
249
- app.use(fileUpload());
250
-
251
- // json formatted response
252
- app.set('json spaces', 2);
253
-
254
- // lang handling middleware
255
- app.use(function (req, res, next) {
256
- const lang = req.headers['accept-language'] || 'en';
257
- if (typeof lang === 'string' && lang.toLowerCase().match('es')) {
258
- req.lang = 'es';
259
- } else req.lang = 'en';
260
- return next();
261
- });
262
-
263
- // cors
264
- app.use(cors({ origin: origins }));
265
-
266
- if (redirect) {
267
- app.use(function (req = express.Request, res = express.Response, next = express.NextFunction) {
268
- if (process.env.NODE_ENV === 'production' && !req.url.startsWith(`/.well-known/acme-challenge`))
269
- return res.status(302).redirect(redirectTarget + req.url);
270
- // if (!req.url.startsWith(`/.well-known/acme-challenge`)) return res.status(302).redirect(redirect);
271
- return next();
272
- });
273
- // app.use(
274
- // '*',
275
- // createProxyMiddleware({
276
- // target: redirect,
277
- // changeOrigin: true,
278
- // }),
279
- // );
280
- await network.port.portClean(port);
281
- await listenPortController(app, port, runningData);
282
- break;
283
- }
284
-
285
- const swaggerJsonPath = `./public/${host}${path === '/' ? path : `${path}/`}swagger-output.json`;
286
- if (fs.existsSync(swaggerJsonPath)) {
287
- // logger.info('Build swagger serve', swaggerJsonPath);
288
-
289
- const swaggerInstance =
290
- (swaggerDoc) =>
291
- (...args) =>
292
- swaggerUi.setup(swaggerDoc)(...args);
293
-
294
- const swaggerDoc = JSON.parse(fs.readFileSync(swaggerJsonPath, 'utf8'));
295
-
296
- app.use(`${path === '/' ? `/api-docs` : `${path}/api-docs`}`, swaggerUi.serve, swaggerInstance(swaggerDoc));
297
- }
298
-
299
- if (db && apis) await DataBaseProvider.load({ apis, host, path, db });
300
-
301
- if (mailer)
302
- await MailerProvider.load({
303
- id: `${host}${path}`,
304
- meta: `mailer-${host}${path}`,
305
- host,
306
- path,
307
- ...mailer,
308
- });
309
-
310
- if (apis) {
311
- const apiPath = `${path === '/' ? '' : path}/${process.env.BASE_API}`;
312
- for (const api of apis)
313
- await (async () => {
314
- const { ApiRouter } = await import(`../api/${api}/${api}.router.js`);
315
- const router = ApiRouter({ host, path, apiPath, mailer, db });
316
- // router.use(cors({ origin: origins }));
317
- // logger.info('Load api router', { host, path: apiPath, api });
318
- app.use(`${apiPath}/${api}`, router);
319
- })();
320
- }
321
-
322
- app.use(function (req, res, next) {
323
- res.status(404).send('Sorry cant find that!');
324
- });
325
-
326
- app.use(function (err, req, res, next) {
327
- logger.error(err, err.stack);
328
- res.status(500).send('Something broke!');
329
- });
330
-
331
- // instance server
332
- const server = createServer({}, app);
333
-
334
- if (ws)
335
- await (async () => {
336
- const { createIoServer } = await import(`../ws/${ws}/${ws}.ws.server.js`);
337
- // logger.info('Load socket.io ws router', { host, ws });
338
- // start socket.io
339
- const { options, meta } = await createIoServer(server, {
340
- host,
341
- path,
342
- db,
343
- port,
344
- origins,
345
- });
346
- await listenPortController(listenServerFactory(), port, {
347
- runtime: 'nodejs',
348
- client: null,
349
- host,
350
- path: options.path,
351
- meta,
352
- });
353
- })();
354
-
355
- if (peer) {
356
- currentPort++;
357
- const peerPort = newInstance(currentPort);
358
- const { options, meta, peerServer } = await createPeerServer({
359
- port: peerPort,
360
- devPort: port,
361
- origins,
362
- host,
363
- path,
364
- });
365
- await network.port.portClean(peerPort);
366
- await listenPortController(peerServer, peerPort, {
367
- runtime: 'nodejs',
368
- client: null,
369
- host,
370
- path: options.path,
371
- meta,
372
- });
373
- }
374
-
375
- await network.port.portClean(port);
376
- await listenPortController(server, port, runningData);
377
-
378
- break;
379
- default:
380
- break;
381
- }
382
- currentPort++;
383
- }
384
- }
385
-
386
- if (Xampp.enabled() && Xampp.router) await Xampp.initService({ daemon: true });
387
- if (Lampp.enabled() && Lampp.router) await Lampp.initService({ daemon: true });
388
-
389
- saveRuntimeRouter();
390
- logRuntimeRouter();
391
- };
392
-
393
- export { buildRuntime };
1
+ import fs from 'fs';
2
+ import express from 'express';
3
+ import cors from 'cors';
4
+ import dotenv from 'dotenv';
5
+ import fileUpload from 'express-fileupload';
6
+ import swaggerUi from 'swagger-ui-express';
7
+ import * as promClient from 'prom-client';
8
+ import compression from 'compression';
9
+
10
+ import { createServer } from 'http';
11
+ import { getRootDirectory } from './process.js';
12
+ import { network, listenPortController, saveRuntimeRouter, logRuntimeRouter, listenServerFactory } from './network.js';
13
+ import { loggerFactory, loggerMiddleware } from './logger.js';
14
+ import { newInstance } from '../client/components/core/CommonJs.js';
15
+ import { Xampp } from '../runtime/xampp/Xampp.js';
16
+ import { MailerProvider } from '../mailer/MailerProvider.js';
17
+ import { DataBaseProvider } from '../db/DataBaseProvider.js';
18
+ import { createProxyMiddleware } from 'http-proxy-middleware';
19
+ import { createPeerServer } from './peer.js';
20
+ import { Lampp } from '../runtime/lampp/Lampp.js';
21
+
22
+ dotenv.config();
23
+
24
+ const logger = loggerFactory(import.meta);
25
+
26
+ const buildRuntime = async () => {
27
+ const deployId = `${process.argv[3] ? process.argv[3] : 'default'}`;
28
+
29
+ const collectDefaultMetrics = promClient.collectDefaultMetrics;
30
+ collectDefaultMetrics();
31
+
32
+ if (fs.existsSync(`/root/.bashrc`) && !fs.readFileSync(`/root/.bashrc`, 'utf8').match(`underpost-engine`)) {
33
+ fs.writeFileSync(
34
+ `/root/.bashrc`,
35
+ `${fs.readFileSync(`/root/.bashrc`, 'utf8')}
36
+ ` +
37
+ `export NVM_DIR="$HOME/.nvm"
38
+ [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
39
+ [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm underpost-engine bash_completion
40
+
41
+ export PATH=$PATH:/opt/lampp/bin`,
42
+ 'utf8',
43
+ );
44
+ }
45
+
46
+ const promCounterOption = {
47
+ name: `${deployId.replaceAll('-', '_')}_http_requests_total`,
48
+ help: 'Total number of HTTP requests',
49
+ labelNames: ['instance', 'method', 'status_code'],
50
+ };
51
+
52
+ // logger.info('promCounterOption', promCounterOption);
53
+
54
+ const requestCounter = new promClient.Counter(promCounterOption);
55
+
56
+ const ipInstance = ''; // await ip.public.ipv4();
57
+ const initPort = parseInt(process.env.PORT) + 1;
58
+ let currentPort = initPort;
59
+ const confServer = JSON.parse(fs.readFileSync(`./conf/conf.server.json`, 'utf8'));
60
+ const singleReplicaHosts = [];
61
+ for (const host of Object.keys(confServer)) {
62
+ if (singleReplicaHosts.length > 0 && !singleReplicaHosts.includes(host)) {
63
+ currentPort += singleReplicaHosts.reduce((accumulator, currentValue) => accumulator + currentValue.replicas, 0);
64
+ }
65
+ const rootHostPath = `/public/${host}`;
66
+ for (const path of Object.keys(confServer[host])) {
67
+ confServer[host][path].port = newInstance(currentPort);
68
+ const {
69
+ runtime,
70
+ port,
71
+ client,
72
+ apis,
73
+ origins,
74
+ directory,
75
+ ws,
76
+ mailer,
77
+ db,
78
+ redirect,
79
+ peer,
80
+ singleReplica,
81
+ replicas,
82
+ } = confServer[host][path];
83
+
84
+ if (singleReplica && replicas && replicas.length > 0 && !singleReplicaHosts.includes(host)) {
85
+ singleReplicaHosts.push({
86
+ host,
87
+ replicas: replicas.length,
88
+ });
89
+ continue;
90
+ }
91
+
92
+ const runningData = {
93
+ host,
94
+ path,
95
+ runtime,
96
+ client,
97
+ meta: import.meta,
98
+ };
99
+
100
+ let redirectUrl;
101
+ let redirectTarget;
102
+ if (redirect) {
103
+ redirectUrl = new URL(redirect);
104
+ redirectTarget = redirect[redirect.length - 1] === '/' ? redirect.slice(0, -1) : redirect;
105
+ }
106
+
107
+ switch (runtime) {
108
+ case 'lampp':
109
+ if (!Lampp.enabled()) continue;
110
+ if (!Lampp.ports.includes(port)) Lampp.ports.push(port);
111
+ if (currentPort === initPort) Lampp.removeRouter();
112
+ Lampp.appendRouter(`
113
+
114
+ Listen ${port}
115
+
116
+ <VirtualHost *:${port}>
117
+ DocumentRoot "${directory ? directory.replace(path, '/') : `${getRootDirectory()}${rootHostPath}`}"
118
+ ServerName ${host}:${port}
119
+
120
+ <Directory "${directory ? directory.replace(path, '/') : `${getRootDirectory()}${rootHostPath}`}">
121
+ Options Indexes FollowSymLinks MultiViews
122
+ AllowOverride All
123
+ Require all granted
124
+ </Directory>
125
+
126
+ ${
127
+ redirect
128
+ ? `
129
+ RewriteEngine on
130
+
131
+ RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge
132
+ RewriteRule ^(.*)$ ${redirectTarget}%{REQUEST_URI} [R=302,L]
133
+ `
134
+ : ''
135
+ }
136
+
137
+ </VirtualHost>
138
+
139
+ `);
140
+ // ERR too many redirects:
141
+ // Check: SELECT * FROM database.wp_options where option_name = 'siteurl' or option_name = 'home';
142
+ // Check: wp-config.php
143
+ // if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
144
+ // $_SERVER['HTTPS'] = 'on';
145
+ // }
146
+
147
+ // ErrorDocument 404 /custom_404.html
148
+ // ErrorDocument 500 /custom_50x.html
149
+ // ErrorDocument 502 /custom_50x.html
150
+ // ErrorDocument 503 /custom_50x.html
151
+ // ErrorDocument 504 /custom_50x.html
152
+
153
+ // Respond When Error Pages are Directly Requested
154
+
155
+ // <Files "custom_404.html">
156
+ // <If "-z %{ENV:REDIRECT_STATUS}">
157
+ // RedirectMatch 404 ^/custom_404.html$
158
+ // </If>
159
+ // </Files>
160
+
161
+ // <Files "custom_50x.html">
162
+ // <If "-z %{ENV:REDIRECT_STATUS}">
163
+ // RedirectMatch 404 ^/custom_50x.html$
164
+ // </If>
165
+ // </Files>
166
+
167
+ // Add www or https with htaccess rewrite
168
+
169
+ // Options +FollowSymLinks
170
+ // RewriteEngine On
171
+ // RewriteCond %{HTTP_HOST} ^ejemplo.com [NC]
172
+ // RewriteRule ^(.*)$ http://ejemplo.com/$1 [R=301,L]
173
+
174
+ // Redirect http to https with htaccess rewrite
175
+
176
+ // RewriteEngine On
177
+ // RewriteCond %{SERVER_PORT} 80
178
+ // RewriteRule ^(.*)$ https://www.ejemplo.com/$1 [R,L]
179
+
180
+ // Redirect to HTTPS with www subdomain
181
+
182
+ // RewriteEngine On
183
+ // RewriteCond %{HTTPS} off [OR]
184
+ // RewriteCond %{HTTP_HOST} ^www\. [NC]
185
+ // RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
186
+ // RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
187
+
188
+ await listenPortController(listenServerFactory(), port, runningData);
189
+ break;
190
+ case 'xampp':
191
+ if (!Xampp.enabled()) continue;
192
+ if (!Xampp.ports.includes(port)) Xampp.ports.push(port);
193
+ if (currentPort === initPort) Xampp.removeRouter();
194
+ Xampp.appendRouter(`
195
+
196
+ Listen ${port}
197
+
198
+ <VirtualHost *:${port}>
199
+ DocumentRoot "${directory ? directory.replace(path, '/') : `${getRootDirectory()}${rootHostPath}`}"
200
+ ServerName ${host}:${port}
201
+
202
+ <Directory "${directory ? directory.replace(path, '/') : `${getRootDirectory()}${rootHostPath}`}">
203
+ Options Indexes FollowSymLinks MultiViews
204
+ AllowOverride All
205
+ Require all granted
206
+ </Directory>
207
+
208
+ ${
209
+ redirect
210
+ ? `
211
+ RewriteEngine on
212
+
213
+ RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge
214
+ RewriteRule ^(.*)$ ${redirectTarget}%{REQUEST_URI} [R=302,L]
215
+ `
216
+ : ''
217
+ }
218
+
219
+ </VirtualHost>
220
+
221
+ `);
222
+ // ERR too many redirects:
223
+ // Check: SELECT * FROM database.wp_options where option_name = 'siteurl' or option_name = 'home';
224
+ // Check: wp-config.php
225
+ // if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
226
+ // $_SERVER['HTTPS'] = 'on';
227
+ // }
228
+ await listenPortController(listenServerFactory(), port, runningData);
229
+ break;
230
+ case 'nodejs':
231
+ const app = express();
232
+
233
+ app.use((req, res, next) => {
234
+ // const info = `${req.headers.host}${req.url}`;
235
+ return next();
236
+ });
237
+
238
+ // https://github.com/prometheus/prometheus/blob/main/documentation/examples/prometheus.yml
239
+ // https://github.com/grafana/grafana/tree/main/conf
240
+ // https://medium.com/@diego.coder/monitoreo-de-aplicaciones-con-node-js-grafana-y-prometheus-afd2b33e3f91
241
+ // for grafana prometheus server: host.docker.internal:9090
242
+
243
+ app.use((req, res, next) => {
244
+ requestCounter.inc({
245
+ instance: `${host}:${port}${path}`,
246
+ method: req.method,
247
+ status_code: res.statusCode,
248
+ });
249
+ // decodeURIComponent(req.url)
250
+ return next();
251
+ });
252
+
253
+ app.get(`${path === '/' ? '' : path}/metrics`, async (req, res) => {
254
+ res.set('Content-Type', promClient.register.contentType);
255
+ return res.end(await promClient.register.metrics());
256
+ });
257
+
258
+ // set logger
259
+ app.use(loggerMiddleware(import.meta));
260
+
261
+ // instance public static
262
+ app.use('/', express.static(directory ? directory : `.${rootHostPath}`));
263
+
264
+ // js src compression
265
+ app.use(compression({ filter: shouldCompress }));
266
+ function shouldCompress(req, res) {
267
+ if (req.headers['x-no-compression']) {
268
+ // don't compress responses with this request header
269
+ return false;
270
+ }
271
+
272
+ // fallback to standard filter function
273
+ return compression.filter(req, res);
274
+ }
275
+
276
+ if (process.argv.includes('static')) {
277
+ logger.info('Build static server runtime', `${host}${path}`);
278
+ currentPort += 2;
279
+ const staticPort = newInstance(currentPort);
280
+ await network.port.portClean(staticPort);
281
+ await listenPortController(app, staticPort, runningData);
282
+ currentPort++;
283
+ continue;
284
+ }
285
+ logger.info('Build api server runtime', `${host}${path}`);
286
+
287
+ // parse requests of content-type - application/json
288
+ app.use(express.json({ limit: '100MB' }));
289
+
290
+ // parse requests of content-type - application/x-www-form-urlencoded
291
+ app.use(express.urlencoded({ extended: true, limit: '20MB' }));
292
+
293
+ // file upload middleware
294
+ app.use(fileUpload());
295
+
296
+ // json formatted response
297
+ app.set('json spaces', 2);
298
+
299
+ // lang handling middleware
300
+ app.use(function (req, res, next) {
301
+ const lang = req.headers['accept-language'] || 'en';
302
+ if (typeof lang === 'string' && lang.toLowerCase().match('es')) {
303
+ req.lang = 'es';
304
+ } else req.lang = 'en';
305
+ return next();
306
+ });
307
+
308
+ // cors
309
+ const originPayload = {
310
+ origin: origins.concat(
311
+ apis && process.env.NODE_ENV === 'development' ? [`http://localhost:${currentPort + 2}`] : [],
312
+ ),
313
+ };
314
+ logger.info('originPayload', originPayload);
315
+ app.use(cors(originPayload));
316
+
317
+ if (redirect) {
318
+ app.use(function (req = express.Request, res = express.Response, next = express.NextFunction) {
319
+ if (process.env.NODE_ENV === 'production' && !req.url.startsWith(`/.well-known/acme-challenge`))
320
+ return res.status(302).redirect(redirectTarget + req.url);
321
+ // if (!req.url.startsWith(`/.well-known/acme-challenge`)) return res.status(302).redirect(redirect);
322
+ return next();
323
+ });
324
+ // app.use(
325
+ // '*',
326
+ // createProxyMiddleware({
327
+ // target: redirect,
328
+ // changeOrigin: true,
329
+ // }),
330
+ // );
331
+ await network.port.portClean(port);
332
+ await listenPortController(app, port, runningData);
333
+ break;
334
+ }
335
+
336
+ const swaggerJsonPath = `./public/${host}${path === '/' ? path : `${path}/`}swagger-output.json`;
337
+ if (fs.existsSync(swaggerJsonPath)) {
338
+ // logger.info('Build swagger serve', swaggerJsonPath);
339
+
340
+ const swaggerInstance =
341
+ (swaggerDoc) =>
342
+ (...args) =>
343
+ swaggerUi.setup(swaggerDoc)(...args);
344
+
345
+ const swaggerDoc = JSON.parse(fs.readFileSync(swaggerJsonPath, 'utf8'));
346
+
347
+ app.use(`${path === '/' ? `/api-docs` : `${path}/api-docs`}`, swaggerUi.serve, swaggerInstance(swaggerDoc));
348
+ }
349
+
350
+ if (db && apis) await DataBaseProvider.load({ apis, host, path, db });
351
+
352
+ if (mailer)
353
+ await MailerProvider.load({
354
+ id: `${host}${path}`,
355
+ meta: `mailer-${host}${path}`,
356
+ host,
357
+ path,
358
+ ...mailer,
359
+ });
360
+
361
+ if (apis) {
362
+ const apiPath = `${path === '/' ? '' : path}/${process.env.BASE_API}`;
363
+ for (const api of apis)
364
+ await (async () => {
365
+ const { ApiRouter } = await import(`../api/${api}/${api}.router.js`);
366
+ const router = ApiRouter({ host, path, apiPath, mailer, db });
367
+ // router.use(cors({ origin: origins }));
368
+ // logger.info('Load api router', { host, path: apiPath, api });
369
+ app.use(`${apiPath}/${api}`, router);
370
+ })();
371
+ }
372
+
373
+ app.use(function (req, res, next) {
374
+ res.status(404).send('Sorry cant find that!');
375
+ });
376
+
377
+ app.use(function (err, req, res, next) {
378
+ logger.error(err, err.stack);
379
+ res.status(500).send('Something broke!');
380
+ });
381
+
382
+ // instance server
383
+ const server = createServer({}, app);
384
+
385
+ if (ws)
386
+ await (async () => {
387
+ const { createIoServer } = await import(`../ws/${ws}/${ws}.ws.server.js`);
388
+ // logger.info('Load socket.io ws router', { host, ws });
389
+ // start socket.io
390
+ const { options, meta } = await createIoServer(server, {
391
+ host,
392
+ path,
393
+ db,
394
+ port,
395
+ origins,
396
+ });
397
+ await listenPortController(listenServerFactory(), port, {
398
+ runtime: 'nodejs',
399
+ client: null,
400
+ host,
401
+ path: options.path,
402
+ meta,
403
+ });
404
+ })();
405
+
406
+ if (peer) {
407
+ currentPort++;
408
+ const peerPort = newInstance(currentPort);
409
+ const { options, meta, peerServer } = await createPeerServer({
410
+ port: peerPort,
411
+ devPort: port,
412
+ origins,
413
+ host,
414
+ path,
415
+ });
416
+ await network.port.portClean(peerPort);
417
+ await listenPortController(peerServer, peerPort, {
418
+ runtime: 'nodejs',
419
+ client: null,
420
+ host,
421
+ path: options.path,
422
+ meta,
423
+ });
424
+ }
425
+
426
+ await network.port.portClean(port);
427
+ await listenPortController(server, port, runningData);
428
+
429
+ break;
430
+ default:
431
+ break;
432
+ }
433
+ currentPort++;
434
+ }
435
+ }
436
+
437
+ if (Xampp.enabled() && Xampp.router) await Xampp.initService({ daemon: true });
438
+ if (Lampp.enabled() && Lampp.router) await Lampp.initService({ daemon: true });
439
+
440
+ saveRuntimeRouter();
441
+ logRuntimeRouter();
442
+ };
443
+
444
+ export { buildRuntime };