@nodestackapp/server 2.5.0 → 2.6.0

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 (221) hide show
  1. package/README.md +40 -28
  2. package/dist/NodeStack.d.ts +1 -1
  3. package/dist/NodeStack.d.ts.map +1 -1
  4. package/dist/NodeStack.js +73 -12
  5. package/dist/NodeStack.js.map +1 -1
  6. package/dist/admin/AdminUIBundler.d.ts.map +1 -1
  7. package/dist/admin/AdminUIBundler.js +1 -0
  8. package/dist/admin/AdminUIBundler.js.map +1 -1
  9. package/dist/admin/ui/css/main.css +34 -0
  10. package/dist/admin/ui/css/webhooks.css +8 -0
  11. package/dist/admin/ui/index.html +19150 -17212
  12. package/dist/admin/ui/js/api-keys.js +1381 -0
  13. package/dist/admin/ui/js/app.js +667 -641
  14. package/dist/admin/ui/js/apps.js +496 -489
  15. package/dist/admin/ui/js/collections.js +486 -484
  16. package/dist/admin/ui/js/command-palette.js +683 -673
  17. package/dist/admin/ui/js/flows-designer.js +1125 -1076
  18. package/dist/admin/ui/js/flows.js +908 -890
  19. package/dist/admin/ui/js/functions-tester.js +1 -1
  20. package/dist/admin/ui/js/functions-workbench.js +1144 -1101
  21. package/dist/admin/ui/js/functions.js +980 -979
  22. package/dist/admin/ui/js/rules.js +1080 -775
  23. package/dist/admin/ui/js/schema.js +346 -304
  24. package/dist/admin/ui/js/views.js +1 -1
  25. package/dist/apps/AppManager.d.ts +1 -1
  26. package/dist/apps/AppManager.d.ts.map +1 -1
  27. package/dist/apps/AppManager.js +4 -18
  28. package/dist/apps/AppManager.js.map +1 -1
  29. package/dist/apps/AppRegistry.d.ts +1 -0
  30. package/dist/apps/AppRegistry.d.ts.map +1 -1
  31. package/dist/apps/AppRegistry.js +78 -23
  32. package/dist/apps/AppRegistry.js.map +1 -1
  33. package/dist/apps/AppScope.d.ts +0 -1
  34. package/dist/apps/AppScope.d.ts.map +1 -1
  35. package/dist/apps/AppScope.js +5 -15
  36. package/dist/apps/AppScope.js.map +1 -1
  37. package/dist/auth/ApiKeyService.d.ts +62 -2
  38. package/dist/auth/ApiKeyService.d.ts.map +1 -1
  39. package/dist/auth/ApiKeyService.js +503 -8
  40. package/dist/auth/ApiKeyService.js.map +1 -1
  41. package/dist/auth/AuthService.d.ts +30 -1
  42. package/dist/auth/AuthService.d.ts.map +1 -1
  43. package/dist/auth/AuthService.js +468 -65
  44. package/dist/auth/AuthService.js.map +1 -1
  45. package/dist/auth/oauth/AppleProvider.d.ts +2 -0
  46. package/dist/auth/oauth/AppleProvider.d.ts.map +1 -1
  47. package/dist/auth/oauth/AppleProvider.js +40 -3
  48. package/dist/auth/oauth/AppleProvider.js.map +1 -1
  49. package/dist/auth/oauth/BaseOAuthProvider.d.ts +3 -2
  50. package/dist/auth/oauth/BaseOAuthProvider.d.ts.map +1 -1
  51. package/dist/auth/oauth/BaseOAuthProvider.js +29 -3
  52. package/dist/auth/oauth/BaseOAuthProvider.js.map +1 -1
  53. package/dist/auth/oauth/DiscordProvider.d.ts.map +1 -1
  54. package/dist/auth/oauth/DiscordProvider.js +4 -1
  55. package/dist/auth/oauth/DiscordProvider.js.map +1 -1
  56. package/dist/auth/oauth/GitHubProvider.d.ts.map +1 -1
  57. package/dist/auth/oauth/GitHubProvider.js +4 -1
  58. package/dist/auth/oauth/GitHubProvider.js.map +1 -1
  59. package/dist/auth/oauth/GoogleProvider.d.ts.map +1 -1
  60. package/dist/auth/oauth/GoogleProvider.js +4 -1
  61. package/dist/auth/oauth/GoogleProvider.js.map +1 -1
  62. package/dist/auth/oauth/MicrosoftProvider.d.ts.map +1 -1
  63. package/dist/auth/oauth/MicrosoftProvider.js +4 -1
  64. package/dist/auth/oauth/MicrosoftProvider.js.map +1 -1
  65. package/dist/auth/oauth/OAuthProviderRegistry.d.ts +6 -2
  66. package/dist/auth/oauth/OAuthProviderRegistry.d.ts.map +1 -1
  67. package/dist/auth/oauth/OAuthProviderRegistry.js +25 -10
  68. package/dist/auth/oauth/OAuthProviderRegistry.js.map +1 -1
  69. package/dist/auth/oauth/types.d.ts +4 -2
  70. package/dist/auth/oauth/types.d.ts.map +1 -1
  71. package/dist/cli/cli.d.ts.map +1 -1
  72. package/dist/cli/cli.js +228 -12
  73. package/dist/cli/cli.js.map +1 -1
  74. package/dist/core/config/ConfigService.d.ts.map +1 -1
  75. package/dist/core/config/ConfigService.js +5 -3
  76. package/dist/core/config/ConfigService.js.map +1 -1
  77. package/dist/core/config/EnvLoader.d.ts +14 -0
  78. package/dist/core/config/EnvLoader.d.ts.map +1 -1
  79. package/dist/core/config/EnvLoader.js +44 -0
  80. package/dist/core/config/EnvLoader.js.map +1 -1
  81. package/dist/core/container/Container.d.ts +14 -0
  82. package/dist/core/container/Container.d.ts.map +1 -1
  83. package/dist/core/container/Container.js +32 -0
  84. package/dist/core/container/Container.js.map +1 -1
  85. package/dist/core/errors/AppError.d.ts +7 -7
  86. package/dist/core/errors/AppError.d.ts.map +1 -1
  87. package/dist/core/errors/AppError.js +18 -14
  88. package/dist/core/errors/AppError.js.map +1 -1
  89. package/dist/core/events/EventBus.d.ts.map +1 -1
  90. package/dist/core/events/EventBus.js +36 -6
  91. package/dist/core/events/EventBus.js.map +1 -1
  92. package/dist/core/maintenance/MaintenanceGate.d.ts +47 -0
  93. package/dist/core/maintenance/MaintenanceGate.d.ts.map +1 -1
  94. package/dist/core/maintenance/MaintenanceGate.js +265 -7
  95. package/dist/core/maintenance/MaintenanceGate.js.map +1 -1
  96. package/dist/core/plugins/PluginManager.d.ts +20 -1
  97. package/dist/core/plugins/PluginManager.d.ts.map +1 -1
  98. package/dist/core/plugins/PluginManager.js +231 -146
  99. package/dist/core/plugins/PluginManager.js.map +1 -1
  100. package/dist/core/plugins/types.d.ts +48 -31
  101. package/dist/core/plugins/types.d.ts.map +1 -1
  102. package/dist/database/DatabaseService.d.ts +1 -0
  103. package/dist/database/DatabaseService.d.ts.map +1 -1
  104. package/dist/database/DatabaseService.js +24 -6
  105. package/dist/database/DatabaseService.js.map +1 -1
  106. package/dist/database/drivers/DriverRegistry.d.ts +1 -0
  107. package/dist/database/drivers/DriverRegistry.d.ts.map +1 -1
  108. package/dist/database/drivers/DriverRegistry.js +29 -0
  109. package/dist/database/drivers/DriverRegistry.js.map +1 -1
  110. package/dist/database/drivers/IDatabaseDriver.d.ts +1 -0
  111. package/dist/database/drivers/IDatabaseDriver.d.ts.map +1 -1
  112. package/dist/database/drivers/MssqlDriver.d.ts.map +1 -1
  113. package/dist/database/drivers/MssqlDriver.js +8 -2
  114. package/dist/database/drivers/MssqlDriver.js.map +1 -1
  115. package/dist/database/drivers/NodeSqliteDriver.d.ts.map +1 -1
  116. package/dist/database/drivers/NodeSqliteDriver.js +15 -1
  117. package/dist/database/drivers/NodeSqliteDriver.js.map +1 -1
  118. package/dist/database/migrations/SystemMigrations.d.ts.map +1 -1
  119. package/dist/database/migrations/SystemMigrations.js +62 -5
  120. package/dist/database/migrations/SystemMigrations.js.map +1 -1
  121. package/dist/flows/FlowEngine.js.map +1 -1
  122. package/dist/flows/FlowService.d.ts +7 -1
  123. package/dist/flows/FlowService.d.ts.map +1 -1
  124. package/dist/flows/FlowService.js +126 -12
  125. package/dist/flows/FlowService.js.map +1 -1
  126. package/dist/flows/FlowValidator.d.ts +1 -0
  127. package/dist/flows/FlowValidator.d.ts.map +1 -1
  128. package/dist/flows/FlowValidator.js +76 -1
  129. package/dist/flows/FlowValidator.js.map +1 -1
  130. package/dist/flows/types.d.ts +14 -2
  131. package/dist/flows/types.d.ts.map +1 -1
  132. package/dist/functions/FunctionService.d.ts +5 -1
  133. package/dist/functions/FunctionService.d.ts.map +1 -1
  134. package/dist/functions/FunctionService.js +84 -33
  135. package/dist/functions/FunctionService.js.map +1 -1
  136. package/dist/functions/runtime/QuickJsWasmRuntime.d.ts.map +1 -1
  137. package/dist/functions/runtime/QuickJsWasmRuntime.js +19 -10
  138. package/dist/functions/runtime/QuickJsWasmRuntime.js.map +1 -1
  139. package/dist/functions/types.d.ts +16 -2
  140. package/dist/functions/types.d.ts.map +1 -1
  141. package/dist/http/HttpServer.d.ts +3 -0
  142. package/dist/http/HttpServer.d.ts.map +1 -1
  143. package/dist/http/HttpServer.js +153 -6
  144. package/dist/http/HttpServer.js.map +1 -1
  145. package/dist/http/controllers/ApiKeyController.d.ts +1 -0
  146. package/dist/http/controllers/ApiKeyController.d.ts.map +1 -1
  147. package/dist/http/controllers/ApiKeyController.js +47 -1
  148. package/dist/http/controllers/ApiKeyController.js.map +1 -1
  149. package/dist/http/controllers/AuthController.d.ts +12 -0
  150. package/dist/http/controllers/AuthController.d.ts.map +1 -1
  151. package/dist/http/controllers/AuthController.js +40 -2
  152. package/dist/http/controllers/AuthController.js.map +1 -1
  153. package/dist/http/controllers/FlowController.d.ts.map +1 -1
  154. package/dist/http/controllers/FlowController.js +45 -4
  155. package/dist/http/controllers/FlowController.js.map +1 -1
  156. package/dist/http/controllers/FunctionController.d.ts.map +1 -1
  157. package/dist/http/controllers/FunctionController.js +16 -2
  158. package/dist/http/controllers/FunctionController.js.map +1 -1
  159. package/dist/http/controllers/HealthController.js +2 -2
  160. package/dist/http/middleware/AppResolutionMiddleware.d.ts +1 -1
  161. package/dist/http/middleware/AppResolutionMiddleware.d.ts.map +1 -1
  162. package/dist/http/middleware/AppResolutionMiddleware.js +2 -3
  163. package/dist/http/middleware/AppResolutionMiddleware.js.map +1 -1
  164. package/dist/http/middleware/AuthMiddleware.d.ts.map +1 -1
  165. package/dist/http/middleware/AuthMiddleware.js +6 -3
  166. package/dist/http/middleware/AuthMiddleware.js.map +1 -1
  167. package/dist/http/middleware/ChaosMiddleware.js +6 -6
  168. package/dist/http/middleware/ChaosMiddleware.js.map +1 -1
  169. package/dist/index.d.ts +2 -2
  170. package/dist/index.d.ts.map +1 -1
  171. package/dist/index.js +6 -2
  172. package/dist/index.js.map +1 -1
  173. package/dist/queue/QueueService.d.ts +9 -0
  174. package/dist/queue/QueueService.d.ts.map +1 -1
  175. package/dist/queue/QueueService.js +143 -60
  176. package/dist/queue/QueueService.js.map +1 -1
  177. package/dist/queue/drivers/SqliteQueueDriver.d.ts +3 -0
  178. package/dist/queue/drivers/SqliteQueueDriver.d.ts.map +1 -1
  179. package/dist/queue/drivers/SqliteQueueDriver.js +315 -255
  180. package/dist/queue/drivers/SqliteQueueDriver.js.map +1 -1
  181. package/dist/records/FtsService.d.ts +7 -3
  182. package/dist/records/FtsService.d.ts.map +1 -1
  183. package/dist/records/FtsService.js +69 -5
  184. package/dist/records/FtsService.js.map +1 -1
  185. package/dist/records/QueryFilterParser.d.ts.map +1 -1
  186. package/dist/records/QueryFilterParser.js +58 -20
  187. package/dist/records/QueryFilterParser.js.map +1 -1
  188. package/dist/records/RecordSanitizer.d.ts.map +1 -1
  189. package/dist/records/RecordSanitizer.js +32 -4
  190. package/dist/records/RecordSanitizer.js.map +1 -1
  191. package/dist/records/RecordService.d.ts +6 -0
  192. package/dist/records/RecordService.d.ts.map +1 -1
  193. package/dist/records/RecordService.js +95 -14
  194. package/dist/records/RecordService.js.map +1 -1
  195. package/dist/records/RecordValidator.d.ts +10 -0
  196. package/dist/records/RecordValidator.d.ts.map +1 -1
  197. package/dist/records/RecordValidator.js +110 -2
  198. package/dist/records/RecordValidator.js.map +1 -1
  199. package/dist/records/fts/IFtsDriver.d.ts +7 -6
  200. package/dist/records/fts/IFtsDriver.d.ts.map +1 -1
  201. package/dist/records/fts/MssqlFtsDriver.d.ts +5 -1
  202. package/dist/records/fts/MssqlFtsDriver.d.ts.map +1 -1
  203. package/dist/records/fts/MssqlFtsDriver.js +35 -3
  204. package/dist/records/fts/MssqlFtsDriver.js.map +1 -1
  205. package/dist/records/fts/PostgresFtsDriver.d.ts +9 -2
  206. package/dist/records/fts/PostgresFtsDriver.d.ts.map +1 -1
  207. package/dist/records/fts/PostgresFtsDriver.js +116 -11
  208. package/dist/records/fts/PostgresFtsDriver.js.map +1 -1
  209. package/dist/records/fts/SqliteFts5Driver.d.ts +7 -1
  210. package/dist/records/fts/SqliteFts5Driver.d.ts.map +1 -1
  211. package/dist/records/fts/SqliteFts5Driver.js +66 -6
  212. package/dist/records/fts/SqliteFts5Driver.js.map +1 -1
  213. package/dist/schema/OpenApiGenerator.d.ts.map +1 -1
  214. package/dist/schema/OpenApiGenerator.js +103 -3
  215. package/dist/schema/OpenApiGenerator.js.map +1 -1
  216. package/dist/schema/models/Field.d.ts +1 -0
  217. package/dist/schema/models/Field.d.ts.map +1 -1
  218. package/dist/templates/definitions/ecommerce.js +6 -6
  219. package/dist/templates/definitions/ecommerce.js.map +1 -1
  220. package/dist/webhooks/WebhookService.js +1 -1
  221. package/package.json +4 -3
