webspresso 0.0.89 → 0.0.91

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 (102) hide show
  1. package/README.md +450 -53
  2. package/bin/commands/service.js +193 -0
  3. package/bin/webspresso.js +2 -0
  4. package/core/auth/manager.js +36 -26
  5. package/core/auth/middleware.js +21 -2
  6. package/core/compression/compressible.js +51 -0
  7. package/core/compression/compression-stream.js +59 -0
  8. package/core/compression/index.js +25 -0
  9. package/core/compression/middleware.js +301 -0
  10. package/core/compression/negotiate.js +153 -0
  11. package/core/errors/base.js +31 -0
  12. package/core/errors/domain.js +193 -0
  13. package/core/errors/http.js +133 -0
  14. package/core/errors/index.js +77 -0
  15. package/core/errors/middleware.js +162 -0
  16. package/core/errors/normalize.js +171 -0
  17. package/core/orm/complexity.js +120 -0
  18. package/core/orm/events.js +64 -14
  19. package/core/orm/index.js +45 -10
  20. package/core/orm/model.js +10 -2
  21. package/core/orm/query-builder.js +30 -4
  22. package/core/orm/repository.js +57 -25
  23. package/core/orm/scopes.js +2 -1
  24. package/core/orm/transaction.js +39 -5
  25. package/core/orm/utils.js +6 -3
  26. package/core/queue/adapters/database.js +284 -0
  27. package/core/queue/adapters/memory.js +155 -0
  28. package/core/queue/adapters/redis.js +336 -0
  29. package/core/queue/index.js +21 -0
  30. package/core/queue/job.js +103 -0
  31. package/core/queue/manager.js +387 -0
  32. package/core/realtime/adapters/redis.js +431 -0
  33. package/core/realtime/adapters/socket-io.js +203 -0
  34. package/core/realtime/adapters/sse.js +210 -0
  35. package/core/realtime/adapters/websocket.js +337 -0
  36. package/core/realtime/auth-manager.js +140 -0
  37. package/core/realtime/core.js +359 -0
  38. package/core/realtime/emitter.js +98 -0
  39. package/core/realtime/errors.js +71 -0
  40. package/core/realtime/index.js +79 -0
  41. package/core/realtime/reconnect-manager.js +118 -0
  42. package/core/realtime/registry.js +243 -0
  43. package/core/shutdown/http-adapter.js +134 -0
  44. package/core/shutdown/index.js +12 -0
  45. package/core/shutdown/shutdown-manager.js +312 -0
  46. package/core/ssr/index.js +13 -0
  47. package/core/ssr/stream.js +174 -0
  48. package/index.d.ts +829 -52
  49. package/index.js +103 -0
  50. package/package.json +22 -2
  51. package/plugins/admin-panel/api.js +37 -4
  52. package/plugins/admin-panel/app.js +67 -17
  53. package/plugins/admin-panel/client/parts/01-state-api-breadcrumb.js +4 -1
  54. package/plugins/admin-panel/client/parts/03-pagination-intro.js +25 -18
  55. package/plugins/admin-panel/client/parts/04-field-renderers.js +102 -58
  56. package/plugins/admin-panel/client/parts/05-rich-text-file-helpers.js +37 -23
  57. package/plugins/admin-panel/client/parts/08-record-list.js +27 -34
  58. package/plugins/admin-panel/client/parts/09-record-form.js +168 -19
  59. package/plugins/admin-panel/core/admin-module.js +2 -2
  60. package/plugins/admin-panel/core/api-extensions.js +149 -0
  61. package/plugins/admin-panel/field-renderers/rich-text.js +3 -2
  62. package/plugins/admin-panel/index.js +131 -18
  63. package/plugins/admin-panel/modules/admin-users.js +770 -0
  64. package/plugins/admin-panel/modules/custom-pages.js +144 -45
  65. package/plugins/admin-panel/modules/menu.js +85 -0
  66. package/plugins/admin-panel/modules/user-management.js +5 -2
  67. package/plugins/admin-panel/vendor/mithril.min.js +1 -0
  68. package/plugins/admin-panel/vendor/quill.min.js +7 -0
  69. package/plugins/admin-panel/vendor/quill.snow.min.css +945 -0
  70. package/plugins/admin-panel/vendor/tailwind.min.js +65 -0
  71. package/plugins/basic-auth/index.js +293 -0
  72. package/plugins/content/client/inline-edit.js +41 -17
  73. package/plugins/cors.js +12 -8
  74. package/plugins/csrf/index.js +8 -8
  75. package/plugins/data-exchange/export-xlsx.js +5 -1
  76. package/plugins/data-exchange/import.js +16 -2
  77. package/plugins/data-exchange/index.js +14 -0
  78. package/plugins/email/index.js +14 -1
  79. package/plugins/index.js +29 -0
  80. package/plugins/queue/index.js +108 -0
  81. package/plugins/realtime/index.js +150 -0
  82. package/plugins/recaptcha/index.js +11 -0
  83. package/plugins/redirect/index.js +9 -1
  84. package/plugins/rest-resources/index.js +280 -11
  85. package/plugins/upload/index.js +16 -0
  86. package/src/app-context.js +46 -6
  87. package/src/file-router.js +220 -28
  88. package/src/helpers.js +24 -5
  89. package/src/plugin-manager.js +134 -7
  90. package/src/server.js +470 -44
  91. package/src/services/builtins/auth.js +273 -0
  92. package/src/services/builtins/exchange.js +229 -0
  93. package/src/services/builtins/mail.js +134 -0
  94. package/src/services/builtins/media.js +196 -0
  95. package/src/services/builtins/system.js +221 -0
  96. package/src/services/discovery.js +140 -0
  97. package/src/services/executor.js +292 -0
  98. package/src/services/index.js +70 -0
  99. package/src/services/memoize.js +256 -0
  100. package/src/services/registry.js +288 -0
  101. package/src/services/validator.js +281 -0
  102. package/templates/skills/webspresso-usage/REFERENCE-framework.md +2 -2
