underpost 2.8.884 → 2.8.885

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +4 -120
  2. package/bin/deploy.js +9 -10
  3. package/bin/file.js +4 -6
  4. package/cli.md +15 -11
  5. package/manifests/deployment/dd-default-development/deployment.yaml +2 -2
  6. package/manifests/deployment/dd-test-development/deployment.yaml +2 -2
  7. package/package.json +1 -1
  8. package/src/cli/cluster.js +21 -0
  9. package/src/cli/cron.js +8 -0
  10. package/src/cli/db.js +63 -1
  11. package/src/cli/deploy.js +156 -3
  12. package/src/cli/env.js +43 -0
  13. package/src/cli/fs.js +94 -0
  14. package/src/cli/image.js +8 -0
  15. package/src/cli/index.js +17 -4
  16. package/src/cli/monitor.js +0 -1
  17. package/src/cli/repository.js +95 -2
  18. package/src/client/components/core/Css.js +16 -0
  19. package/src/client/components/core/Docs.js +5 -13
  20. package/src/client/components/core/Modal.js +48 -29
  21. package/src/client/components/core/Router.js +6 -3
  22. package/src/client/components/core/Worker.js +205 -118
  23. package/src/client/components/default/MenuDefault.js +1 -0
  24. package/src/client.dev.js +6 -3
  25. package/src/db/DataBaseProvider.js +65 -12
  26. package/src/db/mariadb/MariaDB.js +39 -6
  27. package/src/db/mongo/MongooseDB.js +51 -133
  28. package/src/index.js +1 -1
  29. package/src/mailer/EmailRender.js +58 -9
  30. package/src/mailer/MailerProvider.js +98 -25
  31. package/src/runtime/express/Express.js +20 -34
  32. package/src/server/auth.js +9 -28
  33. package/src/server/client-build-live.js +14 -5
  34. package/src/server/client-dev-server.js +21 -8
  35. package/src/server/conf.js +78 -25
  36. package/src/server/peer.js +2 -2
  37. package/src/server/runtime.js +0 -5
  38. package/src/server/start.js +39 -0
  39. package/src/ws/IoInterface.js +132 -39
  40. package/src/ws/IoServer.js +79 -31
  41. package/src/ws/core/core.ws.connection.js +50 -16
  42. package/src/ws/core/core.ws.emit.js +47 -8
  43. package/src/ws/core/core.ws.server.js +62 -10
@@ -1,152 +1,70 @@
1
1
  import mongoose from 'mongoose';
2
2
  import { loggerFactory } from '../../server/logger.js';
3
3
  import { getCapVariableName } from '../../client/components/core/CommonJs.js';
4
- import { shellCd, shellExec } from '../../server/process.js';
4
+
5
+ /**
6
+ * Module for connecting to and loading models for a MongoDB database using Mongoose.
7
+ * @module src/db/MongooseDB.js
8
+ * @namespace MongooseDBNamespace
9
+ */
5
10
 
6
11
  const logger = loggerFactory(import.meta);
7
12
 
