@nodestackapp/server 2.5.0 → 2.7.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 (269) hide show
  1. package/README.md +42 -28
  2. package/dist/NodeStack.d.ts +5 -1
  3. package/dist/NodeStack.d.ts.map +1 -1
  4. package/dist/NodeStack.js +117 -18
  5. package/dist/NodeStack.js.map +1 -1
  6. package/dist/admin/AdminUIBundler.d.ts.map +1 -1
  7. package/dist/admin/AdminUIBundler.js +2 -0
  8. package/dist/admin/AdminUIBundler.js.map +1 -1
  9. package/dist/admin/ui/css/main.css +40 -3
  10. package/dist/admin/ui/css/webhooks.css +8 -0
  11. package/dist/admin/ui/index.html +21479 -17251
  12. package/dist/admin/ui/js/api-keys.js +1381 -0
  13. package/dist/admin/ui/js/api.js +8 -0
  14. package/dist/admin/ui/js/app.js +698 -641
  15. package/dist/admin/ui/js/apps.js +514 -489
  16. package/dist/admin/ui/js/collections.js +486 -484
  17. package/dist/admin/ui/js/command-palette.js +693 -673
  18. package/dist/admin/ui/js/cron.js +1706 -0
  19. package/dist/admin/ui/js/database.js +10 -0
  20. package/dist/admin/ui/js/flows-designer.js +1219 -1076
  21. package/dist/admin/ui/js/flows.js +947 -890
  22. package/dist/admin/ui/js/functions-tester.js +1 -1
  23. package/dist/admin/ui/js/functions-workbench.js +1162 -1101
  24. package/dist/admin/ui/js/functions.js +983 -979
  25. package/dist/admin/ui/js/rules.js +1080 -775
  26. package/dist/admin/ui/js/schema.js +346 -304
  27. package/dist/admin/ui/js/snapshots.js +338 -0
  28. package/dist/admin/ui/js/views.js +1 -1
  29. package/dist/apps/AppManager.d.ts +1 -1
  30. package/dist/apps/AppManager.d.ts.map +1 -1
  31. package/dist/apps/AppManager.js +11 -21
  32. package/dist/apps/AppManager.js.map +1 -1
  33. package/dist/apps/AppRegistry.d.ts +1 -0
  34. package/dist/apps/AppRegistry.d.ts.map +1 -1
  35. package/dist/apps/AppRegistry.js +78 -23
  36. package/dist/apps/AppRegistry.js.map +1 -1
  37. package/dist/apps/AppScope.d.ts +2 -1
  38. package/dist/apps/AppScope.d.ts.map +1 -1
  39. package/dist/apps/AppScope.js +27 -17
  40. package/dist/apps/AppScope.js.map +1 -1
  41. package/dist/auth/ApiKeyService.d.ts +63 -2
  42. package/dist/auth/ApiKeyService.d.ts.map +1 -1
  43. package/dist/auth/ApiKeyService.js +518 -8
  44. package/dist/auth/ApiKeyService.js.map +1 -1
  45. package/dist/auth/AuthService.d.ts +30 -1
  46. package/dist/auth/AuthService.d.ts.map +1 -1
  47. package/dist/auth/AuthService.js +468 -65
  48. package/dist/auth/AuthService.js.map +1 -1
  49. package/dist/auth/oauth/AppleProvider.d.ts +2 -0
  50. package/dist/auth/oauth/AppleProvider.d.ts.map +1 -1
  51. package/dist/auth/oauth/AppleProvider.js +40 -3
  52. package/dist/auth/oauth/AppleProvider.js.map +1 -1
  53. package/dist/auth/oauth/BaseOAuthProvider.d.ts +3 -2
  54. package/dist/auth/oauth/BaseOAuthProvider.d.ts.map +1 -1
  55. package/dist/auth/oauth/BaseOAuthProvider.js +29 -3
  56. package/dist/auth/oauth/BaseOAuthProvider.js.map +1 -1
  57. package/dist/auth/oauth/DiscordProvider.d.ts.map +1 -1
  58. package/dist/auth/oauth/DiscordProvider.js +4 -1
  59. package/dist/auth/oauth/DiscordProvider.js.map +1 -1
  60. package/dist/auth/oauth/GitHubProvider.d.ts.map +1 -1
  61. package/dist/auth/oauth/GitHubProvider.js +4 -1
  62. package/dist/auth/oauth/GitHubProvider.js.map +1 -1
  63. package/dist/auth/oauth/GoogleProvider.d.ts.map +1 -1
  64. package/dist/auth/oauth/GoogleProvider.js +4 -1
  65. package/dist/auth/oauth/GoogleProvider.js.map +1 -1
  66. package/dist/auth/oauth/MicrosoftProvider.d.ts.map +1 -1
  67. package/dist/auth/oauth/MicrosoftProvider.js +4 -1
  68. package/dist/auth/oauth/MicrosoftProvider.js.map +1 -1
  69. package/dist/auth/oauth/OAuthProviderRegistry.d.ts +6 -2
  70. package/dist/auth/oauth/OAuthProviderRegistry.d.ts.map +1 -1
  71. package/dist/auth/oauth/OAuthProviderRegistry.js +25 -10
  72. package/dist/auth/oauth/OAuthProviderRegistry.js.map +1 -1
  73. package/dist/auth/oauth/types.d.ts +4 -2
  74. package/dist/auth/oauth/types.d.ts.map +1 -1
  75. package/dist/cli/cli.d.ts.map +1 -1
  76. package/dist/cli/cli.js +228 -12
  77. package/dist/cli/cli.js.map +1 -1
  78. package/dist/core/config/ConfigService.d.ts.map +1 -1
  79. package/dist/core/config/ConfigService.js +5 -3
  80. package/dist/core/config/ConfigService.js.map +1 -1
  81. package/dist/core/config/EnvLoader.d.ts +14 -0
  82. package/dist/core/config/EnvLoader.d.ts.map +1 -1
  83. package/dist/core/config/EnvLoader.js +44 -0
  84. package/dist/core/config/EnvLoader.js.map +1 -1
  85. package/dist/core/container/Container.d.ts +14 -0
  86. package/dist/core/container/Container.d.ts.map +1 -1
  87. package/dist/core/container/Container.js +32 -0
  88. package/dist/core/container/Container.js.map +1 -1
  89. package/dist/core/container/Tokens.d.ts +2 -0
  90. package/dist/core/container/Tokens.d.ts.map +1 -1
  91. package/dist/core/container/Tokens.js +2 -0
  92. package/dist/core/container/Tokens.js.map +1 -1
  93. package/dist/core/errors/AppError.d.ts +7 -7
  94. package/dist/core/errors/AppError.d.ts.map +1 -1
  95. package/dist/core/errors/AppError.js +18 -14
  96. package/dist/core/errors/AppError.js.map +1 -1
  97. package/dist/core/events/EventBus.d.ts.map +1 -1
  98. package/dist/core/events/EventBus.js +36 -6
  99. package/dist/core/events/EventBus.js.map +1 -1
  100. package/dist/core/maintenance/MaintenanceGate.d.ts +47 -0
  101. package/dist/core/maintenance/MaintenanceGate.d.ts.map +1 -1
  102. package/dist/core/maintenance/MaintenanceGate.js +265 -7
  103. package/dist/core/maintenance/MaintenanceGate.js.map +1 -1
  104. package/dist/core/plugins/PluginManager.d.ts +20 -1
  105. package/dist/core/plugins/PluginManager.d.ts.map +1 -1
  106. package/dist/core/plugins/PluginManager.js +231 -146
  107. package/dist/core/plugins/PluginManager.js.map +1 -1
  108. package/dist/core/plugins/types.d.ts +48 -31
  109. package/dist/core/plugins/types.d.ts.map +1 -1
  110. package/dist/cron/CronParser.d.ts +83 -0
  111. package/dist/cron/CronParser.d.ts.map +1 -0
  112. package/dist/cron/CronParser.js +538 -0
  113. package/dist/cron/CronParser.js.map +1 -0
  114. package/dist/cron/CronService.d.ts +74 -0
  115. package/dist/cron/CronService.d.ts.map +1 -0
  116. package/dist/cron/CronService.js +1254 -0
  117. package/dist/cron/CronService.js.map +1 -0
  118. package/dist/cron/types.d.ts +98 -0
  119. package/dist/cron/types.d.ts.map +1 -0
  120. package/dist/cron/types.js +3 -0
  121. package/dist/cron/types.js.map +1 -0
  122. package/dist/database/DatabaseService.d.ts +4 -1
  123. package/dist/database/DatabaseService.d.ts.map +1 -1
  124. package/dist/database/DatabaseService.js +34 -9
  125. package/dist/database/DatabaseService.js.map +1 -1
  126. package/dist/database/config/DatabaseConfigService.d.ts +1 -0
  127. package/dist/database/config/DatabaseConfigService.d.ts.map +1 -1
  128. package/dist/database/config/DatabaseConfigService.js +4 -2
  129. package/dist/database/config/DatabaseConfigService.js.map +1 -1
  130. package/dist/database/drivers/DriverPackageLoader.d.ts +11 -0
  131. package/dist/database/drivers/DriverPackageLoader.d.ts.map +1 -0
  132. package/dist/database/drivers/DriverPackageLoader.js +112 -0
  133. package/dist/database/drivers/DriverPackageLoader.js.map +1 -0
  134. package/dist/database/drivers/DriverRegistry.d.ts +1 -0
  135. package/dist/database/drivers/DriverRegistry.d.ts.map +1 -1
  136. package/dist/database/drivers/DriverRegistry.js +29 -0
  137. package/dist/database/drivers/DriverRegistry.js.map +1 -1
  138. package/dist/database/drivers/IDatabaseDriver.d.ts +1 -0
  139. package/dist/database/drivers/IDatabaseDriver.d.ts.map +1 -1
  140. package/dist/database/drivers/MssqlDriver.d.ts.map +1 -1
  141. package/dist/database/drivers/MssqlDriver.js +10 -5
  142. package/dist/database/drivers/MssqlDriver.js.map +1 -1
  143. package/dist/database/drivers/NodeSqliteDriver.d.ts.map +1 -1
  144. package/dist/database/drivers/NodeSqliteDriver.js +15 -1
  145. package/dist/database/drivers/NodeSqliteDriver.js.map +1 -1
  146. package/dist/database/drivers/PostgresDriver.d.ts.map +1 -1
  147. package/dist/database/drivers/PostgresDriver.js +4 -5
  148. package/dist/database/drivers/PostgresDriver.js.map +1 -1
  149. package/dist/database/migration/DatabaseMigrationService.d.ts +1 -0
  150. package/dist/database/migration/DatabaseMigrationService.d.ts.map +1 -1
  151. package/dist/database/migration/DatabaseMigrationService.js +51 -0
  152. package/dist/database/migration/DatabaseMigrationService.js.map +1 -1
  153. package/dist/database/migrations/SystemMigrations.d.ts.map +1 -1
  154. package/dist/database/migrations/SystemMigrations.js +200 -5
  155. package/dist/database/migrations/SystemMigrations.js.map +1 -1
  156. package/dist/flows/FlowEngine.js.map +1 -1
  157. package/dist/flows/FlowService.d.ts +10 -1
  158. package/dist/flows/FlowService.d.ts.map +1 -1
  159. package/dist/flows/FlowService.js +227 -14
  160. package/dist/flows/FlowService.js.map +1 -1
  161. package/dist/flows/FlowValidator.d.ts +2 -1
  162. package/dist/flows/FlowValidator.d.ts.map +1 -1
  163. package/dist/flows/FlowValidator.js +89 -4
  164. package/dist/flows/FlowValidator.js.map +1 -1
  165. package/dist/flows/types.d.ts +20 -3
  166. package/dist/flows/types.d.ts.map +1 -1
  167. package/dist/functions/FunctionService.d.ts +10 -2
  168. package/dist/functions/FunctionService.d.ts.map +1 -1
  169. package/dist/functions/FunctionService.js +271 -37
  170. package/dist/functions/FunctionService.js.map +1 -1
  171. package/dist/functions/runtime/QuickJsWasmRuntime.d.ts.map +1 -1
  172. package/dist/functions/runtime/QuickJsWasmRuntime.js +189 -177
  173. package/dist/functions/runtime/QuickJsWasmRuntime.js.map +1 -1
  174. package/dist/functions/types.d.ts +31 -2
  175. package/dist/functions/types.d.ts.map +1 -1
  176. package/dist/http/HttpServer.d.ts +7 -1
  177. package/dist/http/HttpServer.d.ts.map +1 -1
  178. package/dist/http/HttpServer.js +187 -8
  179. package/dist/http/HttpServer.js.map +1 -1
  180. package/dist/http/controllers/ApiKeyController.d.ts +1 -0
  181. package/dist/http/controllers/ApiKeyController.d.ts.map +1 -1
  182. package/dist/http/controllers/ApiKeyController.js +47 -1
  183. package/dist/http/controllers/ApiKeyController.js.map +1 -1
  184. package/dist/http/controllers/AuthController.d.ts +12 -0
  185. package/dist/http/controllers/AuthController.d.ts.map +1 -1
  186. package/dist/http/controllers/AuthController.js +40 -2
  187. package/dist/http/controllers/AuthController.js.map +1 -1
  188. package/dist/http/controllers/CronController.d.ts +63 -0
  189. package/dist/http/controllers/CronController.d.ts.map +1 -0
  190. package/dist/http/controllers/CronController.js +92 -0
  191. package/dist/http/controllers/CronController.js.map +1 -0
  192. package/dist/http/controllers/DatabaseController.d.ts.map +1 -1
  193. package/dist/http/controllers/DatabaseController.js +53 -0
  194. package/dist/http/controllers/DatabaseController.js.map +1 -1
  195. package/dist/http/controllers/FlowController.d.ts.map +1 -1
  196. package/dist/http/controllers/FlowController.js +45 -4
  197. package/dist/http/controllers/FlowController.js.map +1 -1
  198. package/dist/http/controllers/FunctionController.d.ts.map +1 -1
  199. package/dist/http/controllers/FunctionController.js +16 -2
  200. package/dist/http/controllers/FunctionController.js.map +1 -1
  201. package/dist/http/controllers/HealthController.js +2 -2
  202. package/dist/http/middleware/AppResolutionMiddleware.d.ts +1 -1
  203. package/dist/http/middleware/AppResolutionMiddleware.d.ts.map +1 -1
  204. package/dist/http/middleware/AppResolutionMiddleware.js +2 -3
  205. package/dist/http/middleware/AppResolutionMiddleware.js.map +1 -1
  206. package/dist/http/middleware/AuthMiddleware.d.ts.map +1 -1
  207. package/dist/http/middleware/AuthMiddleware.js +6 -3
  208. package/dist/http/middleware/AuthMiddleware.js.map +1 -1
  209. package/dist/http/middleware/ChaosMiddleware.js +6 -6
  210. package/dist/http/middleware/ChaosMiddleware.js.map +1 -1
  211. package/dist/index.d.ts +2 -2
  212. package/dist/index.d.ts.map +1 -1
  213. package/dist/index.js +6 -2
  214. package/dist/index.js.map +1 -1
  215. package/dist/queue/QueueService.d.ts +9 -0
  216. package/dist/queue/QueueService.d.ts.map +1 -1
  217. package/dist/queue/QueueService.js +143 -60
  218. package/dist/queue/QueueService.js.map +1 -1
  219. package/dist/queue/drivers/SqliteQueueDriver.d.ts +3 -0
  220. package/dist/queue/drivers/SqliteQueueDriver.d.ts.map +1 -1
  221. package/dist/queue/drivers/SqliteQueueDriver.js +315 -255
  222. package/dist/queue/drivers/SqliteQueueDriver.js.map +1 -1
  223. package/dist/records/FtsService.d.ts +7 -3
  224. package/dist/records/FtsService.d.ts.map +1 -1
  225. package/dist/records/FtsService.js +69 -5
  226. package/dist/records/FtsService.js.map +1 -1
  227. package/dist/records/QueryFilterParser.d.ts.map +1 -1
  228. package/dist/records/QueryFilterParser.js +58 -20
  229. package/dist/records/QueryFilterParser.js.map +1 -1
  230. package/dist/records/RecordSanitizer.d.ts.map +1 -1
  231. package/dist/records/RecordSanitizer.js +32 -4
  232. package/dist/records/RecordSanitizer.js.map +1 -1
  233. package/dist/records/RecordService.d.ts +6 -0
  234. package/dist/records/RecordService.d.ts.map +1 -1
  235. package/dist/records/RecordService.js +95 -14
  236. package/dist/records/RecordService.js.map +1 -1
  237. package/dist/records/RecordValidator.d.ts +10 -0
  238. package/dist/records/RecordValidator.d.ts.map +1 -1
  239. package/dist/records/RecordValidator.js +110 -2
  240. package/dist/records/RecordValidator.js.map +1 -1
  241. package/dist/records/fts/IFtsDriver.d.ts +7 -6
  242. package/dist/records/fts/IFtsDriver.d.ts.map +1 -1
  243. package/dist/records/fts/MssqlFtsDriver.d.ts +5 -1
  244. package/dist/records/fts/MssqlFtsDriver.d.ts.map +1 -1
  245. package/dist/records/fts/MssqlFtsDriver.js +35 -3
  246. package/dist/records/fts/MssqlFtsDriver.js.map +1 -1
  247. package/dist/records/fts/PostgresFtsDriver.d.ts +9 -2
  248. package/dist/records/fts/PostgresFtsDriver.d.ts.map +1 -1
  249. package/dist/records/fts/PostgresFtsDriver.js +116 -11
  250. package/dist/records/fts/PostgresFtsDriver.js.map +1 -1
  251. package/dist/records/fts/SqliteFts5Driver.d.ts +7 -1
  252. package/dist/records/fts/SqliteFts5Driver.d.ts.map +1 -1
  253. package/dist/records/fts/SqliteFts5Driver.js +66 -6
  254. package/dist/records/fts/SqliteFts5Driver.js.map +1 -1
  255. package/dist/schema/OpenApiGenerator.d.ts.map +1 -1
  256. package/dist/schema/OpenApiGenerator.js +103 -3
  257. package/dist/schema/OpenApiGenerator.js.map +1 -1
  258. package/dist/schema/models/Field.d.ts +1 -0
  259. package/dist/schema/models/Field.d.ts.map +1 -1
  260. package/dist/snapshots/SnapshotService.d.ts.map +1 -1
  261. package/dist/snapshots/SnapshotService.js +21 -9
  262. package/dist/snapshots/SnapshotService.js.map +1 -1
  263. package/dist/snapshots/drivers/LogicalSnapshotDriver.d.ts.map +1 -1
  264. package/dist/snapshots/drivers/LogicalSnapshotDriver.js +2 -0
  265. package/dist/snapshots/drivers/LogicalSnapshotDriver.js.map +1 -1
  266. package/dist/templates/definitions/ecommerce.js +6 -6
  267. package/dist/templates/definitions/ecommerce.js.map +1 -1
  268. package/dist/webhooks/WebhookService.js +1 -1
  269. package/package.json +5 -3