@@ -0,0 +1,293 @@
1
+ /**
2
+ * Basic Auth Plugin — HTTP Basic Authentication (RFC 7617) for Webspresso
3
+ * Zero external dependencies (uses native Node.js crypto for timing-safe equality)
4
+ * @module plugins/basic-auth
5
+ */
6
+
7
+ const crypto = require('crypto');
8
+
9
+ /**
10
+ * Compare two strings in constant time to prevent timing attacks.
11
+ * Uses dummy buffer comparison if lengths differ to avoid leaking length via response timing.
12
+ *
13
+ * @param {string} a
14
+ * @param {string} b
15
+ * @returns {boolean}
16
+ */
17
+ function safeCompare(a, b) {
18
+ if (typeof a !== 'string' || typeof b !== 'string') {
19
+ return false;
20
+ }
21
+
22
+ const bufA = Buffer.from(a, 'utf8');
23
+ const bufB = Buffer.from(b, 'utf8');
24
+
25
+ if (bufA.length !== bufB.length) {
26
+ // Perform dummy timing-safe comparison with itself to preserve constant execution time
27
+ crypto.timingSafeEqual(bufA, bufA);
28
+ return false;
29
+ }
30
+
31
+ return crypto.timingSafeEqual(bufA, bufB);
32
+ }
33
+
34
+ /**
35
+ * Parse an HTTP Authorization header for Basic credentials.
36
+ *
37
+ * @param {string} header - e.g. "Basic dXNlcjpwYXNz"
38
+ * @returns {{ username: string, password: string } | null}
39
+ */
40
+ function parseBasicAuthHeader(header) {
41
+ if (!header || typeof header !== 'string') {
42
+ return null;
43
+ }
44
+
45
+ const parts = header.trim().split(/\s+/);
46
+ if (parts.length !== 2 || parts[0].toLowerCase() !== 'basic') {
47
+ return null;
48
+ }
49
+
50
+ try {
51
+ const decoded = Buffer.from(parts[1], 'base64').toString('utf8');
52
+ const colonIndex = decoded.indexOf(':');
53
+ if (colonIndex === -1) {
54
+ return null;
55
+ }
56
+
57
+ const username = decoded.slice(0, colonIndex);
58
+ const password = decoded.slice(colonIndex + 1);
59
+ return { username, password };
60
+ } catch {
61
+ return null;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Extract credentials from request Authorization header or proxy headers
67
+ *
68
+ * @param {import('express').Request} req
69
+ * @returns {{ username: string, password: string } | null}
70
+ */
71
+ function extractCredentials(req) {
72
+ const header = req.headers.authorization || req.headers.Authorization;
73
+ return parseBasicAuthHeader(header);
74
+ }
75
+
76
+ /**
77
+ * Check if request matches path prefix list
78
+ *
79
+ * @param {string} path
80
+ * @param {string|string[]|boolean} routes
81
+ * @returns {boolean}
82
+ */
83
+ function shouldApplyToRoute(path, routes) {
84
+ if (routes === true || routes == null) return true;
85
+ const list = Array.isArray(routes) ? routes : [routes];
86
+ return list.some((prefix) => path.startsWith(prefix));
87
+ }
88
+
89
+ /**
90
+ * Check if request path should be skipped
91
+ *
92
+ * @param {import('express').Request} req
93
+ * @param {string[]} skipPaths
94
+ * @param {Function} [skipFn]
95
+ * @returns {boolean}
96
+ */
97
+ function isSkipped(req, skipPaths = [], skipFn) {
98
+ if (typeof skipFn === 'function' && skipFn(req)) {
99
+ return true;
100
+ }
101
+ const p = req.path || req.url || '';
102
+ if (Array.isArray(skipPaths) && skipPaths.some((prefix) => p.startsWith(prefix))) {
103
+ return true;
104
+ }
105
+ return false;
106
+ }
107
+
108
+ /**
109
+ * Send 401 Unauthorized response with optional Basic challenge header
110
+ *
111
+ * @param {import('express').Request} req
112
+ * @param {import('express').Response} res
113
+ * @param {Object} config
114
+ */
115
+ function sendUnauthorized(req, res, config) {
116
+ res.statusCode = 401;
117
+
118
+ if (config.challenge !== false) {
119
+ const realm = String(config.realm || 'Restricted Area')
120
+ .split(/[\r\n]/)[0]
121
+ .replace(/"/g, '\\"');
122
+ res.setHeader('WWW-Authenticate', `Basic realm="${realm}"`);
123
+ }
124
+
125
+ if (typeof config.unauthorizedResponse === 'function') {
126
+ return config.unauthorizedResponse(req, res);
127
+ }
128
+
129
+ if (config.unauthorizedResponse && typeof config.unauthorizedResponse === 'object') {
130
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
131
+ return res.end(JSON.stringify(config.unauthorizedResponse));
132
+ }
133
+
134
+ if (typeof config.unauthorizedResponse === 'string') {
135
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
136
+ return res.end(config.unauthorizedResponse);
137
+ }
138
+
139
+ const acceptsJson = req.headers.accept && req.headers.accept.includes('application/json');
140
+ if (acceptsJson) {
141
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
142
+ return res.end(JSON.stringify({ error: 'Unauthorized', message: 'Authentication required.' }));
143
+ }
144
+
145
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
146
+ res.end('Unauthorized');
147
+ }
148
+
149
+ /**
150
+ * Create Basic Auth Express middleware
151
+ *
152
+ * @param {Object} [options]
153
+ * @param {Record<string, string>} [options.users] - Static username-password map
154
+ * @param {Function} [options.verify] - Custom verification function (username, password, req) => boolean | object | Promise<boolean | object>
155
+ * @param {string} [options.realm='Restricted Area'] - Realm name in WWW-Authenticate header
156
+ * @param {boolean} [options.challenge=true] - Whether to send WWW-Authenticate challenge header
157
+ * @param {string|string[]|boolean} [options.routes=true] - Route prefixes to protect (used in global mode)
158
+ * @param {string[]} [options.skipPaths] - Array of path prefixes to skip authentication
159
+ * @param {Function} [options.skip] - Custom predicate function (req) => boolean
160
+ * @param {Function|string|Object} [options.unauthorizedResponse] - Custom 401 response
161
+ * @param {Function} [options.onAuthenticated] - Callback hook (req, user) => void
162
+ * @returns {Function} Express middleware handler
163
+ */
164
+ function createBasicAuthMiddleware(options = {}) {
165
+ const config = {
166
+ realm: 'Restricted Area',
167
+ challenge: true,
168
+ routes: true,
169
+ skipPaths: [],
170
+ ...options,
171
+ };
172
+
173
+ return async (req, res, next) => {
174
+ const reqPath = req.path || req.url || '/';
175
+
176
+ if (!shouldApplyToRoute(reqPath, config.routes)) {
177
+ return next();
178
+ }
179
+
180
+ if (isSkipped(req, config.skipPaths, config.skip)) {
181
+ return next();
182
+ }
183
+
184
+ const credentials = extractCredentials(req);
185
+ if (!credentials) {
186
+ return sendUnauthorized(req, res, config);
187
+ }
188
+
189
+ const { username, password } = credentials;
190
+ let authResult = false;
191
+
192
+ if (typeof config.verify === 'function') {
193
+ try {
194
+ authResult = await config.verify(username, password, req);
195
+ } catch (err) {
196
+ return next(err);
197
+ }
198
+ } else if (config.users && typeof config.users === 'object') {
199
+ const expectedPassword = config.users[username];
200
+ if (typeof expectedPassword === 'string') {
201
+ authResult = safeCompare(password, expectedPassword);
202
+ }
203
+ }
204
+
205
+ if (!authResult) {
206
+ return sendUnauthorized(req, res, config);
207
+ }
208
+
209
+ // Attach authentication context to request
210
+ req.basicAuth = { username };
211
+ req.auth = req.auth || {};
212
+ const userObj = typeof authResult === 'object' && authResult !== null
213
+ ? authResult
214
+ : { username, type: 'basic' };
215
+
216
+ req.auth.user = userObj;
217
+ if (!req.user) {
218
+ req.user = userObj;
219
+ }
220
+
221
+ if (typeof config.onAuthenticated === 'function') {
222
+ try {
223
+ config.onAuthenticated(req, userObj);
224
+ } catch (err) {
225
+ return next(err);
226
+ }
227
+ }
228
+
229
+ next();
230
+ };
231
+ }
232
+
233
+ /**
234
+ * Webspresso Basic Auth Plugin Factory
235
+ *
236
+ * @param {Object} [options] - Plugin configuration options
237
+ * @param {boolean} [options.global=false] - Whether to apply basic auth as a global middleware on the app
238
+ * @param {Record<string, string>} [options.users] - Default static username-password dictionary
239
+ * @param {Function} [options.verify] - Default custom verification function
240
+ * @param {string} [options.realm='Restricted Area'] - Default realm name
241
+ * @param {boolean} [options.challenge=true] - Default challenge header flag
242
+ * @param {string|string[]|boolean} [options.routes=true] - Route prefixes (when global: true)
243
+ * @param {string[]} [options.skipPaths] - Default skip path prefixes
244
+ * @param {Function} [options.skip] - Default skip predicate function
245
+ * @param {Function|string|Object} [options.unauthorizedResponse] - Custom 401 response
246
+ * @param {Function} [options.onAuthenticated] - Callback hook on successful login
247
+ * @returns {Object} Webspresso Plugin Definition
248
+ */
249
+ function basicAuthPlugin(options = {}) {
250
+ const { global: applyGlobal = false, ...pluginDefaults } = options;
251
+
252
+ return {
253
+ name: 'basic-auth',
254
+ version: '1.0.0',
255
+ description: 'HTTP Basic Authentication (RFC 7617) plugin with named middleware and global guard',
256
+ options,
257
+
258
+ api: {
259
+ createMiddleware: (routeOpts = {}) =>
260
+ createBasicAuthMiddleware({ ...pluginDefaults, ...routeOpts }),
261
+ parseHeader: parseBasicAuthHeader,
262
+ safeCompare,
263
+ extractCredentials,
264
+ },
265
+
266
+ register(ctx) {
267
+ // Register named middleware factory for file routes: middleware: ['basicAuth'] or [['basicAuth', { ... }]]
268
+ if (ctx.middlewares) {
269
+ ctx.middlewares.basicAuth = (routeOpts = {}) =>
270
+ createBasicAuthMiddleware({ ...pluginDefaults, ...routeOpts });
271
+ }
272
+
273
+ // Mount global middleware if global: true
274
+ if (applyGlobal && ctx.app) {
275
+ const globalMw = createBasicAuthMiddleware(options);
276
+ ctx.app.use(globalMw);
277
+ }
278
+ },
279
+ };
280
+ }
281
+
282
+ basicAuthPlugin.basicAuthPlugin = basicAuthPlugin;
283
+ basicAuthPlugin.createBasicAuthMiddleware = createBasicAuthMiddleware;
284
+ basicAuthPlugin.parseBasicAuthHeader = parseBasicAuthHeader;
285
+ basicAuthPlugin.safeCompare = safeCompare;
286
+ basicAuthPlugin.extractCredentials = extractCredentials;
287
+
288
+ module.exports = basicAuthPlugin;
289
+ module.exports.basicAuthPlugin = basicAuthPlugin;
290
+ module.exports.createBasicAuthMiddleware = createBasicAuthMiddleware;
291
+ module.exports.parseBasicAuthHeader = parseBasicAuthHeader;
292
+ module.exports.safeCompare = safeCompare;
293
+ module.exports.extractCredentials = extractCredentials;
@@ -243,35 +243,59 @@
243
243
  });
244
244
  }