@@ -33,7 +33,8 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.AuthService = void 0;
36
+ exports.AuthService = exports.COMMON_WEAK_PASSWORDS = void 0;
37
+ exports.validatePasswordStrength = validatePasswordStrength;
37
38
  const crypto = __importStar(require("crypto"));
38
39
  const bcrypt = __importStar(require("bcryptjs"));
39
40
  const jwt = __importStar(require("jsonwebtoken"));
@@ -41,7 +42,60 @@ const AppError_1 = require("../core/errors/AppError");
41
42
  const OAuthProviderRegistry_1 = require("./oauth/OAuthProviderRegistry");
42
43
  const RuleEngine_1 = require("../rules/RuleEngine");
43
44
  const RecordValidator_1 = require("../records/RecordValidator");
45
+ const RecordSanitizer_1 = require("../records/RecordSanitizer");
44
46
  const SsrfGuard_1 = require("../functions/security/SsrfGuard");
47
+ const RESERVED_AUTH_CLAIM_KEYS = new Set([
48
+ 'id',
49
+ 'email',
50
+ 'collection',
51
+ 'tokenKey',
52
+ 'isAdmin',
53
+ 'isSuperAdmin',
54
+ 'isTenantScoped',
55
+ 'isApiKey',
56
+ 'apiKeyId',
57
+ 'apiKeyName',
58
+ 'scopes',
59
+ 'allowedIps',
60
+ 'appId',
61
+ 'appSlug',
62
+ 'exp',
63
+ 'iat',
64
+ ]);
65
+ exports.COMMON_WEAK_PASSWORDS = new Set([
66
+ 'password',
67
+ '12345678',
68
+ '123456789',
69
+ '1234567890',
70
+ 'qwertyuiop',
71
+ 'asdfghjkl',
72
+ 'adminadmin',
73
+ 'letmein123',
74
+ 'welcome123',
75
+ 'iloveyou1',
76
+ ]);
77
+ /**
78
+ * Validates password strength, length bounds, and common weak passwords.
79
+ */
80
+ function validatePasswordStrength(password) {
81
+ if (!password || typeof password !== 'string' || password.length < 8) {
82
+ throw new AppError_1.AppError('Password must be at least 8 characters long', 400);
83
+ }
84
+ if (password.length > 128) {
85
+ throw new AppError_1.AppError('Password must not exceed 128 characters', 400);
86
+ }
87
+ if (exports.COMMON_WEAK_PASSWORDS.has(password.toLowerCase())) {
88
+ throw new AppError_1.AppError('Password is too common and easily guessed. Please choose a stronger password.', 400);
89
+ }
90
+ if (/^(.)\1+$/.test(password)) {
91
+ throw new AppError_1.AppError('Password cannot be composed of a single repeated character', 400);
92
+ }
93
+ const hasLetter = /[a-zA-Z]/.test(password);
94
+ const hasNumberOrSymbol = /[0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?`~]/.test(password);
95
+ if (!hasLetter || !hasNumberOrSymbol) {
96
+ throw new AppError_1.AppError('Password must contain both letters and at least one number or special character', 400);
97
+ }
98
+ }
45
99
  class AuthService {
46
100
  db;
47
101
  config;
@@ -56,6 +110,8 @@ class AuthService {
56
110
  tokenKeyCache = new Map();
57
111
  tokenKeyCacheTtlMs = 30000; // 30 seconds TTL
58
112
  maxTokenKeyCacheSize = 5000;
113
+ registrationLocks = new Map();
114
+ verificationCooldowns = new Map();
59
115
  isControlPlane;
60
116
  constructor(db, config, schemaService, registry, oauthRegistry, ruleEngine, eventBus, realtimeService, options) {
61
117
  this.db = db;
@@ -126,7 +182,7 @@ class AuthService {
126
182
  }
127
183
  }
128
184
  }
129
- getCachedTokenKey(cacheKey) {
185
+ getCachedAuthEntry(cacheKey) {
130
186
  const entry = this.tokenKeyCache.get(cacheKey);
131
187
  if (!entry)
132
188
  return null;
@@ -137,9 +193,9 @@ class AuthService {
137
193
  // Re-insert entry to move to the most-recently-used end in Map iteration order
138
194
  this.tokenKeyCache.delete(cacheKey);
139
195
  this.tokenKeyCache.set(cacheKey, entry);
140
- return entry.tokenKey;
196
+ return entry;
141
197
  }
142
- setCachedTokenKey(cacheKey, tokenKey) {
198
+ setCachedAuthEntry(cacheKey, tokenKey, profile) {
143
199
  this.tokenKeyCache.delete(cacheKey);
144
200
  if (this.tokenKeyCache.size >= this.maxTokenKeyCacheSize) {
145
201
  const firstKey = this.tokenKeyCache.keys().next().value;
@@ -148,9 +204,29 @@ class AuthService {
148
204
  }
149
205
  this.tokenKeyCache.set(cacheKey, {
150
206
  tokenKey,
207
+ profile,
151
208
  expiresAt: Date.now() + this.tokenKeyCacheTtlMs,
152
209
  });
153
210
  }
211
+ mergeHydratedProfile(decoded, profile) {
212
+ if (!profile) {
213
+ return decoded;
214
+ }
215
+ const merged = { ...decoded };
216
+ for (const [key, val] of Object.entries(profile)) {
217
+ if (!RESERVED_AUTH_CLAIM_KEYS.has(key)) {
218
+ merged[key] = val;
219
+ }
220
+ }
221
+ return merged;
222
+ }
223
+ getCachedTokenKey(cacheKey) {
224
+ const entry = this.getCachedAuthEntry(cacheKey);
225
+ return entry ? entry.tokenKey : null;
226
+ }
227
+ setCachedTokenKey(cacheKey, tokenKey) {
228
+ this.setCachedAuthEntry(cacheKey, tokenKey);
229
+ }
154
230
  invalidateTokenCache(collection, idOrEmail) {
155
231
  if (!collection && !idOrEmail) {
156
232
  this.tokenKeyCache.clear();
@@ -226,12 +302,13 @@ class AuthService {
226
302
  }
227
303
  try {
228
304
  const driver = this.registry.getDriver();
229
- const columns = ['id', 'email', 'passwordHash', 'tokenKey', 'avatar', 'created', 'updated'];
230
- const updateColumns = ['email', 'passwordHash', 'tokenKey', 'avatar', 'created', 'updated'];
305
+ const columns = ['id', 'email', 'passwordHash', 'tokenKey', 'avatar', 'verified', 'created', 'updated'];
306
+ const updateColumns = ['email', 'passwordHash', 'tokenKey', 'avatar', 'verified', 'created', 'updated'];
231
307
  const upsertSql = driver.dialect.upsertSql('_admins', columns, 'id', updateColumns);
308
+ const isVerifiedVal = (admin.verified === true || admin.verified === 1 || String(admin.verified) === 'true' || String(admin.verified) === '1') ? 1 : 0;
232
309
  const runRes = driver
233
310
  .prepare(upsertSql)
234
- .run(admin.id, admin.email, admin.passwordHash, admin.tokenKey, admin.avatar || null, admin.created, admin.updated);
311
+ .run(admin.id, admin.email, admin.passwordHash, admin.tokenKey, admin.avatar || null, isVerifiedVal, admin.created, admin.updated);
235
312
  if (runRes && typeof runRes.then === 'function') {
236
313
  return runRes.then(() => undefined, () => undefined);
237
314
  }
@@ -301,21 +378,24 @@ class AuthService {
301
378
  throw new AppError_1.UnauthorizedError('Authentication token collection not found');
302
379
  }
303
380
  const cacheKey = `${col.name}:${decoded.id}`;
304
- const cached = this.getCachedTokenKey(cacheKey);
305
- if (cached !== null) {
306
- if (cached !== decoded.tokenKey) {
381
+ const cachedEntry = this.getCachedAuthEntry(cacheKey);
382
+ if (cachedEntry !== null) {
383
+ if (cachedEntry.tokenKey !== decoded.tokenKey) {
307
384
  throw new AppError_1.UnauthorizedError('Authentication token has been revoked or expired');
308
385
  }
309
- return decoded;
386
+ if (cachedEntry.profile) {
387
+ return this.mergeHydratedProfile(decoded, cachedEntry.profile);
388
+ }
310
389
  }
311
390
  const qTable = this.db.dialect.quoteIdentifier(col.name);
312
- const recordRaw = this.db.get(`SELECT tokenKey FROM ${qTable} WHERE id = ?`, decoded.id);
391
+ const recordRaw = this.db.get(`SELECT * FROM ${qTable} WHERE id = ?`, decoded.id);
313
392
  const finalizeRecord = (record) => {
314
393
  if (!record || !record.tokenKey || record.tokenKey !== decoded.tokenKey) {
315
394
  throw new AppError_1.UnauthorizedError('Authentication token has been revoked or expired');
316
395
  }
317
- this.setCachedTokenKey(cacheKey, record.tokenKey);
318
- return decoded;
396
+ const profile = this.sanitizeAuthRecord(record, col);
397
+ this.setCachedAuthEntry(cacheKey, record.tokenKey, profile);
398
+ return this.mergeHydratedProfile(decoded, profile);
319
399
  };
320
400
  if (recordRaw && typeof recordRaw.then === 'function') {
321
401
  return recordRaw.then((resolvedRecord) => finalizeRecord(resolvedRecord));
@@ -352,9 +432,7 @@ class AuthService {
352
432
  if (!cleanEmail || !cleanEmail.includes('@')) {
353
433
  throw new AppError_1.AppError('Valid email is required', 400);
354
434
  }
355
- if (!password || password.length < 8) {
356
- throw new AppError_1.AppError('Password must be at least 8 characters long', 400);
357
- }
435
+ validatePasswordStrength(password);
358
436
  if (await this.hasAdmins()) {
359
437
  throw new AppError_1.AppError('Initial admin setup is already complete', 400);
360
438
  }
@@ -395,48 +473,92 @@ class AuthService {
395
473
  updated: now,
396
474
  };
397
475
  }
476
+ async withRegistrationLock(key, fn) {
477
+ const cleanKey = key.trim().toLowerCase();
478
+ const previous = this.registrationLocks.get(cleanKey) || Promise.resolve();
479
+ let release;
480
+ const current = new Promise((resolve) => {
481
+ release = resolve;
482
+ });
483
+ this.registrationLocks.set(cleanKey, current);
484
+ await previous.catch(() => { });
485
+ try {
486
+ return await fn();
487
+ }
488
+ finally {
489
+ if (this.registrationLocks.get(cleanKey) === current) {
490
+ this.registrationLocks.delete(cleanKey);
491
+ }
492
+ release();
493
+ }
494
+ }
398
495
  async createAdmin(email, password, avatar) {
399
496
  const cleanEmail = email.trim().toLowerCase();
400
497
  if (!cleanEmail || !cleanEmail.includes('@')) {
401
498
  throw new AppError_1.AppError('Valid email is required', 400);
402
499
  }
403
- if (!password || password.length < 8) {
404
- throw new AppError_1.AppError('Password must be at least 8 characters long', 400);
405
- }
406
- if (this.registry && this.isControlPlane) {
407
- const regExisting = await this.registry.getAdminByEmail(cleanEmail);
408
- if (regExisting) {
500
+ validatePasswordStrength(password);
501
+ return this.withRegistrationLock(`_admins:${cleanEmail}`, async () => {
502
+ if (this.registry && this.isControlPlane) {
503
+ const regExisting = await this.registry.getAdminByEmail(cleanEmail);
504
+ if (regExisting) {
505
+ throw new AppError_1.ConflictError(`Admin with email '${cleanEmail}' already exists`);
506
+ }
507
+ }
508
+ const existing = await this.db.get('SELECT id FROM _admins WHERE LOWER(email) = ?', cleanEmail);
509
+ if (existing) {
409
510
  throw new AppError_1.ConflictError(`Admin with email '${cleanEmail}' already exists`);
410
511
  }
411
- }
412
- const existing = await this.db.get('SELECT id FROM _admins WHERE email = ?', cleanEmail);
413
- if (existing) {
414
- throw new AppError_1.ConflictError(`Admin with email '${cleanEmail}' already exists`);
415
- }
416
- const id = `adm_${crypto.randomBytes(6).toString('hex')}`;
417
- const passwordHash = await this.hashPassword(password);
418
- const tokenKey = crypto.randomBytes(16).toString('hex');
419
- const now = new Date().toISOString();
420
- await this.db.run(`INSERT INTO _admins (id, email, passwordHash, tokenKey, avatar, created, updated)
421
- VALUES (?, ?, ?, ?, ?, ?, ?)`, id, cleanEmail, passwordHash, tokenKey, avatar || null, now, now);
422
- if (this.registry && this.isControlPlane) {
512
+ const id = `adm_${crypto.randomBytes(6).toString('hex')}`;
513
+ const passwordHash = await this.hashPassword(password);
514
+ const tokenKey = crypto.randomBytes(16).toString('hex');
515
+ const now = new Date().toISOString();
516
+ const insertSql = `
517
+ INSERT INTO _admins (id, email, passwordHash, tokenKey, avatar, created, updated)
518
+ SELECT ?, ?, ?, ?, ?, ?, ?
519
+ WHERE NOT EXISTS (SELECT 1 FROM _admins WHERE LOWER(email) = ?)
520
+ `;
423
521
  try {
424
- await this.registry.getDriver().prepare(`
425
- INSERT INTO _admins (id, email, passwordHash, tokenKey, avatar, created, updated)
426
- VALUES (?, ?, ?, ?, ?, ?, ?)
427
- `).run(id, cleanEmail, passwordHash, tokenKey, avatar || null, now, now);
522
+ const result = await this.db.run(insertSql, id, cleanEmail, passwordHash, tokenKey, avatar || null, now, now, cleanEmail);
523
+ if (result && Number(result.changes || 0) === 0) {
524
+ throw new AppError_1.ConflictError(`Admin with email '${cleanEmail}' already exists`);
525
+ }
428
526
  }
429
- catch {
430
- // ignore duplicate in system DB
527
+ catch (err) {
528
+ if (err instanceof AppError_1.ConflictError ||
529
+ err?.message?.includes('UNIQUE constraint failed') ||
530
+ err?.message?.includes('duplicate key') ||
531
+ err?.code === '23505' ||
532
+ err?.number === 2627 ||
533
+ err?.number === 2601) {
534
+ throw new AppError_1.ConflictError(`Admin with email '${cleanEmail}' already exists`);
535
+ }
536
+ throw err;
431
537
  }
432
- }
433
- return {
434
- id,
435
- email: cleanEmail,
436
- avatar: avatar || null,
437
- created: now,
438
- updated: now,
439
- };
538
+ if (this.registry && this.isControlPlane) {
539
+ try {
540
+ const regStmt = this.registry.getDriver().prepare(`
541
+ INSERT INTO _admins (id, email, passwordHash, tokenKey, avatar, created, updated)
542
+ SELECT ?, ?, ?, ?, ?, ?, ?
543
+ WHERE NOT EXISTS (SELECT 1 FROM _admins WHERE LOWER(email) = ?)
544
+ `);
545
+ const regRes = regStmt.run(id, cleanEmail, passwordHash, tokenKey, avatar || null, now, now, cleanEmail);
546
+ if (regRes && typeof regRes.then === 'function') {
547
+ await regRes;
548
+ }
549
+ }
550
+ catch {
551
+ // ignore duplicate in system DB
552
+ }
553
+ }
554
+ return {
555
+ id,
556
+ email: cleanEmail,
557
+ avatar: avatar || null,
558
+ created: now,
559
+ updated: now,
560
+ };
561
+ });
440
562
  }
441
563
  async authenticateAdmin(email, password) {
442
564
  const cleanEmail = email.trim().toLowerCase();
@@ -469,12 +591,71 @@ class AuthService {
469
591
  appSlug: this.options?.appSlug || (isSuper ? 'default' : undefined),
470
592
  };
471
593
  const token = this.generateToken(claims, '14d');
472
- const { passwordHash, tokenKey, ...adminSafe } = admin;
594
+ const adminSafe = this.sanitizeAdminRecord(admin);
473
595
  return {
474
596
  token,
475
597
  record: adminSafe,
476
598
  };
477
599
  }
600
+ sanitizeAdminRecord(admin) {
601
+ return {
602
+ id: admin.id,
603
+ email: admin.email,
604
+ avatar: admin.avatar || null,
605
+ created: admin.created,
606
+ updated: admin.updated,
607
+ verified: admin.verified !== undefined ? Boolean(admin.verified) : true,
608
+ };
609
+ }
610
+ sanitizeAuthRecord(record, col, isOwner = true) {
611
+ const rawVerified = record.verified;
612
+ let clean;
613
+ if (col) {
614
+ clean = RecordSanitizer_1.RecordSanitizer.sanitize(record, col, undefined, isOwner);
615
+ }
616
+ else {
617
+ clean = { ...record };
618
+ const sensitive = [
619
+ 'passwordHash',
620
+ 'password_hash',
621
+ 'tokenKey',
622
+ 'token_key',
623
+ 'password',
624
+ 'resetToken',
625
+ 'reset_token',
626
+ 'verificationToken',
627
+ 'verification_token',
628
+ 'totpSecret',
629
+ 'totp_secret',
630
+ 'twoFactorSecret',
631
+ 'two_factor_secret',
632
+ 'backupCodes',
633
+ 'backup_codes',
634
+ 'recoveryCodes',
635
+ 'recovery_codes',
636
+ 'securityAnswers',
637
+ 'security_answers',
638
+ 'internalNotes',
639
+ 'internal_notes',
640
+ 'failedLoginAttempts',
641
+ 'failed_login_attempts',
642
+ ];
643
+ for (const key of sensitive) {
644
+ delete clean[key];
645
+ }
646
+ if (clean.verified !== undefined)
647
+ clean.verified = Boolean(clean.verified);
648
+ if (clean.emailVisibility !== undefined)
649
+ clean.emailVisibility = Boolean(clean.emailVisibility);
650
+ if (!isOwner && !clean.emailVisibility) {
651
+ delete clean.email;
652
+ }
653
+ }
654
+ if (typeof rawVerified === 'number') {
655
+ clean.verified = rawVerified;
656
+ }
657
+ return clean;
658
+ }
478
659
  async getAdminById(id) {
479
660
  let admin = (this.registry && this.isControlPlane)
480
661
  ? await this.registry.getAdminById(id)
@@ -484,8 +665,7 @@ class AuthService {
484
665
  }
485
666
  if (!admin)
486
667
  return undefined;
487
- const { passwordHash, tokenKey, ...adminSafe } = admin;
488
- return adminSafe;
668
+ return this.sanitizeAdminRecord(admin);
489
669
  }
490
670
  async updateAdminPassword(email, newPassword) {
491
671
  const cleanEmail = email.trim().toLowerCase();
@@ -495,9 +675,7 @@ class AuthService {
495
675
  if (!admin) {
496
676
  throw new AppError_1.NotFoundError(`Admin with email '${cleanEmail}' not found`);
497
677
  }
498
- if (!newPassword || newPassword.length < 8) {
499
- throw new AppError_1.AppError('Password must be at least 8 characters long', 400);
500
- }
678
+ validatePasswordStrength(newPassword);
501
679
  const passwordHash = await this.hashPassword(newPassword);
502
680
  const tokenKey = crypto.randomBytes(16).toString('hex');
503
681
  const now = new Date().toISOString();
@@ -626,6 +804,12 @@ class AuthService {
626
804
  if (!valid) {
627
805
  throw new AppError_1.UnauthorizedError('Invalid authentication credentials');
628
806
  }
807
+ if (col.options?.requireEmailVerification === true) {
808
+ const isVerified = Boolean(record.verified);
809
+ if (!isVerified) {
810
+ throw new AppError_1.ForbiddenError('Please verify your email address before logging in');
811
+ }
812
+ }
629
813
  const claims = {
630
814
  id: record.id,
631
815
  email: record.email,
@@ -634,12 +818,222 @@ class AuthService {
634
818
  isAdmin: false,
635
819
  };
636
820
  const token = this.generateToken(claims, '7d');
637
- const { passwordHash, tokenKey, ...recordSafe } = record;
821
+ const recordSafe = this.sanitizeAuthRecord(record, col);
638
822
  return {
639
823
  token,
640
824
  record: recordSafe,
641
825
  };
642
826
  }
827
+ // --- Email Verification ---
828
+ createVerificationToken(collectionName, recordId, email, tokenKey, expiresIn = '24h') {
829
+ const currentAppSlug = (this.options?.appSlug || (this.isControlPlane ? 'default' : undefined) || 'default').trim().toLowerCase();
830
+ const currentAppId = this.options?.appId || (currentAppSlug === 'default' ? 'app_default' : undefined);
831
+ const payload = {
832
+ id: recordId,
833
+ email: email.trim().toLowerCase(),
834
+ collection: collectionName,
835
+ tokenKey: tokenKey || '',
836
+ type: 'verification',
837
+ action: 'verify-email',
838
+ appId: currentAppId,
839
+ appSlug: currentAppSlug,
840
+ };
841
+ return jwt.sign(payload, this.config.jwtSecret, { expiresIn: expiresIn });
842
+ }
843
+ async verifyVerificationToken(token) {
844
+ let decoded;
845
+ try {
846
+ decoded = jwt.verify(token, this.config.jwtSecret);
847
+ }
848
+ catch {
849
+ throw new AppError_1.UnauthorizedError('Invalid or expired verification token');
850
+ }
851
+ if (!decoded || !decoded.id || !decoded.collection || decoded.type !== 'verification' || decoded.action !== 'verify-email') {
852
+ throw new AppError_1.UnauthorizedError('Invalid verification token payload');
853
+ }
854
+ // Tenant / Application binding verification:
855
+ // Reject tokens issued for another application to prevent cross-tenant token replay attacks
856
+ const expectedAppSlug = (this.options?.appSlug || (this.isControlPlane ? 'default' : undefined) || 'default').trim().toLowerCase();
857
+ const tokenAppSlug = (decoded.appSlug || '').trim().toLowerCase();
858
+ if (!tokenAppSlug || tokenAppSlug !== expectedAppSlug) {
859
+ throw new AppError_1.UnauthorizedError('Verification token was issued for a different application');
860
+ }
861
+ if (decoded.appId && this.options?.appId) {
862
+ const isDefaultMatch = expectedAppSlug === 'default' &&
863
+ (decoded.appId === 'default' || decoded.appId === 'app_default') &&
864
+ (this.options.appId === 'default' || this.options.appId === 'app_default');
865
+ if (!isDefaultMatch && decoded.appId !== this.options.appId) {
866
+ throw new AppError_1.UnauthorizedError('Verification token was issued for a different application');
867
+ }
868
+ }
869
+ if (decoded.collection === '_admins') {
870
+ let admin = (this.registry && this.isControlPlane)
871
+ ? await this.registry.getAdminById(decoded.id)
872
+ : undefined;
873
+ if (!admin) {
874
+ admin = await this.db.get('SELECT * FROM _admins WHERE id = ?', decoded.id);
875
+ }
876
+ if (!admin) {
877
+ throw new AppError_1.NotFoundError('Admin account for verification not found');
878
+ }
879
+ const adminEmail = (admin.email || '').trim().toLowerCase();
880
+ const tokenEmail = (decoded.email || '').trim().toLowerCase();
881
+ if (!tokenEmail || tokenEmail !== adminEmail) {
882
+ throw new AppError_1.UnauthorizedError('Verification token does not match the current account email');
883
+ }
884
+ if (decoded.tokenKey && admin.tokenKey && decoded.tokenKey !== admin.tokenKey) {
885
+ throw new AppError_1.UnauthorizedError('Verification token has been invalidated');
886
+ }
887
+ return { id: admin.id, email: adminEmail, collection: '_admins', tokenKey: admin.tokenKey, appId: decoded.appId, appSlug: decoded.appSlug };
888
+ }
889
+ else {
890
+ const col = await this.schemaService.getCollectionOrThrow(decoded.collection);
891
+ if (col.type !== 'auth') {
892
+ throw new AppError_1.AppError(`Collection '${decoded.collection}' is not an auth collection`, 400);
893
+ }
894
+ const qTable = this.db.dialect.quoteIdentifier(col.name);
895
+ const record = await this.db.get(`SELECT * FROM ${qTable} WHERE id = ?`, decoded.id);
896
+ if (!record) {
897
+ throw new AppError_1.NotFoundError(`Record '${decoded.id}' not found in '${col.name}'`);
898
+ }
899
+ const recordEmail = (record.email || '').trim().toLowerCase();
900
+ const tokenEmail = (decoded.email || '').trim().toLowerCase();
901
+ if (!tokenEmail || tokenEmail !== recordEmail) {
902
+ throw new AppError_1.UnauthorizedError('Verification token does not match the current account email');
903
+ }
904
+ if (decoded.tokenKey && record.tokenKey && decoded.tokenKey !== record.tokenKey) {
905
+ throw new AppError_1.UnauthorizedError('Verification token has been invalidated');
906
+ }
907
+ return { id: record.id, email: recordEmail, collection: col.name, tokenKey: record.tokenKey, appId: decoded.appId, appSlug: decoded.appSlug };
908
+ }
909
+ }
910
+ async requestVerification(collectionName, email) {
911
+ const cleanEmail = email.trim().toLowerCase();
912
+ if (!cleanEmail || !cleanEmail.includes('@')) {
913
+ throw new AppError_1.AppError('Valid email is required', 400);
914
+ }
915
+ let targetId;
916
+ let targetTokenKey;
917
+ if (collectionName === '_admins') {
918
+ let admin = await this.db.get('SELECT id, tokenKey, verified FROM _admins WHERE LOWER(email) = ?', cleanEmail);
919
+ if (!admin && this.registry && this.isControlPlane) {
920
+ admin = await this.registry.getAdminByEmail(cleanEmail);
921
+ }
922
+ if (!admin) {
923
+ throw new AppError_1.NotFoundError(`Admin with email '${cleanEmail}' not found`);
924
+ }
925
+ const isVerified = admin.verified === true || admin.verified === 1 || String(admin.verified) === 'true' || String(admin.verified) === '1';
926
+ if (isVerified) {
927
+ throw new AppError_1.AppError(`Admin '${cleanEmail}' is already verified`, 400);
928
+ }
929
+ targetId = admin.id;
930
+ targetTokenKey = admin.tokenKey;
931
+ }
932
+ else {
933
+ const col = await this.schemaService.getCollectionOrThrow(collectionName);
934
+ if (col.type !== 'auth') {
935
+ throw new AppError_1.AppError(`Collection '${collectionName}' is not an auth collection`, 400);
936
+ }
937
+ const qTable = this.db.dialect.quoteIdentifier(col.name);
938
+ const record = await this.db.get(`SELECT id, tokenKey, verified FROM ${qTable} WHERE LOWER(email) = ?`, cleanEmail);
939
+ if (!record) {
940
+ throw new AppError_1.NotFoundError(`Record with email '${cleanEmail}' not found in '${collectionName}'`);
941
+ }
942
+ const isVerified = record.verified === true || record.verified === 1 || String(record.verified) === 'true' || String(record.verified) === '1';
943
+ if (isVerified) {
944
+ throw new AppError_1.AppError(`Account '${cleanEmail}' is already verified`, 400);
945
+ }
946
+ targetId = record.id;
947
+ targetTokenKey = record.tokenKey;
948
+ }
949
+ const cooldownKey = `${collectionName}:${cleanEmail}`;
950
+ const lastSent = this.verificationCooldowns.get(cooldownKey);
951
+ const nowMs = Date.now();
952
+ const cooldownMs = 60000;
953
+ if (lastSent && nowMs - lastSent < cooldownMs) {
954
+ const waitSec = Math.ceil((cooldownMs - (nowMs - lastSent)) / 1000);
955
+ throw new AppError_1.AppError(`A verification email was recently requested for '${cleanEmail}'. Please wait ${waitSec} seconds before requesting again.`, 429);
956
+ }
957
+ this.verificationCooldowns.set(cooldownKey, nowMs);
958
+ if (this.verificationCooldowns.size > 2000) {
959
+ for (const [k, timestamp] of this.verificationCooldowns.entries()) {
960
+ if (nowMs - timestamp > cooldownMs) {
961
+ this.verificationCooldowns.delete(k);
962
+ }
963
+ }
964
+ }
965
+ const token = this.createVerificationToken(collectionName, targetId, cleanEmail, targetTokenKey);
966
+ // Emit event on EventBus for email delivery plugins/mailers
967
+ try {
968
+ this.eventBus?.emit('email:verification', {
969
+ collection: collectionName,
970
+ id: targetId,
971
+ email: cleanEmail,
972
+ token,
973
+ appId: this.options?.appId,
974
+ appSlug: this.options?.appSlug,
975
+ });
976
+ }
977
+ catch {
978
+ // non-fatal
979
+ }
980
+ return { token, email: cleanEmail };
981
+ }
982
+ async confirmVerification(token) {
983
+ const claims = await this.verifyVerificationToken(token);
984
+ this.verificationCooldowns.delete(`${claims.collection}:${claims.email.toLowerCase()}`);
985
+ const now = new Date().toISOString();
986
+ const isPg = this.db.dialect?.name === 'postgres';
987
+ const verifiedVal = isPg ? true : 1;
988
+ if (claims.collection === '_admins') {
989
+ const result = await this.db.run('UPDATE _admins SET verified = ?, updated = ? WHERE id = ?', verifiedVal, now, claims.id);
990
+ if (result && Number(result.changes || 0) === 0) {
991
+ throw new AppError_1.NotFoundError(`Admin '${claims.id}' not found`);
992
+ }
993
+ if (this.registry && this.isControlPlane) {
994
+ try {
995
+ const res = this.registry.updateAdminVerified(claims.id, true);
996
+ if (res && typeof res.then === 'function') {
997
+ await res;
998
+ }
999
+ }
1000
+ catch {
1001
+ // non-fatal secondary registry sync
1002
+ }
1003
+ }
1004
+ const admin = await this.getAdminById(claims.id);
1005
+ if (!admin) {
1006
+ throw new AppError_1.NotFoundError(`Admin '${claims.id}' not found`);
1007
+ }
1008
+ return { ...admin, verified: true };
1009
+ }
1010
+ else {
1011
+ const col = await this.schemaService.getCollectionOrThrow(claims.collection);
1012
+ const qTable = this.db.dialect.quoteIdentifier(col.name);
1013
+ const result = await this.db.run(`UPDATE ${qTable} SET verified = ?, updated = ? WHERE id = ?`, verifiedVal, now, claims.id);
1014
+ if (result && Number(result.changes || 0) === 0) {
1015
+ throw new AppError_1.NotFoundError(`Record '${claims.id}' not found in '${col.name}'`);
1016
+ }
1017
+ const record = await this.db.get(`SELECT * FROM ${qTable} WHERE id = ?`, claims.id);
1018
+ if (!record) {
1019
+ throw new AppError_1.NotFoundError(`Record '${claims.id}' not found in '${col.name}'`);
1020
+ }
1021
+ const safeRecord = this.sanitizeAuthRecord(record || {}, col);
1022
+ try {
1023
+ this.eventBus?.emit('email:verified', {
1024
+ collection: col.name,
1025
+ id: claims.id,
1026
+ email: claims.email,
1027
+ appId: this.options?.appId,
1028
+ appSlug: this.options?.appSlug,
1029
+ });
1030
+ }
1031
+ catch {
1032
+ // non-fatal
1033
+ }
1034
+ return { ...safeRecord, verified: true };
1035
+ }
1036
+ }
643
1037
  // --- OAuth2 / Social Logins ---
644
1038
  async listAuthMethods(collectionName, redirectUri) {
645
1039
  const col = await this.schemaService.getCollectionOrThrow(collectionName);
@@ -651,7 +1045,7 @@ class AuthService {
651
1045
  authProviders: providers,
652
1046
  };
653
1047
  }
654
- async authenticateOAuth2(collectionName, providerName, code, codeVerifier, redirectUri, createData, fileStorageService, callerAuth, state, httpContext) {
1048
+ async authenticateOAuth2(collectionName, providerName, code, codeVerifier, redirectUri, createData, fileStorageService, callerAuth, state, httpContext, extraData) {
655
1049
  const col = await this.schemaService.getCollectionOrThrow(collectionName);
656
1050
  if (col.type !== 'auth') {
657
1051
  throw new AppError_1.AppError(`Collection '${collectionName}' is not an auth collection`, 400);
@@ -667,8 +1061,13 @@ class AuthService {
667
1061
  // Validate and consume state before exchanging the code
668
1062
  const session = this.oauthRegistry.validateAndConsumeState(state, cleanProviderName, col.name, codeVerifier, redirectUri, this.options?.appId);
669
1063
  const effectiveRedirectUri = redirectUri || session.redirectUri;
1064
+ const effectiveExtraData = extraData ||
1065
+ (httpContext?.body?.extraData ? httpContext.body.extraData : undefined) ||
1066
+ (httpContext?.body?.user !== undefined ? { user: httpContext.body.user } : undefined) ||
1067
+ (createData?.extraData ? createData.extraData : undefined) ||
1068
+ (createData?.user !== undefined ? { user: createData.user } : undefined);
670
1069
  // 1. Exchange authorization code and code_verifier with provider
671
- const exchange = await provider.exchangeCode(code, codeVerifier, effectiveRedirectUri);
1070
+ const exchange = await provider.exchangeCode(code, codeVerifier, effectiveRedirectUri, effectiveExtraData);
672
1071
  const { id: providerUserId, email: rawEmail, name, avatarUrl, isEmailVerified, rawUser } = exchange.profile;
673
1072
  const cleanEmail = (rawEmail || '').toLowerCase().trim();
674
1073
  // 2. Check if external auth identity is already linked
@@ -752,11 +1151,15 @@ class AuthService {
752
1151
  }
753
1152
  }
754
1153
  if (createData && typeof createData === 'object') {
1154
+ RecordValidator_1.RecordValidator.assertProtectedFieldsOnCreate(col.schema, createData, Boolean(callerAuth?.isAdmin));
755
1155
  const reservedFields = new Set(['id', 'passwordHash', 'tokenKey', 'created', 'updated']);
756
1156
  for (const [key, val] of Object.entries(createData)) {
757
- if (!reservedFields.has(key)) {
758
- insertRecord[key] = val;
1157
+ if (reservedFields.has(key))
1158
+ continue;
1159
+ if ((key === 'user' || key === 'extraData') && !col.schema.some((f) => f.name === key)) {
1160
+ continue;
759
1161
  }
1162
+ insertRecord[key] = val;
760
1163
  }
761
1164
  }
762
1165
  // 1. Trigger lifecycle hook: onRecordBeforeCreate
@@ -767,7 +1170,8 @@ class AuthService {
767
1170
  // 2. Enforce collection schema validation semantics before insertion
768
1171
  for (const field of col.schema) {
769
1172
  const val = insertRecord[field.name];
770
- RecordValidator_1.RecordValidator.validateField(field, val);
1173
+ const effectiveVal = val === undefined && field.defaultValue !== undefined ? field.defaultValue : val;
1174
+ RecordValidator_1.RecordValidator.validateField(field, effectiveVal);
771
1175
  insertRecord[field.name] = RecordValidator_1.RecordValidator.normalizeFieldValue(field, val);
772
1176
  }
773
1177
  // 3. Enforce collection create authorization rule semantics
@@ -797,11 +1201,10 @@ class AuthService {
797
1201
  const hookRecord = { ...insertRecord, password: '[SET]' };
798
1202
  await effectiveEventBus.triggerRecordAfterCreate(col.name, hookRecord, callerAuth, httpContext);
799
1203
  }
800
- // 7. Broadcast realtime event
1204
+ // 7. Broadcast realtime event (pass raw record so RealtimeService sanitizes per client based on subscriber identity)
801
1205
  const effectiveRealtime = this.realtimeService || httpContext?.appScope?.realtime;
802
1206
  if (effectiveRealtime) {
803
- const { passwordHash: _, tokenKey: __, ...publicRecord } = insertRecord;
804
- effectiveRealtime.broadcast('create', col.name, publicRecord);
1207
+ effectiveRealtime.broadcast('create', col.name, insertRecord);
805
1208
  }
806
1209
  }
807
1210
  if (!targetRecord) {
@@ -816,7 +1219,7 @@ class AuthService {
816
1219
  isAdmin: false,
817
1220
  };
818
1221
  const token = this.generateToken(claims, '7d');
819
- const { passwordHash: _, tokenKey: __, ...recordSafe } = targetRecord;
1222
+ const recordSafe = this.sanitizeAuthRecord(targetRecord, col);
820
1223
  return {
821
1224
  token,
822
1225
  record: recordSafe,