@@ -35,6 +35,11 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.ApiKeyService = void 0;
37
37
  exports.hasScope = hasScope;
38
+ exports.hasFunctionScope = hasFunctionScope;
39
+ exports.hasFlowScope = hasFlowScope;
40
+ exports.hasQueueScope = hasQueueScope;
41
+ exports.hasCronScope = hasCronScope;
42
+ exports.normalizeApiKeyScopes = normalizeApiKeyScopes;
38
43
  const crypto = __importStar(require("crypto"));
39
44
  const AppError_1 = require("../core/errors/AppError");
40
45
  const secret_1 = require("../core/crypto/secret");
@@ -72,9 +77,181 @@ function hasScope(auth, resource, action) {
72
77
  }
73
78
  return false;
74
79
  }
80
+ function hasScopedResourceAccess(auth, category, resourceName, actions) {
81
+ if (!auth)
82
+ return false;
83
+ if (auth.isAdmin)
84
+ return true;
85
+ if (!auth.isApiKey || !Array.isArray(auth.scopes))
86
+ return false;
87
+ const cat = category.trim().toLowerCase();
88
+ const res = resourceName.trim().toLowerCase();
89
+ const actSet = new Set(actions.map((a) => a.toLowerCase()));
90
+ for (const s of auth.scopes) {
91
+ const scope = String(s || '').trim().toLowerCase();
92
+ if (!scope)
93
+ continue;
94
+ if (scope === '*' || scope === 'admin:*' || scope === cat || scope === `${cat}:*`) {
95
+ return true;
96
+ }
97
+ if (res && (scope === `${cat}:${res}` || scope === `${cat}:${res}:*`)) {
98
+ return true;
99
+ }
100
+ for (const act of actSet) {
101
+ if (scope === `${cat}:${act}`)
102
+ return true;
103
+ if (res && (scope === `${cat}:${res}:${act}` || scope === `${res}:${act}`))
104
+ return true;
105
+ }
106
+ }
107
+ return false;
108
+ }
109
+ /**
110
+ * Checks whether an API key or admin caller is permitted to invoke a serverless function.
111
+ */
112
+ function hasFunctionScope(auth, functionName) {
113
+ return hasScopedResourceAccess(auth, 'functions', functionName, ['invoke', 'execute']);
114
+ }
115
+ /**
116
+ * Checks whether an API key or admin caller is permitted to execute an HTTP flow.
117
+ */
118
+ function hasFlowScope(auth, flowName) {
119
+ return hasScopedResourceAccess(auth, 'flows', flowName, ['execute', 'invoke']);
120
+ }
121
+ /**
122
+ * Checks whether an API key or admin caller has permission for a queue action (global or per-queue).
123
+ */
124
+ function hasQueueScope(auth, queueName, action) {
125
+ if (!auth)
126
+ return false;
127
+ if (auth.isAdmin)
128
+ return true;
129
+ if (!auth.isApiKey || !Array.isArray(auth.scopes))
130
+ return false;
131
+ const normalizedActions = action === 'send'
132
+ ? ['send', 'write', 'create']
133
+ : action === 'read'
134
+ ? ['read', 'view', 'list']
135
+ : ['delete', 'write'];
136
+ return hasScopedResourceAccess(auth, 'queues', queueName || '', normalizedActions);
137
+ }
138
+ function hasCronScope(auth, action) {
139
+ if (!auth)
140
+ return false;
141
+ if (auth.isAdmin)
142
+ return true;
143
+ if (!auth.isApiKey || !Array.isArray(auth.scopes))
144
+ return false;
145
+ const normalizedActions = action === 'read'
146
+ ? ['read', 'list', 'view']
147
+ : action === 'trigger'
148
+ ? ['trigger', 'execute', 'run', 'write']
149
+ : ['write', 'create', 'update', 'delete'];
150
+ return hasScopedResourceAccess(auth, 'cron', '*', normalizedActions);
151
+ }
152
+ const RESERVED_SCOPE_CATEGORIES = new Set(['*', 'admin', 'functions', 'flows', 'queues', 'cron']);
153
+ const COLLECTION_READ_ACTIONS = new Set(['read', 'list', 'view']);
154
+ const COLLECTION_WRITE_ACTIONS = new Set(['write', 'create', 'update', 'delete']);
155
+ const QUEUE_GLOBAL_ACTIONS = new Set(['send', 'read', 'delete', '*']);
156
+ /**
157
+ * Deduplicates scopes and removes specific resource scopes that are superseded
158
+ * by a broader wildcard scope in the same permission group.
159
+ */
160
+ function normalizeApiKeyScopes(rawScopes, role) {
161
+ const cleaned = [];
162
+ const seen = new Set();
163
+ for (const raw of rawScopes || []) {
164
+ const trimmed = String(raw || '').trim();
165
+ if (!trimmed)
166
+ continue;
167
+ const key = trimmed.toLowerCase();
168
+ if (!seen.has(key)) {
169
+ seen.add(key);
170
+ cleaned.push(trimmed);
171
+ }
172
+ }
173
+ if (role === 'admin' || seen.has('*')) {
174
+ return ['*'];
175
+ }
176
+ if (seen.has('admin:*')) {
177
+ return ['admin:*'];
178
+ }
179
+ const hasAllColRead = seen.has('*:read');
180
+ const hasAllColWrite = seen.has('*:write');
181
+ const hasAllFunctions = seen.has('functions') || seen.has('functions:*') || seen.has('functions:invoke') || seen.has('functions:execute');
182
+ const hasAllFlows = seen.has('flows') || seen.has('flows:*') || seen.has('flows:execute') || seen.has('flows:invoke');
183
+ const hasAllQueues = seen.has('queues') || seen.has('queues:*');
184
+ const hasQueueSendAll = hasAllQueues || seen.has('queues:send');
185
+ const hasQueueReadAll = hasAllQueues || seen.has('queues:read');
186
+ const hasQueueDeleteAll = hasAllQueues || seen.has('queues:delete');
187
+ // Track per-collection `<col>:*` and per-queue `queues:<q>` / `queues:<q>:*` wildcards
188
+ const wildcardCollections = new Set();
189
+ const wildcardQueues = new Set();
190
+ for (const s of seen) {
191
+ const parts = s.split(':');
192
+ if (parts.length === 2 && parts[1] === '*' && !RESERVED_SCOPE_CATEGORIES.has(parts[0])) {
193
+ wildcardCollections.add(parts[0]);
194
+ }
195
+ if (parts[0] === 'queues' && parts.length === 2 && !QUEUE_GLOBAL_ACTIONS.has(parts[1])) {
196
+ wildcardQueues.add(parts[1]);
197
+ }
198
+ if (parts[0] === 'queues' && parts.length === 3 && parts[2] === '*' && !QUEUE_GLOBAL_ACTIONS.has(parts[1])) {
199
+ wildcardQueues.add(parts[1]);
200
+ }
201
+ }
202
+ return cleaned.filter((original) => {
203
+ const s = original.toLowerCase();
204
+ const parts = s.split(':');
205
+ // 1. Collections: `<col>:<action>`
206
+ if (parts.length === 2 && !RESERVED_SCOPE_CATEGORIES.has(parts[0])) {
207
+ const [col, act] = parts;
208
+ if (act !== '*' && wildcardCollections.has(col))
209
+ return false;
210
+ if (hasAllColRead && COLLECTION_READ_ACTIONS.has(act))
211
+ return false;
212
+ if (hasAllColWrite && COLLECTION_WRITE_ACTIONS.has(act))
213
+ return false;
214
+ return true;
215
+ }
216
+ // 2. Functions: strip specific `functions:<name>` / `functions:<name>:<act>` when wildcard is present
217
+ if (parts[0] === 'functions' && hasAllFunctions) {
218
+ if (s === 'functions' || s === 'functions:*' || s === 'functions:invoke' || s === 'functions:execute') {
219
+ return true;
220
+ }
221
+ return false;
222
+ }
223
+ // 3. Flows: strip specific `flows:<name>` / `flows:<name>:<act>` when wildcard is present
224
+ if (parts[0] === 'flows' && hasAllFlows) {
225
+ if (s === 'flows' || s === 'flows:*' || s === 'flows:execute' || s === 'flows:invoke') {
226
+ return true;
227
+ }
228
+ return false;
229
+ }
230
+ // 4. Queues
231
+ if (parts[0] === 'queues') {
232
+ if (hasAllQueues) {
233
+ return s === 'queues' || s === 'queues:*';
234
+ }
235
+ if (parts.length === 3) {
236
+ const [, qName, qAct] = parts;
237
+ if (qAct !== '*' && wildcardQueues.has(qName))
238
+ return false;
239
+ if (qAct === 'send' && hasQueueSendAll)
240
+ return false;
241
+ if (qAct === 'read' && hasQueueReadAll)
242
+ return false;
243
+ if (qAct === 'delete' && hasQueueDeleteAll)
244
+ return false;
245
+ }
246
+ return true;
247
+ }
248
+ return true;
249
+ });
250
+ }
75
251
  class ApiKeyService {
76
252
  db;
77
253
  config;
254
+ static DEFAULT_MAX_API_KEYS_PER_USER = 50;
78
255
  // In-memory quick lookup cache (keyPrefix -> CachedKey) with 10s TTL
79
256
  keyCache = new Map();
80
257
  pendingUsageUpdates = new Map();
@@ -82,6 +259,7 @@ class ApiKeyService {
82
259
  usageFlushTimer;
83
260
  realtimeService;
84
261
  keyRevokedListeners = [];
262
+ userQuotaLocks = new Map();
85
263
  constructor(db, config) {
86
264
  this.db = db;
87
265
  this.config = config;
@@ -148,12 +326,74 @@ class ApiKeyService {
148
326
  }
149
327
  /**
150
328
  * Generates a new API Key with full secret returned only once.
329
+ * Enforces per-user quota check and insertion atomically within a single transaction boundary.
151
330
  */
152
331
  createKey(dto) {
153
332
  const name = (dto.name || '').trim();
154
333
  if (!name) {
155
334
  throw new AppError_1.AppError('API key name is required', 400);
156
335
  }
336
+ const maxKeys = this.config?.maxApiKeysPerUser || ApiKeyService.DEFAULT_MAX_API_KEYS_PER_USER;
337
+ const executeInTransaction = () => {
338
+ if (dto.createdBy) {
339
+ const countRow = this.db.get("SELECT COUNT(*) as count FROM _api_keys WHERE createdBy = ? AND status != 'revoked'", dto.createdBy);
340
+ const verifyCount = (r) => {
341
+ const currentCount = Number(r?.count || 0);
342
+ if (currentCount >= maxKeys) {
343
+ throw new AppError_1.AppError(`API key quota exceeded: maximum of ${maxKeys} active keys allowed per user`, 400);
344
+ }
345
+ };
346
+ if (countRow && typeof countRow.then === 'function') {
347
+ return countRow.then((r) => {
348
+ verifyCount(r);
349
+ return this.insertKeyRecord(dto, name);
350
+ });
351
+ }
352
+ verifyCount(countRow);
353
+ }
354
+ return this.insertKeyRecord(dto, name);
355
+ };
356
+ if (this.db.dialect.name === 'sqlite') {
357
+ return this.db.transaction(() => executeInTransaction());
358
+ }
359
+ return this.serializeUserCreation(dto.createdBy, async () => {
360
+ return this.db.transaction(async () => {
361
+ if (this.db.dialect.name === 'postgres' && dto.createdBy) {
362
+ try {
363
+ await this.db.get("SELECT pg_advisory_xact_lock(hashtext('api_key_quota_' || ?))", dto.createdBy);
364
+ }
365
+ catch { }
366
+ }
367
+ return await executeInTransaction();
368
+ });
369
+ });
370
+ }
371
+ async serializeUserCreation(userId, fn) {
372
+ if (!userId) {
373
+ return fn();
374
+ }
375
+ while (this.userQuotaLocks.has(userId)) {
376
+ try {
377
+ await this.userQuotaLocks.get(userId);
378
+ }
379
+ catch { }
380
+ }
381
+ let release;
382
+ const lockPromise = new Promise((resolve) => {
383
+ release = resolve;
384
+ });
385
+ this.userQuotaLocks.set(userId, lockPromise);
386
+ try {
387
+ return await fn();
388
+ }
389
+ finally {
390
+ if (this.userQuotaLocks.get(userId) === lockPromise) {
391
+ this.userQuotaLocks.delete(userId);
392
+ }
393
+ release();
394
+ }
395
+ }
396
+ insertKeyRecord(dto, name) {
157
397
  const env = (dto.env || (this.config.dev ? 'test' : 'live')).replace(/[^a-z0-9]/gi, '').toLowerCase() || 'live';
158
398
  const keyId = crypto.randomBytes(3).toString('hex'); // 6 chars
159
399
  const secretEntropy = crypto.randomBytes(24).toString('hex'); // 48 chars
@@ -173,10 +413,7 @@ class ApiKeyService {
173
413
  expiresAt = expDate.toISOString();
174
414
  }
175
415
  const role = dto.role || 'service';
176
- let scopes = dto.scopes || [];
177
- if (role === 'admin' && !scopes.includes('*')) {
178
- scopes = ['*'];
179
- }
416
+ const scopes = normalizeApiKeyScopes(dto.scopes, role);
180
417
  const allowedIps = (dto.allowedIps || []).map((ip) => ip.trim()).filter(Boolean);
181
418
  const runRes = this.db.run(`INSERT INTO _api_keys (
182
419
  id, name, description, keyPrefix, secretHash, redactedKey, role, scopes, allowedIps,
@@ -512,8 +749,29 @@ class ApiKeyService {
512
749
  // Non-fatal if DB is temporarily locked
513
750
  }
514
751
  }
515
- listKeys() {
516
- const rows = this.db.all('SELECT * FROM _api_keys ORDER BY created DESC');
752
+ listKeys(options) {
753
+ const rawLimit = options?.limit !== undefined && Number.isFinite(Number(options.limit))
754
+ ? Math.trunc(Number(options.limit))
755
+ : 100;
756
+ const limit = Math.max(1, Math.min(500, rawLimit));
757
+ const rawOffset = options?.offset !== undefined && Number.isFinite(Number(options.offset))
758
+ ? Math.trunc(Number(options.offset))
759
+ : 0;
760
+ const offset = Math.max(0, rawOffset);
761
+ const conditions = [];
762
+ const params = [];
763
+ if (options?.status) {
764
+ conditions.push('status = ?');
765
+ params.push(options.status);
766
+ }
767
+ if (options?.createdBy) {
768
+ conditions.push('createdBy = ?');
769
+ params.push(options.createdBy);
770
+ }
771
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
772
+ const sql = `SELECT * FROM _api_keys ${whereClause} ORDER BY created DESC LIMIT ? OFFSET ?`;
773
+ params.push(limit, offset);
774
+ const rows = this.db.all(sql, ...params);
517
775
  const processRows = (r) => (r || []).map((item) => {
518
776
  const { secretHash: _, ...safe } = this.mapRow(item);
519
777
  return safe;
@@ -554,13 +812,38 @@ class ApiKeyService {
554
812
  updates.push('description = ?');
555
813
  params.push(dto.description);
556
814
  }
815
+ const effectiveRole = dto.role !== undefined ? dto.role : current.role;
816
+ const isRoleChanging = dto.role !== undefined && dto.role !== current.role;
557
817
  if (dto.role !== undefined) {
558
818
  updates.push('role = ?');
559
819
  params.push(dto.role);
560
820
  }
561
- if (dto.scopes !== undefined) {
821
+ if (dto.scopes !== undefined || isRoleChanging || effectiveRole === 'admin') {
822
+ let baseScopes;
823
+ if (dto.scopes !== undefined) {
824
+ baseScopes = dto.scopes;
825
+ // If the key is non-admin, remove admin wildcard scopes to prevent privilege escalation/leakage
826
+ if (effectiveRole !== 'admin') {
827
+ baseScopes = baseScopes.filter((s) => {
828
+ const trimmed = String(s || '').trim().toLowerCase();
829
+ return trimmed !== '*' && trimmed !== 'admin:*';
830
+ });
831
+ }
832
+ }
833
+ else if (effectiveRole === 'admin') {
834
+ baseScopes = ['*'];
835
+ }
836
+ else {
837
+ // Role changed to non-admin without explicit scopes (role downgrade)
838
+ // Strip any admin wildcard scopes inherited from the admin role
839
+ baseScopes = (current.scopes || []).filter((s) => {
840
+ const trimmed = String(s || '').trim().toLowerCase();
841
+ return trimmed !== '*' && trimmed !== 'admin:*';
842
+ });
843
+ }
844
+ const nextScopes = normalizeApiKeyScopes(baseScopes, effectiveRole);
562
845
  updates.push('scopes = ?');
563
- params.push(JSON.stringify(dto.scopes));
846
+ params.push(JSON.stringify(nextScopes));
564
847
  }
565
848
  if (dto.allowedIps !== undefined) {
566
849
  updates.push('allowedIps = ?');
@@ -664,6 +947,233 @@ class ApiKeyService {
664
947
  }
665
948
  return doRotate(existing);
666
949
  }
950
+ /**
951
+ * Evaluates key permissions and IP restrictions against a subsystem resource and action
952
+ * in dry-run simulation mode without side-effects.
953
+ */
954
+ async simulate(options) {
955
+ let key = null;
956
+ if (options.keyId) {
957
+ key = await this.getKey(options.keyId);
958
+ if (!key) {
959
+ throw new AppError_1.NotFoundError(`API key '${options.keyId}' not found`);
960
+ }
961
+ }
962
+ const subsystem = (options.subsystem || '').toLowerCase();
963
+ const resource = (options.resource || '').trim();
964
+ const action = (options.action || '').trim().toLowerCase();
965
+ const effectiveRole = (options.role || key?.role || 'service');
966
+ const effectiveScopes = normalizeApiKeyScopes(options.scopes !== undefined ? options.scopes : (key?.scopes || []), effectiveRole);
967
+ const effectiveIps = options.allowedIps !== undefined ? options.allowedIps : (key?.allowedIps || []);
968
+ const hasIpRestriction = Array.isArray(effectiveIps) && effectiveIps.length > 0;
969
+ let isKeyActive = true;
970
+ let inactiveReason = '';
971
+ if (key) {
972
+ if (key.status === 'revoked') {
973
+ isKeyActive = false;
974
+ inactiveReason = 'API key is revoked';
975
+ }
976
+ else if (key.status === 'expired' || (key.expiresAt && new Date(key.expiresAt) < new Date())) {
977
+ isKeyActive = false;
978
+ inactiveReason = 'API key has expired';
979
+ }
980
+ }
981
+ if (!isKeyActive) {
982
+ return {
983
+ allowed: false,
984
+ status: 403,
985
+ reason: inactiveReason,
986
+ matchedScope: null,
987
+ requiredScope: '',
988
+ subsystem,
989
+ resource,
990
+ action,
991
+ ipCheck: { enforced: hasIpRestriction, allowed: true, clientIp: options.clientIp || null },
992
+ curlExample: '',
993
+ };
994
+ }
995
+ if (hasIpRestriction && options.clientIp) {
996
+ const ipAllowed = this.isIpAllowed(options.clientIp, effectiveIps);
997
+ if (!ipAllowed) {
998
+ return {
999
+ allowed: false,
1000
+ status: 403,
1001
+ reason: `Client IP '${options.clientIp}' not in allowed IP list (${effectiveIps.join(', ')})`,
1002
+ matchedScope: null,
1003
+ requiredScope: '',
1004
+ subsystem,
1005
+ resource,
1006
+ action,
1007
+ ipCheck: { enforced: true, allowed: false, clientIp: options.clientIp },
1008
+ curlExample: '',
1009
+ };
1010
+ }
1011
+ }
1012
+ const isAdmin = effectiveRole === 'admin' || effectiveScopes.includes('*') || effectiveScopes.includes('admin:*');
1013
+ const simulatedAuth = {
1014
+ id: key?.id || 'simulated_key',
1015
+ email: `${(key?.name || 'simulated').toLowerCase().replace(/[^a-z0-9]/g, '_')}@service.nodestack.local`,
1016
+ collection: '_api_keys',
1017
+ tokenKey: key?.id || 'simulated_key',
1018
+ isAdmin,
1019
+ isApiKey: true,
1020
+ scopes: effectiveScopes,
1021
+ role: effectiveRole,
1022
+ allowedIps: effectiveIps,
1023
+ };
1024
+ let allowed = false;
1025
+ let matchedScope = null;
1026
+ let requiredScope = '';
1027
+ let reason = '';
1028
+ if (subsystem === 'collections') {
1029
+ requiredScope = `${resource}:${action}`;
1030
+ allowed = hasScope(simulatedAuth, resource, action);
1031
+ if (allowed) {
1032
+ if (isAdmin) {
1033
+ matchedScope = effectiveScopes.find(s => s === '*' || s === 'admin:*') || 'role:admin';
1034
+ reason = `Granted with full administrative access (${matchedScope})`;
1035
+ }
1036
+ else {
1037
+ matchedScope = effectiveScopes.find(s => {
1038
+ const sc = s.toLowerCase();
1039
+ return sc === '*' || sc === `${resource.toLowerCase()}:*` || sc === requiredScope.toLowerCase() ||
1040
+ ((action === 'list' || action === 'view' || action === 'export') && (sc === `${resource.toLowerCase()}:read` || sc === '*:read')) ||
1041
+ ((action === 'create' || action === 'update' || action === 'delete' || action === 'import') && (sc === `${resource.toLowerCase()}:write` || sc === '*:write'));
1042
+ }) || null;
1043
+ reason = `Granted by scope '${matchedScope}'`;
1044
+ }
1045
+ }
1046
+ else {
1047
+ reason = `Missing required scope '${resource}:${action}' (or wildcard '${resource}:*')`;
1048
+ }
1049
+ }
1050
+ else if (subsystem === 'functions') {
1051
+ requiredScope = `functions:${resource}`;
1052
+ allowed = hasFunctionScope(simulatedAuth, resource);
1053
+ if (allowed) {
1054
+ if (isAdmin) {
1055
+ matchedScope = effectiveScopes.find(s => s === '*' || s === 'admin:*') || 'role:admin';
1056
+ reason = `Granted with full administrative access (${matchedScope})`;
1057
+ }
1058
+ else {
1059
+ matchedScope = effectiveScopes.find(s => {
1060
+ const sc = s.toLowerCase();
1061
+ return sc === '*' || sc === 'functions' || sc === 'functions:*' || sc === `functions:${resource.toLowerCase()}` || sc === `functions:${resource.toLowerCase()}:*` || sc === `functions:${resource.toLowerCase()}:invoke`;
1062
+ }) || null;
1063
+ reason = `Granted by scope '${matchedScope}'`;
1064
+ }
1065
+ }
1066
+ else {
1067
+ reason = `Missing required scope 'functions:${resource}' (or wildcard 'functions:*')`;
1068
+ }
1069
+ }
1070
+ else if (subsystem === 'flows') {
1071
+ requiredScope = `flows:${resource}`;
1072
+ allowed = hasFlowScope(simulatedAuth, resource);
1073
+ if (allowed) {
1074
+ if (isAdmin) {
1075
+ matchedScope = effectiveScopes.find(s => s === '*' || s === 'admin:*') || 'role:admin';
1076
+ reason = `Granted with full administrative access (${matchedScope})`;
1077
+ }
1078
+ else {
1079
+ matchedScope = effectiveScopes.find(s => {
1080
+ const sc = s.toLowerCase();
1081
+ return sc === '*' || sc === 'flows' || sc === 'flows:*' || sc === `flows:${resource.toLowerCase()}` || sc === `flows:${resource.toLowerCase()}:*` || sc === `flows:${resource.toLowerCase()}:execute`;
1082
+ }) || null;
1083
+ reason = action === 'poll'
1084
+ ? `Granted by scope '${matchedScope}' (Note: caller must also match execution actorId)`
1085
+ : `Granted by scope '${matchedScope}'`;
1086
+ }
1087
+ }
1088
+ else {
1089
+ reason = `Missing required scope 'flows:${resource}' (or wildcard 'flows:*')`;
1090
+ }
1091
+ }
1092
+ else if (subsystem === 'queues') {
1093
+ const queueAct = action === 'claim' ? 'read' : action;
1094
+ requiredScope = `queues:${resource}:${queueAct}`;
1095
+ allowed = hasQueueScope(simulatedAuth, resource, queueAct);
1096
+ if (allowed) {
1097
+ if (isAdmin) {
1098
+ matchedScope = effectiveScopes.find(s => s === '*' || s === 'admin:*') || 'role:admin';
1099
+ reason = `Granted with full administrative access (${matchedScope})`;
1100
+ }
1101
+ else {
1102
+ matchedScope = effectiveScopes.find(s => {
1103
+ const sc = s.toLowerCase();
1104
+ return sc === '*' || sc === 'queues' || sc === 'queues:*' || sc === `queues:${resource.toLowerCase()}` || sc === `queues:${resource.toLowerCase()}:*` || sc === `queues:${resource.toLowerCase()}:${queueAct}`;
1105
+ }) || null;
1106
+ reason = `Granted by scope '${matchedScope}'`;
1107
+ }
1108
+ }
1109
+ else {
1110
+ reason = `Missing required scope 'queues:${resource}:${queueAct}' (or wildcard 'queues:${resource}:*')`;
1111
+ }
1112
+ }
1113
+ else {
1114
+ throw new AppError_1.AppError(`Invalid subsystem '${options.subsystem}'. Expected one of: collections, functions, flows, queues`, 400);
1115
+ }
1116
+ const keyToken = key?.redactedKey ? `${key.keyPrefix}...` : 'YOUR_API_KEY';
1117
+ const pathPrefix = options.appSlug && options.appSlug !== 'default'
1118
+ ? `/api/apps/${encodeURIComponent(options.appSlug)}`
1119
+ : '/api';
1120
+ let curlExample = '';
1121
+ if (subsystem === 'collections') {
1122
+ if (action === 'list') {
1123
+ curlExample = `curl -X GET "${pathPrefix}/collections/${resource}/records" \\\n -H "Authorization: ApiKey ${keyToken}"`;
1124
+ }
1125
+ else if (action === 'view') {
1126
+ curlExample = `curl -X GET "${pathPrefix}/collections/${resource}/records/<RECORD_ID>" \\\n -H "Authorization: ApiKey ${keyToken}"`;
1127
+ }
1128
+ else if (action === 'create') {
1129
+ curlExample = `curl -X POST "${pathPrefix}/collections/${resource}/records" \\\n -H "Authorization: ApiKey ${keyToken}" \\\n -H "Content-Type: application/json" \\\n -d '{"field": "value"}'`;
1130
+ }
1131
+ else if (action === 'update') {
1132
+ curlExample = `curl -X PATCH "${pathPrefix}/collections/${resource}/records/<RECORD_ID>" \\\n -H "Authorization: ApiKey ${keyToken}" \\\n -H "Content-Type: application/json" \\\n -d '{"field": "value"}'`;
1133
+ }
1134
+ else if (action === 'delete') {
1135
+ curlExample = `curl -X DELETE "${pathPrefix}/collections/${resource}/records/<RECORD_ID>" \\\n -H "Authorization: ApiKey ${keyToken}"`;
1136
+ }
1137
+ }
1138
+ else if (subsystem === 'functions') {
1139
+ curlExample = `curl -X POST "${pathPrefix}/functions/${resource}/invoke" \\\n -H "Authorization: ApiKey ${keyToken}" \\\n -H "Content-Type: application/json" \\\n -d '{"param": "value"}'`;
1140
+ }
1141
+ else if (subsystem === 'flows') {
1142
+ if (action === 'poll') {
1143
+ curlExample = `curl -X GET "${pathPrefix}/flows/executions/<EXECUTION_ID>" \\\n -H "Authorization: ApiKey ${keyToken}"`;
1144
+ }
1145
+ else {
1146
+ curlExample = `curl -X POST "${pathPrefix}/flows/${resource}/execute" \\\n -H "Authorization: ApiKey ${keyToken}" \\\n -H "Content-Type: application/json" \\\n -d '{"param": "value"}'`;
1147
+ }
1148
+ }
1149
+ else if (subsystem === 'queues') {
1150
+ if (action === 'send') {
1151
+ curlExample = `curl -X POST "${pathPrefix}/queues/${resource}/messages" \\\n -H "Authorization: ApiKey ${keyToken}" \\\n -H "Content-Type: application/json" \\\n -d '{"payload": {"task": "demo"}}'`;
1152
+ }
1153
+ else if (action === 'read' || action === 'claim') {
1154
+ curlExample = `curl -X GET "${pathPrefix}/queues/${resource}/messages" \\\n -H "Authorization: ApiKey ${keyToken}"`;
1155
+ }
1156
+ else {
1157
+ curlExample = `curl -X DELETE "${pathPrefix}/queues/${resource}/messages/<MESSAGE_ID>" \\\n -H "Authorization: ApiKey ${keyToken}"`;
1158
+ }
1159
+ }
1160
+ return {
1161
+ allowed,
1162
+ status: allowed ? 200 : 403,
1163
+ reason,
1164
+ matchedScope,
1165
+ requiredScope,
1166
+ subsystem,
1167
+ resource,
1168
+ action,
1169
+ ipCheck: {
1170
+ enforced: hasIpRestriction,
1171
+ allowed: !hasIpRestriction || !options.clientIp ? true : this.isIpAllowed(options.clientIp, effectiveIps),
1172
+ clientIp: options.clientIp || null,
1173
+ },
1174
+ curlExample,
1175
+ };
1176
+ }
667
1177
  mapRow(row) {
668
1178
  let scopes = [];
669
1179
  let allowedIps = [];