8
- const MongooseDB = {
9
- connect: async (host, name) => {
13
+ /**
14
+ * @class
15
+ * @alias MongooseDBService
16
+ * @memberof MongooseDBNamespace
17
+ * @classdesc Manages the Mongoose connection lifecycle and dynamic loading of database models
18
+ * based on API configuration.
19
+ */
20
+ class MongooseDBService {
21
+ /**
22
+ * Establishes a Mongoose connection to the specified MongoDB instance.
23
+ *
24
+ * @async
25
+ * @param {string} host - The MongoDB host (e.g., 'mongodb://localhost:27017').
26
+ * @param {string} name - The database name.
27
+ * @returns {Promise<mongoose.Connection>} A promise that resolves to the established Mongoose connection object.
28
+ */
29
+ async connect(host, name) {
10
30
  const uri = `${host}/${name}`;
11
- // logger.info('MongooseDB connect', { host, name, uri });
31
+ logger.info('MongooseDB connect', { host, name, uri });
12
32
  return await mongoose
13
33
  .createConnection(uri, {
14
- // useNewUrlParser: true,
15
- // useUnifiedTopology: true,
34
+ // Options like useNewUrlParser and useUnifiedTopology are often set here.
16
35
  })
17
36
  .asPromise();
18
- return new Promise((resolve, reject) =>
19
- mongoose
20
- .connect(
21
- uri,
22
- // ,{
23
- // useNewUrlParser: true,
24
- // useUnifiedTopology: true,
25
- // }
26
- )
27
- .then((db) => {
28
- logger.info(`db connected`, uri);
29
- return resolve(db);
30
- })
31
- .catch((err) => {
32
- logger.error(err, { host, name, error: err.stack });
33
- // return reject(err);
34
- return resolve(undefined);
35
- }),
36
- );
37
- },
38
- loadModels: async function (options = { apis: ['test'], conn: new mongoose.Connection() }) {
37
+ }
38
+
39
+ /**
40
+ * Dynamically loads Mongoose models for a list of APIs and binds them to the given connection.
41
+ *
42
+ * @async
43
+ * @param {object} [options] - Options for model loading.
44
+ * @param {Array<string>} [options.apis=['test']] - List of API names (folders) to load models from.
45
+ * @param {mongoose.Connection} [options.conn=new mongoose.Connection()] - The active Mongoose connection.
46
+ * @returns {Promise<object>} A promise that resolves to an object map of loaded Mongoose models.
47
+ */
48
+ async loadModels(options = { apis: ['test'], conn: new mongoose.Connection() }) {
39
49
  const { conn, apis } = options;
40
50
  const models = {};
41
51
  for (const api of apis) {
52
+ // Dynamic import of the model file
42
53
  const { ProviderSchema } = await import(`../../api/${api}/${api}.model.js`);
43
- const keyModel = getCapVariableName(api);
54
+ const keyModel = getCapVariableName(api); // Assuming this returns a capitalized model name
44
55
  models[keyModel] = conn.model(keyModel, ProviderSchema);
45
56
  }
46
57
 
47
58
  return models;
48
- },
49
- server: async function () {
50
- logger.info('platform', process.platform);
51
- switch (process.platform) {
52
- case 'win32':
53
- {
54
- // https://www.mongodb.com/docs/v7.0/tutorial/install-mongodb-on-windows-unattended/
55
-
56
- // C:\Program Files\MongoDB\Tools\100\bin
57
-
58
- const urlDownload = `https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-7.0.14-signed.msi`;
59
- const folderPath = `./engine-private/setup`;
60
- if (!fs.existsSync(folderPath)) fs.mkdirSync(folderPath, { recursive: true });
61
- const fullPath = `${folderPath}/${urlDownload.split('/').pop()}`;
62
- logger.info('destination', fullPath);
63
- shellCd(folderPath);
64
- }
65
- break;
66
- case 'linux':
67
- {
68
- if (!process.argv.includes('server')) {
69
- logger.info('remove');
70
- shellExec(`sudo apt-get purge mongodb-org*`);
71
- shellExec(`sudo rm -r /var/log/mongodb`);
72
- shellExec(`sudo rm -r /var/lib/mongodb`);
73
- // restore lib
74
- // shellExec(`sudo chown -R mongodb:mongodb /var/lib/mongodb/*`);
75
- // mongod --repair
76
-
77
- if (process.argv.includes('legacy')) {
78
- // TODO:
79
- if (process.argv.includes('rocky')) {
80
- // https://github.com/mongodb/mongodb-selinux
81
- // https://www.mongodb.com/docs/v7.0/tutorial/install-mongodb-enterprise-on-red-hat/
82
- // https://www.mongodb.com/docs/v6.0/tutorial/install-mongodb-on-red-hat/
83
- // https://www.mongodb.com/docs/v4.4/tutorial/install-mongodb-on-red-hat/
84
- // dnf install selinux-policy-devel
85
- // git clone https://github.com/mongodb/mongodb-selinux
86
- // cd mongodb-selinux
87
- // make
88
- // sudo make install
89
- // yum list installed | grep mongo
90
- // sudo yum erase $(rpm -qa | grep mongodb)
91
- // remove service
92
- // sudo systemctl reset-failed
93
- // MongoDB 5.0+ requires a CPU with AVX support
94
- // check: grep avx /proc/cpuinfo
95
- }
96
- logger.info('install legacy 4.4');
97
- shellExec(`wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -`);
98
-
99
- shellExec(
100
- `echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list`,
101
- );
102
-
103
- shellExec(`sudo apt-get update`);
104
-
105
- shellExec(
106
- `sudo apt-get install mongodb-org=4.4.8 mongodb-org-server=4.4.8 mongodb-org-shell=4.4.8 mongodb-org-mongos=4.4.8 mongodb-org-tools=4.4.8`,
107
- );
108
- } else {
109
- logger.info('install 7.0');
110
- shellExec(`curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
111
- sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg \
112
- --dearmor`);
113
- shellExec(
114
- `echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list`,
115
- );
116
-
117
- shellExec(`sudo apt-get update`);
118
-
119
- shellExec(`sudo apt-get install -y mongodb-org`);
120
- }
121
- }
122
- logger.info('clean server environment');
123
- shellExec(`sudo service mongod stop`);
124
- shellExec(`sudo systemctl unmask mongod`);
125
- shellExec(`sudo pkill -f mongod`);
126
- shellExec(`sudo systemctl enable mongod.service`);
127
-
128
- shellExec(`sudo chown -R mongodb:mongodb /var/lib/mongodb`);
129
- shellExec(`sudo chown mongodb:mongodb /tmp/mongodb-27017.sock`);
130
-
131
- shellExec(`sudo chown -R mongod:mongod /var/lib/mongodb`);
132
- shellExec(`sudo chown mongod:mongod /tmp/mongodb-27017.sock`);
133
-
134
- logger.info('run server');
135
- shellExec(`sudo service mongod restart`);
136
-
137
- const checkStatus = () => {
138
- logger.info('check status');
139
- shellExec(`sudo systemctl status mongod`);
140
- shellExec(`sudo systemctl --type=service | grep mongod`);
141
- };
142
-
143
- checkStatus();
144
- }
145
- break;
146
- default:
147
- break;
148
- }
149
- },
150
- };
151
-
152
- export { MongooseDB };
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Singleton instance of the MongooseDBService class for backward compatibility.
64
+ * @alias MongooseDB
65
+ * @memberof MongooseDBNamespace
66
+ * @type {MongooseDBService}
67
+ */
68
+ const MongooseDB = new MongooseDBService();
69
+
70
+ export { MongooseDB, MongooseDBService as MongooseDBClass };
package/src/index.js CHANGED
@@ -35,7 +35,7 @@ class Underpost {
35
35
  * @type {String}
36
36
  * @memberof Underpost
37
37
  */
38
- static version = 'v2.8.884';
38
+ static version = 'v2.8.885';
39
39
  /**
40
40
  * Repository cli API
41
41
  * @static
@@ -1,7 +1,31 @@
1
1
  import { ssrFactory } from '../server/ssr.js';
2
2
 
3
- const EmailRender = {
4
- style: {
3
+ /**
4
+ * Module for handling the rendering and styling of HTML emails using SSR components.
5
+ * @module src/mailer/EmailRender.js
6
+ * @namespace EmailRenderNamespace
7
+ */
8
+
9
+ /**
10
+ * @class
11
+ * @alias EmailRenderService
12
+ * @memberof EmailRenderNamespace
13
+ * @classdesc Utility class for managing CSS styles and rendering email templates using
14
+ * Server-Side Rendering (SSR) components.
15
+ */
16
+ class EmailRenderService {
17
+ /**
18
+ * Defines the base CSS styles for different elements within the email template.
19
+ * Keys are CSS selectors (or class names), and values are objects of CSS properties.
20
+ * @type {object.<string, object.<string, string>>}
21
+ * @property {object} body - Styles for the main email body wrapper.
22
+ * @property {object} .container - Styles for the main content container.
23
+ * @property {object} h1 - Styles for primary headings.
24
+ * @property {object} p - Styles for standard paragraphs.
25
+ * @property {object} button - Styles for call-to-action buttons.
26
+ * @property {object} .footer - Styles for the email footer.
27
+ */
28
+ style = {
5
29
  body: {
6
30
  'font-family': 'Arial, sans-serif',
7
31
  'background-color': '#f4f4f4',
@@ -46,22 +70,47 @@ const EmailRender = {
46
70
  'font-size': '14px',
47
71
  color: '#999999',
48
72
  },
49
- },
50
- renderStyle: function (classObj) {
73
+ };
74
+
75
+ /**
76
+ * Converts a style object defined in the `this.style` property into a CSS style string.
77
+ *
78
+ * @param {string} classObj - The key corresponding to a style object in `this.style`.
79
+ * @returns {string} A string containing inline CSS properties (e.g., ` property: value;`).
80
+ */
81
+ renderStyle(classObj) {
82
+ if (!this.style[classObj]) return '';
51
83
  return Object.keys(this.style[classObj])
52
84
  .map((classKey) => ` ${classKey}: ${this.style[classObj][classKey]};`)
53
85
  .join(``);
54
- },
86
+ }
55
87
 
56
- getTemplates: async function (options = { templates: {} }) {
88
+ /**
89
+ * Loads and renders email templates using the SSR factory.
90
+ *
91
+ * @async
92
+ * @param {object} [options] - Options containing the template names.
93
+ * @param {object.<string, string>} [options.templates={}] - Map of template keys to their SSR component file names.
94
+ * @returns {Promise<object.<string, string>>} A promise that resolves to an object map of rendered HTML email strings.
95
+ */
96
+ async getTemplates(options = { templates: {} }) {
57
97
  const templates = {};
58
98
  for (const templateKey of Object.keys(options.templates)) {
59
99
  const ssrEmailComponent = options.templates[templateKey];
100
+ // Note: ssrFactory is assumed to load and return a functional component/function
60
101
  const SrrComponent = await ssrFactory(`./src/client/ssr/mailer/${ssrEmailComponent}.js`);
61
102
  templates[templateKey] = SrrComponent(this, options);
62
103
  }
63
104
  return templates;
64
- },
65
- };
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Singleton instance of the EmailRenderService class for backward compatibility.
110
+ * @alias EmailRender
111
+ * @memberof EmailRenderNamespace
112
+ * @type {EmailRenderService}
113
+ */
114
+ const EmailRender = new EmailRenderService();
66
115
 
67
- export { EmailRender };
116
+ export { EmailRender, EmailRenderService as EmailRenderClass };
@@ -2,11 +2,66 @@ import nodemailer from 'nodemailer';
2
2
  import { loggerFactory } from '../server/logger.js';
3
3
  import { EmailRender } from './EmailRender.js';
4
4
 
5
+ /**
6
+ * Module for configuring and sending emails using Nodemailer.
7
+ * @module src/mailer/MailerProvider.js
8
+ * @namespace MailerProviderNamespace
9
+ */
10
+
5
11
  const logger = loggerFactory(import.meta);
6
12
 
7
- const MailerProvider = {
8
- instance: {},
9
- load: async function (
13
+ /**
14
+ * @typedef {object} MailerOptions
15
+ * @property {string} id - Unique identifier for the mailer configuration.
16
+ * @property {string} [meta='mailer'] - Meta identifier for logging/context.
17
+ * @property {object} sender - The default sender details.
18
+ * @property {string} sender.email - The default sender email address.
19
+ * @property {string} sender.name - The default sender name.
20
+ * @property {object} transport - Nodemailer transport configuration.
21
+ * @property {string} transport.host - SMTP host.
22
+ * @property {number} [transport.port=587] - SMTP port.
23
+ * @property {boolean} [transport.secure=false] - Use TLS (true for 465, false for other ports).
24
+ * @property {object} transport.auth - Authentication details.
25
+ * @property {string} transport.auth.user - Username.
26
+ * @property {string} transport.auth.pass - Password.
27
+ * @property {string} [host=''] - Application host for context.
28
+ * @property {string} [path=''] - Application path for context.
29
+ * @property {object.<string, string>} templates - Map of template keys to SSR component file names.
30
+ */
31
+
32
+ /**
33
+ * @class
34
+ * @alias MailerProviderService
35
+ * @memberof MailerProviderNamespace
36
+ * @classdesc Manages multiple Nodemailer transporter instances and handles loading of
37
+ * email templates and sending emails.
38
+ */
39
+ class MailerProviderService {
40
+ /**
41
+ * Internal storage for mailer instances (transporters, options, templates), keyed by ID.
42
+ * @type {object.<string, object>}
43
+ * @private
44
+ */
45
+ #instance = {};
46
+
47
+ /**
48
+ * Retrieves the internal instance storage for direct access (used for backward compatibility).
49
+ * @returns {object.<string, object>} The internal mailer instance map.
50
+ */
51
+ get instance() {
52
+ return this.#instance;
53
+ }
54
+
55
+ /**
56
+ * Loads and initializes a new mailer provider instance using Nodemailer.
57
+ * The created instance is stored internally and includes the transporter and rendered templates.
58
+ *
59
+ * @async
60
+ * @param {MailerOptions} [options] - Configuration options for the mailer instance.
61
+ * @returns {Promise<object|undefined>} A promise that resolves to the initialized mailer instance
62
+ * object, or `undefined` on error.
63
+ */
64
+ async load(
10
65
  options = {
11
66
  id: '',
12
67
  meta: 'mailer',
@@ -33,18 +88,13 @@ const MailerProvider = {
33
88
  ) {
34
89
  try {
35
90
  options.transport.tls = {
36
- rejectUnauthorized: false,
91
+ rejectUnauthorized: false, // allows self-signed certs for local/dev
37
92
  };
38
93
  const { id } = options;
39
- // Generate test SMTP service account from ethereal.email
40
- // Only needed if you don't have a real mail account for testing
41
- // let testAccount = await nodemailer.createTestAccount();
42
94
 
43
- // create reusable transporter object using the default SMTP transport
44
95
  const transporter = nodemailer.createTransport(options.transport);
45
96
 
46
- // console.log('load logger', { url: options.meta });
47
- this.instance[id] = {
97
+ this.#instance[id] = {
48
98
  ...options,
49
99
  transporter,
50
100
  templates: await EmailRender.getTemplates(options),
@@ -87,13 +137,28 @@ const MailerProvider = {
87
137
  },
88
138
  };
89
139
 
90
- return this.instance[id];
140
+ return this.#instance[id];
91
141
  } catch (error) {
92
142
  logger.error(error, error.stack);
93
143
  return undefined;
94
144
  }
95
- },
96
- send: async function (
145
+ }
146
+
147
+ /**
148
+ * Sends an email using a previously loaded transporter instance.
149
+ *
150
+ * @async
151
+ * @param {object} [options] - Options for sending the email.
152
+ * @param {string} options.id - The ID of the mailer instance/transporter to use.
153
+ * @param {object} options.sendOptions - Nodemailer mail options.
154
+ * @param {string} [options.sendOptions.from] - Sender address (defaults to loaded instance sender).
155
+ * @param {string} options.sendOptions.to - List of receivers (comma-separated).
156
+ * @param {string} options.sendOptions.subject - Subject line.
157
+ * @param {string} [options.sendOptions.text] - Plain text body.
158
+ * @param {string} [options.sendOptions.html] - HTML body.
159
+ * @returns {Promise<object|undefined>} A promise that resolves to the Nodemailer `info` object, or `undefined` on error.
160
+ */
161
+ async send(
97
162
  options = {
98
163
  id: '',
99
164
  sendOptions: {
@@ -114,26 +179,34 @@ const MailerProvider = {
114
179
  ) {
115
180
  try {
116
181
  const { id, sendOptions } = options;
117
- if (!sendOptions.from) sendOptions.from = `${this.instance[id].sender.name} <${this.instance[id].sender.email}>`;
182
+ const instance = this.#instance[id];
118
183
 
119
- // send mail with defined transport object
120
- const info = await this.instance[id].transporter.sendMail(sendOptions);
184
+ if (!instance) {
185
+ logger.error(`Mailer instance with ID '${id}' not loaded.`);
186
+ return undefined;
187
+ }
121
188
 
122
- // console.log('Message sent: %s', info.messageId);
123
- // logger.info('Message sent', info);
189
+ if (!sendOptions.from) sendOptions.from = `${instance.sender.name} <${instance.sender.email}>`;
124
190
 
125
- // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>
191
+ // send mail with defined transport object
192
+ const info = await instance.transporter.sendMail(sendOptions);
126
193
 
127
- // Preview only available when sending through an Ethereal account
128
- // console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
129
- // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
194
+ // logger.info('Message sent', info);
130
195
 
131
196
  return info;
132
197
  } catch (error) {
133
198
  logger.error(error, error.stack);
134
199
  return undefined;
135
200
  }
136
- },
137
- };
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Singleton instance of the MailerProviderService class for backward compatibility.
206
+ * @alias MailerProvider
207
+ * @memberof MailerProviderNamespace
208
+ * @type {MailerProviderService}
209
+ */
210
+ const MailerProvider = new MailerProviderService();
138
211
 
139
- export { MailerProvider };
212
+ export { MailerProvider, MailerProviderService as MailerProviderClass };
@@ -50,7 +50,6 @@ class ExpressService {
50
50
  * @param {boolean} [config.peer] - Whether to enable the peer server.
51
51
  * @param {object} [config.valkey] - Valkey connection configuration.
52
52
  * @param {string} [config.apiBaseHost] - Base host for the API (if running separate API).
53
- * @param {number} [config.devApiPort] - The dynamically calculated development API port used for CORS in dev mode.
54
53
  * @param {string} config.redirectTarget - The full target URL for redirection (used if `redirect` is true).
55
54
  * @param {string} config.rootHostPath - The root path for public host assets (e.g., `/public/hostname`).
56
55
  * @param {object} config.confSSR - The SSR configuration object, used to look up Mailer templates.
@@ -73,7 +72,6 @@ class ExpressService {
73
72
  peer,
74
73
  valkey,
75
74
  apiBaseHost,
76
- devApiPort, // New parameter for dev environment CORS
77
75
  redirectTarget,
78
76
  rootHostPath,
79
77
  confSSR,
@@ -131,35 +129,6 @@ class ExpressService {
131
129
  // Static file serving
132
130
  app.use('/', express.static(directory ? directory : `.${rootHostPath}`));
133
131
 
134
- // Swagger path definition
135
- const swaggerJsonPath = `./public/${host}${path === '/' ? path : `${path}/`}swagger-output.json`;
136
- const swaggerPath = `${path === '/' ? `/api-docs` : `${path}/api-docs`}`;
137
-
138
- // Flag swagger requests before security middleware
139
- if (fs.existsSync(swaggerJsonPath)) {
140
- app.use(swaggerPath, (req, res, next) => {
141
- res.locals.isSwagger = true;
142
- next();
143
- });
144
- }
145
-
146
- // Security and CORS
147
- applySecurity(app, {
148
- origin: (origin, callback) => {
149
- // Use devApiPort if provided to calculate the allowed development CORS origin
150
- const devOrigin =
151
- apis && process.env.NODE_ENV === 'development' && devApiPort ? [`http://localhost:${devApiPort}`] : [];
152
-
153
- const allowedOrigins = origins.concat(devOrigin);
154
-
155
- if (!origin || allowedOrigins.includes(origin)) {
156
- callback(null, true);
157
- } else {
158
- callback(new Error('Not allowed by CORS'));
159
- }
160
- },
161
- });
162
-
163
132
  // Handle redirection-only instances
164
133
  if (redirect) {
165
134
  app.use((req, res, next) => {
@@ -174,9 +143,20 @@ class ExpressService {
174
143
 
175
144
  // Create HTTP server for regular instances (required for WebSockets)
176
145
  const server = createServer({}, app);
177
- if (peer) portsUsed++; // Peer server uses one additional port
178
146
 
179
147
  if (!apiBaseHost) {
148
+ // Swagger path definition
149
+ const swaggerJsonPath = `./public/${host}${path === '/' ? path : `${path}/`}swagger-output.json`;
150
+ const swaggerPath = `${path === '/' ? `/api-docs` : `${path}/api-docs`}`;
151
+
152
+ // Flag swagger requests before security middleware
153
+ if (fs.existsSync(swaggerJsonPath)) {
154
+ app.use(swaggerPath, (req, res, next) => {
155
+ res.locals.isSwagger = true;
156
+ next();
157
+ });
158
+ }
159
+
180
160
  // Swagger UI setup
181
161
  if (fs.existsSync(swaggerJsonPath)) {
182
162
  const swaggerDoc = JSON.parse(fs.readFileSync(swaggerJsonPath, 'utf8'));
@@ -184,6 +164,11 @@ class ExpressService {
184
164
  app.use(swaggerPath, swaggerUi.serve, swaggerUi.setup(swaggerDoc));
185
165
  }
186
166
 
167
+ // Security and CORS
168
+ applySecurity(app, {
169
+ origin: origins,
170
+ });
171
+
187
172
  // Database and Valkey connections
188
173
  if (db && apis) await DataBaseProvider.load({ apis, host, path, db });
189
174
  if (valkey) await createValkeyConnection({ host, path }, valkey);
@@ -216,10 +201,10 @@ class ExpressService {
216
201
  // WebSocket server setup
217
202
  if (ws) {
218
203
  const { createIoServer } = await import(`../../ws/${ws}/${ws}.ws.server.js`);
219
- const { options, meta } = await createIoServer(server, { host, path, db, port, origins });
204
+ const { options, meta, ioServer } = await createIoServer(server, { host, path, db, port, origins });
220
205
 
221
206
  // Listen on the main port for the WS server
222
- await UnderpostStartUp.API.listenPortController(UnderpostStartUp.API.listenServerFactory(), port, {
207
+ await UnderpostStartUp.API.listenPortController(ioServer, port, {
223
208
  runtime: 'nodejs',
224
209
  client: null,
225
210
  host,
@@ -230,6 +215,7 @@ class ExpressService {
230
215
 
231
216
  // Peer server setup
232
217
  if (peer) {
218
+ portsUsed++; // Peer server uses one additional port
233
219
  const peerPort = newInstance(port + portsUsed); // portsUsed is 1 here
234
220
  const { options, meta, peerServer } = await createPeerServer({
235
221
  port: peerPort,
@@ -325,33 +325,13 @@ const validatePasswordMiddleware = (req) => {
325
325
  /**
326
326
  * Creates cookie options for the refresh token.
327
327
  * @param {import('express').Request} req The Express request object.
328
+ * @param {string} host The host name.
328
329
  * @returns {object} Cookie options.
329
330
  * @memberof Auth
330
331
  */
331
- const cookieOptionsFactory = (req) => {
332
+ const cookieOptionsFactory = (req, host) => {
332
333
  const isProduction = process.env.NODE_ENV === 'production';
333
334
 
334
- // Determine hostname safely:
335
- // Prefer origin header if present (it contains protocol + host)
336
- let candidateHost = undefined;
337
- try {
338
- if (req.headers && req.headers.origin) {
339
- candidateHost = new URL(req.headers.origin).hostname;
340
- }
341
- } catch (e) {
342
- /* ignore parse error */
343
- logger.error(e);
344
- }
345
-
346
- // fallback to req.hostname (Express sets this; ensure trust proxy if behind proxy)
347
- if (!candidateHost) candidateHost = (req.hostname || '').split(':')[0];
348
-
349
- candidateHost = (candidateHost || '').trim().replace(/^www\./i, '');
350
-
351
- // Do not set domain for localhost, 127.x.x.x, or plain IPs
352
- const isIpOrLocal = /^(localhost|127(?:\.\d+){0,2}\.\d+|\[::1\]|\d+\.\d+\.\d+\.\d+)$/i.test(candidateHost);
353
- const domain = isProduction && candidateHost && !isIpOrLocal ? `.${candidateHost}` : undefined;
354
-
355
335
  // Determine if request is secure: respect X-Forwarded-Proto when behind proxy
356
336
  const forwardedProto = (req.headers && req.headers['x-forwarded-proto']) || '';
357
337
  const reqIsSecure = Boolean(req.secure || forwardedProto.split(',')[0] === 'https');
@@ -361,17 +341,16 @@ const cookieOptionsFactory = (req) => {
361
341
  const sameSite = secure ? 'None' : 'Lax';
362
342
 
363
343
  // Safe parse of maxAge minutes
364
- const minutes = Number.parseInt(process.env.ACCESS_EXPIRE_MINUTES, 10);
365
- const maxAge = Number.isFinite(minutes) && minutes > 0 ? minutes * 60 * 1000 : undefined;
344
+ const maxAge = parseInt(process.env.ACCESS_EXPIRE_MINUTES) * 60 * 1000;
366
345
 
367
346
  const opts = {
368
347
  httpOnly: true,
369
348
  secure,
370
349
  sameSite,
371
350
  path: '/',
351
+ domain: process.env.NODE_ENV === 'production' ? host : 'localhost',
352
+ maxAge,
372
353
  };
373
- if (typeof maxAge !== 'undefined') opts.maxAge = maxAge;
374
- if (domain) opts.domain = domain;
375
354
 
376
355
  return opts;
377
356
  };
@@ -409,7 +388,7 @@ async function createSessionAndUserToken(user, User, req, res, options = { host:
409
388
  const jwtid = session._id.toString();
410
389
 
411
390
  // Secure cookie settings
412
- res.cookie('refreshToken', refreshToken, cookieOptionsFactory(req));
391
+ res.cookie('refreshToken', refreshToken, cookieOptionsFactory(req, options.host));
413
392
 
414
393
  return { jwtid };
415
394
  }
@@ -512,6 +491,7 @@ async function refreshSessionAndToken(req, res, User, options = { host: '', path
512
491
 
513
492
  if (!user) {
514
493
  // Possible token reuse: look up user by some other signals? If not possible, log and throw.
494
+ // TODO: on cors requests, this will throw an error, because the cookie is not sent.
515
495
  logger.warn('Refresh token reuse or invalid token detected');
516
496
  // Optional: revoke by clearing cookie and returning unauthorized
517
497
  res.clearCookie('refreshToken', { path: '/' });
@@ -543,7 +523,7 @@ async function refreshSessionAndToken(req, res, User, options = { host: '', path
543
523
 
544
524
  logger.warn('Refreshed session for user ' + user.email);
545
525
 
546
- res.cookie('refreshToken', refreshToken, cookieOptionsFactory(req));
526
+ res.cookie('refreshToken', refreshToken, cookieOptionsFactory(req, options.host));
547
527
 
548
528
  return jwtSign(
549
529
  UserDto.auth.payload(user, session._id.toString(), req.ip, req.headers['user-agent'], options.host, options.path),
@@ -663,6 +643,7 @@ function applySecurity(app, opts = {}) {
663
643
  maxAge: 600,
664
644
  }),
665
645
  );
646
+ logger.info('Cors origin', origin);
666
647
 
667
648
  // Rate limiting + slow down
668
649
  const limiter = rateLimit({