245
245
 
246
- function sanitizeClientHtml(htmlStr) {
247
- if (!htmlStr) return '';
246
+ function setSanitizedHtmlContent(el, htmlStr) {
247
+ if (!htmlStr) {
248
+ el.textContent = '';
249
+ return;
250
+ }
248
251
  try {
249
252
  var parser = new DOMParser();
250
253
  var doc = parser.parseFromString(htmlStr, 'text/html');
251
- var forbiddenTags = ['script', 'iframe', 'object', 'embed', 'applet', 'base'];
252
- forbiddenTags.forEach(function (tag) {
253
- var nodes = doc.querySelectorAll(tag);
254
- for (var i = 0; i < nodes.length; i++) {
255
- nodes[i].parentNode.removeChild(nodes[i]);
256
- }
257
- });
258
- var allNodes = doc.querySelectorAll('*');
259
- for (var i = 0; i < allNodes.length; i++) {
254
+ var allowedTags = {
255
+ p: 1, br: 1, b: 1, i: 1, strong: 1, em: 1, u: 1, s: 1, strike: 1,
256
+ h1: 1, h2: 1, h3: 1, h4: 1, h5: 1, h6: 1, ul: 1, ol: 1, li: 1,
257
+ blockquote: 1, pre: 1, code: 1, a: 1, span: 1, div: 1, hr: 1,
258
+ table: 1, thead: 1, tbody: 1, tr: 1, th: 1, td: 1, img: 1
259
+ };
260
+ var allowedAttrs = {
261
+ href: 1, title: 1, target: 1, rel: 1, class: 1, id: 1, src: 1, alt: 1, width: 1, height: 1
262
+ };
263
+ var allNodes = doc.body.querySelectorAll('*');
264
+ for (var i = allNodes.length - 1; i >= 0; i--) {
260
265
  var node = allNodes[i];
266
+ var tag = node.tagName.toLowerCase();
267
+ if (!allowedTags[tag]) {
268
+ if (node.parentNode) {
269
+ node.parentNode.removeChild(node);
270
+ } else {
271
+ node.remove();
272
+ }
273
+ continue;
274
+ }
261
275
  var attrs = Array.prototype.slice.call(node.attributes);
262
276
  for (var j = 0; j < attrs.length; j++) {
263
277
  var attrName = attrs[j].name.toLowerCase();
264
- var attrVal = attrs[j].value.toLowerCase().trim();
265
- if (attrName.indexOf('on') === 0) {
278
+ var attrVal = attrs[j].value.toLowerCase().replace(/[\x00-\x20\s]+/g, '').trim();
279
+ if (attrName.indexOf('on') === 0 || !allowedAttrs[attrName]) {
266
280
  node.removeAttribute(attrs[j].name);
267
- } else if ((attrName === 'href' || attrName === 'src') && attrVal.indexOf('javascript:') === 0) {
281
+ } else if ((attrName === 'href' || attrName === 'src' || attrName === 'action' || attrName === 'formaction' || attrName === 'xlink:href') &&
282
+ /^(?:javascript|data|vbscript):/i.test(attrVal)) {
268
283
  node.removeAttribute(attrs[j].name);
284
+ } else if (tag === 'a' && node.getAttribute('target') === '_blank') {
285
+ node.setAttribute('rel', 'noopener noreferrer');
269
286
  }
270
287
  }
271
288
  }
272
- return doc.body.innerHTML;
289
+
290
+ // Transfer DOM nodes directly to target element
291
+ while (el.firstChild) {
292
+ el.removeChild(el.firstChild);
293
+ }
294
+ while (doc.body.firstChild) {
295
+ el.appendChild(doc.body.firstChild);
296
+ }
273
297
  } catch (e) {
274
- return '';
298
+ el.textContent = htmlStr;
275
299
  }
276
300
  }
277
301
 
@@ -282,7 +306,7 @@
282
306
  var val = data[field];
283
307
  var isHtml = el.getAttribute('data-ws-content-html') === 'true';
284
308
  if (isHtml) {
285
- el.innerHTML = sanitizeClientHtml(val);
309
+ setSanitizedHtmlContent(el, val);
286
310
  } else {
287
311
  el.textContent = val != null ? val : '';
288
312
  }
package/plugins/cors.js CHANGED
@@ -47,9 +47,12 @@ function createCorsMiddleware(options = {}) {
47
47
 
48
48
  function isOriginAllowed(reqOrigin, callback) {
49
49
  if (!config.origin || config.origin === '*') {
50
- return callback(null, config.origin);
50
+ if (config.credentials) {
51
+ return callback(null, false);
52
+ }
53
+ return callback(null, '*');
51
54
  }
52
- if (!reqOrigin) {
55
+ if (!reqOrigin || reqOrigin === 'null') {
53
56
  return callback(null, false);
54
57
  }
55
58
  if (typeof config.origin === 'string') {
@@ -72,6 +75,9 @@ function createCorsMiddleware(options = {}) {
72
75
  if (typeof config.origin === 'function') {
73
76
  return config.origin(reqOrigin, callback);
74
77
  }
78
+ if (config.origin === true) {
79
+ return callback(null, reqOrigin);
80
+ }
75
81
  return callback(null, false);
76
82
  }
77
83
 
@@ -96,15 +102,13 @@ function createCorsMiddleware(options = {}) {
96
102
  }
97
103
 
98
104
  if (allowedOrigin) {
99
- if (allowedOrigin === '*' && config.credentials) {
100
- res.setHeader('Access-Control-Allow-Origin', reqOrigin || '*');
101
- } else {
102
- res.setHeader('Access-Control-Allow-Origin', allowedOrigin);
105
+ res.setHeader('Access-Control-Allow-Origin', allowedOrigin);
106
+ if (allowedOrigin !== '*') {
107
+ res.setHeader('Vary', 'Origin');
103
108
  }
104
- res.setHeader('Vary', 'Origin');
105
109
  }
106
110
 
107
- if (config.credentials) {
111
+ if (config.credentials && allowedOrigin && allowedOrigin !== '*') {
108
112
  res.setHeader('Access-Control-Allow-Credentials', 'true');
109
113
  }
110
114
 
@@ -158,11 +158,11 @@ function csrfPlugin(options = {}) {
158
158
  }
159
159
 
160
160
  // 1. Retrieve or generate secret token
161
- let secret;
161
+ let csrfTokenValue;
162
162
  if (useCookie) {
163
- secret = cookieOptions.signed ? req.signedCookies[cookieKey] : req.cookies[cookieKey];
164
- if (!secret) {
165
- secret = crypto.randomBytes(32).toString('hex');
163
+ csrfTokenValue = cookieOptions.signed ? req.signedCookies[cookieKey] : req.cookies[cookieKey];
164
+ if (!csrfTokenValue) {
165
+ csrfTokenValue = crypto.randomBytes(32).toString('hex');
166
166
  const isHttps = req.secure || req.headers?.['x-forwarded-proto'] === 'https' || process.env.NODE_ENV === 'production' || process.env.COOKIE_SECURE === 'true';
167
167
  const effectiveCookieOptions = {
168
168
  httpOnly: true,
@@ -170,18 +170,18 @@ function csrfPlugin(options = {}) {
170
170
  ...cookieOptions,
171
171
  secure: cookieOpts.secure !== undefined ? cookieOpts.secure : isHttps,
172
172
  };
173
- res.cookie(cookieKey, secret, effectiveCookieOptions);
173
+ res.cookie(cookieKey, csrfTokenValue, effectiveCookieOptions);
174
174
  }
175
175
  } else {
176
176
  // Session based
177
177
  if (!req.session[sessionKey]) {
178
178
  req.session[sessionKey] = crypto.randomBytes(32).toString('hex');
179
179
  }
180
- secret = req.session[sessionKey];
180
+ csrfTokenValue = req.session[sessionKey];
181
181
  }
182
182
 
183
183
  // Define standard req.csrfToken()
184
- req.csrfToken = () => secret;
184
+ req.csrfToken = () => csrfTokenValue;
185
185
 
186
186
  // 2. Perform CSRF verification for mutating HTTP methods
187
187
  const method = req.method ? req.method.toUpperCase() : 'GET';
@@ -196,7 +196,7 @@ function csrfPlugin(options = {}) {
196
196
  req.headers['x-xsrf-token']
197
197
  );
198
198
 
199
- if (!submitted || !safeCompare(submitted, secret)) {
199
+ if (!submitted || !safeCompare(submitted, csrfTokenValue)) {
200
200
  res.status(errorStatus);
201
201
  if (req.accepts('html') && !req.path.startsWith('/api')) {
202
202
  return res.send(`<h1>${errorStatus} Forbidden</h1><p>${errorMessage}</p>`);
@@ -15,7 +15,11 @@ const { resolveExportRecords } = require('./record-selection');
15
15
  async function buildXlsxBuffer(model, records) {
16
16
  const clean = sanitizeForOutput(records, model);
17
17
  const hiddenSet = new Set(model.hidden || []);
18
- const columns = Array.from(model.columns.keys()).filter((c) => !hiddenSet.has(c));
18
+ const columns = (model.columns && model.columns.size > 0)
19
+ ? Array.from(model.columns.keys()).filter((c) => !hiddenSet.has(c))
20
+ : (model.schema?.shape
21
+ ? Object.keys(model.schema.shape).filter((c) => !hiddenSet.has(c))
22
+ : Object.keys(clean[0] || {}));
19
23
 
20
24
  const wb = new ExcelJS.Workbook();
21
25
  const ws = wb.addWorksheet('Export', {
@@ -10,7 +10,13 @@ const { buildHeaderMapping, dataRowsToObjects } = require('./parse-table');
10
10
 
11
11
  function allowedImportColumns(model) {
12
12
  const hidden = new Set(model.hidden || []);
13
- return Array.from(model.columns.keys()).filter((c) => !hidden.has(c));
13
+ if (model.columns && model.columns.size > 0) {
14
+ return Array.from(model.columns.keys()).filter((c) => !hidden.has(c));
15
+ }
16
+ if (model.schema && model.schema.shape) {
17
+ return Object.keys(model.schema.shape).filter((c) => !hidden.has(c));
18
+ }
19
+ return [];
14
20
  }
15
21
 
16
22
  /**
@@ -28,7 +34,15 @@ function coerceCell(raw, meta, column) {
28
34
  raw = t;
29
35
  }
30
36
 
31
- if (!meta || !meta.type) return raw;
37
+ if (!meta || !meta.type) {
38
+ if (raw === 'true' || raw === '1' || raw === 'yes') return true;
39
+ if (raw === 'false' || raw === '0' || raw === 'no') return false;
40
+ if (typeof raw === 'string' && /^-?\d+(\.\d+)?$/.test(raw)) {
41
+ const num = Number(raw);
42
+ if (!Number.isNaN(num)) return num;
43
+ }
44
+ return raw;
45
+ }
32
46
 
33
47
  switch (meta.type) {
34
48
  case 'bigint':
@@ -33,6 +33,20 @@ function dataExchangePlugin(options = {}) {
33
33
  description: 'Admin spreadsheet import (CSV/XLSX) and Excel export',
34
34
  enabled,
35
35
 
36
+ register(ctx) {
37
+ if (!enabled) return;
38
+ const db = dbOption ?? ctx.db ?? ctx.app?.get?.('db') ?? null;
39
+ if (ctx.app && ctx.app.serviceRegistry) {
40
+ const { createExchangeServices } = require('../../src/services/builtins/exchange');
41
+ const exchangeServices = createExchangeServices({ db });
42
+ for (const [name, def] of Object.entries(exchangeServices)) {
43
+ if (!ctx.app.serviceRegistry.has(name)) {
44
+ ctx.app.serviceRegistry.register(name, def);
45
+ }
46
+ }
47
+ }
48
+ },
49
+
36
50
  onRoutesReady(ctx) {
37
51
  if (!enabled) return;
38
52
 
@@ -106,7 +106,20 @@ function emailPlugin(options = {}) {
106
106
  },
107
107
 
108
108
  register(ctx) {
109
- // noop — templates loaded at plugin init; register available for future hot-reload
109
+ if (ctx.app && ctx.app.serviceRegistry) {
110
+ const { createMailServices } = require('../../src/services/builtins/mail');
111
+ const mailServices = createMailServices({
112
+ emailService,
113
+ registry,
114
+ db,
115
+ tableName,
116
+ });
117
+ for (const [name, def] of Object.entries(mailServices)) {
118
+ if (!ctx.app.serviceRegistry.has(name)) {
119
+ ctx.app.serviceRegistry.register(name, def);
120
+ }
121
+ }
122
+ }
110
123
  },
111
124
 
112
125
  onRoutesReady(ctx) {
package/plugins/index.js CHANGED
@@ -25,6 +25,20 @@ const emailPlugin = require('./email');
25
25
  const contentPlugin = require('./content');
26
26
  const csrfPlugin = require('./csrf');
27
27
  const corsPlugin = require('./cors');
28
+ const { basicAuthPlugin, createBasicAuthMiddleware } = require('./basic-auth');
29
+ const {
30
+ realtimePlugin,
31
+ realtime,
32
+ createRealtime,
33
+ websocket,
34
+ createWebSocketAdapter,
35
+ sse,
36
+ createSseAdapter,
37
+ socketIo,
38
+ createSocketIoAdapter,
39
+ redis,
40
+ createRedisAdapter,
41
+ } = require('./realtime');
28
42
 
29
43
  module.exports = {
30
44
  sitemapPlugin,
@@ -49,5 +63,20 @@ module.exports = {
49
63
  contentPlugin,
50
64
  csrfPlugin,
51
65
  corsPlugin,
66
+ basicAuthPlugin,
67
+ createBasicAuthMiddleware,
68
+ realtimePlugin,
69
+ realtime,
70
+ createRealtime,
71
+ websocket,
72
+ createWebSocketAdapter,
73
+ sse,
74
+ createSseAdapter,
75
+ socketIo,
76
+ createSocketIoAdapter,
77
+ redis,
78
+ createRedisAdapter,
79
+ queuePlugin: require('./queue'),
52
80
  };
53
81
 
82
+